@namahapdf/react 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +22 -1
- package/dist/index.cjs +74 -73
- package/dist/index.d.cts +59 -2
- package/dist/index.d.ts +59 -2
- package/dist/index.js +35 -34
- 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 fa from"react";import T0,{useCallback as pu,useEffect as Pt,useMemo as gu,useRef as ye,useState as ie}from"react";var or=process.env.NEXT_PUBLIC_ENGINE_DEBUG==="1",Ho=(...t)=>{or&&console.log(...t)},ut=(...t)=>{or&&console.warn(...t)},wn=(...t)=>{or&&console.error(...t)};var Go=class{constructor(){this.processors=new Map}registerProcessor(e){this.processors.set(e.name,e),Ho(`[AvniEngine] Registered processor: ${e.name}`)}async runPipeline(e,n){let r=[],i=e;for(let o of n.tasks){let s=this.processors.get(o.processorName);if(!s)throw new Error(`Processor ${o.processorName} not found`);Ho(`[AvniEngine] Executing ${s.name}...`);let a=Date.now(),l=await s.process(i,o.params),c=Date.now();if(l.metrics={duration:c-a,originalSize:i.size,newSize:l.document.size},r.push(l),!l.success){wn(`[AvniEngine] Pipeline failed at ${s.name}: ${l.error}`);break}i=l.document}return r}getAvailableProcessors(){return Array.from(this.processors.keys())}},sr=new Go;import{degrees as mm,rgb as _r,PDFDocument as Cs,PDFRef as Fs,StandardFonts as mt,TextAlignment as Rs}from"pdf-lib";var Vo=t=>({type:"name",value:t.startsWith("/")?t.slice(1):t}),Ko=()=>({type:"null"}),ar=t=>({type:"boolean",value:t}),qo=t=>({type:"integer",value:t}),Jo=t=>({type:"real",value:t}),ki=(t,e)=>({type:"string",value:t,encoding:e}),Zo=(t,e=0)=>({type:"ref",objNum:t,genNum:e});var Pi=t=>typeof t=="object"&&t!==null&&"type"in t&&t.type==="integer",lc=t=>typeof t=="object"&&t!==null&&"type"in t&&t.type==="real",Qo=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",he=t=>typeof t=="object"&&t!==null&&"type"in t&&t.type==="stream",$e=t=>typeof t=="object"&&t!==null&&"type"in t&&t.type==="ref",ue=t=>typeof t=="object"&&t!==null&&"type"in t&&t.type==="array",Di=t=>Pi(t)||lc(t),V=t=>!t||typeof t!="object"||!("type"in t)?null:t.type==="integer"||t.type==="real"?t.value:null,jn=t=>!t||typeof t!="object"||!("type"in t)?null:t.type==="name"?t.value:null,Or=(t,e)=>t?V(t.entries.get(e)):null,Xt=t=>t===0||t===9||t===10||t===12||t===13||t===32,Ir=t=>t===40||t===41||t===60||t===62||t===91||t===93||t===123||t===125||t===47||t===37,cr=(t,e)=>{let n=e;for(;n<t.length&&Xt(t[n]);)n++;return n};import dc from"zlib";var uc=jn;function Hf(t){if(!t)return[];let e=uc(t);return e?[e]:ue(t)?t.items.map(n=>uc(n)).filter(n=>n!==null):[]}function fc(t){return t&&Q(t)?t:null}function Gf(t,e){if(e<=0)return[];if(!t)return new Array(e).fill(null);let n=fc(t);if(n)return new Array(e).fill(n);if(ue(t)){let r=t.items.map(i=>fc(i));return r.length>=e?r.slice(0,e):[...r,...new Array(e-r.length).fill(null)]}return new Array(e).fill(null)}function Vf(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 i=r.length%2===0?r:`${r}0`,o=new Uint8Array(i.length/2);for(let s=0;s<o.length;s++){let a=Number.parseInt(i.slice(s*2,s*2+2),16);if(Number.isNaN(a))throw new Error("Invalid ASCIIHex stream data");o[s]=a}return o}function Kf(t){let e=new TextDecoder("latin1").decode(t),n=[],r=[];for(let i=0;i<e.length;i++){let o=e[i];if(o==="~"&&e[i+1]===">")break;if(/\s/.test(o))continue;if(o==="z"){if(r.length!==0)throw new Error("Invalid ASCII85 stream data");n.push(0,0,0,0);continue}let s=o.charCodeAt(0);if(!(s<33||s>117)&&(r.push(s-33),r.length===5)){let a=0;for(let l of r)a=a*85+l;n.push(a>>>24&255,a>>>16&255,a>>>8&255,a&255),r=[]}}if(r.length>0){let i=r.length;for(;r.length<5;)r.push(84);let o=0;for(let a of r)o=o*85+a;let s=[o>>>24&255,o>>>16&255,o>>>8&255,o&255];n.push(...s.slice(0,i-1))}return new Uint8Array(n)}function qf(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 i=257-r;if(n>=t.length)break;let o=t[n++];for(let s=0;s<i;s++)e.push(o)}return new Uint8Array(e)}function Jf(t,e,n){let r=t+e-n,i=Math.abs(r-t),o=Math.abs(r-e),s=Math.abs(r-n);return i<=o&&i<=s?t:o<=s?e:n}function Zf(t,e,n,r){let i=Math.max(1,Math.ceil(e*n/8)),o=Math.ceil(r*e*n/8);if(o<=0)return t;let s=o+1,a=Math.floor(t.length/s);if(a<=0)return t;let l=new Uint8Array(a*o),c=new Uint8Array(o);for(let d=0;d<a;d++){let h=t[d*s],f=t.subarray(d*s+1,d*s+1+o),m=l.subarray(d*o,(d+1)*o);switch(h){case 0:{m.set(f);break}case 1:{for(let p=0;p<o;p++){let b=p>=i?m[p-i]:0;m[p]=f[p]+b&255}break}case 2:{for(let p=0;p<o;p++)m[p]=f[p]+c[p]&255;break}case 3:{for(let p=0;p<o;p++){let b=p>=i?m[p-i]:0,y=c[p];m[p]=f[p]+Math.floor((b+y)/2)&255}break}case 4:{for(let p=0;p<o;p++){let b=p>=i?m[p-i]:0,y=c[p],k=p>=i?c[p-i]:0;m[p]=f[p]+Jf(b,y,k)&255}break}default:{m.set(f);break}}c=m.slice()}return l}function Qf(t,e,n,r){let i=Math.ceil(r*e*n/8);if(i<=0)return t;let o=t.slice(),s=Math.floor(o.length/i);if(n===8){for(let a=0;a<s;a++){let l=a*i;for(let c=e;c<i;c++)o[l+c]=o[l+c]+o[l+c-e]&255}return o}if(n===16){let a=new DataView(o.buffer,o.byteOffset,o.byteLength),l=r*e;for(let c=0;c<s;c++){let d=c*i;for(let h=e;h<l;h++){let f=a.getUint16(d+h*2,!1),m=a.getUint16(d+(h-e)*2,!1);a.setUint16(d+h*2,f+m&65535,!1)}}return o}return console.warn(`[StreamDecoder] TIFF Predictor 2 unsupported for ${n}-bit components; returning undifferenced data`),t}function hc(t,e){var s,a,l,c;let n=(s=Or(e,"Predictor"))!=null?s:1;if(n<2)return t;let r=(a=Or(e,"Colors"))!=null?a:1,i=(l=Or(e,"BitsPerComponent"))!=null?l:8,o=(c=Or(e,"Columns"))!=null?c:1;return n>=10?Zf(t,r,i,o):n===2?Qf(t,r,i,o):t}function eh(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 i=t.subarray(0,t.length-r);e.push({bytes:i,trimmed:r,skippedHeader:!1}),i.length>2&&e.push({bytes:i.subarray(2),trimmed:r,skippedHeader:!0})}for(let r of e){try{return{inflated:new Uint8Array(dc.inflateSync(Buffer.from(r.bytes))),mode:"zlib",trimmed:r.trimmed,skippedHeader:r.skippedHeader}}catch{}try{return{inflated:new Uint8Array(dc.inflateRawSync(Buffer.from(r.bytes))),mode:"raw",trimmed:r.trimmed,skippedHeader:r.skippedHeader}}catch{}}return null}function th(t,e){let n=eh(t);if(!n){let i=Array.from(t.subarray(0,Math.min(8,t.length))).map(a=>`0x${a.toString(16).padStart(2,"0")}`).join(" "),o=Math.max(0,t.length-8),s=Array.from(t.subarray(o)).map(a=>`0x${a.toString(16).padStart(2,"0")}`).join(" ");throw new Error(`FlateDecode failed after zlib/raw retries (including tail-trim recovery). len=${t.length} first=[${i}] last=[${s}]`)}let r=n.inflated;if(n.trimmed>0||n.skippedHeader){let i=[];n.trimmed>0&&i.push(`trimmed ${n.trimmed} byte(s)`),n.skippedHeader&&i.push("skipped first 2 header byte(s)"),console.warn(`[StreamDecoder] FlateDecode recovered (${i.join(", ")}) using ${n.mode} mode`)}return hc(r,e)}function nh(t,e){let o=0,s=9,a=258,l=[];for(let p=0;p<256;p++)l[p]=[p];let c=()=>{if(Math.floor(o/8)>=t.length)return null;let b=0;for(let y=0;y<s;y++){let k=o+y,P=t[Math.floor(k/8)]>>7-k%8&1;b=b<<1|P}return o+=s,b},d=()=>{l.length=0;for(let p=0;p<256;p++)l[p]=[p];s=9,a=258},h=[],f=null;for(;;){let p=c();if(p===null||p===257)break;if(p===256){d(),f=null;continue}let b;if(l[p])b=l[p];else if(f)b=[...f,f[0]];else break;h.push(...b),f&&(l[a++]=[...f,b[0]],a===1<<s&&s<12&&s++),f=b}let m=new Uint8Array(h);return hc(m,e)}var Pe=class{static async decodeStream(e){return this.decodeStreamSync(e)}static decodeStreamSync(e){var l,c;let n=e.dict.entries.get("Filter"),r=e.dict.entries.get("DecodeParms"),i=Hf(n),o=Gf(r,i.length),s=(l=e.rawBytes)!=null?l:e.data;if(!s)throw new Error("Stream has no byte payload");if(i.length===0)return s;let a=s;for(let d=0;d<i.length;d++)a=this.applyFilterSync(i[d],a,(c=o[d])!=null?c: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 th(n,r);case"ASCII85Decode":case"A85":return Kf(n);case"ASCIIHexDecode":case"AHx":return Vf(n);case"LZWDecode":case"LZW":return nh(n,r);case"DCTDecode":case"DCT":return n;case"JPXDecode":return n;case"CCITTFaxDecode":case"CCF":return n;case"JBIG2Decode":return n;case"RunLengthDecode":case"RL":return qf(n);case"Crypt":return n;default:return console.warn(`[StreamDecoder] Unknown filter: ${e}; returning raw bytes`),n}}};var an=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),i=r.length;for(;this.pos<=this.bytes.length-i;){let o=!0;for(let s=0;s<i;s++)if(this.bytes[this.pos+s]!==r[s]){o=!1;break}if(o){let s=this.bytes.subarray(n,this.pos);return this.pos+=i,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 rh(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}ut(`[WARN] No newline after 'stream' keyword at tokenizer position ${t.getPosition()}`)}function ih(t){let e=t.getBytes(),n=t.getPosition(),r=[101,110,100,115,116,114,101,97,109];for(let i=n;i<=e.length-r.length;i++){let o=!0;for(let h=0;h<r.length;h++)if(e[i+h]!==r[h]){o=!1;break}if(!o)continue;let s=i>0?e[i-1]:10,a=i+r.length<e.length?e[i+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=i;return d>n&&e[d-1]===10&&(d-=1),d>n&&e[d-1]===13&&(d-=1),t.setPosition(i+r.length),e.subarray(n,d)}throw new Error("Could not find 'endstream' marker for stream object")}function mc(t){let e=t.readWord();return parseFloat(e)}function oh(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)?qo(e):Jo(e)}function sh(t){t.skipWhitespace();let e=t.readWord(),n=oh(e);if(!Pi(n))return n;let r=t.getPosition();try{t.skipWhitespace();let i=t.readWord();if(!/^[+-]?\d+$/.test(i))return t.setPosition(r),n;if(t.skipWhitespace(),t.readWord()==="R")return Zo(n.value,parseInt(i,10))}catch{return t.setPosition(r),n}return t.setPosition(r),n}function pc(t){let e=t.peek();if(e===40){t.read();let n=[],r=1;for(;r>0&&t.peekRaw()!==void 0;){let i=t.readRaw();if(i===40)r++;else if(i===41){if(r--,r===0)break;n.push(i)}else if(i===92){let o=t.peekRaw();if(o===void 0)break;if(o>=48&&o<=55){let s="";for(let a=0;a<3;a++){let l=t.peekRaw();if(l!==void 0&&l>=48&&l<=55)s+=String.fromCharCode(t.readRaw());else break}n.push(parseInt(s,8)&255);continue}t.readRaw(),o===110?n.push(10):o===114?n.push(13):o===116?n.push(9):o===98?n.push(8):o===102?n.push(12):o===40?n.push(40):o===41?n.push(41):o===92?n.push(92):o===10||(o===13?t.peekRaw()===10&&t.readRaw():n.push(o))}else n.push(i)}return ki(new Uint8Array(n),"literal")}else if(e===60){t.read();let n=[];for(;t.peekRaw()!==62;){let i=t.readRaw();if(i===void 0)throw new Error("Unexpected EOF in hex string");if(i===0||i===9||i===10||i===12||i===13||i===32)continue;let o=ah(i);o!==-1&&n.push(o)}t.readRaw(),n.length%2===1&&n.push(0);let r=new Uint8Array(n.length/2);for(let i=0,o=0;i<n.length;i+=2,o++)r[o]=n[i]<<4|n[i+1];return ki(r,"hex")}throw new Error("Invalid string format")}function ah(t){return t>=48&&t<=57?t-48:t>=65&&t<=70?t-65+10:t>=97&&t<=102?t-97+10:-1}function ch(t){if(t.peek()!==47)throw new Error("Expected / for name");t.read();let n=t.readWord();return Vo(n)}var lh=200;function dh(t,e){if(t.peek()!==91)throw new Error("Expected [ for array");t.read();let r=[];for(;t.peek()!==93;)r.push(wt(t,e+1));return t.read(),{type:"array",items:r}}function uh(t,e){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 r=new Map;for(;;){if(t.skipWhitespace(),t.peekRaw()===62&&t.peekRaw(1)===62){t.readRaw(),t.readRaw();break}let i=wt(t,e+1);if(!i||typeof i!="object"||i.type!=="name")throw new Error("Dictionary key must be a name");let o=i.value,s=wt(t,e+1);r.set(o,s)}return{type:"dict",entries:r}}function wt(t,e=0){if(e>lh)throw new Error("PDF object nesting too deep");let n=t.peek();if(n===void 0)throw new Error("Unexpected EOF while reading object");if(n===110){let r=t.readWord();if(r==="null")return Ko();if(r==="true")return ar(!0);if(r==="false")return ar(!1);throw new Error("Unknown keyword: "+r)}if(n===116||n===102){let r=t.readWord();if(r==="true")return ar(!0);if(r==="false")return ar(!1)}if(n===45||n===43||n===46||n>=48&&n<=57)return sh(t);if(n===40)return pc(t);if(n===47)return ch(t);if(n===91)return dh(t,e);if(n===60){if(t.peekRaw(1)!==60)return pc(t);let i=uh(t,e),o=t.getPosition();try{if(t.skipWhitespace(),t.readWord()==="stream"){rh(t);let a,l=i.entries.get("Length"),c=V(l);if(typeof c=="number"){let d=t.getPosition();a=t.getRemainingBytes().subarray(0,c),t.setPosition(d+c),t.skipWhitespace();let h=t.readWord();h!=="endstream"&&ut(`[WARN] Expected 'endstream' but got '${h}' - stream may be malformed`)}else a=ih(t);return{type:"stream",dict:i,rawBytes:a,data:a,decode:Pe.createLazyDecoder(i,a)}}else return t.setPosition(o),i}catch{return t.setPosition(o),i}}throw new Error(`Unknown object type at byte ${n}`)}function gc(t){let e=mc(t),n=mc(t);if(t.readWord()!=="obj")throw new Error("Expected obj keyword");let i=wt(t),o=t.readWord();if(o!=="endobj"){let s=t.getRemainingBytes(),a=s.subarray(0,Math.min(8192,s.length)),l=new TextDecoder("latin1").decode(a),c=l.search(/\bendobj\b/);if(c===-1){let d=l.replace(/[\r\n\t]+/g," ").slice(0,220);throw new Error(`Expected endobj keyword (got '${o||"<EOF>"}'). Nearby: "${d}"`)}t.setPosition(t.getPosition()+c+6),ut(`[ObjectReader] Recovered non-immediate endobj for ${Math.floor(e)} ${Math.floor(n)} obj (first token: '${o||"<EOF>"}')`)}return{objNum:Math.floor(e),genNum:Math.floor(n),object:i}}function lr(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 i=4096,o=8192,s=Math.max(0,e-i),a=Math.min(t.length,e+o),l=t.subarray(s,a),c=r.decode(l),d=/(\d+)\s+(\d+)\s+obj\b/g,h,f=[];for(;(h=d.exec(c))!==null;){let w=s+h.index,P=Math.abs(w-e),S=parseInt(h[1],10);f.push({absolutePos:w,matched:h[0],distance:P,objNum:S})}if(f.length===0){let w=Math.max(0,e-64),P=Math.min(t.length,e+128),S=r.decode(t.subarray(w,P)).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&&!f.some(w=>w.objNum===n)){let w=r.decode(t),P=String(n),S=new RegExp(`(?<![0-9])${P}\\s+\\d+\\s+obj\\b`,"g"),R;for(;(R=S.exec(w))!==null;){let I=R.index;if(f.some(A=>A.absolutePos===I))continue;let F=Math.abs(I-e);f.push({absolutePos:I,matched:R[0].trim(),distance:F,objNum:n})}}f.sort((w,P)=>{let S=n!==void 0&&w.objNum===n?0:1,R=n!==void 0&&P.objNum===n?0:1;return S!==R?S-R:w.distance-P.distance});let m=Math.min(12,f.length),p=[];for(let w=0;w<m;w++){let P=f[w];try{let S=new an(t.subarray(P.absolutePos)),R=gc(S);if(n!==void 0&&R.objNum!==n)throw new Error(`Parsed object ${R.objNum} but expected ${n}`);return w>0&&ut(`[ObjectReader] Offset ${e} resolved via fallback candidate #${w+1}: ${P.matched} at ${P.absolutePos}`),{...R,objectOffset:P.absolutePos}}catch(S){let R=S instanceof Error?S.message:String(S);p.push(`#${w+1} ${P.matched} @${P.absolutePos}: ${R}`)}}let b=Math.max(0,e-64),y=Math.min(t.length,e+256),k=r.decode(t.subarray(b,y)).replace(/[\r\n\t]+/g," ").slice(0,280);throw new Error(`Failed to read indirect object near offset ${e}. Tried ${m}/${f.length} candidates. Errors: ${p.join(" || ")}. Snippet: "${k}"`)}function es(t){let e=V(t.entries.get("XRefStm"));return e===null?null:Math.floor(e)}function xc(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 rs(t,e,n){e:for(let r=n;r<=t.length-e.length;r++){for(let i=0;i<e.length;i++)if(t[r+i]!==e[i])continue e;return r}return-1}function bc(t){return t===void 0||Xt(t)||Ir(t)}function is(t,e,n){if(e<0||e+n.length>t.length)return!1;for(let o=0;o<n.length;o++)if(t[e+o]!==n[o])return!1;let r=e>0?t[e-1]:void 0,i=e+n.length<t.length?t[e+n.length]:void 0;return bc(r)&&bc(i)}function Ci(t,e,n){let r=Math.max(0,n);for(;r<=t.length-e.length;){let i=rs(t,e,r);if(i===-1)return-1;if(is(t,i,e))return i;r=i+1}return-1}function fh(t,e,n,r){let i=[],o=Math.max(0,n),s=Math.min(t.length-e.length,Math.max(o,r));for(;o<=s;){let a=rs(t,e,o);if(a===-1||a>s)break;is(t,a,e)&&i.push(a),o=a+1}return i}function yc(t,e,n,r){let i=Math.max(0,n-r),o=Math.min(t.length,n+r),s=fh(t,e,i,o);return s.length===0?-1:(s.sort((a,l)=>Math.abs(a-n)-Math.abs(l-n)),s[0])}function hh(t,e,n,r){let i=Math.min(r,t.length);for(let o=Math.max(n,0);o<=i-e.length;o++){let s=!0;for(let a=0;a<e.length;a++)if(t[o+a]!==e[a]){s=!1;break}if(s){let a=o;for(let l=o+1;l<=i-e.length;l++){let c=!0;for(let d=0;d<e.length;d++)if(t[l+d]!==e[d]){c=!1;break}c&&(a=l)}return a}}return-1}function Si(t,e){let n=new an(t.subarray(e)),r=wt(n);if(!Q(r))throw new Error("Trailer object is not a dictionary");return r}function Ln(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 kc(t,e){or&&console.debug("[XRefTable]",t,e!=null?e:{})}function ts(t,e){or&&console.warn("[XRefTable]",t,e!=null?e:{})}function wc(t,e){if(!t)throw new Error(`/${e} missing`);if(ue(t)){let i=[];for(let o of t.items){let s=V(o);if(s===null)throw new Error(`/${e} must contain only numbers`);i.push(Math.floor(s))}return i}if(Array.isArray(t))return t.map(i=>Math.floor(Number(i)||0));if(typeof t=="number")return[Math.floor(t)];let n=V(t);if(n!==null)return[Math.floor(n)];let r=t;if(Array.isArray(r.items))return r.items.map(i=>Math.floor(Number(i)||0));throw new Error(`/${e} must be an array, got ${Ln(t)}`)}function Pc(t){let e=t.length,n=Math.min(1024*1024,e),r=new TextDecoder("latin1").decode(t.subarray(e-n,e)),i=r.lastIndexOf("startxref");if(i!==-1){let o=r.slice(i+9).match(/\d+/);if(o)return parseInt(o[0],10)}throw new Error("PDF missing startxref offset")}function Br(t,e){let n=new TextDecoder("latin1"),r=new Uint8Array([120,114,101,102]),i=e,o=Ci(t,r,i);if(o===-1||o-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(i=o+r.length;i<t.length&&(t[i]===13||t[i]===10);)i++;let s=new Map;for(;i<t.length;){for(;i<t.length&&(t[i]===13||t[i]===10);)i++;let a=i;for(;i<t.length&&t[i]!==13&&t[i]!==10;)i++;let l=n.decode(t.subarray(a,i)).trim();for(;i<t.length&&(t[i]===13||t[i]===10);)i++;if(!l)continue;if(l==="trailer"||l.startsWith("trailer")||l==="railer"||l.startsWith("railer")){let f=l.startsWith("railer")?Math.max(0,a-1):a,m=cr(t,f+7),p=Si(t,m),b=p.entries.get("Prev"),y=V(b),k=y===null?null:Math.floor(y),w=es(p);if(s.size===0&&k===null&&w===null)throw new Error("No valid xref entries found");return{entries:s,trailer:p,prevXRefOffset:k,offset:e,xrefStmOffset:w}}if(l==="%%EOF"||l.startsWith("startxref")){let f=new Uint8Array([116,114,97,105,108,101,114]),m=hh(t,f,e,a);if(m!==-1){let p=cr(t,m+7),b=Si(t,p),y=b.entries.get("Prev"),k=V(y),w=k===null?null:Math.floor(k),P=es(b);if(s.size===0&&w===null&&P===null)throw new Error("No valid xref entries found");return{entries:s,trailer:b,prevXRefOffset:w,offset:e,xrefStmOffset:P}}throw new Error("Reached EOF before trailer in traditional xref section")}let c=l.match(/^(\d+)\s+(\d+)$/);if(!c){if(/^\d+$/.test(l)){let f=new Uint8Array([116,114,97,105,108,101,114]),m=rs(t,f,Math.max(0,a-1));if(m!==-1&&m-a<=256){let p=cr(t,m+7),b=Si(t,p),y=b.entries.get("Prev"),k=V(y),w=k===null?null:Math.floor(k),P=es(b);if(s.size===0&&w===null&&P===null)throw new Error("No valid xref entries found");return{entries:s,trailer:b,prevXRefOffset:w,offset:e,xrefStmOffset:P}}continue}throw new Error(`Invalid xref subsection header: ${l}`)}let d=parseInt(c[1],10),h=parseInt(c[2],10);for(let f=0;f<h;f++){if(i+20>t.length)throw new Error(`Truncated xref at entry ${d+f}`);let m=i,p=n.decode(t.subarray(i,i+20));i+=20;let b=p.substring(0,10),y=p.substring(11,16),k=p[17],w=0,P=0,S="f";if(/^\d{10}$/.test(b)&&/^\d{5}$/.test(y)&&(k==="n"||k==="f"))w=parseInt(b,10),P=parseInt(y,10),S=k;else{i=m;let R=xc(t,i);i=R.next;let I=0;for(;I<3&&R.line.trim()==="";)R=xc(t,i),i=R.next,I++;let F=R.line.match(/^\s*(\d{10})\s+(\d{5})\s+([nf])\b/);if(!F)throw new Error(`Malformed fixed-width xref entry: ${p}`);w=parseInt(F[1],10),P=parseInt(F[2],10),S=F[3]}s.set(d+f,{type:"uncompressed",offset:w,genNum:P,inUse:S==="n"})}}throw new Error("trailer keyword not found after xref entries")}function mh(t,e){let{stream:n,resolvedObj:r}=ph(t,e),i=n.dict,o=jn(i.entries.get("Type"));o!=="XRef"&&ts("Resolved stream is not /Type /XRef",{offset:e,resolvedObj:r,type:o}),kc("Parsing xref stream",{offset:e,resolvedObj:r,type:o,wShape:Ln(i.entries.get("W")),indexShape:Ln(i.entries.get("Index")),sizeShape:Ln(i.entries.get("Size"))});let s,a;{let R=i.entries.get("W"),I=i.entries.get("Size"),F=V(I),A=i.entries.get("Index");try{if(s=wc(R,"W"),s.length!==3)throw new Error("/W must contain three integers");if(F===null)throw new Error("XRef stream missing /Size");if(a=A?wc(A,"Index"):[0,Math.floor(F)],a.length%2!==0)throw new Error("/Index must have even number of elements")}catch(G){let Y=G instanceof Error?G.message:String(G);throw ts("Failed parsing /W or /Index in xref stream",{offset:e,resolvedObj:r,error:Y,wShape:Ln(R),indexShape:Ln(A),sizeShape:Ln(I)}),G}}let l=new Map,[c,d,h]=s,f=c+d+h,m=Pe.decodeStreamSync(n),p=0;for(let R=0;R<a.length;R+=2){let I=a[R],F=a[R+1];for(let A=0;A<F;A++){if(p+f>m.length)throw new Error("XRef stream data is shorter than expected from /W and /Index");let G=O=>{let ge=0;for(let fe=0;fe<O;fe++)ge=ge<<8|m[p++];return ge},Y=c===0?1:G(c),E=G(d),ee=G(h),ne=I+A;Y===0?l.set(ne,{type:"uncompressed",offset:0,genNum:ee,inUse:!1}):Y===1?l.set(ne,{type:"uncompressed",offset:E,genNum:ee,inUse:!0}):Y===2&&l.set(ne,{type:"compressed",streamNum:E,indexNum:ee,genNum:0,inUse:!0})}}let b=i.entries.get("Prev"),y=V(b),k=y===null?null:Math.floor(y),w=new Map(i.entries),P=new Set(["W","Index","Filter","DecodeParms","Length","Columns","Predictor","Type","DL"]);for(let R of P)w.delete(R);return{entries:l,trailer:{type:"dict",entries:w},prevXRefOffset:k,offset:e}}function ph(t,e){let n=[0,-64,64,-256,256,-1024,1024,-4096,4096,-8192,8192],r=new Set,i=[],o=[];for(let s of n){let a=e+s;if(!(a<0||a>=t.length))try{let l=lr(t,a),c=`${l.objNum}.${l.genNum}`;if(r.has(c))continue;if(r.add(c),!he(l.object)){i.push(`offset ${a}: ${c} is not a stream`);continue}let d=l.object,h=d.dict.entries.has("W"),f=d.dict.entries.has("Size"),m=d.dict.entries.get("Type"),p=m&&typeof m=="object"&&"type"in m&&m.type==="name"?m.value:null,b=p==="XRef";if(h&&f)return kc("Resolved xref stream candidate",{requestedOffset:e,probeOffset:a,object:`${l.objNum} ${l.genNum} obj`,type:p}),{stream:d,resolvedObj:`${l.objNum} ${l.genNum} obj`};o.push(`offset ${a}: ${c} stream type=${p!=null?p:"unknown"} hasW=${h} hasSize=${f} isTypeXRef=${b}`)}catch(l){let c=l instanceof Error?l.message:String(l);i.push(`offset ${a}: ${c}`)}}throw new Error(`Could not resolve xref stream with /W and /Size near startxref ${e}. Non-xref streams: ${o.join(" || ")||"none"}. Failures: ${i.join(" || ")||"none"}`)}function Dc(t,e){let n=new Uint8Array([120,114,101,102]),r=cr(t,e);if(is(t,r,n))return Br(t,r);let i=Ci(t,n,Math.max(0,e));if(i!==-1&&i-e<=2048)return Br(t,i);let o=yc(t,n,e,32768);if(o!==-1)return Br(t,o);if(new TextDecoder("latin1").decode(t.subarray(e,Math.min(e+64,t.length))).trimStart().startsWith("xref"))return Br(t,e);try{return mh(t,e)}catch(a){let l=yc(t,n,e,131072);if(l!==-1)return Br(t,l);throw a}}var ns=new TextDecoder("latin1"),vc=t=>t>=48&&t<=57;function gh(t,e){let n=e-1;for(;n>=0&&Xt(t[n]);)n--;let r=n;for(;n>=0&&vc(t[n]);)n--;let i=n+1;if(i>r)return null;for(;n>=0&&Xt(t[n]);)n--;let o=n;for(;n>=0&&vc(t[n]);)n--;let s=n+1;if(s>o)return null;let a=parseInt(ns.decode(t.subarray(i,r+1)),10),l=parseInt(ns.decode(t.subarray(s,o+1)),10);return Number.isFinite(l)?{objNum:l,genNum:Number.isFinite(a)?a:0,start:s}:null}function xh(t){let e=new Uint8Array([116,114,97,105,108,101,114]),n=null,r=0;for(;;){let i=Ci(t,e,r);if(i===-1)break;try{let o=cr(t,i+e.length),s=Si(t,o);s.entries.get("Root")&&(n=s)}catch{}r=i+e.length}return n}function bh(t,e){for(let[n,r]of e)if(!(r.type!=="uncompressed"||!r.inUse))try{let{object:i}=lr(t,r.offset,n),o=he(i)?i.dict:Q(i)?i:null;if(!o)continue;if(jn(o.entries.get("Type"))==="Catalog"){let s=new Map;return s.set("Root",{type:"ref",objNum:n,genNum:r.genNum}),{type:"dict",entries:s}}}catch{}throw new Error("xref recovery: no trailer and no /Catalog object found")}function yh(t,e){for(let[n,r]of Array.from(e))if(!(r.type!=="uncompressed"||!r.inUse))try{let{object:i}=lr(t,r.offset,n);if(!he(i)||jn(i.dict.entries.get("Type"))!=="ObjStm")continue;let o=V(i.dict.entries.get("N")),s=V(i.dict.entries.get("First"));if(o===null||s===null)continue;let a=Pe.decodeStreamSync(i),c=ns.decode(a.subarray(0,Math.min(Math.floor(s),a.length))).split(/\s+/).map(d=>parseInt(d,10)).filter(d=>Number.isFinite(d));for(let d=0;d<Math.floor(o);d++){let h=c[d*2];if(h===void 0)break;e.has(h)||e.set(h,{type:"compressed",streamNum:n,indexNum:d,genNum:0,inUse:!0})}}catch{}}function os(t){var o;let e=new Uint8Array([111,98,106]),n=new Map,r=0;for(;;){let s=Ci(t,e,r);if(s===-1)break;let a=gh(t,s);a&&n.set(a.objNum,{type:"uncompressed",offset:a.start,genNum:a.genNum,inUse:!0}),r=s+e.length}if(n.size===0)throw new Error("xref recovery: no indirect objects found (not a PDF?)");yh(t,n);let i=(o=xh(t))!=null?o:bh(t,n);return ts("Rebuilt xref by full-file scan",{objects:n.size}),{entries:n,trailer:i,prevXRefOffset:null,offset:0}}function ss(t){let e=[],n=new Set,r=[Pc(t)];for(;r.length>0;){let i=r.shift();if(i===null||n.has(i))continue;n.add(i);let o=Dc(t,i);e.push(o),o.xrefStmOffset!=null&&r.push(o.xrefStmOffset),o.prevXRefOffset!=null&&r.push(o.prevXRefOffset)}return e}var wh=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function Sc(t,e,n){let r=t.length*8,i=Math.ceil((t.length+1+n)/e)*e,o=new Uint8Array(i);o.set(t),o[t.length]=128;let s=new DataView(o.buffer);return s.setUint32(i-4,r>>>0,!1),s.setUint32(i-8,Math.floor(r/4294967296)>>>0,!1),o}function Fi(t){let e=1779033703,n=3144134277,r=1013904242,i=2773480762,o=1359893119,s=2600822924,a=528734635,l=1541459225,c=Sc(t,64,8),d=new DataView(c.buffer),h=(b,y)=>b>>>y|b<<32-y,f=new Uint32Array(64);for(let b=0;b<c.length;b+=64){for(let A=0;A<16;A++)f[A]=d.getUint32(b+A*4,!1);for(let A=16;A<64;A++){let G=f[A-15],Y=f[A-2],E=h(G,7)^h(G,18)^G>>>3,ee=h(Y,17)^h(Y,19)^Y>>>10;f[A]=f[A-16]+E+f[A-7]+ee|0}let y=e,k=n,w=r,P=i,S=o,R=s,I=a,F=l;for(let A=0;A<64;A++){let G=h(S,6)^h(S,11)^h(S,25),Y=S&R^~S&I,E=F+G+Y+wh[A]+f[A]|0,ee=h(y,2)^h(y,13)^h(y,22),ne=y&k^y&w^k&w,O=ee+ne|0;F=I,I=R,R=S,S=P+E|0,P=w,w=k,k=y,y=E+O|0}e=e+y|0,n=n+k|0,r=r+w|0,i=i+P|0,o=o+S|0,s=s+R|0,a=a+I|0,l=l+F|0}let m=new Uint8Array(32),p=new DataView(m.buffer);return[e,n,r,i,o,s,a,l].forEach((b,y)=>p.setUint32(y*4,b>>>0,!1)),m}var ft=(BigInt(1)<<BigInt(64))-BigInt(1),vh=BigInt(32),kh=BigInt(255),Ph=["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(t=>BigInt(t)),Dh=["0x6a09e667f3bcc908","0xbb67ae8584caa73b","0x3c6ef372fe94f82b","0xa54ff53a5f1d36f1","0x510e527fade682d1","0x9b05688c2b3e6c1f","0x1f83d9abfb41bd6b","0x5be0cd19137e2179"].map(t=>BigInt(t)),Sh=["0xcbbb9d5dc1059ed8","0x629a292a367cd507","0x9159015a3070dd17","0x152fecd8f70e5939","0x67332667ffc00b31","0x8eb44a8768581511","0xdb0c2e0d64f98fa7","0x47b5481dbefa4fa4"].map(t=>BigInt(t));function Cc(t,e,n){let r=(k,w)=>(k>>BigInt(w)|k<<BigInt(64-w))&ft,i=(k,w)=>k>>BigInt(w),o=Sc(t,128,16),s=new DataView(o.buffer),[a,l,c,d,h,f,m,p]=e,b=new Array(80);for(let k=0;k<o.length;k+=128){for(let Y=0;Y<16;Y++){let E=BigInt(s.getUint32(k+Y*8,!1)>>>0),ee=BigInt(s.getUint32(k+Y*8+4,!1)>>>0);b[Y]=E<<vh|ee}for(let Y=16;Y<80;Y++){let E=b[Y-15],ee=b[Y-2],ne=r(E,1)^r(E,8)^i(E,7),O=r(ee,19)^r(ee,61)^i(ee,6);b[Y]=b[Y-16]+ne+b[Y-7]+O&ft}let w=a,P=l,S=c,R=d,I=h,F=f,A=m,G=p;for(let Y=0;Y<80;Y++){let E=r(I,14)^r(I,18)^r(I,41),ee=I&F^~I&ft&A,ne=G+E+ee+Ph[Y]+b[Y]&ft,O=r(w,28)^r(w,34)^r(w,39),ge=w&P^w&S^P&S,fe=O+ge&ft;G=A,A=F,F=I,I=R+ne&ft,R=S,S=P,P=w,w=ne+fe&ft}a=a+w&ft,l=l+P&ft,c=c+S&ft,d=d+R&ft,h=h+I&ft,f=f+F&ft,m=m+A&ft,p=p+G&ft}let y=new Uint8Array(64);return[a,l,c,d,h,f,m,p].forEach((k,w)=>{for(let P=0;P<8;P++)y[w*8+P]=Number(k>>BigInt((7-P)*8)&kh)}),y.subarray(0,n)}var Fc=t=>Cc(t,Dh,64),Rc=t=>Cc(t,Sh,48);var Ch=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 as(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,i=4023233417,o=2562383102,s=271733878,a=t.length,l=(56-(a+1)%64+64)%64,c=new Uint8Array(a+1+l+8);c.set(t),c[a]=128;let d=a*8;c[c.length-8]=d&255,c[c.length-7]=d>>>8&255,c[c.length-6]=d>>>16&255,c[c.length-5]=d>>>24&255;let h=new DataView(c.buffer);for(let p=0;p<c.length;p+=64){let b=r,y=i,k=o,w=s,P=new Uint32Array(16);for(let S=0;S<16;S++)P[S]=h.getUint32(p+S*4,!0);for(let S=0;S<64;S++){let R,I;S<16?(R=y&k|~y&w,I=S):S<32?(R=w&y|~w&k,I=(5*S+1)%16):S<48?(R=y^k^w,I=(3*S+5)%16):(R=k^(y|~w),I=7*S%16);let F=w;w=k,k=y;let A=b+R+n[S]+P[I]|0;y=y+(A<<e[S]|A>>>32-e[S])|0,b=F}r=r+b|0,i=i+y|0,o=o+k|0,s=s+w|0}let f=new Uint8Array(16),m=new DataView(f.buffer);return m.setUint32(0,r,!0),m.setUint32(4,i,!0),m.setUint32(8,o,!0),m.setUint32(12,s,!0),f}function Fh(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 i=new Uint8Array(e.length),o=0;r=0;for(let s=0;s<e.length;s++){o=(o+1)%256,r=(r+n[o])%256;let a=n[o];n[o]=n[r],n[r]=a,i[s]=e[s]^n[(n[o]+n[r])%256]}return i}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]),Rh=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 ls(t){let e=t.length/4,n=e+6,r=new Uint32Array(4*(n+1));for(let o=0;o<e;o++)r[o]=t[4*o]<<24|t[4*o+1]<<16|t[4*o+2]<<8|t[4*o+3];let i=[0,1,2,4,8,16,32,64,128,27,54];for(let o=e;o<4*(n+1);o++){let s=r[o-1];if(o%e===0){let a=s>>>24&255,l=s>>>16&255,c=s>>>8&255,d=s&255;s=cn[l]<<24|cn[c]<<16|cn[d]<<8|cn[a],s^=i[o/e]<<24}else if(e>6&&o%e===4){let a=s>>>24&255,l=s>>>16&255,c=s>>>8&255,d=s&255;s=cn[a]<<24|cn[l]<<16|cn[c]<<8|cn[d]}r[o]=r[o-e]^s}return r}function Mc(t){for(let e=0;e<16;e++)t[e]=Rh[t[e]]}function Ac(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 Mh=t=>(t<<1^(t>>>7&1)*27)&255;function Ye(t,e){let n=0,r=t;for(let i=0;i<8;i++)e>>>i&1&&(n^=r),r=Mh(r);return n}function Ah(t){for(let e=0;e<4;e++){let n=e*4,r=t[n],i=t[n+1],o=t[n+2],s=t[n+3];t[n]=Ye(r,14)^Ye(i,11)^Ye(o,13)^Ye(s,9),t[n+1]=Ye(r,9)^Ye(i,14)^Ye(o,11)^Ye(s,13),t[n+2]=Ye(r,13)^Ye(i,9)^Ye(o,14)^Ye(s,11),t[n+3]=Ye(r,11)^Ye(i,13)^Ye(o,9)^Ye(s,14)}}function dr(t,e,n){for(let r=0;r<4;r++){let i=e[n*4+r];t[r*4]^=i>>>24&255,t[r*4+1]^=i>>>16&255,t[r*4+2]^=i>>>8&255,t[r*4+3]^=i&255}}function Oc(t,e,n){let r=new Uint8Array(16);r.set(t),dr(r,e,n);for(let i=n-1;i>=1;i--)Ac(r),Mc(r),dr(r,e,i),Ah(r);return Ac(r),Mc(r),dr(r,e,0),r}function Nc(t,e){if(e.length<16)return e;let n=ls(t),r=t.length/4+6,i=e.subarray(0,16),o=e.subarray(16),s=o.length/16,a=new Uint8Array(o.length),l=i;for(let d=0;d<s;d++){let h=d*16,f=o.subarray(h,h+16),m=Oc(f,n,r);for(let p=0;p<16;p++)a[h+p]=m[p]^l[p];l=f}let c=a[a.length-1];if(c>0&&c<=16){let d=!0;for(let h=a.length-c;h<a.length;h++)if(a[h]!==c){d=!1;break}if(d)return a.subarray(0,a.length-c)}return a}function Tc(t){for(let e=0;e<16;e++)t[e]=cn[t[e]]}function Ec(t){let e;e=t[1],t[1]=t[5],t[5]=t[9],t[9]=t[13],t[13]=e,e=t[2],t[2]=t[10],t[10]=e,e=t[6],t[6]=t[14],t[14]=e,e=t[15],t[15]=t[11],t[11]=t[7],t[7]=t[3],t[3]=e}function Nh(t){for(let e=0;e<4;e++){let n=e*4,r=t[n],i=t[n+1],o=t[n+2],s=t[n+3];t[n]=Ye(r,2)^Ye(i,3)^o^s,t[n+1]=r^Ye(i,2)^Ye(o,3)^s,t[n+2]=r^i^Ye(o,2)^Ye(s,3),t[n+3]=Ye(r,3)^i^o^Ye(s,2)}}function Th(t,e,n){let r=new Uint8Array(16);r.set(t),dr(r,e,0);for(let i=1;i<n;i++)Tc(r),Ec(r),Nh(r),dr(r,e,i);return Tc(r),Ec(r),dr(r,e,n),r}function Eh(t,e,n){let r=ls(t),i=t.length/4+6,o=new Uint8Array(n.length),s=e;for(let a=0;a<n.length;a+=16){let l=new Uint8Array(16);for(let d=0;d<16;d++)l[d]=n[a+d]^s[d];let c=Th(l,r,i);o.set(c,a),s=c}return o}function Oh(t,e,n){let r=ls(t),i=t.length/4+6,o=new Uint8Array(n.length),s=e;for(let a=0;a<n.length;a+=16){let l=n.subarray(a,a+16),c=Oc(l,r,i);for(let d=0;d<16;d++)o[a+d]=c[d]^s[d];s=l}return o}function Ih(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}function cs(...t){let e=t.reduce((i,o)=>i+o.length,0),n=new Uint8Array(e),r=0;for(let i of t)n.set(i,r),r+=i.length;return n}function Bh(t,e,n){let r=Fi(cs(t,e,n)),i=0;for(;;){let o=cs(t,r,n),s=new Uint8Array(o.length*64);for(let c=0;c<64;c++)s.set(o,c*o.length);let a=Eh(r.subarray(0,16),r.subarray(16,32),s),l=0;for(let c=0;c<16;c++)l+=a[c];if(l%=3,r=l===0?Fi(a):l===1?Rc(a):Fc(a),i++,i>=64&&a[a.length-1]<=i-32)break}return r.subarray(0,32)}var Ri=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 R,I,F,A;let r=e.entries.get("V"),i=e.entries.get("R"),o=e.entries.get("Length"),s=e.entries.get("O"),a=e.entries.get("U"),l=e.entries.get("P"),c=e.entries.get("EncryptMetadata");this.v=(R=V(r))!=null?R:0,this.r=(I=V(i))!=null?I:0;let h=((F=V(o))!=null?F:40)/8,f=e.entries.get("UE"),m=s&&"value"in s&&s.value instanceof Uint8Array?s.value:new Uint8Array(0),p=a&&"value"in a&&a.value instanceof Uint8Array?a.value:new Uint8Array(0),b=f&&"value"in f&&f.value instanceof Uint8Array?f.value:new Uint8Array(0),y=(A=V(l))!=null?A:0,k=c&&"value"in c?c.value:!0,w=e.entries.get("CF"),P=e.entries.get("StmF"),S=(()=>{if(P&&"value"in P&&(P.value==="AESV2"||P.value==="AESV3"))return P.value;if(w&&Q(w)){let G=w.entries.get("StdCF");if(G&&Q(G)){let Y=G.entries.get("CFM");if(Y&&"value"in Y&&typeof Y.value=="string")return Y.value}}})();(S==="AESV2"||S==="AESV3")&&(this.isAes=!0),(this.v===5||this.r===5||this.r===6)&&(this.isAes=!0),this.fileKey=this.v===5?this.deriveFileKeyV5(new Uint8Array(0),p,b):this.deriveFileKey(new Uint8Array(0),h,m,p,y,n,k)}deriveFileKeyV5(e,n,r){if(n.length<48||r.length<32)return new Uint8Array(0);let i=n.subarray(0,32),o=n.subarray(32,40),s=n.subarray(40,48),a=new Uint8Array(0),l=this.hashV5(e,o,a);if(!Ih(l,i))return ut("[Decryption] AES-256 document requires a non-empty user password; cannot decrypt."),new Uint8Array(0);let c=this.hashV5(e,s,a);return Oh(c,new Uint8Array(16),r.subarray(0,32))}hashV5(e,n,r){return this.r===6?Bh(e,n,r):Fi(cs(e,n,r))}deriveFileKey(e,n,r,i,o,s,a=!0){let l=new Uint8Array(32);l.set(e.subarray(0,Math.min(32,e.length))),e.length<32&&l.set(Ch.subarray(0,32-e.length),e.length);let c=[];c.push(...l),c.push(...r),c.push(o&255),c.push(o>>>8&255),c.push(o>>>16&255),c.push(o>>>24&255),s&&s.length>0&&c.push(...s),this.r>=3&&!a&&c.push(255,255,255,255);let d=as(new Uint8Array(c));if(this.r>=3){let f=d.subarray(0,n);for(let m=0;m<50;m++)f=as(f).subarray(0,n);return f}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 i=new Uint8Array(this.fileKey.length+r.length+(this.isAes?4:0));i.set(this.fileKey),i.set(r,this.fileKey.length),this.isAes&&i.set([115,65,108,84],this.fileKey.length+r.length);let o=as(i),s=Math.min(16,this.fileKey.length+5);return o.subarray(0,s)}decrypt(e,n,r){return this.v===5?this.fileKey.length===0?e:Nc(this.fileKey,e):this.isAes?Nc(this.deriveObjectKey(n,r),e):Fh(this.deriveObjectKey(n,r),e)}};var ln=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[l,c]of n[a].entries)r.set(l,c);let i=n[0].trailer,o=this.extractRootRef(i);this.document={rawBytes:this.bytes,xrefTables:new Map([[0,r]]),objectCache:new Map,rootRef:o,trailer:i,version:e};let s=i.entries.get("Encrypt");if(s){let a=null;if($e(s)){this.encryptRef=s;let l=this.loadObject(s);Q(l)&&(a=l)}else Q(s)&&(a=s);if(a){let l,c=i.entries.get("ID");if(c&&ue(c)&&c.items.length>0){let d=c.items[0];Qo(d)&&(l=d.value)}this.decryptionHandler=new Ri(a,l)}}return this.document}catch(e){throw wn("[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(){try{let e=ss(this.bytes);if(e.length>0&&e[0].trailer.entries.get("Root"))return e;ut("[PDFParser] xref parsed but no /Root in newest trailer \u2014 rebuilding by scan")}catch(e){ut("[PDFParser] xref parse failed, rebuilding by scan:",e instanceof Error?e.message:e)}return[os(this.bytes)]}extractRootRef(e){let n=e.entries.get("Root");if(!n)throw wn("[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 wn("[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 i=r.get(e.objNum);if(!i)throw new Error(`Object ${e.objNum} not found in xref`);if(i.type==="uncompressed"){if(!i.inUse)throw new Error(`Object ${e.objNum} is marked free in xref`);if(i.offset===0){let o={type:"dict",entries:new Map};throw this.document.objectCache.set(n,o),new Error(`Object ${e.objNum} has ghost xref entry (offset 0)`)}try{let{object:o,objectOffset:s}=lr(this.bytes,i.offset,e.objNum),a=he(o)?this.repairStreamBytesFromLengthRef(o,s):o,l=this.decryptObject(a,e.objNum,e.genNum);return this.document.objectCache.set(n,l),l}catch(o){throw ut(`[PDFParser] Failed to load object ${e.objNum}: ${o}`),o}}else{if(!i.inUse)throw new Error(`Object ${e.objNum} is marked free in compressed xref entry`);let o=i.streamNum;if(!this.objectStreamCache.has(o)){let a=this.loadObjectStream(o,r);this.objectStreamCache.set(o,a)}let s=this.document.objectCache.get(n);if(!s)throw new Error(`Object ${e.objNum} not found in object stream ${o}`);return s}}loadObjectStream(e,n){var y,k;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 i={type:"ref",objNum:e,genNum:0},o=this.loadObject(i);if(!he(o))throw new Error(`Object ${e} is not a stream`);let s=o.dict.entries.get("Type");if(!s||s.type!=="name"||s.value!=="ObjStm")throw new Error(`Object ${e} is not an /ObjStm`);let a=o.dict.entries.get("N"),l=o.dict.entries.get("First");if(!a||!Di(a)||!l||!Di(l))throw new Error(`Object stream ${e} missing numeric /N or /First`);let c=Math.floor(a.value),d=Math.floor(l.value);if(c<0||d<0)throw new Error(`Object stream ${e} has invalid /N or /First values`);let h=o,f;try{f=Pe.decodeStreamSync(h)}catch(w){let P=h.dict.entries.get("Filter"),S=h.dict.entries.get("Length"),R=(k=(y=h.rawBytes)!=null?y:h.data)!=null?k:new Uint8Array(0),I=Array.from(R.subarray(0,8)).map(Y=>Y.toString(16).padStart(2,"0")).join(" "),F=Math.max(0,R.length-8),A=Array.from(R.subarray(F)).map(Y=>Y.toString(16).padStart(2,"0")).join(" "),G=w instanceof Error?w.message:String(w);throw new Error(`Object stream ${e} decode failed: ${G}; Filter=${JSON.stringify(P)} Length=${JSON.stringify(S)} rawLen=${R.length} first8=[${I}] last8=[${A}]`)}if(d>f.length)throw new Error(`Object stream ${e} /First (${d}) exceeds decoded length (${f.length})`);let p=new TextDecoder("latin1").decode(f.subarray(0,d)).match(/\d+/g)||[];if(p.length<c*2)throw new Error(`Object stream ${e} header has ${p.length} numbers, expected at least ${c*2}`);let b=new Map;for(let w=0;w<c;w++){let P=parseInt(p[w*2],10),S=parseInt(p[w*2+1],10),R=d+S;if(!(!Number.isFinite(P)||!Number.isFinite(S)||S<0||R>f.length))try{let I=new an(f.subarray(R)),F=wt(I);b.set(P,F),this.document.objectCache.set(`${P}.0`,F)}catch(I){ut(`[WARN] Failed to parse object ${P} from object stream ${e}:`,I)}}return b}repairStreamBytesFromLengthRef(e,n){var c,d;let r=e.dict.entries.get("Length");if(!r||!$e(r))return e;let i=null;try{let h=this.loadObject(r);i=V(h)}catch{return e}if(i===null)return e;let o=Math.max(0,Math.floor(i)),s=this.findStreamDataStart(n);if(s<0||s+o>this.bytes.length)return e;let a=(c=e.rawBytes)!=null?c:e.data;if(a&&a.length===o)return e;let l=this.bytes.subarray(s,s+o);return ut(`[PDFParser] Repaired stream bytes via indirect /Length at offset ${n}: resolved length=${o}, previous length=${(d=a==null?void 0:a.length)!=null?d:0}`),{type:"stream",dict:e.dict,rawBytes:l,data:l,decode:Pe.createLazyDecoder(e.dict,l)}}findStreamDataStart(e){let n=[115,116,114,101,97,109],r=Math.min(this.bytes.length-n.length,e+1024*1024);for(let i=Math.max(0,e);i<=r;i++){let o=!0;for(let h=0;h<n.length;h++)if(this.bytes[i+h]!==n[h]){o=!1;break}if(!o)continue;let s=i>0?this.bytes[i-1]:32,a=this.bytes[i+n.length];if(!(s===10||s===13||s===32||s===9||s===62)||!(a===10||a===13||a===32||a===9))continue;let d=i+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 i,o;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,l]of e.entries)s.set(a,this.decryptObjectRecursive(l,n,r));return{...e,entries:s}}if(e.type==="stream"){let s=(o=(i=e.rawBytes)!=null?i:e.data)!=null?o:new Uint8Array(0),a=s.length>0?this.decryptionHandler.decrypt(s,n,r):s,l=this.decryptObjectRecursive(e.dict,n,r);return{type:"stream",dict:l,rawBytes:a,data:a,decode:Pe.createLazyDecoder(l,a)}}return e}};function jr(t){if(!t)return[];if($e(t))return[t];if(ue(t)){let e=[];for(let n of t.items)e.push(...jr(n));return e}return[]}function jh(t){if(t.length===0)return new Uint8Array(0);let e=Math.max(0,t.length-1),n=t.reduce((o,s)=>o+s.length,0)+e,r=new Uint8Array(n),i=0;for(let o=0;o<t.length;o++)r.set(t[o],i),i+=t[o].length,o<t.length-1&&(r[i]=32,i+=1);return r}async function ds(t,e){let n=jr(t);if(n.length===0)return{combinedBytes:new Uint8Array(0),streamCount:0,streamByteLengths:[]};let r=[];for(let i of n){let o=await Promise.resolve(e(i));if(!he(o)){ut(`[WARN] Contents ref ${i.objNum} ${i.genNum} R is not a stream, skipping`);continue}try{let s=o.decode?await o.decode():await Pe.decodeStream(o);r.push(s)}catch(s){throw wn(`[ContentStreamLoader] Failed to decode stream ${i.objNum} ${i.genNum} R:`,s),s}}return{combinedBytes:jh(r),streamCount:r.length,streamByteLengths:r.map(i=>i.length)}}function un(t){return ur(t).commands}function ur(t){let e=new an(t),n=[],r=[],i=[],o=-1;for(;e.skipWhitespace(),!(e.getPosition()>=t.length);){let s=e.getPosition(),a=t[s];if(Bc(a)){let l=e.readWord();if(!l)break;if(l==="BI"){let d=Uh(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()})),i.length=0,o=-1;continue}let c=$h(l,i);c&&(n.push(c),r.push({start:o>=0?o:s,end:e.getPosition()})),i.length=0,o=-1}else{o<0&&(o=s);try{let l=wt(e);i.push(l)}catch{e.setPosition(s+1)}}}return{commands:n,ranges:r}}function Bc(t){return t>=65&&t<=90||t>=97&&t<=122||t===39||t===34}var Lh=t=>{var r,i;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=(i=t.entries.get("CS"))!=null?i: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 Uh(t,e){var n,r,i,o,s;try{let a=new Map;for(;;){t.skipWhitespace();let k=t.getPosition();if(k>=e.length)return null;let w=e[k];if(w===47){let P=wt(t);if(!P||!("type"in P)||P.type!=="name")return null;t.skipWhitespace(),a.set(P.value,wt(t))}else if(Bc(w)){if(t.readWord()==="ID")break;return null}else return null}let l={type:"dict",entries:a},c=t.getPosition();Xt(e[c])&&(c+=e[c]===13&&e[c+1]===10?2:1);let d=(n=a.get("L"))!=null?n:a.get("Length"),h=V(d),f=a.has("F")||a.has("Filter"),m=-1;if(h!==null&&h>=0&&c+h<=e.length)m=c+h;else if(!f){let k=V((r=a.get("W"))!=null?r:a.get("Width")),w=V((i=a.get("H"))!=null?i:a.get("Height")),P=(s=V((o=a.get("BPC"))!=null?o:a.get("BitsPerComponent")))!=null?s:8;if(k!==null&&w!==null&&k>0&&w>0){let S=Math.ceil(k*P*Lh(l)/8)*w;c+S<=e.length&&(m=c+S)}}if(m<0){for(let k=c;k+1<e.length;k++){if(e[k]!==69||e[k+1]!==73||k>c&&!Xt(e[k-1]))continue;let w=e[k+2];if(!(w!==void 0&&!Xt(w)&&!Ir(w))){m=Math.max(c,k-1);break}}if(m<0)return null}let p=new Uint8Array(e.subarray(c,m));t.setPosition(m),t.skipWhitespace();let b=t.getPosition();if(e[b]!==69||e[b+1]!==73)return null;let y=e[b+2];return y!==void 0&&!Xt(y)&&!Ir(y)?null:(t.setPosition(b+2),{command:{op:"inline_image",params:l,data:p},end:b+2})}catch{return null}}function $h(t,e){switch(t){case"q":return{op:"save_state"};case"Q":return{op:"restore_state"};case"cm":return{op:"set_ctm",matrix:Ic(e)};case"w":return{op:"set_line_width",width:oe(e,0)};case"J":return{op:"set_line_cap",cap:Math.floor(oe(e,0))};case"j":return{op:"set_line_join",join:Math.floor(oe(e,0))};case"M":return{op:"set_miter_limit",limit:oe(e,0)};case"d":return{op:"set_dash",array:_h(e,0),phase:oe(e,1)};case"ri":return{op:"set_rendering_intent",intent:dn(e,0)};case"gs":return{op:"set_graphics_state",name:dn(e,0)};case"rg":return{op:"set_fill_color_rgb",r:oe(e,0),g:oe(e,1),b:oe(e,2)};case"RG":return{op:"set_stroke_color_rgb",r:oe(e,0),g:oe(e,1),b:oe(e,2)};case"g":return{op:"set_fill_gray",gray:oe(e,0)};case"G":return{op:"set_stroke_gray",gray:oe(e,0)};case"k":return{op:"set_fill_cmyk",c:oe(e,0),m:oe(e,1),y:oe(e,2),k:oe(e,3)};case"K":return{op:"set_stroke_cmyk",c:oe(e,0),m:oe(e,1),y:oe(e,2),k:oe(e,3)};case"cs":return{op:"set_fill_color_space",name:dn(e,0)};case"CS":return{op:"set_stroke_color_space",name:dn(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(Mi),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(Mi),patternName:r}}case"m":return{op:"move_to",x:oe(e,0),y:oe(e,1)};case"l":return{op:"line_to",x:oe(e,0),y:oe(e,1)};case"c":return{op:"curve_to",x1:oe(e,0),y1:oe(e,1),x2:oe(e,2),y2:oe(e,3),x3:oe(e,4),y3:oe(e,5)};case"v":return{op:"curve_to_v",x2:oe(e,0),y2:oe(e,1),x3:oe(e,2),y3:oe(e,3)};case"y":return{op:"curve_to",x1:oe(e,0),y1:oe(e,1),x2:oe(e,2),y2:oe(e,3),x3:oe(e,2),y3:oe(e,3)};case"re":return{op:"rect",x:oe(e,0),y:oe(e,1),w:oe(e,2),h:oe(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:dn(e,0),size:oe(e,1)};case"Td":return{op:"move_text",tx:oe(e,0),ty:oe(e,1)};case"TD":return{op:"move_text_set_leading",tx:oe(e,0),ty:oe(e,1)};case"Tm":return{op:"set_text_matrix",matrix:Ic(e)};case"T*":return{op:"next_line"};case"Tc":return{op:"set_char_spacing",spacing:oe(e,0)};case"Tw":return{op:"set_word_spacing",spacing:oe(e,0)};case"Tz":return{op:"set_horiz_scale",scale:oe(e,0)};case"TL":return{op:"set_leading",leading:oe(e,0)};case"Tr":return{op:"set_text_render",mode:oe(e,0)};case"Ts":return{op:"set_text_rise",rise:oe(e,0)};case"Tj":return{op:"show_string",data:us(e,0)};case"TJ":return{op:"show_strings",items:zh(e,0)};case"'":return{op:"next_line_show_string",data:us(e,0)};case'"':return{op:"set_spacing_next_line_show_string",wordSpacing:oe(e,0),charSpacing:oe(e,1),data:us(e,2)};case"d0":return{op:"type3_glyph_width",wx:oe(e,0),wy:oe(e,1)};case"d1":return{op:"type3_glyph_width",wx:oe(e,0),wy:oe(e,1)};case"sh":return{op:"shade",name:dn(e,0)};case"Do":return{op:"xobject",name:dn(e,0)};case"BMC":return{op:"begin_marked_content",tag:dn(e,0)};case"BDC":{let n=e[1];return{op:"begin_marked_content",tag:dn(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 oe(t,e){return Mi(t[e])}function Mi(t){let e=V(t);return e===null?0:e}function dn(t,e){let n=t[e];return n&&typeof n=="object"&&"type"in n&&n.type==="name"?n.value:""}function us(t,e){let n=t[e];return n&&typeof n=="object"&&"type"in n&&n.type==="string"?n.value:new Uint8Array(0)}function _h(t,e){let n=t[e];return ue(n)?n.items.map(Mi):[]}function zh(t,e){let n=t[e];return ue(n)?n.items.map(r=>{let i=V(r);return i!==null?i:r&&typeof r=="object"&&"type"in r&&r.type==="string"?r.value:0}):[]}function Ic(t){return[oe(t,0),oe(t,1),oe(t,2),oe(t,3),oe(t,4),oe(t,5)]}var Ai=t=>t.map(e=>e.text).join(""),Lc=(t,e={})=>{let n=Un(t);return n.length>1?!0:n.length===0?!1:vn(n[0].style)!==vn(e)},Xh=t=>t?`${t.r.toFixed(4)},${t.g.toFixed(4)},${t.b.toFixed(4)}`:"-",vn=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:"-",Xh(t.color)].join("|")},Un=t=>{let e=[];for(let n of t){if(n.text.length===0)continue;let r=e[e.length-1];r&&vn(r.style)===vn(n.style)?r.text+=n.text:e.push({text:n.text,style:{...n.style}})}return e},Yh=[[/times|serif|georgia|cambria|garamond|minion/,"Times"],[/courier|mono|consol/,"Courier"]],fs=(t,e={})=>{let n=(t!=null?t:"").replace(/^[A-Z]{6}\+/,"").replace(/[#,\s]/g,"").toLowerCase(),r="Helvetica";for(let[o,s]of Yh)if(o.test(n)){r=s;break}let i=`${e.bold?"Bold":""}${e.italic?"Italic":""}`;return i?`${r}-${i}`:r},jc={Helvetica:718,Times:662,Courier:562},Wh=t=>{var n;let e=fs(t).split("-")[0];return(n=jc[e])!=null?n:jc.Helvetica},Uc=(t,e)=>{if(!t||!Number.isFinite(t)||t<=0)return 1;let n=Wh(e),r=t/n;return!Number.isFinite(r)||r<=0?1:Math.min(1.5,Math.max(.5,r))};var Ni=(t,e,n,r=.5)=>{let i=t.y+t.height,o=t.y,s=t.x+t.width,a=m=>{let p=m.pdfX+m.width/2,b=m.pdfY+m.height/2;if(p>=t.x&&p<=s&&b>=o&&b<=i)return!0;let y=Math.max(0,Math.min(s,m.pdfX+m.width)-Math.max(t.x,m.pdfX)),k=Math.max(0,Math.min(i,m.pdfY+m.height)-Math.max(o,m.pdfY)),w=m.width*m.height;return w>0&&y*k/w>=.6},l=e.filter(m=>!a(m)),c={},d,h;for(let m of l)if(!(m.pdfX+m.width<=t.x||m.pdfX>=n)){if(m.pdfY>=i)d=d===void 0?m.pdfY:Math.min(d,m.pdfY);else if(m.pdfY+m.height<=o){let p=m.pdfY+m.height;h=h===void 0?p:Math.max(h,p)}}d!==void 0&&(c.maxY=Math.max(i,d-r)),h!==void 0&&(c.minY=Math.min(o,h+r));let f;for(let m of l)Math.min(i,m.pdfY+m.height)-Math.max(o,m.pdfY)<=0||m.pdfX<s||(f=f===void 0?m.pdfX:Math.min(f,m.pdfX));return f!==void 0&&(c.maxRight=Math.max(s,f-r)),c},Ti=(t,e)=>{let n=t.y+t.height,r=t.y,i=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<i&&e.maxRight>t.x&&(i=e.maxRight),{x:t.x,y:r,width:Math.max(0,i-t.x),height:Math.max(0,n-r)}};var $c=50,fr=class{static getAllPages(e,n={}){let r=[],i=[];try{r.push("[TRAVERSE] Starting page tree traversal...");let o=e.rootRef;r.push(`[CATALOG] Root reference: ${o.objNum} ${o.genNum} R`);let s=`${o.objNum}.${o.genNum}`,a=e.objectCache.get(s);if((!a||!Q(a))&&n.objectLoader)try{a=n.objectLoader(o),r.push("[CATALOG] Loaded root catalog from file")}catch(p){let b=p instanceof Error?p.message:String(p);r.push(`[WARN] Failed to load root catalog: ${b}`)}if(!a||!Q(a))return r.push(`[ERROR] Root catalog not found in object cache at ${s}`),{pages:i,logs:r};let l=a;r.push("[CATALOG] \u2713 Found catalog in cache");let c=l.entries.get("Pages");if(!c)return r.push("[ERROR] /Pages reference not found in catalog"),{pages:i,logs:r};if(!$e(c))return r.push("[ERROR] /Pages is not an indirect reference"),{pages:i,logs:r};let d=c;r.push(`[PAGES] Pages tree root: ${d.objNum} ${d.genNum} R`);let h=`${d.objNum}.${d.genNum}`,f=e.objectCache.get(h);if((!f||!Q(f))&&n.objectLoader)try{f=n.objectLoader(d),r.push("[PAGES] Loaded pages tree root from file")}catch(p){let b=p instanceof Error?p.message:String(p);r.push(`[WARN] Failed to load pages tree root: ${b}`)}if(!f||!Q(f))return r.push(`[ERROR] Pages tree object not in cache at ${h}`),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:i,logs:r};let m=f;return r.push("[PAGES] \u2713 Found pages tree root"),this.walkPageTree(m,d,e,i,r,n,1,new Set([h]),0),r.push(`[TRAVERSE] \u2713 Complete. Found ${i.length} page(s)`),{pages:i,logs:r}}catch(o){let s=o instanceof Error?o.message:String(o);return r.push(`[ERROR] Traversal failed: ${s}`),{pages:i,logs:r}}}static walkPageTree(e,n,r,i,o,s,a,l,c){if(c>$c)return o.push(`[WARN] Page tree too deep (>${$c}) at ${n.objNum} ${n.genNum} R \u2014 stopping`),a;let d=e.entries.get("Type"),h=this.extractName(d);if(h==="Pages"){let f=e.entries.get("Kids");if(!f)return o.push(`[WARN] Pages node has no /Kids at ${n.objNum} ${n.genNum} R`),a;let m=this.extractArray(f);if(!m)return o.push("[WARN] /Kids is not an array"),a;o.push(`[NODE] Pages node with ${m.length} child(ren) at ${n.objNum}`);for(let p of m){if(!$e(p)){o.push("[WARN] /Kids contains non-reference");continue}let b=p,y=`${b.objNum}.${b.genNum}`;if(l.has(y)){o.push(`[WARN] Cycle detected in page tree at ${y} \u2014 skipping`);continue}l.add(y);let k=r.objectCache.get(y);if((!k||!Q(k))&&s.objectLoader)try{k=s.objectLoader(b),o.push(`[NODE] Loaded child page node ${b.objNum} ${b.genNum} R from file`)}catch(w){let P=w instanceof Error?w.message:String(w);o.push(`[WARN] Failed to load child node: ${P}`)}if(!k||!Q(k)){o.push(`[SKIP] Child page node not in cache: ${b.objNum} ${b.genNum} R`),o.push("[NOTE] Would need ObjectReader to load from file");continue}if(a=this.walkPageTree(k,b,r,i,o,s,a,l,c+1),s.maxPages&&i.length>=s.maxPages)return a}return a}else if(h==="Page"){o.push(`[PAGE ${a}] Found at ${n.objNum} ${n.genNum} R`);let f=this.extractContentStreams(e,r,o,s);o.push(`[PAGE ${a}] \u2713 Found ${f.length} stream(s)`);let m=this.extractMediaBox(e),p=this.extractResources(e,r,o,s),b=this.extractNumber(e.entries.get("Rotate"));return i.push({pageNum:a,ref:n,dict:e,contentStreams:f,mediaBox:m||[0,0,612,792],resources:p,rotate:b||0}),a+1}else return o.push(`[WARN] Unknown node type: ${h}`),a}static extractContentStreams(e,n,r,i){let o=[];try{let s=e.entries.get("Contents");if(!s)return r.push("[WARN] Page has no /Contents"),o;if(he(s))o.push(s);else if($e(s)){let a=s,l=`${a.objNum}.${a.genNum}`,c=n.objectCache.get(l);if((!c||!he(c))&&i.objectLoader)try{c=i.objectLoader(a),r.push(`[STREAM] Loaded content stream ${a.objNum} ${a.genNum} R from file`)}catch(d){let h=d instanceof Error?d.message:String(d);r.push(`[WARN] Failed to load content stream ${a.objNum} ${a.genNum} R: ${h}`)}c&&he(c)?o.push(c):r.push(`[STREAM] Content stream reference not cached: ${a.objNum} ${a.genNum} R`)}else if(ue(s)){let a=this.extractArray(s);if(a){for(let l of a)if(he(l))o.push(l);else if($e(l)){let c=l,d=`${c.objNum}.${c.genNum}`,h=n.objectCache.get(d);if((!h||!he(h))&&i.objectLoader)try{h=i.objectLoader(c),r.push(`[STREAM] Loaded content stream ${c.objNum} ${c.genNum} R from file`)}catch(f){let m=f instanceof Error?f.message:String(f);r.push(`[WARN] Failed to load content stream ${c.objNum} ${c.genNum} R: ${m}`)}h&&he(h)?o.push(h):r.push(`[STREAM] Content stream reference not cached: ${c.objNum} ${c.genNum} R`)}}}}catch(s){r.push(`[ERROR] Failed to extract content streams: ${s instanceof Error?s.message:String(s)}`)}return o}static extractMediaBox(e){let n=e.entries.get("MediaBox");if(n&&ue(n)){let r=this.extractArray(n);if(r&&r.length>=4){let i=r.slice(0,4).map(o=>this.extractNumber(o));if(i.every(o=>o!==null))return i}}return null}static extractResources(e,n,r,i){let o=e.entries.get("Resources");if(o&&Q(o))return o;if(o&&$e(o)){let s=o,a=`${s.objNum}.${s.genNum}`,l=n.objectCache.get(a);if((!l||!Q(l))&&i.objectLoader)try{l=i.objectLoader(s),r.push(`[RESOURCES] Loaded resources ${s.objNum} ${s.genNum} R from file`)}catch(c){let d=c instanceof Error?c.message:String(c);r.push(`[WARN] Failed to load resources ${s.objNum} ${s.genNum} R: ${d}`)}if(l&&Q(l))return l;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 V(e)}};var _c=new Set(["show_string","show_strings","next_line_show_string"]),zc=t=>t==="show_string"?"() Tj":t==="show_strings"?"[] TJ":"() '",Xc=(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 hs(t,e){let n=new ln(t),r=n.parse(),o=fr.getAllPages(r,{objectLoader:f=>n.loadObject(f)}).pages[e];if(!o)throw new Error(`Page ${e+1} not found`);let s=jr(o.dict.entries.get("Contents"));if(s.length===0)throw new Error("Page has no content streams");let a=[];for(let f of s){let m=n.loadObject(f);if(!he(m))continue;let p=m.decode?await m.decode():await Pe.decodeStream(m);a.push({objNum:f.objNum,genNum:f.genNum,bytes:p})}if(a.length===0)throw new Error("Page content streams could not be decoded");let l=a.reduce((f,m)=>f+m.bytes.length,0)+Math.max(0,a.length-1),c=new Uint8Array(l),d=[],h=0;for(let f=0;f<a.length;f++)c.set(a[f].bytes,h),d.push({start:h,end:h+a[f].bytes.length}),h+=a[f].bytes.length,f<a.length-1&&(c[h]=32,h+=1);return{chunks:a,pristine:c,chunkSpans:d}}var Yc=(t,e)=>t.chunks.map((n,r)=>{let i=new Uint8Array(e.subarray(t.chunkSpans[r].start,t.chunkSpans[r].end));return{objNum:n.objNum,genNum:n.genNum,bytes:i,changed:!Xc(i,n.bytes)}});async function Wc(t,e,n,r){let i=await hs(t,e);if(r&&r.length!==i.pristine.length)throw new Error("Stale rewrite state for page");let{commands:o,ranges:s}=ur(i.pristine),a=new Uint8Array(r!=null?r:i.pristine);for(let l of n){let c=o[l],d=s[l];if(!c||!d)throw new Error(`No operator at index ${l}`);if(!_c.has(c.op))throw new Error(`Operator ${c.op} at index ${l} is not rewritable`);if(!i.chunkSpans.some(m=>d.start>=m.start&&d.end<=m.end))throw new Error(`Operator at index ${l} spans multiple content streams`);let f=zc(c.op);if(d.end-d.start<f.length)throw new Error(`Operator span too small at index ${l}`);a.fill(32,d.start,d.end);for(let m=0;m<f.length;m++)a[d.start+m]=f.charCodeAt(m)}return{streams:Yc(i,a),combined:a}}var Hh=t=>{let e=t.toFixed(6).replace(/\.?0+$/,"");return e===""||e==="-"?"0":e};async function Hc(t,e,n,r,i){var w;let o=await hs(t,e);if(i&&i.length!==o.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}=ur(o.pristine);if(n.start<0||n.end<n.start||n.end>=s.length)throw new Error(`Invalid operator span ${n.start}..${n.end}`);let l=0;for(let P=n.start;P<=n.end;P++){let S=(w=s[P])==null?void 0:w.op;if(S==="save_state")l+=1;else if(S==="restore_state"&&(l-=1,l<0))throw new Error("Span restores state it did not save")}if(l!==0)throw new Error("Span has unbalanced q/Q");let c=a[n.start].start,d=a[n.end].end,h=o.chunkSpans.findIndex(P=>c>=P.start&&d<=P.end);if(h<0)throw new Error("Span crosses content-stream chunk boundaries");let f=i!=null?i:o.pristine,m=new TextEncoder().encode(`
|
|
3
|
+
q ${r.map(Hh).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
|
+
`),b=new Uint8Array(f.length+m.length+p.length);b.set(f.subarray(0,c),0),b.set(m,c),b.set(f.subarray(c,d),c+m.length),b.set(p,c+m.length+(d-c)),b.set(f.subarray(d),c+m.length+(d-c)+p.length);let y=m.length+p.length;return{streams:o.chunks.map((P,S)=>{let R=o.chunkSpans[S].start,I=o.chunkSpans[S].end;S===h?I+=y:S>h&&(R+=y,I+=y);let F=new Uint8Array(b.subarray(R,I));return{objNum:P.objNum,genNum:P.genNum,bytes:F,changed:!Xc(F,P.bytes)}}),combined:b,lengthChanged:!0}}var Gh=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 Gc(t,e,n,r){let i=await hs(t,e);if(r&&r.length!==i.pristine.length)throw new Error("Stale rewrite state for page");let{commands:o,ranges:s}=ur(i.pristine),a=new Uint8Array(r!=null?r:i.pristine),l=c=>{let d=s[c];if(!i.chunkSpans.some(f=>d.start>=f.start&&d.end<=f.end))throw new Error(`Operator at index ${c} spans multiple content streams`);a.fill(32,d.start,d.end)};for(let c of n){if(c.start<0||c.end<c.start||c.end>=o.length)throw new Error(`Invalid operator span ${c.start}..${c.end}`);let d=0;for(let h=c.start;h<=c.end;h++){let f=o[h],m=s[h];if(!f||!m)throw new Error(`No operator at index ${h}`);if(f.op==="save_state"){d+=1;continue}if(f.op==="restore_state"){d-=1;continue}if(!Gh.has(f.op)){if(f.op==="clip"||f.op==="clip_even_odd"){if(d<=0)throw new Error("Span contains a clip that outlives it");l(h);continue}if(f.op==="set_spacing_next_line_show_string")throw new Error('Span contains a " operator (spacing side effects)');if(_c.has(f.op)){let p=zc(f.op);if(m.end-m.start<p.length)throw new Error(`Operator span too small at index ${h}`);l(h);for(let b=0;b<p.length;b++)a[m.start+b]=p.charCodeAt(b);continue}l(h)}}}return{streams:Yc(i,a),combined:a}}var Vc=["view","annotate"],Kc=["view","annotate","edit-text","sign","redact","forms","export-clean"];import{ed25519 as Vh}from"@noble/curves/ed25519";var qc="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",Lr={};for(let t=0;t<qc.length;t++)Lr[qc[t]]=t;function Zc(t){return new TextDecoder().decode(t)}function Qc(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 Jc(t){let e=[];for(let n=0;n<t.length;n+=4){let r=Lr[t[n]],i=Lr[t[n+1]];if(r===void 0||i===void 0)break;e.push(r<<2|i>>4);let o=Lr[t[n+2]];if(o===void 0)break;e.push((i&15)<<4|o>>2);let s=Lr[t[n+3]];if(s===void 0)break;e.push((o&3)<<6|s)}return new Uint8Array(e)}function el(t,e){let n=t.indexOf(".");if(n<0)return null;try{let r=Jc(t.slice(0,n)),i=Jc(t.slice(n+1));return Vh.verify(i,r,e)?r:null}catch{return null}}var Ur="bde297640169e8f75d2d9bd260e8eab78aa93c39e10c84a8f6abe565a19057e3";function tl(t,e){if(!t||/^0+$/.test(e))return null;let n=el(t,Qc(e));if(!n)return null;try{return JSON.parse(Zc(n))}catch{return null}}function Ei(t,e=Ur){let n=tl(t,e);return!n||typeof n.lid!="string"||!Array.isArray(n.features)?null:n}function Oi(t,e=Ur){let n=tl(t,e);return!n||typeof n.lid!="string"||!Array.isArray(n.features)?null:n}function ms(t,e){return t===0||t*1e3>e}function nl(t,e){if(!e||e==="localhost"||e==="127.0.0.1"||e==="::1")return!0;let n=e.toLowerCase();return t.some(r=>{let i=r.trim().toLowerCase();return i==="*"||i===n?!0:n.endsWith("."+i)})}var ps="NamahaPDF \xB7 Unlicensed SDK";function gs(t,e,n,r=ps){t.save(),t.globalAlpha=.16,t.fillStyle="#C20E3A";let i=Math.max(14,Math.round(Math.min(e,n)/22));t.font=`600 ${i}px Inter, system-ui, sans-serif`,t.textAlign="center",t.textBaseline="middle";let o=i*9;t.translate(e/2,n/2),t.rotate(-28*Math.PI/180);for(let s=-n;s<n;s+=o*.5)for(let a=-e;a<e;a+=o)t.fillText(r,a,s);t.restore()}async function xs(t,e=ps){try{let{PDFDocument:n,StandardFonts:r,rgb:i,degrees:o}=await import("pdf-lib"),s=await n.load(t,{ignoreEncryption:!0}),a=await s.embedFont(r.HelveticaBold),l=i(.76,.055,.227);for(let c of s.getPages()){let{width:d,height:h}=c.getSize(),f=Math.max(16,Math.min(d,h)/26),m=f*6,p=a.widthOfTextAtSize(e,f)+f*4;for(let b=-h;b<h*2;b+=m)for(let y=-d;y<d*2;y+=p)c.drawText(e,{x:y,y:b,size:f,font:a,color:l,opacity:.14,rotate:o(28)})}return await s.save()}catch{return t}}var il=5,Kh=4320*60*1e3,qh=4320*60*1e3,Jh="/api/license/activate",Le={publicKeyHex:Ur,now:()=>Date.now()},vt=null,Ii=[];function Zh(){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 Qh(t){if(t.storage)return t.storage;try{if(typeof localStorage!="undefined")return localStorage}catch{}return Zh()}function ol(t){if(t.host)return t.host;try{if(typeof location!="undefined")return location.hostname}catch{}return""}function sl(t){return`namaha.lic.${t}`}function al(t){try{let e=vt==null?void 0:vt.getItem(sl(t));if(e)return JSON.parse(e)}catch{}return{failCount:0,firstSeen:Le.now(),lastAttempt:0}}function ys(t,e){try{vt==null||vt.setItem(sl(t),JSON.stringify(e))}catch{}}function em(){if(Le.deviceId)return Le.deviceId;let t="namaha.lic.device";try{let n=vt==null?void 0:vt.getItem(t);if(n)return n}catch{}let e="dev_"+Math.random().toString(36).slice(2)+Date.now().toString(36);try{vt==null||vt.setItem(t,e)}catch{}return e}function $n(){let t=Le.now();if(Le.owner)return{status:"LICENSED",edition:"enterprise",features:Kc,watermark:!1,reason:"owner"};if(!Le.licenseKey)return l("UNLICENSED","no key");let e=Ei(Le.licenseKey,Le.publicKeyHex);if(!e)return l("INVALID","bad signature");if(!ms(e.exp,t))return l("INVALID","key expired");if(!nl(e.domains,ol(Le)))return l("INVALID","domain not allowed");let n=al(e.lid);if(n.revoked)return l("DEGRADED","revoked");let r=n.token?Oi(n.token,Le.publicKeyHex):null;if(r&&r.lid===e.lid&&ms(r.exp,t))return c("LICENSED",r.edition,r.features,"active token");let i=r?r.exp*1e3:n.firstSeen,o=r?qh:Kh,s=t-i<o,a=n.failCount<il;if(s||a)return c("GRACE",e.edition,e.features,"grace");return l("DEGRADED","grace exhausted");function l(d,h){return{status:d,edition:null,features:Vc.slice(),watermark:!0,reason:h}}function c(d,h,f,m){return{status:d,edition:h,features:f.slice(),watermark:!1,reason:m}}}function ws(){let t=$n();for(let e of Ii)try{e(t)}catch{}}async function tm(){var s,a;if(Le.owner||!Le.licenseKey)return;let t=Ei(Le.licenseKey,Le.publicKeyHex);if(!t)return;let e=(s=Le.activationUrl)!=null?s:Jh,n=(a=Le.fetchImpl)!=null?a:typeof fetch!="undefined"?fetch:null;if(!n)return;let r=ol(Le),i=em(),o=al(t.lid);try{let l=await n(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({licenseKey:Le.licenseKey,origin:r,deviceId:i})}),c=await l.json().catch(()=>({}));if(c.status==="revoked"||c.status==="invalid"){ys(t.lid,{...o,revoked:!0,lastAttempt:Le.now()}),ws();return}if(l.ok&&c.status==="active"&&c.token&&Oi(c.token,Le.publicKeyHex)){ys(t.lid,{...o,token:c.token,failCount:0,lastAttempt:Le.now(),revoked:!1}),ws();return}rl(t.lid,o)}catch{rl(t.lid,o)}}function rl(t,e){ys(t,{...e,failCount:Math.min(il,e.failCount+1),lastAttempt:Le.now()}),ws()}function vs(t={}){Le={publicKeyHex:Ur,now:()=>Date.now(),...t},vt=Qh(t);let e=$n();return nm(),e}var bs=!1;async function nm(){var e;if(bs||Le.owner||!Le.licenseKey)return;bs=!0;let t=(e=Le.retryDelays)!=null?e:[0,2e3,6e3,2e4];try{for(let n=0;n<t.length;n++){t[n]>0&&await rm(t[n]);let r=$n();if(r.status==="LICENSED"&&r.reason==="active token"||r.status==="DEGRADED"||r.status==="INVALID"||r.status==="UNLICENSED")break;await tm();let i=$n();if(i.status==="LICENSED"||i.status==="DEGRADED")break}}finally{bs=!1}}function rm(t){return new Promise(e=>setTimeout(e,t))}function im(){return $n()}function cl(t){return $n().features.includes(t)}function ll(t){if(!cl(t))throw new Error(`NamahaPDF: feature "${t}" requires a license. See namahapdf.com/sdk.`)}function Bi(){return $n().watermark}function om(t){return Ii.push(t),()=>{Ii=Ii.filter(e=>e!==t)}}import{PDFName as pl,PDFString as kn}from"pdf-lib";var Ps=t=>t.kind==="highlight"||t.kind==="underline"||t.kind==="strikeout"||t.kind==="squiggly",sm=t=>t.kind==="rect"||t.kind==="ellipse"||t.kind==="line"||t.kind==="arrow"||t.kind==="polygon"||t.kind==="polyline",ks=t=>{let e=t.map(o=>o.x),n=t.map(o=>o.y),r=Math.min(...e),i=Math.min(...n);return{x:r,y:i,width:Math.max(...e)-r,height:Math.max(...n)-i}},ht=t=>{if(Ps(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?ks(e):{x:0,y:0,width:0,height:0}}if(t.kind==="ink"){let e=t.strokes.flat();return e.length?ks(e):{x:0,y:0,width:0,height:0}}return t.kind==="note"||t.kind==="freetext"?{...t.rect}:ks(t.points)},am=(t,e,n,r)=>t>=n.x-r&&t<=n.x+n.width+r&&e>=n.y-r&&e<=n.y+n.height+r,dl=(t,e,n)=>{let r=n.x-e.x,i=n.y-e.y,o=r*r+i*i;if(o===0)return Math.hypot(t.x-e.x,t.y-e.y);let s=((t.x-e.x)*r+(t.y-e.y)*i)/o;return s=Math.max(0,Math.min(1,s)),Math.hypot(t.x-(e.x+s*r),t.y-(e.y+s*i))},fl=(t,e,n=4)=>{var i;let r=Math.max(n,((i=e.style.strokeWidth)!=null?i:0)/2+2);if((e.kind==="line"||e.kind==="arrow"||e.kind==="polyline")&&sm(e)){for(let o=0;o<e.points.length-1;o++)if(dl(t,e.points[o],e.points[o+1])<=r)return!0;return!1}if(e.kind==="ink"){for(let o of e.strokes){for(let s=0;s<o.length-1;s++)if(dl(t,o[s],o[s+1])<=r)return!0;if(o.length===1&&Math.hypot(t.x-o[0].x,t.y-o[0].y)<=r)return!0}return!1}return am(t.x,t.y,ht(e),n)},hl=(t,e,n)=>{if(Ps(t))return{...t,quads:t.quads.map(i=>({...i,x:i.x+e,y:i.y+n,baselineY:i.baselineY+n}))};if(t.kind==="ink")return{...t,strokes:t.strokes.map(i=>i.map(o=>({x:o.x+e,y:o.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(i=>({x:i.x+e,y:i.y+n}))}},ul=(t,e,n,r,i)=>n<=0?r:r+(t-e)/n*i,ml=(t,e)=>{let n=ht(t),r=s=>ul(s,n.x,n.width,e.x,e.width),i=s=>ul(s,n.y,n.height,e.y,e.height);if(Ps(t))return{...t,quads:t.quads.map(s=>{let a=r(s.x),l=i(s.y);return{x:a,y:l,width:r(s.x+s.width)-a,height:i(s.y+s.height)-l,baselineY:i(s.baselineY)}})};if(t.kind==="ink")return{...t,strokes:t.strokes.map(s=>s.map(a=>({x:r(a.x),y:i(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 o=t;return{...o,points:o.points.map(s=>({x:r(s.x),y:i(s.y)}))}};var $r=1.5,se=t=>{let e=Math.round(t*1e3)/1e3;return Object.is(e,-0)?"0":String(e)},_n=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))],gl=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())}`},bl=(t,e)=>({x:t.x-e,y:t.y-e,width:t.width+e*2,height:t.height+e*2}),xl=t=>[t.x,t.y,t.x+t.width,t.y+t.height],hr=t=>{var o;let[e,n,r]=_n(t.color),i=(o=t.strokeWidth)!=null?o:$r;return`${se(i)} w 1 J 1 j ${se(e)} ${se(n)} ${se(r)} RG`},ji=t=>{let[e,n,r]=_n(t);return`${se(e)} ${se(n)} ${se(r)} rg`},Ds=t=>{var r;let e=!!t.fill,n=((r=t.strokeWidth)!=null?r:$r)>0;return e&&n?"B":e?"f":"S"},cm=t=>{let n=t.x+t.width/2,r=t.y+t.height/2,i=t.width/2,o=t.height/2;return[`${se(n+i)} ${se(r)} m`,`${se(n+i)} ${se(r+o*.5523)} ${se(n+i*.5523)} ${se(r+o)} ${se(n)} ${se(r+o)} c`,`${se(n-i*.5523)} ${se(r+o)} ${se(n-i)} ${se(r+o*.5523)} ${se(n-i)} ${se(r)} c`,`${se(n-i)} ${se(r-o*.5523)} ${se(n-i*.5523)} ${se(r-o)} ${se(n)} ${se(r-o)} c`,`${se(n+i*.5523)} ${se(r-o)} ${se(n+i)} ${se(r-o*.5523)} ${se(n+i)} ${se(r)} c`].join(`
|
|
7
|
+
`)},Ss=(t,e)=>{let n=t.map((r,i)=>`${se(r.x)} ${se(r.y)} ${i===0?"m":"l"}`);return e&&n.push("h"),n.join(`
|
|
8
|
+
`)},lm=(t,e,n)=>{let r=Math.atan2(e.y-t.y,e.x-t.x),i=Math.PI/7,o={x:e.x-n*Math.cos(r-i),y:e.y-n*Math.sin(r-i)},s={x:e.x-n*Math.cos(r+i),y:e.y-n*Math.sin(r+i)};return`${se(o.x)} ${se(o.y)} m ${se(e.x)} ${se(e.y)} l ${se(s.x)} ${se(s.y)} l S`},dm=(t,e)=>{let i=[`${se(t.x)} ${se(e)} m`],o=!0;for(let s=t.x+4;s<=t.x+t.width;s+=4)i.push(`${se(s)} ${se(o?e+1.5:e-1.5)} l`),o=!o;return`${i.join(`
|
|
9
9
|
`)}
|
|
10
|
-
S`},
|
|
10
|
+
S`},um=t=>{var s,a,l;let e=Math.max((s=t.style.strokeWidth)!=null?s:$r,2)+1,n=bl(ht(t),e);if(t.kind==="highlight"){let c=t.quads.map(d=>`${se(d.x)} ${se(d.y)} ${se(d.width)} ${se(d.height)} re`).join(`
|
|
11
11
|
`);return{content:`/GS0 gs
|
|
12
|
-
${
|
|
13
|
-
${
|
|
14
|
-
f`,bbox:n,multiply:!0}}if(t.kind==="underline"||t.kind==="strikeout"||t.kind==="squiggly"){let
|
|
15
|
-
`),[
|
|
16
|
-
${d}`,bbox:n,multiply:!1}}if(t.kind==="ink"){let
|
|
12
|
+
${ji(t.style.color)}
|
|
13
|
+
${c}
|
|
14
|
+
f`,bbox:n,multiply:!0}}if(t.kind==="underline"||t.kind==="strikeout"||t.kind==="squiggly"){let c=Math.max(.75,(a=t.style.strokeWidth)!=null?a:1),d=t.quads.map(p=>{let b=t.kind==="strikeout"?p.y+p.height*.5:p.baselineY-Math.max(1,p.height*.12);return t.kind==="squiggly"?dm(p,p.y+1):`${se(p.x)} ${se(b)} m ${se(p.x+p.width)} ${se(b)} l S`}).join(`
|
|
15
|
+
`),[h,f,m]=_n(t.style.color);return{content:`${se(c)} w ${se(h)} ${se(f)} ${se(m)} RG
|
|
16
|
+
${d}`,bbox:n,multiply:!1}}if(t.kind==="ink"){let c=t.strokes.map(d=>Ss(d,!1)+`
|
|
17
17
|
S`).join(`
|
|
18
|
-
`);return{content:`${
|
|
19
|
-
${
|
|
20
|
-
`:"")+
|
|
18
|
+
`);return{content:`${hr(t.style)}
|
|
19
|
+
${c}`,bbox:n,multiply:!1}}if(t.kind==="rect"){let c=ht(t),d=`${se(c.x)} ${se(c.y)} ${se(c.width)} ${se(c.height)} re`;return{content:`${(t.style.fill?ji(t.style.fill)+`
|
|
20
|
+
`:"")+hr(t.style)}
|
|
21
21
|
${d}
|
|
22
|
-
${
|
|
23
|
-
`:"")+
|
|
24
|
-
${
|
|
25
|
-
${
|
|
26
|
-
`:"")+
|
|
27
|
-
${
|
|
28
|
-
${
|
|
29
|
-
${
|
|
30
|
-
S`,bbox:n,multiply:!1};let[r,
|
|
31
|
-
${
|
|
32
|
-
${
|
|
22
|
+
${Ds(t.style)}`,bbox:n,multiply:!1}}if(t.kind==="ellipse")return{content:`${(t.style.fill?ji(t.style.fill)+`
|
|
23
|
+
`:"")+hr(t.style)}
|
|
24
|
+
${cm(ht(t))}
|
|
25
|
+
${Ds(t.style)}`,bbox:n,multiply:!1};if(t.kind==="polygon")return{content:`${(t.style.fill?ji(t.style.fill)+`
|
|
26
|
+
`:"")+hr(t.style)}
|
|
27
|
+
${Ss(t.points,!0)}
|
|
28
|
+
${Ds(t.style)}`,bbox:n,multiply:!1};if(t.kind==="polyline")return{content:`${hr(t.style)}
|
|
29
|
+
${Ss(t.points,!1)}
|
|
30
|
+
S`,bbox:n,multiply:!1};let[r,i]=t.points,o=`${hr(t.style)}
|
|
31
|
+
${se(r.x)} ${se(r.y)} m ${se(i.x)} ${se(i.y)} l S`;if(t.kind==="arrow"){let c=Math.max(8,((l=t.style.strokeWidth)!=null?l:$r)*4);o+=`
|
|
32
|
+
${lm(r,i,c)}`}return{content:o,bbox:n,multiply:!1}},fm=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],hm=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},yl=(t,e)=>{var l,c,d;let n=t.getPageCount();if(e.pageIndex<0||e.pageIndex>=n)return;let r=t.getPage(e.pageIndex),i=t.context,o=ht(e),s={Type:"Annot",Subtype:fm(e),Rect:xl(bl(o,Math.max((l=e.style.strokeWidth)!=null?l:$r,2)+1)),C:_n(e.style.color),CA:e.style.opacity,F:4,NM:kn.of(e.id),M:kn.of(gl(e.createdAt)),CreationDate:kn.of(gl(e.createdAt))};if(e.author&&(s.T=kn.of(e.author)),e.kind==="highlight"||e.kind==="underline"||e.kind==="strikeout"||e.kind==="squiggly")s.QuadPoints=hm(e.quads),e.text&&(s.Contents=kn.of(e.text));else if(e.kind==="line"||e.kind==="arrow"){let[h,f]=e.points;s.L=[h.x,h.y,f.x,f.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(h=>[h.x,h.y]),e.style.fill&&(s.IC=_n(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=_n(e.style.fill)),e.style.strokeWidth&&(s.BS={W:e.style.strokeWidth,S:"S"});else if(e.kind==="ink")s.InkList=e.strokes.map(h=>h.flatMap(f=>[f.x,f.y])),e.style.strokeWidth&&(s.BS={W:e.style.strokeWidth,S:"S"});else if(e.kind==="note")s.Contents=kn.of((c=e.text)!=null?c:""),s.Name="Comment",s.Open=!1;else if(e.kind==="freetext"){s.Contents=kn.of((d=e.text)!=null?d:"");let[h,f,m]=_n(e.style.color);s.DA=kn.of(`${se(h)} ${se(f)} ${se(m)} rg /Helv 12 Tf`),s.Q=0}if(e.kind!=="note"){let{content:h,bbox:f,multiply:m}=um(e),p={Type:"XObject",Subtype:"Form",FormType:1,BBox:xl(f),Resources:m?{ExtGState:{GS0:{Type:"ExtGState",BM:"Multiply",ca:1,CA:1}}}:{}},b=i.stream(h,p),y=i.register(b);s.AP={N:y}}let a=i.register(i.obj(s));r.node.addAnnot(a),r.node.get(pl.of("Annots"))||r.node.set(pl.of("Annots"),i.obj([a]))};var Ce=(t,e)=>{let[n,r,i,o,s,a]=t,[l,c,d,h,f,m]=e;return[n*l+i*c,r*l+o*c,n*d+i*h,r*d+o*h,n*f+i*m+s,r*f+o*m+a]};var mr=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,i=-t[2]/e,o=t[0]/e;return[n,r,i,o,-(n*t[4]+i*t[5]),-(r*t[4]+o*t[5])]};var pm={left:Rs.Left,center:Rs.Center,right:Rs.Right},gm={"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"},zr=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))}),xm=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?mt.TimesRomanBoldItalic:n?mt.TimesRomanBold:r?mt.TimesRomanItalic:mt.TimesRoman:e.includes("courier")?n&&r?mt.CourierBoldOblique:n?mt.CourierBold:r?mt.CourierOblique:mt.Courier:n&&r?mt.HelveticaBoldOblique:n?mt.HelveticaBold:r?mt.HelveticaOblique:mt.Helvetica},Li=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},bm=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
|
-
`&&
|
|
36
|
-
`||a===" "||r.has(s)){
|
|
37
|
-
`||r.has(d))){
|
|
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"]]),kl=t=>(t!=null?t:"").replace(/^[A-Z]{6}\+/,"").replace(/[#,\s]/g,"").toLowerCase(),Ms=t=>!t||typeof t!="object"||!("type"in t)?null:t.type==="name"?t.value:null,zn=(t,e)=>{if(t){if(!$e(t))return t;try{return e(t)}catch{return}}},ym=t=>{if(!(!t||!ue(t)))return t.items[0]},wl={liga:!1,dlig:!1,clig:!1,hlig:!1,calt:!1},wm=(t,e)=>{let n=zn(t.entries.get("FontDescriptor"),e);if(n&&Q(n))return n;let r=zn(t.entries.get("DescendantFonts"),e),i=zn(ym(r),e);if(i&&Q(i)){let o=zn(i.entries.get("FontDescriptor"),e);if(o&&Q(o))return o}},vm=t=>{var a,l,c,d,h,f,m,p;let e=new ln(t),r=e.parse().xrefTables.get(0);if(!r)return[];let i=[],o=new Set,s=b=>e.loadObject(b);for(let[b,y]of r.entries()){if(!y.inUse)continue;let k;try{k=s({type:"ref",objNum:b,genNum:y.genNum})}catch{continue}if(!Q(k))continue;let w=Ms(k.entries.get("Subtype"));if(!w||!["Type1","TrueType","Type0","CIDFontType0","CIDFontType2"].includes(w))continue;let P=wm(k,s);if(!P)continue;let S=(l=(a=zn(P.entries.get("FontFile2"),s))!=null?a:zn(P.entries.get("FontFile3"),s))!=null?l:zn(P.entries.get("FontFile"),s);if(!S||!he(S))continue;let R=(d=(c=Ms(k.entries.get("BaseFont")))!=null?c:Ms(P.entries.get("FontName")))!=null?d:`Font${b}`,I=kl(R),F=`${I}:${(p=(m=(h=S.rawBytes)==null?void 0:h.length)!=null?m:(f=S.data)==null?void 0:f.length)!=null?p:0}`;if(!o.has(F))try{let A=Pe.decodeStreamSync(S);if(A.length===0)continue;i.push({baseName:R,normalizedName:I,bytes:A}),o.add(F)}catch{continue}}return i},vl=(t,e,n,r)=>{let i=Math.max(0,t.x-e),o=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:i,y:o,width:Math.max(0,s-i),height:Math.max(0,a-o)}},Ui=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),i=await Cs.load(r,{ignoreEncryption:!0});return new t(i,r)}static async fromBytes(e){let n=e instanceof Uint8Array?e:new Uint8Array(e),r=await Cs.load(n,{ignoreEncryption:!0});return new t(r,n)}getPageCount(){return this.pdfDoc.getPageCount()}async applyOperations(e){var r,i,o,s,a,l,c,d,h,f,m,p,b,y,k,w,P,S,R,I,F,A,G,Y;if(e.length===0)return;for(let E of e)ll(gm[E.type]);let n=await this.getStandardFont(mt.Helvetica);for(let E of e){if(E.type==="create-form-field"||E.type==="set-form-values"||E.type==="delete-form-field"||E.type==="flatten-form")continue;if(E.type==="delete-page"){this.deletePage(E.pageIndex);continue}if(E.type==="delete-object"){if(!await this.tryNeutralizeSpans(E.pageIndex,E.spans))throw new Error("This object cannot be deleted safely.");continue}if(E.type==="transform-object"){if(!await this.tryWrapSpanWithTransform(E))throw new Error("This object cannot be moved safely.");continue}if(E.type==="add-annotation"){yl(this.pdfDoc,E.annotation);continue}let ee=this.pdfDoc.getPage(E.pageIndex);if(E.type==="insert-image"){let ne=await this.getEmbeddedImage(E.bytes,E.format);ee.drawImage(ne,{x:E.x,y:E.y,width:E.width,height:E.height});continue}if(E.type==="insert-text"){if((r=E.spans)!=null&&r.length){await this.drawStyledSpans(ee,E.spans,E.x,E.y,(i=E.size)!=null?i:14,E.fontName);continue}let ne=zr((o=E.color)!=null?o:{r:0,g:0,b:0}),O=this.fitTextToFont(n,E.text);if(O.length===0)continue;this.safeDrawText(ee,O,{x:E.x,y:E.y,size:(s=E.size)!=null?s:14,font:n,color:_r(ne.r,ne.g,ne.b)},n);continue}if(E.type==="redact-area"){let ne=zr((a=E.color)!=null?a:{r:1,g:1,b:1}),{width:O,height:ge}=ee.getSize();(c=(l=E.removeOperators)==null?void 0:l.streamOperatorIndices)!=null&&c.length&&await this.tryRemoveTextOperators(E.pageIndex,E.removeOperators.streamOperatorIndices);let fe=vl({x:E.x,y:E.y,width:E.width,height:E.height},(d=E.padding)!=null?d:1.75,O,ge);ee.drawRectangle({x:fe.x,y:fe.y,width:fe.width,height:fe.height,color:_r(ne.r,ne.g,ne.b)});continue}if(E.type==="replace-text"){let ne=zr((h=E.backgroundColor)!=null?h:{r:1,g:1,b:1}),O=zr((p=(m=E.color)!=null?m:(f=E.font)==null?void 0:f.color)!=null?p:{r:0,g:0,b:0}),ge=(b=E.font)!=null&&b.pdfName?await this.getRenderableFont(E.font.pdfName,E.newText):{font:n,substituted:!0},fe=ge.font,Oe=Uc((y=E.font)==null?void 0:y.capHeight,(k=E.font)==null?void 0:k.pdfName),Te=(S=(P=E.size)!=null?P:(w=E.font)==null?void 0:w.sizePt)!=null?S:Math.max(8,E.height*.8),_=Te*(ge.substituted?Oe:1),ce=this.fitTextToFont(fe,E.newText),{width:ae,height:W}=ee.getSize(),me=ce.trim().length>0?this.safeWidth(fe,ce,_):0;if(!((I=(R=E.removeOperators)==null?void 0:R.streamOperatorIndices)!=null&&I.length?await this.tryRemoveTextOperators(E.pageIndex,E.removeOperators.streamOperatorIndices):!1)){let Ie=Math.min(ae-E.x,Math.max(E.width,me+_*.25)),Me=vl({x:E.x,y:E.y,width:Ie,height:E.height},(F=E.erasePadding)!=null?F:1.75,ae,W);E.eraseClamp&&(Me=Ti(Me,E.eraseClamp)),ee.drawRectangle({x:Me.x,y:Me.y,width:Me.width,height:Me.height,color:_r(ne.r,ne.g,ne.b)})}let be=(A=E.baselineY)!=null?A:E.y+Math.max(0,(E.height-_)/2);if((G=E.spans)!=null&&G.length){await this.drawStyledSpans(ee,E.spans,E.x,be,Te*Oe,(Y=E.font)==null?void 0:Y.pdfName,Oe);continue}if(ce.length===0)continue;this.safeDrawText(ee,ce,{x:E.x,y:be,size:_,font:fe,color:_r(O.r,O.g,O.b)},n);continue}if(E.type==="rotate-page"){let ne=ee.getRotation().angle;ee.setRotation(mm(ne+E.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 i=this.pdfDoc.getForm(),o=!1,s=!1;for(let a of r)if(a.type==="create-form-field")this.createFormField(a,n),o=!0;else if(a.type==="update-form-field"){try{let l=i.getField(a.oldName);l&&i.removeField(l)}catch{}this.createFormField(a,n),o=!0}else if(a.type==="set-form-values"){for(let l of a.values)this.setFieldValue(i,l.name,l.fieldType,l.value);o=!0}else if(a.type==="delete-form-field"){try{let l=i.getField(a.name);l&&i.removeField(l)}catch{}o=!0}else a.type==="flatten-form"&&(s=!0);if(o)try{i.updateFieldAppearances(n)}catch{}if(s)try{i.flatten()}catch{}}createFormField(e,n){var d,h;let r=this.pdfDoc.getForm(),i=this.pdfDoc.getPage(e.pageIndex),{x:o,y:s,width:a,height:l}=e.rect,c=e.fontSize&&e.fontSize>0?e.fontSize:void 0;switch(e.fieldType){case"text":case"signature":{let f=r.createTextField(e.name);if(e.value&&f.setText(e.value),c)try{f.setFontSize(c)}catch{}if(e.multiline)try{f.enableMultiline()}catch{}if(e.maxLength&&e.maxLength>0)try{f.setMaxLength(e.maxLength)}catch{}if(e.align)try{f.setAlignment(pm[e.align])}catch{}f.addToPage(i,{x:o,y:s,width:a,height:l,font:n}),(e.fieldType==="signature"||e.readOnly)&&f.enableReadOnly(),e.required&&f.enableRequired();break}case"checkbox":{let f=r.createCheckBox(e.name);f.addToPage(i,{x:o,y:s,width:a,height:l}),e.value&&e.value!=="Off"?f.check():f.uncheck(),e.readOnly&&f.enableReadOnly(),e.required&&f.enableRequired();break}case"dropdown":{let f=r.createDropdown(e.name);if((d=e.options)!=null&&d.length&&f.addOptions(e.options),e.editable)try{f.enableEditing()}catch{}if(e.value)try{f.select(e.value)}catch{}if(c)try{f.setFontSize(c)}catch{}f.addToPage(i,{x:o,y:s,width:a,height:l,font:n}),e.readOnly&&f.enableReadOnly(),e.required&&f.enableRequired();break}case"radio":{let f=r.createRadioGroup(e.name);if(((h=e.options)!=null?h:[]).forEach((p,b)=>{var k,w;let y=(w=(k=e.optionRects)==null?void 0:k[b])!=null?w:{x:o,y:s-b*(l+4),width:a,height:l};f.addOptionToPage(p,i,{x:y.x,y:y.y,width:y.width,height:y.height})}),e.value)try{f.select(e.value)}catch{}e.readOnly&&f.enableReadOnly(),e.required&&f.enableRequired();break}}}setFieldValue(e,n,r,i){try{switch(r){case"text":case"signature":e.getTextField(n).setText(i!=null?i:"");break;case"checkbox":{let o=e.getCheckBox(n);i&&i!=="Off"&&i!=="false"?o.check():o.uncheck();break}case"dropdown":i?e.getDropdown(n).select(i):e.getDropdown(n).clear();break;case"radio":i&&i!=="Off"?e.getRadioGroup(n).select(i):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 i of this.pdfDoc.getPages()){let o=i;o.contentStream=void 0,o.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:i}=await Wc(this.currentBytes,e,n,this.rewrittenPages.get(e)),o=r.filter(c=>c.changed);if(o.length===0)return!1;let s=o.map(c=>Fs.of(c.objNum,c.genNum));for(let c of s)if(!this.pdfDoc.context.lookup(c))return!1;o.forEach((c,d)=>{this.pdfDoc.context.assign(s[d],this.pdfDoc.context.flateStream(c.bytes))});let a=this.pdfDoc.getPage(e),l=a.contentStreamRef;return l&&s.some(c=>c.tag===l.tag)&&(a.contentStream=void 0),this.rewrittenPages.set(e,i),!0}catch{return!1}}async tryNeutralizeSpans(e,n){if(!n.length||this.indexInvalidPages.has(e))return!1;try{let{streams:r,combined:i}=await Gc(this.currentBytes,e,n,this.rewrittenPages.get(e)),o=r.filter(c=>c.changed);if(o.length===0)return!1;let s=o.map(c=>Fs.of(c.objNum,c.genNum));for(let c of s)if(!this.pdfDoc.context.lookup(c))return!1;o.forEach((c,d)=>{this.pdfDoc.context.assign(s[d],this.pdfDoc.context.flateStream(c.bytes))});let a=this.pdfDoc.getPage(e),l=a.contentStreamRef;return l&&s.some(c=>c.tag===l.tag)&&(a.contentStream=void 0),this.rewrittenPages.set(e,i),!0}catch{return!1}}async tryWrapSpanWithTransform(e){if(this.indexInvalidPages.has(e.pageIndex))return!1;try{let n=mr(e.baseCtm);if(!n)return!1;let r=Ce(Ce(n,e.matrix),e.baseCtm),{streams:i,combined:o}=await Hc(this.currentBytes,e.pageIndex,e.span,r,this.rewrittenPages.get(e.pageIndex)),s=i.filter(d=>d.changed);if(s.length===0)return!1;let a=s.map(d=>Fs.of(d.objNum,d.genNum));for(let d of a)if(!this.pdfDoc.context.lookup(d))return!1;s.forEach((d,h)=>{this.pdfDoc.context.assign(a[h],this.pdfDoc.context.flateStream(d.bytes))});let l=this.pdfDoc.getPage(e.pageIndex),c=l.contentStreamRef;return c&&a.some(d=>d.tag===c.tag)&&(l.contentStream=void 0),this.rewrittenPages.set(e.pageIndex,o),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 i=`${n}:${e.length}:${r}`,o=this.embeddedImageCache.get(i);if(o)return o;let s=n==="png"?this.pdfDoc.embedPng(e):this.pdfDoc.embedJpg(e);return this.embeddedImageCache.set(i,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,i,o,s,a=1){var d;let l=r,c=await this.getStandardFont(mt.Helvetica);for(let h of n){if(h.text.length===0)continue;let f=h.style.sizePt!=null?h.style.sizePt*a:o,m=fs(s,{bold:h.style.bold,italic:h.style.italic}),{font:p}=await this.getRenderableFont(m,h.text),b=this.fitTextToFont(p,h.text);if(b.length===0)continue;let y=zr((d=h.style.color)!=null?d:{r:0,g:0,b:0}),k=_r(y.r,y.g,y.b),w=this.safeDrawText(e,b,{x:l,y:i,size:f,font:p,color:k},c),P=this.safeWidth(w,b,f);if(h.style.underline||h.style.strikethrough){let S=Math.max(.5,f*.06);h.style.underline&&e.drawRectangle({x:l,y:i-f*.12,width:P,height:S,color:k}),h.style.strikethrough&&e.drawRectangle({x:l,y:i+f*.28,width:P,height:S,color:k})}l+=P}}async getRenderableFont(e,n){let r=kl(e),i=await this.getEmbeddedFont(r);if(i&&this.fontSupportsText(i,n))return{font:i,substituted:!1};let o=await this.getStandardFont(xm(e));if(this.fontSupportsText(o,n))return{font:o,substituted:!0};let s=await this.getStandardFont(mt.Helvetica);if(this.fontSupportsText(s,n))return{font:s,substituted:!0};let a=i?[{font:i,substituted:!1},{font:o,substituted:!0},{font:s,substituted:!0}]:[{font:o,substituted:!0},{font:s,substituted:!0}],l=a[0],c=1/0;for(let d of a){let h=this.unsupportedCount(d.font,n);h<c&&(c=h,l=d)}return l}supportedCodePoints(e){try{return new Set(e.getCharacterSet())}catch{return new Set}}unsupportedCount(e,n){let r=this.supportedCodePoints(e);return Li(n).filter(i=>{let o=String.fromCodePoint(i);return o!=="\r"&&o!==`
|
|
35
|
+
`&&o!==" "&&!r.has(i)}).length}fitTextToFont(e,n){if(this.fontSupportsText(e,n))return n;let r=this.supportedCodePoints(e),i=[],o="";for(let s of Li(n)){let a=String.fromCodePoint(s);if(a==="\r"||a===`
|
|
36
|
+
`||a===" "||r.has(s)){o+=a;continue}let l=bm.get(a);if(l!==void 0&&Li(l).every(d=>String.fromCodePoint(d)===`
|
|
37
|
+
`||r.has(d))){o+=l;continue}i.push(a)}i.length>0&&console.warn(`[PDFEditSession] Dropped ${i.length} character(s) the font cannot encode: ${[...new Set(i)].join(" ")}`);try{return e.encodeText(o),o}catch{return o.replace(/[^\x20-\x7E\r\n\t]/g,"")}}fontSupportsText(e,n){if(n.length===0)return!0;try{let r=new Set(e.getCharacterSet());if(Li(n).filter(o=>{let s=String.fromCodePoint(o);return s!=="\r"&&s!==`
|
|
38
|
+
`&&s!==" "}).some(o=>!r.has(o)))return!1;e.encodeText(n)}catch{return!1}return this.fontCanLayout(e,n)}fontCanLayout(e,n){if(n.length===0)return!0;try{return e.widthOfTextAtSize(n,12),!0}catch{return!1}}safeWidth(e,n,r){try{return e.widthOfTextAtSize(n,r)}catch{return 0}}safeDrawText(e,n,r,i){try{return e.drawText(n,r),r.font}catch{let o=this.fitTextToFont(i,n);return o.length===0||e.drawText(o,{...r,font:i}),i}}async getEmbeddedFont(e){let n=this.embeddedFontCache.get(e);if(n)return n;let r=(async()=>{var s;await this.ensureFontkitRegistered();let i=this.getEmbeddedFontPrograms(),o=(s=i.find(a=>a.normalizedName===e))!=null?s:i.find(a=>a.normalizedName.includes(e)||e.includes(a.normalizedName));if(!o||!await this.embedSurvivesSave(o.bytes))return null;try{return await this.pdfDoc.embedFont(o.bytes,{subset:!1,features:wl})}catch{return null}})();return this.embeddedFontCache.set(e,r),r}async embedSurvivesSave(e){try{let n=await Cs.create(),r=(await import("./fontkit.es-6MF4HMXW.js")).default;n.registerFontkit(r);let i=await n.embedFont(e,{subset:!1,features:wl});return n.addPage().drawText("Aa Bb Cc 0123 office efficient settling",{x:10,y:10,size:10,font:i}),await n.save(),!0}catch{return!1}}getEmbeddedFontPrograms(){return this.embeddedFonts||(this.embeddedFonts=vm(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 Pl=new WeakMap,$i=class{constructor(){this.name="pdf-editor-core";this.supportedTypes=["pdf"]}async process(e,n){var r,i;try{let o=(r=n.operations)!=null?r:[];if(o.length===0)return{success:!1,document:e,error:"No edit operations were provided."};let s=(i=Pl.get(e.blob))!=null?i:await Ui.fromAvniDocument(e);await s.applyOperations(o);let a=await s.toBlob();Pl.set(a,s);let l={taskId:crypto.randomUUID(),processorName:this.name,timestamp:Date.now(),params:n};return{success:!0,document:{...e,blob:a,size:a.size,history:[...e.history,l]},metrics:{duration:0,originalSize:e.size,newSize:a.size}}}catch(o){return{success:!1,document:e,error:o instanceof Error?o.message:"Unknown PDF edit failure"}}}};import{forwardRef as Bm,useCallback as Es,useEffect as Nl,useImperativeHandle as jm,useLayoutEffect as Tl,useRef as gr,useState as Os}from"react";import{Check as Lm,X as Um}from"lucide-react";var km=t=>t?`rgb(${Math.round(t.r*255)},${Math.round(t.g*255)},${Math.round(t.b*255)})`:"#000",Pm=(t,e,n,r)=>{var s,a;let i=((s=t.sizePt)!=null?s:n)*e,o=[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:${o||"none"}`,`font-size:${i}px`,`color:${km((a=t.color)!=null?a:r)}`,"white-space:pre-wrap"].join(";")},Dm=(t,e,n,r)=>{let i=document.createElement("span"),{style:o}=t;return o.bold&&(i.dataset.b="1"),o.italic&&(i.dataset.i="1"),o.underline&&(i.dataset.u="1"),o.strikethrough&&(i.dataset.s="1"),o.sizePt!==void 0&&(i.dataset.size=String(o.sizePt)),o.color&&(i.dataset.color=`${o.color.r},${o.color.g},${o.color.b}`),i.setAttribute("style",Pm(o,e,n,r)),i.textContent=t.text,i},Sm=(t,e)=>{let n={},r=t;for(;r;){let i=r.dataset;if(i.b==="1"&&(n.bold=!0),i.i==="1"&&(n.italic=!0),i.u==="1"&&(n.underline=!0),i.s==="1"&&(n.strikethrough=!0),i.size&&n.sizePt===void 0&&(n.sizePt=parseFloat(i.size)),i.color&&!n.color){let[o,s,a]=i.color.split(",").map(Number);[o,s,a].every(Number.isFinite)&&(n.color={r:o,g:s,b:a})}if(r===e)break;r=r.parentElement}return n},_i=t=>{let e=[],n=r=>{var i;if(r.nodeType===Node.TEXT_NODE){let o=(i=r.textContent)!=null?i:"";if(o.length===0)return;e.push({text:o,style:Sm(r.parentElement,t)})}else r.nodeName!=="BR"&&r.childNodes.forEach(n)};return t.childNodes.forEach(n),Un(e)},As=(t,e,n,r,i)=>{t.textContent="";for(let o of e)o.text.length!==0&&t.appendChild(Dm(o,n,r,i))},Cm=t=>t.reduce((e,n)=>e+n.text.length,0),Ns=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 i=r.toString().length;return{start:i,end:i+n.toString().length}},Dl=(t,e)=>{let n=e,r=null,i=o=>{var s,a;if(!r)if(o.nodeType===Node.TEXT_NODE){let l=(a=(s=o.textContent)==null?void 0:s.length)!=null?a:0;if(n<=l){r={node:o,offset:n};return}n-=l}else o.childNodes.forEach(i)};return t.childNodes.forEach(i),r!=null?r:{node:t,offset:t.childNodes.length}},zi=(t,e,n)=>{let r=Dl(t,e),i=Dl(t,n),o=document.createRange();o.setStart(r.node,r.offset),o.setEnd(i.node,i.offset);let s=window.getSelection();s&&(s.removeAllRanges(),s.addRange(o))},Sl=t=>{let e=[];for(let n of t)for(let r of n.text.split(""))e.push({ch:r,style:{...n.style}});return e},Cl=(t,e,n,r)=>{let i=e,o=n;i===o&&(i=0,o=Cm(t));let s=Sl(t);for(let a=i;a<o&&a<s.length;a++)s[a].style={...s[a].style,...r};return Un(s.map(a=>({text:a.ch,style:a.style})))},Ts=(t,e,n,r)=>{let i=Sl(t);if(e===n){let h=i[Math.max(0,e-1)];return h?{...h.style}:{...r}}let o=i.slice(e,n);if(o.length===0)return{...r};let s=h=>o.every(f=>f.style[h]),a=o.every(h=>h.style.sizePt===o[0].style.sizePt)?o[0].style.sizePt:void 0,l=h=>h?`${h.r},${h.g},${h.b}`:"",c=o[0].style.color,d=o.every(h=>l(h.style.color)===l(c))?c: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 Am,Italic as Nm,Underline as Tm,Strikethrough as Em,Minus as Rl,Plus as Ml}from"lucide-react";import{jsx as Pn,jsxs as pr}from"react/jsx-runtime";var Dn=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)}`},Fm=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}),Rm=(t,e)=>!!t&&Math.abs(t.r-e.r)<.02&&Math.abs(t.g-e.g)<.02&&Math.abs(t.b-e.b)<.02,Mm=[{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}],Fl=({children:t})=>Pn("p",{className:"mb-1.5 text-[10px] font-bold uppercase tracking-widest text-ink-muted dark:text-zinc-500",children:t});function Yt({color:t,onColor:e,opacity:n,onOpacity:r,presets:i=Mm,shape:o="round",label:s="Color",allowNone:a=!1,isNone:l=!1,onNone:c,keepFocus:d=!1}){let h=d?m=>m.preventDefault():void 0,f=o==="round"?"rounded-full":"rounded-md";return pr("div",{children:[Pn(Fl,{children:s}),pr("div",{className:"flex flex-wrap items-center gap-1.5",children:[a&&Pn("button",{type:"button",title:"No fill",onMouseDown:h,onClick:c,className:`relative h-7 w-7 overflow-hidden border bg-white ${f} ${l?"ring-2 ring-crimson-600 ring-offset-1 dark:ring-offset-zinc-900":"border-ink-line-strong dark:border-white/20"}`,children:Pn("span",{className:"absolute left-1/2 top-0 h-[140%] w-px -translate-x-1/2 rotate-45 bg-red-500"})}),i.map(m=>Pn("button",{type:"button",title:Dn(m),onMouseDown:h,onClick:()=>e(m),style:{background:Dn(m)},className:`h-7 w-7 border ${f} ${!l&&Rm(t,m)?"ring-2 ring-crimson-600 ring-offset-1 dark:ring-offset-zinc-900":"border-ink-line-strong dark:border-white/20"}`},Dn(m))),pr("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 ${f}`,title:"Custom color",children:[Pn("input",{type:"color",value:Dn(t),onMouseDown:m=>m.stopPropagation(),onChange:m=>e(Fm(m.target.value)),className:"h-0 w-0 opacity-0"}),"+"]})]}),r&&typeof n=="number"&&pr("div",{className:"mt-3",children:[pr("div",{className:"mb-1 flex items-center justify-between",children:[Pn(Fl,{children:"Opacity"}),pr("span",{className:"text-[10px] font-semibold tabular-nums text-ink-soft dark:text-zinc-400",children:[Math.round(n*100),"%"]})]}),Pn("input",{type:"range",min:10,max:100,value:Math.round(n*100),onMouseDown:h,onChange:m=>r(parseInt(m.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 We,jsxs as Xr}from"react/jsx-runtime";var Om=[{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}],Im=(t,e)=>!!t&&Math.abs(t.r-e.r)<.02&&Math.abs(t.g-e.g)<.02&&Math.abs(t.b-e.b)<.02,Al=[{attr:"bold",icon:We(Am,{className:"h-3.5 w-3.5"}),title:"Bold (Ctrl+B)"},{attr:"italic",icon:We(Nm,{className:"h-3.5 w-3.5"}),title:"Italic (Ctrl+I)"},{attr:"underline",icon:We(Tm,{className:"h-3.5 w-3.5"}),title:"Underline (Ctrl+U)"},{attr:"strikethrough",icon:We(Em,{className:"h-3.5 w-3.5"}),title:"Strikethrough"}];function Yr({value:t,onToggle:e,onSize:n,onColor:r,variant:i="bar",fallbackSizePt:o,touch:s}){var p,b;let a=Math.round((p=t.sizePt)!=null?p:o),l=y=>y.preventDefault(),c=s?"h-11 w-11":"h-8 w-8",d=s?"h-11 w-16":"h-8 w-14",h=s?"h-9 w-9":"h-7 w-7",f=s?"h-9 w-8":"h-7 w-6",m=s?"h-6 w-6":"h-4 w-4";return i==="panel"?Xr("div",{className:"flex flex-col gap-4 p-4",onMouseDown:l,children:[Xr("div",{children:[We("p",{className:"mb-1.5 text-[10px] font-bold uppercase tracking-widest text-ink-muted dark:text-zinc-500",children:"Style"}),We("div",{className:"flex gap-1",children:Al.map(({attr:y,icon:k,title:w})=>We("button",{type:"button",title:w,onMouseDown:l,onClick:()=>e(y),className:`flex ${c} items-center justify-center rounded-lg border transition-colors ${t[y]?"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:k},y))})]}),Xr("div",{children:[We("p",{className:"mb-1.5 text-[10px] font-bold uppercase tracking-widest text-ink-muted dark:text-zinc-500",children:"Size"}),Xr("div",{className:"flex items-center gap-1.5",children:[We("button",{type:"button",onMouseDown:l,onClick:()=>n(Math.max(4,a-1)),className:`flex ${c} 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:We(Rl,{className:"h-3.5 w-3.5"})}),We("input",{type:"number",value:a,min:4,max:96,onMouseDown:y=>y.stopPropagation(),onChange:y=>{let k=parseInt(y.target.value,10);Number.isFinite(k)&&n(Math.min(96,Math.max(4,k)))},className:`${d} 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`}),We("button",{type:"button",onMouseDown:l,onClick:()=>n(Math.min(96,a+1)),className:`flex ${c} 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:We(Ml,{className:"h-3.5 w-3.5"})})]})]}),We(Yt,{color:(b=t.color)!=null?b:{r:0,g:0,b:0},onColor:r,shape:"square",keepFocus:!0})]}):Xr("div",{onMouseDown:l,className:`flex items-center gap-0.5 rounded-lg bg-inverse-surface px-1 py-1 text-inverse-on-surface shadow-2xl ${s?"flex-wrap justify-center":""}`,children:[Al.map(({attr:y,icon:k,title:w})=>We("button",{type:"button",title:w,onMouseDown:l,onClick:()=>e(y),className:`flex ${h} items-center justify-center rounded-md transition-colors ${t[y]?"bg-primary text-white":"hover:bg-white/15"}`,children:k},y)),We("span",{className:"mx-0.5 h-4 w-px bg-white/20"}),We("button",{type:"button",title:"Smaller",onMouseDown:l,onClick:()=>n(Math.max(4,a-1)),className:`flex ${f} items-center justify-center rounded-md hover:bg-white/15`,children:We(Rl,{className:"h-3 w-3"})}),We("span",{className:"w-6 text-center text-xs font-semibold tabular-nums",children:a}),We("button",{type:"button",title:"Larger",onMouseDown:l,onClick:()=>n(Math.min(96,a+1)),className:`flex ${f} items-center justify-center rounded-md hover:bg-white/15`,children:We(Ml,{className:"h-3 w-3"})}),We("span",{className:"mx-0.5 h-4 w-px bg-white/20"}),Om.slice(0,5).map(y=>We("button",{type:"button",title:Dn(y),onMouseDown:l,onClick:()=>r(y),style:{background:Dn(y)},className:`${m} rounded ${Im(t.color,y)?"ring-2 ring-white":"ring-1 ring-white/30"}`},Dn(y)))]})}import{jsx as fn,jsxs as El}from"react/jsx-runtime";var $m=Bm(function(e,n){let{containerX:r,containerY:i,screenWidth:o,screenHeight:s,scale:a,fontSizePt:l,fontFamily:c,baselineOffsetPx:d,maxWidth:h,initialSpans:f,baseColor:m,maskRect:p,bgColor:b,ocr:y,touch:k,placeholder:w,onCommit:P,onCancel:S,onActiveStyleChange:R}=e,I=gr(null),F=gr(null),A=gr(null),G=gr({sizePt:l,color:m}),Y=gr(!0),E=gr(""),[ee,ne]=Os(G.current),[O,ge]=Os(0),[fe,Oe]=Os({top:-40,left:0});Nl(()=>()=>{Y.current=!1},[]),Tl(()=>{let W=I.current,me=A.current,xe=F.current;if(!W||!me)return;let be=()=>{var tt;let Ie=W.getBoundingClientRect(),Me=me.offsetWidth||220,Ke=me.offsetHeight||36,et=(tt=xe==null?void 0:xe.offsetHeight)!=null?tt:s,qe=window.innerWidth,Rt=Ie.top-Ke-8>=4?-(Ke+8):et+10,ve=0;Ie.left+Me>qe-6&&(ve=qe-6-Me-Ie.left),Ie.left+ve<6&&(ve=6-Ie.left),Oe({top:Rt,left:ve})};return be(),window.addEventListener("resize",be),()=>window.removeEventListener("resize",be)},[O]);let Te=Es(()=>{var Me;let W=F.current;if(!W)return;let me=(Me=Ns(W))!=null?Me:{start:0,end:0},xe=_i(W),be=Ts(xe,me.start,me.end,G.current),Ie=vn(be);Ie!==E.current&&(E.current=Ie,ne(be),R==null||R(be))},[R]);Tl(()=>{let W=F.current;if(!W)return;As(W,f,a,l,m),W.focus();let me=Ai(f).length;if(zi(W,me,me),Te(),d!=null){let xe=document.createElement("span");xe.style.cssText="display:inline-block;width:0;height:0;overflow:hidden;vertical-align:baseline",xe.setAttribute("aria-hidden","true"),W.insertBefore(xe,W.firstChild);let be=xe.getBoundingClientRect().top-W.getBoundingClientRect().top;W.removeChild(xe),Number.isFinite(be)&&ge(d-be)}},[]),Nl(()=>{let W=()=>{let me=F.current;me&&document.activeElement===me&&Te()};return document.addEventListener("selectionchange",W),()=>document.removeEventListener("selectionchange",W)},[Te]);let _=Es((W,me)=>{var qe;let xe=F.current;if(!xe)return;xe.focus();let be=(qe=Ns(xe))!=null?qe:{start:0,end:0},Ie=_i(xe),Me=W;if(me){let Rt=Ts(Ie,be.start,be.end,G.current);Me={[me]:!Rt[me]}}let Ke=Cl(Ie,be.start,be.end,Me);As(xe,Ke,a,l,m);let et=Ai(Ke).length;be.start===be.end?zi(xe,0,et):zi(xe,Math.min(be.start,et),Math.min(be.end,et)),Te()},[a,l,m,Te]),ce=Es(()=>{let W=F.current;if(!W){S();return}let me=_i(W);P(me,Ai(me))},[P,S]);jm(n,()=>({toggle:W=>_({},W),setSize:W=>_({sizePt:W}),setColor:W=>_({color:W}),commit:ce,focus:()=>{var W;return(W=F.current)==null?void 0:W.focus()}}),[_,ce]);let ae=Math.max(s,Math.ceil(l*a*1.2));return El("div",{ref:I,style:{position:"absolute",left:`${r}px`,top:`${i}px`,zIndex:50,pointerEvents:"none"},children:[p&&fn("div",{style:{position:"absolute",left:`${p.x}px`,top:`${p.y}px`,width:`${p.w}px`,height:`${p.h}px`,background:b?`rgb(${Math.round(b.r*255)},${Math.round(b.g*255)},${Math.round(b.b*255)})`:"#fff",pointerEvents:"none"}}),fn("div",{ref:A,style:{position:"absolute",left:fe.left,top:fe.top,maxWidth:"92vw",pointerEvents:"auto"},onMouseDown:W=>W.stopPropagation(),onTouchStart:W=>W.stopPropagation(),onClick:W=>W.stopPropagation(),children:fn(Yr,{value:ee,onToggle:W=>_({},W),onSize:W=>_({sizePt:W}),onColor:W=>_({color:W}),variant:"bar",fallbackSizePt:l,touch:k})}),fn("div",{ref:F,contentEditable:!0,suppressContentEditableWarning:!0,"data-placeholder":w,onMouseDown:W=>W.stopPropagation(),onPointerDown:W=>W.stopPropagation(),onTouchStart:W=>W.stopPropagation(),onClick:W=>W.stopPropagation(),onKeyUp:Te,onMouseUp:Te,onBlur:()=>{setTimeout(()=>{var me;if(!Y.current)return;let W=document.activeElement;(me=I.current)!=null&&me.contains(W)||ce()},150)},onKeyDown:W=>{if((W.ctrlKey||W.metaKey)&&!W.shiftKey){let me=W.key.toLowerCase();if(me==="b"){W.preventDefault(),_({},"bold");return}if(me==="i"){W.preventDefault(),_({},"italic");return}if(me==="u"){W.preventDefault(),_({},"underline");return}}W.key==="Enter"&&(W.preventDefault(),ce()),W.key==="Escape"&&(W.preventDefault(),S())},style:{position:"relative",display:"inline-block",transform:`translateY(${O}px)`,minWidth:`${Math.max(40,o)}px`,width:"auto",maxWidth:h?`${h}px`:void 0,minHeight:`${ae}px`,height:"auto",padding:0,margin:0,border:"none",outline:"none",background:b?`rgb(${Math.round(b.r*255)},${Math.round(b.g*255)},${Math.round(b.b*255)})`:p?"#fff":"transparent",fontSize:`${l*a}px`,lineHeight:`${ae}px`,fontFamily:c!=null?c:"inherit",color:m?`rgb(${Math.round(m.r*255)},${Math.round(m.g*255)},${Math.round(m.b*255)})`:"#000",caretColor:"rgba(59, 130, 246, 0.9)",pointerEvents:"auto",whiteSpace:"pre-wrap",overflowWrap:"break-word",overflow:"visible"}}),y&&fn("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"}),k&&El("div",{style:{position:"absolute",left:0,top:s+(y?28:8),display:"flex",gap:8,pointerEvents:"auto"},onMouseDown:W=>W.stopPropagation(),onTouchStart:W=>W.stopPropagation(),onClick:W=>W.stopPropagation(),children:[fn("button",{type:"button","aria-label":"Cancel",onClick:()=>S(),style:{display:"flex",alignItems:"center",justifyContent:"center",width:40,height:40,borderRadius:9999,background:"#fff",color:"#b91c1c",border:"1px solid rgba(0,0,0,0.12)",boxShadow:"0 4px 12px -4px rgba(0,0,0,0.35)"},children:fn(Um,{className:"h-5 w-5"})}),fn("button",{type:"button","aria-label":"Done",onClick:()=>ce(),style:{display:"flex",alignItems:"center",justifyContent:"center",width:40,height:40,borderRadius:9999,background:"#C20E3A",color:"#fff",border:"none",boxShadow:"0 4px 12px -4px rgba(162,7,48,0.6)"},children:fn(Lm,{className:"h-5 w-5"})})]})]})}),Ol=$m;import{MousePointer as Wm,Type as Bs,MessageSquareText as Hm,Eraser as Gm,Highlighter as Ll,PenLine as Ul,StickyNote as Vm,PenTool as $l,FileText as Km,Trash2 as qm,Eye as Jm,Underline as Zm,Strikethrough as Qm,Minus as ep,ArrowUpRight as tp,Square as np,Circle as rp,Hexagon as ip,CheckSquare as op,Circle as sp,ChevronDownSquare as ap,Layers as cp,X as lp}from"lucide-react";import{Plus as _m,Trash2 as zm,X as Xm}from"lucide-react";import{jsx as Re,jsxs as Nt}from"react/jsx-runtime";var Ym=({children:t})=>Re("p",{className:"mb-1 text-[10px] font-bold uppercase tracking-widest text-ink-muted dark:text-zinc-500",children:t}),hn="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",Sn=({label:t,children:e})=>Nt("div",{children:[Re(Ym,{children:t}),e]}),Wr=({label:t,checked:e,onChange:n})=>Nt("label",{className:"flex cursor-pointer items-center justify-between gap-2 text-sm text-ink-soft dark:text-zinc-300",children:[Re("span",{children:t}),Re("input",{type:"checkbox",checked:e,onChange:r=>n(r.target.checked),className:"h-4 w-4 accent-crimson-600"})]});function Is({field:t,onChange:e,onDelete:n}){var f,m,p,b;let{type:r,rect:i}=t,o=r==="text"||r==="signature",s=r==="dropdown"||r==="radio",a=(f=t.options)!=null?f:[],l=y=>e({rect:{...i,...y}}),c=(y,k)=>{let w=a.slice();w[y]=k,e({options:w})},d=()=>e({options:[...a,`Option ${a.length+1}`]}),h=y=>e({options:a.filter((k,w)=>w!==y)});return Nt("div",{className:"flex flex-col gap-3 border-t border-ink-line pt-3 dark:border-white/10",children:[Nt("p",{className:"text-[10px] font-bold uppercase tracking-widest text-crimson-600",children:[r," field"]}),Re(Sn,{label:"Field name",children:Re("input",{className:hn,value:t.name,onChange:y=>e({name:y.target.value})})}),Re(Sn,{label:"Default value",children:r==="checkbox"?Re(Wr,{label:"Checked by default",checked:!!t.value&&t.value!=="Off",onChange:y=>{var k;return e({value:y?(k=t.onState)!=null?k:"Yes":"Off"})}}):s?Nt("select",{className:hn,value:(m=t.value)!=null?m:"",onChange:y=>e({value:y.target.value}),children:[Re("option",{value:"",children:"- none -"}),a.map(y=>Re("option",{value:y,children:y},y))]}):Re("input",{className:hn,value:(p=t.value)!=null?p:"",onChange:y=>e({value:y.target.value})})}),Nt("div",{className:"grid grid-cols-2 gap-2",children:[Re(Sn,{label:"Width (pt)",children:Re("input",{type:"number",min:1,className:hn,value:Math.round(i.width),onChange:y=>l({width:Math.max(1,Number(y.target.value)||0)})})}),Re(Sn,{label:"Height (pt)",children:Re("input",{type:"number",min:1,className:hn,value:Math.round(i.height),onChange:y=>l({height:Math.max(1,Number(y.target.value)||0)})})}),Re(Sn,{label:"X (pt)",children:Re("input",{type:"number",className:hn,value:Math.round(i.x),onChange:y=>l({x:Number(y.target.value)||0})})}),Re(Sn,{label:"Y (pt)",children:Re("input",{type:"number",className:hn,value:Math.round(i.y),onChange:y=>l({y:Number(y.target.value)||0})})})]}),(o||r==="dropdown")&&Re(Sn,{label:"Font size (0 = auto)",children:Re("input",{type:"number",min:0,className:hn,value:(b=t.fontSize)!=null?b:0,onChange:y=>e({fontSize:Math.max(0,Number(y.target.value)||0)})})}),s&&Re(Sn,{label:"Options",children:Nt("div",{className:"flex flex-col gap-1.5",children:[a.map((y,k)=>Nt("div",{className:"flex items-center gap-1.5",children:[Re("input",{className:hn,value:y,onChange:w=>c(k,w.target.value)}),Re("button",{type:"button",onClick:()=>h(k),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:Re(Xm,{className:"h-3.5 w-3.5"})})]},k)),Nt("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:[Re(_m,{className:"h-3.5 w-3.5"})," Add option"]})]})}),Nt("div",{className:"flex flex-col gap-2 rounded-lg bg-paper px-3 py-2 dark:bg-zinc-800/40",children:[Re(Wr,{label:"Required",checked:!!t.required,onChange:y=>e({required:y})}),r!=="signature"&&Re(Wr,{label:"Read-only",checked:!!t.readOnly,onChange:y=>e({readOnly:y})}),o&&Re(Wr,{label:"Multi-line",checked:!!t.multiline,onChange:y=>e({multiline:y})}),r==="dropdown"&&Re(Wr,{label:"Allow custom text",checked:!!t.editable,onChange:y=>e({editable:y})})]}),Nt("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:[Re(zm,{className:"h-3.5 w-3.5"})," Delete field"]})]})}import{Fragment as Xn,jsx as le,jsxs as Ue}from"react/jsx-runtime";var dp=[1,2,4,8],Il={view:{icon:le(Jm,{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:le(Wm,{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:le(Bs,{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:le(Bs,{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:le(Ll,{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:le(Ul,{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:le(Hm,{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:le(Gm,{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:le(Vm,{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:le($l,{className:"h-4 w-4"}),title:"Sign",help:"Choose or draw your signature, then click the page to place it. Then either download a quick visual copy, or \u201CSign & certify\u201D to embed a cryptographic signature that makes the document tamper-evident and records an audit trail (with a downloadable Certificate of Completion)."},form:{icon:le(Km,{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."}},up=[{key:"text",icon:le(Bs,{className:"h-4 w-4"}),label:"Text"},{key:"checkbox",icon:le(op,{className:"h-4 w-4"}),label:"Checkbox"},{key:"radio",icon:le(sp,{className:"h-4 w-4"}),label:"Radio"},{key:"dropdown",icon:le(ap,{className:"h-4 w-4"}),label:"Dropdown"},{key:"signature",icon:le($l,{className:"h-4 w-4"}),label:"Signature"}],fp=[{key:"highlight",icon:le(Ll,{className:"h-4 w-4"}),label:"Highlight"},{key:"underline",icon:le(Zm,{className:"h-4 w-4"}),label:"Underline"},{key:"strikeout",icon:le(Qm,{className:"h-4 w-4"}),label:"Strike"},{key:"brush",icon:le(Ul,{className:"h-4 w-4"}),label:"Brush"}],hp=[{key:"line",icon:le(ep,{className:"h-4 w-4"}),label:"Line"},{key:"arrow",icon:le(tp,{className:"h-4 w-4"}),label:"Arrow"},{key:"rect",icon:le(np,{className:"h-4 w-4"}),label:"Rectangle"},{key:"ellipse",icon:le(rp,{className:"h-4 w-4"}),label:"Ellipse"},{key:"polygon",icon:le(ip,{className:"h-4 w-4"}),label:"Polygon"}],xr=({children:t})=>le("p",{className:"mb-1.5 text-[10px] font-bold uppercase tracking-widest text-ink-muted dark:text-zinc-500",children:t}),Bl=({value:t,options:e,onChange:n})=>le("div",{className:"grid grid-cols-2 gap-1.5",children:e.map(r=>Ue("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))}),jl=({value:t,onChange:e})=>Ue("div",{children:[le(xr,{children:"Thickness"}),le("div",{className:"flex gap-1.5",children:dp.map(n=>Ue("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 js(t){var d,h,f;let{tool:e,annotStyle:n,setAnnotStyle:r}=t,i=(d=Il[e])!=null?d:Il.select,o=e==="edit-text"||e==="add-text",s=t.drawShape==="rect"||t.drawShape==="ellipse"||t.drawShape==="polygon",a=Ue("div",{className:"flex items-center gap-2 border-b border-ink-line px-4 py-3 text-crimson-600 dark:border-white/10",children:[i.icon,le("span",{className:"font-display text-sm font-bold text-ink dark:text-white",children:i.title}),t.asSheet&&Ue(Xn,{children:[le("div",{className:"flex-1"}),le("button",{type:"button",onClick:t.onClose,"aria-label":"Close options",className:"rounded-lg p-1 text-ink-muted hover:bg-paper hover:text-ink dark:hover:bg-zinc-800",children:le(lp,{className:"h-4 w-4"})})]})]}),l=Ue("div",{className:"border-t border-ink-line bg-[#F3ECDD] px-4 py-3 dark:border-white/10 dark:bg-zinc-800/30",children:[le("p",{className:"mb-1 text-[10px] font-bold uppercase tracking-widest text-ink-muted dark:text-zinc-500",children:"How to use"}),le("p",{className:"text-xs leading-relaxed text-ink-soft dark:text-zinc-400",children:i.help})]}),c=Ue(Xn,{children:[Ue("div",{className:"flex-1 overflow-y-auto",children:[Ue("div",{className:"flex flex-col gap-4 p-4",children:[o&&Ue(Xn,{children:[!t.textActive&&le("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."}),Ue("div",{children:[le(xr,{children:"Font"}),Ue("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:[le("span",{className:"truncate",children:((h=t.fontName)!=null?h:"Helvetica").replace(/^[A-Z]{6}\+/,"")}),le("span",{className:"ml-2 shrink-0 text-[9px] font-semibold uppercase tracking-wide text-ink-muted dark:text-zinc-500",children:"soon"})]})]})]}),e==="annotate"&&Ue(Xn,{children:[Ue("div",{children:[le(xr,{children:"Tool"}),le(Bl,{value:t.annotSubtool,options:fp,onChange:t.setAnnotSubtool})]}),t.annotSubtool==="highlight"&&Ue("div",{children:[le(xr,{children:"Mode"}),le(Bl,{value:t.highlightMode,options:[{key:"select",label:"Select text"},{key:"box",label:"Box / region"}],onChange:t.setHighlightMode})]}),le(Yt,{color:n.color,onColor:m=>r({color:m}),opacity:n.opacity,onOpacity:m=>r({opacity:m})}),t.annotSubtool==="brush"&&le(jl,{value:n.strokeWidth,onChange:m=>r({strokeWidth:m})})]}),e==="draw"&&Ue(Xn,{children:[Ue("div",{children:[le(xr,{children:"Shape"}),le("div",{className:"grid grid-cols-3 gap-1.5",children:hp.map(m=>le("button",{type:"button",title:m.label,onClick:()=>t.setDrawShape(m.key),className:`flex h-10 items-center justify-center rounded-lg border transition-colors ${t.drawShape===m.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:m.icon},m.key))})]}),le(Yt,{label:"Stroke",color:n.color,onColor:m=>r({color:m}),opacity:n.opacity,onOpacity:m=>r({opacity:m})}),le(jl,{value:n.strokeWidth,onChange:m=>r({strokeWidth:m})}),s&&le(Yt,{label:"Fill",color:(f=n.fill)!=null?f:{r:1,g:1,b:1},onColor:m=>r({fill:m}),allowNone:!0,isNone:n.fill===null,onNone:()=>r({fill:null})})]}),e==="form"&&Ue(Xn,{children:[Ue("div",{children:[le(xr,{children:"Add field"}),le("div",{className:"grid grid-cols-2 gap-1.5",children:up.map(m=>Ue("button",{type:"button",onClick:()=>t.setAddFieldType(t.addFieldType===m.key?null:m.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===m.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:[m.icon,m.label]},m.key))}),t.addFieldType&&Ue("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?le(Is,{field:t.selectedField,onChange:t.onUpdateField,onDelete:t.onDeleteField}):le("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."}),Ue("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:[le(cp,{className:"h-3.5 w-3.5"})," Flatten form"]})]}),(e==="annotate"||e==="draw")&&t.annotationCount>0&&Ue("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:[le(qm,{className:"h-3.5 w-3.5"})," Clear all annotations"]})]}),o&&le(Yr,{value:t.textStyle,onToggle:t.onToggle,onSize:t.onSize,onColor:t.onColor,variant:"panel",fallbackSizePt:t.fallbackSizePt,touch:t.asSheet})]}),l]});return t.asSheet?t.open?Ue(Xn,{children:[le("div",{className:"sheet-backdrop",onClick:t.onClose}),Ue("aside",{className:"bottom-sheet border-t border-ink-line bg-paper-card dark:border-white/10 dark:bg-[#1a1712]",children:[le("div",{className:"sheet-handle"}),a,c]})]}):null:Ue("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:[a,c]})}var xt=(t,e,n,r,i)=>{let o=t-n.left,s=e-n.top;return{x:o/r,y:i-s/r}},Qe=(t,e,n,r)=>({x:t*n,y:(r-e)*n});import{Fragment as bp,jsx as Ge,jsxs as Hr}from"react/jsx-runtime";var Xi=t=>`rgb(${Math.round(t.r*255)},${Math.round(t.g*255)},${Math.round(t.b*255)})`,_l=(t,e,n)=>{let r=Math.atan2(e.y-t.y,e.x-t.x),i=Math.PI/7,o={x:e.x-n*Math.cos(r-i),y:e.y-n*Math.sin(r-i)},s={x:e.x-n*Math.cos(r+i),y:e.y-n*Math.sin(r+i)};return`${o.x},${o.y} ${e.x},${e.y} ${s.x},${s.y}`},mp=(t,e,n)=>{let r=1.5*n,i=4*n,o=t(e.x,e.y+1),s=[`M ${o.x} ${o.y}`],a=t(e.x+e.width,e.y).x,l=!0;for(let c=o.x+i;c<=a;c+=i)s.push(`L ${c} ${o.y+(l?-r:r)}`),l=!l;return s.join(" ")},zl=(t,e,n,r,i,o)=>e.map((s,a)=>{if(t==="highlight"){let h=n(s.x,s.y+s.height);return Ge("rect",{x:h.x,y:h.y,width:s.width*r,height:s.height*r,fill:i,opacity:Math.min(.4,o),style:{mixBlendMode:"multiply"}},a)}if(t==="squiggly")return Ge("path",{d:mp(n,s,r),stroke:i,strokeWidth:Math.max(.75,r),fill:"none",opacity:o},a);let l=t==="strikeout"?s.y+s.height*.5:s.baselineY-Math.max(1,s.height*.12),c=n(s.x,l),d=n(s.x+s.width,l);return Ge("line",{x1:c.x,y1:c.y,x2:d.x,y2:d.y,stroke:i,strokeWidth:Math.max(1.5,r),opacity:o},a)}),pp=(t,e,n)=>{var c;let r=Xi(t.style.color),i=Math.max(.5,((c=t.style.strokeWidth)!=null?c:1.5)*n),o=t.style.fill?Xi(t.style.fill):"none";if(t.kind==="highlight"||t.kind==="underline"||t.kind==="strikeout"||t.kind==="squiggly")return zl(t.kind,t.quads,e,n,r,t.style.opacity);if(t.kind==="ink")return t.strokes.map((d,h)=>{let f=d.map((m,p)=>{let b=e(m.x,m.y);return`${p===0?"M":"L"} ${b.x} ${b.y}`}).join(" ");return Ge("path",{d:f,stroke:r,strokeWidth:i,fill:"none",strokeLinecap:"round",strokeLinejoin:"round",opacity:t.style.opacity},h)});if(t.kind==="rect"){let d=ht(t),h=e(d.x,d.y+d.height);return Ge("rect",{x:h.x,y:h.y,width:d.width*n,height:d.height*n,stroke:r,strokeWidth:i,fill:o,opacity:t.style.opacity})}if(t.kind==="ellipse"){let d=ht(t),h=e(d.x+d.width/2,d.y+d.height/2);return Ge("ellipse",{cx:h.x,cy:h.y,rx:d.width/2*n,ry:d.height/2*n,stroke:r,strokeWidth:i,fill:o,opacity:t.style.opacity})}if(t.kind==="polygon"||t.kind==="polyline"){let d=t.points.map(h=>{let f=e(h.x,h.y);return`${f.x},${f.y}`}).join(" ");return t.kind==="polygon"?Ge("polygon",{points:d,stroke:r,strokeWidth:i,fill:o,opacity:t.style.opacity}):Ge("polyline",{points:d,stroke:r,strokeWidth:i,fill:"none",opacity:t.style.opacity})}let s=t,a=e(s.points[0].x,s.points[0].y),l=e(s.points[1].x,s.points[1].y);return Hr("g",{opacity:t.style.opacity,children:[Ge("line",{x1:a.x,y1:a.y,x2:l.x,y2:l.y,stroke:r,strokeWidth:i,strokeLinecap:"round"}),t.kind==="arrow"&&Ge("polyline",{points:_l(a,l,Math.max(8,i*3)),stroke:r,strokeWidth:i,fill:"none",strokeLinecap:"round",strokeLinejoin:"round"})]})},gp=(t,e,n,r,i)=>{let o=Xi(r.color),s=Math.max(.5,r.strokeWidth*n),a=r.fill?Xi(r.fill):"none";if(t.kind==="quads")return zl(i,t.quads,e,n,o,r.opacity);if(t.kind==="box"){let d=e(t.rect.x,t.rect.y+t.rect.height);return Ge("rect",{x:d.x,y:d.y,width:t.rect.width*n,height:t.rect.height*n,stroke:o,strokeWidth:s,fill:a,opacity:r.opacity,strokeDasharray:"4 3"})}if(t.kind==="line"){let d=e(t.a.x,t.a.y),h=e(t.b.x,t.b.y);return Hr("g",{opacity:r.opacity,children:[Ge("line",{x1:d.x,y1:d.y,x2:h.x,y2:h.y,stroke:o,strokeWidth:s,strokeLinecap:"round"}),t.arrow&&Ge("polyline",{points:_l(d,h,Math.max(8,s*3)),stroke:o,strokeWidth:s,fill:"none"})]})}if(t.kind==="ink"){let d=t.points.map((h,f)=>{let m=e(h.x,h.y);return`${f===0?"M":"L"} ${m.x} ${m.y}`}).join(" ");return Ge("path",{d,stroke:o,strokeWidth:s,fill:"none",strokeLinecap:"round",strokeLinejoin:"round",opacity:r.opacity})}let l=t.points.map(d=>{let h=e(d.x,d.y);return`${h.x},${h.y}`}).join(" "),c=t.cursor?e(t.cursor.x,t.cursor.y):null;return Hr("g",{opacity:r.opacity,children:[Ge("polyline",{points:l,stroke:o,strokeWidth:s,fill:"none"}),c&&t.points.length>0&&(()=>{let d=e(t.points[t.points.length-1].x,t.points[t.points.length-1].y);return Ge("line",{x1:d.x,y1:d.y,x2:c.x,y2:c.y,stroke:o,strokeWidth:s,strokeDasharray:"4 3"})})(),t.points.map((d,h)=>{let f=e(d.x,d.y);return Ge("circle",{cx:f.x,cy:f.y,r:3,fill:o},h)})]})},xp=[{key:"nw",cursor:"nwse-resize"},{key:"ne",cursor:"nesw-resize"},{key:"sw",cursor:"nesw-resize"},{key:"se",cursor:"nwse-resize"}];function Ls({pageIndex:t,pageHeight:e,scale:n,annots:r,live:i,liveStyle:o,selectedId:s,interactive:a,liveMarkupKind:l,onBeginResize:c}){var m;let d=(p,b)=>Qe(p,b,n,e),h=r.filter(p=>p.pageIndex===t),f=(m=h.find(p=>p.id===s))!=null?m:null;return Hr(bp,{children:[Hr("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:[h.map(p=>Ge("g",{children:pp(p,d,n)},p.id)),(i==null?void 0:i.pageIndex)===t&&gp(i,d,n,o,l),f&&(()=>{let p=ht(f),b=d(p.x,p.y+p.height);return Ge("rect",{x:b.x-3,y:b.y-3,width:p.width*n+6,height:p.height*n+6,fill:"none",stroke:"#D6002F",strokeWidth:1,strokeDasharray:"4 3"})})()]}),a&&f&&(()=>{let p=ht(f),b={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 Ge("div",{style:{position:"absolute",inset:0,zIndex:12,pointerEvents:"none"},children:xp.map(({key:y,cursor:k})=>Ge("div",{onPointerDown:w=>{w.stopPropagation(),w.preventDefault(),c(f.id,y,w)},style:{position:"absolute",left:b[y].x-5,top:b[y].y-5,width:10,height:10,background:"#fff",border:"1.5px solid #D6002F",borderRadius:2,cursor:k,pointerEvents:"auto"}},y))})})()]})}var yp=t=>{var r;let e=Array.from(t.text);if((r=t.glyphs)!=null&&r.length){let i=[];for(let o of t.glyphs){let s=Math.max(1,Array.from(o.char).length);for(let a=0;a<s;a++)i.push({x:o.pdfX,y:o.pdfY,width:o.width,height:o.height,baselineY:o.pdfBaselineY})}if(i.length===e.length)return e.map((o,s)=>({char:o,...i[s]}))}let n=t.width/Math.max(1,e.length);return e.map((i,o)=>({char:i,x:t.pdfX+o*n,y:t.pdfY,width:n,height:t.height,baselineY:t.pdfBaselineY}))},wp=t=>{let e=[],n=0;for(let r of t)for(let i of yp(r))e.push({...i,order:n++});return e},Xl=(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,i=-1,o=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,l=e.y<s.y?s.y:e.y>s.y+s.height?s.y+s.height:e.y,c=Math.hypot(e.x-a,e.y-l);c<o&&(o=c,i=s.order)}return i},vp=t=>{if(!t.length)return[];let e=[],n=[];for(let r of t){if(n.length){let i=Math.max(2,r.height*.5);Math.abs(r.baselineY-n[0].baselineY)>i&&(e.push(n),n=[])}n.push(r)}return n.length&&e.push(n),e.map(r=>{let i=Math.min(...r.map(d=>d.x)),o=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)),l=r.map(d=>d.baselineY).sort((d,h)=>d-h),c=l[Math.floor(l.length/2)];return{x:i,y:o,width:s-i,height:a-o,baselineY:c}})},Yl=(t,e,n)=>{let r=wp(t);if(!r.length)return{quads:[],text:""};let i=Xl(r,e),o=Xl(r,n);if(i<0||o<0)return{quads:[],text:""};let s=Math.min(i,o),a=Math.max(i,o),l=r.slice(s,a+1);return{quads:vp(l),text:l.map(c=>c.char).join("")}};function nt(t,e){if(t){if(!$e(t))return t;try{return e(t)}catch{return}}}function kp(t,e){if(!t)return;let n=nt(t.entries.get("AcroForm"),e);if(!(!n||!Q(n)))return n}function Pp(t,e){if(!t)return[];let n=nt(t.entries.get("Annots"),e);if(!n)return[];let r=[];if(ue(n))for(let i of n.items){let o=nt(i,e);o&&Q(o)&&r.push(o)}return r}var Us=t=>t&&typeof t=="object"&&"type"in t&&t.type==="name"?t.value:null,Yn=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 i=2;i+1<e.length;i+=2)r+=String.fromCharCode(e[i]<<8|e[i+1]);return r}let n="";for(let r=0;r<e.length;r++)n+=String.fromCharCode(e[r]);return n},Hl=t=>t&&typeof t=="object"&&"type"in t&&(t.type==="integer"||t.type==="real")?t.value:null,Dp=1,Sp=2,Cp=4096,Fp=32768,Rp=65536,a1=1<<17,Mp=t=>{if(!t||!ue(t)||t.items.length<4)return null;let e=t.items.slice(0,4).map(s=>Hl(s));if(e.some(s=>s===null))return null;let[n,r,i,o]=e;return{x:Math.min(n,i),y:Math.min(r,o),width:Math.abs(i-n),height:Math.abs(o-r)}},Wl=(t,e)=>{let n=nt(t.entries.get("AP"),e);if(!n||!Q(n))return[];let r=nt(n.entries.get("N"),e);return!r||!Q(r)?[]:Array.from(r.entries.keys()).filter(i=>i!=="Off")},Ap=(t,e)=>{var i,o,s;let n=nt(t,e);if(!n||!ue(n))return[];let r=[];for(let a of n.items){let l=nt(a,e);l&&ue(l)&&l.items.length>0?r.push((o=(i=Yn(l.items[0]))!=null?i:Yn(l.items[1]))!=null?o:""):r.push((s=Yn(l))!=null?s:"")}return r.filter(a=>a.length>0)},Np=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},Tp=(t,e)=>{switch(t){case"Tx":return"text";case"Ch":return"dropdown";case"Sig":return"signature";case"Btn":return e&Rp?null:e&Fp?"radio":"checkbox";default:return null}},Ep=(t,e)=>{let n=new Map;for(let[r,i]of t)for(let o of Pp(i,e))n.has(o)||n.set(o,r);return n};function Gl(t,e,n){let r=kp(t,n);if(!r)return[];let i=nt(r.entries.get("Fields"),n);if(!i||!ue(i))return[];let o=Yn(r.entries.get("DA")),s=Ep(e,n),a=[],l=(c,d)=>{var ge,fe,Oe,Te,_;let h=Yn(c.entries.get("T")),f=h?d.namePrefix?`${d.namePrefix}.${h}`:h:d.namePrefix,m=Hl(c.entries.get("Ff")),p=m!==null?m:d.flags,b=(ge=Us(c.entries.get("FT")))!=null?ge:d.ft,y=(fe=Yn(c.entries.get("DA")))!=null?fe:d.da,k=(Te=(Oe=Yn(c.entries.get("V")))!=null?Oe:Us(c.entries.get("V")))!=null?Te:d.value,w={flags:p,namePrefix:f,ft:b,da:y,value:k!=null?k:void 0},P=nt(c.entries.get("Kids"),n),S=P&&ue(P)?P.items.map(ce=>nt(ce,n)).filter(ce=>!!ce&&Q(ce)):[],I=Us(c.entries.get("Subtype"))==="Widget"||S.length===0&&c.entries.has("Rect"),F=S.some(ce=>ce.entries.has("T"));if(S.length>0&&F){for(let ce of S)l(ce,w);return}let A=Tp(b,p);if(!A){for(let ce of S)l(ce,w);return}let G=Np(y!=null?y:o),Y=(p&Dp)!==0,E=(p&Sp)!==0,ee=(p&Cp)!==0,ne=A==="dropdown"?Ap(c.entries.get("Opt"),n):void 0,O=S.length>0?S:I?[c]:[];for(let ce of O){let ae=Mp(nt(ce.entries.get("Rect"),n));if(!ae)continue;let W=(_=s.get(ce))!=null?_:0,xe=(A==="checkbox"||A==="radio"?Wl(ce,n):[])[0];a.push({id:`${f}__${a.length}`,name:f,type:A,pageIndex:W,rect:ae,value:k!=null?k:void 0,options:A==="radio"?O.map(be=>Wl(be,n)[0]).filter(be=>!!be):ne,onState:xe,fontSize:G,multiline:ee,readOnly:Y,required:E})}};for(let c of i.items){let d=nt(c,n);d&&Q(d)&&l(d,{flags:0,namePrefix:""})}return a}var Vl=t=>t&&typeof t=="object"&&"type"in t&&t.type==="name"?t.value:null,Op=t=>t&&typeof t=="object"&&"type"in t&&(t.type==="integer"||t.type==="real")?t.value:null,Ip=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 i=2;i+1<e.length;i+=2)r+=String.fromCharCode(e[i]<<8|e[i+1]);return r}let n="";for(let r=0;r<e.length;r++)n+=String.fromCharCode(e[r]);return n},Bp=t=>{if(!t||!ue(t)||t.items.length<4)return null;let e=t.items.slice(0,4).map(s=>Op(s));if(e.some(s=>s===null))return null;let[n,r,i,o]=e;return{x:Math.min(n,i),y:Math.min(r,o),width:Math.abs(i-n),height:Math.abs(o-r)}},Kl=(t,e,n)=>{let r=$e(t)?t:nt(t,n);if(!r||!ue(r)||r.items.length===0)return;let i=r.items[0];if($e(i))return e.get(`${i.objNum}:${i.genNum}`)};function $s(t,e,n){var o;if(!t)return[];let r=nt(t.entries.get("Annots"),n);if(!r||!ue(r))return[];let i=[];for(let s of r.items){let a=nt(s,n);if(!a||!Q(a)||Vl(a.entries.get("Subtype"))!=="Link")continue;let l=Bp(nt(a.entries.get("Rect"),n));if(!l||l.width<1||l.height<1)continue;let c,d,h=nt(a.entries.get("A"),n);if(h&&Q(h)){let f=Vl(h.entries.get("S"));f==="URI"?c=(o=Ip(h.entries.get("URI")))!=null?o:void 0:f==="GoTo"&&(d=Kl(h.entries.get("D"),e,n))}c===void 0&&d===void 0&&(d=Kl(a.entries.get("Dest"),e,n)),(c||d!==void 0)&&i.push({rect:l,uri:c,destPageIndex:d})}return i}import{useLayoutEffect as jp,useRef as Lp}from"react";import{jsx as ql,jsxs as Up}from"react/jsx-runtime";function _s({runs:t,scale:e,pageHeight:n}){let r=Lp(null);return jp(()=>{let i=r.current;if(!i)return;i.querySelectorAll("span[data-w]").forEach(s=>{var c;let a=parseFloat((c=s.dataset.w)!=null?c:"0"),l=s.offsetWidth;a>0&&l>0&&(s.style.transform=`scaleX(${a/l})`)})},[t,e,n]),Up("div",{ref:r,className:"pdf-text-layer",style:{position:"absolute",inset:0,zIndex:4,cursor:"text",userSelect:"text",WebkitUserSelect:"text",lineHeight:1},children:[ql("style",{children:".pdf-text-layer ::selection{background:rgba(37,99,235,0.30)}"}),t.map((i,o)=>{var a;if(!i.text)return null;let s=Qe(i.pdfX,i.pdfY+i.height,e,n);return ql("span",{"data-w":i.width*e,style:{position:"absolute",left:`${s.x}px`,top:`${s.y}px`,fontSize:`${Math.max(1,i.fontSize*e)}px`,fontFamily:(a=i.fontFamily)!=null?a:"sans-serif",color:"transparent",whiteSpace:"pre",transformOrigin:"0 0",pointerEvents:"auto"},children:i.text},o)})]})}var zs=(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,Jl=(t,e,n)=>{let r=Math.max(n.pdfX-t,0,t-(n.pdfX+n.width)),i=Math.max(n.pdfY-e,0,e-(n.pdfY+n.height));return Math.hypot(r,i)},Zl=(t,e,n=5)=>{var a,l;if(!e||e.length===0)return null;let r=[...e].sort((c,d)=>{var f,m;let h=((f=d.contentStreamIndex)!=null?f:0)-((m=c.contentStreamIndex)!=null?m:0);return h!==0?h:c.width*c.height-d.width*d.height});for(let c of r){let d=Math.max(n,c.fontSize*.35);if((a=c.glyphs)==null?void 0:a.some(f=>zs(t.x,t.y,f,d)))return c}let i=r.find(c=>zs(t.x,t.y,c,Math.max(n,c.fontSize*.25)));if(i)return i;let o=null,s=Number.POSITIVE_INFINITY;for(let c of e){let d=(l=c.glyphs)==null?void 0:l.reduce((p,b)=>Math.min(p,Jl(t.x,t.y,b)),Number.POSITIVE_INFINITY),h=Jl(t.x,t.y,c),f=Math.abs(t.y-c.pdfBaselineY)*.2,m=Math.min(d!=null?d:Number.POSITIVE_INFINITY,h+f);m<s&&(s=m,o=c)}return o&&s<=Math.max(n,o.fontSize*.5)?o:null},Yi=(t,e,n=3)=>{if(!e||e.length===0)return null;let r=e.filter(i=>zs(t.x,t.y,i,n));return r.length===0?null:(r.sort((i,o)=>o.spanEnd!==i.spanEnd?o.spanEnd-i.spanEnd:i.width*i.height-o.width*o.height),r[0])};var $p=(t,e,n)=>{let r=t.canvasX/n,i=Math.max(1,t.canvasWidth/n),o=Math.max(1,t.canvasHeight/n),s=e-(t.canvasY+t.canvasHeight)/n,a=e-t.canvasBaselineY/n;return{x:r,y:s,width:i,height:o,baselineY:a}},Ql=(t,e,n,r,i,o)=>({pdfX:t/o,pdfY:i-(e+r)/o,width:Math.max(.5,n/o),height:Math.max(.5,r/o)}),ed=(t,e,n,r)=>({kind:"image",pageIndex:e,...Ql(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}),td=(t,e,n,r)=>({kind:"graphic",pageIndex:e,...Ql(t.canvasX,t.canvasY,t.canvasWidth,t.canvasHeight,n,r),spanStart:t.operatorStart,spanEnd:t.operatorEnd,ctm:[...t.ctmAtStart],fromXObject:t.fromXObject}),nd=(t,e,n,r)=>{let i=$p(t,n,r);return{pageIndex:e,text:t.text,pdfX:i.x,pdfY:i.y,pdfBaselineY:i.baselineY,width:i.width,height:i.height,fontSize:Math.max(6,t.fontSize),fontCapHeight:t.fontCapHeight,fontName:t.fontName,fontFamily:t.fontFamily,color:t.fillColor,streamOperatorIndices:[t.streamOperatorIndex],fromXObject:t.fromXObject,invisible:t.invisible,glyphs:t.glyphs.map(o=>({char:o.char,pdfX:o.canvasX/r,pdfY:n-(o.canvasY+o.canvasHeight)/r,pdfBaselineY:n-o.canvasBaselineY/r,width:Math.max(1,o.canvasWidth/r),height:Math.max(1,o.canvasHeight/r)}))}};var rd=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}`},id=(t,e,n)=>{var i,o;if(!((i=t.glyphs)!=null&&i.length)||!((o=e.glyphs)!=null&&o.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},Gr=t=>{var s,a,l;if(!t.length)return[];let e=[...t].sort((c,d)=>Math.abs(d.pdfBaselineY-c.pdfBaselineY)>2?d.pdfBaselineY-c.pdfBaselineY:c.pdfX-d.pdfX),n=[];e.forEach(c=>{let d=Math.max(2,c.height*.45),h=n[n.length-1];if(!h||Math.abs(h.baselineY-c.pdfBaselineY)>d){n.push({baselineY:c.pdfBaselineY,runs:[c]});return}h.runs.push(c),h.baselineY=(h.baselineY*(h.runs.length-1)+c.pdfBaselineY)/h.runs.length});let r=[];n.forEach(c=>{var f,m,p,b,y,k,w,P,S,R;let d=[...c.runs].sort((I,F)=>I.pdfX-F.pdfX);if(!d.length)return;let h={...d[0]};for(let I=1;I<d.length;I+=1){let F=d[I],A=F.pdfX-(h.pdfX+h.width),G=Math.max(1,h.fontSize*.15),Y=Math.max(2,h.fontSize*.6);if(!(((f=h.contentStreamIndex)!=null?f:0)===((m=F.contentStreamIndex)!=null?m:0))){r.push(h),h={...F};continue}if(rd(h)!==rd(F)){r.push(h),h={...F};continue}A<=G?h={...h,text:`${h.text}${F.text}`,width:F.pdfX+F.width-h.pdfX,height:Math.max(h.height,F.height),glyphs:id(h,F,!1),streamOperatorIndices:[...(p=h.streamOperatorIndices)!=null?p:[],...(b=F.streamOperatorIndices)!=null?b:[]],fromXObject:((y=h.fromXObject)!=null?y:!1)||((k=F.fromXObject)!=null?k:!1)}:A<=Y?h={...h,text:`${h.text} ${F.text}`,width:F.pdfX+F.width-h.pdfX,height:Math.max(h.height,F.height),glyphs:id(h,F,!0),streamOperatorIndices:[...(w=h.streamOperatorIndices)!=null?w:[],...(P=F.streamOperatorIndices)!=null?P:[]],fromXObject:((S=h.fromXObject)!=null?S:!1)||((R=F.fromXObject)!=null?R:!1)}:(r.push(h),h={...F})}r.push(h)});let i=(c,d)=>`${c!=null?c:0}:${d}`,o=new Map;for(let c of r)for(let d of new Set((s=c.streamOperatorIndices)!=null?s:[])){let h=i(c.contentStreamIndex,d);o.set(h,((a=o.get(h))!=null?a:0)+1)}for(let c of r)c.sharedOperator=((l=c.streamOperatorIndices)!=null?l:[]).some(d=>{var h;return((h=o.get(i(c.contentStreamIndex,d)))!=null?h:0)>1});return r};var _p=new Set(["show_string","show_strings","next_line_show_string","set_spacing_next_line_show_string"]),od=t=>t.reduce((e,n)=>_p.has(n.op)?e+1:e,0),sd=(t,e)=>{var o,s;if(!t)return null;let n=a=>a&&$e(a)?e(a):a,r=n(t.entries.get("XObject"));if(!r||!Q(r))return null;let i=null;for(let a of r.entries.values()){let l=n(a);if(!l||!he(l))continue;let c=(o=V(n(l.dict.entries.get("Width"))))!=null?o:0,d=(s=V(n(l.dict.entries.get("Height"))))!=null?s:0;c>0&&d>0&&(!i||c*d>i.w*i.h)&&(i={w:c,h:d})}return i},ad=t=>{var a,l,c;let e=(a=t.maxScale)!=null?a:4,n=(l=t.maxCanvasPx)!=null?l:3e3,r=(c=t.textThreshold)!=null?c:10,i=t.baseScale;if(!!t.imageDims&&t.textShowCount<r&&t.imageDims){let d=Math.max(t.imageDims.w/t.pageWidth,t.imageDims.h/t.pageHeight);i=Math.min(Math.max(d,t.baseScale),e)}let s=Math.min(n/t.pageWidth,n/t.pageHeight);return Math.min(i,s)};function cd(t,e,n,r){var s;let i=r>0?r:1,o=[];for(let a of t){let l=((s=a.text)!=null?s:"").trim();if(!l)continue;let c=Math.max(1,a.width/i),d=Math.max(1,a.height/i),h=a.x/i,f=n-(a.y+a.height)/i,m=f+d*.2;o.push({text:l,pdfX:h,pdfY:f,width:c,height:d,pdfBaselineY:m,fontSize:Math.max(4,d*.78),fontName:"Helvetica",color:{r:0,g:0,b:0},pageIndex:e,ocr:!0})}return o}var zp={a:"e",b:"q",c:"c",d:"p",e:"a",f:"J",g:"b",h:"y",i:"r",j:"f",k:"k",l:"l",m:"w",n:"u",o:"o",p:"d",q:"b",r:"J",s:"s",t:"l",u:"n",v:"v",w:"m",x:"x",y:"h",z:"z",A:"V",B:"8",C:"O",D:"p",E:"3",F:"J",G:"9",H:"H",I:"I",J:"f",K:"k",L:"7",M:"W",N:"N",O:"O",P:"d",Q:"O",R:"8",S:"S",T:"1",U:"R",V:"A",W:"M",X:"X",Y:"A",Z:"Z",0:"0",1:"l",2:"2",3:"E",4:"h",5:"S",6:"9",7:"L",8:"8",9:"6","(":")",")":"(","[":"]","]":"[","^":"v","'":",",",":"'",".":".","-":"-","/":"/",":":":",";":";",_:"_"," ":" "},dd=t=>{var e;return(e=zp[t])!=null?e:t},ud=t=>{let e="";for(let n=t.length-1;n>=0;n-=1)e+=dd(t[n]);return e},Xp=new Set(["the","and","for","has","have","been","not","are","with","this","from","was","that","you","all","can","will","would","there","his","her","our","out","who","get","may","any","one","two","which","their","were","when","them","into","than","then","also","such","form","name","date","number","account","member","fund","funds","transfer","signature","previous","scheme","employee","employer","above","below","details","option","request","generated","portal","approved","uploaded","establishment","organisation","organization"]),ld=t=>{let e=t.toLowerCase().split(/[^a-z]+/).filter(r=>r.length>=3);if(e.length===0)return 0;let n=0;for(let r of e)Xp.has(r)&&(n+=1);return n/e.length},Yp=.03,Wp=.035,Hp=2,Gp=24,fd=(t,e)=>{let n=t.map(d=>d.text).join(" ");if(n.replace(/[^A-Za-z]/g,"").length<Gp)return"no-text";let i=ld(n);if(i>=Yp)return"normal";let o=t.filter(d=>d.invisible),s=o.length>0?o:t,a=o.length>=t.length*.6,l=s.map(d=>ud(d.text)).join(" "),c=ld(l);return e&&a&&c>=Wp&&c>i*Hp?"rotated-garbage":"normal"},Xs=t=>t.map(e=>{let n=ud(e.text),r=e.glyphs;if(r&&r.length>0){let i=[...r].sort((s,a)=>s.pdfX-a.pdfX),o=i.length;r=i.map((s,a)=>({...s,char:dd(i[o-1-a].char)}))}return{...e,text:n,glyphs:r,recovered:!0}}),Vp=()=>!1,hd={id:"local-unrotate",label:"Recover text",isAvailable:()=>!0,recover:async t=>{let e=t.runs.filter(r=>r.invisible),n=e.length>0?e:t.runs;return Xs(n)}},Kp={id:"ocr",label:"Recognize text (OCR)",isAvailable:()=>Vp(),recover:async t=>{if(!t.runServerOcr)throw new Error("OCR recovery is not wired in this context");return t.runServerOcr()}},qp=[Kp,hd],md=()=>{var t;return(t=qp.find(e=>e.isAvailable()))!=null?t:hd};var Wi=()=>({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 pd=t=>t===" "||t===" "||t==="\r"||t===`
|
|
39
|
+
`||t==="\f"||t==="\0";function xd(t){let e=[],n=[e],r=0;for(;r<t.length;){let i=t[r];if(pd(i)){r++;continue}if(i==="%"){for(;r<t.length&&t[r]!==`
|
|
40
|
+
`&&t[r]!=="\r";)r++;continue}if(i==="{"){let l=[];n[n.length-1].push(l),n.push(l),r++;continue}if(i==="}"){if(n.length===1)throw new Error("Unbalanced } in PostScript function");n.pop(),r++;continue}let o=r;for(;o<t.length&&!pd(t[o])&&t[o]!=="{"&&t[o]!=="}"&&t[o]!=="%";)o++;let s=t.slice(r,o);r=o;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 Ys=Math.PI/180;function Se(t,e){if(typeof t!="number")throw new Error(`${e}: expected number`);return t}function at(t,e){if(typeof t!="number")throw new Error(`${e}: expected integer`);return Math.trunc(t)}function gd(t,e){if(typeof t!="boolean")throw new Error(`${e}: expected boolean`);return t}function bd(t,e,n){let r=[...e],i=0,o=h=>{if(r.length>=100)throw new Error("PostScript stack overflow");r.push(h)},s=h=>{let f=r.pop();if(f===void 0)throw new Error(`${h}: stack underflow`);return f},a=h=>{let f=s(h);if(!Array.isArray(f))throw new Error(`${h}: expected procedure`);return f},l=h=>{for(let f of h){if(++i>1e4)throw new Error("PostScript op budget exceeded");if(typeof f=="number"){o(f);continue}if(Array.isArray(f)){o(f);continue}switch(f){case"add":{let m=Se(s(f),f),p=Se(s(f),f);o(p+m);break}case"sub":{let m=Se(s(f),f),p=Se(s(f),f);o(p-m);break}case"mul":{let m=Se(s(f),f),p=Se(s(f),f);o(p*m);break}case"div":{let m=Se(s(f),f),p=Se(s(f),f);o(m===0?0:p/m);break}case"idiv":{let m=at(s(f),f),p=at(s(f),f);o(m===0?0:Math.trunc(p/m));break}case"mod":{let m=at(s(f),f),p=at(s(f),f);o(m===0?0:p%m);break}case"neg":o(-Se(s(f),f));break;case"abs":o(Math.abs(Se(s(f),f)));break;case"ceiling":o(Math.ceil(Se(s(f),f)));break;case"floor":o(Math.floor(Se(s(f),f)));break;case"round":o(Math.round(Se(s(f),f)));break;case"truncate":o(Math.trunc(Se(s(f),f)));break;case"sqrt":o(Math.sqrt(Math.max(0,Se(s(f),f))));break;case"sin":o(Math.sin(Se(s(f),f)*Ys));break;case"cos":o(Math.cos(Se(s(f),f)*Ys));break;case"atan":{let m=Se(s(f),f),p=Se(s(f),f),b=Math.atan2(p,m)/Ys;b<0&&(b+=360),o(b);break}case"exp":{let m=Se(s(f),f),p=Se(s(f),f);o(Math.pow(p,m));break}case"ln":o(Math.log(Math.max(Number.MIN_VALUE,Se(s(f),f))));break;case"log":o(Math.log10(Math.max(Number.MIN_VALUE,Se(s(f),f))));break;case"cvi":o(Math.trunc(Se(s(f),f)));break;case"cvr":o(Se(s(f),f));break;case"eq":{let m=s(f),p=s(f);o(p===m);break}case"ne":{let m=s(f),p=s(f);o(p!==m);break}case"gt":{let m=Se(s(f),f),p=Se(s(f),f);o(p>m);break}case"ge":{let m=Se(s(f),f),p=Se(s(f),f);o(p>=m);break}case"lt":{let m=Se(s(f),f),p=Se(s(f),f);o(p<m);break}case"le":{let m=Se(s(f),f),p=Se(s(f),f);o(p<=m);break}case"and":{let m=s(f),p=s(f);o(typeof p=="boolean"&&typeof m=="boolean"?p&&m:at(p,f)&at(m,f));break}case"or":{let m=s(f),p=s(f);o(typeof p=="boolean"&&typeof m=="boolean"?p||m:at(p,f)|at(m,f));break}case"xor":{let m=s(f),p=s(f);o(typeof p=="boolean"&&typeof m=="boolean"?p!==m:at(p,f)^at(m,f));break}case"not":{let m=s(f);o(typeof m=="boolean"?!m:~at(m,f));break}case"bitshift":{let m=at(s(f),f),p=at(s(f),f);o(m>=0?p<<m:p>>-m);break}case"true":o(!0);break;case"false":o(!1);break;case"pop":s(f);break;case"exch":{let m=s(f),p=s(f);o(m),o(p);break}case"dup":{let m=s(f);o(m),o(m);break}case"copy":{let m=at(s(f),f);if(m<0||m>r.length)throw new Error("copy: bad count");let p=r.length-m;for(let b=0;b<m;b++)o(r[p+b]);break}case"index":{let m=at(s(f),f);if(m<0||m>=r.length)throw new Error("index: out of range");o(r[r.length-1-m]);break}case"roll":{let m=at(s(f),f),p=at(s(f),f);if(p<0||p>r.length)throw new Error("roll: bad count");if(p>0&&m!==0){let b=r.splice(r.length-p,p),y=(m%p+p)%p;r.push(...b.slice(p-y),...b.slice(0,p-y))}break}case"if":{let m=a(f);gd(s(f),f)&&l(m);break}case"ifelse":{let m=a(f),p=a(f),b=gd(s(f),f);l(b?p:m);break}default:throw new Error(`Unknown PostScript operator: ${f}`)}}};l(t);let c=Math.floor(n.length/2);if(r.length<c)throw new Error("PostScript function returned too few values");return r.slice(r.length-c).map((h,f)=>{if(typeof h!="number"&&typeof h!="boolean")throw new Error("PostScript function returned a non-numeric value");let m=typeof h=="number"?h:h?1:0,p=n[f*2],b=n[f*2+1];return Math.max(p,Math.min(b,m))})}var Hi=V,Wt=t=>!t||!ue(t)?null:t.items.map(e=>{var n;return(n=Hi(e))!=null?n:0}),lt=(t,e)=>{if(t){if(!$e(t))return t;try{return e(t)}catch{return}}},yd=new WeakMap,Jp=(t,e,n)=>{var l;let r=e*n,i=r>>3,o=r&7,s=n,a=0;for(;s>0;){let c=8-o,d=Math.min(c,s),f=((l=t[i])!=null?l:0)>>c-d&(1<<d)-1;a=a*(1<<d)+f,s-=d,o+=d,o===8&&(o=0,i++)}return a},Zp=(t,e)=>t.map((n,r)=>{let i=e[r*2],o=e[r*2+1];return i===void 0||o===void 0?n:Math.max(i,Math.min(o,n))}),Gi=(t,e,n)=>{var c,d,h,f,m,p,b,y,k,w,P,S,R,I,F,A,G,Y,E,ee,ne,O,ge,fe,Oe,Te;let r=lt(t,n);if(!r)return null;let i=he(r)?r.dict:Q(r)?r:null;if(!i)return null;let o=Math.floor((c=Hi(lt(i.entries.get("FunctionType"),n)))!=null?c:-1),s=(d=Wt(lt(i.entries.get("Domain"),n)))!=null?d:[0,1],a=Math.max(1,Math.floor(s.length/2)),l=[];for(let _=0;_<a;_++){let ce=(h=e[_])!=null?h:0,ae=(f=s[_*2])!=null?f:0,W=(m=s[_*2+1])!=null?m:1;l.push(Math.max(Math.min(ae,W),Math.min(Math.max(ae,W),ce)))}if(o===2){let _=(p=Hi(lt(i.entries.get("N"),n)))!=null?p:1,ce=(b=Wt(lt(i.entries.get("C0"),n)))!=null?b:[0],ae=(y=Wt(lt(i.entries.get("C1"),n)))!=null?y:[1],W=Math.pow(l[0],_);return ce.map((me,xe)=>{var be;return me+W*(((be=ae[xe])!=null?be:1)-me)})}if(o===0){if(!he(r))return null;let _=((k=Wt(lt(i.entries.get("Size"),n)))!=null?k:[2]).map(De=>Math.max(1,Math.floor(De)));if(_.length<a||a>8)return null;let ce=Math.floor((w=Hi(lt(i.entries.get("BitsPerSample"),n)))!=null?w:8);if(![1,2,4,8,12,16,24,32].includes(ce))return null;let ae=Wt(lt(i.entries.get("Range"),n));if(!ae||ae.length<2)return null;let W=Math.floor(ae.length/2),me=[];for(let De=0;De<a;De++)me.push(0,_[De]-1);let xe=(P=Wt(lt(i.entries.get("Encode"),n)))!=null?P:me,be=(S=Wt(lt(i.entries.get("Decode"),n)))!=null?S:ae,Ie=ce===32?4294967295:(1<<ce)-1,Me;try{Me=Pe.decodeStreamSync(r)}catch{return null}let Ke=[],et=[];for(let De=0;De<a;De++){let it=(R=s[De*2])!=null?R:0,pt=(I=s[De*2+1])!=null?I:1,je=(F=xe[De*2])!=null?F:0,qt=(A=xe[De*2+1])!=null?A:_[De]-1,Jt=pt!==it?(l[De]-it)/(pt-it):0,kr=Math.max(0,Math.min(_[De]-1,je+Jt*(qt-je))),Pr=Math.min(_[De]-1,Math.floor(kr));Ke.push(Pr),et.push(Math.max(0,Math.min(1,kr-Pr)))}let qe=[],Rt=1;for(let De=0;De<a;De++)qe.push(Rt),Rt*=_[De];let ve=new Array(W).fill(0),tt=1<<a;for(let De=0;De<tt;De++){let it=1,pt=0;for(let je=0;je<a;je++)if(De>>je&1){if(et[je]===0){it=0;break}it*=et[je],pt+=Math.min(_[je]-1,Ke[je]+1)*qe[je]}else it*=1-et[je],pt+=Ke[je]*qe[je];if(it!==0)for(let je=0;je<W;je++)ve[je]+=it*Jp(Me,pt*W+je,ce)}let Kt=ve.map((De,it)=>{var qt,Jt;let pt=(qt=be[it*2])!=null?qt:0,je=(Jt=be[it*2+1])!=null?Jt:1;return pt+De/Ie*(je-pt)});return Zp(Kt,ae)}if(o===3){let _=(G=Wt(lt(i.entries.get("Bounds"),n)))!=null?G:[],ce=(Y=Wt(lt(i.entries.get("Encode"),n)))!=null?Y:[],ae=lt(i.entries.get("Functions"),n);if(!ae||!ue(ae))return null;let W=ae.items,me=l[0],xe=0;for(let qe=0;qe<_.length&&me>=_[qe];qe++)xe=qe+1;let be=xe===0?(E=s[0])!=null?E:0:(ne=(ee=_[xe-1])!=null?ee:s[0])!=null?ne:0,Ie=xe<_.length?(ge=(O=_[xe])!=null?O:s[1])!=null?ge:1:(fe=s[1])!=null?fe:1,Me=(Oe=ce[xe*2])!=null?Oe:0,Ke=(Te=ce[xe*2+1])!=null?Te:1,et=be===Ie?Me:Me+(me-be)/(Ie-be)*(Ke-Me);return Gi(W[xe],[et],n)}if(o===4){if(!he(r))return null;let _=Wt(lt(i.entries.get("Range"),n));if(!_||_.length<2)return null;try{let ce=yd.get(r);if(!ce){let ae=new TextDecoder("latin1").decode(Pe.decodeStreamSync(r));ce=xd(ae),yd.set(r,ce)}return bd(ce,l,_)}catch{return null}}return null},Vi=(t,e,n)=>Gi(t,[e],n),Ws=(t,e,n)=>{let r=lt(t,n);if(!r)return null;if(ue(r)){let i=[];for(let o of r.items){let s=Gi(o,e,n);if(!s)return null;i.push(...s)}return i}return Gi(r,e,n)};var wd=t=>Math.max(1,Math.min(2048,Math.ceil(t)));function vd(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 i=Math.hypot(r[0],r[1]),o=Math.hypot(r[2],r[3]);if(i<1e-12||o<1e-12)return null;let s=wd(Math.abs(e)*i),a=wd(Math.abs(n)*o),[l,c]=t,d=[s/e,0,0,-a/n,-l*s/e,(c+n)*a/n],h=mr(d);return h?{cellPxW:s,cellPxH:a,contentTransform:d,paintTransform:h}:null}var br=5e4,Gs=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 i;let n=0,r=e;for(;r>0;){let o=this.bitPos>>3,a=8-(this.bitPos&7),l=Math.min(a,r),d=((i=this.bytes[o])!=null?i:0)>>a-l&(1<<l)-1;n=n*(1<<l)+d,this.bitPos+=l,r-=l}return n}alignToByte(){this.bitPos=this.bitPos+7&-8}},Qp=t=>t>=32?4294967295:(1<<t)-1,Hs=(t,e,n,r)=>n+t/Qp(e)*(r-n);function kd(t,e,n,r){var S;let i=new Gs(n),o=[],{bitsPerCoordinate:s,bitsPerComponent:a,bitsPerFlag:l,decode:c,numColorComponents:d}=e;if(c.length<4+d*2)return[];let h=()=>[Hs(i.read(s),s,c[0],c[1]),Hs(i.read(s),s,c[2],c[3])],f=()=>{let R=[];for(let I=0;I<d;I++)R.push(Hs(i.read(a),a,c[4+I*2],c[5+I*2]));return r(R)},m=2*s+d*a;if(t===4){let R=l+m,I=null,F=null,A=null,G=()=>{let Y=i.read(l),[E,ee]=h(),ne=f();return i.alignToByte(),{flag:Y,v:{x:E,y:ee,color:ne}}};for(;i.remainingBits>=R&&o.length<br;){let Y=G();if(Y.flag===0||I===null||F===null||A===null){if(I=Y.v,i.remainingBits<R||(F=G().v,i.remainingBits<R))break;A=G().v}else Y.flag===1?(I=F,F=A,A=Y.v):(F=A,A=Y.v);Vr(o,I,F,A)}return o}if(t===5){let R=Math.max(2,Math.floor((S=e.verticesPerRow)!=null?S:2)),I=[];for(;i.remainingBits>=R*m;){let F=[];for(let A=0;A<R;A++){let[G,Y]=h();F.push({x:G,y:Y,color:f()})}if(I.push(F),I.length*R>br)break}for(let F=0;F+1<I.length&&o.length<br;F++)for(let A=0;A+1<R&&o.length<br;A++)Vr(o,I[F][A],I[F][A+1],I[F+1][A]),Vr(o,I[F][A+1],I[F+1][A+1],I[F+1][A]);return o}let p=t===6?12:16,b=t===6?8:12,y=null,k=null,w=p*2*s+4*d*a,P=b*2*s+2*d*a;for(;i.remainingBits>=l+P&&o.length<br;){let R=i.read(l),I,F;if(R===0||!y||!k){if(i.remainingBits<w)break;I=[];for(let A=0;A<p;A++)I.push(h());F=[f(),f(),f(),f()]}else{let A=[];for(let ne=0;ne<b;ne++)A.push(h());let G=f(),Y=f(),E,ee;R===1?(E=[y[3],y[4],y[5],y[6]],ee=[k[1],k[2]]):R===2?(E=[y[6],y[7],y[8],y[9]],ee=[k[2],k[3]]):(E=[y[9],y[10],y[11],y[0]],ee=[k[3],k[0]]),I=[...E,...A],F=[ee[0],ee[1],G,Y]}if(!Number.isFinite(I[0][0]))break;tg(o,I,F),y=I,k=F}return o}var Vr=(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]})},Ki=(t,e,n,r,i)=>{let o=1-i,s=o*o*o,a=3*o*o*i,l=3*o*i*i,c=i*i*i;return[s*t[0]+a*e[0]+l*n[0]+c*r[0],s*t[1]+a*e[1]+l*n[1]+c*r[1]]},eg=6,tg=(t,e,n)=>{let[r,i,o,s,a,l,c,d,h,f,m,p]=e,[b,y,k,w]=n,P=(F,A)=>{let G=Ki(r,i,o,s,A),Y=Ki(f,h,d,c,A),E=Ki(r,p,m,f,F),ee=Ki(s,a,l,c,F),ne=(1-F)*G[0]+F*Y[0]+(1-A)*E[0]+A*ee[0]-((1-F)*(1-A)*r[0]+F*(1-A)*f[0]+(1-F)*A*s[0]+F*A*c[0]),O=(1-F)*G[1]+F*Y[1]+(1-A)*E[1]+A*ee[1]-((1-F)*(1-A)*r[1]+F*(1-A)*f[1]+(1-F)*A*s[1]+F*A*c[1]);return[ne,O]},S=(F,A)=>[(1-F)*(1-A)*b[0]+(1-F)*A*y[0]+F*A*k[0]+F*(1-A)*w[0],(1-F)*(1-A)*b[1]+(1-F)*A*y[1]+F*A*k[1]+F*(1-A)*w[1],(1-F)*(1-A)*b[2]+(1-F)*A*y[2]+F*A*k[2]+F*(1-A)*w[2]],R=eg,I=[];for(let F=0;F<=R;F++){let A=[];for(let G=0;G<=R;G++){let Y=G/R,E=F/R,[ee,ne]=P(Y,E);A.push({x:ee,y:ne,color:S(Y,E)})}I.push(A)}for(let F=0;F<R;F++)for(let A=0;A<R;A++){if(t.length+2>br)return;Vr(t,I[F][A],I[F][A+1],I[F+1][A]),Vr(t,I[F][A+1],I[F+1][A+1],I[F+1][A])}};function Pd(t,e,n,r){let i=new Uint8ClampedArray(n*r*4),o=(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,l,c]=s.p.map(([b,y])=>o(b,y)),d=(l[0]-a[0])*(c[1]-a[1])-(l[1]-a[1])*(c[0]-a[0]);if(Math.abs(d)<1e-9)continue;let h=Math.max(0,Math.floor(Math.min(a[0],l[0],c[0]))),f=Math.min(n-1,Math.ceil(Math.max(a[0],l[0],c[0]))),m=Math.max(0,Math.floor(Math.min(a[1],l[1],c[1]))),p=Math.min(r-1,Math.ceil(Math.max(a[1],l[1],c[1])));for(let b=m;b<=p;b++)for(let y=h;y<=f;y++){let k=y+.5,w=b+.5,P=((l[0]-k)*(c[1]-w)-(l[1]-w)*(c[0]-k))/d,S=((c[0]-k)*(a[1]-w)-(c[1]-w)*(a[0]-k))/d,R=1-P-S;if(P<-1e-6||S<-1e-6||R<-1e-6)continue;let I=(b*n+y)*4;i[I]=255*(P*s.c[0][0]+S*s.c[1][0]+R*s.c[2][0]),i[I+1]=255*(P*s.c[0][1]+S*s.c[1][1]+R*s.c[2][1]),i[I+2]=255*(P*s.c[0][2]+S*s.c[1][2]+R*s.c[2][2]),i[I+3]=255}}return i}var ng=12,rg=(t,e,n)=>t.minX-n<=e.maxX&&e.minX-n<=t.maxX&&t.minY-n<=e.maxY&&e.minY-n<=t.maxY,ig=(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 Dd(t,e,n,r){if(!t.length)return[];let i=Math.max(2,.01*Math.hypot(n,r)),o=[...e].sort((d,h)=>d-h),s=(d,h)=>{let f=0,m=o.length-1;for(;f<=m;){let p=f+m>>1,b=o[p];if(b<=d)f=p+1;else if(b>=h)m=p-1;else return!0}return!1},a=[],l=null;for(let d of t)l!==null&&d.fromXObject===l.fromXObject&&d.pathStartIndex-l.operatorEnd<=ng&&!s(l.operatorEnd,d.pathStartIndex)&&rg(l.bbox,d.bbox,i)&&l?(l.bbox=ig(l.bbox,d.bbox),l.operatorEnd=Math.max(l.operatorEnd,d.paintIndex),l.operatorStart=Math.min(l.operatorStart,d.pathStartIndex),l.paintOperatorIndices.push(d.paintIndex)):(l&&a.push(l),l={bbox:{...d.bbox},operatorStart:d.pathStartIndex,operatorEnd:d.paintIndex,paintOperatorIndices:[d.paintIndex],ctmAtStart:[...d.ctmAtStart],fromXObject:d.fromXObject});l&&a.push(l);let c=n*r;return a.filter(d=>{let h=d.bbox.maxX-d.bbox.minX,f=d.bbox.maxY-d.bbox.minY;return h>0&&f>0&&h*f<=.9*c})}var Kr=(t,e)=>t[e],Ht=(t,e)=>t[e]<<8|t[e+1],Sd=(t,e)=>t[e]*16777216+(t[e+1]<<16)+(t[e+2]<<8)+t[e+3],Cd=(t,e,n)=>{let r=0;for(let i=0;i<n;i+=1)r=r*256+t[e+i];return r};var og=15,sg=17,ag=1230,cg=1206,lg=1207,qi=(t,e)=>{let n=Ht(t,e);if(n===0)return{offsets:[],count:0,end:e+2};let r=Kr(t,e+2),i=e+3,o=i+(n+1)*r-1,s=[];for(let a=0;a<=n;a+=1)s.push(o+Cd(t,i+a*r,r));return{offsets:s,count:n,end:s[n]}},dg=(t,e,n)=>{let r=new Map,i=[],o=e;for(;o<n;){let s=t[o];if(s<=21){let a=s;o+=1,s===12&&(a=1200+t[o],o+=1),r.set(a,i),i=[]}else if(s===28)i.push((t[o+1]<<8|t[o+2])<<16>>16),o+=3;else if(s===29)i.push(t[o+1]<<24|t[o+2]<<16|t[o+3]<<8|t[o+4]),o+=5;else if(s===30){o+=1;let a="",l=!1;for(;o<n&&!l;){let c=t[o];o+=1;for(let d of[c>>4,c&15])if(d<=9)a+=String(d);else if(d===10)a+=".";else if(d===11)a+="E";else if(d===12)a+="E-";else if(d===14)a+="-";else if(d===15){l=!0;break}}i.push(parseFloat(a)||0)}else s>=32&&s<=246?(i.push(s-139),o+=1):s>=247&&s<=250?(i.push((s-247)*256+t[o+1]+108),o+=2):s>=251&&s<=254?(i.push(-(s-251)*256-t[o+1]-108),o+=2):o+=1}return r},ug=(t,e,n)=>{let r=new Array(n).fill(0);if(e===0){for(let a=1;a<n;a+=1)r[a]=a;return r}if(e===1||e===2)return null;let i=Kr(t,e),o=e+1,s=1;if(i===0)for(;s<n;)r[s]=Ht(t,o),o+=2,s+=1;else if(i===1||i===2){let a=i===1?1:2;for(;s<n;){let l=Ht(t,o);o+=2;let c=a===1?Kr(t,o):Ht(t,o);o+=a;for(let d=0;d<=c&&s<n;d+=1)r[s]=l+d,s+=1}}else return null;return r},fg=t=>{var e,n,r,i,o;try{if(t.length<4)return null;let s=Kr(t,2),a=qi(t,s),l=qi(t,a.end),c=qi(t,l.end);if(l.count<1)return null;let d=dg(t,l.offsets[0],l.offsets[1]);if(d.has(ag)||((n=(e=d.get(cg))==null?void 0:e[0])!=null?n:2)!==2)return null;let f=(r=d.get(sg))==null?void 0:r[0];if(f==null)return null;let p=qi(t,f).count;if(p<1)return null;let b=(o=(i=d.get(og))==null?void 0:i[0])!=null?o:0,y=ug(t,b,p);if(!y)return null;let k=d.get(lg),w=1e3;if(k&&k[0]>0){let P=Math.round(1/k[0]);P>=16&&P<=16384&&(w=P)}return{numGlyphs:p,sids:y,stringIndex:c,bytes:t,unitsPerEm:w}}catch{return null}},kt=class{constructor(){this.buf=[]}u8(e){this.buf.push(e&255)}u16(e){this.u8(e>>8),this.u8(e)}i16(e){this.u16(e&65535)}u32(e){this.u8(e>>>24),this.u8(e>>>16),this.u8(e>>>8),this.u8(e)}i32(e){this.u32(e>>>0)}bytes(e){for(let n=0;n<e.length;n+=1)this.buf.push(e[n])}tag(e){for(let n=0;n<4;n+=1)this.u8(e.charCodeAt(n))}utf16be(e){for(let n=0;n<e.length;n+=1)this.u16(e.charCodeAt(n))}get length(){return this.buf.length}toUint8Array(){return Uint8Array.from(this.buf)}},Fd=t=>{var n,r,i;let e=0;for(let o=0;o<t.length;o+=4){let s=(t[o]<<24)+(((n=t[o+1])!=null?n:0)<<16)+(((r=t[o+2])!=null?r:0)<<8)+((i=t[o+3])!=null?i:0);e=e+(s>>>0)>>>0}return e>>>0},hg=t=>{let e=t.length+1,n=new kt,r=Math.floor(Math.log2(Math.max(1,e))),i=2*2**r,o=16+e*8;n.u16(4),n.u16(o),n.u16(0),n.u16(e*2),n.u16(i),n.u16(r),n.u16(e*2-i);for(let[s]of t)n.u16(s);n.u16(65535),n.u16(0);for(let[s]of t)n.u16(s);n.u16(65535);for(let[s,a]of t)n.u16(a-s&65535);n.u16(1);for(let s=0;s<e;s+=1)n.u16(0);return n.toUint8Array()},mg=t=>{let e=new kt,n=16+t.length*12;e.u16(12),e.u16(0),e.u32(n),e.u32(0),e.u32(t.length);for(let[r,i]of t)e.u32(r),e.u32(r),e.u32(i);return e.toUint8Array()},pg=t=>{let e=t.filter(([d])=>d<=65535),n=t.filter(([d])=>d>65535),r=hg(e),i=n.length?mg(t):null,o=[{platform:0,encoding:3,isFormat12:!1},{platform:3,encoding:1,isFormat12:!1}];i&&(o.push({platform:0,encoding:4,isFormat12:!0}),o.push({platform:3,encoding:10,isFormat12:!0}));let s=4+o.length*8,a=s,l=s+r.length,c=new kt;c.u16(0),c.u16(o.length);for(let d of o)c.u16(d.platform),c.u16(d.encoding),c.u32(d.isFormat12?l:a);return c.bytes(r),i&&c.bytes(i),c.toUint8Array()},gg=t=>{let e=new kt;return e.u32(65536),e.u32(65536),e.u32(0),e.u32(1594834165),e.u16(11),e.u16(t),e.u32(0),e.u32(0),e.u32(0),e.u32(0),e.i16(-t),e.i16(-t),e.i16(2*t),e.i16(2*t),e.u16(0),e.u16(8),e.i16(2),e.i16(0),e.i16(0),e.toUint8Array()},xg=(t,e)=>{let n=new kt;return n.u32(65536),n.i16(Math.round(t*.8)),n.i16(-Math.round(t*.2)),n.i16(0),n.u16(t),n.i16(0),n.i16(0),n.i16(t),n.i16(1),n.i16(0),n.i16(0),n.i16(0),n.i16(0),n.i16(0),n.i16(0),n.i16(0),n.u16(e),n.toUint8Array()},bg=(t,e)=>{let n=new kt;for(let r=0;r<e;r+=1)n.u16(t),n.i16(0);return n.toUint8Array()},yg=t=>{let e=new kt;return e.u32(20480),e.u16(t),e.toUint8Array()},wg=()=>{let t=new kt;return t.u32(196608),t.i32(0),t.i16(-100),t.i16(50),t.u32(0),t.u32(0),t.u32(0),t.u32(0),t.u32(0),t.toUint8Array()},vg=(t,e,n)=>{let r=new kt;r.u16(4),r.i16(Math.round(t*.5)),r.u16(400),r.u16(5),r.u16(0),r.i16(650),r.i16(600),r.i16(0),r.i16(75),r.i16(650),r.i16(600),r.i16(0),r.i16(350),r.i16(50),r.i16(Math.round(t*.25)),r.i16(0);for(let i=0;i<10;i+=1)r.u8(0);return r.u32(0),r.u32(0),r.u32(0),r.u32(0),r.tag("NPDF"),r.u16(64),r.u16(e&65535),r.u16(n&65535),r.i16(Math.round(t*.8)),r.i16(-Math.round(t*.2)),r.i16(0),r.u16(Math.round(t*1)),r.u16(Math.round(t*.25)),r.u32(1),r.u32(0),r.i16(Math.round(t*.5)),r.i16(Math.round(t*.7)),r.u16(0),r.u16(32),r.u16(0),r.toUint8Array()},kg=()=>{let t=[{nameId:1,value:"NamahaPDF Embedded"},{nameId:2,value:"Regular"},{nameId:4,value:"NamahaPDF Embedded"},{nameId:6,value:"NamahaPDF-Embedded"}],e=6+t.length*12,n=new kt;n.u16(0),n.u16(t.length),n.u16(e);let r=0;for(let i of t){let o=i.value.length*2;n.u16(3),n.u16(1),n.u16(1033),n.u16(i.nameId),n.u16(o),n.u16(r),r+=o}for(let i of t)n.utf16be(i.value);return n.toUint8Array()},Pg=t=>{let e=[...t].sort((d,h)=>d.tag<h.tag?-1:d.tag>h.tag?1:0),n=e.length,r=Math.floor(Math.log2(n)),i=16*2**r,o=new kt;o.u32(1330926671),o.u16(n),o.u16(i),o.u16(r),o.u16(n*16-i);let s=12+n*16,a=-1,l=e.map(d=>{let h=d.data.length+3&-4,f={tag:d.tag,data:d.data,offset:s,checksum:Fd(d.data),len:d.data.length};return d.tag==="head"&&(a=s),s+=h,f});for(let d of l)o.tag(d.tag),o.u32(d.checksum),o.u32(d.offset),o.u32(d.len);let c=new Uint8Array(s);c.set(o.toUint8Array(),0);for(let d of l)c.set(d.data,d.offset);if(a>=0){let d=2981146554-Fd(c)>>>0;new DataView(c.buffer).setUint32(a+8,d)}return c},Dg=[0,32,33,34,35,36,37,38,8217,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,8216,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,161,162,163,8260,165,402,167,164,39,8220,171,8249,8250,64257,64258,8211,8224,8225,183,182,8226,8218,8222,8221,187,8230,8240,191,96,180,710,732,175,728,729,168,730,184,733,731,711,8212,198,170,321,216,338,186,230,305,322,248,339,223,185,172,181,8482,208,189,177,222,188,247,166,176,254,190,178,174,8722,240,215,179,169,193,194,196,192,197,195,199,201,202,203,200,205,206,207,204,209,211,212,214,210,213,352,218,219,220,217,221,376,381,225,226,228,224,229,227,231,233,234,235,232,237,238,239,236,241,243,244,246,242,245,353,250,251,252,249,253,255,382,0,0,0,0,0,0,0,0,8229,8228,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64256,64259,64260,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,8210,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],Sg=t=>{var i;let e=t.includes(".")?t.slice(0,t.indexOf(".")):t;if(!e)return null;let n=/^uni([0-9A-Fa-f]{4})/.exec(e);if(n)return parseInt(n[1],16);let r=/^u([0-9A-Fa-f]{4,6})$/.exec(e);return r?parseInt(r[1],16):Array.from(e).length===1&&(i=e.codePointAt(0))!=null?i:null},Cg=(t,e)=>{var a;let n=t.sids[e];if(n<391){let l=(a=Dg[n])!=null?a:0;return l>0?l:null}let r=n-391;if(r<0||r>=t.stringIndex.count)return null;let i=t.stringIndex.offsets[r],o=t.stringIndex.offsets[r+1],s="";for(let l=i;l<o;l+=1)s+=String.fromCharCode(t.bytes[l]);return Sg(s)},Rd=t=>{let e=fg(t);if(!e)return null;let n=new Map;for(let l=1;l<e.numGlyphs;l+=1){let c=Cg(e,l);c!=null&&c>0&&!n.has(c)&&n.set(c,l)}if(n.size===0)return null;let r=[...n.entries()].sort((l,c)=>l[0]-c[0]),i=r[0][0],o=r[r.length-1][0],{unitsPerEm:s,numGlyphs:a}=e;try{return Pg([{tag:"CFF ",data:e.bytes},{tag:"OS/2",data:vg(s,i,Math.min(65535,o))},{tag:"cmap",data:pg(r)},{tag:"head",data:gg(s)},{tag:"hhea",data:xg(s,a)},{tag:"hmtx",data:bg(s,a)},{tag:"maxp",data:yg(a)},{tag:"name",data:kg()},{tag:"post",data:wg()}])}catch{return null}};function Fg(t){return t&&typeof t=="object"&&"type"in t&&t.type==="name"&&"value"in t?String(t.value):""}function Md(t,e){if(!t)return null;let n=s=>{let a=e(s);if(!a||!he(a))return null;try{return Pe.decodeStreamSync(a)}catch{return null}},r=n(t.entries.get("FontFile2"));if(r&&r.length>0)return{bytes:r,kind:"truetype"};let i=e(t.entries.get("FontFile3"));if(i&&he(i)){let s=n(i);if(s&&s.length>0){let l=Fg(i.dict.entries.get("Subtype"))==="OpenType"?"opentype":"cff";return{bytes:s,kind:l}}}let o=n(t.entries.get("FontFile"));return o&&o.length>0?{bytes:o,kind:"type1"}:null}function Rg(t){return t==="truetype"||t==="opentype"}function Mg(t){if(t.length<12)return!1;let e=Ht(t,4),n=-1;for(let i=0;i<e;i+=1){let o=12+i*16;if(o+16>t.length)return!1;if(t[o]===99&&t[o+1]===109&&t[o+2]===97&&t[o+3]===112){n=Sd(t,o+8);break}}if(n<0||n+4>t.length)return!1;let r=Ht(t,n+2);for(let i=0;i<r;i+=1){let o=n+4+i*8;if(o+8>t.length)break;let s=Ht(t,o),a=Ht(t,o+2);if(s===3&&(a===1||a===10)||s===0)return!0}return!1}function Ag(t){let e=2166136261,n=t.length,r=Math.max(1,Math.floor(n/4096));for(let i=0;i<n;i+=r)e^=t[i],e=Math.imul(e,16777619);return e^=n,e=Math.imul(e,16777619),`npf-${(e>>>0).toString(16)}`}function qs(t){let e=null;return Rg(t.kind)?e=t.bytes:t.kind==="cff"&&(e=Rd(t.bytes)),!e||!Mg(e)?null:{family:Ag(t.bytes),bytes:e}}var Vs=new Map,Ks=new Map,Ng=()=>typeof document!="undefined"&&typeof globalThis.FontFace!="undefined"&&!!document.fonts;async function Ad(t){if(!Ng())return null;let e=qs(t);if(!e)return null;let{family:n,bytes:r}=e,i=Vs.get(n);if(i==="loaded")return n;if(i==="failed")return null;let o=Ks.get(n);if(o)return o;let s=r,a=(async()=>{try{let l=s.slice().buffer,c=new FontFace(n,l);return await c.load(),document.fonts.add(c),Vs.set(n,"loaded"),n}catch{return Vs.set(n,"failed"),null}finally{Ks.delete(n)}})();return Ks.set(n,a),a}var Cn=t=>{};var Nd=[[-1,-1],[-1,-1],[7,8],[7,7],[6,6],[6,6],[6,5],[6,5],[4,0],[4,0],[4,0],[4,0],[4,0],[4,0],[4,0],[4,0],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2]],Td=[[-1,-1],[12,-2],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[11,1792],[11,1792],[12,1984],[12,2048],[12,2112],[12,2176],[12,2240],[12,2304],[11,1856],[11,1856],[11,1920],[11,1920],[12,2368],[12,2432],[12,2496],[12,2560]],Ed=[[-1,-1],[-1,-1],[-1,-1],[-1,-1],[8,29],[8,29],[8,30],[8,30],[8,45],[8,45],[8,46],[8,46],[7,22],[7,22],[7,22],[7,22],[7,23],[7,23],[7,23],[7,23],[8,47],[8,47],[8,48],[8,48],[6,13],[6,13],[6,13],[6,13],[6,13],[6,13],[6,13],[6,13],[7,20],[7,20],[7,20],[7,20],[8,33],[8,33],[8,34],[8,34],[8,35],[8,35],[8,36],[8,36],[8,37],[8,37],[8,38],[8,38],[7,19],[7,19],[7,19],[7,19],[8,31],[8,31],[8,32],[8,32],[6,1],[6,1],[6,1],[6,1],[6,1],[6,1],[6,1],[6,1],[6,12],[6,12],[6,12],[6,12],[6,12],[6,12],[6,12],[6,12],[8,53],[8,53],[8,54],[8,54],[7,26],[7,26],[7,26],[7,26],[8,39],[8,39],[8,40],[8,40],[8,41],[8,41],[8,42],[8,42],[8,43],[8,43],[8,44],[8,44],[7,21],[7,21],[7,21],[7,21],[7,28],[7,28],[7,28],[7,28],[8,61],[8,61],[8,62],[8,62],[8,63],[8,63],[8,0],[8,0],[8,320],[8,320],[8,384],[8,384],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[7,27],[7,27],[7,27],[7,27],[8,59],[8,59],[8,60],[8,60],[9,1472],[9,1536],[9,1600],[9,1728],[7,18],[7,18],[7,18],[7,18],[7,24],[7,24],[7,24],[7,24],[8,49],[8,49],[8,50],[8,50],[8,51],[8,51],[8,52],[8,52],[7,25],[7,25],[7,25],[7,25],[8,55],[8,55],[8,56],[8,56],[8,57],[8,57],[8,58],[8,58],[6,192],[6,192],[6,192],[6,192],[6,192],[6,192],[6,192],[6,192],[6,1664],[6,1664],[6,1664],[6,1664],[6,1664],[6,1664],[6,1664],[6,1664],[8,448],[8,448],[8,512],[8,512],[9,704],[9,768],[8,640],[8,640],[8,576],[8,576],[9,832],[9,896],[9,960],[9,1024],[9,1088],[9,1152],[9,1216],[9,1280],[9,1344],[9,1408],[7,256],[7,256],[7,256],[7,256],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[6,16],[6,16],[6,16],[6,16],[6,16],[6,16],[6,16],[6,16],[6,17],[6,17],[6,17],[6,17],[6,17],[6,17],[6,17],[6,17],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[6,14],[6,14],[6,14],[6,14],[6,14],[6,14],[6,14],[6,14],[6,15],[6,15],[6,15],[6,15],[6,15],[6,15],[6,15],[6,15],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7]],Od=[[-1,-1],[-1,-1],[12,-2],[12,-2],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[11,1792],[11,1792],[11,1792],[11,1792],[12,1984],[12,1984],[12,2048],[12,2048],[12,2112],[12,2112],[12,2176],[12,2176],[12,2240],[12,2240],[12,2304],[12,2304],[11,1856],[11,1856],[11,1856],[11,1856],[11,1920],[11,1920],[11,1920],[11,1920],[12,2368],[12,2368],[12,2432],[12,2432],[12,2496],[12,2496],[12,2560],[12,2560],[10,18],[10,18],[10,18],[10,18],[10,18],[10,18],[10,18],[10,18],[12,52],[12,52],[13,640],[13,704],[13,768],[13,832],[12,55],[12,55],[12,56],[12,56],[13,1280],[13,1344],[13,1408],[13,1472],[12,59],[12,59],[12,60],[12,60],[13,1536],[13,1600],[11,24],[11,24],[11,24],[11,24],[11,25],[11,25],[11,25],[11,25],[13,1664],[13,1728],[12,320],[12,320],[12,384],[12,384],[12,448],[12,448],[13,512],[13,576],[12,53],[12,53],[12,54],[12,54],[13,896],[13,960],[13,1024],[13,1088],[13,1152],[13,1216],[10,64],[10,64],[10,64],[10,64],[10,64],[10,64],[10,64],[10,64]],Id=[[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[11,23],[11,23],[12,50],[12,51],[12,44],[12,45],[12,46],[12,47],[12,57],[12,58],[12,61],[12,256],[10,16],[10,16],[10,16],[10,16],[10,17],[10,17],[10,17],[10,17],[12,48],[12,49],[12,62],[12,63],[12,30],[12,31],[12,32],[12,33],[12,40],[12,41],[11,22],[11,22],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[9,15],[9,15],[9,15],[9,15],[9,15],[9,15],[9,15],[9,15],[12,128],[12,192],[12,26],[12,27],[12,28],[12,29],[11,19],[11,19],[11,20],[11,20],[12,34],[12,35],[12,36],[12,37],[12,38],[12,39],[11,21],[11,21],[12,42],[12,43],[10,0],[10,0],[10,0],[10,0],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12]],Bd=[[-1,-1],[-1,-1],[-1,-1],[-1,-1],[6,9],[6,8],[5,7],[5,7],[4,6],[4,6],[4,6],[4,6],[4,5],[4,5],[4,5],[4,5],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2]],Ji=class{constructor(e,n={}){var i;if(!e||typeof e.next!="function")throw new Error('CCITTFaxDecoder - invalid "source" parameter.');this.source=e,this.eof=!1,this.encoding=n.K||0,this.eoline=n.EndOfLine||!1,this.byteAlign=n.EncodedByteAlign||!1,this.columns=n.Columns||1728,this.rows=n.Rows||0,this.eoblock=(i=n.EndOfBlock)!=null?i:!0,this.black=n.BlackIs1||!1,this.codingLine=new Uint32Array(this.columns+1),this.refLine=new Uint32Array(this.columns+2),this.codingLine[0]=this.columns,this.codingPos=0,this.row=0,this.nextLine2D=this.encoding<0,this.inputBits=0,this.inputBuf=0,this.outputBits=0,this.rowsDone=!1,this.err=!1;let r;for(;(r=this._lookBits(12))===0;)this._eatBits(1);r===1&&this._eatBits(12),this.encoding>0&&(this.nextLine2D=!this._lookBits(1),this._eatBits(1))}readNextChar(){if(this.eof)return-1;let e=this.refLine,n=this.codingLine,r=this.columns,i=0,o=0,s=0,a=0;if(this.outputBits===0){if(this.rowsDone&&(this.eof=!0),this.eof)return-1;this.err=!1;let c=0,d=0,h=0;if(this.nextLine2D){for(a=0;n[a]<r;++a)e[a]=n[a];for(e[a++]=r,e[a]=r,n[0]=0,this.codingPos=0,i=0,o=0;n[this.codingPos]<r;)switch(c=this._getTwoDimCode(),c){case 0:this._addPixels(e[i+1],o),e[i+1]<r&&(i+=2);break;case 1:if(c=d=0,o){do c+=h=this._getBlackCode();while(h>=64);do d+=h=this._getWhiteCode();while(h>=64)}else{do c+=h=this._getWhiteCode();while(h>=64);do d+=h=this._getBlackCode();while(h>=64)}for(this._addPixels(n[this.codingPos]+c,o),n[this.codingPos]<r&&this._addPixels(n[this.codingPos]+d,o^1);e[i]<=n[this.codingPos]&&e[i]<r;)i+=2;break;case 7:if(this._addPixels(e[i]+3,o),o^=1,n[this.codingPos]<r)for(++i;e[i]<=n[this.codingPos]&&e[i]<r;)i+=2;break;case 5:if(this._addPixels(e[i]+2,o),o^=1,n[this.codingPos]<r)for(++i;e[i]<=n[this.codingPos]&&e[i]<r;)i+=2;break;case 3:if(this._addPixels(e[i]+1,o),o^=1,n[this.codingPos]<r)for(++i;e[i]<=n[this.codingPos]&&e[i]<r;)i+=2;break;case 2:if(this._addPixels(e[i],o),o^=1,n[this.codingPos]<r)for(++i;e[i]<=n[this.codingPos]&&e[i]<r;)i+=2;break;case 8:if(this._addPixelsNeg(e[i]-3,o),o^=1,n[this.codingPos]<r)for(i>0?--i:++i;e[i]<=n[this.codingPos]&&e[i]<r;)i+=2;break;case 6:if(this._addPixelsNeg(e[i]-2,o),o^=1,n[this.codingPos]<r)for(i>0?--i:++i;e[i]<=n[this.codingPos]&&e[i]<r;)i+=2;break;case 4:if(this._addPixelsNeg(e[i]-1,o),o^=1,n[this.codingPos]<r)for(i>0?--i:++i;e[i]<=n[this.codingPos]&&e[i]<r;)i+=2;break;case-1:this._addPixels(r,0),this.eof=!0;break;default:Cn("bad 2d code"),this._addPixels(r,0),this.err=!0}}else for(n[0]=0,this.codingPos=0,o=0;n[this.codingPos]<r;){if(c=0,o)do c+=h=this._getBlackCode();while(h>=64);else do c+=h=this._getWhiteCode();while(h>=64);this._addPixels(n[this.codingPos]+c,o),o^=1}let f=!1;if(this.byteAlign&&(this.inputBits&=-8),!this.eoblock&&this.row===this.rows-1)this.rowsDone=!0;else{if(c=this._lookBits(12),this.eoline)for(;c!==-1&&c!==1;)this._eatBits(1),c=this._lookBits(12);else for(;c===0;)this._eatBits(1),c=this._lookBits(12);c===1?(this._eatBits(12),f=!0):c===-1&&(this.eof=!0)}if(!this.eof&&this.encoding>0&&!this.rowsDone&&(this.nextLine2D=!this._lookBits(1),this._eatBits(1)),this.eoblock&&f&&this.byteAlign){if(c=this._lookBits(12),c===1){if(this._eatBits(12),this.encoding>0&&(this._lookBits(1),this._eatBits(1)),this.encoding>=0)for(a=0;a<4;++a)c=this._lookBits(12),c!==1&&Cn("bad rtc code: "+c),this._eatBits(12),this.encoding>0&&(this._lookBits(1),this._eatBits(1));this.eof=!0}}else if(this.err&&this.eoline){for(;;){if(c=this._lookBits(13),c===-1)return this.eof=!0,-1;if(c>>1===1)break;this._eatBits(1)}this._eatBits(12),this.encoding>0&&(this._eatBits(1),this.nextLine2D=!(c&1))}this.outputBits=n[0]>0?n[this.codingPos=0]:n[this.codingPos=1],this.row++}let l;if(this.outputBits>=8)l=this.codingPos&1?0:255,this.outputBits-=8,this.outputBits===0&&n[this.codingPos]<r&&(this.codingPos++,this.outputBits=n[this.codingPos]-n[this.codingPos-1]);else{s=8,l=0;do{if(typeof this.outputBits!="number")throw new Error('Invalid /CCITTFaxDecode data, "outputBits" must be a number.');this.outputBits>s?(l<<=s,this.codingPos&1||(l|=255>>8-s),this.outputBits-=s,s=0):(l<<=this.outputBits,this.codingPos&1||(l|=255>>8-this.outputBits),s-=this.outputBits,this.outputBits=0,n[this.codingPos]<r?(this.codingPos++,this.outputBits=n[this.codingPos]-n[this.codingPos-1]):s>0&&(l<<=s,s=0))}while(s)}return this.black&&(l^=255),l}_addPixels(e,n){let r=this.codingLine,i=this.codingPos;e>r[i]&&(e>this.columns&&(Cn("row is wrong length"),this.err=!0,e=this.columns),i&1^n&&++i,r[i]=e),this.codingPos=i}_addPixelsNeg(e,n){let r=this.codingLine,i=this.codingPos;if(e>r[i])e>this.columns&&(Cn("row is wrong length"),this.err=!0,e=this.columns),i&1^n&&++i,r[i]=e;else if(e<r[i]){for(e<0&&(Cn("invalid code"),this.err=!0,e=0);i>0&&e<r[i-1];)--i;r[i]=e}this.codingPos=i}_findTableCode(e,n,r,i){let o=i||0;for(let s=e;s<=n;++s){let a=this._lookBits(s);if(a===-1)return[!0,1,!1];if(s<n&&(a<<=n-s),!o||a>=o){let l=r[a-o];if(l[0]===s)return this._eatBits(s),[!0,l[1],!0]}}return[!1,0,!1]}_getTwoDimCode(){let e=0,n;if(this.eoblock){if(e=this._lookBits(7),n=Nd[e],(n==null?void 0:n[0])>0)return this._eatBits(n[0]),n[1]}else{let r=this._findTableCode(1,7,Nd);if(r[0]&&r[2])return r[1]}return Cn("Bad two dim code"),-1}_getWhiteCode(){let e=0,n;if(this.eoblock){if(e=this._lookBits(12),e===-1)return 1;if(n=e>>5===0?Td[e]:Ed[e>>3],n[0]>0)return this._eatBits(n[0]),n[1]}else{let r=this._findTableCode(1,9,Ed);if(r[0]||(r=this._findTableCode(11,12,Td),r[0]))return r[1]}return Cn("bad white code"),this._eatBits(1),1}_getBlackCode(){let e,n;if(this.eoblock){if(e=this._lookBits(13),e===-1)return 1;if(e>>7===0?n=Od[e]:e>>9===0&&e>>7!==0?n=Id[(e>>1)-64]:n=Bd[e>>7],n[0]>0)return this._eatBits(n[0]),n[1]}else{let r=this._findTableCode(2,6,Bd);if(r[0]||(r=this._findTableCode(7,12,Id,64),r[0])||(r=this._findTableCode(10,13,Od),r[0]))return r[1]}return Cn("bad black code"),this._eatBits(1),1}_lookBits(e){let n;for(;this.inputBits<e;){if((n=this.source.next())===-1)return this.inputBits===0?-1:this.inputBuf<<e-this.inputBits&65535>>16-e;this.inputBuf=this.inputBuf<<8|n,this.inputBits+=8}return this.inputBuf>>this.inputBits-e&65535>>16-e}_eatBits(e){(this.inputBits-=e)<0&&(this.inputBits=0)}};var yr=t=>Number.isFinite(t)?t<0?0:t>1?1:t:0,jd=(t,e,n,r)=>({r:(1-yr(t))*(1-yr(r)),g:(1-yr(e))*(1-yr(r)),b:(1-yr(n))*(1-yr(r))}),Tg=t=>t?typeof t=="string"?t:typeof t=="object"&&"type"in t&&t.type==="name"&&"value"in t?String(t.value):null:null;var Ld=t=>t==="DeviceCMYK"?4:t==="DeviceGray"||t==="Separation"?1:3,Zi=(t,e,n,r,i,o)=>{var d,h,f,m;if(i===8)return t;let s=e*r,a=new Uint8Array(s*n);if(i===16){for(let p=0,b=0;p<a.length;p++,b+=2)a[p]=(d=t[b])!=null?d:0;return a}let l=(1<<i)-1,c=Math.ceil(s*i/8);for(let p=0;p<n;p++){let b=p*c,y=0;for(let k=0;k<s;k++){let w=b+(y>>3),S=8-(y&7),R;if(i<=S)R=((h=t[w])!=null?h:0)>>S-i&l;else{let I=i-S,F=((f=t[w])!=null?f:0)&(1<<S)-1,A=((m=t[w+1])!=null?m:0)>>8-I;R=F<<I|A}a[p*s+k]=o?Math.round(R*255/l):R,y+=i}}return a},Ud=(t,e,n,r)=>{let i=e*n,o=new Uint8ClampedArray(i*4);if(r==="DeviceRGB"){if(t.length<i*3)return null;for(let a=0,l=0;l<o.length;a+=3,l+=4)o[l]=t[a],o[l+1]=t[a+1],o[l+2]=t[a+2],o[l+3]=255;return new ImageData(o,e,n)}if(r==="DeviceGray"){if(t.length<i)return null;for(let a=0,l=0;l<o.length;a+=1,l+=4){let c=t[a];o[l]=c,o[l+1]=c,o[l+2]=c,o[l+3]=255}return new ImageData(o,e,n)}if(r==="DeviceCMYK"){if(t.length<i*4)return null;for(let a=0,l=0;l<o.length;a+=4,l+=4){let c=jd(t[a]/255,t[a+1]/255,t[a+2]/255,t[a+3]/255);o[l]=Math.round(c.r*255),o[l+1]=Math.round(c.g*255),o[l+2]=Math.round(c.b*255),o[l+3]=255}return new ImageData(o,e,n)}let s=Math.floor(t.length/Math.max(1,i));if(s>=3){let a=s;for(let l=0,c=0;l<i;l++,c+=4){let d=l*a;o[c]=t[d],o[c+1]=t[d+1],o[c+2]=t[d+2],o[c+3]=255}return new ImageData(o,e,n)}if(s>=1){let a=r==="Separation"||r==="DeviceN";for(let l=0,c=0;l<i;l++,c+=4){let d=a?255-t[l]:t[l];o[c]=d,o[c+1]=d,o[c+2]=d,o[c+3]=255}return new ImageData(o,e,n)}return null},qr=(t,e,n,r)=>{let i=t.data,o=n*r;for(let s=0;s<o&&s<e.length;s++)i[s*4+3]=e[s]},$d=(t,e,n,r,i)=>{var f,m,p,b,y,k,w,P,S,R,I;if(r.length<4)return null;let o=(f=Tg(r[1]))!=null?f:"DeviceRGB",s=Math.floor((m=V(r[2]))!=null?m:255),a=i(r[3]),l=null;if(a&&he(a))try{l=Pe.decodeStreamSync(a)}catch{}else a&&typeof a=="object"&&"type"in a&&a.type==="string"&&(l=a.value);if(!l)return null;let c=o==="DeviceCMYK"?4:o==="DeviceGray"?1:3,d=e*n,h=new Uint8ClampedArray(d*4);for(let F=0;F<d;F++){let G=Math.min((p=t[F])!=null?p:0,s)*c,Y=0,E=0,ee=0;if(c===3)Y=(b=l[G])!=null?b:0,E=(y=l[G+1])!=null?y:0,ee=(k=l[G+2])!=null?k:0;else if(c===1)Y=E=ee=(w=l[G])!=null?w:0;else if(c===4){let O=jd(((P=l[G])!=null?P:0)/255,((S=l[G+1])!=null?S:0)/255,((R=l[G+2])!=null?R:0)/255,((I=l[G+3])!=null?I:0)/255);Y=Math.round(O.r*255),E=Math.round(O.g*255),ee=Math.round(O.b*255)}let ne=F*4;h[ne]=Y,h[ne+1]=E,h[ne+2]=ee,h[ne+3]=255}return new ImageData(h,e,n)},_d=(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 i=0;i<r.length;i+=4)r[i]=255-r[i],r[i+1]=255-r[i+1],r[i+2]=255-r[i+2]};var Js=null,Zs=()=>Js!=null?Js:Js=import("./pdf.image_decoders.min-ABCYWBEM.js"),Eg=1e8,zd=new Set,Xd=new Set,Yd=new Map,Wd=new Set(["F1","F3","F4"]),Hd=new WeakMap,Og=()=>new Promise(t=>setTimeout(t,0)),wr=class wr{constructor(e,n,r,i,o){this.canvas=e;this.pageWidth=n;this.pageHeight=r;this.scale=i;this.stateStack=[];this.state=Wi();this.atomicLogCount=0;this.commandIndex=0;this.xobjectDepth=0;this.pageResources=null;this.objectLoader=null;this.fontCache=new Map;this.embeddedFamilies=new Map;this.embeddedFontBytes=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.pathOpen=!1;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 l,c,d,h,f,m,p;let s=(l=o==null?void 0:o.debugAtomic)!=null?l:!1,a=e.getContext("2d",{willReadFrequently:s});if(!a)throw new Error("2D context unavailable");a.imageSmoothingEnabled=!0,"imageSmoothingQuality"in a&&(a.imageSmoothingQuality="high"),this.ctx=a,this.baseCtx=a,this.disableClip=(c=o==null?void 0:o.disableClip)!=null?c:!1,this.debug=(d=o==null?void 0:o.debug)!=null?d:!1,this.debugAtomic=s,this.maxAtomicLogs=(h=o==null?void 0:o.maxAtomicLogs)!=null?h:500,this.initialTransform=(f=o==null?void 0:o.initialTransform)!=null?f:null,this.forcedColor=(m=o==null?void 0:o.forcedColor)!=null?m:null,this.patternDepth=(p=o==null?void 0:o.patternDepth)!=null?p:0,e.width=Math.ceil(n*i),e.height=Math.ceil(r*i),o!=null&&o.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=mn(this.forcedColor),this.ctx.strokeStyle=mn(this.forcedColor)),this.applyCurrentTransform(),this.logDebug("init",{pageWidth:n,pageHeight:r,scale:i,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 o=this.debugAtomic&&this.atomicLogCount<this.maxAtomicLogs?this.captureAtomicState():null;this.execute(n),o&&this.logAtomic(r,n,o,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.pathOpen=!1,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||!ue(n))return;let r=this.state;this.state=Wi(),this.applyCurrentTransform();try{for(let i of n.items){let o=this.resolveObject(i);if(!(!o||!Q(o)))try{await this.renderOneAnnotation(o)}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 c,d;let n=Ee(e.entries.get("Subtype"));if(n==="Popup"||n==="Link"||n==="Widget")return;let r=Math.floor((c=V(e.entries.get("F")))!=null?c:0);if((r&2)!==0||(r&32)!==0)return;let i=this.resolveAppearanceStream(e);if(!i)return;let o=bt(this.resolveObject(e.entries.get("Rect")));if(!o||o.length<4)return;let s=bt(i.dict.entries.get("BBox"));if(!s||s.length<4)return;let a=(d=Jr(i.dict.entries.get("Matrix")))!=null?d:[1,0,0,1,0,0],l=jg(o,s,a);if(l){this.execute({op:"save_state"}),this.execute({op:"set_ctm",matrix:l});try{await this.renderFormStreamInline(i)}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 i=Ee(e.entries.get("AS"));r=i?this.resolveObject(r.entries.get(i)):void 0}return r&&he(r)?r:null}async runCommandsAsync(e){let n=()=>typeof performance!="undefined"?performance.now():Date.now(),r=n();for(let i of e){let o=this.commandIndex++;this.debug&&this.logDebug("command",{index:o,op:i.op,payload:this.commandPayload(i)}),n()-r>12&&(await Og(),r=n());let a=this.debugAtomic&&this.atomicLogCount<this.maxAtomicLogs?this.captureAtomicState():null;i.op==="xobject"?await this.renderXObject(i.name):i.op==="inline_image"?await this.renderInlineImage(i.params,i.data):(i.op==="set_fill_color"||i.op==="set_stroke_color")&&i.patternName&&!this.forcedColor&&(i.op==="set_fill_color"?this.state.fillColorSpace:this.state.strokeColorSpace)==="Pattern"?await this.applyPatternColor(i.op==="set_fill_color"?"fill":"stroke",i.patternName,i.values):i.op==="set_graphics_state"?(this.execute(i),await this.applySoftMaskFromExtGState(i.name)):this.execute(i),a&&this.logAtomic(o,i,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 Dd(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=Ce(this.deviceBase(),this.state.ctm),r=this.pendingPath.bbox;for(let[i,o]of e){let s=He(n,i,o);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=Ce(this.deviceBase(),this.state.ctm),i=[He(r,0,0),He(r,1,0),He(r,0,1),He(r,1,1)],o=i.map(c=>c.x),s=i.map(c=>c.y),a=Math.min(...o),l=Math.min(...s);this.capturedImages.push({canvasX:a,canvasY:l,canvasWidth:Math.max(...o)-a,canvasHeight:Math.max(...s)-l,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(Zg(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 i=this.layerStack[this.layerStack.length-1];if(i.kind==="smask"&&i.stateDepthAtPush>=this.stateStack.length)this.popLayer();else break}if(this.stateStack.length>0&&(this.state=this.stateStack.pop()),this.resolverStack.length>0){let i=this.resolverStack.pop();this.fillColorResolver=i.fill,this.strokeColorResolver=i.stroke}this.ctx.restore();break;case"set_ctm":this.state.ctm=Ce(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 i=["butt","round","square"];this.state.lineCap=e.cap,this.ctx.lineCap=(n=i[e.cap])!=null?n:"butt";break}case"set_line_join":{let i=["miter","round","bevel"];this.state.lineJoin=e.join,this.ctx.lineJoin=(r=i[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=Tt(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=Tt(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=Tt(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=Tt(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 i=no(e.c,e.m,e.y,e.k);this.ctx.fillStyle=Tt(i.r,i.g,i.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 i=no(e.c,e.m,e.y,e.k);this.ctx.strokeStyle=Tt(i.r,i.g,i.b);break}case"move_to":this.beginSubpathIfNeeded(),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.beginSubpathIfNeeded(),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.beginSubpathIfNeeded(),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.beginSubpathIfNeeded(),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.beginSubpathIfNeeded(),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.pathOpen=!1,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=Ce(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=Ce(this.state.textLineMatrix,[1,0,0,1,e.tx,e.ty]),this.state.textMatrix=[...this.state.textLineMatrix];break;case"next_line":this.state.textLineMatrix=Ce(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 i of e.items)if(i instanceof Uint8Array)this.renderText(i);else{let o=-(i/1e3)*this.state.fontSize*(this.state.horizScale/100);this.state.textMatrix=Ce(this.state.textMatrix,[1,0,0,1,o,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 i=this.resolvePatternFillStyle(e.patternName,"fill");this.ctx.fillStyle=i}else this.state.fillPatternName=null,this.state.fillPattern=null,this.state.fillColor=this.fillColorResolver?this.fillColorResolver(e.values):Rn(this.state.fillColorSpace,e.values),this.ctx.fillStyle=mn(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 i=this.resolvePatternFillStyle(e.patternName,"stroke");this.ctx.strokeStyle=i}else this.state.strokePatternName=null,this.state.strokePattern=null,this.state.strokeColor=this.strokeColorResolver?this.strokeColorResolver(e.values):Rn(this.state.strokeColorSpace,e.values),this.ctx.strokeStyle=mn(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=Ce(this.state.textLineMatrix,[1,0,0,1,0,-this.state.leading]),this.state.textMatrix=[...this.state.textLineMatrix]}renderText(e){var Rt;if(e.length===0)return;let n=this.getCurrentFontInfo();if(n.isType3){this.renderType3Text(e,n);return}let r=this.decodeTextWithFont(e,n),i=Math.max(1,this.state.fontSize);this.ctx.font=Zd(n,i);let o=ve=>this.measureGlyphWidthCached(ve),s=Yg(e,r,n,i,this.state.charSpacing,this.state.wordSpacing,o),a=s.glyphs,l=a.map(ve=>ve.text).join("")||r;this.logDebug("text:before",{text:l,textLength:l.length,font:this.state.font,fontSize:i,textMatrix:this.state.textMatrix,fillColor:mn(this.state.fillColor),textRise:this.state.textRise,horizScale:this.state.horizScale}),this.ctx.save();let c=this.state.textMatrix;this.ctx.transform(c[0],c[1],c[2],c[3],c[4],c[5]);let d=this.state.horizScale/100;d!==1&&this.ctx.scale(d,1);let h=this.state.textRise;this.ctx.font=Zd(n,i),this.ctx.fillStyle=mn(this.state.fillColor),this.ctx.globalAlpha=this.state.fillAlpha;let f=this.ctx.measureText(l),m=Math.max(1e-4,f.width),p=s.hasPdfMetrics?a.reduce((ve,tt)=>ve+tt.advance,0)*d:null,b=p!=null?p:m*d,y=Math.max(1,f.actualBoundingBoxAscent||i*.8),k=Math.max(1,f.actualBoundingBoxDescent||i*.2);this.ctx.scale(1,-1);let w=s.hasPdfMetrics&&a.length>0,P=m*Math.max(1e-4,d),S=p?Jg(b/P,.5,1.8):1;!w&&S!==1&&this.ctx.scale(S,1);let R=this.state.textRenderMode,I=R===0||R===2||R===4||R===6,F=R===1||R===2||R===5||R===6;I&&(this.ctx.fillStyle=mn(this.state.fillColor)),F&&(this.ctx.strokeStyle=mn(this.state.strokeColor),this.ctx.lineWidth=Math.max(.01,this.state.lineWidth/i));let A=(ve,tt)=>{I&&(this.ctx.globalAlpha=this.state.fillAlpha,this.ctx.fillText(ve,tt,-h)),F&&(this.ctx.globalAlpha=this.state.strokeAlpha,this.ctx.strokeText(ve,tt,-h))};if(w){let ve=0;for(let tt of a)tt.text&&A(tt.text,ve),ve+=tt.advance}else A(l,0);this.ctx.restore();let G=[1,0,0,-1,0,this.pageHeight],Y=Ce(Ce(G,this.state.ctm),c),E=b,ee=He(Y,0,h),ne=[He(Y,0,h+y),He(Y,E,h+y),He(Y,E,h-k),He(Y,0,h-k)],O=Math.min(...ne.map(ve=>ve.x)),ge=Math.max(...ne.map(ve=>ve.x)),fe=Math.min(...ne.map(ve=>ve.y)),Oe=Math.max(...ne.map(ve=>ve.y)),Te=O*this.scale,_=fe*this.scale,ce=Math.max(1,(ge-O)*this.scale),ae=Math.max(1,(Oe-fe)*this.scale),W=Fn(this.state.fillColor),me=(Rt=n.baseFontName)!=null?Rt:this.state.font,xe=Ce(this.state.ctm,c),be=Math.hypot(xe[1],xe[3]),Ie=Math.max(1,i*(be>.01?be:1)),Me=this.capturedTextRuns.length,Ke=0,et=a.map(ve=>{let tt=s.hasPdfMetrics?ve.advance:m>0?this.measureGlyphWidthCached(ve.text)/m*(b/Math.max(1e-4,d)):0,Kt=He(Y,Ke*d,h),De=He(Y,(Ke+tt)*d,h),it=Math.min(Kt.x,De.x)*this.scale,pt=Math.max(1,Math.abs(De.x-Kt.x)*this.scale);return Ke+=tt,{canvasX:it,canvasY:_,canvasWidth:pt,canvasHeight:ae,canvasBaselineY:ee.y*this.scale,char:ve.text,charCode:ve.code,runIndex:Me}});this.capturedTextRuns.push({index:Me,text:l,fontName:me,fontSize:Ie,canvasX:Te,canvasY:_,canvasWidth:ce,canvasHeight:ae,canvasBaselineX:ee.x*this.scale,canvasBaselineY:ee.y*this.scale,fillColor:W,streamOperatorIndex:Math.max(0,this.commandIndex-1),fromXObject:this.xobjectDepth>0,glyphs:et,fontFamily:ra(n),textRenderMode:R,invisible:R===3||R===7,fontCapHeight:n.registeredFamily?this.measureRegisteredCapHeight(n.registeredFamily):void 0,fontWeight:n.fontWeight,fontStyle:n.fontStyle,registeredFamily:n.registeredFamily});let qe=p!=null?p:b;this.state.textMatrix=Ce(this.state.textMatrix,[1,0,0,1,qe,0]),this.logDebug("text:after",{text:l,measuredWidth:m,advance:qe,needsTextFlip:!0,bytesHexPreview:Array.from(e.slice(0,12)).map(ve=>ve.toString(16).padStart(2,"0")).join(" "),printableChars:Array.from(r).filter(ve=>ve>=" "&&ve<="~").length,totalChars:r.length,nextTextMatrix:this.state.textMatrix})}renderType3Text(e,n){var I,F,A,G,Y,E,ee,ne;let r=n.type3CharProcs,i=n.type3Encoding;if(!r)return;let o=Math.max(1,this.state.fontSize),s=this.state.horizScale/100,a=this.state.textRise,l=(I=n.fontMatrix)!=null?I:[.001,0,0,.001,0,0],c=this.capturedTextRuns.length,d="";for(let O=0;O<e.length;O++){let ge=e[O],fe=(F=n.encodingMap)==null?void 0:F.get(ge);d+=fe!=null?fe:i&&(A=i.get(ge))!=null?A:String.fromCharCode(ge)}let h=[...this.state.textMatrix],f=[1,0,0,-1,0,this.pageHeight],m=this.pageResources;for(let O=0;O<e.length;O++){let ge=e[O],fe=(G=i==null?void 0:i.get(ge))!=null?G:".notdef",Te=((ee=(E=(Y=n.widths)==null?void 0:Y.get(ge))!=null?E:n.defaultWidth)!=null?ee:1e3)/1e3*o+this.state.charSpacing+(ge===32?this.state.wordSpacing:0),_=r.entries.get(fe),ce=_?this.resolveObject(_):void 0;if(ce&&he(ce)){let ae=this.state.textMatrix,W=[o*s,0,0,o,0,a],me=Ce(Ce(ae,W),l),xe=[...this.state.textMatrix],be=[...this.state.textLineMatrix];this.execute({op:"save_state"}),this.execute({op:"set_ctm",matrix:me}),n.type3Resources&&(this.pageResources=n.type3Resources),this.captureSuppressed+=1;try{let Ie=Pe.decodeStreamSync(ce),Me=un(Ie);for(let Ke of Me)Ke.op!=="type3_glyph_width"&&this.execute(Ke)}catch{}finally{this.captureSuppressed-=1}this.pageResources=m,this.execute({op:"restore_state"}),this.state.textMatrix=xe,this.state.textLineMatrix=be}this.state.textMatrix=Ce(this.state.textMatrix,[1,0,0,1,Te,0])}let p=Ce(Ce(f,this.state.ctm),h),b=He(p,0,a),y=Ce(Ce(f,this.state.ctm),this.state.textMatrix),k=He(y,0,a),w=Math.min(b.x,k.x)*this.scale,P=(Math.min(b.y,k.y)-o)*this.scale,S=Math.max(1,Math.abs(k.x-b.x)*this.scale),R=Math.max(1,o*this.scale);this.capturedTextRuns.push({index:c,text:d,fontName:(ne=n.baseFontName)!=null?ne:this.state.font,fontSize:o,canvasX:w,canvasY:P,canvasWidth:S,canvasHeight:R,canvasBaselineX:b.x*this.scale,canvasBaselineY:b.y*this.scale,fillColor:Fn(this.state.fillColor),streamOperatorIndex:Math.max(0,this.commandIndex-1),fromXObject:this.xobjectDepth>0,glyphs:[],fontFamily:ra(n),textRenderMode:this.state.textRenderMode,invisible:this.state.textRenderMode===3||this.state.textRenderMode===7,fontCapHeight:n.registeredFamily?this.measureRegisteredCapHeight(n.registeredFamily):void 0,fontWeight:n.fontWeight,fontStyle:n.fontStyle,registeredFamily:n.registeredFamily})}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 i=this.ctx.measureText(e).width;return this.glyphWidthCache.set(n,i),i}measureRegisteredCapHeight(e){let n=Yd.get(e);if(n!==void 0)return n||void 0;let r=0;try{let i=this.ctx.font;this.ctx.font=`1000px "${e}"`;let o=this.ctx.measureText("H").actualBoundingBoxAscent;this.ctx.font=i,Number.isFinite(o)&&o>0&&o<1200&&(r=o)}catch{r=0}return Yd.set(e,r),r||void 0}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,i]of e.entries)try{let o=this.resolveObject(i);if(!o||!Q(o))continue;let a=Ee(o.entries.get("Subtype"))==="Type0"?qd(o,n):void 0,l=Jd(o,a,n),c=Md(l,n);if(!c)continue;let d=await Ad(c);d&&this.embeddedFamilies.set(r,d);let h=qs(c);if(h&&!this.embeddedFontBytes.has(h.family)){let f=Ee(o.entries.get("BaseFont"))||r;this.embeddedFontBytes.set(h.family,{bytes:h.bytes,baseName:f})}}catch{}}getEmbeddedFontPrograms(){return this.embeddedFontBytes}getCurrentFontInfo(){let e=this.state.font;if(!e)return Qi();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 Y,E,ee,ne,O,ge,fe,Oe,Te;if(!this.pageResources)return Qi();let n=this.resolveObject(this.pageResources.entries.get("Font"));if(!n||!Q(n))return Qi();let r=n.entries.get(e),i=this.resolveObject(r);if(!i||!Q(i))return Qi();let o=Hd.get(i);if(o)return o;let s=i.entries.get("Subtype"),a=(Y=Ee(s))!=null?Y:"Unknown",l=(E=Ee(i.entries.get("BaseFont")))!=null?E:void 0,c=a==="Type0",d=Math.floor((ee=V(i.entries.get("FirstChar")))!=null?ee:0),h=c?qd(i,_=>this.resolveObject(_)):void 0,f=Jd(i,h,_=>this.resolveObject(_)),m=c?_g(h):$g(i,d),p=c?zg(h):Xg(i),b=i.entries.get("ToUnicode"),y=i.entries.get("Encoding"),k=null,w=this.resolveObject(b);if(w&&he(w))try{let _=Pe.decodeStreamSync(w),ce=new TextDecoder("latin1").decode(_),ae=S0(ce);this.logFontDiagnostic(e,{subtype:a,isComposite:c,hasRawToUnicode:!!b,rawToUnicodeType:pn(b),resolvedToUnicodeType:pn(w),encoding:pn(y),cmapRaw:ae}),this.debug&&Wd.has(e)&&!Xd.has(e)&&(Xd.add(e),console.log(`=== Raw CMap text for ${e} (first 500 chars) ===`),console.log(ce.slice(0,500)),console.log("===")),k=Qg(ce),this.logDebug("font:cmap-parsed",{fontName:e,cmapType:k.cmapType,isUsable:k.isUsable,bfChar:k.bfChar.size,bfRange:k.bfRange.length,codeSpaceRanges:k.codeSpaceRanges.length}),this.debug&&k&&Wd.has(e)&&r0(k,e)}catch(_){this.logDebug("font:toUnicode-failed",{fontName:e,subtype:a,error:_ instanceof Error?_.message:String(_)}),this.logFontDiagnostic(e,{subtype:a,isComposite:c,hasRawToUnicode:!!b,rawToUnicodeType:pn(b),resolvedToUnicodeType:pn(w),encoding:pn(y),toUnicodeError:_ instanceof Error?_.message:String(_)})}else this.logFontDiagnostic(e,{subtype:a,isComposite:c,hasRawToUnicode:!!b,rawToUnicodeType:pn(b),resolvedToUnicodeType:pn(w),encoding:pn(y),note:c?"Composite font without resolved ToUnicode stream":"No ToUnicode stream"});if(!k&&c){let _=i.entries.get("Encoding");_&&_.type==="name"&&(_.value==="Identity-H"||_.value==="Identity-V")&&this.logDebug("font:identity-no-tounicode",{fontName:e,subtype:a,encoding:_.value})}let P;c||(P=Kg(y,_=>this.resolveObject(_)));let S=!1,R,I,F,A;if(a==="Type3"){S=!0;let _=this.resolveObject(i.entries.get("CharProcs"));_&&Q(_)&&(R=_);let ce=i.entries.get("FontMatrix");if(ce&&ue(ce)){let W=ce.items;F=[(ne=V(W[0]))!=null?ne:.001,(O=V(W[1]))!=null?O:0,(ge=V(W[2]))!=null?ge:0,(fe=V(W[3]))!=null?fe:.001,(Oe=V(W[4]))!=null?Oe:0,(Te=V(W[5]))!=null?Te:0]}let ae=this.resolveObject(i.entries.get("Resources"));ae&&Q(ae)&&(A=ae),I=qg(y,W=>this.resolveObject(W))}let G={subtype:a,baseFontName:l,fontWeight:Wg(l,f),fontStyle:Hg(l,f),isComposite:c,firstChar:d,widths:m,defaultWidth:p,toUnicode:k,encodingMap:P,isType3:S,type3CharProcs:R,type3Encoding:I,fontMatrix:F,type3Resources:A,registeredFamily:this.embeddedFamilies.get(e)};return this.logDebug("font:loaded",{fontName:e,subtype:a,isComposite:c,hasToUnicode:!!k}),Hd.set(i,G),G}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(!$e(e))return e;if(this.objectLoader)try{return this.objectLoader(e)}catch{return}}}resolveColorSpaceName(e){var o;let n=Et(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 i=this.resolveObject(r.entries.get(e));return(o=Vd(i))!=null?o:e}buildComplexColorResolver(e){var m;if(Et(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 i=this.resolveObject(r.entries.get(e));if(!i||!ue(i)||i.items.length<2)return null;let o=Ee(i.items[0]);if(o!=="Separation"&&o!=="DeviceN")return null;let s=2,a=3,l=i.items[s]?this.resolveObject(i.items[s]):void 0,c=(m=Vd(l))!=null?m:"DeviceGray",d=i.items[a],h=this.objectLoader,f=p=>{var k;let b=(k=p[0])!=null?k:0,y=Vi(d,b,h);return y&&y.length>0?Rn(c,y):c==="DeviceCMYK"?{space:"cmyk",c:0,m:0,y:0,k:b}:{space:"gray",gray:1-b}};return this.separationColorCache.set(e,f),f}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||!he(r))return;let i=Ee(r.dict.entries.get("Subtype"));if(i==="Image"){this.captureImageBox("xobject",e),await this.renderImageXObject(r);return}if(i==="Form")try{let o=r,s=this.resolveObject(o.dict.entries.get("Resources")),l=await(o.decode?o.decode():Promise.resolve(Pe.decodeStreamSync(o))),c=un(l instanceof Uint8Array?l:new Uint8Array(await l)),d=this.pageResources,h=this.objectLoader,f=this.patternCache;this.patternCache=new Map,this.pageResources=s&&Q(s)?s:this.pageResources;let m=this.resolveObject(o.dict.entries.get("Group")),y=!!m&&Q(m)&&Ee(m.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 k=o.dict.entries.get("Matrix");if(k&&Array.isArray(k.items))try{let P=k.items.map(S=>{var R;return Number((R=V(S))!=null?R:0)});this.execute({op:"set_ctm",matrix:P})}catch{}let w=this.commandIndex;this.xobjectDepth+=1;try{await this.runCommandsAsync(c)}finally{this.xobjectDepth-=1,this.commandIndex=w}this.execute({op:"restore_state"}),y&&this.popLayer(),this.pageResources=d,this.objectLoader=h,this.patternCache=f;return}catch(o){this.logDebug("xobject:form-failed",{name:e,error:o instanceof Error?o.message:String(o)});return}}resolveImageColorSpace(e){var r,i,o;if(!e)return"DeviceRGB";let n=Ee(e);if(n)return(r=Et(n))!=null?r:n;if(ue(e)&&e.items.length>0){let s=Ee(e.items[0]);if(s==="ICCBased"){let a=this.resolveObject(e.items[1]);if(a&&he(a)){let l=Math.floor((i=V(a.dict.entries.get("N")))!=null?i:3);return l===1?"DeviceGray":l===4?"DeviceCMYK":"DeviceRGB"}return"DeviceRGB"}if(s==="Indexed")return"Indexed";if(s==="CalRGB")return"DeviceRGB";if(s==="CalGray")return"DeviceGray";if(s)return(o=Et(s))!=null?o: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(ue(n))for(let i of n.items){let o=this.resolveObject(i);if(o&&Q(o))return o}return null}async decodeJbig2(e,n,r){var o;let i=(o=e.rawBytes)!=null?o:e.data;if(!i||i.length===0)return null;if(n>0&&r>0&&n*r>Eg)return this.logDebug("xobject:jbig2-failed",{error:`JBIG2 image too large (${n}x${r}) \u2014 skipped to avoid OOM`}),null;try{let{Jbig2Image:s}=await Zs(),a,l=this.resolveDecodeParms(e.dict);if(l){let h=this.resolveObject(l.entries.get("JBIG2Globals"));if(h&&he(h))try{a=Pe.decodeStreamSync(h)}catch{}}let c=[];a&&a.length>0&&c.push({data:a,start:0,end:a.length}),c.push({data:i,start:0,end:i.length});let d=new s().parseChunks(c);for(let h=0;h<d.length;h++)d[h]^=255;return d}catch(s){return this.logDebug("xobject:jbig2-failed",{error:s instanceof Error?s.message:String(s)}),null}}async decodeCcitt(e,n,r){var o;let i=(o=e.rawBytes)!=null?o:e.data;if(!i||i.length===0)return null;try{let s=this.resolveDecodeParms(e.dict),a=(P,S)=>{var R;return s?Math.floor((R=V(s.entries.get(P)))!=null?R:S):S},l=(P,S)=>{let R=s==null?void 0:s.entries.get(P);return R&&typeof R=="object"&&"type"in R&&R.type==="boolean"?R.value:S},c=a("Columns",1728),d=a("Rows",r),h=0,f={next:()=>h<i.length?i[h++]:-1},m=new Ji(f,{K:a("K",0),EndOfLine:l("EndOfLine",!1),EncodedByteAlign:l("EncodedByteAlign",!1),Columns:c,Rows:d,EndOfBlock:l("EndOfBlock",!0),BlackIs1:l("BlackIs1",!1)}),b=(c+7>>3)*(d>0?d:r),y=new Uint8Array(b),k=0,w;for(;k<b&&(w=m.readNextChar())!==-1;)y[k++]=w;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 i=document.createElement("canvas");i.width=n,i.height=r;let o=i.getContext("2d");o&&(o.putImageData(e,0,0),this.drawImageBitmapLike(i))}async renderImageXObject(e){var f,m,p,b;let n=e.dict,r=Math.floor((f=V(n.entries.get("Width")))!=null?f:0),i=Math.floor((m=V(n.entries.get("Height")))!=null?m:0);if(r<=0||i<=0)return;let o=Kd(n.entries.get("Filter")),s=Math.floor((p=V(n.entries.get("BitsPerComponent")))!=null?p:8),a=n.entries.get("ImageMask"),l=a!=null&&typeof a=="object"&&"type"in a&&a.type==="boolean"&&a.value===!0||Ee(a)==="true",c=this.resolveImageColorSpace(n.entries.get("ColorSpace")),d=o.includes("JBIG2Decode"),h=o.includes("CCITTFaxDecode")||o.includes("CCF");try{let y=null;if(d?y=await this.decodeJbig2(e,r,i):h&&(y=await this.decodeCcitt(e,r,i)),(d||h)&&!y)return;if(l){await this.renderStencilMask(e,r,i,y);return}if(!d&&!h&&(o.includes("DCTDecode")||o.includes("DCT"))){let k=(b=e.rawBytes)!=null?b:e.data;if(!k)return;if(c==="DeviceCMYK"){await this.renderJpegViaPdfjs(e,k,r,i);return}let w=this.resolveObject(n.entries.get("SMask"));if(w&&he(w))await this.renderImageWithSMask(k,"image/jpeg",w,r,i);else{let P=await Qs(k,"image/jpeg");this.drawImageBitmapLike(P),ea(P)}return}if(!d&&!h&&o.includes("JPXDecode")){await this.renderJpxViaPdfjs(e,r,i);return}if(!y&&o.some(k=>!Bg.has(k)))return;if(s===1||s===2||s===4||s===8||s===16){let k=y!=null?y:Pe.decodeStreamSync(e),w=null;if(c==="Indexed"){let S=n.entries.get("ColorSpace"),R=F=>this.resolveObject(F),I=Zi(k,r,i,1,s,!1);w=$d(I,r,i,S&&ue(S)?S.items:[],R)}else{let S=Ld(c),R=Zi(k,r,i,S,s,!0);w=Ud(R,r,i,c)}if(!w)return;_d(w,bt(n.entries.get("Decode")),c);let P=this.resolveObject(n.entries.get("SMask"));if(P&&he(P))try{let S=await this.decodeSMaskAlpha(P,r,i);qr(w,S,r,i)}catch{}this.drawRgbaImageData(w,r,i)}}catch(y){this.logDebug("xobject:image-failed",{width:r,height:i,colorSpace:c,bitsPerComponent:s,filters:o,error:y instanceof Error?y.message:String(y)})}}async renderJpegViaPdfjs(e,n,r,i){let{JpegImage:o}=await Zs(),s=new o;s.parse(n);let a=s.getData({width:r,height:i,forceRGBA:!0,isSourcePDF:!0});if(a.length<r*i*4)return;let l=new ImageData(new Uint8ClampedArray(a.subarray(0,r*i*4)),r,i),c=this.resolveObject(e.dict.entries.get("SMask"));if(c&&he(c))try{let d=await this.decodeSMaskAlpha(c,r,i);qr(l,d,r,i)}catch{}this.drawRgbaImageData(l,r,i)}async renderJpxViaPdfjs(e,n,r){var b,y,k;let i=(b=e.rawBytes)!=null?b:e.data;if(!i)return;let{JpxImage:o}=await Zs(),s=new o;s.parse(i);let a=s.width||n,l=s.height||r,c=s.componentsCount||1,d=(k=(y=s.tiles)==null?void 0:y[0])==null?void 0:k.items;if(!d)return;let h=a*l,f=new Uint8ClampedArray(h*4);for(let w=0,P=0;w<h;w++,P+=4){let S=w*c;if(c>=4){let R=d[S],I=d[S+1],F=d[S+2],A=d[S+3];f[P]=255-Math.min(255,R+A),f[P+1]=255-Math.min(255,I+A),f[P+2]=255-Math.min(255,F+A)}else c===3?(f[P]=d[S],f[P+1]=d[S+1],f[P+2]=d[S+2]):f[P]=f[P+1]=f[P+2]=d[S];f[P+3]=255}let m=new ImageData(f,a,l),p=this.resolveObject(e.dict.entries.get("SMask"));if(p&&he(p))try{let w=await this.decodeSMaskAlpha(p,a,l);qr(m,w,a,l)}catch{}this.drawRgbaImageData(m,a,l)}async renderInlineImage(e,n){var c;this.captureImageBox("inline",null);let r={W:"Width",H:"Height",BPC:"BitsPerComponent",CS:"ColorSpace",F:"Filter",IM:"ImageMask",D:"Decode",DP:"DecodeParms",I:"Interpolate"},i={AHx:"ASCIIHexDecode",A85:"ASCII85Decode",LZW:"LZWDecode",Fl:"FlateDecode",RL:"RunLengthDecode",CCF:"CCITTFaxDecode",DCT:"DCTDecode"},o={G:"DeviceGray",RGB:"DeviceRGB",CMYK:"DeviceCMYK",I:"Indexed"},s=(d,h)=>d&&"type"in d&&d.type==="name"&&h[d.value]?{type:"name",value:h[d.value]}:d,a=new Map;for(let[d,h]of e.entries){let f=(c=r[d])!=null?c:d,m=h;if(f==="Filter")m=ue(h)?{type:"array",items:h.items.map(p=>s(p,i))}:s(h,i);else if(f==="ColorSpace")if(h&&"type"in h&&h.type==="name"&&!o[h.value]&&!["DeviceGray","DeviceRGB","DeviceCMYK","Indexed"].includes(h.value)){let p=this.lookupResource("ColorSpace",h.value);m=p!=null?p:h}else m=s(h,o);a.set(f,m)}let l={type:"stream",dict:{type:"dict",entries:a},data:n,rawBytes:n};await this.renderImageXObject(l)}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 h,f,m,p;let i=Kd(e.dict.entries.get("Filter")),o=i.includes("JPXDecode");if(i.includes("DCTDecode")||i.includes("DCT")||o){let b=(h=e.rawBytes)!=null?h:e.data;if(b&&b.length>0){let y=await Qs(b,o?"image/jp2":"image/jpeg");try{let k=document.createElement("canvas");k.width=n,k.height=r;let w=k.getContext("2d");if(w){w.drawImage(y,0,0,n,r);let{data:P}=w.getImageData(0,0,n,r),S=new Uint8Array(n*r);for(let R=0;R<S.length;R++)S[R]=P[R*4];return S}}finally{ea(y)}}}let a=Pe.decodeStreamSync(e),l=Math.floor((f=V(e.dict.entries.get("BitsPerComponent")))!=null?f:8);if(l===8)return a;let c=Math.floor((m=V(e.dict.entries.get("Width")))!=null?m:n),d=Math.floor((p=V(e.dict.entries.get("Height")))!=null?p:r);return Zi(a,c,d,1,l,!0)}async renderImageWithSMask(e,n,r,i,o){let s=await Qs(e,n);try{let a=document.createElement("canvas");a.width=i,a.height=o;let l=a.getContext("2d");if(!l){this.drawImageBitmapLike(s);return}l.drawImage(s,0,0,i,o);let c=l.getImageData(0,0,i,o);try{let d=await this.decodeSMaskAlpha(r,i,o);qr(c,d,i,o)}catch{}l.putImageData(c,0,0),this.drawImageBitmapLike(a)}finally{ea(s)}}async renderStencilMask(e,n,r,i){try{let o=i!=null?i:Pe.decodeStreamSync(e),s=Fn(this.state.fillColor),a=Math.round(s.r*255),l=Math.round(s.g*255),c=Math.round(s.b*255),d=n*r,h=new Uint8ClampedArray(d*4),f=bt(e.dict.entries.get("Decode")),m=!!f&&f.length>=2&&f[0]===1&&f[1]===0,p=0;for(let k=0;k<o.length&&p<d;k++){let w=o[k];for(let P=7;P>=0&&p<d;P--){let S=w>>P&1,R=p*4;S===1!==m&&(h[R]=a,h[R+1]=l,h[R+2]=c,h[R+3]=255),p++}}let b=document.createElement("canvas");b.width=n,b.height=r;let y=b.getContext("2d");if(!y)return;y.putImageData(new ImageData(h,n,r),0,0),this.drawImageBitmapLike(b)}catch(o){this.logDebug("xobject:stencil-mask-failed",{error:o instanceof Error?o.message:String(o)})}}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 i=String(this.state.font||"").toLowerCase();if(i==="f1"||i==="f2"){let o=Array.from(e.subarray(0,24)).map(a=>a.toString(16).padStart(2,"0")).join(" "),s=`${i}|${o}`;this.rawByteDiagnosticsLogged.has(s)||(this.rawByteDiagnosticsLogged.add(s),console.log(`[${i} RAW BYTES] ${o}`))}}if(n.toUnicode)return!n.toUnicode.isUsable&&n.isComposite?o0(e,n.toUnicode):i0(e,n.toUnicode,n.isComposite,this.state.font,this.debug);if(n.isComposite)return su(e);if(n.encodingMap&&n.encodingMap.size>0){let i=[];for(let o of e)i.push((r=n.encodingMap.get(o))!=null?r:String.fromCharCode(o));return i.join("")}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))]],i=[],o=this.ctx.getTransform();this.ctx.setTransform(1,0,0,1,0,0);try{for(let[s,a]of r){let l=this.ctx.getImageData(Math.min(e-1,s),Math.min(n-1,a),1,1).data;i.push([l[0],l[1],l[2],l[3]])}}finally{this.ctx.setTransform(o.a,o.b,o.c,o.d,o.e,o.f)}return i}logAtomic(e,n,r,i){if(!this.debugAtomic||this.atomicLogCount>=this.maxAtomicLogs)return;let o=JSON.stringify(r.samples),s=JSON.stringify(i.samples),a=o!==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:i.stackDepth,transformBefore:[r.transform.a,r.transform.b,r.transform.c,r.transform.d,r.transform.e,r.transform.f],transformAfter:[i.transform.a,i.transform.b,i.transform.c,i.transform.d,i.transform.e,i.transform.f],lineWidthBefore:r.lineWidth,lineWidthAfter:i.lineWidth,fillStyleBefore:r.fillStyle,fillStyleAfter:i.fillStyle,strokeStyleBefore:r.strokeStyle,strokeStyleAfter:i.strokeStyle,pixelChanged:a,samplesBefore:r.samples,samplesAfter:i.samples}))}applyExtGState(e){var p,b,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 i=r,o=V(i.entries.get("LW"));o!==null&&(this.state.lineWidth=o,this.ctx.lineWidth=o);let s=V(i.entries.get("LC"));if(s!==null){let k=Math.floor(s),w=["butt","round","square"];this.state.lineCap=k,this.ctx.lineCap=(p=w[k])!=null?p:"butt"}let a=V(i.entries.get("LJ"));if(a!==null){let k=Math.floor(a),w=["miter","round","bevel"];this.state.lineJoin=k,this.ctx.lineJoin=(b=w[k])!=null?b:"miter"}let l=V(i.entries.get("ML"));l!==null&&(this.state.miterLimit=l,this.ctx.miterLimit=l);let c=i.entries.get("D");if(c&&ue(c)&&c.items.length>=1){let k=c.items[0],w=(y=V(c.items[1]))!=null?y:0;if(ue(k)){let P=k.items.map(S=>{var R;return(R=V(S))!=null?R:0});this.state.dashArray=P,this.state.dashPhase=w,this.ctx.setLineDash(P),this.ctx.lineDashOffset=w}}let d=V(i.entries.get("CA"));d!==null&&(this.state.strokeAlpha=rt(d));let h=V(i.entries.get("ca"));h!==null&&(this.state.fillAlpha=rt(h));let f=i.entries.get("BM"),m=Ee(f);m&&(this.state.blendMode=m,this.ctx.globalCompositeOperation=Gd(m))}deviceBase(){if(this.initialTransform)return this.initialTransform;let e=this.scale;return[e,0,0,-e,0,e*this.pageHeight]}applyCurrentTransform(){let e=Ce(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,i,o;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=V(a.entries.get("PatternType")))!=null?r:0)!==2)return"transparent";let c=this.resolveObject(a.entries.get("Shading"));if(!c||!Q(c))return"transparent";let d=(i=Jr(a.entries.get("Matrix")))!=null?i:[1,0,0,1,0,0];return(o=this.createCanvasGradient(c,d))!=null?o:"transparent"}catch{return"transparent"}}async resolvePattern(e,n){var s,a;let r=`${e}|${mn(n)}`,i=this.patternCache.get(r);if(i!==void 0)return i;let o=null;try{if(this.pageResources&&this.objectLoader){let l=this.resolveObject(this.pageResources.entries.get("Pattern")),c=l&&Q(l)?this.resolveObject(l.entries.get(e)):void 0,d=c?he(c)?c.dict:Q(c)?c:null:null;if(d){let h=Math.floor((s=V(d.entries.get("PatternType")))!=null?s:0),f=(a=Jr(d.entries.get("Matrix")))!=null?a:[1,0,0,1,0,0];if(h===2){let m=this.resolveObject(d.entries.get("Shading")),p=m?he(m)?m.dict:Q(m)?m:null:null;p&&(o={kind:"shading",shading:p,stream:m&&he(m)?m:null,matrix:f})}else h===1&&c&&he(c)&&(o=await this.renderTilingCell(c,d,f,n))}}}catch{o=null}return this.patternCache.set(r,o),o}async applyPatternColor(e,n,r){let i=e==="fill"?this.state.fillColor:this.state.strokeColor,o=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]}:i,s=await this.resolvePattern(n,o);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,i){var I,F,A,G;if(this.patternDepth>=4)return null;let o=bt(n.entries.get("BBox"));if(!o||o.length<4)return null;let s=[o[0],o[1],o[2],o[3]],a=s[2]-s[0],l=s[3]-s[1],c=(I=V(n.entries.get("XStep")))!=null?I:a,d=(F=V(n.entries.get("YStep")))!=null?F:l,h=Math.abs(c)<1e-9?a:c,f=Math.abs(d)<1e-9?l:d,m=Math.floor((A=V(n.entries.get("PaintType")))!=null?A:1),p=Ce(this.deviceBase(),r),b=vd(s,h,f,p);if(!b)return null;let y=document.createElement("canvas"),k=new wr(y,b.cellPxW,b.cellPxH,1,{disableClip:this.disableClip,transparentBackground:!0,initialTransform:b.contentTransform,forcedColor:m===2?i:void 0,patternDepth:this.patternDepth+1}),w=this.resolveObject(n.entries.get("Resources"));k.setFontContext(w&&Q(w)?w:void 0,(G=this.objectLoader)!=null?G:void 0);let P=e.decode?await e.decode():Pe.decodeStreamSync(e),S=un(P),R=a>0&&l>0?[{op:"rect",x:s[0],y:s[1],w:a,h:l},{op:"clip"},{op:"end_path"}]:[];return await k.renderAsync([...R,...S]),{kind:"tiling",cell:y,layout:b,matrix:r}}beginSubpathIfNeeded(){this.pathOpen||(this.ctx.beginPath(),this.pathOpen=!0)}paintFill(e){this.pathOpen=!1;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(){this.pathOpen=!1;let e=this.state.strokePattern;if(this.ctx.globalAlpha=this.state.strokeAlpha,e)if(e.kind==="tiling"){let l=this.ctx.createPattern(e.cell,"repeat");l&&(this.ctx.strokeStyle=l)}else{let l=this.createCanvasGradient(e.shading,e.matrix);l&&(this.ctx.strokeStyle=l)}let n=this.deviceBase(),r=Math.sqrt(Math.abs(n[0]*n[3]-n[1]*n[2]))||1,i=this.state.ctm,o=Math.sqrt(Math.abs(i[0]*i[3]-i[1]*i[2]))||1,s=r*o,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 i=Ce(this.deviceBase(),e.matrix);if(e.kind==="tiling"){let o=this.ctx.createPattern(e.cell,"repeat");if(!o)return;let s=Ce(i,e.layout.paintTransform);this.ctx.setTransform(s[0],s[1],s[2],s[3],s[4],s[5]),this.ctx.fillStyle=o,this.floodCanvasExtent(s,Math.max(e.layout.cellPxW,e.layout.cellPxH))}else this.paintShadingBackground(e.shading,i),this.paintShadingWithBase(e.shading,e.stream,i)}finally{this.ctx.restore()}}paintShadingBackground(e,n){var a,l;let r=bt(e.entries.get("Background"));if(!r||!r.length)return;let i=(a=Ee(e.entries.get("ColorSpace")))!=null?a:"DeviceRGB",o=(l=Et(i))!=null?l:"DeviceRGB",s=Fn(Rn(o,r));this.ctx.save(),this.ctx.setTransform(n[0],n[1],n[2],n[3],n[4],n[5]),this.ctx.fillStyle=Tt(s.r,s.g,s.b),this.floodCanvasExtent(n,0),this.ctx.restore()}paintShadingWithBase(e,n,r){var o;let i=Math.floor((o=V(e.entries.get("ShadingType")))!=null?o:0);if(i===2||i===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(i===1){this.paintFunctionShading(e,r);return}i>=4&&i<=7&&n&&this.paintMeshShading(i,e,n,r)}paintFunctionShading(e,n){var P,S,R,I,F,A,G,Y;if(!this.objectLoader)return;let r=e.entries.get("Function");if(!r)return;let i=(P=bt(e.entries.get("Domain")))!=null?P:[0,1,0,1],[o,s,a,l]=[(S=i[0])!=null?S:0,(R=i[1])!=null?R:1,(I=i[2])!=null?I:0,(F=i[3])!=null?F:1];if(!(s>o)||!(l>a))return;let c=(A=Jr(e.entries.get("Matrix")))!=null?A:[1,0,0,1,0,0],d=(G=Ee(e.entries.get("ColorSpace")))!=null?G:"DeviceRGB",h=(Y=Et(d))!=null?Y:"DeviceRGB",f=128,m=128,p=new ImageData(f,m);for(let E=0;E<m;E++){let ee=a+(E+.5)/m*(l-a);for(let ne=0;ne<f;ne++){let O=o+(ne+.5)/f*(s-o),ge=Ws(r,[O,ee],this.objectLoader);if(!ge)continue;let fe=Fn(Rn(h,ge)),Oe=(E*f+ne)*4;p.data[Oe]=Math.round(fe.r*255),p.data[Oe+1]=Math.round(fe.g*255),p.data[Oe+2]=Math.round(fe.b*255),p.data[Oe+3]=255}}let b=document.createElement("canvas");b.width=f,b.height=m;let y=b.getContext("2d");if(!y)return;y.putImageData(p,0,0);let k=[(s-o)/f,0,0,(l-a)/m,o,a],w=Ce(Ce(n,c),k);this.ctx.save(),this.ctx.setTransform(w[0],w[1],w[2],w[3],w[4],w[5]),this.ctx.drawImage(b,0,0),this.ctx.restore()}paintMeshShading(e,n,r,i){var k,w,P,S,R,I;if(!this.objectLoader)return;let o=this.objectLoader,s=this.meshCache.get(n);if(!s){try{let F=Pe.decodeStreamSync(r),A=(k=Ee(n.entries.get("ColorSpace")))!=null?k:"DeviceRGB",G=(w=Et(A))!=null?w:"DeviceRGB",Y=n.entries.get("Function"),E=Y?1:Ig(G),ee=bt(n.entries.get("Decode"));if(!ee)return;let ne=O=>{var Oe;let ge=Y&&(Oe=Ws(Y,O,o))!=null?Oe:O,fe=Fn(Rn(G,ge));return[fe.r,fe.g,fe.b]};s=kd(e,{bitsPerCoordinate:Math.floor((P=V(n.entries.get("BitsPerCoordinate")))!=null?P:16),bitsPerComponent:Math.floor((S=V(n.entries.get("BitsPerComponent")))!=null?S:8),bitsPerFlag:Math.floor((R=V(n.entries.get("BitsPerFlag")))!=null?R:8),decode:ee,numColorComponents:E,verticesPerRow:(I=V(n.entries.get("VerticesPerRow")))!=null?I:void 0},F,ne)}catch{s=[]}this.meshCache.set(n,s)}if(!s.length)return;let a=1/0,l=1/0,c=-1/0,d=-1/0;for(let F of s)for(let[A,G]of F.p){let Y=He(i,A,G);Y.x<a&&(a=Y.x),Y.x>c&&(c=Y.x),Y.y<l&&(l=Y.y),Y.y>d&&(d=Y.y)}a=Math.max(0,Math.floor(a)),l=Math.max(0,Math.floor(l)),c=Math.min(this.canvas.width,Math.ceil(c)),d=Math.min(this.canvas.height,Math.ceil(d));let h=Math.min(4096,c-a),f=Math.min(4096,d-l);if(h<=0||f<=0)return;let m=Ce([1,0,0,1,-a,-l],i),p=Pd(s,m,h,f),b=document.createElement("canvas");b.width=h,b.height=f;let y=b.getContext("2d");y&&(y.putImageData(new ImageData(p,h,f),0,0),this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.drawImage(b,a,l),this.ctx.restore())}floodCanvasExtent(e,n){let r=mr(e);if(!r)return;let i=this.canvas.width,o=this.canvas.height,s=[He(r,0,0),He(r,i,0),He(r,0,o),He(r,i,o)],a=s.map(m=>m.x),l=s.map(m=>m.y),c=Math.min(...a)-n,d=Math.min(...l)-n,h=Math.max(...a)+n,f=Math.max(...l)+n;this.ctx.fillRect(c,d,h-c,f-d)}createCanvasGradient(e,n){var y,k,w,P;let r=Math.floor((y=V(e.entries.get("ShadingType")))!=null?y:0),i=(k=Ee(e.entries.get("ColorSpace")))!=null?k:"DeviceRGB",o=(w=Et(i))!=null?w:"DeviceRGB",s=e.entries.get("Function"),a=(P=bt(e.entries.get("Domain")))!=null?P:[0,1],[l,c]=Lg(e.entries.get("Extend")),d=S=>{var F,A;let R=a[0]+S*(((F=a[1])!=null?F:1)-a[0]),I=this.objectLoader?(A=Vi(s,R,this.objectLoader))!=null?A:[0]:[0];return Fn(Rn(o,I))},h=S=>`rgb(${Math.round(S.r*255)},${Math.round(S.g*255)},${Math.round(S.b*255)})`,f=S=>`rgba(${Math.round(S.r*255)},${Math.round(S.g*255)},${Math.round(S.b*255)},0)`,m=bt(e.entries.get("Coords"));if(!m)return null;let p=(S,R)=>n?[n[0]*S+n[2]*R+n[4],n[1]*S+n[3]*R+n[5]]:[S,R],b=S=>{let I=.000244140625,F=l?0:I,A=c?1:1-I;l||S.addColorStop(0,f(d(0)));for(let G=0;G<=64;G++){let Y=G/64;S.addColorStop(F+Y*(A-F),h(d(Y)))}c||S.addColorStop(1,f(d(1)))};try{if(r===2){let[S,R,I,F]=m,[A,G]=p(S,R),[Y,E]=p(I,F),ee=this.ctx.createLinearGradient(A,G,Y,E);return b(ee),ee}if(r===3){let[S,R,I,F,A,G]=m,[Y,E]=p(S,R),[ee,ne]=p(F,A),O=n?(Math.hypot(n[0],n[1])+Math.hypot(n[2],n[3]))/2:1,ge=this.ctx.createRadialGradient(Y,E,Math.max(0,I*O),ee,ne,Math.max(0,G*O));return b(ge),ge}}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<wr.MAX_LAYER_DEPTH&&this.layerPool.push(e)}pushLayer(e,n,r,i){if(this.layerStack.length>=wr.MAX_LAYER_DEPTH)return!1;let o=this.acquireLayerCanvas(),s=o==null?void 0:o.getContext("2d");return!o||!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:o,alpha:n,blend:r,mask:i,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=Gd(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 i=r.entries.get("SMask");if(!i)return;if(Ee(i)==="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 o=this.resolveObject(i);if(!o||!Q(o))return;let s=await this.renderSMaskCanvas(o);if(!s)return;this.pushLayer("smask",1,"Normal",s)}catch{}}async renderSMaskCanvas(e){var h;let n=this.resolveObject(e.entries.get("G"));if(!n||!he(n))return null;let r=((h=Ee(e.entries.get("S")))!=null?h:"Alpha")==="Luminosity",i=this.acquireLayerCanvas(),o=i==null?void 0:i.getContext("2d",{willReadFrequently:!0});if(!i||!o)return null;if(r){let f=bt(e.entries.get("BC"));if(o.save(),o.setTransform(1,0,0,1,0,0),f&&f.length){let m=Fn(Rn(f.length===1?"DeviceGray":f.length===4?"DeviceCMYK":"DeviceRGB",f));o.fillStyle=Tt(m.r,m.g,m.b)}else o.fillStyle="black";o.fillRect(0,0,i.width,i.height),o.restore()}o.setTransform(this.ctx.getTransform());let s=this.ctx,a=this.capturedTextRuns.length;this.ctx=o,this.captureSuppressed+=1;try{await this.renderFormStreamInline(n)}finally{this.captureSuppressed-=1,this.ctx=s,this.capturedTextRuns.length=a}let l=e.entries.get("TR"),c=this.objectLoader,d=l&&c&&Ee(l)!=="Identity"?f=>{let m=Vi(l,f,c);return m&&m.length?Math.max(0,Math.min(1,m[0])):f}:null;try{let f=o.getImageData(0,0,i.width,i.height),m=f.data;for(let p=0;p<m.length;p+=4){let b=r?(.3*m[p]+.59*m[p+1]+.11*m[p+2])/255:m[p+3]/255,y=d?d(b):b;m[p+3]=Math.round(y*255)}o.putImageData(f,0,0)}catch{return this.releaseLayerCanvas(i),null}return i}async renderFormStreamInline(e){let n=e.decode?await e.decode():Pe.decodeStreamSync(e),r=un(n),i=this.pageResources,o=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 l=Jr(e.dict.entries.get("Matrix"));l&&this.execute({op:"set_ctm",matrix:l});let c=bt(e.dict.entries.get("BBox"));c&&c.length>=4&&(this.ctx.beginPath(),this.ctx.rect(c[0],c[1],c[2]-c[0],c[3]-c[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=i,this.objectLoader=o,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)),i=r?he(r)?r.dict:Q(r)?r:null:null;if(!i)return;let o=r&&he(r)?r:null;this.ctx.save();try{this.ctx.globalAlpha=this.state.fillAlpha;let s=bt(i.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=Ce(this.deviceBase(),this.state.ctm);this.paintShadingWithBase(i,o,a)}finally{this.ctx.restore()}}catch{}}};wr.MAX_LAYER_DEPTH=6;var Qr=wr,Ig=t=>t==="DeviceGray"||t==="CalGray"?1:t==="DeviceCMYK"?4:3,Gd=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"}},bt=t=>!t||!ue(t)?null:t.items.map(e=>{var n;return(n=V(e))!=null?n:0}),Bg=new Set(["FlateDecode","Fl","LZWDecode","LZW","ASCII85Decode","A85","ASCIIHexDecode","AHx","RunLengthDecode","RL","Crypt"]),Jr=t=>{let e=bt(t);return!e||e.length<6?null:[e[0],e[1],e[2],e[3],e[4],e[5]]},jg=(t,e,n)=>{let r=[He(n,e[0],e[1]),He(n,e[2],e[1]),He(n,e[2],e[3]),He(n,e[0],e[3])],i=r.map(w=>w.x),o=r.map(w=>w.y),s=Math.min(...i),a=Math.max(...i),l=Math.min(...o),c=Math.max(...o),d=Math.min(t[0],t[2]),h=Math.max(t[0],t[2]),f=Math.min(t[1],t[3]),m=Math.max(t[1],t[3]),p=a-s,b=c-l;if(!(p>1e-6)||!(b>1e-6))return null;let y=(h-d)/p,k=(m-f)/b;return[y,0,0,k,d-y*s,f-k*l]},Lg=t=>{if(!t||!ue(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])]},Tt=(t,e,n)=>`rgb(${Math.round(rt(t)*255)},${Math.round(rt(e)*255)},${Math.round(rt(n)*255)})`,mn=t=>{if(t.space==="rgb")return Tt(t.r,t.g,t.b);if(t.space==="gray")return Tt(t.gray,t.gray,t.gray);let e=no(t.c,t.m,t.y,t.k);return Tt(e.r,e.g,e.b)},Fn=t=>{if(t.space==="rgb")return{r:rt(t.r),g:rt(t.g),b:rt(t.b)};if(t.space==="gray"){let e=rt(t.gray);return{r:e,g:e,b:e}}return no(t.c,t.m,t.y,t.k)},Et=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}},Vd=t=>{var r;let e=Ee(t),n=e?Et(e):null;if(n)return n;if(t&&ue(t)&&t.items.length>0){let i=Ee(t.items[0]),o=i?Et(i):null;if(o)return o;if(i==="ICCBased"){let s=t.items[1];if(s&&he(s)){let a=Math.floor((r=V(s.dict.entries.get("N")))!=null?r:0);if(a===1)return"DeviceGray";if(a===3)return"DeviceRGB";if(a===4)return"DeviceCMYK"}}if(i==="CalGray")return"DeviceGray";if(i==="CalRGB")return"DeviceRGB";if(i==="Lab")return"Lab";if(i==="Separation")return"Separation";if(i==="DeviceN")return"DeviceN";if(i==="Indexed")return"Indexed";if(i==="Pattern")return"Pattern"}return null},Ug=(t,e,n)=>{let r=(t+16)/116,i=e/500+r,o=r-n/200,s=p=>p>.206897?p*p*p:(p-16/116)/7.787,a=.9642*s(i),l=1*s(r),c=.8249*s(o),d=3.1338561*a-1.6168667*l-.4906146*c,h=-.9787684*a+1.9161415*l+.033454*c,f=.0719453*a-.2289914*l+1.4052427*c,m=p=>p<=.0031308?12.92*p:1.055*Math.pow(Math.max(0,p),1/2.4)-.055;return{r:rt(m(d)),g:rt(m(h)),b:rt(m(f))}},Rn=(t,e)=>{var r,i,o,s,a,l,c,d,h,f,m,p,b,y,k,w,P;let n=Et(t);if(n==="DeviceGray")return{space:"gray",gray:(r=e[0])!=null?r:0};if(n==="DeviceCMYK")return{space:"cmyk",c:(i=e[0])!=null?i:0,m:(o=e[1])!=null?o: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:(l=e[0])!=null?l:0,g:(c=e[1])!=null?c:0,b:(d=e[2])!=null?d:0};if(t==="Lab"){let S=Ug((h=e[0])!=null?h:0,(f=e[1])!=null?f:0,(m=e[2])!=null?m: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:(b=e[0])!=null?b:0,m:(y=e[1])!=null?y:0,y:(k=e[2])!=null?k:0,k:(w=e[3])!=null?w:0}:{space:"gray",gray:(P=e[0])!=null?P:0}},Kd=t=>{if(!t)return[];let e=Ee(t);return e?[e]:ue(t)?t.items.map(n=>Ee(n)).filter(n=>n!==null):[]},Qs=async(t,e)=>typeof createImageBitmap=="function"?createImageBitmap(new Blob([t.slice().buffer],{type:e})):new Promise((n,r)=>{let i=new Image,o=URL.createObjectURL(new Blob([t.slice().buffer],{type:e}));i.onload=()=>{URL.revokeObjectURL(o),n(i)},i.onerror=()=>{URL.revokeObjectURL(o),r(new Error(`Could not decode image ${e}`))},i.src=o}),ea=t=>{"close"in t&&typeof t.close=="function"&&t.close()},$g=(t,e)=>{let n=t.entries.get("Widths");if(!n||!ue(n))return;let r=new Map;return n.items.forEach((i,o)=>{let s=V(i);s!==null&&r.set(e+o,s)}),r.size>0?r:void 0},qd=(t,e)=>{let n=t.entries.get("DescendantFonts");if(!n||!ue(n)||n.items.length===0)return;let r=e(n.items[0]);return r&&Q(r)?r:void 0},Jd=(t,e,n)=>{let r=n(t.entries.get("FontDescriptor"));if(r&&Q(r))return r;let i=n(e==null?void 0:e.entries.get("FontDescriptor"));return i&&Q(i)?i:void 0},_g=t=>{let e=t==null?void 0:t.entries.get("W");if(!e||!ue(e))return;let n=new Map,r=e.items;for(let i=0;i<r.length;i+=1){let o=V(r[i]);if(o===null)continue;let s=r[i+1];if(s&&ue(s)){s.items.forEach((c,d)=>{let h=V(c);h!==null&&n.set(o+d,h)}),i+=1;continue}let a=V(s),l=V(r[i+2]);if(!(a===null||l===null)){for(let c=o;c<=a;c+=1)n.set(c,l);i+=2}}return n.size>0?n:void 0},zg=t=>{let e=V(t==null?void 0:t.entries.get("DW"));return e!=null?e:void 0},Xg=t=>{let e=t.entries.get("FontDescriptor");if(!e||!Q(e))return;let n=V(e.entries.get("MissingWidth"));return n!=null?n:void 0},Yg=(t,e,n,r,i,o,s)=>{let a=n.isComposite?Gg(t,n.toUnicode):Array.from(t).map((f,m)=>({code:f,bytes:t.slice(m,m+1)})),l=Array.from(e),c=!!n.widths||n.defaultWidth!==void 0,d=0;return{glyphs:a.map(f=>{var w,P,S;let m=n.toUnicode?gn(f.code,n.toUnicode):null,p=(w=m!=null?m:l[d])!=null?w:"";d+=Math.max(1,Array.from(p).length);let b=(S=(P=n.widths)==null?void 0:P.get(f.code))!=null?S:n.defaultWidth,y;b!==void 0?y=b/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 k=i+(p===" "||f.code===32?o:0);return{text:p,code:f.code,bytes:f.bytes,glyphWidth:y,advance:y+k}}),hasPdfMetrics:c}},ra=t=>{var r;let e=ro((r=t.baseFontName)!=null?r:"").toLowerCase(),n=iu(e);return t.registeredFamily?`"${t.registeredFamily}", ${n}`:n},Zd=(t,e)=>{var s,a,l;let r=ro((s=t.baseFontName)!=null?s:"").toLowerCase(),i=(a=t.fontStyle)!=null?a:r.includes("italic")||r.includes("oblique")?"italic":"normal",o=String((l=t.fontWeight)!=null?l:r.includes("bold")||r.includes("black")?700:400);return t.registeredFamily?`${e}px ${ra(t)}`:`${i} ${o} ${e}px ${iu(r)}`},Wg=(t,e)=>{var s;let n=ro(t!=null?t:"").toLowerCase(),r=V(e==null?void 0:e.entries.get("FontWeight"));if(r!==null)return Math.max(100,Math.min(900,Math.round(r/100)*100));let i=Math.floor((s=V(e==null?void 0:e.entries.get("Flags")))!=null?s:0),o=V(e==null?void 0:e.entries.get("StemV"));if(n.includes("bold")||n.includes("black")||n.includes("heavy")||(i&262144)!==0||o!==null&&o>=120)return 700},Hg=(t,e)=>{var o;let n=ro(t!=null?t:"").toLowerCase(),r=Math.floor((o=V(e==null?void 0:e.entries.get("Flags")))!=null?o:0),i=V(e==null?void 0:e.entries.get("ItalicAngle"));if(n.includes("italic")||n.includes("oblique")||(r&64)!==0||i!==null&&i!==0)return"italic"},ro=t=>/^[A-Z]{6}\+/.test(t)?t.slice(7):t,iu=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"),Gg=(t,e)=>{var r,i;if(t.length===0)return[];if(e!=null&&e.codeSpaceRanges.length){let o=Array.from(new Set(e.codeSpaceRanges.map(a=>a.byteLength))).sort((a,l)=>l-a),s=[];for(let a=0;a<t.length;){let l=0,c=0;for(let d of o){if(a+d>t.length)continue;let h=vr(t,a,d);if(h!==null&&au(h,d,e.codeSpaceRanges)){l=d,c=h;break}}l===0&&(l=Math.min(2,t.length-a),c=(r=vr(t,a,l))!=null?r:t[a]),s.push({code:c,bytes:t.slice(a,a+l)}),a+=l}return s}let n=[];for(let o=0;o<t.length;){let s=Math.min(2,t.length-o);n.push({code:(i=vr(t,o,s))!=null?i:t[o],bytes:t.slice(o,o+s)}),o+=s}return n},Vg=t=>{var i;if(!t)return null;let e=t.match(/^uni([0-9A-Fa-f]{4,6})$/);if(e){let o=parseInt(e[1],16);try{return String.fromCodePoint(o)}catch{return null}}let n=t.match(/^u([0-9A-Fa-f]{5,6})$/);if(n){let o=parseInt(n[1],16);try{return String.fromCodePoint(o)}catch{return null}}return t.length===1?t:(i={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?i:null},Qd=(()=>{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})(),eu=(()=>{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})(),Kg=(t,e)=>{if(!t)return;let n=e(t);if(!n)return;let r=Ee(n);if(r)return r==="MacRomanEncoding"?new Map(Qd):r==="WinAnsiEncoding"?new Map(eu):void 0;if(!Q(n))return;let i=n,o=Ee(i.entries.get("BaseEncoding")),s;o==="MacRomanEncoding"?s=new Map(Qd):o==="WinAnsiEncoding"?s=new Map(eu):s=new Map;let a=i.entries.get("Differences");if(!a||!ue(a))return s.size>0?s:void 0;let l=0;for(let c of a.items){let d=V(c);if(d!==null)l=Math.floor(d);else{let h=Ee(c);if(h){let f=Vg(h);f&&s.set(l,f),l++}}}return s.size>0?s:void 0},qg=(t,e)=>{let n=new Map;if(!t)return n;let r=e(t);if(!r||!Q(r))return n;let i=r.entries.get("Differences");if(!i||!ue(i))return n;let o=0;for(let s of i.items){let a=V(s);if(a!==null)o=Math.floor(a);else{let l=Ee(s);l&&(n.set(o,l),o++)}}return n},no=(t,e,n,r)=>({r:(1-rt(t))*(1-rt(r)),g:(1-rt(e))*(1-rt(r)),b:(1-rt(n))*(1-rt(r))}),rt=t=>!Number.isFinite(t)||t<0?0:t>1?1:t,Jg=(t,e,n)=>Number.isFinite(t)?Math.min(n,Math.max(e,t)):e,Zg=t=>({...t,ctm:[...t.ctm],textMatrix:[...t.textMatrix],textLineMatrix:[...t.textLineMatrix],fillColor:{...t.fillColor},strokeColor:{...t.strokeColor},dashArray:[...t.dashArray]}),He=(t,e,n)=>({x:t[0]*e+t[2]*n+t[4],y:t[1]*e+t[3]*n+t[5]}),Qi=()=>({subtype:"Unknown",baseFontName:void 0,isComposite:!1,firstChar:void 0,widths:void 0,defaultWidth:void 0,toUnicode:null}),Qg=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
|
-
`),
|
|
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
|
+
`),i=e0(r);for(let o=0;o<i.length;){let s=i[o];if(s==="usecmap"){let a=o>0?i[o-1]:"(unknown)";console.warn("[PageRenderer][CMap] usecmap reference not resolved",{inheritedName:a}),o+=1;continue}if(s==="begincmap"){for(o+=1;o<i.length&&i[o]!=="endcmap";){let a=i[o];if(n0(a))break;let l=i[o+1];if(Gt(a)&&Gt(l)){e.bfChar.set(to(a),eo(Wn(l))),o+=2;continue}o+=1}continue}if(s==="beginbfchar"||s==="begincidchar"){for(o+=1;o<i.length&&i[o]!=="endbfchar"&&i[o]!=="endcidchar";){let a=i[o],l=i[o+1];if(Gt(a)&&Gt(l)){e.bfChar.set(to(a),eo(Wn(l))),o+=2;continue}if(Zr(a)&&Gt(l)){e.bfChar.set(Number.parseInt(a,10),eo(Wn(l))),o+=2;continue}if(Zr(a)&&Zr(l)){let c=Number.parseInt(a,10),d=Number.parseInt(l,10);if(Number.isFinite(c)&&Number.isFinite(d))try{e.bfChar.set(c,String.fromCodePoint(d))}catch{e.bfChar.set(c,"\uFFFD")}o+=2;continue}o+=1}o<i.length&&(o+=1);continue}if(s==="begincodespacerange"){for(o+=1;o<i.length&&i[o]!=="endcodespacerange";){let a=i[o],l=i[o+1];if(!Gt(a)||!Gt(l)){o+=1;continue}let c=Wn(a),d=Wn(l),h=Math.max(c.length,d.length)/2;h>0&&e.codeSpaceRanges.push({start:Number.parseInt(c,16),end:Number.parseInt(d,16),byteLength:h}),o+=2}o<i.length&&(o+=1);continue}if(s==="beginbfrange"||s==="begincidrange"){for(o+=1;o<i.length&&i[o]!=="endbfrange"&&i[o]!=="endcidrange";){let a=i[o],l=i[o+1];if(!a||!l){o+=1;continue}let c=tu(a),d=tu(l);if(c===null||d===null){o+=1;continue}let h=i[o+2];if(!h){o+=2;continue}if(h==="["){let f=[],m=o+3;for(;m<i.length&&i[m]!=="]";)Gt(i[m])&&f.push(eo(Wn(i[m]))),m+=1;e.bfRange.push({start:c,end:d,mapped:f}),o=m<i.length?m+1:m;continue}if(Gt(h)){e.bfRange.push({start:c,end:d,unicodeStart:to(h)}),o+=3;continue}if(Zr(h)){e.bfRange.push({start:c,end:d,unicodeStart:Number.parseInt(h,10)}),o+=3;continue}o+=1}o<i.length&&(o+=1);continue}o+=1}return e},e0=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 i=n;for(n+=1;n<t.length&&t[n]!==">";)n+=1;n<t.length&&(n+=1),e.push(t.slice(i,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 i=t.slice(r,n),o=t0(i);o?(o.count&&e.push(o.count),e.push(o.keyword)):e.push(i)}}return e},t0=t=>{let e=t.match(/^(\d+)?(begin\w+|end\w+|usecmap|begincmap|endcmap)$/i);return e?{count:e[1],keyword:e[2]}:null},n0=t=>t?t==="beginbfchar"||t==="endbfchar"||t==="beginbfrange"||t==="endbfrange"||t==="begincidchar"||t==="endcidchar"||t==="begincidrange"||t==="endcidrange"||t==="begincodespacerange"||t==="endcodespacerange":!1,Gt=t=>!!t&&t.startsWith("<")&&t.endsWith(">"),Zr=t=>!!t&&/^\d+$/.test(t),Wn=t=>t.slice(1,-1),to=t=>Number.parseInt(Wn(t),16),tu=t=>Gt(t)?to(t):Zr(t)?Number.parseInt(t,10):null,eo=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 i=e.slice(r,r+4).padStart(4,"0"),o=Number.parseInt(i,16);if(!Number.isFinite(o)){n+="\uFFFD";continue}try{n+=String.fromCodePoint(o)}catch{n+="\uFFFD"}}return n},r0=(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[i,o]of t.bfChar.entries()){if(n>=10)break;let s=o.codePointAt(0);console.log(` 0x${i.toString(16).padStart(4,"0")} -> "${o}" (U+${(r=s==null?void 0:s.toString(16).toUpperCase())!=null?r:"????"})`),n+=1}for(let i of t.bfRange.slice(0,5))typeof i.unicodeStart=="number"?console.log(` range 0x${i.start.toString(16).padStart(4,"0")}-0x${i.end.toString(16).padStart(4,"0")} -> U+${i.unicodeStart.toString(16).toUpperCase()}`):i.mapped&&console.log(` range 0x${i.start.toString(16).padStart(4,"0")}-0x${i.end.toString(16).padStart(4,"0")} -> [mapped:${i.mapped.length}]`);for(let i of t.codeSpaceRanges.slice(0,5))console.log(` codespace ${i.byteLength}b 0x${i.start.toString(16).padStart(i.byteLength*2,"0")}-0x${i.end.toString(16).padStart(i.byteLength*2,"0")}`)},gn=(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 i=t-r.start;return i>=0&&i<r.mapped.length?r.mapped[i]:null}if(typeof r.unicodeStart=="number"){let i=r.unicodeStart+(t-r.start);return String.fromCodePoint(i)}}return null},i0=(t,e,n,r,i=!1)=>{var s,a;if(n){let l=x0(e),c=c0(e),h=(c?[{mode:"raw",bytes:t}]:a0(t)).map(y=>({mode:y.mode,attempt:s0(y.bytes,e,l)})),f=l0(h),m=f.attempt,p=w0(m)?v0(t):null,b=k0(m,p);if(i&&console.debug("[PageRenderer][CMap] decode strategy",{font:r!=null?r:"?",mapped:m.mapped,unmapped:m.unmapped,utf16Score:(s=p==null?void 0:p.score)!=null?s:null,codespaceRanges:e.codeSpaceRanges.length,inferredCodeLengths:l,payloadMode:f.mode,sparseToUnicode:c,chosen:b===p?"utf16be":"cmap"}),i&&m.unmappedGlyphs.length>0){let y=m.unmappedGlyphs.slice(0,12).map(P=>`0x${P.toString(16).padStart(4,"0")}`),k=b0(m.unmappedGlyphs,l),w=c?`${r!=null?r:"?"}|sparse-tounicode`:`${r!=null?r:"?"}|${f.mode}`;zd.has(w)||(zd.add(w),console.warn("[PageRenderer][CMap] unmapped composite glyphs",{font:r!=null?r:"?",count:m.unmappedGlyphs.length,payloadMode:f.mode,sparseToUnicode:c,rootCause:c?`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:k.topMissing,mappingHints:k.mappingHints,note:"Use mappingHints as candidate ToUnicode entries (<src> <dst>) for manual verification."}))}return(a=b==null?void 0:b.text)!=null?a:m.text}let o=[];for(let l=0;l<t.length;l++){let c=gn(t[l],e);o.push(c!==null?c:String.fromCharCode(t[l]))}return o.join("")},o0=(t,e)=>{let n=[],r=0;for(;r+1<t.length;){let i=t[r],o=t[r+1],s=i<<8|o,a=gn(s,e);if(a!==null){n.push(a),r+=2;continue}if(o>=32&&o<=126){n.push(String.fromCharCode(o)),r+=2;continue}if(i>=32&&i<=126){n.push(String.fromCharCode(i)),r+=2;continue}r+=2}if(r<t.length){let i=t[r];i>=32&&i<=126&&n.push(String.fromCharCode(i))}return n.join("")},s0=(t,e,n)=>e.codeSpaceRanges.length>0?p0(t,e):g0(t,e,n),a0=t=>{var s;let e=[{mode:"raw",bytes:t}],n=new Set([`raw:${t.length}:${(s=t[0])!=null?s:-1}`]),r=(a,l)=>{var d,h;if(!l||l.length===0)return;let c=`${a}:${l.length}:${(d=l[0])!=null?d:-1}:${(h=l[1])!=null?h:-1}`;n.has(c)||(n.add(c),e.push({mode:a,bytes:l}))},i=d0(t);r("zero-stripped",i);let o=u0(t);return r("pair-swapped",o),r("ascii-hex",ta(t)),i&&r("zero-stripped+ascii-hex",ta(i)),o&&r("pair-swapped+ascii-hex",ta(o)),e},c0=t=>t.bfChar.size+t.bfRange.length<=2,l0=t=>{let e=t[0],n=nu(e.attempt);for(let r=1;r<t.length;r+=1){let i=t[r],o=nu(i.attempt);o>n+1&&(e=i,n=o)}return e},d0=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,i=e>=Math.floor(r*.7),o=n>=Math.floor(r*.7);if(!i&&!o)return null;let s=new Uint8Array(r);for(let a=0;a<r;a+=1)s[a]=i?t[a*2+1]:t[a*2];return s},u0=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},nu=t=>t.mapped*2-t.unmapped,ta=t=>{if(t.length<8)return null;let e=0,n=0,r=0,i=[];for(let s of t)if(!f0(s)){if(n+=1,!h0(s))return null;(s>=65&&s<=70||s>=97&&s<=102)&&(r+=1),e+=1,i.push(String.fromCharCode(s))}if(n<8||e!==n||e%2!==0||r===0)return null;let o=new Uint8Array(e/2);for(let s=0;s<o.length;s+=1){let a=ru(i[s*2]),l=ru(i[s*2+1]);if(a<0||l<0)return null;o[s]=a<<4|l}return o},f0=t=>t===32||t===9||t===10||t===13,h0=t=>t>=48&&t<=57||t>=65&&t<=70||t>=97&&t<=102,ru=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,m0=(t,e)=>{let n=[],r=0,i=0,o=[];for(let s=0;s<t.length;){if(s+1<t.length){let l=t[s]<<8|t[s+1],c=gn(l,e);if(c!==null){n.push(c),r+=1,s+=2;continue}let d=gn(t[s],e),h=gn(t[s+1],e);if(d!==null||h!==null){n.push("\uFFFD\uFFFD"),i+=1,o.push(l),s+=2;continue}n.push("\uFFFD"),i+=1,o.push(l),s+=2;continue}let a=gn(t[s],e);a!==null?(n.push(a),r+=1):(n.push("\uFFFD"),i+=1,o.push(t[s])),s+=1}return{text:n.join(""),mapped:r,unmapped:i,unmappedGlyphs:o}},p0=(t,e)=>{let n=Array.from(new Set(e.codeSpaceRanges.map(a=>a.byteLength))).sort((a,l)=>l-a);if(n.length===0)return m0(t,e);let r=[],i=0,o=0,s=[];for(let a=0;a<t.length;){let l=0,c=null;for(let h of n){if(a+h>t.length)continue;let f=vr(t,a,h);if(f!==null&&au(f,h,e.codeSpaceRanges)){l=h,c=f;break}}if(l>0&&c!==null){let h=gn(c,e);h!==null?(r.push(h),i+=1):(r.push("\uFFFD"),o+=1,s.push(c)),a+=l;continue}let d=a+1<t.length?t[a]<<8|t[a+1]:t[a];r.push("\uFFFD"),o+=1,s.push(d),a+=1}return{text:r.join(""),mapped:i,unmapped:o,unmappedGlyphs:s}},g0=(t,e,n)=>{var l,c;let r=n.length>0?[...n].sort((d,h)=>h-d):[2,1],i=[],o=0,s=0,a=[];for(let d=0;d<t.length;){let h=0,f=null;for(let b of r){if(d+b>t.length)continue;let y=vr(t,d,b);if(y===null)continue;let k=gn(y,e);if(k!==null){f=k,h=b;break}}if(f!==null&&h>0){i.push(f),o+=1,d+=h;continue}let m=(l=r[r.length-1])!=null?l:1,p=(c=vr(t,d,Math.min(m,t.length-d)))!=null?c:t[d];i.push("\uFFFD"),s+=1,a.push(p),d+=Math.min(m,t.length-d)}return{text:i.join(""),mapped:o,unmapped:s,unmappedGlyphs:a}},x0=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(na(r));for(let r of t.bfRange)e.add(na(r.start)),e.add(na(r.end));let n=Array.from(e).filter(r=>r>=1&&r<=4);return n.length===0?[2,1]:n.sort((r,i)=>i-r)},na=t=>t<=255?1:t<=65535?2:t<=16777215?3:4,b0=(t,e)=>{var l;let n=new Map;for(let c of t)n.set(c,((l=n.get(c))!=null?l:0)+1);let i=Array.from(n.entries()).sort((c,d)=>d[1]-c[1]).slice(0,8),o=i.map(([c,d])=>({glyph:`0x${c.toString(16).padStart(4,"0")}`,count:d})),s=e.length>0?e[e.length-1]:2,a=i.map(([c])=>y0(c,s)).filter(c=>c!==null);return{topMissing:o,mappingHints:a}},y0=(t,e)=>{let n=t.toString(16).padStart(Math.max(4,e*2),"0"),r=t&255;if(r>=32&&r<=126){let i=r.toString(16).toUpperCase().padStart(4,"0");return{glyph:`0x${n}`,candidateUnicode:`U+${i} (${String.fromCharCode(r)})`,reason:"Printable ASCII low-byte candidate",cmapLine:`<${n}> <${i}>`}}if(t>=32&&t<=126){let i=t.toString(16).toUpperCase().padStart(4,"0");return{glyph:`0x${n}`,candidateUnicode:`U+${i} (${String.fromCharCode(t)})`,reason:"Direct ASCII glyph code candidate",cmapLine:`<${n}> <${i}>`}}return null},w0=t=>t.text.length===0?!1:t.mapped>0?t.unmapped>=t.mapped*3:t.unmapped>0,v0=t=>{var o;let e=su(t),n=ou(e),r=((o=e.match(/\uFFFD/g))!=null?o:[]).length,i=n-r*3;return{text:e,mapped:n,unmapped:r,unmappedGlyphs:[],printable:n,score:i}},k0=(t,e)=>{if(!e)return t;let n=P0(t.text);return D0(e.text)&&e.score>=n+8?e:t},P0=t=>{var r;let e=ou(t),n=((r=t.match(/\uFFFD/g))!=null?r:[]).length;return e-n*3},ou=t=>{var n;let e=0;for(let r of t){let i=(n=r.codePointAt(0))!=null?n:0;if(i===9||i===10||i===13){e+=1;continue}if(i>=32&&i<=126){e+=2;continue}if(i>=160&&i<=591){e+=1;continue}}return e},D0=t=>{var i,o;if(!t||((i=t.match(/\uFFFD/g))!=null?i:[]).length>Math.floor(t.length*.2))return!1;let n=0,r=0;for(let s of t){let a=(o=s.codePointAt(0))!=null?o: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)},Ee=t=>t?typeof t=="string"?t:typeof t=="object"&&"type"in t&&t.type==="name"&&"value"in t?String(t.value):null:null,su=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},S0=t=>{var e,n,r,i,o,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:((i=t.match(/begincidrange/g))!=null?i:[]).length,begincodespacerange:((o=t.match(/begincodespacerange/g))!=null?o:[]).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)}},pn=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 i=String((e=t.type)!=null?e:"unknown");return i==="ref"&&"objectNumber"in t?`ref:${String((n=t.objectNumber)!=null?n:"?")}`:i==="name"&&"value"in t?`name:${String((r=t.value)!=null?r:"")}`:i}return typeof t},vr=(t,e,n)=>{if(n<1||n>4||e+n>t.length)return null;let r=0;for(let i=0;i<n;i+=1)r=r<<8|t[e+i];return r>>>0},au=(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 cu}from"react";var C0="/api/decrypt-pdf";function F0(t){let e=new TextDecoder("latin1"),n=Math.min(t.length,1024*1024),r=e.decode(t.subarray(0,n)),i=Math.max(0,t.length-n),o=i===0?"":e.decode(t.subarray(i));return/\/Encrypt\s+(?:\d+\s+\d+\s+R|<<)/.test(`${r}
|
|
44
|
+
${o}`)}function lu(t={}){var l;let e=(l=t.decryptUrl)!=null?l:C0,[n,r]=cu(!1),[i,o]=cu(null),s=async(c,d)=>{r(!0),o(null);try{let h=new Uint8Array(await c.arrayBuffer());if(!d&&!F0(h))return r(!1),{success:!0,pdfBytes:h,isEncrypted:!1,requiresPassword:!1};let f=new FormData;f.append("file",c),d&&f.append("password",d);let m;try{m=await fetch(e,{method:"POST",body:f})}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 o(y),r(!1),{success:!1,isEncrypted:!0,requiresPassword:!0,error:y}}if(m.status===404){let y=`This PDF is password protected, but no decryption endpoint was found at "${e}". Configure \`decryptUrl\` to enable encrypted PDFs.`;return o(y),r(!1),{success:!1,isEncrypted:!0,requiresPassword:!0,error:y}}if(m.ok){let y=new Uint8Array(await m.arrayBuffer());return r(!1),{success:!0,pdfBytes:y,isEncrypted:!0,requiresPassword:!1}}m.status===401&&typeof window!="undefined"&&window.dispatchEvent(new Event("namaha:needs-auth"));let p=await m.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 b=(p==null?void 0:p.error)||"Failed to process PDF";return o(b),r(!1),{success:!1,isEncrypted:!1,requiresPassword:!1,error:b}}catch(h){let f=h instanceof Error?h.message:"Unknown error";return o(f),r(!1),{success:!1,isEncrypted:!1,requiresPassword:!1,error:f}}};return{uploadPdf:s,uploadPdfWithPasswordPrompt:async(c,d=`${c.name} is password protected. Enter the PDF password:`)=>{let h=await s(c);for(let f=0;h.requiresPassword&&f<3;f+=1){let m=window.prompt(f===0?d:`That password did not unlock ${c.name}. Try again:`);if(!m){let p="Password required to process this PDF.";return o(p),{success:!1,isEncrypted:!0,requiresPassword:!0,error:p}}h=await s(c,m)}return h},isLoading:n,error:i}}import{useEffect as R0}from"react";var M0=t=>{if(!t)return!1;let e=t.tagName;return e==="INPUT"||e==="TEXTAREA"||t.isContentEditable===!0};function du({enabled:t=!0,onUndo:e,onSave:n}){R0(()=>{if(!t)return;let r=i=>{if(!(i.ctrlKey||i.metaKey)||i.altKey)return;let o=i.key.toLowerCase();if(o==="s"){i.preventDefault(),n==null||n();return}if(o==="z"&&!i.shiftKey){if(M0(document.activeElement))return;i.preventDefault(),e==null||e()}};return window.addEventListener("keydown",r),()=>window.removeEventListener("keydown",r)},[t,e,n])}import{useSyncExternalStore as uu}from"react";var A0="(max-width: 767px)",N0="(pointer: coarse)";function fu(t){return{subscribe:i=>{if(typeof window=="undefined"||!window.matchMedia)return()=>{};let o=window.matchMedia(t);return o.addEventListener("change",i),()=>o.removeEventListener("change",i)},getSnapshot:()=>typeof window=="undefined"||!window.matchMedia?!1:window.matchMedia(t).matches,getServerSnapshot:()=>!1}}var ia=fu(A0),oa=fu(N0);function hu(){return uu(ia.subscribe,ia.getSnapshot,ia.getServerSnapshot)}function mu(){return uu(oa.subscribe,oa.getSnapshot,oa.getServerSnapshot)}import{ArrowLeft as E0,ArrowRight as O0,Check as io,ChevronUp as I0,ChevronDown as B0,Clock as j0,Download as xu,Edit3 as L0,Eraser as ca,Eye as Cu,FilePlus2 as U0,FileText as ao,Highlighter as $0,Maximize2 as _0,Shapes as z0,History as bu,Lock as X0,MessageSquareText as Fu,MoreHorizontal as yu,MousePointer as Y0,PenTool as la,Replace as W0,RotateCw as wu,ScanText as vu,Search as oo,ShieldCheck as ei,SlidersHorizontal as H0,Image as ku,Share2 as G0,StickyNote as Ru,Trash2 as so,Type as Mu,Upload as sa,X as Ot,ZoomIn as V0,ZoomOut as K0}from"lucide-react";import{Fragment as Vt,jsx as v,jsxs as $}from"react/jsx-runtime";var Au=[{t:"view",icon:v(Cu,{className:"h-4 w-4"}),label:"View",hint:"Read, select text, zoom, navigate & follow links"},{t:"select",icon:v(Y0,{className:"h-4 w-4"}),label:"Select",hint:"Select, move, resize or delete images and graphics"},{t:"edit-text",icon:v(L0,{className:"h-4 w-4"}),label:"Edit",hint:"Edit text"},{t:"add-text",icon:v(Mu,{className:"h-4 w-4"}),label:"Add Text",hint:"Add new text"}],Nu=[{t:"annotate",icon:v($0,{className:"h-4 w-4"}),label:"Annotate"},{t:"draw",icon:v(z0,{className:"h-4 w-4"}),label:"Draw"},{t:"comment",icon:v(Ru,{className:"h-4 w-4"}),label:"Comment"}],Tu=[{t:"sign",icon:v(la,{className:"h-4 w-4"}),label:"Sign"},{t:"redact",icon:v(ca,{className:"h-4 w-4"}),label:"Redact"},{t:"stamp",icon:v(Fu,{className:"h-4 w-4"}),label:"Stamp"},{t:"form",icon:v(ao,{className:"h-4 w-4"}),label:"Forms"}],q0=[...Au,...Nu,...Tu],Pu=new Set(["edit-text","add-text","annotate","draw","form"]),J0={se:"0% 0%",sw:"100% 0%",ne:"0% 100%",nw:"100% 100%",n:"50% 100%",s:"50% 0%",e:"0% 50%",w:"100% 50%"},Z0=30,Mn=2,Du=50,Q0=15,ex=2,Su=t=>{let e=new Uint8Array(t);return new Blob([e.buffer],{type:"application/pdf"})},tx=t=>{var e;try{let n=t.getContext("2d"),r=t.width,i=t.height;if(!n||r<4||i<4)return"#ffffff";let o=[[2,2],[r-3,2],[2,i-3],[r-3,i-3],[Math.floor(r/2),2],[2,Math.floor(i/2)],[r-3,Math.floor(i/2)],[Math.floor(r/2),i-3]],s=new Map;for(let[l,c]of o){let d=n.getImageData(l,c,1,1).data;if(d[3]<200)continue;let h=`${d[0]>>4}-${d[1]>>4}-${d[2]>>4}`,f=(e=s.get(h))!=null?e:{n:0,r:0,g:0,b:0};f.n++,f.r+=d[0],f.g+=d[1],f.b+=d[2],s.set(h,f)}let a=null;for(let l of s.values())(!a||l.n>a.n)&&(a=l);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"}},aa=(t,e)=>({id:crypto.randomUUID(),name:e,blob:t,type:"pdf",size:t.size,metadata:{},history:[]}),nx=({license:t,decryptUrl:e,signUrl:n}={})=>{var ec,tc;let{uploadPdf:r,isLoading:i}=lu({decryptUrl:e}),[o,s]=ie(null),[a,l]=ie(null),[c,d]=ie([]),[h,f]=ie({}),[m,p]=ie(!1),[b,y]=ie(!1),[k,w]=ie(""),[P,S]=ie("view"),[R,I]=ie(""),[F,A]=ie(14),[G,Y]=ie({r:.84,g:0,b:.19}),E=1.4,[ee,ne]=ie(1),O=E*ee,ge=ye(null),[fe,Oe]=ie(0),Te=ye({}),[_,ce]=ie({}),[ae,W]=ie(null),me=ye(null),[xe,be]=ie({}),[Ie,Me]=ie(!1),[Ke,et]=ie(0),[qe,Rt]=ie(!1),[ve,tt]=ie(!1),[Kt,De]=ie(null),it=ye(new Set),pt=ye(new Set),je=ye({}),qt=ye(new Set),Jt=ye({}),kr=ye({}),[Pr,ju]=ie(!1),[Dr,ni]=ie(""),[Lu,Hn]=ie(!1),[Uu,An]=ie(!1),co=ye(null),ri=ye(null),ii=ye(!1),ha=ye(null),xn=ye(null),Je=ye({}),_e=ye({}),ot=ye({}),Mt=ye({}),lo=ye({}),bn=ye(null),oi=ye(new Set),[Nn,It]=ie([]),[ke,St]=ie(null),[ma,pa]=ie(!1),Zt=ye(null),Sr=ye(!1),[At,Tn]=ie([]),uo=ye(null),[ze,Bt]=ie(null),[yt,En]=ie(null),[Ct,ga]=ie(null),Gn=ye(null),[Vn,xa]=ie(null),Cr=ye(null),jt=ye({}),[ba,si]=ie(0),[$u,ai]=ie({}),[On,fo]=ie(null),[ci,ho]=ie(null),[_u,mo]=ie(!1),[Kn,li]=ie(null),Fr=ye(null),qn=ye({}),po=ye(null),go=ye(!1),[Jn,xo]=ie(null),bo=ye(null),[di,Zn]=ie(!1),[yn,ya]=ie(""),[wa,zu]=ie(""),[ui,fi]=ie(0),[dt,hi]=ie([]),Rr=ye(null),[gt,Qn]=ie([]),[ct,Qt]=ie([]),[Lt,Xu]=ie({color:{r:1,g:.85,b:0},opacity:1,strokeWidth:2,fill:null}),Yu=u=>Xu(g=>({...g,...u})),[In,Wu]=ie("highlight"),[va,Hu]=ie("select"),[Ut,Gu]=ie("rect"),[Mr,$t]=ie(null),[yo,Ft]=ie(null),[wo,Ar]=ie(!1),en=ye(null),tn=ye(null),vo=ye(!1),[ka,mi]=ie(null),[Vu,er]=ie(!1),[Pa,Da]=ie(null),[ko,pi]=ie(!1),tr=ye(null),gi=ye(!1),Sa=ye(null),[Ku,Nr]=ie(!1),[Po,Ca]=ie(""),[Do,Fa]=ie(""),[Ra,So]=ie(!1),[Ma,Aa]=ie(null),[nr,Co]=ie([]),[Fo,Ro]=ie(!1),rr=hu(),Na=mu(),[Ta,Mo]=ie(!1),[qu,Bn]=ie(!1),Ao=()=>{var u;return{blob:(u=a!=null?a:o)!=null?u:null,annotations:gt,annots:ct}},No=(u,g,x,D,N)=>Co(T=>{let j=[...T,{id:crypto.randomUUID(),time:new Date,action:u,icon:g,pageIndex:x,detail:D,snapshot:N}],M=j.length-Z0;return M<=0?j:j.map((B,L)=>L<M?{...B,snapshot:null}:B)}),nn=(u,g,x,D)=>No(u,g,x,D,Ao()),Ea=u=>{var x;if(!u.snapshot)return;let g=u.snapshot;bn.current=null,W(null),Bt(null),En(null),It([]),St(null),Qn(g.annotations),Qt((x=g.annots)!=null?x:[]),$t(null),Co(D=>{let N=D.findIndex(T=>T.id===u.id);return N<0?D:D.slice(0,N)}),l(g.blob===o?null:g.blob),w("Reverted to an earlier state.")},Ju=()=>{for(let u=nr.length-1;u>=0;u--)if(nr[u].snapshot){Ea(nr[u]);return}},[Oa,sx]=ie(90),[xi,ax]=ie(0),_t=ye(0);Pt(()=>{sr.getAvailableProcessors().includes("pdf-editor-core")||sr.registerProcessor(new $i)},[]),Pt(()=>{vs(t!=null?t:{})},[t]);let Ia=pu(async u=>{if(!Bi())return u;try{let g=await xs(new Uint8Array(await u.arrayBuffer()));return new Blob([g],{type:"application/pdf"})}catch{return u}},[]),Ae=gu(()=>a!=null?a:o,[a,o]),To=(ec=o==null?void 0:o.name)!=null?ec:"document.pdf",Eo=u=>{let g=lo.current,x=u!=null?u:Object.keys(g).map(Number);for(let D of x){let N=g[D];N&&URL.revokeObjectURL(N),delete g[D]}},Ba=async(u,g)=>{var T,j;let x=g==null?void 0:g.onlyPages,D=!!x&&x.length>0,N=++_t.current;D||p(!0);try{let M=new Uint8Array(await u.arrayBuffer()),B=new ln(M),L=B.parse(),U=fr.getAllPages(L,{objectLoader:te=>B.loadObject(te)}).pages,K=U.map(te=>{var de;let J=(de=te.mediaBox)!=null?de:[0,0,612,792];return{pageIndex:te.pageNum-1,pageNum:te.pageNum,width:Math.max(1,J[2]-J[0]),height:Math.max(1,J[3]-J[1]),mediaBox:J}});d(K);try{let te=B.loadObject(L.rootRef),J=new Map;for(let we of U)J.set(we.pageNum-1,we.dict);let de=te&&"entries"in te?Gl(te,J,we=>B.loadObject(we)):[],pe={},Ne={};for(let we of de)((j=pe[T=we.pageIndex])!=null?j:pe[T]=[]).push(we),we.value!==void 0&&(Ne[we.id]=we.value);if(jt.current=pe,Fr.current){let we=de.find(zt=>zt.name===Fr.current);ho(we?we.id:null),we&&(qn.current[we.id]=we.name)}ai(we=>D?{...Ne,...we}:Ne),mo(de.length>0),si(we=>we+1);let Xe=new Map;for(let we of U)Xe.set(`${we.ref.objNum}:${we.ref.genNum}`,we.pageNum-1);let Be={};for(let we of U){let zt=$s(we.dict,Xe,Ze=>B.loadObject(Ze));zt.length&&(Be[we.pageNum-1]=zt)}Te.current=Be}catch{jt.current={},Te.current={},mo(!1)}if(D||(Eo(),f({}),ce({}),_e.current={},ot.current={},Mt.current={}),U.length===0){w("No pages were found in this PDF.");return}D||w(U.length>Mn?`Loading first ${Mn} pages...`:"Rendering pages...");let C=async te=>{var oc,sc,ac;let J=te.pageNum-1,de=(oc=te.mediaBox)!=null?oc:[0,0,612,792],pe=Math.max(1,de[2]-de[0]),Ne=Math.max(1,de[3]-de[1]),Xe=te.dict.entries.get("Contents"),Be=await ds(Xe,Fe=>B.loadObject(Fe)),we=un(Be.combinedBytes),zt=we.length;if(Be.streamCount>1&&Be.streamByteLengths.length>0){let Fe=Be.combinedBytes.subarray(0,Be.streamByteLengths[0]);zt=un(Fe).length}let Ze=Math.min(Math.max(typeof window!="undefined"&&window.devicePixelRatio||1,1),2),on=ad({baseScale:E*Ze,pageWidth:pe,pageHeight:Ne,textShowCount:od(we),imageDims:sd(te.resources,Fe=>B.loadObject(Fe))}),sn=document.createElement("canvas"),ir=new Qr(sn,Math.ceil(pe),Math.ceil(Ne),on,{disableClip:!1,debug:!1});ir.setFontContext(te.resources,Fe=>B.loadObject(Fe)),await ir.renderAsync(we),await ir.renderAnnotations(te.dict);let Xo=ir.getCapturedTextRuns().filter(Fe=>Fe.text.trim().length>0).map(Fe=>{let cc=nd(Fe,J,Ne,on);return Be.streamCount>1&&Fe.streamOperatorIndex>=zt?{...cc,contentStreamIndex:1}:cc}),nc=[...ir.getCapturedImages().map(Fe=>ed(Fe,J,Ne,on)),...ir.getCapturedGraphics().map(Fe=>td(Fe,J,Ne,on))],zf=nc.some(Fe=>Fe.kind==="image"&&Fe.width>=pe*.4&&Fe.height>=Ne*.4);kr.current[J]=fd(Xo,zf);let vi=qt.current.has(J)?[...Xo.filter(Fe=>!Fe.invisible),...(sc=Jt.current[J])!=null?sc:[]]:Xo,Xf=Gr(vi);if(Bi()){let Fe=sn.getContext("2d");Fe&&gs(Fe,sn.width,sn.height)}let Yo=await new Promise(Fe=>sn.toBlob(Fe,"image/png"));Eo([J]);let rc=Yo?URL.createObjectURL(Yo):sn.toDataURL("image/png");Yo&&(lo.current[J]=rc);let Yf={pageIndex:J,pageNum:te.pageNum,canvasDataUrl:rc,canvasWidth:sn.width,canvasHeight:sn.height,mediaBox:de,textRuns:vi,bgCss:tx(sn)},Wo=(ac=je.current[J])!=null?ac:[],ic=Wo.length?[...vi,...Wo]:vi,Wf=Wo.length?Gr(ic):Xf;f(Fe=>({...Fe,[J]:Yf})),ce(Fe=>({...Fe,[J]:{width:pe,height:Ne}})),_e.current={..._e.current,[J]:ic},ot.current={...ot.current,[J]:Wf},Mt.current={...Mt.current,[J]:nc}};if(D){let te=new Set(x);for(let de of U)if(te.has(de.pageNum-1)){if(_t.current!==N)return;await C(de)}let J=U.filter(de=>{let pe=de.pageNum-1;return!te.has(pe)&&!_e.current[pe]});for(let de of J){if(_t.current!==N||(await new Promise(pe=>setTimeout(pe,Du)),_t.current!==N))return;await C(de)}return}let q=U.slice(0,Mn);for(let te of q){if(_t.current!==N)return;await C(te)}_t.current===N&&(p(!1),An(!1),U.length>Mn&&w(`Showing ${Mn} of ${U.length} pages, loading remaining pages in background...`));let z=new Map(U.slice(Mn).map(te=>[te.pageNum-1,te])),H=U.length>Q0,Z=()=>{let te=[...z.keys()];if(H&&oi.current.size>0){let J,de=1/0;for(let pe of te)for(let Ne of oi.current){let Xe=Math.abs(pe-Ne);Xe<=ex&&Xe<de&&(J=pe,de=Xe)}if(J!==void 0)return J}return Math.min(...te)},re=0;for(;z.size>0;){if(_t.current!==N||(await new Promise(pe=>setTimeout(pe,Du)),_t.current!==N))return;let te=Z(),J=z.get(te);if(z.delete(te),!J)continue;await C(J),re+=1;let de=Mn+re;w(`Loaded ${de}/${U.length} pages...`)}if(_t.current!==N)return;U.length>Mn&&w(`All ${U.length} pages loaded.`)}catch(M){D||(d([]),f({}),ce({}),_e.current={},ot.current={},Mt.current={}),w(M instanceof Error?`Engine render failed: ${M.message}`:"Engine render failed")}finally{_t.current===N&&(p(!1),An(!1))}};Pt(()=>{let u=g=>{(g.ctrlKey||g.metaKey)&&g.key==="f"&&(g.preventDefault(),Zn(!0),setTimeout(()=>{var x;return(x=Rr.current)==null?void 0:x.focus()},50)),g.key==="Escape"&&Zn(!1)};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[]),Pt(()=>{if(!yn.trim()){hi([]),fi(0);return}let u=yn.toLowerCase(),g=[];for(let x of Object.values(_e.current))for(let D of x)D.text.toLowerCase().includes(u)&&g.push(D);hi(g),fi(0)},[yn]),Pt(()=>{if(!Ae){Eo(),d([]),f({}),ce({}),_e.current={},ot.current={},Mt.current={};return}let u=bn.current;bn.current=null,u?Ba(Ae,{onlyPages:u}):Ba(Ae)},[Ae]),Pt(()=>{let u=lo.current;return()=>{for(let g of Object.values(u))URL.revokeObjectURL(g)}},[]),Pt(()=>{if(typeof IntersectionObserver=="undefined")return;let u=oi.current,g=new IntersectionObserver(x=>{for(let D of x){let N=D.target.dataset.pageIndex;if(N===void 0)continue;let T=Number(N);D.isIntersecting?u.add(T):u.delete(T)}u.size&&Oe(Math.min(...u))},{rootMargin:"300px"});for(let[x,D]of Object.entries(Je.current))D&&(D.dataset.pageIndex=x,g.observe(D));return()=>{g.disconnect(),u.clear()}},[c]);let Zu=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 D,N,T,j;if(!Ae)return;let x=Ao();y(!0),w("Applying change...");try{let M=(D=o==null?void 0:o.name)!=null?D:"document.pdf",B=aa(Ae,M),L=await sr.runPipeline(B,{tasks:[{processorName:"pdf-editor-core",params:{operations:[u]}}]}),X=L[L.length-1];if(!(X!=null&&X.success)){w((N=X==null?void 0:X.error)!=null?N:"Operation failed");return}bn.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,l(X.document.blob),Bt(null),En(null),w("Saved");let U={"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}"},K={"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"},C="pageIndex"in u?u.pageIndex:void 0;No((T=K[u.type])!=null?T:u.type,(j=U[u.type])!=null?j:"\u2699\uFE0F",C,g!=null?g:Zu(u),x)}catch(M){w(M instanceof Error?M.message:"Operation failed")}finally{y(!1)}},Qu=async(u,g,x,D)=>{var T,j;if(!Ae||u.length===0)return;let N=Ao();y(!0),w("Applying change...");try{let M=(T=o==null?void 0:o.name)!=null?T:"document.pdf",B=aa(Ae,M),L=await sr.runPipeline(B,{tasks:[{processorName:"pdf-editor-core",params:{operations:u}}]}),X=L[L.length-1];if(!(X!=null&&X.success)){w((j=X==null?void 0:X.error)!=null?j:"Operation failed");return}let U=Array.from(new Set(u.map(C=>"pageIndex"in C?C.pageIndex:-1).filter(C=>C>=0)));bn.current=U.length?U:null,l(X.document.blob),Bt(null),En(null),w("Saved");let K=U.length?U[0]:void 0;No(g,x,K,D,N)}catch(M){w(M instanceof Error?M.message:"Operation failed")}finally{y(!1)}},ja=(u,g,x,D)=>{var L,X;D.stopPropagation(),D.preventDefault();let N=_[u.pageIndex],T=(L=N==null?void 0:N.width)!=null?L:612,j=(X=N==null?void 0:N.height)!=null?X:792;uo.current={id:u.id,pageIndex:u.pageIndex,mode:g,handle:x,startClientX:D.clientX,startClientY:D.clientY,startRect:{x:u.x,y:u.y,width:u.width,height:u.height}};let M=U=>{var de;let K=uo.current;if(!K)return;let C=(U.clientX-K.startClientX)/O,q=-(U.clientY-K.startClientY)/O,z=K.startRect,H=z.x,Z=z.y,re=z.width,te=z.height;if(K.mode==="move")H=z.x+C,Z=z.y+q;else{let pe=(de=K.handle)!=null?de:"se",Ne=z.x,Xe=z.x+z.width,Be=z.y,we=z.y+z.height;pe.includes("e")&&(Xe=z.x+z.width+C),pe.includes("w")&&(Ne=z.x+C),pe.includes("n")&&(we=z.y+z.height+q),pe.includes("s")&&(Be=z.y+q),H=Math.min(Ne,Xe),re=Math.abs(Xe-Ne),Z=Math.min(Be,we),te=Math.abs(we-Be)}let J=4;re=Math.max(J,re),te=Math.max(J,te),H=Math.max(0,Math.min(T-re,H)),Z=Math.max(0,Math.min(j-te,Z)),Tn(pe=>pe.map(Ne=>Ne.id===K.id?{...Ne,x:H,y:Z,width:re,height:te}:Ne))},B=()=>{window.removeEventListener("pointermove",M),window.removeEventListener("pointerup",B),uo.current=null};window.addEventListener("pointermove",M),window.addEventListener("pointerup",B)},ef=u=>Tn(g=>g.filter(x=>x.id!==u)),tf=async()=>{if(At.length===0)return;let u=At.map(x=>{var X;let D=x.x,N=x.x+x.width,T=x.y,j=x.y+x.height,M=(X=_e.current[x.pageIndex])!=null?X:[],B=U=>U.pdfX<N&&U.pdfX+U.width>D&&U.pdfY<j&&U.pdfY+U.height>T,L=M.filter(U=>!U.fromXObject&&B(U)).flatMap(U=>{var K;return(K=U.streamOperatorIndices)!=null?K:[]});return{type:"redact-area",pageIndex:x.pageIndex,x:D,y:T,width:x.width,height:x.height,color:{r:0,g:0,b:0},padding:1.5,removeOperators:L.length?{streamOperatorIndices:L}:void 0}}),g=u.length;Tn([]),await Qu(u,"Redacted area","\u2B1B",`${g} area${g>1?"s":""} redacted`)},Oo=(u,g,x,D,N)=>new Promise(T=>{let j=h[u],M=_[u];if(!j||!M)return T({r:1,g:1,b:1});let B=new Image;B.onload=()=>{try{let L=document.createElement("canvas");L.width=B.width,L.height=B.height;let X=L.getContext("2d");if(!X)return T({r:1,g:1,b:1});X.drawImage(B,0,0);let U=B.width/M.width,K=B.height/M.height,C=N*.5,q=x-C,z=N+C*2,H=Math.max(0,Math.floor(g*U)),Z=Math.max(0,Math.floor((M.height-q-z)*K)),re=Math.max(1,Math.min(Math.ceil(D*U),B.width-H)),te=Math.max(1,Math.min(Math.ceil(z*K),B.height-Z)),J=X.getImageData(H,Z,re,te).data,de=0,pe=0,Ne=0,Xe=0;for(let Be=0;Be<J.length;Be+=4)(J[Be]+J[Be+1]+J[Be+2])/3>160&&(de+=J[Be],pe+=J[Be+1],Ne+=J[Be+2],Xe++);if(Xe===0)return T({r:1,g:1,b:1});T({r:de/Xe/255,g:pe/Xe/255,b:Ne/Xe/255})}catch{T({r:1,g:1,b:1})}},B.onerror=()=>T({r:1,g:1,b:1}),B.src=j.canvasDataUrl}),nf=u=>{let[g,x]=u.split(","),D=atob(x!=null?x:""),N=new Uint8Array(D.length);for(let T=0;T<D.length;T++)N[T]=D.charCodeAt(T);return{bytes:N,format:g.includes("image/png")?"png":"jpeg"}},La=async()=>{var T,j,M;if(!Ae)return null;if(ct.length===0&>.length===0)return{blob:Ae,count:0};let u=[];for(let B of ct)u.push({type:"add-annotation",annotation:B});for(let B of gt){let L=_[B.pageIndex];if(L){if(B.kind==="comment"){let X={id:B.id,pageIndex:B.pageIndex,kind:"note",rect:{x:B.x/O,y:L.height-(B.y+22)/O,width:22/O,height:22/O},text:(T=B.text)!=null?T:"",style:{color:{r:.96,g:.62,b:.04},opacity:1},createdAt:Date.now()};u.push({type:"add-annotation",annotation:X})}else if(B.kind==="sign"){let{bytes:X,format:U}=nf(B.dataUrl);u.push({type:"insert-image",pageIndex:B.pageIndex,bytes:X,format:U,x:B.x/O,y:L.height-(B.y+B.height)/O,width:B.width/O,height:B.height/O})}}}let g=aa(Ae,(j=o==null?void 0:o.name)!=null?j:"document.pdf"),x=await sr.runPipeline(g,{tasks:[{processorName:"pdf-editor-core",params:{operations:u}}]}),D=x[x.length-1];if(!(D!=null&&D.success))return w((M=D==null?void 0:D.error)!=null?M:"Could not write annotations."),null;let N=D.document.blob;return l(N),Qt([]),Qn([]),$t(null),bn.current=null,{blob:N,count:u.length}},Io=async()=>{var g;if(!Ae)return;let u=((g=o==null?void 0:o.name)!=null?g:"document").replace(/\.pdf$/i,"");y(!0),w("Writing annotations\u2026");try{let x=await La();if(!x)return;let D=await Ia(x.blob),N=URL.createObjectURL(D),T=document.createElement("a");T.href=N,T.download=x.count>0?`${u}-annotated.pdf`:`${u}-edited.pdf`,T.click(),URL.revokeObjectURL(N),nn(x.count>0?`Downloaded with ${x.count} annotation${x.count!==1?"s":""}`:"Downloaded PDF","\u2B07\uFE0F")}catch(x){w("Download failed: "+(x instanceof Error?x.message:String(x)))}finally{y(!1),w("")}},rf=async()=>{var g,x;if(!Ae)return;Nr(!1);let u=((g=o==null?void 0:o.name)!=null?g:"document").replace(/\.pdf$/i,"");y(!0),w("Signing securely\u2026");try{let D=await La();if(!D)return;let N=await Ia(D.blob),T=new FormData;T.append("file",new File([N],`${u}.pdf`,{type:"application/pdf"})),T.append("consent","true"),Po.trim()&&T.append("reason",Po.trim()),Do.trim()&&T.append("location",Do.trim());let j=await fetch(n!=null?n:"/api/sign",{method:"POST",body:T});if(j.status===401){window.dispatchEvent(new Event("namaha:needs-auth")),w("Please sign in to certify your signature.");return}if(j.status===503){w("Secure signing isn\u2019t configured on this server \u2014 you can still use Quick sign (visual only).");return}if(!j.ok){let K=await j.json().catch(()=>null);w((x=K==null?void 0:K.error)!=null?x:"Could not sign the document.");return}let M=null,B=j.headers.get("X-Signature-Receipt");if(B)try{M=JSON.parse(decodeURIComponent(B))}catch{}let L=await j.blob(),X=URL.createObjectURL(L),U=document.createElement("a");U.href=X,U.download=`${u}-signed.pdf`,U.click(),URL.revokeObjectURL(X),M&&Aa({...M,documentName:`${u}.pdf`}),Ca(""),Fa(""),So(!1),nn("Signed & certified","\u{1F50F}")}catch(D){w("Signing failed: "+(D instanceof Error?D.message:String(D)))}finally{y(!1),w("")}},of=async u=>{var g,x,D,N,T;try{let{PDFDocument:j,StandardFonts:M,rgb:B}=await import("pdf-lib"),L=await j.create(),X=L.addPage([595,842]),U=await L.embedFont(M.Helvetica),K=await L.embedFont(M.HelveticaBold),C=B(.55,.04,.09),q=B(.1,.1,.12),z=B(.4,.4,.45),H=780;X.drawText("Certificate of Completion",{x:48,y:H,size:22,font:K,color:C}),H-=16,X.drawText("NamahaPDF electronic signature record",{x:48,y:H-6,size:10,font:U,color:z}),H-=40;let Z=[["Document",(g=u.documentName)!=null?g:"\u2014"],["Signer",(x=u.signerName)!=null?x:"\u2014"],["Signer email",(D=u.signerEmail)!=null?D:"\u2014"],["Signed at (UTC)",u.signedAt],["Document hash (SHA-256)",u.documentHash],["Certificate fingerprint",u.certFingerprint],["Audit reference",u.eventId]];for(let[Ne,Xe]of Z){X.drawText(Ne,{x:48,y:H,size:9,font:K,color:z}),H-=14;let Be=(N=Xe.match(/.{1,72}/g))!=null?N:[Xe];for(let we of Be)X.drawText(we,{x:48,y:H,size:10,font:U,color:q}),H-=14;H-=10}X.drawText("This document was electronically signed via NamahaPDF. The embedded cryptographic",{x:48,y:H,size:9,font:U,color:z}),X.drawText("signature makes the file tamper-evident: any change after signing invalidates it.",{x:48,y:H-12,size:9,font:U,color:z});let re=await L.save(),te=new Blob([re],{type:"application/pdf"}),J=URL.createObjectURL(te),de=((T=u.documentName)!=null?T:"document").replace(/\.pdf$/i,""),pe=document.createElement("a");pe.href=J,pe.download=`${de}-certificate.pdf`,pe.click(),URL.revokeObjectURL(J)}catch(j){w("Could not build the certificate: "+(j instanceof Error?j.message:String(j)))}};du({enabled:!!Ae,onUndo:Ju,onSave:()=>{b||Io()}});let sf=async(u,g)=>{if(!Ae||P!=="add-text"&&P!=="stamp")return;let x=_[g];if(!x)return;let D=Je.current[g];if(!D)return;let N=D.getBoundingClientRect(),T=xt(u.clientX,u.clientY,N,O,x.height);if(P==="add-text"){df(g,T.x,T.y);return}let j=R.trim();if(!j){w("Type or pick a stamp first.");return}await st({type:"insert-text",pageIndex:g,text:j,x:T.x,y:T.y,size:F,color:G},`"${j}" stamp`)},Ua=(u,g,x,D,N)=>{var K;let T=Ni(u,(K=_e.current[x])!=null?K:[],D.width),j=Math.max(1,g*.1),M=Math.max(0,u.x-j),B=Math.max(0,u.y-j),L={x:M,y:B,width:Math.min(D.width,u.x+u.width+j)-M,height:Math.min(D.height,u.y+u.height+j)-B},X=Ti(L,T),U=Qe(X.x,X.y+X.height,O,D.height);return{eraseClamp:T,maskRect:{x:U.x-N.x,y:U.y-N.y,w:X.width*O,h:X.height*O}}},$a=(u,g)=>{Oo(u,g.x,g.y,g.width,Math.max(8,g.height)).then(x=>{W(D=>D&&D.pageIndex===u&&D.pdfX===g.x&&D.pdfY===g.y?{...D,bgColor:x}:D)})},af=()=>{let u=Array.from(oi.current);return u.length?Math.min(...u):0},Bo=async u=>{var D;let g=h[u],x=_[u];if(!g||!x){w("Page not ready yet.");return}Me(!0),w(`Recognizing text on page ${u+1}\u2026`);try{let N=await(await fetch(g.canvasDataUrl)).blob(),T=new FormData;T.append("file",new File([N],`page-${u+1}.png`,{type:"image/png"}));let j=await fetch("/api/ocr",{method:"POST",body:T});if(!j.ok){j.status===401&&window.dispatchEvent(new Event("namaha:needs-auth"));let U=await j.json().catch(()=>({}));throw new Error(U.error||`OCR failed (${j.status})`)}let{words:M}=await j.json(),B=g.canvasWidth/Math.max(1,x.width),L=cd(M!=null?M:[],u,x.height,B);if(pt.current.add(u),L.length===0){w("No text recognized on this page."),et(U=>U+1);return}je.current[u]=L;let X=[...(D=_e.current[u])!=null?D:[],...L];_e.current={..._e.current,[u]:X},ot.current={...ot.current,[u]:Gr(X)},et(U=>U+1),w(`Recognized ${L.length} line${L.length===1?"":"s"}, text is now selectable & editable.`)}catch(N){w(N instanceof Error?N.message:"OCR failed.")}finally{Me(!1)}},cf=u=>{var j;let g=(j=_e.current[u])!=null?j:[],x=g.filter(M=>M.invisible),D=x.length?x:g,N=Xs(D);Jt.current[u]=N,qt.current.add(u);let T=[...g.filter(M=>!M.invisible),...N];_e.current={..._e.current,[u]:T},ot.current={...ot.current,[u]:Gr(T)},et(M=>M+1),w(`Recovered text on page ${u+1} (approximate \u2014 best for identifying & re-typing).`)},lf=u=>{md().id==="ocr"?Bo(u):cf(u)},jo=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}},Lo=()=>{ae&&me.current&&me.current.commit()},_a=(u,g)=>{let x=_[g];if(!x)return;Lo();let D=Qe(u.pdfX,u.pdfY+u.height,O,x.height),N={x:u.pdfX,y:u.pdfY,width:u.width,height:u.height},{eraseClamp:T,maskRect:j}=Ua(N,u.fontSize,g,x,D),M=(x.height-u.pdfBaselineY)*O;W({pageIndex:g,value:u.text,spans:[{text:u.text,style:jo(u)}],pdfX:u.pdfX,pdfY:u.pdfY,pdfBaselineY:u.pdfBaselineY,width:u.width,height:u.height,fontSize:u.fontSize,fontCapHeight:u.fontCapHeight,fontName:u.fontName,fontFamily:u.fontFamily,color:u.color,containerX:D.x,containerY:D.y,screenWidth:Math.max(60,u.width*O),screenHeight:Math.max(16,u.height*O),baselineOffsetPx:M-D.y,maxWidth:Math.max(60,x.width*O-D.x-2),eraseClamp:T,maskRect:j,streamOperatorIndices:u.streamOperatorIndices,fromXObject:u.fromXObject,sharedOperator:u.sharedOperator,originalText:u.text,ocr:u.ocr,recovered:u.recovered}),$a(g,N)},df=(u,g,x)=>{let D=_[u];if(!D)return;Lo();let N=F,T=Qe(g,x+N,O,D.height);W({pageIndex:u,value:"",spans:[],isNew:!0,pdfX:g,pdfY:x,pdfBaselineY:x,width:120,height:N,fontSize:N,color:{r:0,g:0,b:0},containerX:T.x,containerY:T.y,screenWidth:Math.max(60,120*O),screenHeight:Math.max(16,N*O),baselineOffsetPx:N*O,maxWidth:Math.max(60,D.width*O-T.x-2)})},uf=(u,g)=>{var B;if(P!=="edit-text")return;let x=_[g],D=Je.current[g];if(!x||!D)return;let N=D.getBoundingClientRect(),T=xt(u.clientX,u.clientY,N,O,x.height),j=(B=ot.current[g])!=null?B:_e.current[g],M=Zl(T,j,Na?14:6);M&&_a(M,g)},za=async u=>{var j,M,B,L;if(!yn.trim())return;let g=u.text.replace(new RegExp(yn.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"gi"),wa);if(g===u.text)return;let x=await Oo(u.pageIndex,u.pdfX,u.pdfY,u.width,u.height),D=Ni({x:u.pdfX,y:u.pdfY,width:u.width,height:u.height},(j=_e.current[u.pageIndex])!=null?j:[],(B=(M=_[u.pageIndex])==null?void 0:M.width)!=null?B: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:D,removeOperators:!u.fromXObject&&!u.sharedOperator&&((L=u.streamOperatorIndices)!=null&&L.length)?{streamOperatorIndices:u.streamOperatorIndices}:void 0,size:u.fontSize,backgroundColor:x,font:u.fontName?{pdfName:u.fontName,sizePt:u.fontSize,capHeight:u.fontCapHeight}:void 0,color:u.color});let N=yn.toLowerCase(),T=[];for(let X of Object.values(_e.current))for(let U of X)U.text.toLowerCase().includes(N)&&T.push(U);hi(T)},ff=async()=>{let u=[...dt];for(let g of u)await za(g)},Xa=async u=>{var D,N,T,j,M,B,L;let g=(D=u.bgColor)!=null?D:await Oo(u.pageIndex,u.x,u.y,u.width,Math.max(8,u.height)),x=(M=u.eraseClamp)!=null?M:Ni({x:u.x,y:u.y,width:u.width,height:u.height},(N=_e.current[u.pageIndex])!=null?N:[],(j=(T=_[u.pageIndex])==null?void 0:T.width)!=null?j: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&&!u.sharedOperator&&((B=u.streamOperatorIndices)!=null&&B.length)?{streamOperatorIndices:u.streamOperatorIndices}:void 0,size:u.fontSize,backgroundColor:g,font:u.fontName?{pdfName:u.fontName,sizePt:u.fontSize,color:u.color,capHeight:u.fontCapHeight}:void 0,color:u.color,spans:(L=u.spans)!=null&&L.length?u.spans:void 0},u.detail)},hf=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)},mf=new Set([8364,8218,402,8222,8230,8224,8225,710,8240,352,8249,338,381,8216,8217,8220,8221,8226,8211,8212,732,8482,353,8250,339,382,376]),pf=u=>{var g;for(let x of u){let D=(g=x.codePointAt(0))!=null?g:0;if(!(D===9||D===10||D===13)&&!(D>=32&&D<=255)&&!mf.has(D))return!0}return!1},Ya=async u=>{if(u.ocr){let g=je.current[u.pageIndex];g&&(je.current[u.pageIndex]=g.filter(x=>!(Math.abs(x.pdfX-u.pdfX)<.6&&Math.abs(x.pdfY-u.pdfY)<.6)))}if(u.recovered){let g=Jt.current[u.pageIndex];g&&(Jt.current[u.pageIndex]=g.filter(x=>!(Math.abs(x.pdfX-u.pdfX)<.6&&Math.abs(x.pdfY-u.pdfY)<.6)))}await Xa({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,fontCapHeight:u.fontCapHeight,fontName:u.fontName,color:u.color,streamOperatorIndices:u.streamOperatorIndices,fromXObject:u.fromXObject,sharedOperator:u.sharedOperator,bgColor:u.bgColor,eraseClamp:u.eraseClamp,detail:u.originalText!==void 0&&u.originalText!==u.value?`"${u.originalText}" \u2192 "${u.value}"`:`"${u.value}"`})},gf=async(u,g)=>{var X;let x=ae;if(W(null),!x)return;let D=Un(u),N=x.isNew?{}:jo({fontName:x.fontName,color:x.color}),T=Lc(D,N);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:T?D:void 0},`"${g}"`);return}let j=U=>Un(U).map(K=>`${K.text}\0${vn(K.style)}`).join("");if(j(D)===j((X=x.spans)!=null?X:[]))return;let M={...x,spans:T?D:void 0,value:g},B=x.fontName;if(!x.ocr&&!x.recovered&&!!B&&!hf(B)&&pf(g)&&!it.current.has(B)){De(M);return}await Ya(M)},xf=(u,g,x,D)=>{var j;let N=x/O,T=-D/O;Xa({pageIndex:g,x:u.pdfX+N,y:u.pdfY+T,baselineY:((j=u.pdfBaselineY)!=null?j:u.pdfY)+T,width:u.width,height:u.height,newText:u.text,fontSize:u.fontSize,fontCapHeight:u.fontCapHeight,fontName:u.fontName,color:u.color,streamOperatorIndices:u.streamOperatorIndices,fromXObject:u.fromXObject,sharedOperator:u.sharedOperator,detail:`moved "${u.text}"`})},bf=(u,g,x)=>{var X;let D=x.clientX,N=x.clientY,T=!u.fromXObject&&!!((X=u.streamOperatorIndices)!=null&&X.length);Cr.current={pageIndex:g,run:u,dxPx:0,dyPx:0},xa({pageIndex:g,run:u,dxPx:0,dyPx:0});let j=U=>{if(!Cr.current)return;let K=U.clientX-D,C=U.clientY-N;Cr.current={pageIndex:g,run:u,dxPx:K,dyPx:C},ri.current&&(ri.current.style.transform=`translate(${K}px, ${C}px)`)},M=U=>{window.removeEventListener("pointermove",j),window.removeEventListener("pointerup",B),window.removeEventListener("keydown",L);let K=Cr.current;if(Cr.current=null,ri.current=null,xa(null),ii.current=!0,!K)return;let C=Math.abs(K.dxPx)>=3||Math.abs(K.dyPx)>=3;U&&(C?T&&xf(u,g,K.dxPx,K.dyPx):_a(u,g))},B=()=>M(!0),L=U=>{U.key==="Escape"&&(U.stopPropagation(),M(!1))};window.addEventListener("pointermove",j),window.addEventListener("pointerup",B),window.addEventListener("keydown",L)},bi=(u,g)=>{ai(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}]})},yf=(u,g,x)=>{var L,X;let D={x:x.x,y:x.y,width:Math.max(12,x.width),height:Math.max(g==="checkbox"||g==="radio"?12:16,x.height)},N=`${g}_${Date.now().toString(36)}`,T=g==="dropdown"?["Option 1","Option 2"]:g==="radio"?["Choice 1","Choice 2"]:void 0,j=g==="checkbox"?"Yes":void 0,M={id:`${N}__new`,name:N,type:g,pageIndex:u,rect:D,value:g==="checkbox"?"Off":"",options:T,onState:j,fontSize:0,isNew:!0};((X=(L=jt.current)[u])!=null?X:L[u]=[]).push(M),qn.current[M.id]=N,si(U=>U+1),mo(!0),Uo(M),fo(null);let B=g==="radio"?(T!=null?T:[]).map((U,K)=>({x:D.x,y:D.y-K*(D.height+4),width:D.width,height:D.height})):void 0;st({type:"create-form-field",pageIndex:u,fieldType:g,name:N,rect:D,value:M.value,options:T,optionRects:B,fontSize:0})},Wa=u=>{var D,N;let g=(D=qn.current[u.id])!=null?D:u.name,x=(N=jt.current[u.pageIndex])!=null?N:[];jt.current[u.pageIndex]=x.filter(T=>T.id!==u.id),delete qn.current[u.id],Uo(null),si(T=>T+1),st({type:"delete-form-field",name:g})},wf=async()=>{await st({type:"flatten-form"}),w("Form flattened, values are now baked into the page.")},Uo=u=>{var g,x;ho((g=u==null?void 0:u.id)!=null?g:null),Fr.current=(x=u==null?void 0:u.name)!=null?x:null},Tr=gu(()=>{if(!ci)return null;for(let u of Object.values(jt.current)){let g=u.find(x=>x.id===ci);if(g)return g}return null},[ci,ba]),vf=(u,g)=>{var M,B;let x=(M=jt.current[u.pageIndex])!=null?M:[],D={...u,...g,rect:{...u.rect,...(B=g.rect)!=null?B:{}}};jt.current[u.pageIndex]=x.map(L=>L.id===u.id?D:L),g.value!==void 0&&ai(L=>{var X;return{...L,[u.id]:String((X=g.value)!=null?X:"")}}),g.name!==void 0&&(Fr.current=D.name),si(L=>L+1),po.current&&clearTimeout(po.current);let N=u.id,T=D.pageIndex,j=u.name;po.current=setTimeout(()=>{var K,C,q;let L=((K=jt.current[T])!=null?K:[]).find(z=>z.id===N);if(!L)return;let X=(C=qn.current[N])!=null?C:j,U=L.type==="radio"?((q=L.options)!=null?q:[]).map((z,H)=>({x:L.rect.x,y:L.rect.y-H*(L.rect.height+4),width:L.rect.width,height:L.rect.height})):void 0;qn.current[N]=L.name,st({type:"update-form-field",oldName:X,pageIndex:L.pageIndex,fieldType:L.type,name:L.name,rect:L.rect,value:L.value,options:L.options,optionRects:U,fontSize:L.fontSize,required:L.required,readOnly:L.readOnly,multiline:L.multiline,align:L.align,maxLength:L.maxLength,editable:L.editable})},400)},kf=.25,Pf=5,yi=u=>Math.max(kf,Math.min(Pf,u)),Ha=u=>ne(g=>yi(g*u)),Ga=()=>rr?28:96,Va=()=>{var x;let u=ge.current,g=(x=_[fe])!=null?x:_[0];!u||!g||ne(yi((u.clientWidth-Ga())/(g.width*E)))},Df=()=>{var x;let u=ge.current,g=(x=_[fe])!=null?x:_[0];!u||!g||ne(yi((u.clientHeight-Ga())/(g.height*E)))},wi=u=>{var x;let g=Math.max(0,Math.min(c.length-1,u));(x=Je.current[g])==null||x.scrollIntoView({behavior:"smooth",block:"start"})},$o=ye(!1);Pt(()=>{if(!rr||!c.length||!_[0]){c.length||($o.current=!1);return}$o.current||($o.current=!0,Va())},[rr,c.length,_]);let Er=ye(null),Ka=u=>Math.hypot(u[0].clientX-u[1].clientX,u[0].clientY-u[1].clientY),Sf=u=>{u.touches.length===2&&(Er.current={startDist:Ka(u.touches),startZoom:ee},(wo||yo)&&(Ar(!1),en.current=null,Ft(null)))},Cf=u=>{if(!Er.current||u.touches.length!==2)return;let g=Ka(u.touches)/(Er.current.startDist||1);ne(yi(Er.current.startZoom*g))},Ff=u=>{u.touches.length<2&&(Er.current=null)},Rf=(u,g)=>{if(!On)return;let x=Je.current[u],D=_[u];if(!x||!D)return;g.preventDefault(),g.stopPropagation();let N=x.getBoundingClientRect(),T=g.clientX-N.left,j=g.clientY-N.top,M=On,B=X=>{let U=Math.min(T,X.clientX-N.left),K=Math.min(j,X.clientY-N.top),C=Math.abs(X.clientX-N.left-T),q=Math.abs(X.clientY-N.top-j);li({pageIndex:u,x:U,y:K,w:C,h:q})},L=X=>{window.removeEventListener("pointermove",B),window.removeEventListener("pointerup",L),li(null);let U=X.clientX-N.left,K=X.clientY-N.top,C=Math.min(T,U),q=Math.min(j,K),z=Math.max(Math.abs(U-T),80),H=Math.max(Math.abs(K-j),M==="checkbox"||M==="radio"?16:22),Z=C/O,re=D.height-(q+H)/O;yf(u,M,{x:Z,y:re,width:z/O,height:H/O})};li({pageIndex:u,x:T,y:j,w:0,h:0}),window.addEventListener("pointermove",B),window.addEventListener("pointerup",L)},Mf=(u,g)=>{let x=_e.current[u];if(!x)return[];let D=Math.min(g.startPdfX,g.endPdfX),N=Math.max(g.startPdfX,g.endPdfX),T=Math.min(g.startPdfY,g.endPdfY),j=Math.max(g.startPdfY,g.endPdfY);return x.filter(M=>M.pdfX<N&&M.pdfX+M.width>D&&M.pdfY<j&&M.pdfY+M.height>T)},qa=(u,g)=>{for(let x=ct.length-1;x>=0;x--){let D=ct[x];if(D.pageIndex===u&&fl(g,D))return D}return null},Ja=(u,g,x,D)=>{let N=D.clientX,T=D.clientY,j=!1,M=L=>{let X=(L.clientX-N)/O,U=-(L.clientY-T)/O;(Math.abs(L.clientX-N)>2||Math.abs(L.clientY-T)>2)&&(j=!0),Qt(K=>K.map(C=>{if(C.id!==u.id)return C;if(g==="move")return hl(u,X,U);let q=ht(u),z=q.x,H=q.y,Z=q.width,re=q.height;return x==="ne"?(Z=q.width+X,re=q.height+U):x==="nw"?(z=q.x+X,Z=q.width-X,re=q.height+U):x==="se"?(H=q.y+U,Z=q.width+X,re=q.height-U):x==="sw"&&(z=q.x+X,H=q.y+U,Z=q.width-X,re=q.height-U),Z<5||re<5?C:ml(u,{x:z,y:H,width:Z,height:re})}))},B=()=>{window.removeEventListener("pointermove",M),window.removeEventListener("pointerup",B),j&&(vo.current=!0,nn(g==="move"?"Moved annotation":"Resized annotation","\u2725"))};window.addEventListener("pointermove",M),window.addEventListener("pointerup",B)},Af=(u,g,x)=>{let D=ct.find(N=>N.id===u);D&&Ja(D,"resize",g,x)},Nf=(u,g)=>{if(u.button!==0||u.pointerType==="touch"&&!u.isPrimary||P==="view"||P==="form")return;if(P==="annotate"||P==="draw"){let j=_[g],M=Je.current[g];if(!j||!M)return;u.preventDefault();let B=M.getBoundingClientRect(),L=xt(u.clientX,u.clientY,B,O,j.height);if(P==="annotate"){In==="brush"?(en.current={pageIndex:g,pt:L},Ft({kind:"ink",pageIndex:g,points:[L]})):In==="highlight"&&va==="box"?(en.current={pageIndex:g,pt:L},Ft({kind:"box",pageIndex:g,rect:{x:L.x,y:L.y,width:0,height:0}})):(en.current={pageIndex:g,pt:L},Ft({kind:"quads",pageIndex:g,quads:[]})),Ar(!0);return}if(Ut==="polygon")return;en.current={pageIndex:g,pt:L},Ft(Ut==="line"||Ut==="arrow"?{kind:"line",pageIndex:g,a:L,b:L,arrow:Ut==="arrow"}:{kind:"box",pageIndex:g,rect:{x:L.x,y:L.y,width:0,height:0}}),Ar(!0);return}if(P==="select"){let j=_[g],M=Je.current[g];if(j&&M){let B=M.getBoundingClientRect(),L=xt(u.clientX,u.clientY,B,O,j.height),X=qa(g,L);if(X){u.preventDefault(),$t(X.id),Bt(null),Ja(X,"move",void 0,u);return}}if(ze&&!ze.fromXObject&&ze.pageIndex===g){let B=_[g],L=Je.current[g];if(!B||!L)return;let X=L.getBoundingClientRect(),U=xt(u.clientX,u.clientY,X,O,B.height);Yi(U,Mt.current[g])===ze&&(u.preventDefault(),Za(ze,"move",null,u))}return}if(P!=="edit-text"&&P!=="redact")return;u.preventDefault();let x=_[g],D=Je.current[g];if(!x||!D)return;let N=D.getBoundingClientRect(),T=xt(u.clientX,u.clientY,N,O,x.height);Sr.current=!1,ii.current=!1,Zt.current={pageIndex:g,pdfX:T.x,pdfY:T.y},pa(!0),It([]),St(null),W(null)},Tf=(u,g)=>{var j;if(P==="select"){if(Gn.current)return;let M=_[g],B=Je.current[g];if(!M||!B)return;let L=B.getBoundingClientRect(),X=xt(u.clientX,u.clientY,L,O,M.height),U=Yi(X,Mt.current[g]);En(K=>K===U?K:U);return}if(P==="draw"&&Ut==="polygon"&&((j=tn.current)==null?void 0:j.pageIndex)===g){let M=_[g],B=Je.current[g];if(!M||!B)return;let L=B.getBoundingClientRect(),X=xt(u.clientX,u.clientY,L,O,M.height);Ft({kind:"polygon",pageIndex:g,points:tn.current.points,cursor:X});return}if(wo&&en.current&&en.current.pageIndex===g){let M=_[g],B=Je.current[g];if(!M||!B)return;let L=B.getBoundingClientRect(),X=xt(u.clientX,u.clientY,L,O,M.height),U=en.current.pt;Ft(K=>{var C,q;if(!K)return K;if(K.kind==="quads"){let z=(q=(C=ot.current[g])!=null?C:_e.current[g])!=null?q:[];return{kind:"quads",pageIndex:g,quads:Yl(z,U,X).quads}}return K.kind==="box"?{kind:"box",pageIndex:g,rect:{x:Math.min(U.x,X.x),y:Math.min(U.y,X.y),width:Math.abs(X.x-U.x),height:Math.abs(X.y-U.y)}}:K.kind==="line"?{...K,b:X}:K.kind==="ink"?{...K,points:[...K.points,X]}:K});return}if(!ma||!Zt.current||Zt.current.pageIndex!==g)return;let x=_[g],D=Je.current[g];if(!x||!D)return;let N=D.getBoundingClientRect(),T=xt(u.clientX,u.clientY,N,O,x.height);if(!Sr.current){let M=Math.abs(T.x-Zt.current.pdfX)*O,B=Math.abs(T.y-Zt.current.pdfY)*O;if(M<6&&B<6)return;Sr.current=!0,St({pageIndex:g,startPdfX:Zt.current.pdfX,startPdfY:Zt.current.pdfY,endPdfX:T.x,endPdfY:T.y});return}St({pageIndex:g,startPdfX:Zt.current.pdfX,startPdfY:Zt.current.pdfY,endPdfX:T.x,endPdfY:T.y})},Ef=(u,g)=>{if(wo){Ar(!1),en.current=null;let D=yo;if(Ft(null),!D||D.pageIndex!==g)return;let N={color:Lt.color,opacity:Lt.opacity,strokeWidth:Lt.strokeWidth,fill:Lt.fill},T={id:crypto.randomUUID(),pageIndex:g,style:N,createdAt:Date.now()},j=(M,B,L)=>{Qt(X=>[...X,M]),nn(B,L,g)};if(D.kind==="quads"){if(!D.quads.length)return;let M=In==="underline"?"underline":In==="strikeout"?"strikeout":"highlight",B=M==="underline"?"Underlined text":M==="strikeout"?"Struck through text":"Highlighted text";j({...T,kind:M,quads:D.quads,text:""},B,"\u{1F58A}\uFE0F")}else if(D.kind==="box"){if(D.rect.width<3||D.rect.height<3)return;if(P==="annotate"){let M=D.rect;j({...T,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:D.rect.x,y:D.rect.y},{x:D.rect.x+D.rect.width,y:D.rect.y+D.rect.height}];j({...T,kind:Ut==="ellipse"?"ellipse":"rect",points:M},Ut==="ellipse"?"Added ellipse":"Added rectangle","\u25FB\uFE0F")}}else if(D.kind==="line"){if(Math.hypot(D.b.x-D.a.x,D.b.y-D.a.y)<3)return;j({...T,kind:D.arrow?"arrow":"line",points:[D.a,D.b]},D.arrow?"Added arrow":"Added line","\u2197\uFE0F")}else if(D.kind==="ink"){if(D.points.length<2)return;j({...T,kind:"ink",strokes:[D.points]},"Freehand drawing","\u270F\uFE0F")}return}if(pa(!1),!Sr.current){It([]),St(null);return}if(!ke||ke.pageIndex!==g)return;if(P==="redact"){let D=Math.min(ke.startPdfX,ke.endPdfX),N=Math.max(ke.startPdfX,ke.endPdfX),T=Math.min(ke.startPdfY,ke.endPdfY),j=Math.max(ke.startPdfY,ke.endPdfY),M=N-D,B=j-T;if(St(null),It([]),M<3||B<3)return;Tn(L=>[...L,{id:crypto.randomUUID(),pageIndex:g,x:D,y:T,width:M,height:B}]),w("Adjust the box, then press \u201CApply redactions\u201D. Add more boxes as needed.");return}let x=Mf(g,ke);It(x),x.length>0?w(`Selected ${x.length} text run(s). Click Edit or drag to re-select.`):(w("No text selected in that area."),St(null))},Of=(u,g)=>{var x;if(P==="draw"&&Ut==="polygon"&&((x=tn.current)==null?void 0:x.pageIndex)===g){let D=tn.current.points;if(tn.current=null,Ft(null),D.length>=3){let N={color:Lt.color,opacity:Lt.opacity,strokeWidth:Lt.strokeWidth,fill:Lt.fill};Qt(T=>[...T,{id:crypto.randomUUID(),pageIndex:g,style:N,createdAt:Date.now(),kind:"polygon",points:D}]),nn("Added polygon","\u2B21",g)}}},If=(u,g)=>{if(go.current){go.current=!1;return}if(vo.current){vo.current=!1;return}let x=_[g],D=Je.current[g];if(!x||!D)return;let N=D.getBoundingClientRect(),T=xt(u.clientX,u.clientY,N,O,x.height),j=qa(g,T);if(j){$t(j.id),Bt(null);return}$t(null);let M=Yi(T,Mt.current[g]);Bt(M),M!=null&&M.fromXObject?w("This object is part of a reusable form and is locked in this version."):M&&w(`Selected ${M.kind==="image"?"image":"graphic"}, press Delete to remove it.`)},_o=pu(()=>{if(!ze||ze.fromXObject)return;let u=ze;Bt(null),En(null),st({type:"delete-object",pageIndex:u.pageIndex,spans:[{start:u.spanStart,end:u.spanEnd}]})},[ze,Ae]),Bf=async u=>{try{let g=new Uint8Array(await u.arrayBuffer()),x=g[0]===137&&g[1]===80&&g[2]===78&&g[3]===71,D=g[0]===255&&g[1]===216;if(!x&&!D){w("Only PNG and JPEG images can be inserted.");return}let N=await new Promise((T,j)=>{let M=URL.createObjectURL(u),B=new window.Image;B.onload=()=>{T({w:B.naturalWidth,h:B.naturalHeight}),URL.revokeObjectURL(M)},B.onerror=()=>{j(new Error("unreadable image")),URL.revokeObjectURL(M)},B.src=M});xo({bytes:g,format:x?"png":"jpeg",naturalWidth:Math.max(1,N.w),naturalHeight:Math.max(1,N.h)}),w("Click on a page to place the image (Esc to cancel).")}catch{w("Could not read that image file.")}},jf=(u,g)=>{let x=Jn,D=_[g],N=Je.current[g];if(!x||!D||!N)return;let T=N.getBoundingClientRect(),j=xt(u.clientX,u.clientY,T,O,D.height),M=D.width*.5,B=x.naturalWidth*.75,L=Math.min(M,Math.max(16,B)),X=L*(x.naturalHeight/x.naturalWidth),U=Math.max(0,Math.min(D.width-L,j.x-L/2)),K=Math.max(0,Math.min(D.height-X,j.y-X/2));xo(null),st({type:"insert-image",pageIndex:g,x:U,y:K,width:L,height:X,bytes:x.bytes,format:x.format})};Pt(()=>{if(!Jn)return;let u=g=>{g.key==="Escape"&&(xo(null),w("Image placement cancelled."))};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[Jn]);let Lf=u=>{let g=u.object,x=null;if(u.mode==="move"){if(Math.abs(u.dxPx)<2&&Math.abs(u.dyPx)<2)return;let D=u.dxPx/O,N=-u.dyPx/O;x=[1,0,0,1,D,N]}else if(u.handle){let D=u.scaleX,N=u.scaleY;if(Math.abs(D-1)<.01&&Math.abs(N-1)<.01)return;let T=g.pdfX,j=g.pdfX+g.width,M=g.pdfY,B=g.pdfY+g.height,L=u.handle.includes("w")?j:T,X=u.handle.includes("n")?M:B;x=[D,0,0,N,L-D*L,X-N*X]}x&&(go.current=!0,Bt(null),En(null),st({type:"transform-object",pageIndex:g.pageIndex,span:{start:g.spanStart,end:g.spanEnd},matrix:x,baseCtm:g.ctm}))},Za=(u,g,x,D)=>{let N={object:u,mode:g,handle:x,startClientX:D.clientX,startClientY:D.clientY,dxPx:0,dyPx:0,scaleX:1,scaleY:1};Gn.current=N,ga(N);let T=Math.max(1,u.width*O),j=Math.max(1,u.height*O),M=U=>{var Z;let K=Gn.current;if(!K)return;let C=U.clientX-K.startClientX,q=U.clientY-K.startClientY,z,H;if(K.mode==="move")z={...K,dxPx:C,dyPx:q},H=`translate(${C}px, ${q}px)`;else{let re=(Z=K.handle)!=null?Z:"se",te=1,J=1;if(re.includes("e")&&(te=(T+C)/T),re.includes("w")&&(te=(T-C)/T),re.includes("s")&&(J=(j+q)/j),re.includes("n")&&(J=(j-q)/j),K.object.kind==="image"&&re.length===2){let de=Math.max(Math.abs(te),Math.abs(J));te=de,J=de}z={...K,scaleX:Math.max(.05,te),scaleY:Math.max(.05,J)},H=`scale(${z.scaleX}, ${z.scaleY})`}Gn.current=z,co.current&&(co.current.style.transform=H)},B=U=>{window.removeEventListener("pointermove",M),window.removeEventListener("pointerup",L),window.removeEventListener("keydown",X);let K=Gn.current;Gn.current=null,ga(null),U&&K&&Lf(K)},L=()=>B(!0),X=U=>{U.key==="Escape"&&(U.stopPropagation(),B(!1))};window.addEventListener("pointermove",M),window.addEventListener("pointerup",L),window.addEventListener("keydown",X)};Pt(()=>{if(!ze)return;let u=g=>{let x=g.target;x&&(x.tagName==="INPUT"||x.tagName==="TEXTAREA")||(g.key==="Delete"||g.key==="Backspace"?(g.preventDefault(),_o()):g.key==="Escape"&&Bt(null))};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[ze,_o]),Pt(()=>{if(!Mr)return;let u=g=>{let x=g.target;x&&(x.tagName==="INPUT"||x.tagName==="TEXTAREA")||(g.key==="Delete"||g.key==="Backspace"?(g.preventDefault(),Qt(D=>D.filter(N=>N.id!==Mr)),$t(null),nn("Deleted annotation","\u{1F5D1}\uFE0F")):g.key==="Escape"&&$t(null))};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[Mr]),Pt(()=>{Bt(null),En(null),fo(null),ho(null),Fr.current=null,li(null),Tn([]),$t(null),Ft(null),Ar(!1),tn.current=null},[P]),Pt(()=>{if(P!=="redact"||At.length===0)return;let u=g=>{g.key==="Escape"&&(Tn([]),w("Redaction marks cleared."))};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[P,At.length]);let Uf=()=>{if(Nn.length===0||!ke)return;Lo();let u=[...Nn].sort((H,Z)=>H.pageIndex!==Z.pageIndex?H.pageIndex-Z.pageIndex:Math.abs(Z.pdfY-H.pdfY)>10?Z.pdfY-H.pdfY:H.pdfX-Z.pdfX),g=u[0].pageIndex,x=_[g],D=Je.current[g];if(!x||!D)return;let N=u.map(H=>H.text).join(" "),T=Math.min(...u.map(H=>H.pdfX)),j=Math.min(...u.map(H=>H.pdfY)),M=Math.max(...u.map(H=>H.pdfX+H.width)),B=Math.max(...u.map(H=>H.pdfY+H.height)),L=u.reduce((H,Z)=>H+Z.fontSize,0)/u.length,X=u.reduce((H,Z)=>H+Z.pdfBaselineY,0)/u.length,U=u.find(H=>H.fontName||H.color),K=Qe(T,j+(B-j),O,x.height),C={x:T,y:j,width:M-T,height:B-j},{eraseClamp:q,maskRect:z}=Ua(C,L,g,x,K);W({pageIndex:g,value:N,spans:[{text:N,style:jo({fontName:U==null?void 0:U.fontName,color:U==null?void 0:U.color})}],pdfX:T,pdfY:j,pdfBaselineY:X,width:M-T,height:B-j,fontSize:L,fontName:U==null?void 0:U.fontName,fontFamily:U==null?void 0:U.fontFamily,color:U==null?void 0:U.color,containerX:K.x,containerY:K.y,screenWidth:Math.max(150,(M-T)*O+12),screenHeight:Math.max(30,(B-j)*O+8),maxWidth:Math.max(60,x.width*O-K.x-2),eraseClamp:q,maskRect:z,streamOperatorIndices:u.every(H=>{var Z;return((Z=H.streamOperatorIndices)!=null?Z:[]).length>0})?u.flatMap(H=>{var Z;return(Z=H.streamOperatorIndices)!=null?Z:[]}):void 0,fromXObject:u.some(H=>H.fromXObject)}),$a(g,C),It([]),St(null)},$f=async()=>{if(Nn.length===0||!ke)return;let u=ke.pageIndex;if(!_[u])return;let x=Nn.filter(M=>M.pageIndex===u),D=x.length>0?Math.min(...x.map(M=>M.pdfX)):Math.min(ke.startPdfX,ke.endPdfX),N=x.length>0?Math.max(...x.map(M=>M.pdfX+M.width)):Math.max(ke.startPdfX,ke.endPdfX),T=x.length>0?Math.min(...x.map(M=>M.pdfY)):Math.min(ke.startPdfY,ke.endPdfY),j=x.length>0?Math.max(...x.map(M=>M.pdfY+M.height)):Math.max(ke.startPdfY,ke.endPdfY);It([]),St(null),await st({type:"redact-area",pageIndex:u,x:D,y:T,width:N-D,height:j-T,color:{r:0,g:0,b:0},padding:x.length>0?Math.max(1.75,x.reduce((M,B)=>M+B.fontSize,0)/x.length*.14):1.75})},zo=()=>{var u;(u=ha.current)==null||u.click()},Qa=async()=>{if(!xn.current||!Dr.trim())return;An(!0);let u=await r(xn.current,Dr);if(u.success&&u.pdfBytes){let g=Su(u.pdfBytes);bn.current=null,s(xn.current),l(g),d([]),f({}),ce({}),_e.current={},ot.current={},Mt.current={},It([]),St(null),W(null),w("Rendering PDF..."),ni(""),Hn(!1),xn.current=null}else w("Incorrect password. Please try again."),An(!1),Hn(!0)},_f=Ae?`${(Ae.size/1024).toFixed(1)} KB`:"No file loaded",rn=(()=>{var u,g,x;if(!Ae||qe&&Pr)return null;for(let D of Object.keys(h)){let N=Number(D);if(!(pt.current.has(N)||qt.current.has(N))){if(!Pr&&kr.current[N]==="rotated-garbage")return{index:N,kind:"rotated-garbage"};if(!qe){let T=((u=_e.current[N])!=null?u:[]).filter(M=>!M.ocr&&!M.recovered).length,j=(x=(g=Mt.current[N])==null?void 0:g.length)!=null?x:0;if(T===0&&j>0)return{index:N,kind:"no-text"}}}}return null})();return $("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:[$("header",{className:"flex h-12 shrink-0 items-center gap-2 border-b border-ink-line bg-paper-card px-3 md:h-14 md:gap-3.5 md:px-4 dark:border-white/10 dark:bg-[#1a1712]",children:[$("div",{className:"flex items-center gap-2.5 border-r border-ink-line pr-2 md:pr-4 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(ao,{className:"h-4 w-4 text-white"})}),$("span",{className:"hidden font-display text-[18px] font-semibold tracking-[-0.01em] text-ink sm:inline 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?$(Vt,{children:[v("span",{className:"truncate text-[13.5px] font-semibold text-ink dark:text-zinc-200",children:To}),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:_f}),b&&v("span",{className:"shrink-0 text-xs text-crimson-600 animate-pulse",children:"saving\u2026"}),!b&&k&&$("span",{className:"hidden min-w-0 items-center gap-1 text-xs text-emerald-700 sm:inline-flex dark:text-green-400",children:[v(io,{className:"h-3 w-3 shrink-0"}),v("span",{className:"truncate",children:k})]})]}):v("span",{className:"text-sm text-ink-muted",children:"No document open"})}),v("div",{className:"flex-1"}),$("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(X0,{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."})]}),$("div",{className:"flex items-center gap-1.5",children:[Ae&&v("button",{type:"button",title:"Activity log",onClick:()=>Ro(u=>!u),className:`flex h-8 w-8 items-center justify-center rounded-lg transition-colors ${Fo?"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(bu,{className:"h-4 w-4"})}),Ae&&v("button",{type:"button",title:"Recognize text (OCR), for scanned/outlined pages",disabled:Ie,onClick:()=>{Bo(af())},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(vu,{className:`h-4 w-4 ${Ie?"animate-pulse":""}`})}),$("button",{type:"button",title:"Open PDF",onClick:zo,className:"flex h-8 items-center gap-1.5 rounded-lg border border-ink-line-strong bg-paper-raised px-2.5 text-xs font-semibold text-ink-soft transition-colors hover:bg-paper md:px-3 dark:border-white/10 dark:bg-zinc-800 dark:text-zinc-300 dark:hover:bg-zinc-700",children:[v(sa,{className:"h-3.5 w-3.5"}),v("span",{className:"hidden sm:inline",children:"Open"})]}),$("button",{type:"button",title:"Share",className:"hidden 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 sm:flex dark:border-white/10 dark:bg-zinc-800 dark:text-zinc-300 dark:hover:bg-zinc-700",children:[v(G0,{className:"h-3.5 w-3.5"}),"Share"]}),$("button",{type:"button",onClick:Ae?()=>{Io()}:zo,disabled:b,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(xu,{className:"h-3.5 w-3.5"}),Ae?ct.length+gt.length>0?`Download (${ct.length+gt.length} annot.)`:"Download":"Open PDF"]})]})]}),rn!==null&&$("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(vu,{className:"h-4 w-4 shrink-0"}),v("span",{className:"flex-1",children:rn.kind==="rotated-garbage"?`Page ${rn.index+1} is scanned and its hidden text layer is scrambled. Recover it to make the text readable and editable (approximate).`:`Page ${rn.index+1} looks scanned or has outlined text. Recognize it to make the text selectable and editable.`}),v("button",{type:"button",disabled:Ie,onClick:()=>{rn.kind==="rotated-garbage"?lf(rn.index):Bo(rn.index)},className:"rounded-md bg-amber-600 px-2.5 py-1 font-semibold text-white transition hover:brightness-110 disabled:opacity-60",children:rn.kind==="rotated-garbage"?"Recover text":Ie?"Recognizing\u2026":"Recognize text"}),v("button",{type:"button",onClick:()=>{rn.kind==="rotated-garbage"?ju(!0):Rt(!0)},className:"rounded p-1 hover:bg-amber-100 dark:hover:bg-amber-900/40",title:"Dismiss",children:v(Ot,{className:"h-3.5 w-3.5"})})]}),Ae&&!ve&&$("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:()=>tt(!0),className:"rounded p-1 hover:bg-blue-100 dark:hover:bg-blue-900/40",title:"Dismiss",children:v(Ot,{className:"h-3.5 w-3.5"})})]}),Kt&&v("div",{className:"fixed inset-0 z-[120] flex items-center justify-center bg-black/50 p-4",onClick:()=>De(null),children:$("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:"Some characters need a standard font"}),$("p",{className:"mt-2 text-sm text-zinc-600 dark:text-zinc-400",children:["The font",Kt.fontName?$(Vt,{children:[" (",v("span",{className:"font-medium",children:Kt.fontName.replace(/^[A-Z]{6}\+/,"")}),")"]}):null," ","may not include some of the characters you typed. Those characters will be saved in the closest matching standard font; the rest keeps the original font. Continue?"]}),$("div",{className:"mt-5 flex gap-2",children:[v("button",{type:"button",onClick:()=>{let u=Kt;u.fontName&&it.current.add(u.fontName),De(null),Ya(u)},className:"flex-1 rounded-full bg-primary px-4 py-2.5 text-sm font-semibold text-white transition hover:brightness-110",children:"Continue"}),v("button",{type:"button",onClick:()=>De(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:$("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."}),$("button",{type:"button",onClick:zo,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:[$("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(U0,{className:"h-8 w-8"})})]}),$("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"})]}),$("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(sa,{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=>$("span",{className:"inline-flex items-center gap-1.5",children:[v(io,{className:"h-3 w-3 text-emerald-700"}),u]},u))})]})]})}),$("div",{className:"sr-only",children:[v("input",{ref:ha,type:"file",accept:"application/pdf",onChange:async u=>{var D,N;let g=(N=(D=u.target.files)==null?void 0:D[0])!=null?N:null;if(!g)return;xn.current=g,An(!0),Hn(!1),ni(""),w("Rendering PDF...");let x=await r(g);if(x.success&&x.pdfBytes){let T=Su(x.pdfBytes);bn.current=null,s(g),l(T),d([]),f({}),ce({}),_e.current={},ot.current={},Mt.current={},It([]),St(null),W(null),w("Rendering PDF...")}else x.requiresPassword?(Hn(!0),An(!1),w("")):(w(x.error||"Failed to load PDF"),An(!1),Hn(!1),xn.current=null)},className:"p-2 border rounded"}),Ae&&$("p",{className:"text-sm",style:{color:"var(--footer-muted)"},children:["Current file: ",To," \xB7 ",(Ae.size/1024).toFixed(1)," KB"]})]}),Ae&&$("div",{className:"flex flex-1 flex-col overflow-hidden",children:[$("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(ao,{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:To}),$("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"]}),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:P.replace(/-/g," ")})]}),di&&$("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(oo,{className:"h-3.5 w-3.5 shrink-0 text-amber-600 dark:text-amber-400"}),v("input",{ref:Rr,type:"text",placeholder:"Find\u2026",value:yn,onChange:u=>ya(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:wa,onChange:u=>zu(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"}),dt.length>0&&$(Vt,{children:[$("span",{className:"text-xs font-semibold text-amber-700 dark:text-amber-400",children:[ui+1," / ",dt.length]}),v("button",{type:"button",onClick:()=>fi(u=>(u-1+dt.length)%dt.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(E0,{className:"h-3.5 w-3.5 text-amber-700 dark:text-amber-400"})}),v("button",{type:"button",onClick:()=>fi(u=>(u+1)%dt.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(O0,{className:"h-3.5 w-3.5 text-amber-700 dark:text-amber-400"})})]}),yn&&dt.length===0&&v("span",{className:"text-xs text-zinc-400",children:"No matches"}),$("div",{className:"flex gap-1",children:[$("button",{type:"button",onClick:()=>{dt[ui]&&za(dt[ui])},disabled:dt.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(W0,{className:"h-3 w-3"}),"Replace"]}),$("button",{type:"button",onClick:()=>{ff()},disabled:dt.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 (",dt.length,")"]})]}),v("button",{type:"button",onClick:()=>{Zn(!1),ya(""),hi([])},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(Ot,{className:"h-3.5 w-3.5 text-amber-700 dark:text-amber-400"})})]}),P==="sign"&&ko&&$("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(la,{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:()=>pi(!1),className:"ml-auto text-amber-500 hover:text-amber-400",children:v(Ot,{className:"h-3.5 w-3.5"})})]}),!ko&>.some(u=>u.kind==="sign")&&$("div",{className:"flex flex-wrap items-center gap-2 border-b border-emerald-500/30 bg-emerald-500/10 px-4 py-2 text-xs text-emerald-700 dark:text-emerald-300",children:[v(ei,{className:"h-3.5 w-3.5 shrink-0"}),v("span",{className:"font-semibold",children:"Signature placed."}),v("span",{className:"text-emerald-700/80 dark:text-emerald-300/80",children:"Certify it to make the document tamper-evident with an audit trail, or just download the visual copy."}),$("div",{className:"ml-auto flex items-center gap-2",children:[$("button",{type:"button",disabled:b,onClick:()=>{So(!1),Nr(!0)},className:"inline-flex items-center gap-1.5 rounded-lg bg-emerald-600 px-3 py-1.5 font-bold text-white hover:bg-emerald-700 disabled:opacity-60",children:[v(ei,{className:"h-3.5 w-3.5"})," Sign & certify"]}),v("button",{type:"button",disabled:b,onClick:()=>{Io()},className:"rounded-lg border border-emerald-600/40 px-3 py-1.5 font-semibold text-emerald-700 hover:bg-emerald-500/10 disabled:opacity-60 dark:text-emerald-300",children:"Quick (visual only)"})]})]}),Ma&&$("div",{className:"flex flex-wrap items-center gap-2 border-b border-emerald-600/40 bg-emerald-600/15 px-4 py-2 text-xs text-emerald-800 dark:text-emerald-200",children:[v(ei,{className:"h-3.5 w-3.5 shrink-0"}),v("span",{className:"font-semibold",children:"Document signed & certified."}),v("span",{className:"text-emerald-800/80 dark:text-emerald-200/80",children:"A tamper-evident copy was downloaded."}),$("div",{className:"ml-auto flex items-center gap-2",children:[$("button",{type:"button",onClick:()=>{of(Ma)},className:"inline-flex items-center gap-1.5 rounded-lg bg-emerald-700 px-3 py-1.5 font-bold text-white hover:bg-emerald-800",children:[v(xu,{className:"h-3.5 w-3.5"})," Certificate of Completion"]}),v("button",{type:"button",onClick:()=>Aa(null),className:"text-emerald-700 hover:text-emerald-600 dark:text-emerald-300",children:v(Ot,{className:"h-3.5 w-3.5"})})]})]}),(P==="stamp"||P==="add-text")&&$("div",{className:"flex flex-nowrap items-center gap-2 overflow-x-auto border-b border-ink-line bg-paper-card px-4 py-2 text-xs text-ink-soft [scrollbar-width:none] md:flex-wrap md:overflow-visible",children:[P==="stamp"?v(Fu,{className:"h-3.5 w-3.5 text-primary"}):v(Mu,{className:"h-3.5 w-3.5 text-primary"}),P==="stamp"&&$(Vt,{children:[v("span",{className:"font-semibold text-ink-muted",children:"Presets:"}),["APPROVED","CONFIDENTIAL","DRAFT","REVIEWED"].map(u=>v("button",{type:"button",onClick:()=>I(u),className:`rounded px-2 py-0.5 text-[10px] font-bold tracking-wide transition-colors ${R===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"})]}),P==="stamp"&&v("input",{type:"text",value:R,onChange:u=>I(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:P==="add-text"?"Default size:":"Size:"}),[10,14,18,24,36].map(u=>v("button",{type:"button",onClick:()=>A(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)),P==="stamp"&&$(Vt,{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:()=>Y(g),style:{background:u,width:18,height:18,borderRadius:4,border:G.r===g.r&&G.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:P==="add-text"?"Click the page to add a text box, then type & format":"Click the page to place"})]}),P==="view"&&$("div",{className:"flex flex-nowrap items-center gap-2 overflow-x-auto border-b border-ink-line bg-paper-card px-4 py-1.5 text-xs text-ink-soft [scrollbar-width:none] md:flex-wrap md:overflow-visible dark:border-white/10 dark:bg-[#1a1712]",children:[v(Cu,{className:"h-3.5 w-3.5 text-crimson-600"}),v("button",{type:"button",onClick:()=>Ha(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(K0,{className:"h-3.5 w-3.5"})}),$("span",{className:"w-12 text-center font-semibold text-ink-muted",children:[Math.round(ee*100),"%"]}),v("button",{type:"button",onClick:()=>Ha(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(V0,{className:"h-3.5 w-3.5"})}),$("button",{type:"button",onClick:Va,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(_0,{className:"h-3.5 w-3.5"})," Width"]}),v("button",{type:"button",onClick:Df,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:()=>wi(fe-1),disabled:fe<=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(I0,{className:"h-3.5 w-3.5"})}),v("input",{type:"number",min:1,max:c.length,value:fe+1,onChange:u=>wi((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"}),$("span",{className:"text-ink-muted",children:["/ ",c.length]}),v("button",{type:"button",onClick:()=>wi(fe+1),disabled:fe>=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:v(B0,{className:"h-3.5 w-3.5"})}),$("div",{className:"ml-auto flex items-center gap-2",children:[$("button",{type:"button",onClick:()=>{Zn(u=>!u),setTimeout(()=>{var u;return(u=Rr.current)==null?void 0:u.focus()},50)},className:`flex h-7 items-center gap-1 rounded px-2 font-semibold transition-colors ${di?"bg-amber-500 text-white":"hover:bg-paper dark:hover:bg-zinc-800"}`,children:[v(oo,{className:"h-3.5 w-3.5"})," Find"]}),v("span",{className:"text-ink-muted",children:"Drag to select \xB7 Ctrl+C to copy"})]})]}),P==="redact"&&$("div",{className:"flex flex-nowrap items-center gap-2 overflow-x-auto border-b border-ink-line bg-paper-card px-4 py-2 text-xs text-ink-soft [scrollbar-width:none] md:flex-wrap md:overflow-visible",children:[v(ca,{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."}),$("div",{className:"ml-auto flex items-center gap-3",children:[v("span",{className:"text-ink-muted",children:At.length?`${At.length} mark${At.length>1?"s":""}`:"No marks yet"}),v("button",{type:"button",onClick:()=>Tn([]),disabled:At.length===0||b,className:"rounded bg-paper px-2.5 py-1 font-semibold text-ink-soft hover:bg-ink-line disabled:opacity-40",children:"Clear marks"}),$("button",{type:"button",onClick:()=>{tf()},disabled:At.length===0||b,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(ca,{className:"h-3 w-3"})," Apply redactions"]})]})]}),$("div",{className:"relative flex flex-1 overflow-hidden",children:[$("aside",{className:"z-30 hidden 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 md:flex 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(ao,{className:"h-4 w-4 text-crimson-600"})}),v("div",{className:"mb-1 h-px w-10 bg-ink-line"}),$("button",{type:"button",title:"Find & Replace (Ctrl+F)",onClick:()=>{Zn(u=>!u),setTimeout(()=>{var u;return(u=Rr.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 ${di?"bg-amber-500 text-white shadow-md":"text-ink-soft hover:bg-paper hover:text-ink"}`,children:[v(oo,{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"}),Au.map(({t:u,icon:g,label:x,hint:D})=>$("button",{type:"button",title:D!=null?D:x,onClick:()=>S(u),className:`flex w-full flex-col items-center justify-center rounded-lg py-2.5 text-center transition-all ${P===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"}),Nu.map(({t:u,icon:g,label:x})=>$("button",{type:"button",title:x,onClick:()=>S(u),className:`flex w-full flex-col items-center justify-center rounded-lg py-2.5 text-center transition-all ${P===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"}),Tu.map(({t:u,icon:g,label:x})=>$("button",{type:"button",title:x,onClick:()=>S(u),className:`flex w-full flex-col items-center justify-center rounded-lg py-2.5 text-center transition-all ${P===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)),$("button",{type:"button",title:"Insert image (PNG/JPEG)",onClick:()=>{var u;return(u=bo.current)==null?void 0:u.click()},disabled:b,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(ku,{className:"h-4 w-4"}),v("span",{className:"mt-1 text-[8px] font-semibold leading-tight",children:"Image"})]}),v("input",{ref:bo,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&&Bf(g)}}),v("div",{className:"flex-1"}),v("div",{className:"mt-1 h-px w-10 bg-ink-line"}),$("button",{type:"button",title:"Rotate page",onClick:()=>st({type:"rotate-page",pageIndex:xi,degrees:Oa}),disabled:b,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(wu,{className:"h-4 w-4"}),v("span",{className:"mt-1 text-[8px] font-semibold",children:"Rotate"})]}),$("button",{type:"button",title:"Delete page",onClick:()=>st({type:"delete-page",pageIndex:xi}),disabled:b,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(so,{className:"h-4 w-4"}),v("span",{className:"mt-1 text-[8px] font-semibold",children:"Delete"})]}),ct.length+gt.length>0&&$("div",{className:"mt-2 w-full rounded-lg bg-primary/20 py-1 text-center text-[8px] font-bold text-primary",children:[ct.length+gt.length," annot."]})]}),$("main",{ref:ge,className:"flex-1 overflow-auto p-3 pb-24 md:p-12",onTouchStart:Sf,onTouchMove:Cf,onTouchEnd:Ff,style:{backgroundImage:"radial-gradient(#d8cdb8 1px, transparent 1px)",backgroundSize:"20px 20px",touchAction:"pan-x pan-y"},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&&c.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."}),c.map(u=>{var j,M,B,L,X,U,K;let g=h[u.pageIndex],x=u.pageIndex,D=!!g,N=`${Math.ceil(u.width*O)}px`,T=`${Math.ceil(u.height*O)}px`;return $("div",{className:"relative mx-auto mb-10 overflow-hidden rounded-[3px] shadow-[0_12px_40px_-10px_rgba(33,29,23,0.28)]",ref:C=>{Je.current[x]=C},style:{width:N,minHeight:T,background:(j=g==null?void 0:g.bgCss)!=null?j:"#ffffff",cursor:Jn?"crosshair":P==="form"?On?"crosshair":"default":["add-text","annotate","stamp","draw","comment","sign"].includes(P)?"crosshair":P==="select"?yt&&yt.pageIndex===x?yt.fromXObject?"not-allowed":"pointer":"default":"text",userSelect:P==="view"?"text":"none",touchAction:["annotate","draw","redact","select"].includes(P)?"none":"pan-x pan-y"},onPointerDown:C=>Nf(C,x),onPointerMove:C=>Tf(C,x),onPointerUp:C=>Ef(C,x),onDoubleClick:C=>Of(C,x),onClick:C=>{var q;if(Jn){jf(C,x);return}if(P!=="view"){if(P==="select"){If(C,x);return}if(P==="comment"){let z=Je.current[x];if(!z)return;let H=z.getBoundingClientRect(),Z={id:crypto.randomUUID(),kind:"comment",pageIndex:x,x:C.clientX-H.left,y:C.clientY-H.top,text:"",color:"#F59E0B"};nn("Added comment","\u{1F4AC}",x),Qn(re=>[...re,Z]),mi(Z.id);return}if(P==="sign"){if(Pa&&ko){let z=Je.current[x];if(!z)return;let H=z.getBoundingClientRect();nn("Placed signature","\u2712\uFE0F",x),Qn(Z=>[...Z,{id:crypto.randomUUID(),kind:"sign",pageIndex:x,x:C.clientX-H.left-100,y:C.clientY-H.top-40,width:200,height:80,dataUrl:Pa}]),pi(!1)}else er(!0);return}if(P==="draw"&&Ut==="polygon"){let z=_[x],H=Je.current[x];if(!z||!H)return;let Z=H.getBoundingClientRect(),re=xt(C.clientX,C.clientY,Z,O,z.height),J=[...((q=tn.current)==null?void 0:q.pageIndex)===x?tn.current.points:[],re];tn.current={pageIndex:x,points:J},Ft({kind:"polygon",pageIndex:x,points:J,cursor:re});return}if(P==="add-text"||P==="stamp"){sf(C,x);return}if(ii.current){ii.current=!1;return}!Sr.current&&Nn.length===0&&uf(C,x)}},children:[D?v("img",{src:g.canvasDataUrl,alt:`Engine rendered page ${g.pageNum}`,draggable:!1,decoding:"async",style:{display:"block",width:N,height:T,background:(M=g.bgCss)!=null?M:"#fff"}}):v("div",{className:"flex h-full w-full items-center justify-center",style:{minHeight:T,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:$("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]&&v(Ls,{pageIndex:x,pageHeight:_[x].height,scale:O,annots:ct,live:yo,liveStyle:Lt,selectedId:Mr,interactive:P==="select",liveMarkupKind:In==="underline"?"underline":In==="strikeout"?"strikeout":"highlight",onBeginResize:Af}),$("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:[gt.filter(C=>C.pageIndex===x&&C.kind==="sign").map(C=>v("image",{href:C.dataUrl,x:C.x,y:C.y,width:C.width,height:C.height},C.id)),gt.filter(C=>C.pageIndex===x&&C.kind==="comment").map(C=>$("g",{style:{pointerEvents:"auto",cursor:"pointer"},onClick:q=>{q.stopPropagation(),mi(ka===C.id?null:C.id)},children:[v("rect",{x:C.x,y:C.y,width:22,height:22,rx:4,fill:C.color}),v("text",{x:C.x+11,y:C.y+15,textAnchor:"middle",fontSize:13,fill:"white",style:{fontFamily:"sans-serif",userSelect:"none"},children:"\u270E"})]},C.id))]}),gt.filter(C=>C.pageIndex===x&&C.kind==="comment"&&C.id===ka).map(C=>v("div",{style:{position:"absolute",left:C.x+26,top:C.y,zIndex:60,minWidth:220},onClick:q=>q.stopPropagation(),children:$("div",{className:"rounded-xl bg-white shadow-xl ring-1 ring-black/10 overflow-hidden",children:[$("div",{className:"flex items-center gap-2 bg-amber-400 px-3 py-2",children:[v(Ru,{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:()=>{Qn(q=>q.filter(z=>z.id!==C.id)),mi(null)},children:v(Ot,{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:C.text,autoFocus:!0,onBlur:q=>Qn(z=>z.map(H=>H.id===C.id?{...H,text:q.target.value}:H))}),v("div",{className:"flex justify-end gap-1 border-t border-outline-variant/20 px-3 py-1.5",children:$("button",{className:"rounded-lg px-3 py-1 text-xs font-bold text-primary hover:bg-primary/10",onClick:()=>mi(null),children:[v(io,{className:"mr-1 inline h-3 w-3"}),"Done"]})})]})},C.id)),P==="select"&&_[x]&&(()=>{var te;let C=ct.find(J=>J.id===Mr&&J.pageIndex===x);if(!C)return null;let q=ht(C),z=Qe(q.x,q.y+q.height,O,_[x].height),H=C.kind==="highlight"||C.kind==="underline"||C.kind==="strikeout"||C.kind==="squiggly",Z=C.kind==="rect"||C.kind==="ellipse"||C.kind==="polygon",re=J=>Qt(de=>de.map(pe=>pe.id===C.id?{...pe,style:{...pe.style,...J}}:pe));return v("div",{style:{position:"absolute",left:Math.max(0,z.x),top:Math.max(0,z.y-12),zIndex:60,width:230},onPointerDown:J=>J.stopPropagation(),onClick:J=>J.stopPropagation(),children:$("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(Yt,{label:H?"Color":"Stroke",color:C.style.color,onColor:J=>re({color:J}),opacity:C.style.opacity,onOpacity:J=>re({opacity:J})}),Z&&v(Yt,{label:"Fill",color:(te=C.style.fill)!=null?te:{r:1,g:1,b:1},onColor:J=>re({fill:J}),allowNone:!0,isNone:!C.style.fill,onNone:()=>re({fill:null})}),$("button",{type:"button",onClick:()=>{Qt(J=>J.filter(de=>de.id!==C.id)),$t(null),nn("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(so,{className:"h-3.5 w-3.5"})," Delete"]})]})})})(),P==="select"&&D?$("div",{style:{position:"absolute",left:0,top:0,width:"100%",height:"100%",pointerEvents:"none",zIndex:6},children:[yt&&!Ct&&yt.pageIndex===x&&yt!==ze?(()=>{var q;let C=Qe(yt.pdfX,yt.pdfY+yt.height,O,((q=_[x])==null?void 0:q.height)||792);return v("div",{style:{position:"absolute",left:`${C.x}px`,top:`${C.y}px`,width:`${yt.width*O}px`,height:`${yt.height*O}px`,border:"1.5px dashed rgba(59, 130, 246, 0.8)",borderRadius:"2px",background:"rgba(59, 130, 246, 0.05)",cursor:yt.fromXObject?"not-allowed":"move"},children:!yt.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,ze&&!Ct&&ze.pageIndex===x?(()=>{var H;let C=Qe(ze.pdfX,ze.pdfY+ze.height,O,((H=_[x])==null?void 0:H.height)||792),q=ze.width*O,z=ze.height*O;return $("div",{style:{position:"absolute",left:`${C.x}px`,top:`${C.y}px`,width:`${q}px`,height:`${z}px`,border:ze.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:ze.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)"}):$(Vt,{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"}),$("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:Z=>{Z.stopPropagation(),_o()},children:[v(so,{className:"h-3 w-3"})," Delete"]})]})}),ze.fromXObject?null:["nw","n","ne","e","se","s","sw","w"].filter(Z=>ze.kind==="image"||Z.length===2).map(Z=>{let re={position:"absolute",width:"9px",height:"9px",background:"#fff",border:"1.5px solid rgba(59, 130, 246, 0.95)",borderRadius:"2px",pointerEvents:"auto",cursor:`${Z}-resize`};return Z.includes("n")?re.top="-5px":Z.includes("s")?re.bottom="-5px":re.top="calc(50% - 5px)",Z.includes("w")?re.left="-5px":Z.includes("e")?re.right="-5px":re.left="calc(50% - 5px)",v("div",{style:re,onPointerDown:te=>{te.stopPropagation(),te.preventDefault(),Za(ze,"resize",Z,te)}},Z)})]})})():null,Ct&&Ct.object.pageIndex===x&&g?(()=>{var Z,re,te,J,de;let C=Ct.object,q=Qe(C.pdfX,C.pdfY+C.height,O,((Z=_[x])==null?void 0:Z.height)||792),z=C.width*O,H=C.height*O;return $(Vt,{children:[v("div",{style:{position:"absolute",left:`${q.x}px`,top:`${q.y}px`,width:`${z}px`,height:`${H}px`,background:(re=g.bgCss)!=null?re:"#fff"}}),v("div",{ref:pe=>{co.current=pe},style:{position:"absolute",left:`${q.x}px`,top:`${q.y}px`,width:`${z}px`,height:`${H}px`,backgroundImage:`url(${g.canvasDataUrl})`,backgroundPosition:`-${q.x}px -${q.y}px`,backgroundSize:`${(((te=_[x])==null?void 0:te.width)||612)*O}px ${(((J=_[x])==null?void 0:J.height)||792)*O}px`,transform:Ct.mode==="move"?`translate(${Ct.dxPx}px, ${Ct.dyPx}px)`:`scale(${Ct.scaleX}, ${Ct.scaleY})`,transformOrigin:Ct.mode==="resize"?J0[(de=Ct.handle)!=null?de:"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,P==="edit-text"&&D&&((B=ot.current[x])!=null&&B.length)?v("div",{style:{position:"absolute",left:0,top:0,width:"100%",height:"100%",pointerEvents:"none",zIndex:5},children:ot.current[x].map((C,q)=>{var te,J;let z=Qe(C.pdfX,C.pdfY+C.height,O,((te=_[x])==null?void 0:te.height)||792),H=!C.fromXObject&&!!((J=C.streamOperatorIndices)!=null&&J.length),Z=(Vn==null?void 0:Vn.run)===C&&Vn.pageIndex===x,re=Z?`translate(${Vn.dxPx}px, ${Vn.dyPx}px)`:void 0;return v("div",{ref:Z?de=>{ri.current=de}:void 0,title:H?"Click to edit \xB7 drag to move":"Click to edit",onPointerDown:de=>{de.button===0&&(de.stopPropagation(),de.preventDefault(),bf(C,x,de))},style:{position:"absolute",left:`${z.x}px`,top:`${z.y}px`,width:`${C.width*O}px`,height:`${C.height*O}px`,cursor:H?"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:Z?"rgba(16, 185, 129, 0.18)":"rgba(16, 185, 129, 0.04)",transform:re,transition:Z?"none":"background 0.12s",willChange:Z?"transform":void 0,zIndex:Z?20:void 0},onMouseEnter:de=>{Z||(de.currentTarget.style.background="rgba(16, 185, 129, 0.12)")},onMouseLeave:de=>{Z||(de.currentTarget.style.background="rgba(16, 185, 129, 0.04)")}},q)})}):null,(P==="form"||P==="view")&&D?(()=>{var q;let C=P==="form";return $("div",{"data-fv":ba,style:{position:"absolute",inset:0,zIndex:6,pointerEvents:"none"},children:[C&&On&&v("div",{style:{position:"absolute",inset:0,cursor:"crosshair",pointerEvents:"auto"},onPointerDown:z=>Rf(x,z)}),C&&Kn&&Kn.pageIndex===x&&v("div",{style:{position:"absolute",left:`${Kn.x}px`,top:`${Kn.y}px`,width:`${Kn.w}px`,height:`${Kn.h}px`,border:"2px dashed rgba(99,102,241,0.9)",background:"rgba(99,102,241,0.12)",pointerEvents:"none"}}),((q=jt.current[x])!=null?q:[]).map(z=>{var Ne,Xe,Be,we,zt;let H=Qe(z.rect.x,z.rect.y+z.rect.height,O,((Ne=_[x])==null?void 0:Ne.height)||792),Z=z.rect.width*O,re=z.rect.height*O,te=ci===z.id,J=(Be=(Xe=$u[z.id])!=null?Xe:z.value)!=null?Be:"",de={position:"absolute",left:`${H.x}px`,top:`${H.y}px`,width:`${Z}px`,height:`${re}px`,outline:C?te?"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:C&&On?"none":"auto",boxSizing:"border-box"},pe=()=>{C&&Uo(z)};return $(T0.Fragment,{children:[z.type==="text"||z.type==="signature"?v("input",{type:"text",value:J,readOnly:z.readOnly||z.type==="signature",placeholder:z.type==="signature"?"Signature":"",onFocus:pe,onChange:Ze=>ai(on=>({...on,[z.id]:Ze.target.value})),onBlur:Ze=>bi(z,Ze.target.value),style:{...de,padding:"0 4px",fontSize:`${Math.min(re*.7,14)}px`,color:"#111",fontStyle:z.type==="signature"?"italic":"normal"}}):z.type==="checkbox"?v("input",{type:"checkbox",checked:J===z.onState||J==="Yes"||J==="On"||J==="true",onFocus:pe,onChange:Ze=>{var on;return bi(z,Ze.target.checked?(on=z.onState)!=null?on:"Yes":"Off")},style:{...de,padding:0,accentColor:"#6366f1"}}):z.type==="dropdown"?$("select",{value:J,onFocus:pe,onChange:Ze=>bi(z,Ze.target.value),style:{...de,padding:"0 4px",fontSize:`${Math.min(re*.7,14)}px`,color:"#111"},children:[v("option",{value:""}),((we=z.options)!=null?we:[]).map(Ze=>v("option",{value:Ze,children:Ze},Ze))]}):z.type==="radio"?v("div",{style:{...de,display:"flex",flexDirection:"column",justifyContent:"space-around",padding:"2px 4px",fontSize:"11px",color:"#111"},onClick:pe,children:((zt=z.options)!=null?zt:[]).map(Ze=>$("label",{style:{display:"flex",alignItems:"center",gap:4},children:[v("input",{type:"radio",name:`${z.id}`,checked:J===Ze,onChange:()=>bi(z,Ze),style:{accentColor:"#6366f1"}}),Ze]},Ze))}):null,C&&te&&!On&&v("button",{type:"button",title:"Delete field",onClick:()=>Wa(z),style:{position:"absolute",left:`${H.x+Z-8}px`,top:`${H.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(Ot,{className:"h-3 w-3"})})]},z.id)})]})})():null,P==="view"&&D&&Math.abs(x-fe)<=2&&((L=ot.current[x])!=null&&L.length)?v(_s,{runs:ot.current[x],scale:O,pageHeight:((X=_[x])==null?void 0:X.height)||792}):null,P==="view"&&D&&((U=Te.current[x])!=null&&U.length)?v("div",{style:{position:"absolute",inset:0,zIndex:7,pointerEvents:"none"},children:Te.current[x].map((C,q)=>{var Z,re;let z=Qe(C.rect.x,C.rect.y+C.rect.height,O,((Z=_[x])==null?void 0:Z.height)||792),H={position:"absolute",left:`${z.x}px`,top:`${z.y}px`,width:`${C.rect.width*O}px`,height:`${C.rect.height*O}px`,cursor:"pointer",pointerEvents:"auto",borderRadius:"2px"};return C.uri?v("a",{href:C.uri,target:"_blank",rel:"noopener noreferrer",title:C.uri,style:H},q):v("div",{title:`Go to page ${((re=C.destPageIndex)!=null?re:0)+1}`,style:H,onClick:()=>{var te;return wi((te=C.destPageIndex)!=null?te:0)}},q)})}):null,di&&dt.filter(C=>C.pageIndex===x).length>0&&v("div",{style:{position:"absolute",inset:0,pointerEvents:"none",zIndex:8},children:dt.filter(C=>C.pageIndex===x).map((C,q)=>{var Z;let z=Qe(C.pdfX,C.pdfY+C.height,O,((Z=_[x])==null?void 0:Z.height)||792),H=dt.indexOf(C)===ui;return v("div",{style:{position:"absolute",left:`${z.x}px`,top:`${z.y}px`,width:`${C.width*O}px`,height:`${C.height*O}px`,background:H?"rgba(245, 158, 11, 0.45)":"rgba(245, 158, 11, 0.2)",outline:H?"2px solid rgba(245, 158, 11, 0.8)":"none",borderRadius:"1px"}},q)})}),P==="redact"&&At.some(C=>C.pageIndex===x)&&v("div",{style:{position:"absolute",inset:0,pointerEvents:"none",zIndex:11},children:At.filter(C=>C.pageIndex===x).map(C=>{var Z;let q=Qe(C.x,C.y+C.height,O,((Z=_[x])==null?void 0:Z.height)||792),z=C.width*O,H=C.height*O;return $("div",{style:{position:"absolute",left:`${q.x}px`,top:`${q.y}px`,width:`${z}px`,height:`${H}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",onPointerDown:re=>ja(C,"move",null,re),children:[v("button",{onPointerDown:re=>re.stopPropagation(),onClick:re=>{re.stopPropagation(),ef(C.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(re=>{let te={position:"absolute",width:"9px",height:"9px",background:"#fff",border:"1.5px solid rgba(22, 163, 74, 0.95)",borderRadius:"2px",cursor:`${re}-resize`};return re.includes("n")?te.top="-5px":re.includes("s")?te.bottom="-5px":te.top="calc(50% - 5px)",re.includes("w")?te.left="-5px":re.includes("e")?te.right="-5px":te.left="calc(50% - 5px)",v("div",{style:te,onPointerDown:J=>ja(C,"resize",re,J)},re)})]},C.id)})}),P==="redact"&&ma&&ke&&ke.pageIndex===x&&(()=>{var re;let C=Math.min(ke.startPdfX,ke.endPdfX),q=Math.min(ke.startPdfY,ke.endPdfY),z=Math.abs(ke.endPdfX-ke.startPdfX),H=Math.abs(ke.endPdfY-ke.startPdfY);if(z<.5||H<.5)return null;let Z=Qe(C,q+H,O,((re=_[x])==null?void 0:re.height)||792);return v("div",{style:{position:"absolute",left:`${Z.x}px`,top:`${Z.y}px`,width:`${z*O}px`,height:`${H*O}px`,border:"2px dashed rgba(220, 38, 38, 0.95)",background:"rgba(220, 38, 38, 0.18)",borderRadius:"2px",pointerEvents:"none",zIndex:10}})})(),ke&&ke.pageIndex===x&&v("div",{style:{position:"absolute",left:0,top:0,width:"100%",height:"100%",pointerEvents:"none",zIndex:10},children:Nn.map((C,q)=>{var H;let z=Qe(C.pdfX,C.pdfY+C.height,O,((H=_[x])==null?void 0:H.height)||792);return v("div",{style:{position:"absolute",left:`${z.x}px`,top:`${z.y}px`,width:`${C.width*O}px`,height:`${C.height*O}px`,background:"rgba(186, 0, 48, 0.12)",border:"2px solid rgba(186, 0, 48, 0.55)",borderRadius:"2px"}},q)})}),Nn.length>0&&(ke==null?void 0:ke.pageIndex)===x&&$("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:()=>Uf(),disabled:P==="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:()=>$f(),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:()=>{It([]),St(null)},className:"rounded-full px-3 py-1 text-[10px] font-bold opacity-70 transition-opacity hover:opacity-100",children:"Clear"})]}),(ae==null?void 0:ae.pageIndex)===x&&v(Ol,{ref:me,containerX:ae.containerX,containerY:ae.containerY,screenWidth:ae.screenWidth,screenHeight:ae.screenHeight,scale:O,fontSizePt:ae.fontSize,fontFamily:ae.fontFamily,baselineOffsetPx:ae.baselineOffsetPx,maxWidth:ae.maxWidth,initialSpans:(K=ae.spans)!=null?K:[],baseColor:ae.color,maskRect:ae.maskRect,bgColor:ae.bgColor,ocr:ae.ocr||ae.recovered,touch:Na,onCommit:(C,q)=>{gf(C,q)},onCancel:()=>W(null),onActiveStyleChange:be},`rt-${x}-${Math.round(ae.pdfX)}-${Math.round(ae.pdfY)}-${ae.isNew?"n":"e"}`)]},u.pageNum)})]}),v(js,{asSheet:rr,open:Ta,onClose:()=>Mo(!1),tool:P,textActive:!!ae,textStyle:xe,fallbackSizePt:(tc=ae==null?void 0:ae.fontSize)!=null?tc:F,fontName:ae==null?void 0:ae.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:In,setAnnotSubtool:Wu,highlightMode:va,setHighlightMode:Hu,drawShape:Ut,setDrawShape:Gu,annotStyle:Lt,setAnnotStyle:Yu,annotationCount:ct.length,onClearAnnotations:()=>{Qt([]),$t(null)},addFieldType:On,setAddFieldType:fo,hasFormFields:_u,selectedField:Tr,onUpdateField:u=>{Tr&&vf(Tr,u)},onDeleteField:()=>{Tr&&Wa(Tr)},onFlattenForm:()=>{wf()}}),Fo&&rr&&v("div",{className:"sheet-backdrop",onClick:()=>Ro(!1)}),Fo&&$("aside",{className:rr?"drawer-right border-l border-ink-line bg-paper-card dark:border-white/10 dark:bg-[#1a1712]":"flex w-72 shrink-0 flex-col border-l border-ink-line bg-paper-card dark:border-white/10 dark:bg-[#1a1712]",children:[$("div",{className:"flex items-center gap-2 border-b border-ink-line px-4 py-3 dark:border-white/10",children:[v(bu,{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:()=>Ro(!1),className:"rounded-lg p-1 text-ink-muted hover:bg-paper hover:text-ink dark:hover:bg-zinc-800",children:v(Ot,{className:"h-3.5 w-3.5"})})]}),v("div",{className:"flex-1 overflow-y-auto",children:nr.length===0?$("div",{className:"flex flex-col items-center justify-center gap-3 py-12 text-center",children:[v(j0,{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:[...nr].reverse().map(u=>$("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}),$("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}),$("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:()=>Ea(u),disabled:b,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))})}),nr.length>0&&v("div",{className:"border-t border-ink-line px-4 py-2 dark:border-white/10",children:v("button",{type:"button",onClick:()=>Co([]),className:"text-[11px] text-ink-muted hover:text-crimson-600 dark:text-zinc-500",children:"Clear history"})})]})]}),$("div",{className:"hidden h-6 shrink-0 items-center gap-3 border-t border-ink-line bg-paper-card px-4 text-[11px] text-ink-muted md:flex dark:border-white/10 dark:bg-[#1a1712] dark:text-zinc-500",children:[$("span",{children:[c.length," ",c.length===1?"page":"pages"]}),v("span",{className:"opacity-40",children:"\xB7"}),v("span",{className:"capitalize",children:P.replace(/-/g," ")}),ct.length+gt.length>0&&$(Vt,{children:[v("span",{className:"opacity-40",children:"\xB7"}),$("span",{className:"text-primary",children:[ct.length+gt.length," annotation",ct.length+gt.length!==1?"s":""]})]}),b&&$(Vt,{children:[v("span",{className:"opacity-40",children:"\xB7"}),v("span",{className:"animate-pulse text-primary",children:"Saving\u2026"})]})]}),$("nav",{className:"fixed inset-x-0 bottom-0 z-40 flex items-stretch gap-1 border-t border-ink-line bg-paper-card px-1.5 pt-1.5 md:hidden dark:border-white/10 dark:bg-[#1a1712]",style:{paddingBottom:"max(0.375rem, env(safe-area-inset-bottom))"},children:[v("div",{className:"scroll-x-touch flex flex-1 items-stretch gap-1",children:q0.map(({t:u,icon:g,label:x})=>$("button",{type:"button",onClick:()=>{S(u),Mo(Pu.has(u))},className:`flex min-h-[3rem] min-w-[3.25rem] shrink-0 flex-col items-center justify-center gap-0.5 rounded-lg px-2 py-1 transition-colors ${P===u?"bg-primary text-white shadow-md":"text-ink-soft hover:bg-paper hover:text-ink"}`,children:[g,v("span",{className:"text-[8px] font-semibold leading-tight",children:x})]},u))}),Pu.has(P)&&$("button",{type:"button",onClick:()=>Mo(u=>!u),className:`flex min-h-[3rem] min-w-[3.25rem] shrink-0 flex-col items-center justify-center gap-0.5 rounded-lg px-2 py-1 transition-colors ${Ta?"bg-crimson-100 text-crimson-600":"text-ink-soft hover:bg-paper hover:text-ink"}`,children:[v(H0,{className:"h-4 w-4"}),v("span",{className:"text-[8px] font-semibold leading-tight",children:"Options"})]}),$("button",{type:"button",onClick:()=>Bn(!0),className:"flex min-h-[3rem] min-w-[3.25rem] shrink-0 flex-col items-center justify-center gap-0.5 rounded-lg border-l border-ink-line px-2 py-1 text-ink-soft transition-colors hover:bg-paper hover:text-ink dark:border-white/10",children:[v(yu,{className:"h-4 w-4"}),v("span",{className:"text-[8px] font-semibold leading-tight",children:"More"})]})]}),qu&&$(Vt,{children:[v("div",{className:"sheet-backdrop",onClick:()=>Bn(!1)}),$("div",{className:"bottom-sheet border-t border-ink-line bg-paper-card dark:border-white/10 dark:bg-[#1a1712]",children:[v("div",{className:"sheet-handle"}),$("div",{className:"flex items-center gap-2 border-b border-ink-line px-4 py-3 text-crimson-600 dark:border-white/10",children:[v(yu,{className:"h-4 w-4"}),v("span",{className:"font-display text-sm font-bold text-ink dark:text-white",children:"More actions"}),v("div",{className:"flex-1"}),v("button",{type:"button",onClick:()=>Bn(!1),"aria-label":"Close",className:"rounded-lg p-1 text-ink-muted hover:bg-paper hover:text-ink dark:hover:bg-zinc-800",children:v(Ot,{className:"h-4 w-4"})})]}),$("div",{className:"grid grid-cols-2 gap-2 p-4",children:[$("button",{type:"button",onClick:()=>{Bn(!1),Zn(u=>!u),setTimeout(()=>{var u;return(u=Rr.current)==null?void 0:u.focus()},50)},className:"flex min-h-[3rem] items-center justify-center gap-2 rounded-lg border border-ink-line-strong px-3 py-2 text-sm font-semibold text-ink-soft transition-colors hover:bg-paper dark:border-white/10 dark:text-zinc-300 dark:hover:bg-zinc-800",children:[v(oo,{className:"h-4 w-4"})," Find & Replace"]}),$("button",{type:"button",onClick:()=>{var u;Bn(!1),(u=bo.current)==null||u.click()},disabled:b,className:"flex min-h-[3rem] items-center justify-center gap-2 rounded-lg border border-ink-line-strong px-3 py-2 text-sm 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:[v(ku,{className:"h-4 w-4"})," Insert image"]}),$("button",{type:"button",onClick:()=>{Bn(!1),st({type:"rotate-page",pageIndex:xi,degrees:Oa})},disabled:b,className:"flex min-h-[3rem] items-center justify-center gap-2 rounded-lg border border-ink-line-strong px-3 py-2 text-sm 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:[v(wu,{className:"h-4 w-4"})," Rotate page"]}),$("button",{type:"button",onClick:()=>{Bn(!1),st({type:"delete-page",pageIndex:xi})},disabled:b,className:"flex min-h-[3rem] items-center justify-center gap-2 rounded-lg border border-red-200 px-3 py-2 text-sm font-semibold text-red-500 transition-colors hover:bg-red-50 disabled:opacity-40 dark:border-red-500/30 dark:hover:bg-red-500/10",children:[v(so,{className:"h-4 w-4"})," Delete page"]})]})]})]})]}),Uu&&v("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm",children:$("div",{className:"flex flex-col items-center gap-4",children:[$("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"})]}),$("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"})]})]})}),Lu&&xn.current&&v("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm",children:$("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."}),k&&k.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:k})}),v("input",{type:"password",value:Dr,onChange:u=>ni(u.target.value),onKeyDown:u=>{u.key==="Enter"&&Dr.trim()&&Qa()},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}),$("div",{className:"flex gap-3",children:[v("button",{type:"button",onClick:()=>{ni(""),Hn(!1),xn.current=null,w("")},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:Qa,disabled:!Dr.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"})]})]})}),Vu&&v("div",{className:"fixed inset-0 z-[100] flex items-center justify-center bg-black/60 backdrop-blur-sm",onClick:()=>er(!1),children:$("div",{className:"w-[480px] max-w-[95vw] rounded-2xl bg-paper-raised shadow-2xl dark:bg-zinc-900",onClick:u=>u.stopPropagation(),children:[$("div",{className:"flex items-center gap-3 border-b border-ink-line px-6 py-4 dark:border-white/10",children:[v(la,{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:()=>er(!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(Ot,{className:"h-4 w-4"})})]}),$("div",{className:"px-6 py-4",children:[$("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:"}),$("button",{type:"button",onClick:()=>{var u;return(u=Sa.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(sa,{className:"h-3.5 w-3.5"})," Upload image"]}),v("input",{ref:Sa,type:"file",accept:"image/png,image/jpeg",className:"hidden",onChange:u=>{var D;let g=(D=u.target.files)==null?void 0:D[0];if(u.target.value="",!g)return;let x=new FileReader;x.onload=()=>{typeof x.result=="string"&&(Da(x.result),er(!1),pi(!0))},x.readAsDataURL(g)}})]}),v("canvas",{ref:tr,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"},onPointerDown:u=>{u.currentTarget.setPointerCapture(u.pointerId);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",gi.current=!0)},onPointerMove:u=>{if(!gi.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())},onPointerUp:()=>{gi.current=!1},onPointerLeave:()=>{gi.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"})]}),$("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=tr.current)==null?void 0:g.getContext("2d");u&&tr.current&&u.clearRect(0,0,tr.current.width,tr.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:()=>er(!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"}),$("button",{type:"button",onClick:()=>{let u=tr.current;u&&(Da(u.toDataURL("image/png")),er(!1),pi(!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(io,{className:"h-4 w-4"}),"Apply Signature"]})]})]})}),Ku&&v("div",{className:"fixed inset-0 z-[100] flex items-center justify-center bg-black/60 backdrop-blur-sm",onClick:()=>Nr(!1),children:$("div",{className:"w-[480px] max-w-[95vw] rounded-2xl bg-paper-raised shadow-2xl dark:bg-zinc-900",onClick:u=>u.stopPropagation(),children:[$("div",{className:"flex items-center gap-3 border-b border-ink-line px-6 py-4 dark:border-white/10",children:[v(ei,{className:"h-5 w-5 text-emerald-600"}),v("h2",{className:"font-headline text-lg font-bold text-on-surface dark:text-white",children:"Sign & certify"}),v("div",{className:"flex-1"}),v("button",{type:"button",onClick:()=>Nr(!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(Ot,{className:"h-4 w-4"})})]}),$("div",{className:"space-y-4 px-6 py-4",children:[v("p",{className:"text-sm text-on-secondary-container dark:text-zinc-400",children:"This embeds a cryptographic signature so the document becomes tamper-evident, and records a signing audit trail."}),$("div",{className:"grid gap-3",children:[$("label",{className:"text-xs font-semibold text-on-secondary-container dark:text-zinc-400",children:["Reason ",v("span",{className:"font-normal text-on-secondary-container/60",children:"(optional)"}),v("input",{type:"text",value:Po,onChange:u=>Ca(u.target.value),placeholder:"e.g. I approve this document",className:"mt-1 w-full rounded-lg border border-outline-variant/40 bg-paper px-3 py-2 text-sm text-on-surface dark:border-white/10 dark:bg-zinc-800 dark:text-white"})]}),$("label",{className:"text-xs font-semibold text-on-secondary-container dark:text-zinc-400",children:["Location ",v("span",{className:"font-normal text-on-secondary-container/60",children:"(optional)"}),v("input",{type:"text",value:Do,onChange:u=>Fa(u.target.value),placeholder:"e.g. Mumbai, IN",className:"mt-1 w-full rounded-lg border border-outline-variant/40 bg-paper px-3 py-2 text-sm text-on-surface dark:border-white/10 dark:bg-zinc-800 dark:text-white"})]})]}),$("label",{className:"flex items-start gap-2 text-xs text-on-secondary-container dark:text-zinc-400",children:[v("input",{type:"checkbox",checked:Ra,onChange:u=>So(u.target.checked),className:"mt-0.5"}),v("span",{children:"I intend to sign this document and consent to signing it electronically."})]})]}),$("div",{className:"flex items-center gap-3 border-t border-ink-line px-6 py-4 dark:border-white/10",children:[v("div",{className:"flex-1"}),v("button",{type:"button",onClick:()=>Nr(!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"}),$("button",{type:"button",disabled:!Ra||b,onClick:()=>{rf()},className:"inline-flex items-center gap-2 rounded-xl bg-emerald-600 px-5 py-2 text-sm font-bold text-white hover:bg-emerald-700 disabled:cursor-not-allowed disabled:opacity-60",children:[v(ei,{className:"h-4 w-4"}),"Sign & certify"]})]})]})})]})},Eu=nx;var rx={r:255,g:255,b:255},ix={r:0,g:0,b:0};function da(t){if(typeof t!="string")return null;let e=t.trim().replace(/^#/,"");return e.length===3&&(e=e[0]+e[0]+e[1]+e[1]+e[2]+e[2]),e.length!==6||/[^0-9a-fA-F]/.test(e)?null:{r:parseInt(e.slice(0,2),16),g:parseInt(e.slice(2,4),16),b:parseInt(e.slice(4,6),16)}}function Ou(t,e,n){return{r:Math.round(t.r+(e.r-t.r)*n),g:Math.round(t.g+(e.g-t.g)*n),b:Math.round(t.b+(e.b-t.b)*n)}}function Ve(t){return`${t.r} ${t.g} ${t.b}`}var Dt=(t,e)=>Ou(t,rx,e),ti=(t,e)=>Ou(t,ix,e);function ua(t){let e={};if(!t)return e;let n=t.primary?da(t.primary):null;n&&(e["--namaha-primary-50"]=Ve(Dt(n,.92)),e["--namaha-primary-100"]=Ve(Dt(n,.84)),e["--namaha-primary-200"]=Ve(Dt(n,.68)),e["--namaha-primary-300"]=Ve(Dt(n,.5)),e["--namaha-primary-400"]=Ve(Dt(n,.3)),e["--namaha-primary-500"]=Ve(Dt(n,.14)),e["--namaha-primary-600"]=Ve(n),e["--namaha-primary-700"]=Ve(ti(n,.16)),e["--namaha-primary-800"]=Ve(ti(n,.3)),e["--namaha-primary-900"]=Ve(ti(n,.44)));let r=t.surface?da(t.surface):null;r&&(e["--namaha-surface"]=Ve(r),e["--namaha-surface-card"]=Ve(Dt(r,.45)),e["--namaha-surface-raised"]=Ve(Dt(r,.78)),e["--namaha-surface-high"]=Ve(ti(r,.04)),e["--namaha-surface-editor"]=Ve(ti(r,.07)));let i=t.text?da(t.text):null;return i&&(e["--namaha-text"]=Ve(i),e["--namaha-text-soft"]=Ve(Dt(i,.3)),e["--namaha-text-dim"]=Ve(Dt(i,.4)),e["--namaha-text-muted"]=Ve(Dt(i,.62)),e["--namaha-line"]=Ve(Dt(i,.85)),e["--namaha-line-strong"]=Ve(Dt(i,.8))),e}import{jsx as Iu}from"react/jsx-runtime";function Bu({licenseKey:t,activationUrl:e,decryptUrl:n,signUrl:r,theme:i,className:o,style:s}){let a=fa.useMemo(()=>({licenseKey:t,activationUrl:e}),[t,e]),l=fa.useMemo(()=>({...ua(i),...s}),[i,s]);return Iu("div",{className:o?`namahapdf-root ${o}`:"namahapdf-root",style:l,children:Iu(Eu,{license:a,decryptUrl:n,signUrl:r})})}var ox=Bu;export{Bu as NamahaEditor,ua as buildThemeVars,vs as configureLicense,ox as default,im as getLicenseState,cl as isFeatureEnabled,om as onLicenseChange,Bi as shouldWatermark};
|