From 67b60814a574919c307248acd27302b978a7e141 Mon Sep 17 00:00:00 2001 From: Walid Date: Fri, 10 Jul 2026 01:02:02 +0600 Subject: [PATCH 1/3] chore: update version to 4.2.0 --- README.md | 4 +- main.js | 313 ++++++++++++++++++++++++++++++++++++++++++++++ main.ts | 20 +-- manifest.json | 2 +- package-lock.json | 4 +- package.json | 2 +- 6 files changed, 329 insertions(+), 16 deletions(-) create mode 100644 main.js diff --git a/README.md b/README.md index 8dda0ff..8e7a89a 100644 --- a/README.md +++ b/README.md @@ -33,7 +33,7 @@ If this plugin saves you time, consider **[supporting the project](https://shrek - **Full layout control** — margins, font family/size/line height, paragraph spacing, heading scale, colors - **Page frame** — optional border drawn around the outer edge of every page (solid, dashed, dotted, double, groove, or ridge) - **Background** — solid color or a background image with fit, scope (full page or content area only), and opacity controls -- **Header & footer** — custom text, customizable page numbers (`{{page_current}}` / `{{page_total}}` template placeholders), alignment, font size/color, optional banner image, and first-page suppression +- **Header & footer** — custom text, customizable page numbers (`{{current}}` / `{{total}}` template placeholders), alignment, font size/color, optional banner image, and first-page suppression - **PDF outline (bookmarks)** — heading-based bookmark tree embedded in the exported PDF; most PDF readers display it in a side panel ## Screenshots @@ -187,7 +187,7 @@ All settings take effect after closing the settings panel. | Image left/right margin | Insets the banner from the left and right page edges (px) | | Show page numbers | Toggle *Page X / Y* display | | Page number position | Left, Center, or Right | -| Page number format | Custom template using `{{page_current}}` and `{{page_total}}` placeholders, e.g. `Page {{page_current}} of {{page_total}}`, `{{page_current}}/{{page_total}}`, or just `{{page_current}}` (default: `{{page_current}} / {{page_total}}`) | +| Page number format | Custom template using `{{current}}` and `{{total}}` placeholders, e.g. `Page {{current}} of {{total}}`, `{{current}}/{{total}}`, or just `{{current}}` (default: `{{current}} / {{total}}`) | | Page number start | Number assigned to the first visible page number (default 1) | ### Behaviour diff --git a/main.js b/main.js new file mode 100644 index 0000000..b069885 --- /dev/null +++ b/main.js @@ -0,0 +1,313 @@ +var td=Object.create;var Go=Object.defineProperty;var rd=Object.getOwnPropertyDescriptor;var nd=Object.getOwnPropertyNames;var od=Object.getPrototypeOf,id=Object.prototype.hasOwnProperty;var He=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),ad=(t,e)=>{for(var r in e)Go(t,r,{get:e[r],enumerable:!0})},Es=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of nd(e))!id.call(t,o)&&o!==r&&Go(t,o,{get:()=>e[o],enumerable:!(n=rd(e,o))||n.enumerable});return t};var Ko=(t,e,r)=>(r=t!=null?td(od(t)):{},Es(e||!t||!t.__esModule?Go(r,"default",{value:t,enumerable:!0}):r,t)),sd=t=>Es(Go({},"__esModule",{value:!0}),t);var It=He(Ke=>{"use strict";var vd=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Int32Array<"u";function md(t,e){return Object.prototype.hasOwnProperty.call(t,e)}Ke.assign=function(t){for(var e=Array.prototype.slice.call(arguments,1);e.length;){var r=e.shift();if(r){if(typeof r!="object")throw new TypeError(r+"must be non-object");for(var n in r)md(r,n)&&(t[n]=r[n])}}return t};Ke.shrinkBuf=function(t,e){return t.length===e?t:t.subarray?t.subarray(0,e):(t.length=e,t)};var gd={arraySet:function(t,e,r,n,o){if(e.subarray&&t.subarray){t.set(e.subarray(r,r+n),o);return}for(var i=0;i{"use strict";var bd=It(),xd=4,tl=0,rl=1,Fd=2;function Kr(t){for(var e=t.length;--e>=0;)t[e]=0}var wd=0,ll=1,Sd=2,Pd=3,Dd=258,oa=29,Hn=256,In=Hn+1+oa,Gr=30,ia=19,fl=2*In+1,yr=15,_i=16,Cd=7,aa=256,cl=16,ul=17,dl=18,ra=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],$o=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],kd=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],hl=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],Td=512,zt=new Array((In+2)*2);Kr(zt);var Mn=new Array(Gr*2);Kr(Mn);var zn=new Array(Td);Kr(zn);var jn=new Array(Dd-Pd+1);Kr(jn);var sa=new Array(oa);Kr(sa);var ei=new Array(Gr);Kr(ei);function $i(t,e,r,n,o){this.static_tree=t,this.extra_bits=e,this.extra_base=r,this.elems=n,this.max_length=o,this.has_stree=t&&t.length}var pl,vl,ml;function ea(t,e){this.dyn_tree=t,this.max_code=0,this.stat_desc=e}function gl(t){return t<256?zn[t]:zn[256+(t>>>7)]}function Ln(t,e){t.pending_buf[t.pending++]=e&255,t.pending_buf[t.pending++]=e>>>8&255}function _e(t,e,r){t.bi_valid>_i-r?(t.bi_buf|=e<>_i-t.bi_valid,t.bi_valid+=r-_i):(t.bi_buf|=e<>>=1,r<<=1;while(--e>0);return r>>>1}function Ed(t){t.bi_valid===16?(Ln(t,t.bi_buf),t.bi_buf=0,t.bi_valid=0):t.bi_valid>=8&&(t.pending_buf[t.pending++]=t.bi_buf&255,t.bi_buf>>=8,t.bi_valid-=8)}function Ad(t,e){var r=e.dyn_tree,n=e.max_code,o=e.stat_desc.static_tree,i=e.stat_desc.has_stree,a=e.stat_desc.extra_bits,s=e.stat_desc.extra_base,f=e.stat_desc.max_length,l,c,u,d,p,h,b=0;for(d=0;d<=yr;d++)t.bl_count[d]=0;for(r[t.heap[t.heap_max]*2+1]=0,l=t.heap_max+1;lf&&(d=f,b++),r[c*2+1]=d,!(c>n)&&(t.bl_count[d]++,p=0,c>=s&&(p=a[c-s]),h=r[c*2],t.opt_len+=h*(d+p),i&&(t.static_len+=h*(o[c*2+1]+p)));if(b!==0){do{for(d=f-1;t.bl_count[d]===0;)d--;t.bl_count[d]--,t.bl_count[d+1]+=2,t.bl_count[f]--,b-=2}while(b>0);for(d=f;d!==0;d--)for(c=t.bl_count[d];c!==0;)u=t.heap[--l],!(u>n)&&(r[u*2+1]!==d&&(t.opt_len+=(d-r[u*2+1])*r[u*2],r[u*2+1]=d),c--)}}function bl(t,e,r){var n=new Array(yr+1),o=0,i,a;for(i=1;i<=yr;i++)n[i]=o=o+r[i-1]<<1;for(a=0;a<=e;a++){var s=t[a*2+1];s!==0&&(t[a*2]=yl(n[s]++,s))}}function Rd(){var t,e,r,n,o,i=new Array(yr+1);for(r=0,n=0;n>=7;n8?Ln(t,t.bi_buf):t.bi_valid>0&&(t.pending_buf[t.pending++]=t.bi_buf),t.bi_buf=0,t.bi_valid=0}function Od(t,e,r,n){Fl(t),n&&(Ln(t,r),Ln(t,~r)),bd.arraySet(t.pending_buf,t.window,e,r,t.pending),t.pending+=r}function nl(t,e,r,n){var o=e*2,i=r*2;return t[o]>1;a>=1;a--)ta(t,r,a);l=i;do a=t.heap[1],t.heap[1]=t.heap[t.heap_len--],ta(t,r,1),s=t.heap[1],t.heap[--t.heap_max]=a,t.heap[--t.heap_max]=s,r[l*2]=r[a*2]+r[s*2],t.depth[l]=(t.depth[a]>=t.depth[s]?t.depth[a]:t.depth[s])+1,r[a*2+1]=r[s*2+1]=l,t.heap[1]=l++,ta(t,r,1);while(t.heap_len>=2);t.heap[--t.heap_max]=t.heap[1],Ad(t,e),bl(r,f,t.bl_count)}function il(t,e,r){var n,o=-1,i,a=e[0*2+1],s=0,f=7,l=4;for(a===0&&(f=138,l=3),e[(r+1)*2+1]=65535,n=0;n<=r;n++)i=a,a=e[(n+1)*2+1],!(++s=3&&t.bl_tree[hl[e]*2+1]===0;e--);return t.opt_len+=3*(e+1)+5+5+4,e}function Nd(t,e,r,n){var o;for(_e(t,e-257,5),_e(t,r-1,5),_e(t,n-4,4),o=0;o>>=1)if(e&1&&t.dyn_ltree[r*2]!==0)return tl;if(t.dyn_ltree[9*2]!==0||t.dyn_ltree[10*2]!==0||t.dyn_ltree[13*2]!==0)return rl;for(r=32;r0?(t.strm.data_type===Fd&&(t.strm.data_type=Md(t)),na(t,t.l_desc),na(t,t.d_desc),a=Bd(t),o=t.opt_len+3+7>>>3,i=t.static_len+3+7>>>3,i<=o&&(o=i)):o=i=r+5,r+4<=o&&e!==-1?wl(t,e,r,n):t.strategy===xd||i===o?(_e(t,(ll<<1)+(n?1:0),3),ol(t,zt,Mn)):(_e(t,(Sd<<1)+(n?1:0),3),Nd(t,t.l_desc.max_code+1,t.d_desc.max_code+1,a+1),ol(t,t.dyn_ltree,t.dyn_dtree)),xl(t),n&&Fl(t)}function Ld(t,e,r){return t.pending_buf[t.d_buf+t.last_lit*2]=e>>>8&255,t.pending_buf[t.d_buf+t.last_lit*2+1]=e&255,t.pending_buf[t.l_buf+t.last_lit]=r&255,t.last_lit++,e===0?t.dyn_ltree[r*2]++:(t.matches++,e--,t.dyn_ltree[(jn[r]+Hn+1)*2]++,t.dyn_dtree[gl(e)*2]++),t.last_lit===t.lit_bufsize-1}Xr._tr_init=Id;Xr._tr_stored_block=wl;Xr._tr_flush_block=jd;Xr._tr_tally=Ld;Xr._tr_align=zd});var la=He((_m,Pl)=>{"use strict";function Hd(t,e,r,n){for(var o=t&65535|0,i=t>>>16&65535|0,a=0;r!==0;){a=r>2e3?2e3:r,r-=a;do o=o+e[n++]|0,i=i+o|0;while(--a);o%=65521,i%=65521}return o|i<<16|0}Pl.exports=Hd});var fa=He(($m,Dl)=>{"use strict";function Ud(){for(var t,e=[],r=0;r<256;r++){t=r;for(var n=0;n<8;n++)t=t&1?3988292384^t>>>1:t>>>1;e[r]=t}return e}var Vd=Ud();function qd(t,e,r,n){var o=Vd,i=n+r;t^=-1;for(var a=n;a>>8^o[(t^e[a])&255];return t^-1}Dl.exports=qd});var ti=He((eg,Cl)=>{"use strict";Cl.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}});var Ml=He(kt=>{"use strict";var Xe=It(),at=Sl(),Al=la(),Kt=fa(),Wd=ti(),wr=0,Gd=1,Kd=3,Qt=4,kl=5,Ct=0,Tl=1,st=-2,Xd=-3,ca=-5,Zd=-1,Yd=1,ri=2,Jd=3,Qd=4,_d=0,$d=2,ai=8,eh=9,th=15,rh=8,nh=29,oh=256,da=oh+1+nh,ih=30,ah=19,sh=2*da+1,lh=15,de=3,Yt=258,mt=Yt+de+1,fh=32,si=42,ha=69,ni=73,oi=91,ii=103,br=113,Vn=666,Ne=1,qn=2,xr=3,Jr=4,ch=3;function Jt(t,e){return t.msg=Wd[e],e}function El(t){return(t<<1)-(t>4?9:0)}function Zt(t){for(var e=t.length;--e>=0;)t[e]=0}function Xt(t){var e=t.state,r=e.pending;r>t.avail_out&&(r=t.avail_out),r!==0&&(Xe.arraySet(t.output,e.pending_buf,e.pending_out,r,t.next_out),t.next_out+=r,e.pending_out+=r,t.total_out+=r,t.avail_out-=r,e.pending-=r,e.pending===0&&(e.pending_out=0))}function je(t,e){at._tr_flush_block(t,t.block_start>=0?t.block_start:-1,t.strstart-t.block_start,e),t.block_start=t.strstart,Xt(t.strm)}function he(t,e){t.pending_buf[t.pending++]=e}function Un(t,e){t.pending_buf[t.pending++]=e>>>8&255,t.pending_buf[t.pending++]=e&255}function uh(t,e,r,n){var o=t.avail_in;return o>n&&(o=n),o===0?0:(t.avail_in-=o,Xe.arraySet(e,t.input,t.next_in,o,r),t.state.wrap===1?t.adler=Al(t.adler,e,o,r):t.state.wrap===2&&(t.adler=Kt(t.adler,e,o,r)),t.next_in+=o,t.total_in+=o,o)}function Rl(t,e){var r=t.max_chain_length,n=t.strstart,o,i,a=t.prev_length,s=t.nice_match,f=t.strstart>t.w_size-mt?t.strstart-(t.w_size-mt):0,l=t.window,c=t.w_mask,u=t.prev,d=t.strstart+Yt,p=l[n+a-1],h=l[n+a];t.prev_length>=t.good_match&&(r>>=2),s>t.lookahead&&(s=t.lookahead);do if(o=e,!(l[o+a]!==h||l[o+a-1]!==p||l[o]!==l[n]||l[++o]!==l[n+1])){n+=2,o++;do;while(l[++n]===l[++o]&&l[++n]===l[++o]&&l[++n]===l[++o]&&l[++n]===l[++o]&&l[++n]===l[++o]&&l[++n]===l[++o]&&l[++n]===l[++o]&&l[++n]===l[++o]&&na){if(t.match_start=e,a=i,i>=s)break;p=l[n+a-1],h=l[n+a]}}while((e=u[e&c])>f&&--r!==0);return a<=t.lookahead?a:t.lookahead}function Fr(t){var e=t.w_size,r,n,o,i,a;do{if(i=t.window_size-t.lookahead-t.strstart,t.strstart>=e+(e-mt)){Xe.arraySet(t.window,t.window,e,e,0),t.match_start-=e,t.strstart-=e,t.block_start-=e,n=t.hash_size,r=n;do o=t.head[--r],t.head[r]=o>=e?o-e:0;while(--n);n=e,r=n;do o=t.prev[--r],t.prev[r]=o>=e?o-e:0;while(--n);i+=e}if(t.strm.avail_in===0)break;if(n=uh(t.strm,t.window,t.strstart+t.lookahead,i),t.lookahead+=n,t.lookahead+t.insert>=de)for(a=t.strstart-t.insert,t.ins_h=t.window[a],t.ins_h=(t.ins_h<t.pending_buf_size-5&&(r=t.pending_buf_size-5);;){if(t.lookahead<=1){if(Fr(t),t.lookahead===0&&e===wr)return Ne;if(t.lookahead===0)break}t.strstart+=t.lookahead,t.lookahead=0;var n=t.block_start+r;if((t.strstart===0||t.strstart>=n)&&(t.lookahead=t.strstart-n,t.strstart=n,je(t,!1),t.strm.avail_out===0)||t.strstart-t.block_start>=t.w_size-mt&&(je(t,!1),t.strm.avail_out===0))return Ne}return t.insert=0,e===Qt?(je(t,!0),t.strm.avail_out===0?xr:Jr):(t.strstart>t.block_start&&(je(t,!1),t.strm.avail_out===0),Ne)}function ua(t,e){for(var r,n;;){if(t.lookahead=de&&(t.ins_h=(t.ins_h<=de)if(n=at._tr_tally(t,t.strstart-t.match_start,t.match_length-de),t.lookahead-=t.match_length,t.match_length<=t.max_lazy_match&&t.lookahead>=de){t.match_length--;do t.strstart++,t.ins_h=(t.ins_h<=de&&(t.ins_h=(t.ins_h<4096)&&(t.match_length=de-1)),t.prev_length>=de&&t.match_length<=t.prev_length){o=t.strstart+t.lookahead-de,n=at._tr_tally(t,t.strstart-1-t.prev_match,t.prev_length-de),t.lookahead-=t.prev_length-1,t.prev_length-=2;do++t.strstart<=o&&(t.ins_h=(t.ins_h<=de&&t.strstart>0&&(o=t.strstart-1,n=a[o],n===a[++o]&&n===a[++o]&&n===a[++o])){i=t.strstart+Yt;do;while(n===a[++o]&&n===a[++o]&&n===a[++o]&&n===a[++o]&&n===a[++o]&&n===a[++o]&&n===a[++o]&&n===a[++o]&&ot.lookahead&&(t.match_length=t.lookahead)}if(t.match_length>=de?(r=at._tr_tally(t,1,t.match_length-de),t.lookahead-=t.match_length,t.strstart+=t.match_length,t.match_length=0):(r=at._tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++),r&&(je(t,!1),t.strm.avail_out===0))return Ne}return t.insert=0,e===Qt?(je(t,!0),t.strm.avail_out===0?xr:Jr):t.last_lit&&(je(t,!1),t.strm.avail_out===0)?Ne:qn}function ph(t,e){for(var r;;){if(t.lookahead===0&&(Fr(t),t.lookahead===0)){if(e===wr)return Ne;break}if(t.match_length=0,r=at._tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++,r&&(je(t,!1),t.strm.avail_out===0))return Ne}return t.insert=0,e===Qt?(je(t,!0),t.strm.avail_out===0?xr:Jr):t.last_lit&&(je(t,!1),t.strm.avail_out===0)?Ne:qn}function Dt(t,e,r,n,o){this.good_length=t,this.max_lazy=e,this.nice_length=r,this.max_chain=n,this.func=o}var Yr;Yr=[new Dt(0,0,0,0,dh),new Dt(4,4,8,4,ua),new Dt(4,5,16,8,ua),new Dt(4,6,32,32,ua),new Dt(4,4,16,16,Zr),new Dt(8,16,32,32,Zr),new Dt(8,16,128,128,Zr),new Dt(8,32,128,256,Zr),new Dt(32,128,258,1024,Zr),new Dt(32,258,258,4096,Zr)];function vh(t){t.window_size=2*t.w_size,Zt(t.head),t.max_lazy_match=Yr[t.level].max_lazy,t.good_match=Yr[t.level].good_length,t.nice_match=Yr[t.level].nice_length,t.max_chain_length=Yr[t.level].max_chain,t.strstart=0,t.block_start=0,t.lookahead=0,t.insert=0,t.match_length=t.prev_length=de-1,t.match_available=0,t.ins_h=0}function mh(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=ai,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new Xe.Buf16(sh*2),this.dyn_dtree=new Xe.Buf16((2*ih+1)*2),this.bl_tree=new Xe.Buf16((2*ah+1)*2),Zt(this.dyn_ltree),Zt(this.dyn_dtree),Zt(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Xe.Buf16(lh+1),this.heap=new Xe.Buf16(2*da+1),Zt(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Xe.Buf16(2*da+1),Zt(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function Ol(t){var e;return!t||!t.state?Jt(t,st):(t.total_in=t.total_out=0,t.data_type=$d,e=t.state,e.pending=0,e.pending_out=0,e.wrap<0&&(e.wrap=-e.wrap),e.status=e.wrap?si:br,t.adler=e.wrap===2?0:1,e.last_flush=wr,at._tr_init(e),Ct)}function Bl(t){var e=Ol(t);return e===Ct&&vh(t.state),e}function gh(t,e){return!t||!t.state||t.state.wrap!==2?st:(t.state.gzhead=e,Ct)}function Nl(t,e,r,n,o,i){if(!t)return st;var a=1;if(e===Zd&&(e=6),n<0?(a=0,n=-n):n>15&&(a=2,n-=16),o<1||o>eh||r!==ai||n<8||n>15||e<0||e>9||i<0||i>Qd)return Jt(t,st);n===8&&(n=9);var s=new mh;return t.state=s,s.strm=t,s.wrap=a,s.gzhead=null,s.w_bits=n,s.w_size=1<kl||e<0)return t?Jt(t,st):st;if(n=t.state,!t.output||!t.input&&t.avail_in!==0||n.status===Vn&&e!==Qt)return Jt(t,t.avail_out===0?ca:st);if(n.strm=t,r=n.last_flush,n.last_flush=e,n.status===si)if(n.wrap===2)t.adler=0,he(n,31),he(n,139),he(n,8),n.gzhead?(he(n,(n.gzhead.text?1:0)+(n.gzhead.hcrc?2:0)+(n.gzhead.extra?4:0)+(n.gzhead.name?8:0)+(n.gzhead.comment?16:0)),he(n,n.gzhead.time&255),he(n,n.gzhead.time>>8&255),he(n,n.gzhead.time>>16&255),he(n,n.gzhead.time>>24&255),he(n,n.level===9?2:n.strategy>=ri||n.level<2?4:0),he(n,n.gzhead.os&255),n.gzhead.extra&&n.gzhead.extra.length&&(he(n,n.gzhead.extra.length&255),he(n,n.gzhead.extra.length>>8&255)),n.gzhead.hcrc&&(t.adler=Kt(t.adler,n.pending_buf,n.pending,0)),n.gzindex=0,n.status=ha):(he(n,0),he(n,0),he(n,0),he(n,0),he(n,0),he(n,n.level===9?2:n.strategy>=ri||n.level<2?4:0),he(n,ch),n.status=br);else{var a=ai+(n.w_bits-8<<4)<<8,s=-1;n.strategy>=ri||n.level<2?s=0:n.level<6?s=1:n.level===6?s=2:s=3,a|=s<<6,n.strstart!==0&&(a|=fh),a+=31-a%31,n.status=br,Un(n,a),n.strstart!==0&&(Un(n,t.adler>>>16),Un(n,t.adler&65535)),t.adler=1}if(n.status===ha)if(n.gzhead.extra){for(o=n.pending;n.gzindex<(n.gzhead.extra.length&65535)&&!(n.pending===n.pending_buf_size&&(n.gzhead.hcrc&&n.pending>o&&(t.adler=Kt(t.adler,n.pending_buf,n.pending-o,o)),Xt(t),o=n.pending,n.pending===n.pending_buf_size));)he(n,n.gzhead.extra[n.gzindex]&255),n.gzindex++;n.gzhead.hcrc&&n.pending>o&&(t.adler=Kt(t.adler,n.pending_buf,n.pending-o,o)),n.gzindex===n.gzhead.extra.length&&(n.gzindex=0,n.status=ni)}else n.status=ni;if(n.status===ni)if(n.gzhead.name){o=n.pending;do{if(n.pending===n.pending_buf_size&&(n.gzhead.hcrc&&n.pending>o&&(t.adler=Kt(t.adler,n.pending_buf,n.pending-o,o)),Xt(t),o=n.pending,n.pending===n.pending_buf_size)){i=1;break}n.gzindexo&&(t.adler=Kt(t.adler,n.pending_buf,n.pending-o,o)),i===0&&(n.gzindex=0,n.status=oi)}else n.status=oi;if(n.status===oi)if(n.gzhead.comment){o=n.pending;do{if(n.pending===n.pending_buf_size&&(n.gzhead.hcrc&&n.pending>o&&(t.adler=Kt(t.adler,n.pending_buf,n.pending-o,o)),Xt(t),o=n.pending,n.pending===n.pending_buf_size)){i=1;break}n.gzindexo&&(t.adler=Kt(t.adler,n.pending_buf,n.pending-o,o)),i===0&&(n.status=ii)}else n.status=ii;if(n.status===ii&&(n.gzhead.hcrc?(n.pending+2>n.pending_buf_size&&Xt(t),n.pending+2<=n.pending_buf_size&&(he(n,t.adler&255),he(n,t.adler>>8&255),t.adler=0,n.status=br)):n.status=br),n.pending!==0){if(Xt(t),t.avail_out===0)return n.last_flush=-1,Ct}else if(t.avail_in===0&&El(e)<=El(r)&&e!==Qt)return Jt(t,ca);if(n.status===Vn&&t.avail_in!==0)return Jt(t,ca);if(t.avail_in!==0||n.lookahead!==0||e!==wr&&n.status!==Vn){var f=n.strategy===ri?ph(n,e):n.strategy===Jd?hh(n,e):Yr[n.level].func(n,e);if((f===xr||f===Jr)&&(n.status=Vn),f===Ne||f===xr)return t.avail_out===0&&(n.last_flush=-1),Ct;if(f===qn&&(e===Gd?at._tr_align(n):e!==kl&&(at._tr_stored_block(n,0,0,!1),e===Kd&&(Zt(n.head),n.lookahead===0&&(n.strstart=0,n.block_start=0,n.insert=0))),Xt(t),t.avail_out===0))return n.last_flush=-1,Ct}return e!==Qt?Ct:n.wrap<=0?Tl:(n.wrap===2?(he(n,t.adler&255),he(n,t.adler>>8&255),he(n,t.adler>>16&255),he(n,t.adler>>24&255),he(n,t.total_in&255),he(n,t.total_in>>8&255),he(n,t.total_in>>16&255),he(n,t.total_in>>24&255)):(Un(n,t.adler>>>16),Un(n,t.adler&65535)),Xt(t),n.wrap>0&&(n.wrap=-n.wrap),n.pending!==0?Ct:Tl)}function xh(t){var e;return!t||!t.state?st:(e=t.state.status,e!==si&&e!==ha&&e!==ni&&e!==oi&&e!==ii&&e!==br&&e!==Vn?Jt(t,st):(t.state=null,e===br?Jt(t,Xd):Ct))}function Fh(t,e){var r=e.length,n,o,i,a,s,f,l,c;if(!t||!t.state||(n=t.state,a=n.wrap,a===2||a===1&&n.status!==si||n.lookahead))return st;for(a===1&&(t.adler=Al(t.adler,e,r,0)),n.wrap=0,r>=n.w_size&&(a===0&&(Zt(n.head),n.strstart=0,n.block_start=0,n.insert=0),c=new Xe.Buf8(n.w_size),Xe.arraySet(c,e,r-n.w_size,n.w_size,0),e=c,r=n.w_size),s=t.avail_in,f=t.next_in,l=t.input,t.avail_in=r,t.next_in=0,t.input=e,Fr(n);n.lookahead>=de;){o=n.strstart,i=n.lookahead-(de-1);do n.ins_h=(n.ins_h<{"use strict";var li=It(),Il=!0,zl=!0;try{String.fromCharCode.apply(null,[0])}catch{Il=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch{zl=!1}var Wn=new li.Buf8(256);for(jt=0;jt<256;jt++)Wn[jt]=jt>=252?6:jt>=248?5:jt>=240?4:jt>=224?3:jt>=192?2:1;var jt;Wn[254]=Wn[254]=1;Qr.string2buf=function(t){var e,r,n,o,i,a=t.length,s=0;for(o=0;o>>6,e[i++]=128|r&63):r<65536?(e[i++]=224|r>>>12,e[i++]=128|r>>>6&63,e[i++]=128|r&63):(e[i++]=240|r>>>18,e[i++]=128|r>>>12&63,e[i++]=128|r>>>6&63,e[i++]=128|r&63);return e};function jl(t,e){if(e<65534&&(t.subarray&&zl||!t.subarray&&Il))return String.fromCharCode.apply(null,li.shrinkBuf(t,e));for(var r="",n=0;n4){s[n++]=65533,r+=i-1;continue}for(o&=i===2?31:i===3?15:7;i>1&&r1){s[n++]=65533;continue}o<65536?s[n++]=o:(o-=65536,s[n++]=55296|o>>10&1023,s[n++]=56320|o&1023)}return jl(s,n)};Qr.utf8border=function(t,e){var r;for(e=e||t.length,e>t.length&&(e=t.length),r=e-1;r>=0&&(t[r]&192)===128;)r--;return r<0||r===0?e:r+Wn[t[r]]>e?r:e}});var va=He((ng,Ll)=>{"use strict";function wh(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}Ll.exports=wh});var ql=He(Xn=>{"use strict";var Gn=Ml(),Kn=It(),ga=pa(),ya=ti(),Sh=va(),Vl=Object.prototype.toString,Ph=0,ma=4,_r=0,Hl=1,Ul=2,Dh=-1,Ch=0,kh=8;function Sr(t){if(!(this instanceof Sr))return new Sr(t);this.options=Kn.assign({level:Dh,method:kh,chunkSize:16384,windowBits:15,memLevel:8,strategy:Ch,to:""},t||{});var e=this.options;e.raw&&e.windowBits>0?e.windowBits=-e.windowBits:e.gzip&&e.windowBits>0&&e.windowBits<16&&(e.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new Sh,this.strm.avail_out=0;var r=Gn.deflateInit2(this.strm,e.level,e.method,e.windowBits,e.memLevel,e.strategy);if(r!==_r)throw new Error(ya[r]);if(e.header&&Gn.deflateSetHeader(this.strm,e.header),e.dictionary){var n;if(typeof e.dictionary=="string"?n=ga.string2buf(e.dictionary):Vl.call(e.dictionary)==="[object ArrayBuffer]"?n=new Uint8Array(e.dictionary):n=e.dictionary,r=Gn.deflateSetDictionary(this.strm,n),r!==_r)throw new Error(ya[r]);this._dict_set=!0}}Sr.prototype.push=function(t,e){var r=this.strm,n=this.options.chunkSize,o,i;if(this.ended)return!1;i=e===~~e?e:e===!0?ma:Ph,typeof t=="string"?r.input=ga.string2buf(t):Vl.call(t)==="[object ArrayBuffer]"?r.input=new Uint8Array(t):r.input=t,r.next_in=0,r.avail_in=r.input.length;do{if(r.avail_out===0&&(r.output=new Kn.Buf8(n),r.next_out=0,r.avail_out=n),o=Gn.deflate(r,i),o!==Hl&&o!==_r)return this.onEnd(o),this.ended=!0,!1;(r.avail_out===0||r.avail_in===0&&(i===ma||i===Ul))&&(this.options.to==="string"?this.onData(ga.buf2binstring(Kn.shrinkBuf(r.output,r.next_out))):this.onData(Kn.shrinkBuf(r.output,r.next_out)))}while((r.avail_in>0||r.avail_out===0)&&o!==Hl);return i===ma?(o=Gn.deflateEnd(this.strm),this.onEnd(o),this.ended=!0,o===_r):(i===Ul&&(this.onEnd(_r),r.avail_out=0),!0)};Sr.prototype.onData=function(t){this.chunks.push(t)};Sr.prototype.onEnd=function(t){t===_r&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=Kn.flattenChunks(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg};function ba(t,e){var r=new Sr(e);if(r.push(t,!0),r.err)throw r.msg||ya[r.err];return r.result}function Th(t,e){return e=e||{},e.raw=!0,ba(t,e)}function Eh(t,e){return e=e||{},e.gzip=!0,ba(t,e)}Xn.Deflate=Sr;Xn.deflate=ba;Xn.deflateRaw=Th;Xn.gzip=Eh});var Gl=He((ig,Wl)=>{"use strict";var fi=30,Ah=12;Wl.exports=function(e,r){var n,o,i,a,s,f,l,c,u,d,p,h,b,F,x,m,y,w,S,D,T,C,E,I,A;n=e.state,o=e.next_in,I=e.input,i=o+(e.avail_in-5),a=e.next_out,A=e.output,s=a-(r-e.avail_out),f=a+(e.avail_out-257),l=n.dmax,c=n.wsize,u=n.whave,d=n.wnext,p=n.window,h=n.hold,b=n.bits,F=n.lencode,x=n.distcode,m=(1<>>24,h>>>=S,b-=S,S=w>>>16&255,S===0)A[a++]=w&65535;else if(S&16){D=w&65535,S&=15,S&&(b>>=S,b-=S),b<15&&(h+=I[o++]<>>24,h>>>=S,b-=S,S=w>>>16&255,S&16){if(T=w&65535,S&=15,bl){e.msg="invalid distance too far back",n.mode=fi;break e}if(h>>>=S,b-=S,S=a-s,T>S){if(S=T-S,S>u&&n.sane){e.msg="invalid distance too far back",n.mode=fi;break e}if(C=0,E=p,d===0){if(C+=c-S,S2;)A[a++]=E[C++],A[a++]=E[C++],A[a++]=E[C++],D-=3;D&&(A[a++]=E[C++],D>1&&(A[a++]=E[C++]))}else{C=a-T;do A[a++]=A[C++],A[a++]=A[C++],A[a++]=A[C++],D-=3;while(D>2);D&&(A[a++]=A[C++],D>1&&(A[a++]=A[C++]))}}else if((S&64)===0){w=x[(w&65535)+(h&(1<>3,o-=D,b-=D<<3,h&=(1<{"use strict";var Kl=It(),$r=15,Xl=852,Zl=592,Yl=0,xa=1,Jl=2,Rh=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],Oh=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],Bh=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],Nh=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];Ql.exports=function(e,r,n,o,i,a,s,f){var l=f.bits,c=0,u=0,d=0,p=0,h=0,b=0,F=0,x=0,m=0,y=0,w,S,D,T,C,E=null,I=0,A,R=new Kl.Buf16($r+1),z=new Kl.Buf16($r+1),M=null,X=0,te,L,ue;for(c=0;c<=$r;c++)R[c]=0;for(u=0;u=1&&R[p]===0;p--);if(h>p&&(h=p),p===0)return i[a++]=1<<24|64<<16|0,i[a++]=1<<24|64<<16|0,f.bits=1,0;for(d=1;d0&&(e===Yl||p!==1))return-1;for(z[1]=0,c=1;c<$r;c++)z[c+1]=z[c]+R[c];for(u=0;uXl||e===Jl&&m>Zl)return 1;for(;;){te=c-F,s[u]A?(L=M[X+s[u]],ue=E[I+s[u]]):(L=96,ue=0),w=1<>F)+S]=te<<24|L<<16|ue|0;while(S!==0);for(w=1<>=1;if(w!==0?(y&=w-1,y+=w):y=0,u++,--R[c]===0){if(c===p)break;c=r[n+s[u]]}if(c>h&&(y&T)!==D){for(F===0&&(F=h),C+=d,b=c-F,x=1<Xl||e===Jl&&m>Zl)return 1;D=y&T,i[D]=h<<24|b<<16|C-a|0}}return y!==0&&(i[C+y]=c-F<<24|64<<16|0),f.bits=h,0}});var Nf=He(gt=>{"use strict";var nt=It(),Ca=la(),Tt=fa(),Mh=Gl(),Zn=_l(),Ih=0,Df=1,Cf=2,$l=4,zh=5,ci=6,Pr=0,jh=1,Lh=2,lt=-2,kf=-3,ka=-4,Hh=-5,ef=8,Tf=1,tf=2,rf=3,nf=4,of=5,af=6,sf=7,lf=8,ff=9,cf=10,hi=11,Lt=12,Fa=13,uf=14,wa=15,df=16,hf=17,pf=18,vf=19,ui=20,di=21,mf=22,gf=23,yf=24,bf=25,xf=26,Sa=27,Ff=28,wf=29,be=30,Ta=31,Uh=32,Vh=852,qh=592,Wh=15,Gh=Wh;function Sf(t){return(t>>>24&255)+(t>>>8&65280)+((t&65280)<<8)+((t&255)<<24)}function Kh(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new nt.Buf16(320),this.work=new nt.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function Ef(t){var e;return!t||!t.state?lt:(e=t.state,t.total_in=t.total_out=e.total=0,t.msg="",e.wrap&&(t.adler=e.wrap&1),e.mode=Tf,e.last=0,e.havedict=0,e.dmax=32768,e.head=null,e.hold=0,e.bits=0,e.lencode=e.lendyn=new nt.Buf32(Vh),e.distcode=e.distdyn=new nt.Buf32(qh),e.sane=1,e.back=-1,Pr)}function Af(t){var e;return!t||!t.state?lt:(e=t.state,e.wsize=0,e.whave=0,e.wnext=0,Ef(t))}function Rf(t,e){var r,n;return!t||!t.state||(n=t.state,e<0?(r=0,e=-e):(r=(e>>4)+1,e<48&&(e&=15)),e&&(e<8||e>15))?lt:(n.window!==null&&n.wbits!==e&&(n.window=null),n.wrap=r,n.wbits=e,Af(t))}function Of(t,e){var r,n;return t?(n=new Kh,t.state=n,n.window=null,r=Rf(t,e),r!==Pr&&(t.state=null),r):lt}function Xh(t){return Of(t,Gh)}var Pf=!0,Pa,Da;function Zh(t){if(Pf){var e;for(Pa=new nt.Buf32(512),Da=new nt.Buf32(32),e=0;e<144;)t.lens[e++]=8;for(;e<256;)t.lens[e++]=9;for(;e<280;)t.lens[e++]=7;for(;e<288;)t.lens[e++]=8;for(Zn(Df,t.lens,0,288,Pa,0,t.work,{bits:9}),e=0;e<32;)t.lens[e++]=5;Zn(Cf,t.lens,0,32,Da,0,t.work,{bits:5}),Pf=!1}t.lencode=Pa,t.lenbits=9,t.distcode=Da,t.distbits=5}function Bf(t,e,r,n){var o,i=t.state;return i.window===null&&(i.wsize=1<=i.wsize?(nt.arraySet(i.window,e,r-i.wsize,i.wsize,0),i.wnext=0,i.whave=i.wsize):(o=i.wsize-i.wnext,o>n&&(o=n),nt.arraySet(i.window,e,r-n,o,i.wnext),n-=o,n?(nt.arraySet(i.window,e,r-n,n,0),i.wnext=n,i.whave=i.wsize):(i.wnext+=o,i.wnext===i.wsize&&(i.wnext=0),i.whave>>8&255,r.check=Tt(r.check,E,2,0),l=0,c=0,r.mode=tf;break}if(r.flags=0,r.head&&(r.head.done=!1),!(r.wrap&1)||(((l&255)<<8)+(l>>8))%31){t.msg="incorrect header check",r.mode=be;break}if((l&15)!==ef){t.msg="unknown compression method",r.mode=be;break}if(l>>>=4,c-=4,T=(l&15)+8,r.wbits===0)r.wbits=T;else if(T>r.wbits){t.msg="invalid window size",r.mode=be;break}r.dmax=1<>8&1),r.flags&512&&(E[0]=l&255,E[1]=l>>>8&255,r.check=Tt(r.check,E,2,0)),l=0,c=0,r.mode=rf;case rf:for(;c<32;){if(s===0)break e;s--,l+=n[i++]<>>8&255,E[2]=l>>>16&255,E[3]=l>>>24&255,r.check=Tt(r.check,E,4,0)),l=0,c=0,r.mode=nf;case nf:for(;c<16;){if(s===0)break e;s--,l+=n[i++]<>8),r.flags&512&&(E[0]=l&255,E[1]=l>>>8&255,r.check=Tt(r.check,E,2,0)),l=0,c=0,r.mode=of;case of:if(r.flags&1024){for(;c<16;){if(s===0)break e;s--,l+=n[i++]<>>8&255,r.check=Tt(r.check,E,2,0)),l=0,c=0}else r.head&&(r.head.extra=null);r.mode=af;case af:if(r.flags&1024&&(p=r.length,p>s&&(p=s),p&&(r.head&&(T=r.head.extra_len-r.length,r.head.extra||(r.head.extra=new Array(r.head.extra_len)),nt.arraySet(r.head.extra,n,i,p,T)),r.flags&512&&(r.check=Tt(r.check,n,p,i)),s-=p,i+=p,r.length-=p),r.length))break e;r.length=0,r.mode=sf;case sf:if(r.flags&2048){if(s===0)break e;p=0;do T=n[i+p++],r.head&&T&&r.length<65536&&(r.head.name+=String.fromCharCode(T));while(T&&p>9&1,r.head.done=!0),t.adler=r.check=0,r.mode=Lt;break;case cf:for(;c<32;){if(s===0)break e;s--,l+=n[i++]<>>=c&7,c-=c&7,r.mode=Sa;break}for(;c<3;){if(s===0)break e;s--,l+=n[i++]<>>=1,c-=1,l&3){case 0:r.mode=uf;break;case 1:if(Zh(r),r.mode=ui,e===ci){l>>>=2,c-=2;break e}break;case 2:r.mode=hf;break;case 3:t.msg="invalid block type",r.mode=be}l>>>=2,c-=2;break;case uf:for(l>>>=c&7,c-=c&7;c<32;){if(s===0)break e;s--,l+=n[i++]<>>16^65535)){t.msg="invalid stored block lengths",r.mode=be;break}if(r.length=l&65535,l=0,c=0,r.mode=wa,e===ci)break e;case wa:r.mode=df;case df:if(p=r.length,p){if(p>s&&(p=s),p>f&&(p=f),p===0)break e;nt.arraySet(o,n,i,p,a),s-=p,i+=p,f-=p,a+=p,r.length-=p;break}r.mode=Lt;break;case hf:for(;c<14;){if(s===0)break e;s--,l+=n[i++]<>>=5,c-=5,r.ndist=(l&31)+1,l>>>=5,c-=5,r.ncode=(l&15)+4,l>>>=4,c-=4,r.nlen>286||r.ndist>30){t.msg="too many length or distance symbols",r.mode=be;break}r.have=0,r.mode=pf;case pf:for(;r.have>>=3,c-=3}for(;r.have<19;)r.lens[R[r.have++]]=0;if(r.lencode=r.lendyn,r.lenbits=7,I={bits:r.lenbits},C=Zn(Ih,r.lens,0,19,r.lencode,0,r.work,I),r.lenbits=I.bits,C){t.msg="invalid code lengths set",r.mode=be;break}r.have=0,r.mode=vf;case vf:for(;r.have>>24,m=F>>>16&255,y=F&65535,!(x<=c);){if(s===0)break e;s--,l+=n[i++]<>>=x,c-=x,r.lens[r.have++]=y;else{if(y===16){for(A=x+2;c>>=x,c-=x,r.have===0){t.msg="invalid bit length repeat",r.mode=be;break}T=r.lens[r.have-1],p=3+(l&3),l>>>=2,c-=2}else if(y===17){for(A=x+3;c>>=x,c-=x,T=0,p=3+(l&7),l>>>=3,c-=3}else{for(A=x+7;c>>=x,c-=x,T=0,p=11+(l&127),l>>>=7,c-=7}if(r.have+p>r.nlen+r.ndist){t.msg="invalid bit length repeat",r.mode=be;break}for(;p--;)r.lens[r.have++]=T}}if(r.mode===be)break;if(r.lens[256]===0){t.msg="invalid code -- missing end-of-block",r.mode=be;break}if(r.lenbits=9,I={bits:r.lenbits},C=Zn(Df,r.lens,0,r.nlen,r.lencode,0,r.work,I),r.lenbits=I.bits,C){t.msg="invalid literal/lengths set",r.mode=be;break}if(r.distbits=6,r.distcode=r.distdyn,I={bits:r.distbits},C=Zn(Cf,r.lens,r.nlen,r.ndist,r.distcode,0,r.work,I),r.distbits=I.bits,C){t.msg="invalid distances set",r.mode=be;break}if(r.mode=ui,e===ci)break e;case ui:r.mode=di;case di:if(s>=6&&f>=258){t.next_out=a,t.avail_out=f,t.next_in=i,t.avail_in=s,r.hold=l,r.bits=c,Mh(t,d),a=t.next_out,o=t.output,f=t.avail_out,i=t.next_in,n=t.input,s=t.avail_in,l=r.hold,c=r.bits,r.mode===Lt&&(r.back=-1);break}for(r.back=0;F=r.lencode[l&(1<>>24,m=F>>>16&255,y=F&65535,!(x<=c);){if(s===0)break e;s--,l+=n[i++]<>w)],x=F>>>24,m=F>>>16&255,y=F&65535,!(w+x<=c);){if(s===0)break e;s--,l+=n[i++]<>>=w,c-=w,r.back+=w}if(l>>>=x,c-=x,r.back+=x,r.length=y,m===0){r.mode=xf;break}if(m&32){r.back=-1,r.mode=Lt;break}if(m&64){t.msg="invalid literal/length code",r.mode=be;break}r.extra=m&15,r.mode=mf;case mf:if(r.extra){for(A=r.extra;c>>=r.extra,c-=r.extra,r.back+=r.extra}r.was=r.length,r.mode=gf;case gf:for(;F=r.distcode[l&(1<>>24,m=F>>>16&255,y=F&65535,!(x<=c);){if(s===0)break e;s--,l+=n[i++]<>w)],x=F>>>24,m=F>>>16&255,y=F&65535,!(w+x<=c);){if(s===0)break e;s--,l+=n[i++]<>>=w,c-=w,r.back+=w}if(l>>>=x,c-=x,r.back+=x,m&64){t.msg="invalid distance code",r.mode=be;break}r.offset=y,r.extra=m&15,r.mode=yf;case yf:if(r.extra){for(A=r.extra;c>>=r.extra,c-=r.extra,r.back+=r.extra}if(r.offset>r.dmax){t.msg="invalid distance too far back",r.mode=be;break}r.mode=bf;case bf:if(f===0)break e;if(p=d-f,r.offset>p){if(p=r.offset-p,p>r.whave&&r.sane){t.msg="invalid distance too far back",r.mode=be;break}p>r.wnext?(p-=r.wnext,h=r.wsize-p):h=r.wnext-p,p>r.length&&(p=r.length),b=r.window}else b=o,h=a-r.offset,p=r.length;p>f&&(p=f),f-=p,r.length-=p;do o[a++]=b[h++];while(--p);r.length===0&&(r.mode=di);break;case xf:if(f===0)break e;o[a++]=r.length,f--,r.mode=di;break;case Sa:if(r.wrap){for(;c<32;){if(s===0)break e;s--,l|=n[i++]<{"use strict";Mf.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}});var zf=He((fg,If)=>{"use strict";function $h(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}If.exports=$h});var Lf=He(Jn=>{"use strict";var en=Nf(),Yn=It(),pi=pa(),ke=Ea(),Aa=ti(),ep=va(),tp=zf(),jf=Object.prototype.toString;function Dr(t){if(!(this instanceof Dr))return new Dr(t);this.options=Yn.assign({chunkSize:16384,windowBits:0,to:""},t||{});var e=this.options;e.raw&&e.windowBits>=0&&e.windowBits<16&&(e.windowBits=-e.windowBits,e.windowBits===0&&(e.windowBits=-15)),e.windowBits>=0&&e.windowBits<16&&!(t&&t.windowBits)&&(e.windowBits+=32),e.windowBits>15&&e.windowBits<48&&(e.windowBits&15)===0&&(e.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new ep,this.strm.avail_out=0;var r=en.inflateInit2(this.strm,e.windowBits);if(r!==ke.Z_OK)throw new Error(Aa[r]);if(this.header=new tp,en.inflateGetHeader(this.strm,this.header),e.dictionary&&(typeof e.dictionary=="string"?e.dictionary=pi.string2buf(e.dictionary):jf.call(e.dictionary)==="[object ArrayBuffer]"&&(e.dictionary=new Uint8Array(e.dictionary)),e.raw&&(r=en.inflateSetDictionary(this.strm,e.dictionary),r!==ke.Z_OK)))throw new Error(Aa[r])}Dr.prototype.push=function(t,e){var r=this.strm,n=this.options.chunkSize,o=this.options.dictionary,i,a,s,f,l,c=!1;if(this.ended)return!1;a=e===~~e?e:e===!0?ke.Z_FINISH:ke.Z_NO_FLUSH,typeof t=="string"?r.input=pi.binstring2buf(t):jf.call(t)==="[object ArrayBuffer]"?r.input=new Uint8Array(t):r.input=t,r.next_in=0,r.avail_in=r.input.length;do{if(r.avail_out===0&&(r.output=new Yn.Buf8(n),r.next_out=0,r.avail_out=n),i=en.inflate(r,ke.Z_NO_FLUSH),i===ke.Z_NEED_DICT&&o&&(i=en.inflateSetDictionary(this.strm,o)),i===ke.Z_BUF_ERROR&&c===!0&&(i=ke.Z_OK,c=!1),i!==ke.Z_STREAM_END&&i!==ke.Z_OK)return this.onEnd(i),this.ended=!0,!1;r.next_out&&(r.avail_out===0||i===ke.Z_STREAM_END||r.avail_in===0&&(a===ke.Z_FINISH||a===ke.Z_SYNC_FLUSH))&&(this.options.to==="string"?(s=pi.utf8border(r.output,r.next_out),f=r.next_out-s,l=pi.buf2string(r.output,s),r.next_out=f,r.avail_out=n-f,f&&Yn.arraySet(r.output,r.output,s,f,0),this.onData(l)):this.onData(Yn.shrinkBuf(r.output,r.next_out))),r.avail_in===0&&r.avail_out===0&&(c=!0)}while((r.avail_in>0||r.avail_out===0)&&i!==ke.Z_STREAM_END);return i===ke.Z_STREAM_END&&(a=ke.Z_FINISH),a===ke.Z_FINISH?(i=en.inflateEnd(this.strm),this.onEnd(i),this.ended=!0,i===ke.Z_OK):(a===ke.Z_SYNC_FLUSH&&(this.onEnd(ke.Z_OK),r.avail_out=0),!0)};Dr.prototype.onData=function(t){this.chunks.push(t)};Dr.prototype.onEnd=function(t){t===ke.Z_OK&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=Yn.flattenChunks(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg};function Ra(t,e){var r=new Dr(e);if(r.push(t,!0),r.err)throw r.msg||Aa[r.err];return r.result}function rp(t,e){return e=e||{},e.raw=!0,Ra(t,e)}Jn.Inflate=Dr;Jn.inflate=Ra;Jn.inflateRaw=rp;Jn.ungzip=Ra});var Qn=He((ug,Uf)=>{"use strict";var np=It().assign,op=ql(),ip=Lf(),ap=Ea(),Hf={};np(Hf,op,ip,ap);Uf.exports=Hf});var Im={};ad(Im,{default:()=>Wi});module.exports=sd(Im);var N=require("obsidian");var Xi=function(t,e){return Xi=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,n){r.__proto__=n}||function(r,n){for(var o in n)n.hasOwnProperty(o)&&(r[o]=n[o])},Xi(t,e)};function k(t,e){Xi(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}var Y=function(){return Y=Object.assign||function(e){for(var r,n=1,o=arguments.length;n0&&i[i.length-1])&&(l[0]===6||l[0]===2)){r=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]>2],e+=Vr[(t[n]&3)<<4|t[n+1]>>4],e+=Vr[(t[n+1]&15)<<2|t[n+2]>>6],e+=Vr[t[n+2]&63];return r%3===2?e=e.substring(0,e.length-1)+"=":r%3===1&&(e=e.substring(0,e.length-2)+"=="),e},Rs=function(t){var e=t.length*.75,r=t.length,n,o=0,i,a,s,f;t[t.length-1]==="="&&(e--,t[t.length-2]==="="&&e--);var l=new Uint8Array(e);for(n=0;n>4,l[o++]=(a&15)<<4|s>>2,l[o++]=(s&3)<<6|f&63;return l},ld=/^(data)?:?([\w\/\+]+)?;?(charset=[\w-]+|base64)?.*,/i,Bs=function(t){var e=t.trim(),r=e.substring(0,100),n=r.match(ld);if(!n)return Rs(e);var o=n[0],i=e.substring(o.length);return Rs(i)};var Q=function(t){return t.charCodeAt(0)},Ns=function(t){return t.codePointAt(0)},Mt=function(t,e){return rt(t.toString(16),e,"0").toUpperCase()},Wt=function(t){return Mt(t,2)},tt=function(t){return String.fromCharCode(t)},Ms=function(t){return tt(parseInt(t,16))},rt=function(t,e,r){for(var n="",o=0,i=e-t.length;o=55296&&r<=56319&&t.length>o&&(n=t.charCodeAt(o),n>=56320&&n<=57343&&(i=2)),[t.slice(e,e+i),i]},zs=function(t){for(var e=[],r=0,n=t.length;rr&&l(),a+=d,s+=p}}return l(),f},dd=/^D:(\d\d\d\d)(\d\d)?(\d\d)?(\d\d)?(\d\d)?(\d\d)?([+\-Z])?(\d\d)?'?(\d\d)?'?$/,Zo=function(t){var e=t.match(dd);if(e){var r=e[1],n=e[2],o=n===void 0?"01":n,i=e[3],a=i===void 0?"01":i,s=e[4],f=s===void 0?"00":s,l=e[5],c=l===void 0?"00":l,u=e[6],d=u===void 0?"00":u,p=e[7],h=p===void 0?"Z":p,b=e[8],F=b===void 0?"00":b,x=e[9],m=x===void 0?"00":x,y=h==="Z"?"Z":""+h+F+":"+m,w=new Date(r+"-"+o+"-"+a+"T"+f+":"+c+":"+d+y);return w}},On=function(t,e){for(var r,n=0,o;n=0&&t<=65535},Qs=function(t){return t>=65536&&t<=1114111},Ji=function(t){return Math.floor((t-65536)/1024)+55296},Qi=function(t){return(t-65536)%1024+56320},Gt;(function(t){t.BigEndian="BigEndian",t.LittleEndian="LittleEndian"})(Gt||(Gt={}));var Bn="\uFFFD".codePointAt(0),Qo=function(t,e){if(e===void 0&&(e=!0),t.length<=1)return String.fromCodePoint(Bn);for(var r=e?pd(t):Gt.BigEndian,n=e?2:0,o=[];t.length-n>=2;){var i=Zs(t[n++],t[n++],r);if(hd(i))if(t.length-n<2)o.push(Bn);else{var a=Zs(t[n++],t[n++],r);Xs(a)?o.push(i,a):o.push(Bn)}else Xs(i)?(n+=2,o.push(Bn)):o.push(i)}return n=55296&&t<=56319},Xs=function(t){return t>=56320&&t<=57343},Zs=function(t,e,r){if(r===Gt.LittleEndian)return e<<8|t;if(r===Gt.BigEndian)return t<<8|e;throw new Error("Invalid byteOrder: "+r)},pd=function(t){return _s(t)?Gt.BigEndian:$s(t)?Gt.LittleEndian:Gt.BigEndian},_s=function(t){return t[0]===254&&t[1]===255},$s=function(t){return t[0]===255&&t[1]===254},_o=function(t){return _s(t)||$s(t)};var el=function(t){var e=String(t);if(Math.abs(t)<1){var r=parseInt(t.toString().split("e-")[1]);if(r){var n=t<0;n&&(t*=-1),t*=Math.pow(10,r-1),e="0."+new Array(r).join("0")+t.toString().substring(2),n&&(e="-"+e)}}else{var r=parseInt(t.toString().split("+")[1]);r>20&&(r-=20,t/=Math.pow(10,r),e=t.toString()+new Array(r+1).join("0"))}return e},Nn=function(t){return Math.ceil(t.toString(2).length/8)},mr=function(t){for(var e=new Uint8Array(Nn(t)),r=1;r<=e.length;r++)e[r-1]=t>>(e.length-r)*8;return e};var gr=function(t){throw new Error(t)};var qf=Ko(Qn()),Vf="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",$n=new Uint8Array(256);for(_n=0;_n>4,l[o++]=(a&15)<<4|s>>2,l[o++]=(s&3)<<6|f&63;return l},lp=function(t){for(var e="",r=0;rn)throw new Error(Me(e)+" must be at least "+r+" and at most "+n+", but was actually "+t)},ot=function(t,e,r,n){P(t,e,["number","undefined"]),typeof t=="number"&&Ue(t,e,r,n)},gi=function(t,e,r){if(P(t,e,["number"]),t%r!==0)throw new Error(Me(e)+" must be a multiple of "+r+", but was actually "+t)},cc=function(t,e){if(!Number.isInteger(t))throw new Error(Me(e)+" must be an integer, but was actually "+t)},_t=function(t,e){if(![1,0].includes(Math.sign(t)))throw new Error(Me(e)+" must be a positive number or 0, but was actually "+t)};var $=new Uint16Array(256);for(no=0;no<256;no++)$[no]=no;var no;$[22]=Q("");$[24]=Q("\u02D8");$[25]=Q("\u02C7");$[26]=Q("\u02C6");$[27]=Q("\u02D9");$[28]=Q("\u02DD");$[29]=Q("\u02DB");$[30]=Q("\u02DA");$[31]=Q("\u02DC");$[127]=Q("\uFFFD");$[128]=Q("\u2022");$[129]=Q("\u2020");$[130]=Q("\u2021");$[131]=Q("\u2026");$[132]=Q("\u2014");$[133]=Q("\u2013");$[134]=Q("\u0192");$[135]=Q("\u2044");$[136]=Q("\u2039");$[137]=Q("\u203A");$[138]=Q("\u2212");$[139]=Q("\u2030");$[140]=Q("\u201E");$[141]=Q("\u201C");$[142]=Q("\u201D");$[143]=Q("\u2018");$[144]=Q("\u2019");$[145]=Q("\u201A");$[146]=Q("\u2122");$[147]=Q("\uFB01");$[148]=Q("\uFB02");$[149]=Q("\u0141");$[150]=Q("\u0152");$[151]=Q("\u0160");$[152]=Q("\u0178");$[153]=Q("\u017D");$[154]=Q("\u0131");$[155]=Q("\u0142");$[156]=Q("\u0153");$[157]=Q("\u0161");$[158]=Q("\u017E");$[159]=Q("\uFFFD");$[160]=Q("\u20AC");$[173]=Q("\uFFFD");var yi=function(t){for(var e=new Array(t.length),r=0,n=t.length;r=g.ExclamationPoint&&t<=g.Tilde&&!xi[t]},Tc={},Ec=new Map,Hp=function(t){k(e,t);function e(r,n){var o=this;if(r!==Tc)throw new tn("PDFName");o=t.call(this)||this;for(var i="/",a=0,s=n.length;a=g.Zero&&l<=g.Nine||l>=g.a&&l<=g.f||l>=g.A&&l<=g.F?(n+=f,(n.length===2||!(c>="0"&&c<="9"||c>="a"&&c<="f"||c>="A"&&c<="F"))&&(i(parseInt(n,16)),n="")):i(l):l===g.Hash?o=!0:i(l)}return new Uint8Array(r)},e.prototype.decodeText=function(){var r=this.asBytes();return String.fromCharCode.apply(String,Array.from(r))},e.prototype.asString=function(){return this.encodedName},e.prototype.value=function(){return this.encodedName},e.prototype.clone=function(){return this},e.prototype.toString=function(){return this.encodedName},e.prototype.sizeInBytes=function(){return this.encodedName.length},e.prototype.copyBytesInto=function(r,n){return n+=me(this.encodedName,r,n),this.encodedName.length},e.of=function(r){var n=jp(r),o=Ec.get(n);return o||(o=new e(Tc,n),Ec.set(n,o)),o},e.Length=e.of("Length"),e.FlateDecode=e.of("FlateDecode"),e.Resources=e.of("Resources"),e.Font=e.of("Font"),e.XObject=e.of("XObject"),e.ExtGState=e.of("ExtGState"),e.Contents=e.of("Contents"),e.Type=e.of("Type"),e.Parent=e.of("Parent"),e.MediaBox=e.of("MediaBox"),e.Page=e.of("Page"),e.Annots=e.of("Annots"),e.TrimBox=e.of("TrimBox"),e.ArtBox=e.of("ArtBox"),e.BleedBox=e.of("BleedBox"),e.CropBox=e.of("CropBox"),e.Rotate=e.of("Rotate"),e.Title=e.of("Title"),e.Author=e.of("Author"),e.Subject=e.of("Subject"),e.Creator=e.of("Creator"),e.Keywords=e.of("Keywords"),e.Producer=e.of("Producer"),e.CreationDate=e.of("CreationDate"),e.ModDate=e.of("ModDate"),e}(ve),v=Hp;var Up=function(t){k(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.asNull=function(){return null},e.prototype.clone=function(){return this},e.prototype.toString=function(){return"null"},e.prototype.sizeInBytes=function(){return 4},e.prototype.copyBytesInto=function(r,n){return r[n++]=g.n,r[n++]=g.u,r[n++]=g.l,r[n++]=g.l,4},e}(ve),Te=new Up;var Vp=function(t){k(e,t);function e(r,n){var o=t.call(this)||this;return o.dict=r,o.context=n,o}return e.prototype.keys=function(){return Array.from(this.dict.keys())},e.prototype.values=function(){return Array.from(this.dict.values())},e.prototype.entries=function(){return Array.from(this.dict.entries())},e.prototype.set=function(r,n){this.dict.set(r,n)},e.prototype.get=function(r,n){n===void 0&&(n=!1);var o=this.dict.get(r);if(!(o===Te&&!n))return o},e.prototype.has=function(r){var n=this.dict.get(r);return n!==void 0&&n!==Te},e.prototype.lookupMaybe=function(r){for(var n,o=[],i=1;ithis.largestObjectNumber&&(this.largestObjectNumber=e.objectNumber)},t.prototype.nextRef=function(){return this.largestObjectNumber+=1,J.of(this.largestObjectNumber)},t.prototype.register=function(e){var r=this.nextRef();return this.assign(r,e),r},t.prototype.delete=function(e){return this.indirectObjects.delete(e)},t.prototype.lookupMaybe=function(e){for(var r=[],n=1;n1?(this.subsections.push([e]),this.chunkIdx+=1,this.chunkLength=1):(r.push(e),this.chunkLength+=1)},t.create=function(){return new t({ref:J.of(0,65535),offset:0,deleted:!0})},t.createEmpty=function(){return new t},t}(),oo=$p;var e0=function(){function t(e){this.lastXRefOffset=String(e)}return t.prototype.toString=function(){return`startxref +`+this.lastXRefOffset+` +%%EOF`},t.prototype.sizeInBytes=function(){return 16+this.lastXRefOffset.length},t.prototype.copyBytesInto=function(e,r){var n=r;return e[r++]=g.s,e[r++]=g.t,e[r++]=g.a,e[r++]=g.r,e[r++]=g.t,e[r++]=g.x,e[r++]=g.r,e[r++]=g.e,e[r++]=g.f,e[r++]=g.Newline,r+=me(this.lastXRefOffset,e,r),e[r++]=g.Newline,e[r++]=g.Percent,e[r++]=g.Percent,e[r++]=g.E,e[r++]=g.O,e[r++]=g.F,r-n},t.forLastCrossRefSectionOffset=function(e){return new t(e)},t}(),Er=e0;var t0=function(){function t(e){this.dict=e}return t.prototype.toString=function(){return`trailer +`+this.dict.toString()},t.prototype.sizeInBytes=function(){return 8+this.dict.sizeInBytes()},t.prototype.copyBytesInto=function(e,r){var n=r;return e[r++]=g.t,e[r++]=g.r,e[r++]=g.a,e[r++]=g.i,e[r++]=g.l,e[r++]=g.e,e[r++]=g.r,e[r++]=g.Newline,r+=this.dict.copyBytesInto(e,r),r-n},t.of=function(e){return new t(e)},t}(),Ua=t0;var r0=function(t){k(e,t);function e(r,n,o){o===void 0&&(o=!0);var i=t.call(this,r.obj({}),o)||this;return i.objects=n,i.offsets=i.computeObjectOffsets(),i.offsetsString=i.computeOffsetsString(),i.dict.set(v.of("Type"),v.of("ObjStm")),i.dict.set(v.of("N"),j.of(i.objects.length)),i.dict.set(v.of("First"),j.of(i.offsetsString.length)),i}return e.prototype.getObjectsCount=function(){return this.objects.length},e.prototype.clone=function(r){return e.withContextAndObjects(r||this.dict.context,this.objects.slice(),this.encode)},e.prototype.getContentsString=function(){for(var r=this.offsetsString,n=0,o=this.objects.length;n1&&(a.push(s),a.push(c.ref.objectNumber),s=0),s+=1}return a.push(s),a},i.computeEntryTuples=function(){for(var a=new Array(i.entries.length),s=0,f=i.entries.length;ss[0]&&(s[0]=h),b>s[1]&&(s[1]=b),F>s[2]&&(s[2]=F)}return s},i.entries=n||[],i.entryTuplesCache=Ve.populatedBy(i.computeEntryTuples),i.maxByteWidthsCache=Ve.populatedBy(i.computeMaxEntryByteWidths),i.indexCache=Ve.populatedBy(i.computeIndex),r.set(v.of("Type"),v.of("XRef")),i}return e.prototype.addDeletedEntry=function(r,n){var o=er.Deleted;this.entries.push({type:o,ref:r,nextFreeObjectNumber:n}),this.entryTuplesCache.invalidate(),this.maxByteWidthsCache.invalidate(),this.indexCache.invalidate(),this.contentsCache.invalidate()},e.prototype.addUncompressedEntry=function(r,n){var o=er.Uncompressed;this.entries.push({type:o,ref:r,offset:n}),this.entryTuplesCache.invalidate(),this.maxByteWidthsCache.invalidate(),this.indexCache.invalidate(),this.contentsCache.invalidate()},e.prototype.addCompressedEntry=function(r,n,o){var i=er.Compressed;this.entries.push({type:i,ref:r,objectStreamRef:n,index:o}),this.entryTuplesCache.invalidate(),this.maxByteWidthsCache.invalidate(),this.indexCache.invalidate(),this.contentsCache.invalidate()},e.prototype.clone=function(r){var n=this,o=n.dict,i=n.entries,a=n.encode;return e.of(o.clone(r),i.slice(),a)},e.prototype.getContentsString=function(){for(var r=this.entryTuplesCache.access(),n=this.maxByteWidthsCache.access(),o="",i=0,a=r.length;i=0;h--)o+=(u[h]||0).toString(2);for(var h=n[1]-1;h>=0;h--)o+=(d[h]||0).toString(2);for(var h=n[2]-1;h>=0;h--)o+=(p[h]||0).toString(2)}return o},e.prototype.getUnencodedContents=function(){for(var r=this.entryTuplesCache.access(),n=this.maxByteWidthsCache.access(),o=new Uint8Array(this.getUnencodedContentsSize()),i=0,a=0,s=r.length;a=0;b--)o[i++]=d[b]||0;for(var b=n[1]-1;b>=0;b--)o[i++]=p[b]||0;for(var b=n[2]-1;b>=0;b--)o[i++]=h[b]||0}return o},e.prototype.getUnencodedContentsSize=function(){var r=this.maxByteWidthsCache.access(),n=qs(r);return n*this.entries.length},e.prototype.updateDict=function(){t.prototype.updateDict.call(this);var r=this.maxByteWidthsCache.access(),n=this.indexCache.access(),o=this.dict.context;this.dict.set(v.of("W"),o.obj(r)),this.dict.set(v.of("Index"),o.obj(n))},e.create=function(r,n){n===void 0&&(n=!0);var o=new e(r,[],n);return o.addDeletedEntry(J.of(0,65535),0),o},e.of=function(r,n,o){return o===void 0&&(o=!0),new e(r,n,o)},e}(Tr),Va=i0;var a0=function(t){k(e,t);function e(r,n,o,i){var a=t.call(this,r,n)||this;return a.encodeStreams=o,a.objectsPerStream=i,a}return e.prototype.computeBufferSize=function(){return V(this,void 0,void 0,function(){var r,n,o,i,a,s,f,l,h,b,c,x,u,d,F,p,h,b,F,x,m,y,w,S;return q(this,function(D){switch(D.label){case 0:r=this.context.largestObjectNumber+1,n=Ht.forVersion(1,7),o=n.sizeInBytes()+2,i=Va.create(this.createTrailerDict(),this.encodeStreams),a=[],s=[],f=[],l=this.context.enumerateIndirectObjects(),h=0,b=l.length,D.label=1;case 1:return h"},e.prototype.sizeInBytes=function(){return this.value.length+2},e.prototype.copyBytesInto=function(r,n){return r[n++]=g.LessThan,n+=me(this.value,r,n),r[n++]=g.GreaterThan,this.value.length+2},e.of=function(r){return new e(r)},e.fromText=function(r){for(var n=Ys(r),o="",i=0,a=n.length;i> def +/CMapName /Adobe-Identity-UCS def +/CMapType 2 def +1 begincodespacerange +<0000> +endcodespacerange +`+t.length+` beginbfchar +`+t.map(function(e){var r=e[0],n=e[1];return r+" "+n}).join(` +`)+` +endbfchar +endcmap +CMapName currentdict /CMap defineresource pop +end +end`},Mc=function(){for(var t=[],e=0;e"},wi=function(t){return Mt(t,4)},c0=function(t){if(Js(t))return wi(t);if(Qs(t)){var e=Ji(t),r=Qi(t);return""+wi(e)+wi(r)}var n=Wt(t),o="0x"+n+" is not a valid UTF-8 or UTF-16 codepoint.";throw new Error(o)};var u0=function(t){var e=0,r=function(n){e|=1<=g.Zero&&l<=g.Seven?(n+=f,(n.length===3||!(c>="0"&&c<="7"))&&(i(parseInt(n,8)),n="")):i(l):l===g.BackSlash?o=!0:i(l)}return new Uint8Array(r)},e.prototype.decodeText=function(){var r=this.asBytes();return _o(r)?Qo(r):yi(r)},e.prototype.decodeDate=function(){var r=this.decodeText(),n=Zo(r);if(!n)throw new bi(r);return n},e.prototype.asString=function(){return this.value},e.prototype.clone=function(){return e.of(this.value)},e.prototype.toString=function(){return"("+this.value+")"},e.prototype.sizeInBytes=function(){return this.value.length+2},e.prototype.copyBytesInto=function(r,n){return r[n++]=g.LeftParen,n+=me(this.value,r,n),r[n++]=g.RightParen,this.value.length+2},e.of=function(r){return new e(r)},e.fromDate=function(r){var n=rt(String(r.getUTCFullYear()),4,"0"),o=rt(String(r.getUTCMonth()+1),2,"0"),i=rt(String(r.getUTCDate()),2,"0"),a=rt(String(r.getUTCHours()),2,"0"),s=rt(String(r.getUTCMinutes()),2,"0"),f=rt(String(r.getUTCSeconds()),2,"0");return new e("D:"+n+o+i+a+s+f+"Z")},e}(ve),ne=d0;var h0=function(){function t(e,r,n,o){var i=this;this.allGlyphsInFontSortedById=function(){for(var a=new Array(i.font.characterSet.length),s=0,f=a.length;s>3)]>>7-((h&7)<<0)&1,R=3*A;s[w]=S[R],s[w+1]=S[R+1],s[w+2]=S[R+2],s[w+3]=A>2)]>>6-((h&3)<<1)&3,R=3*A;s[w]=S[R],s[w+1]=S[R+1],s[w+2]=S[R+2],s[w+3]=A>1)]>>4-((h&1)<<2)&15,R=3*A;s[w]=S[R],s[w+1]=S[R+1],s[w+2]=S[R+2],s[w+3]=A>>3)]>>>7-(L&7)&1),ue=M==x*255?0:255;f[te+L]=ue<<24|M<<16|M<<8|M}else if(c==2)for(var L=0;L>>2)]>>>6-((L&3)<<1)&3),ue=M==x*85?0:255;f[te+L]=ue<<24|M<<16|M<<8|M}else if(c==4)for(var L=0;L>>1)]>>>4-((L&1)<<2)&15),ue=M==x*17?0:255;f[te+L]=ue<<24|M<<16|M<<8|M}else if(c==8)for(var L=0;L>>2<<3));o==0;){if(o=F(e,d,1),i=F(e,d+1,2),d+=3,i==0){(d&7)!=0&&(d+=8-(d&7));var C=(d>>>3)+4,E=e[C-4]|e[C-3]<<8;T&&(r=t.H.W(r,u+E)),r.set(new n(e.buffer,e.byteOffset+C,E),u),d=C+E<<3,u+=E;continue}if(T&&(r=t.H.W(r,u+(1<<17))),i==1&&(p=D.J,h=D.h,l=511,c=31),i==2){a=x(e,d,5)+257,s=x(e,d+5,5)+1,f=x(e,d+10,4)+4,d+=14;for(var I=d,A=1,R=0;R<38;R+=2)D.Q[R]=0,D.Q[R+1]=0;for(var R=0;RA&&(A=z)}d+=3*f,y(D.Q,A),w(D.Q,A,D.u),p=D.w,h=D.d,d=m(D.u,(1<>>4;if(!(L>>>8))r[u++]=L;else{if(L==256)break;var ue=u+L-254;if(L>264){var ye=D.q[L-257];ue=u+(ye>>>3)+x(e,d,ye&7),d+=ye&7}var oe=h[S(e,d)&c];d+=oe&15;var Fe=oe>>>4,Ce=D.c[Fe],Be=(Ce>>>4)+F(e,d,Ce&15);for(d+=Ce&15;u>>4;if(u<=15)a[l]=u,l++;else{var d=0,p=0;u==16?(p=3+s(o,i,2),i+=2,d=a[l-1]):u==17?(p=3+s(o,i,3),i+=3):u==18&&(p=11+s(o,i,7),i+=7);for(var h=l+p;l>>1;ai&&(i=f),a++}for(;a>1,l=e[s+1],c=f<<4|l,u=r-l,d=e[s]<>>15-r;n[h]=c,d++}},t.H.l=function(e,r){for(var n=t.H.m.r,o=15-r,i=0;i>>o}},t.H.M=function(e,r,n){n=n<<(r&7);var o=r>>>3;e[o]|=n,e[o+1]|=n>>>8},t.H.I=function(e,r,n){n=n<<(r&7);var o=r>>>3;e[o]|=n,e[o+1]|=n>>>8,e[o+2]|=n>>>16},t.H.e=function(e,r,n){return(e[r>>>3]|e[(r>>>3)+1]<<8)>>>(r&7)&(1<>>3]|e[(r>>>3)+1]<<8|e[(r>>>3)+2]<<16)>>>(r&7)&(1<>>3]|e[(r>>>3)+1]<<8|e[(r>>>3)+2]<<16)>>>(r&7)},t.H.i=function(e,r){return(e[r>>>3]|e[(r>>>3)+1]<<8|e[(r>>>3)+2]<<16|e[(r>>>3)+3]<<24)>>>(r&7)},t.H.m=function(){var e=Uint16Array,r=Uint32Array;return{K:new e(16),j:new e(16),X:[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],S:[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,999,999,999],T:[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0],q:new e(32),p:[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,65535,65535],z:[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0],c:new r(32),J:new e(512),_:[],h:new e(32),$:[],w:new e(32768),C:[],v:[],d:new e(32768),D:[],u:new e(512),Q:[],r:new e(32768),s:new r(286),Y:new r(30),a:new r(19),t:new r(15e3),k:new e(65536),g:new e(32768)}}(),function(){for(var e=t.H.m,r=32768,n=0;n>>1|(o&1431655765)<<1,o=(o&3435973836)>>>2|(o&858993459)<<2,o=(o&4042322160)>>>4|(o&252645135)<<4,o=(o&4278255360)>>>8|(o&16711935)<<8,e.r[n]=(o>>>16|o<<16)>>>17}function i(a,s,f){for(;s--!=0;)a.push(0,f)}for(var n=0;n<32;n++)e.q[n]=e.S[n]<<3|e.T[n],e.c[n]=e.p[n]<<4|e.z[n];i(e._,144,8),i(e._,112,9),i(e._,24,7),i(e._,8,8),t.H.n(e._,9),t.H.A(e._,9,e.J),t.H.l(e._,9),i(e.$,32,5),t.H.n(e.$,5),t.H.A(e.$,5,e.h),t.H.l(e.$,5),i(e.Q,19,0),i(e.C,286,0),i(e.D,30,0),i(e.v,320,0)}(),t.H.N}();B.decode._readInterlace=function(t,e){for(var r=e.width,n=e.height,o=B.decode._getBPP(e),i=o>>3,a=Math.ceil(r*o/8),s=new Uint8Array(n*a),f=0,l=[0,0,4,0,2,0,1],c=[0,4,0,2,0,1,0],u=[8,8,8,4,4,2,2],d=[8,8,4,4,2,2,1],p=0;p<7;){for(var h=u[p],b=d[p],F=0,x=0,m=l[p];m>3];E=E>>7-(C&7)&1,s[D*a+(T>>3)]|=E<<7-((T&7)<<0)}if(o==2){var E=t[C>>3];E=E>>6-(C&7)&3,s[D*a+(T>>2)]|=E<<6-((T&3)<<1)}if(o==4){var E=t[C>>3];E=E>>4-(C&7)&15,s[D*a+(T>>1)]|=E<<4-((T&1)<<2)}if(o>=8)for(var I=D*a+T*i,A=0;A>3)+A];C+=o,T+=b}S++,D+=h}F*x!=0&&(f+=x*(1+w)),p=p+1}return s};B.decode._getBPP=function(t){var e=[1,null,3,1,2,null,4][t.ctype];return e*t.depth};B.decode._filterZero=function(t,e,r,n,o){var i=B.decode._getBPP(e),a=Math.ceil(n*i/8),s=B.decode._paeth;i=Math.ceil(i/8);var f=0,l=1,c=t[r],u=0;if(c>1&&(t[r]=[0,0,1][c-2]),c==3)for(u=i;u>>1)&255;for(var d=0;d>>1);for(;u>>1)}else{for(;u>8&255,t[e+1]=r&255},readUint:function(t,e){return t[e]*(256*256*256)+(t[e+1]<<16|t[e+2]<<8|t[e+3])},writeUint:function(t,e,r){t[e]=r>>24&255,t[e+1]=r>>16&255,t[e+2]=r>>8&255,t[e+3]=r&255},readASCII:function(t,e,r){for(var n="",o=0;o=0&&s>=0?(u=p*e+h<<2,d=(s+p)*o+a+h<<2):(u=(-s+p)*e-a+h<<2,d=p*o+h<<2),f==0)n[d]=t[u],n[d+1]=t[u+1],n[d+2]=t[u+2],n[d+3]=t[u+3];else if(f==1){var b=t[u+3]*.00392156862745098,F=t[u]*b,x=t[u+1]*b,m=t[u+2]*b,y=n[d+3]*(1/255),w=n[d]*y,S=n[d+1]*y,D=n[d+2]*y,T=1-b,C=b+y*T,E=C==0?0:1/C;n[d+3]=255*C,n[d+0]=(F+w*T)*E,n[d+1]=(x+S*T)*E,n[d+2]=(m+D*T)*E}else if(f==2){var b=t[u+3],F=t[u],x=t[u+1],m=t[u+2],y=n[d+3],w=n[d],S=n[d+1],D=n[d+2];b==y&&F==w&&x==S&&m==D?(n[d]=0,n[d+1]=0,n[d+2]=0,n[d+3]=0):(n[d]=F,n[d+1]=x,n[d+2]=m,n[d+3]=b)}else if(f==3){var b=t[u+3],F=t[u],x=t[u+1],m=t[u+2],y=n[d+3],w=n[d],S=n[d+1],D=n[d+2];if(b==y&&F==w&&x==S&&m==D)continue;if(b<220&&y>20)return!1}return!0};B.encode=function(t,e,r,n,o,i,a){n==null&&(n=0),a==null&&(a=!1);var s=B.encode.compress(t,e,r,n,[!1,!1,!1,0,a]);return B.encode.compressPNG(s,-1),B.encode._main(s,e,r,o,i)};B.encodeLL=function(t,e,r,n,o,i,a,s){for(var f={ctype:0+(n==1?0:2)+(o==0?0:4),depth:i,frames:[]},l=Date.now(),c=(n+o)*i,u=c*e,d=0;d1,u=!1,d=33+(c?20:0);if(o.sRGB!=null&&(d+=13),o.pHYs!=null&&(d+=21),t.ctype==3){for(var p=t.plte.length,h=0;h>>24!=255&&(u=!0);d+=8+p*3+4+(u?8+p*1+4:0)}for(var b=0;b>>8&255,T=w>>>16&255;x[l+y+0]=S,x[l+y+1]=D,x[l+y+2]=T}if(l+=p*3,a(x,l,i(x,l-p*3-4,p*3+4)),l+=4,u){a(x,l,p),l+=4,f(x,l,"tRNS"),l+=4;for(var h=0;h>>24&255;l+=p,a(x,l,i(x,l-p-4,p+4)),l+=4}}for(var C=0,b=0;b>2,R>>2));for(var p=0;pX&&L==M[F-X])te[F]=te[F-X];else{var ue=y[L];if(ue==null&&(y[L]=ue=w.length,w.push(L),w.length>=300))break;te[F]=ue}}}var ye=w.length;ye<=256&&l==!1&&(ye<=2?u=1:ye<=4?u=2:ye<=16?u=4:u=8,u=Math.max(u,f));for(var p=0;p>1)]|=Vo[Wo+we]<<4-(we&1)*4;else if(u==2)for(var we=0;we>2)]|=Vo[Wo+we]<<6-(we&3)*2;else if(u==1)for(var we=0;we>3)]|=Vo[Wo+we]<<7-(we&7)*1}Be=wt,c=3,Gi=1}else if(x==!1&&m.length==1){for(var wt=new Uint8Array(X*Ce*3),ed=X*Ce,F=0;FT&&(T=I),EC&&(C=E))}T==-1&&(S=D=T=C=0),o&&((S&1)==1&&S--,(D&1)==1&&D--);var R=(T-S+1)*(C-D+1);RF&&(F=w),Sx&&(x=S))}F==-1&&(h=b=F=x=0),a&&((h&1)==1&&h--,(b&1)==1&&b--),i={x:h,y:b,width:F-h+1,height:x-b+1};var C=n[o];C.rect=i,C.blend=1,C.img=new Uint8Array(i.width*i.height*4),n[o-1].dispose==0?(B._copyTile(l,e,r,C.img,i.width,i.height,-i.x,-i.y,0),B.encode._prepareDiff(d,e,r,C.img,i)):B._copyTile(d,e,r,C.img,i.width,i.height,-i.x,-i.y,0)};B.encode._prepareDiff=function(t,e,r,n,o){B._copyTile(t,e,r,n,o.width,o.height,-o.x,-o.y,2)};B.encode._filterZero=function(t,e,r,n,o,i,a){var s=[],f=[0,1,2,3,4];i!=-1?f=[i]:(e*n>5e5||r==1)&&(f=[0]);var l;a&&(l={level:0});for(var c=a&&UZIP!=null?UZIP:Lc.default,u=0;u>1)+256&255;if(i==4)for(var l=o;l>1)&255;for(var l=o;l>1)&255}if(i==4){for(var l=0;l>>1:r=r>>>1;t[e]=r}return t}(),update:function(t,e,r,n){for(var o=0;o>>8;return t},crc:function(t,e,r){return B.crc.update(4294967295,t,e,r)^4294967295}};B.quantize=function(t,e){for(var r=new Uint8Array(t),n=r.slice(0),o=new Uint32Array(n.buffer),i=B.quantize.getKDtree(n,e),a=i[0],s=i[1],f=B.quantize.planeDst,l=r,c=o,u=l.length,d=new Uint8Array(r.length>>2),p=0;p>2]=m.ind,c[p>>2]=m.est.rgba}return{abuf:n.buffer,inds:d,plte:s}};B.quantize.getKDtree=function(t,e,r){r==null&&(r=1e-4);var n=new Uint32Array(t.buffer),o={i0:0,i1:t.length,bst:null,est:null,tdst:0,left:null,right:null};o.bst=B.quantize.stats(t,o.i0,o.i1),o.est=B.quantize.estats(o.bst);for(var i=[o];i.lengtha&&(a=i[f].est.L,s=f);if(a=c||l.i1<=c;if(u){l.est.L=0;continue}var d={i0:l.i0,i1:c,bst:null,est:null,tdst:0,left:null,right:null};d.bst=B.quantize.stats(t,d.i0,d.i1),d.est=B.quantize.estats(d.bst);var p={i0:c,i1:l.i1,bst:null,est:null,tdst:0,left:null,right:null};p.bst={R:[],m:[],N:l.bst.N-d.bst.N};for(var f=0;f<16;f++)p.bst.R[f]=l.bst.R[f]-d.bst.R[f];for(var f=0;f<4;f++)p.bst.m[f]=l.bst.m[f]-d.bst.m[f];p.est=B.quantize.estats(p.bst),l.left=d,l.right=p,i[s]=d,i.push(p)}i.sort(function(h,b){return b.bst.N-h.bst.N});for(var f=0;f0&&(a=t.right,s=t.left);var f=B.quantize.getNearest(a,e,r,n,o);if(f.tdst<=i*i)return f;var l=B.quantize.getNearest(s,e,r,n,o);return l.tdsti;)n-=4;if(r>=n)break;var f=e[r>>2];e[r>>2]=e[n>>2],e[n>>2]=f,r+=4,n-=4}for(;a(t,r,o)>i;)r-=4;return r+4};B.quantize.vecDot=function(t,e,r){return t[e]*r[0]+t[e+1]*r[1]+t[e+2]*r[2]+t[e+3]*r[3]};B.quantize.stats=function(t,e,r){for(var n=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],o=[0,0,0,0],i=r-e>>2,a=e;a>>0}};B.M4={multVec:function(t,e){return[t[0]*e[0]+t[1]*e[1]+t[2]*e[2]+t[3]*e[3],t[4]*e[0]+t[5]*e[1]+t[6]*e[2]+t[7]*e[3],t[8]*e[0]+t[9]*e[1]+t[10]*e[2]+t[11]*e[3],t[12]*e[0]+t[13]*e[1]+t[14]*e[2]+t[15]*e[3]]},dot:function(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]+t[3]*e[3]},sml:function(t,e){return[t*e[0],t*e[1],t*e[2],t*e[3]]}};B.encode.concatRGBA=function(t){for(var e=0,r=0;r1)throw new Error("Animated PNGs are not supported");var o=new Uint8Array(n[0]),i=b0(o),a=i.rgbChannel,s=i.alphaChannel;this.rgbChannel=a;var f=s.some(function(l){return l<255});f&&(this.alphaChannel=s),this.type=y0(r.ctype),this.width=r.width,this.height=r.height,this.bitsPerComponent=8}return t.load=function(e){return new t(e)},t}();var x0=function(){function t(e){this.image=e,this.bitsPerComponent=e.bitsPerComponent,this.width=e.width,this.height=e.height,this.colorSpace="DeviceRGB"}return t.for=function(e){return V(this,void 0,void 0,function(){var r;return q(this,function(n){return r=Hc.load(e),[2,new t(r)]})})},t.prototype.embedIntoContext=function(e,r){return V(this,void 0,void 0,function(){var n,o;return q(this,function(i){return n=this.embedAlphaChannel(e),o=e.flateStream(this.image.rgbChannel,{Type:"XObject",Subtype:"Image",BitsPerComponent:this.image.bitsPerComponent,Width:this.image.width,Height:this.image.height,ColorSpace:this.colorSpace,SMask:n}),r?(e.assign(r,o),[2,r]):[2,e.register(o)]})})},t.prototype.embedAlphaChannel=function(e){if(this.image.alphaChannel){var r=e.flateStream(this.image.alphaChannel,{Type:"XObject",Subtype:"Image",Height:this.image.height,Width:this.image.width,BitsPerComponent:this.image.bitsPerComponent,ColorSpace:"DeviceGray",Decode:[0,1]});return e.register(r)}},t}(),co=x0;var F0=function(){function t(e,r,n){this.bytes=e,this.start=r||0,this.pos=this.start,this.end=r&&n?r+n:this.bytes.length}return Object.defineProperty(t.prototype,"length",{get:function(){return this.end-this.start},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"isEmpty",{get:function(){return this.length===0},enumerable:!1,configurable:!0}),t.prototype.getByte=function(){return this.pos>=this.end?-1:this.bytes[this.pos++]},t.prototype.getUint16=function(){var e=this.getByte(),r=this.getByte();return e===-1||r===-1?-1:(e<<8)+r},t.prototype.getInt32=function(){var e=this.getByte(),r=this.getByte(),n=this.getByte(),o=this.getByte();return(e<<24)+(r<<16)+(n<<8)+o},t.prototype.getBytes=function(e,r){r===void 0&&(r=!1);var n=this.bytes,o=this.pos,i=this.end;if(e){var s=o+e;s>i&&(s=i),this.pos=s;var a=n.subarray(o,s);return r?new Uint8ClampedArray(a):a}else{var a=n.subarray(o,i);return r?new Uint8ClampedArray(a):a}},t.prototype.peekByte=function(){var e=this.getByte();return this.pos--,e},t.prototype.peekBytes=function(e,r){r===void 0&&(r=!1);var n=this.getBytes(e,r);return this.pos-=n.length,n},t.prototype.skip=function(e){e||(e=1),this.pos+=e},t.prototype.reset=function(){this.pos=this.start},t.prototype.moveStart=function(){this.start=this.pos},t.prototype.makeSubStream=function(e,r){return new t(this.bytes,e,r)},t.prototype.decode=function(){return this.bytes},t}(),Si=F0;var w0=new Uint8Array(0),S0=function(){function t(e){if(this.pos=0,this.bufferLength=0,this.eof=!1,this.buffer=w0,this.minBufferLength=512,e)for(;this.minBufferLengthi&&(n=i)}else{for(;!this.eof;)this.readBlock();n=this.bufferLength}this.pos=n;var a=this.buffer.subarray(o,n);return r&&!(a instanceof Uint8ClampedArray)?new Uint8ClampedArray(a):a},t.prototype.peekByte=function(){var e=this.getByte();return this.pos--,e},t.prototype.peekBytes=function(e,r){r===void 0&&(r=!1);var n=this.getBytes(e,r);return this.pos-=n.length,n},t.prototype.skip=function(e){e||(e=1),this.pos+=e},t.prototype.reset=function(){this.pos=0},t.prototype.makeSubStream=function(e,r){for(var n=e+r;this.bufferLength<=n&&!this.eof;)this.readBlock();return new Si(this.buffer,e,r)},t.prototype.decode=function(){for(;!this.eof;)this.readBlock();return this.buffer.subarray(0,this.bufferLength)},t.prototype.readBlock=function(){throw new Le(this.constructor.name,"readBlock")},t.prototype.ensureBuffer=function(e){var r=this.buffer;if(e<=r.byteLength)return r;for(var n=this.minBufferLength;n=0;--l)f[s+l]=u&255,u>>=8}},e}(At),Vc=P0;var D0=function(t){k(e,t);function e(r,n){var o=t.call(this,n)||this;return o.stream=r,o.firstDigit=-1,n&&(n=.5*n),o}return e.prototype.readBlock=function(){var r=8e3,n=this.stream.getBytes(r);if(!n.length){this.eof=!0;return}for(var o=n.length+1>>1,i=this.ensureBuffer(this.bufferLength+o),a=this.bufferLength,s=this.firstDigit,f=0,l=n.length;f=48&&c<=57)u=c&15;else if(c>=65&&c<=70||c>=97&&c<=102)u=(c&15)+9;else if(c===62){this.eof=!0;break}else continue;s<0?s=u:(i[a++]=s<<4|u,s=-1)}s>=0&&this.eof&&(i[a++]=s<<4,s=-1),this.firstDigit=s,this.bufferLength=a},e}(At),qc=D0;var Wc=new Int32Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),C0=new Int32Array([3,4,5,6,7,8,9,10,65547,65549,65551,65553,131091,131095,131099,131103,196643,196651,196659,196667,262211,262227,262243,262259,327811,327843,327875,327907,258,258,258]),k0=new Int32Array([1,2,3,4,65541,65543,131081,131085,196625,196633,262177,262193,327745,327777,393345,393409,459009,459137,524801,525057,590849,591361,657409,658433,724993,727041,794625,798721,868353,876545]),T0=[new Int32Array([459008,524368,524304,524568,459024,524400,524336,590016,459016,524384,524320,589984,524288,524416,524352,590048,459012,524376,524312,589968,459028,524408,524344,590032,459020,524392,524328,59e4,524296,524424,524360,590064,459010,524372,524308,524572,459026,524404,524340,590024,459018,524388,524324,589992,524292,524420,524356,590056,459014,524380,524316,589976,459030,524412,524348,590040,459022,524396,524332,590008,524300,524428,524364,590072,459009,524370,524306,524570,459025,524402,524338,590020,459017,524386,524322,589988,524290,524418,524354,590052,459013,524378,524314,589972,459029,524410,524346,590036,459021,524394,524330,590004,524298,524426,524362,590068,459011,524374,524310,524574,459027,524406,524342,590028,459019,524390,524326,589996,524294,524422,524358,590060,459015,524382,524318,589980,459031,524414,524350,590044,459023,524398,524334,590012,524302,524430,524366,590076,459008,524369,524305,524569,459024,524401,524337,590018,459016,524385,524321,589986,524289,524417,524353,590050,459012,524377,524313,589970,459028,524409,524345,590034,459020,524393,524329,590002,524297,524425,524361,590066,459010,524373,524309,524573,459026,524405,524341,590026,459018,524389,524325,589994,524293,524421,524357,590058,459014,524381,524317,589978,459030,524413,524349,590042,459022,524397,524333,590010,524301,524429,524365,590074,459009,524371,524307,524571,459025,524403,524339,590022,459017,524387,524323,589990,524291,524419,524355,590054,459013,524379,524315,589974,459029,524411,524347,590038,459021,524395,524331,590006,524299,524427,524363,590070,459011,524375,524311,524575,459027,524407,524343,590030,459019,524391,524327,589998,524295,524423,524359,590062,459015,524383,524319,589982,459031,524415,524351,590046,459023,524399,524335,590014,524303,524431,524367,590078,459008,524368,524304,524568,459024,524400,524336,590017,459016,524384,524320,589985,524288,524416,524352,590049,459012,524376,524312,589969,459028,524408,524344,590033,459020,524392,524328,590001,524296,524424,524360,590065,459010,524372,524308,524572,459026,524404,524340,590025,459018,524388,524324,589993,524292,524420,524356,590057,459014,524380,524316,589977,459030,524412,524348,590041,459022,524396,524332,590009,524300,524428,524364,590073,459009,524370,524306,524570,459025,524402,524338,590021,459017,524386,524322,589989,524290,524418,524354,590053,459013,524378,524314,589973,459029,524410,524346,590037,459021,524394,524330,590005,524298,524426,524362,590069,459011,524374,524310,524574,459027,524406,524342,590029,459019,524390,524326,589997,524294,524422,524358,590061,459015,524382,524318,589981,459031,524414,524350,590045,459023,524398,524334,590013,524302,524430,524366,590077,459008,524369,524305,524569,459024,524401,524337,590019,459016,524385,524321,589987,524289,524417,524353,590051,459012,524377,524313,589971,459028,524409,524345,590035,459020,524393,524329,590003,524297,524425,524361,590067,459010,524373,524309,524573,459026,524405,524341,590027,459018,524389,524325,589995,524293,524421,524357,590059,459014,524381,524317,589979,459030,524413,524349,590043,459022,524397,524333,590011,524301,524429,524365,590075,459009,524371,524307,524571,459025,524403,524339,590023,459017,524387,524323,589991,524291,524419,524355,590055,459013,524379,524315,589975,459029,524411,524347,590039,459021,524395,524331,590007,524299,524427,524363,590071,459011,524375,524311,524575,459027,524407,524343,590031,459019,524391,524327,589999,524295,524423,524359,590063,459015,524383,524319,589983,459031,524415,524351,590047,459023,524399,524335,590015,524303,524431,524367,590079]),9],E0=[new Int32Array([327680,327696,327688,327704,327684,327700,327692,327708,327682,327698,327690,327706,327686,327702,327694,0,327681,327697,327689,327705,327685,327701,327693,327709,327683,327699,327691,327707,327687,327703,327695,0]),5],A0=function(t){k(e,t);function e(r,n){var o=t.call(this,n)||this;o.stream=r;var i=r.getByte(),a=r.getByte();if(i===-1||a===-1)throw new Error("Invalid header in flate stream: "+i+", "+a);if((i&15)!==8)throw new Error("Unknown compression method in flate stream: "+i+", "+a);if(((i<<8)+a)%31!==0)throw new Error("Bad FCHECK in flate stream: "+i+", "+a);if(a&32)throw new Error("FDICT bit set in flate stream: "+i+", "+a);return o.codeSize=0,o.codeBuf=0,o}return e.prototype.readBlock=function(){var r,n,o=this.stream,i=this.getBits(3);if(i&1&&(this.eof=!0),i>>=1,i===0){var a=void 0;if((a=o.getByte())===-1)throw new Error("Bad block header in flate stream");var s=a;if((a=o.getByte())===-1)throw new Error("Bad block header in flate stream");if(s|=a<<8,(a=o.getByte())===-1)throw new Error("Bad block header in flate stream");var f=a;if((a=o.getByte())===-1)throw new Error("Bad block header in flate stream");if(f|=a<<8,f!==(~s&65535)&&(s!==0||f!==0))throw new Error("Bad uncompressed block length in flate stream");this.codeBuf=0,this.codeSize=0;var l=this.bufferLength;r=this.ensureBuffer(l+s);var c=l+s;if(this.bufferLength=c,s===0)o.peekByte()===-1&&(this.eof=!0);else for(var u=l;u0;)S[m++]=C}d=this.generateHuffmanTable(S.subarray(0,h)),p=this.generateHuffmanTable(S.subarray(h,w))}else throw new Error("Unknown block type in flate stream");r=this.buffer;for(var A=r?r.length:0,R=this.bufferLength;;){var z=this.getCode(d);if(z<256){R+1>=A&&(r=this.ensureBuffer(R+1),A=r.length),r[R++]=z;continue}if(z===256){this.bufferLength=R;return}z-=257,z=C0[z];var M=z>>16;M>0&&(M=this.getBits(M)),n=(z&65535)+M,z=this.getCode(p),z=k0[z],M=z>>16,M>0&&(M=this.getBits(M));var X=(z&65535)+M;R+n>=A&&(r=this.ensureBuffer(R+n),A=r.length);for(var te=0;te>r,this.codeSize=o-=r,a},e.prototype.getCode=function(r){for(var n=this.stream,o=r[0],i=r[1],a=this.codeSize,s=this.codeBuf,f;a>16,u=l&65535;if(c<1||a>c,this.codeSize=a-c,u},e.prototype.generateHuffmanTable=function(r){var n=r.length,o=0,i;for(i=0;io&&(o=r[i]);for(var a=1<>=1;for(i=d;i0;if(!S||S<256)F[0]=S,x=1;else if(S>=258)if(S=0;a--)F[a]=u[s],s=p[s];else F[x++]=F[0];else if(S===256){h=9,c=258,x=0;continue}else{this.eof=!0,delete this.lzwState;break}if(D&&(p[c]=b,d[c]=d[b]+1,u[c]=F[0],c++,h=c+l&c+l-1?h:Math.min(Math.log(c+l)/.6931471805599453+1,12)|0),b=S,m+=x,n>>n&(1<0){var a=this.stream.getBytes(i);n.set(a,o),o+=i}}else{i=257-i;var s=r[1];n=this.ensureBuffer(o+i+1);for(var f=0;fn.size())throw new nn(r,0,n.size());n.remove(r)}else{if(r!==0)throw new nn(r,0,0);this.setKids([])}},e.prototype.normalizedEntries=function(){var r=this.Kids();return r||(r=this.dict.context.obj([this.ref]),this.dict.set(v.of("Kids"),r)),{Kids:r}},e.fromDict=function(r,n){return new e(r,n)},e}(vo),it=q0;var W0=function(t){k(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.Opt=function(){return this.dict.lookupMaybe(v.of("Opt"),ne,H,Z)},e.prototype.setOpt=function(r){this.dict.set(v.of("Opt"),this.dict.context.obj(r))},e.prototype.getExportValues=function(){var r=this.Opt();if(r){if(r instanceof ne||r instanceof H)return[r];for(var n=[],o=0,i=r.size();on.size())throw new nn(r,0,n.size());n.remove(r)}},e.prototype.normalizeExportValues=function(){for(var r,n,o,i,a=(r=this.getExportValues())!==null&&r!==void 0?r:[],s=[],f=this.getWidgets(),l=0,c=f.length;l1){if(!this.hasFlag(le.MultiSelect))throw new mc;this.dict.set(v.of("V"),this.dict.context.obj(r))}this.updateSelectedIndices(r)},e.prototype.valuesAreValid=function(r){for(var n=this.getOptions(),o=function(f,l){var c=r[f].decodeText();if(!n.find(function(u){return c===(u.display||u.value).decodeText()}))return{value:!1}},i=0,a=r.length;i1){for(var n=new Array(r.length),o=this.getOptions(),i=function(f,l){var c=r[f].decodeText();n[f]=o.findIndex(function(u){return c===(u.display||u.value).decodeText()})},a=0,s=r.length;a0){var s=a.lookup(0,ne,H),f=a.lookupMaybe(1,ne,H);n.push({value:s,display:f||s})}}return n}return[]},e}(it),go=K0;var X0=function(t){k(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.fromDict=function(r,n){return new e(r,n)},e.create=function(r){var n=r.obj({FT:"Ch",Ff:le.Combo,Kids:[]}),o=r.register(n);return new e(n,o)},e}(go),rr=X0;var Z0=function(t){k(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.addField=function(r){var n=this.normalizedEntries().Kids;n?.push(r)},e.prototype.normalizedEntries=function(){var r=this.Kids();return r||(r=this.dict.context.obj([]),this.dict.set(v.of("Kids"),r)),{Kids:r}},e.fromDict=function(r,n){return new e(r,n)},e.create=function(r){var n=r.obj({}),o=r.register(n);return new e(n,o)},e}(vo),nr=Z0;var Y0=function(t){k(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.fromDict=function(r,n){return new e(r,n)},e}(it),Nr=Y0;var J0=function(t){k(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.MaxLen=function(){var r=this.dict.lookup(v.of("MaxLen"));if(r instanceof j)return r},e.prototype.Q=function(){var r=this.dict.lookup(v.of("Q"));if(r instanceof j)return r},e.prototype.setMaxLength=function(r){this.dict.set(v.of("MaxLen"),j.of(r))},e.prototype.removeMaxLength=function(){this.dict.delete(v.of("MaxLen"))},e.prototype.getMaxLength=function(){var r;return(r=this.MaxLen())===null||r===void 0?void 0:r.asNumber()},e.prototype.setQuadding=function(r){this.dict.set(v.of("Q"),j.of(r))},e.prototype.getQuadding=function(){var r;return(r=this.Q())===null||r===void 0?void 0:r.asNumber()},e.prototype.setValue=function(r){this.dict.set(v.of("V"),r)},e.prototype.removeValue=function(){this.dict.delete(v.of("V"))},e.prototype.getValue=function(){var r=this.V();if(r instanceof ne||r instanceof H)return r},e.fromDict=function(r,n){return new e(r,n)},e.create=function(r){var n=r.obj({FT:"Tx",Kids:[]}),o=r.register(n);return new e(n,o)},e}(it),or=J0;var Q0=function(t){k(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.fromDict=function(r,n){return new e(r,n)},e.create=function(r){var n=r.obj({FT:"Btn",Ff:qe.PushButton,Kids:[]}),o=r.register(n);return new e(n,o)},e}(Br),ir=Q0;var _0=function(t){k(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.setValue=function(r){var n=this.getOnValues();if(!n.includes(r)&&r!==v.of("Off"))throw new on;this.dict.set(v.of("V"),r);for(var o=this.getWidgets(),i=0,a=o.length;ii)throw new Ma(n,i);for(var a=n,s=0,f=o.size();sa)return c.insertLeafNode(r,a)||l;a-=c.Count().asNumber()}c instanceof Ze&&(a-=1)}if(a===0){this.insertLeafKid(o.size(),r);return}throw new Ia(n,"insertLeafNode")},e.prototype.removeLeafNode=function(r,n){n===void 0&&(n=!0);var o=this.Kids(),i=this.Count().asNumber();if(r>=i)throw new Ma(r,i);for(var a=r,s=0,f=o.size();sa){c.removeLeafNode(a,n),n&&c.Kids().size()===0&&o.remove(s);return}else a-=c.Count().asNumber();if(c instanceof Ze)if(a===0){this.removeKid(s);return}else a-=1}throw new Ia(r,"removeLeafNode")},e.prototype.ascend=function(r){r(this);var n=this.Parent();n&&n.ascend(r)},e.prototype.traverse=function(r){for(var n=this.Kids(),o=0,i=n.size();oNumber.MAX_SAFE_INTEGER)if(this.capNumbers){var o="Parsed number that is too large for some PDF readers: "+e+", using Number.MAX_SAFE_INTEGER instead.";return console.warn(o),Number.MAX_SAFE_INTEGER}else{var o="Parsed number that is too large for some PDF readers: "+e+", not capping.";console.warn(o)}return n},t.prototype.skipWhitespace=function(){for(;!this.bytes.done()&&ft[this.bytes.peek()];)this.bytes.next()},t.prototype.skipLine=function(){for(;!this.bytes.done();){var e=this.bytes.peek();if(e===Qc||e===_c)return;this.bytes.next()}},t.prototype.skipComment=function(){if(this.bytes.peek()!==g.Percent)return!1;for(;!this.bytes.done();){var e=this.bytes.peek();if(e===Qc||e===_c)return!0;this.bytes.next()}return!0},t.prototype.skipWhitespaceAndComments=function(){for(this.skipWhitespace();this.skipComment();)this.skipWhitespace()},t.prototype.matchKeyword=function(e){for(var r=this.bytes.offset(),n=0,o=e.length;n=this.length},t.prototype.offset=function(){return this.idx},t.prototype.slice=function(e,r){return this.bytes.slice(e,r)},t.prototype.position=function(){return{line:this.line,column:this.column,offset:this.idx}},t.of=function(e){return new t(e)},t.fromPDFRawStream=function(e){return t.of(uo(e).decode())},t}(),lr=lv;var fv=g.Space,wo=g.CarriageReturn,So=g.Newline,Po=[g.s,g.t,g.r,g.e,g.a,g.m],Ti=[g.e,g.n,g.d,g.s,g.t,g.r,g.e,g.a,g.m],pe={header:[g.Percent,g.P,g.D,g.F,g.Dash],eof:[g.Percent,g.Percent,g.E,g.O,g.F],obj:[g.o,g.b,g.j],endobj:[g.e,g.n,g.d,g.o,g.b,g.j],xref:[g.x,g.r,g.e,g.f],trailer:[g.t,g.r,g.a,g.i,g.l,g.e,g.r],startxref:[g.s,g.t,g.a,g.r,g.t,g.x,g.r,g.e,g.f],true:[g.t,g.r,g.u,g.e],false:[g.f,g.a,g.l,g.s,g.e],null:[g.n,g.u,g.l,g.l],stream:Po,streamEOF1:re(Po,[fv,wo,So]),streamEOF2:re(Po,[wo,So]),streamEOF3:re(Po,[wo]),streamEOF4:re(Po,[So]),endstream:Ti,EOF1endstream:re([wo,So],Ti),EOF2endstream:re([wo],Ti),EOF3endstream:re([So],Ti)};var cv=function(t){k(e,t);function e(r,n,o){o===void 0&&(o=!1);var i=t.call(this,r,o)||this;return i.context=n,i}return e.prototype.parseObject=function(){if(this.skipWhitespaceAndComments(),this.matchKeyword(pe.true))return Ut.True;if(this.matchKeyword(pe.false))return Ut.False;if(this.matchKeyword(pe.null))return Te;var r=this.bytes.peek();if(r===g.LessThan&&this.bytes.peekAhead(1)===g.LessThan)return this.parseDictOrStream();if(r===g.LessThan)return this.parseHexString();if(r===g.LeftParen)return this.parseString();if(r===g.ForwardSlash)return this.parseName();if(r===g.LeftSquareBracket)return this.parseArray();if(Fo[r])return this.parseNumberOrRef();throw new xc(this.bytes.position(),r)},e.prototype.parseNumberOrRef=function(){var r=this.parseRawNumber();this.skipWhitespaceAndComments();var n=this.bytes.offset();if(Ie[this.bytes.peek()]){var o=this.parseRawNumber();if(this.skipWhitespaceAndComments(),this.bytes.peek()===g.R)return this.bytes.assertNext(g.R),J.of(r,o)}return this.bytes.moveTo(n),j.of(r)},e.prototype.parseHexString=function(){var r="";for(this.bytes.assertNext(g.LessThan);!this.bytes.done()&&this.bytes.peek()!==g.GreaterThan;)r+=tt(this.bytes.next());return this.bytes.assertNext(g.GreaterThan),H.of(r)},e.prototype.parseString=function(){for(var r=0,n=!1,o="";!this.bytes.done();){var i=this.bytes.next();if(o+=tt(i),n||(i===g.LeftParen&&(r+=1),i===g.RightParen&&(r-=1)),i===g.BackSlash?n=!n:n&&(n=!1),r===0)return ne.of(o.substring(1,o.length-1))}throw new Sc(this.bytes.position())},e.prototype.parseName=function(){this.bytes.assertNext(g.ForwardSlash);for(var r="";!this.bytes.done();){var n=this.bytes.peek();if(ft[n]||et[n])break;r+=tt(n),this.bytes.next()}return v.of(r)},e.prototype.parseArray=function(){this.bytes.assertNext(g.LeftSquareBracket),this.skipWhitespaceAndComments();for(var r=Z.withContext(this.context);this.bytes.peek()!==g.RightSquareBracket;){var n=this.parseObject();r.push(n),this.skipWhitespaceAndComments()}return this.bytes.assertNext(g.RightSquareBracket),r},e.prototype.parseDict=function(){this.bytes.assertNext(g.LessThan),this.bytes.assertNext(g.LessThan),this.skipWhitespaceAndComments();for(var r=new Map;!this.bytes.done()&&this.bytes.peek()!==g.GreaterThan&&this.bytes.peekAhead(1)!==g.GreaterThan;){var n=this.parseName(),o=this.parseObject();r.set(n,o),this.skipWhitespaceAndComments()}this.skipWhitespaceAndComments(),this.bytes.assertNext(g.GreaterThan),this.bytes.assertNext(g.GreaterThan);var i=r.get(v.of("Type"));return i===v.of("Catalog")?bo.fromMapWithContext(r,this.context):i===v.of("Pages")?xo.fromMapWithContext(r,this.context):i===v.of("Page")?Ze.fromMapWithContext(r,this.context):U.fromMapWithContext(r,this.context)},e.prototype.parseDictOrStream=function(){var r=this.bytes.position(),n=this.parseDict();if(this.skipWhitespaceAndComments(),!this.matchKeyword(pe.streamEOF1)&&!this.matchKeyword(pe.streamEOF2)&&!this.matchKeyword(pe.streamEOF3)&&!this.matchKeyword(pe.streamEOF4)&&!this.matchKeyword(pe.stream))return n;var o=this.bytes.offset(),i,a=n.get(v.of("Length"));a instanceof j?(i=o+a.asNumber(),this.bytes.moveTo(i),this.skipWhitespaceAndComments(),this.matchKeyword(pe.endstream)||(this.bytes.moveTo(o),i=this.findEndOfStreamFallback(r))):i=this.findEndOfStreamFallback(r);var s=this.bytes.slice(o,i);return Et.of(n,s)},e.prototype.findEndOfStreamFallback=function(r){for(var n=1,o=this.bytes.offset();!this.bytes.done()&&(o=this.bytes.offset(),this.matchKeyword(pe.stream)?n+=1:this.matchKeyword(pe.EOF1endstream)||this.matchKeyword(pe.EOF2endstream)||this.matchKeyword(pe.EOF3endstream)||this.matchKeyword(pe.endstream)?n-=1:this.bytes.next(),n!==0););if(n!==0)throw new wc(r);return o},e.forBytes=function(r,n,o){return new e(lr.of(r),n,o)},e.forByteStream=function(r,n,o){return o===void 0&&(o=!1),new e(r,n,o)},e}($c),Do=cv;var uv=function(t){k(e,t);function e(r,n){var o=t.call(this,lr.fromPDFRawStream(r),r.dict.context)||this,i=r.dict;return o.alreadyParsed=!1,o.shouldWaitForTick=n||function(){return!1},o.firstOffset=i.lookup(v.of("First"),j).asNumber(),o.objectCount=i.lookup(v.of("N"),j).asNumber(),o}return e.prototype.parseIntoContext=function(){return V(this,void 0,void 0,function(){var r,n,o,i,a,s,f,l;return q(this,function(c){switch(c.label){case 0:if(this.alreadyParsed)throw new rn("PDFObjectStreamParser","parseIntoContext");this.alreadyParsed=!0,r=this.parseOffsetsAndObjectNumbers(),n=0,o=r.length,c.label=1;case 1:return n=g.Space&&n<=g.Tilde;if(o&&(this.matchKeyword(pe.xref)||this.matchKeyword(pe.trailer)||this.matchKeyword(pe.startxref)||this.matchIndirectObjectHeader())){this.bytes.moveTo(r);break}this.bytes.next()}},e.prototype.skipBinaryHeaderComment=function(){this.skipWhitespaceAndComments();try{var r=this.bytes.offset();this.parseIndirectObjectHeader(),this.bytes.moveTo(r)}catch{this.bytes.next(),this.skipWhitespaceAndComments()}},e.forBytesWithOptions=function(r,n,o,i){return new e(r,n,o,i)},e}(Do),$a=hv;var Rt=function(t){return 1<0&&(n[n.length]=+o),r[r.length]={cmd:e,args:n},n=[],o="",i=!1),e=l;else if([" ",","].includes(l)||l==="-"&&o.length>0&&o[o.length-1]!=="e"||l==="."&&i){if(o.length===0)continue;n.length===a?(r[r.length]={cmd:e,args:n},n=[+o],e==="M"&&(e="L"),e==="m"&&(e="l")):n[n.length]=+o,i=l===".",o=["-","."].includes(l)?l:""}else o+=l,l==="."&&(i=!0)}return o.length>0&&(n.length===a?(r[r.length]={cmd:e,args:n},n=[+o],e==="M"&&(e="L"),e==="m"&&(e="l")):n[n.length]=+o),r[r.length]={cmd:e,args:n},r},gv=function(t){G=K=fe=ce=No=Mo=0;for(var e=[],r=0;r1&&(d=Math.sqrt(d),r*=d,n*=d);var p=u/r,h=c/r,b=-c/n,F=u/n,x=p*s+h*f,m=b*s+F*f,y=p*t+h*e,w=b*t+F*e,S=(y-x)*(y-x)+(w-m)*(w-m),D=1/S-.25;D<0&&(D=0);var T=Math.sqrt(D);i===o&&(T=-T);var C=.5*(x+y)-T*(w-m),E=.5*(m+w)+T*(y-x),I=Math.atan2(m-E,x-C),A=Math.atan2(w-E,y-C),R=A-I;R<0&&i===1?R+=2*Math.PI:R>0&&i===0&&(R-=2*Math.PI);for(var z=Math.ceil(Math.abs(R/(Math.PI*.5+.001))),M=[],X=0;Xt.length)return o-1;var F=e.heightAtSize(o),x=F+F*.2,m=x*i;if(m>Math.abs(r.height))return o-1;o+=1}return o},Sv=function(t,e,r,n){for(var o=r.width/n,i=r.height,a=Ou,s=zs(t);ao*.75;if(u)return a-1}var d=e.heightAtSize(a,{descender:!1});if(d>i)return a-1;a+=1}return a},Pv=function(t){for(var e=t.length;e>0;e--)if(/\s/.test(t[e]))return e},Dv=function(t,e,r,n){for(var o,i=t.length;i>0;){var a=t.substring(0,i),s=r.encodeText(a),f=r.widthOfTextAtSize(a,n);if(fd&&(d=T+S),h+s>p&&(p=h+s),l.push({text:y,encoded:w,width:S,height:s,x:T,y:h}),x=D?.trim()}return{fontSize:n,lineHeight:f,lines:l,bounds:{x:c,y:u,width:d-c,height:p-u}}},Mu=function(t,e){var r=e.fontSize,n=e.font,o=e.bounds,i=e.cellCount,a=Zi(pr(t));if(a.length>i)throw new Eu(a.length,i);(r===void 0||r===0)&&(r=Sv(a,n,o,i));for(var s=o.width/i,f=n.heightAtSize(r,{descender:!1}),l=o.y+(o.height/2-f/2),c=[],u=o.x,d=o.y,p=o.x+o.width,h=o.y+o.height,b=0,F=0;bp&&(p=T+S),l+f>h&&(h=l+f),c.push({text:a,encoded:w,width:S,height:f,x:T,y:l}),b+=1,F+=y}return{fontSize:r,cells:c,bounds:{x:u,y:d,width:p-u,height:h-d}}},jo=function(t,e){var r=e.alignment,n=e.fontSize,o=e.font,i=e.bounds,a=Zi(pr(t));(n===void 0||n===0)&&(n=Nu([a],o,i));var s=o.encodeText(a),f=o.widthOfTextAtSize(a,n),l=o.heightAtSize(n,{descender:!1}),c=r===De.Left?i.x:r===De.Center?i.x+i.width/2-f/2:r===De.Right?i.x+i.width-f:i.x,u=i.y+(i.height/2-l/2);return{fontSize:n,line:{text:a,encoded:s,width:f,height:l,x:c,y:u},bounds:{x:c,y:u,width:f,height:l}}};var pt=function(t){return"normal"in t?t:{normal:t}},Cv=/\/([^\0\t\n\f\r\ ]+)[\0\t\n\f\r\ ]+(\d*\.\d+|\d+)[\0\t\n\f\r\ ]+Tf/,dr=function(t){var e,r,n=(e=t.getDefaultAppearance())!==null&&e!==void 0?e:"",o=(r=On(n,Cv).match)!==null&&r!==void 0?r:[],i=Number(o[2]);return isFinite(i)?i:void 0},kv=/(\d*\.\d+|\d+)[\0\t\n\f\r\ ]*(\d*\.\d+|\d+)?[\0\t\n\f\r\ ]*(\d*\.\d+|\d+)?[\0\t\n\f\r\ ]*(\d*\.\d+|\d+)?[\0\t\n\f\r\ ]+(g|rg|k)/,dt=function(t){var e,r=(e=t.getDefaultAppearance())!==null&&e!==void 0?e:"",n=On(r,kv).match,o=n??[],i=o[1],a=o[2],s=o[3],f=o[4],l=o[5];if(l==="g"&&i)return fs(Number(i));if(l==="rg"&&i&&a&&s)return ae(Number(i),Number(a),Number(s));if(l==="k"&&i&&a&&s&&f)return cs(Number(i),Number(a),Number(s),Number(f))},ht=function(t,e,r,n){var o;n===void 0&&(n=0);var i=[Bt(e).toString(),Oo((o=r?.name)!==null&&o!==void 0?o:"dummy__noop",n).toString()].join(` +`);t.setDefaultAppearance(i)},Iu=function(t,e){var r,n,o,i=dt(e),a=dt(t.acroField),s=e.getRectangle(),f=e.getAppearanceCharacteristics(),l=e.getBorderStyle(),c=(r=l?.getWidth())!==null&&r!==void 0?r:0,u=bt(f?.getRotation()),d=qt(s,u),p=d.width,h=d.height,b=xt(Y(Y({},s),{rotation:u})),F=ae(0,0,0),x=(n=We(f?.getBorderColor()))!==null&&n!==void 0?n:F,m=We(f?.getBackgroundColor()),y=We(f?.getBackgroundColor(),.8),w=(o=i??a)!==null&&o!==void 0?o:F;ht(i?e:t.acroField,w);var S={x:0+c/2,y:0+c/2,width:p-c,height:h-c,thickness:1.5,borderWidth:c,borderColor:x,markColor:w};return{normal:{on:re(b,Io(Y(Y({},S),{color:m,filled:!0}))),off:re(b,Io(Y(Y({},S),{color:m,filled:!1})))},down:{on:re(b,Io(Y(Y({},S),{color:y,filled:!0}))),off:re(b,Io(Y(Y({},S),{color:y,filled:!1})))}}},zu=function(t,e){var r,n,o,i=dt(e),a=dt(t.acroField),s=e.getRectangle(),f=e.getAppearanceCharacteristics(),l=e.getBorderStyle(),c=(r=l?.getWidth())!==null&&r!==void 0?r:0,u=bt(f?.getRotation()),d=qt(s,u),p=d.width,h=d.height,b=xt(Y(Y({},s),{rotation:u})),F=ae(0,0,0),x=(n=We(f?.getBorderColor()))!==null&&n!==void 0?n:F,m=We(f?.getBackgroundColor()),y=We(f?.getBackgroundColor(),.8),w=(o=i??a)!==null&&o!==void 0?o:F;ht(i?e:t.acroField,w);var S={x:p/2,y:h/2,width:p-c,height:h-c,borderWidth:c,borderColor:x,dotColor:w};return{normal:{on:re(b,zo(Y(Y({},S),{color:m,filled:!0}))),off:re(b,zo(Y(Y({},S),{color:m,filled:!1})))},down:{on:re(b,zo(Y(Y({},S),{color:y,filled:!0}))),off:re(b,zo(Y(Y({},S),{color:y,filled:!1})))}}},ju=function(t,e,r){var n,o,i,a,s,f=dt(e),l=dt(t.acroField),c=dr(e),u=dr(t.acroField),d=e.getRectangle(),p=e.getAppearanceCharacteristics(),h=e.getBorderStyle(),b=p?.getCaptions(),F=(n=b?.normal)!==null&&n!==void 0?n:"",x=(i=(o=b?.down)!==null&&o!==void 0?o:F)!==null&&i!==void 0?i:"",m=(a=h?.getWidth())!==null&&a!==void 0?a:0,y=bt(p?.getRotation()),w=qt(d,y),S=w.width,D=w.height,T=xt(Y(Y({},d),{rotation:y})),C=ae(0,0,0),E=We(p?.getBorderColor()),I=We(p?.getBackgroundColor()),A=We(p?.getBackgroundColor(),.8),R={x:m,y:m,width:S-m*2,height:D-m*2},z=jo(F,{alignment:De.Center,fontSize:c??u,font:r,bounds:R}),M=jo(x,{alignment:De.Center,fontSize:c??u,font:r,bounds:R}),X=Math.min(z.fontSize,M.fontSize),te=(s=f??l)!==null&&s!==void 0?s:C;ht(f||c!==void 0?e:t.acroField,te,r,X);var L={x:0+m/2,y:0+m/2,width:S-m,height:D-m,borderWidth:m,borderColor:E,textColor:te,font:r.name,fontSize:X};return{normal:re(T,vs(Y(Y({},L),{color:I,textLines:[z.line]}))),down:re(T,vs(Y(Y({},L),{color:A,textLines:[M.line]})))}},Lu=function(t,e,r){var n,o,i,a,s=dt(e),f=dt(t.acroField),l=dr(e),c=dr(t.acroField),u=e.getRectangle(),d=e.getAppearanceCharacteristics(),p=e.getBorderStyle(),h=(n=t.getText())!==null&&n!==void 0?n:"",b=(o=p?.getWidth())!==null&&o!==void 0?o:0,F=bt(d?.getRotation()),x=qt(u,F),m=x.width,y=x.height,w=xt(Y(Y({},u),{rotation:F})),S=ae(0,0,0),D=We(d?.getBorderColor()),T=We(d?.getBackgroundColor()),C,E,I=t.isCombed()?0:1,A={x:b+I,y:b+I,width:m-(b+I)*2,height:y-(b+I)*2};if(t.isMultiline()){var R=bs(h,{alignment:t.getAlignment(),fontSize:l??c,font:r,bounds:A});C=R.lines,E=R.fontSize}else if(t.isCombed()){var R=Mu(h,{fontSize:l??c,font:r,bounds:A,cellCount:(i=t.getMaxLength())!==null&&i!==void 0?i:0});C=R.cells,E=R.fontSize}else{var R=jo(h,{alignment:t.getAlignment(),fontSize:l??c,font:r,bounds:A});C=[R.line],E=R.fontSize}var z=(a=s??f)!==null&&a!==void 0?a:S;ht(s||l!==void 0?e:t.acroField,z,r,E);var M={x:0+b/2,y:0+b/2,width:m-b,height:y-b,borderWidth:b??0,borderColor:D,textColor:z,font:r.name,fontSize:E,color:T,textLines:C,padding:I};return re(w,gs(M))},Hu=function(t,e,r){var n,o,i,a=dt(e),s=dt(t.acroField),f=dr(e),l=dr(t.acroField),c=e.getRectangle(),u=e.getAppearanceCharacteristics(),d=e.getBorderStyle(),p=(n=t.getSelected()[0])!==null&&n!==void 0?n:"",h=(o=d?.getWidth())!==null&&o!==void 0?o:0,b=bt(u?.getRotation()),F=qt(c,b),x=F.width,m=F.height,y=xt(Y(Y({},c),{rotation:b})),w=ae(0,0,0),S=We(u?.getBorderColor()),D=We(u?.getBackgroundColor()),T=1,C={x:h+T,y:h+T,width:x-(h+T)*2,height:m-(h+T)*2},E=jo(p,{alignment:De.Left,fontSize:f??l,font:r,bounds:C}),I=E.line,A=E.fontSize,R=(i=a??s)!==null&&i!==void 0?i:w;ht(a||f!==void 0?e:t.acroField,R,r,A);var z={x:0+h/2,y:0+h/2,width:x-h,height:m-h,borderWidth:h??0,borderColor:S,textColor:R,font:r.name,fontSize:A,color:D,textLines:[I],padding:T};return re(y,gs(z))},Uu=function(t,e,r){var n,o,i=dt(e),a=dt(t.acroField),s=dr(e),f=dr(t.acroField),l=e.getRectangle(),c=e.getAppearanceCharacteristics(),u=e.getBorderStyle(),d=(n=u?.getWidth())!==null&&n!==void 0?n:0,p=bt(c?.getRotation()),h=qt(l,p),b=h.width,F=h.height,x=xt(Y(Y({},l),{rotation:p})),m=ae(0,0,0),y=We(c?.getBorderColor()),w=We(c?.getBackgroundColor()),S=t.getOptions(),D=t.getSelected();t.isSorted()&&S.sort();for(var T="",C=0,E=S.length;C1||o.length===1&&n)&&this.enableMultiselect();for(var s=new Array(o.length),f=0,l=o.length;f1||o.length===1&&n)&&this.enableMultiselect();for(var a=new Array(o.length),s=0,f=o.length;sn)throw new Au(r.length,n,this.getName());this.markAsDirty(),this.disableRichFormatting(),r?this.acroField.setValue(H.fromText(r)):this.acroField.removeValue()},e.prototype.getAlignment=function(){var r=this.acroField.getQuadding();return r===0?De.Left:r===1?De.Center:r===2?De.Right:De.Left},e.prototype.setAlignment=function(r){yt(r,"alignment",De),this.markAsDirty(),this.acroField.setQuadding(r)},e.prototype.getMaxLength=function(){return this.acroField.getMaxLength()},e.prototype.setMaxLength=function(r){if(ot(r,"maxLength",0,Number.MAX_SAFE_INTEGER),this.markAsDirty(),r===void 0)this.acroField.removeMaxLength();else{var n=this.getText();if(n&&n.length>r)throw new Ru(n.length,r,this.getName());this.acroField.setMaxLength(r)}},e.prototype.removeMaxLength=function(){this.markAsDirty(),this.acroField.removeMaxLength()},e.prototype.setImage=function(r){for(var n=this.getAlignment(),o=n===De.Center?Ft.Center:n===De.Right?Ft.Right:Ft.Left,i=this.acroField.getWidgets(),a=0,s=i.length;at/25.4*96;function Kv(t){return t.pageSize==="Custom"?{w:Math.max(1,Math.round(kn(t.customPageWidth))),h:Math.max(1,Math.round(kn(t.customPageHeight)))}:Vi[t.pageSize]??Vi.A4}function Ui(t){return t.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'")}function Gu(t){return t.replace(/<\/style/gi,"<\\/style")}function Cn(t,e){let r=e.trim();if(!r)return"";if(/^(https?:|data:)/i.test(r))return r;let n=t.vault.getAbstractFileByPath(r);if(n instanceof N.TFile)return t.vault.getResourcePath(n);let o=t.metadataCache.getFirstLinkpathDest(r,"");return o instanceof N.TFile?t.vault.getResourcePath(o):(console.warn("[advanced-pdf-export] Could not resolve image path:",r),r)}function Ku(t){return{size:t==="fill"?"100% 100%":t==="tile"?"auto":t,repeat:t==="tile"?"repeat":"no-repeat"}}var Xv=/[\u0590-\u08FF\uFB1D-\uFDFD\uFE70-\uFEFC]/g,Zv=/[A-Za-z\u0590-\u08FF\uFB1D-\uFDFD\uFE70-\uFEFC]/g;function Yv(t){let e=(t.match(Xv)??[]).length,r=(t.match(Zv)??[]).length;return r>0&&e/r>.1}function Jv(t){return t.replace(/\r\n|\r/g,` +`)}function Qv(t){return t.replace(/^---[ \t]*\n[\s\S]*?\n---[ \t]*(\n|$)/,"")}function _v(t){return t.split(/^\/\/\/\s*$/m).map(e=>e.trim()).filter(Boolean)}async function $v(t){let e=new N.Component;e.load();try{await Qu(t,"$\\mathbf{A}+\\mathfrak{A}+\\mathcal{A}+\\mathsf{A}+\\mathtt{A}+\\mathbb{A}+\\aleph+\\vec{v}$","",e)}catch(r){console.warn("[advanced-pdf-export] MathJax warm-up failed (non-fatal):",r)}finally{e.unload()}}async function Qu(t,e,r,n){let o=activeDocument.createElement("div");o.setCssStyles({position:"fixed",top:"0",left:"-99999px",visibility:"hidden",pointerEvents:"none"}),activeDocument.body.appendChild(o);try{await N.MarkdownRenderer.render(t,e,o,r,n);let i=3e3;try{let s;await Promise.race([(0,N.finishRenderMath)().finally(()=>window.clearTimeout(s)),new Promise(f=>{s=window.setTimeout(f,i)})])}catch(s){console.warn("[advanced-pdf-export] finishRenderMath failed:",s)}await om(o),await im(o);let a=activeDocument.fonts;if(a)try{await a.ready}catch{}}finally{activeDocument.body.removeChild(o)}return nm(o),o}var em=/[^\p{L}\p{N}\s-]/gu,tm=/\s+/g,rm=/-+/g;function Xu(t){return t.toLowerCase().replace(em,"").trim().replace(tm,"-").replace(rm,"-")}function nm(t){let e=new Map;t.querySelectorAll("h1,h2,h3,h4,h5,h6").forEach(r=>{let n=r.textContent||"",o=Xu(n);if(!o)return;let i=e.get(o)??0;e.set(o,i+1),r.id=i===0?o:`${o}-${i}`}),t.querySelectorAll("a").forEach(r=>{r.classList.remove("external-link");let n=r.getAttribute("data-href")??r.getAttribute("href");n?.startsWith("#")&&r.setAttribute("href","#"+Xu(n.slice(1)))}),t.querySelectorAll(".copy-code-button").forEach(r=>r.remove()),t.querySelectorAll(".callout").forEach(r=>{r.removeAttribute("data-callout-fold"),r.classList.remove("is-collapsed"),r.querySelectorAll(".callout-fold").forEach(n=>n.remove())}),t.querySelectorAll("style, script").forEach(r=>{r.closest("svg")||r.remove()})}async function om(t){let e=Array.from(t.querySelectorAll(".mermaid"));if(e.length===0)return;let r=5e3;await Promise.all(e.map(n=>new Promise(o=>{if(n.querySelector("svg")){o();return}let i=window.setTimeout(()=>{a.disconnect(),o()},r),a=new MutationObserver(()=>{n.querySelector("svg")&&(window.clearTimeout(i),a.disconnect(),o())});a.observe(n,{childList:!0,subtree:!0})})))}async function im(t){let e=Array.from(t.querySelectorAll(".math"));if(e.length===0)return;let r=window.MathJax;if(r?.startup?.promise)try{await r.startup.promise}catch{}let n=8e3;await Promise.all(e.filter(o=>!o.querySelector("mjx-container")).map(o=>new Promise(i=>{let a=window.setTimeout(()=>{s.disconnect(),i()},n),s=new MutationObserver(()=>{o.querySelector("mjx-container")&&(window.clearTimeout(a),s.disconnect(),i())});s.observe(o,{childList:!0,subtree:!0})}))),await Ds()}async function Ds(){let n=Date.now(),o=qi().length,i=0;for(;i<2&&Date.now()-n<2500;){await new Promise(s=>window.setTimeout(s,60));let a=qi().length;a===o?i++:(i=0,o=a)}}var am={comment:["comment","prolog","doctype","cdata"],punctuation:["punctuation"],property:["property","tag","boolean","number","constant","symbol","deleted","attr-name"],selector:["selector","string","char","builtin","inserted","attr-value"],operator:["operator","entity","url"],keyword:["atrule","keyword","important"],function:["function","class-name"],regex:["regex","variable"]},Cs={none:{name:"None (plain)"},"github-light":{name:"GitHub Light",background:"#f6f8fa",text:"#24292e",tokens:{comment:"#6a737d",punctuation:"#24292e",property:"#005cc5",selector:"#032f62",operator:"#d73a49",keyword:"#d73a49",function:"#6f42c1",regex:"#032f62"}},"github-dark":{name:"GitHub Dark",background:"#0d1117",text:"#c9d1d9",tokens:{comment:"#8b949e",punctuation:"#c9d1d9",property:"#79c0ff",selector:"#a5d6ff",operator:"#ff7b72",keyword:"#ff7b72",function:"#d2a8ff",regex:"#a5d6ff"}},"atom-one-light":{name:"Atom One Light",background:"#fafafa",text:"#383a42",tokens:{comment:"#a0a1a7",punctuation:"#383a42",property:"#986801",selector:"#50a14f",operator:"#0184bc",keyword:"#a626a4",function:"#4078f2",regex:"#50a14f"}},"atom-one-dark":{name:"Atom One Dark",background:"#282c34",text:"#abb2bf",tokens:{comment:"#5c6370",punctuation:"#abb2bf",property:"#d19a66",selector:"#98c379",operator:"#56b6c2",keyword:"#c678dd",function:"#61afef",regex:"#98c379"}},monokai:{name:"Monokai",background:"#272822",text:"#f8f8f2",tokens:{comment:"#75715e",punctuation:"#f8f8f2",property:"#ae81ff",selector:"#e6db74",operator:"#f92672",keyword:"#f92672",function:"#a6e22e",regex:"#e6db74"}},dracula:{name:"Dracula",background:"#282a36",text:"#f8f8f2",tokens:{comment:"#6272a4",punctuation:"#f8f8f2",property:"#bd93f9",selector:"#f1fa8c",operator:"#ff79c6",keyword:"#ff79c6",function:"#50fa7b",regex:"#ff79c6"}},"tokyo-night":{name:"Tokyo Night",background:"#1a1b26",text:"#a9b1d6",tokens:{comment:"#565f89",punctuation:"#89ddff",property:"#ff9e64",selector:"#9ece6a",operator:"#89ddff",keyword:"#bb9af7",function:"#7aa2f7",regex:"#b4f9f8"}},"solarized-light":{name:"Solarized Light",background:"#fdf6e3",text:"#586e75",tokens:{comment:"#93a1a1",punctuation:"#586e75",property:"#cb4b16",selector:"#2aa198",operator:"#859900",keyword:"#859900",function:"#268bd2",regex:"#2aa198"}},"catppuccin-macchiato":{name:"Catppuccin Macchiato",background:"#24273a",text:"#cad3f5",tokens:{comment:"#939ab7",punctuation:"#b8c0e0",property:"#f5a97f",selector:"#a6da95",operator:"#91d7e3",keyword:"#c6a0f6",function:"#8aadf4",regex:"#f5bde6"}},"catppuccin-mocha":{name:"Catppuccin Mocha",background:"#1e1e2e",text:"#cdd6f4",tokens:{comment:"#9399b2",punctuation:"#bac2de",property:"#fab387",selector:"#a6e3a1",operator:"#89dceb",keyword:"#cba6f7",function:"#89b4fa",regex:"#f5c2e7"}}};function sm(t){let e=Cs[t.codeTheme]??Cs.none,r=e.background??t.codeBackground,n=e.text??t.bodyColor,o=Object.entries(e.tokens??{}).map(([i,a])=>`${am[i].map(l=>`.mpdf-doc pre code .token.${l}`).join(", ")} { color: ${a};${i==="comment"?" font-style: italic;":""} }`).join(` + `);return` + .mpdf-doc pre { + background: ${r}; + border-radius: 4px; + padding: 10px 12px; + margin: 0 0 ${t.paragraphSpacing}em; + overflow: hidden; + } + .mpdf-doc pre code { + font-family: 'Courier New', monospace; + font-size: ${t.codeFontSize}em; + color: ${n}; + white-space: pre-wrap; + overflow-wrap: break-word; + background: none; + padding: 0; + } + ${o}`}function lm(t){let e=t.replace(/^#([\da-f])([\da-f])([\da-f])$/i,(a,s,f,l)=>`#${s}${s}${f}${f}${l}${l}`);if(!/^#[\da-f]{6}$/i.test(e))return 1;let r=a=>a<=.04045?a/12.92:((a+.055)/1.055)**2.4,n=r(parseInt(e.slice(1,3),16)/255),o=r(parseInt(e.slice(3,5),16)/255),i=r(parseInt(e.slice(5,7),16)/255);return .2126*n+.7152*o+.0722*i}function _u(t){return t.fontFamily==="__custom__"?t.customFontName.trim()||"inherit":t.fontFamily}function fm(t,e=!1){let r=t.headingScale,n=_u(t),o=lm(t.tableHeaderBg)<.35?"#fff":t.headingColor;return` + .mpdf-doc { + font-family: ${n}; + font-size: ${t.fontSize}px; + line-height: ${t.lineHeight}; + color: ${t.bodyColor}; + box-sizing: border-box; + ${e?"direction: rtl;":""} + } + .mpdf-doc *, .mpdf-doc *::before, .mpdf-doc *::after { box-sizing: border-box; } + .mpdf-doc strong, .mpdf-doc b { font-weight: 700; font-style: normal; } + .mpdf-doc em, .mpdf-doc i { font-style: italic; font-weight: inherit; } + .mpdf-doc mark { background: #ffe066; color: inherit; padding: 0 2px; border-radius: 2px; } + .mpdf-doc del, .mpdf-doc s { text-decoration: line-through; } + .mpdf-doc h1 { + font-size: ${Math.round(22*r)}px; + font-weight: 700; + color: ${t.headingColor}; + margin: 0 0 ${Math.round(12*r)}px; + line-height: 1.2; + ${t.h1BorderBottom?`border-bottom: 2px solid ${t.accentColor}; padding-bottom: 6px;`:""} + ${t.centerH1?"text-align: center;":""} + } + .mpdf-doc h2 { + font-size: ${Math.round(17*r)}px; + font-weight: 600; + color: ${t.headingColor}; + margin: ${Math.round(20*r)}px 0 ${Math.round(10*r)}px; + ${t.h2BorderBottom?`border-bottom: 0.5px solid ${t.accentColor}55; padding-bottom: 5px;`:""} + } + .mpdf-doc h3 { + font-size: ${Math.round(15*r)}px; + font-weight: 700; + color: ${t.headingColor}; + margin: ${Math.round(16*r)}px 0 ${Math.round(8*r)}px; + letter-spacing: 0.01em; + } + .mpdf-doc h4 { font-size: ${Math.round(13*r)}px; font-weight: 700; color: ${t.headingColor}; margin: 12px 0 6px; text-transform: uppercase; letter-spacing: 0.04em; } + .mpdf-doc h5 { font-size: ${Math.round(12*r)}px; font-weight: 600; color: ${t.headingColor}; margin: 10px 0 4px; font-style: italic; } + .mpdf-doc h6 { font-size: ${Math.round(11*r)}px; font-weight: 600; color: ${t.bodyColor}; margin: 8px 0 4px; font-style: italic; opacity: 0.75; } + .mpdf-doc p { margin: 0 0 ${t.paragraphSpacing}em; } + .mpdf-doc ul, .mpdf-doc ol { padding-inline-start: 1.4em; margin: 0 0 ${t.paragraphSpacing}em; } + .mpdf-doc li { margin-bottom: 0.2em; line-height: ${t.lineHeight}; } + .mpdf-doc blockquote { + border-inline-start: 3px solid ${t.blockquoteBorderColor}; + background: ${t.blockquoteBg}; + padding-block: 4px; + padding-inline: 1em 0; + margin: ${t.paragraphSpacing}em 0; + font-style: italic; + color: ${t.bodyColor}cc; + } + .mpdf-doc code { + font-family: 'Courier New', monospace; + font-size: ${t.codeFontSize}em; + background: ${t.codeBackground}; + padding: 1px 4px; + border-radius: 3px; + color: ${t.accentColor}; + } + ${sm(t)} + .mpdf-doc hr { + border: none; + border-top: 0.5px solid ${t.accentColor}44; + margin: ${t.paragraphSpacing*1.5}em 0; + } + .mpdf-doc img { max-width: 100%; height: auto; display: block; margin: ${t.paragraphSpacing}em auto; } + .mpdf-doc a { color: ${t.accentColor}; ${t.linkUnderline?"":"text-decoration: none;"} } + /* postProcessRenderedHTML removes the external-link class, but some themes + re-inject it at render time. This rule is cheap defense-in-depth. */ + .mpdf-doc a.external-link::after { display: none !important; content: none !important; } + /* Hide copy-code buttons that survive postProcessRenderedHTML (e.g. re-injected by themes). */ + .mpdf-doc .copy-code-button { display: none !important; } + .mpdf-doc table { width: 100%; border-collapse: collapse; margin: 0 0 ${t.paragraphSpacing}em; font-size: 0.92em; } + .mpdf-doc th { + background: ${t.tableHeaderBg}; + color: ${o}; + padding: 6px 10px; + text-align: start; + font-weight: 600; + border: 0.5px solid ${t.accentColor}33; + font-size: 0.9em; + } + .mpdf-doc td { padding: 5px 10px; border: 0.5px solid ${t.bodyColor}22; vertical-align: top; } + ${t.tableStriped?`.mpdf-doc tbody tr:nth-child(even) { background: ${t.tableHeaderBg}55; }`:""} + + /* Callouts \u2014 override theme styles with !important so preview and export are + * identical regardless of the active Obsidian theme. */ + .mpdf-doc .callout { + border-inline-start: 4px solid ${t.accentColor} !important; + border-start-start-radius: 0 !important; + border-start-end-radius: 5px !important; + border-end-end-radius: 5px !important; + border-end-start-radius: 0 !important; + background: ${t.accentColor}12 !important; + margin: ${t.paragraphSpacing*1.2}em 0 !important; + padding: 0 !important; + overflow: hidden !important; + box-shadow: inset 0 0 0 1px ${t.accentColor}22 !important; + font-style: normal !important; + } + .mpdf-doc .callout-title { + display: flex !important; + align-items: center !important; + gap: 7px !important; + padding: 7px 12px !important; + background: ${t.accentColor}28 !important; + border-bottom: 1px solid ${t.accentColor}33 !important; + font-family: ${n} !important; + font-size: 0.8em !important; + font-weight: 800 !important; + font-style: normal !important; + letter-spacing: 0.08em !important; + text-transform: uppercase !important; + color: ${t.accentColor} !important; + line-height: 1.3 !important; + } + .mpdf-doc .callout-icon { + display: inline-flex !important; + align-items: center !important; + flex-shrink: 0 !important; + width: 15px !important; + height: 15px !important; + color: ${t.accentColor} !important; + } + .mpdf-doc .callout-icon svg { + width: 15px !important; + height: 15px !important; + stroke: ${t.accentColor} !important; + fill: none !important; + stroke-width: 2 !important; + } + .mpdf-doc .callout-title-inner { + flex: 1 !important; + min-width: 0 !important; + } + .mpdf-doc .callout-fold { display: none !important; } + .mpdf-doc .callout-content { + padding: 9px 14px !important; + color: ${t.bodyColor} !important; + font-style: normal !important; + background: transparent !important; + } + .mpdf-doc .callout-content > p:first-child { margin-top: 0 !important; } + .mpdf-doc .callout-content > p:last-child { margin-bottom: 0 !important; } + /* Nested blockquotes inside callout content keep a subtler indent */ + .mpdf-doc .callout-content blockquote { + border-inline-start-color: ${t.accentColor}66 !important; + background: transparent !important; + } + + /* Mermaid diagrams \u2014 centre the SVG and prevent it overflowing the content + * column. The `:""} + + + +${C.join(` +`)} + +`;try{let R=window,z=R.require("@electron/remote");if(!z?.dialog)throw new Error("no remote");let M=await z.dialog.showSaveDialog({title:"Save PDF",defaultPath:(this.currentFile?.basename??"export")+".pdf",filters:[{name:"PDF",extensions:["pdf"]}]});if(M.canceled||!M.filePath){r();return}new N.Notice("Advanced PDF Export \u2014 generating PDF\u2026");let X=new Blob([A],{type:"text/html"}),te=URL.createObjectURL(X),L=new z.BrowserWindow({show:!1,webPreferences:{nodeIntegration:!1}});L.loadURL(te);let ue=!1,ye=()=>{URL.revokeObjectURL(te),L.close(),r()};L.webContents.once("did-fail-load",(oe,Fe,Ce)=>{ue||(ue=!0,new N.Notice("Advanced PDF Export \u2014 failed to load page: "+Ce),ye())}),L.webContents.once("did-finish-load",()=>{ue||(ue=!0,L.webContents.executeJavaScript("document.fonts.ready.then(() => true)").catch(()=>!0).then(()=>{let oe=e.pageSize==="Custom";return L.webContents.printToPDF({pageSize:oe?"A4":e.pageSize,landscape:!oe&&e.orientation==="landscape",preferCSSPageSize:oe,printBackground:!0,margins:{marginType:"none"}})}).then(async oe=>{if(e.includeOutline)try{oe=await Om(oe,Rm(o))}catch(Fe){console.warn("[advanced-pdf-export] outline injection failed:",Fe)}R.require("fs").writeFile(M.filePath,oe,Fe=>{Fe?new N.Notice("Advanced PDF Export \u2014 failed to save: "+Fe.message):new N.Notice("\u2713 PDF saved \u2014 "+M.filePath),ye()})}).catch(oe=>{new N.Notice("Advanced PDF Export \u2014 failed to render: "+oe.message),ye()}))})}catch{new N.Notice("Advanced PDF Export requires the Obsidian desktop app."),r()}}},Ts=class extends N.PluginSettingTab{plugin;dirty=!1;constructor(e,r){super(e,r),this.plugin=r}display(){this.dirty=!1,this.buildSettings()}hide(){this.dirty&&(this.dirty=!1,this.plugin.activeModal?.render(!0))}async markDirty(){this.dirty=!0,await this.plugin.saveSettings()}buildSettings(){let{containerEl:e}=this;e.empty();let r=this.plugin.settings,n=(m,y,w,S)=>{let D=new N.Setting(e).setName(m);return S&&D.setDesc(S),D.addText(T=>T.setValue(String(r[y])).onChange(C=>{let E=parseInt(C,10)||0;r[y]=w!==void 0?Math.max(w,E):E,this.markDirty()}))},o=(m,y)=>new N.Setting(e).setName(m).addColorPicker(w=>w.setValue(r[y]).onChange(S=>{r[y]=S,this.markDirty()}));new N.Setting(e).setName("Style Preset").setHeading(),new N.Setting(e).setName("Preset").setDesc("Pick a preset to configure the overall document style. Fine-tune any setting below.").addDropdown(m=>{Object.entries(Tn).forEach(([y,w])=>{m.addOption(y,w.name)}),m.setValue(r.preset).onChange(y=>{this.plugin.applyPreset(y),this.markDirty().then(()=>{this.buildSettings()})})}).addButton(m=>m.setButtonText("Reset Preset").setTooltip("Reset current preset to its default values").onClick(()=>{this.plugin.applyPreset(r.preset,!0),this.markDirty().then(()=>{this.buildSettings()})})),new N.Setting(e).setName("Page").setHeading();let i;new N.Setting(e).setName("Page size").addDropdown(m=>{Object.keys(Vi).forEach(y=>{m.addOption(y,y)}),m.addOption("Custom","Custom\u2026"),m.setValue(r.pageSize).onChange(y=>{r.pageSize=y,i.settingEl.toggleClass("mpdf-is-hidden",y!=="Custom"),this.markDirty()})}),i=new N.Setting(e).setName("Custom page size (mm)").setDesc("Width \xD7 Height in millimetres.").addText(m=>m.setPlaceholder("Width").setValue(String(r.customPageWidth)).onChange(y=>{r.customPageWidth=Math.max(10,parseFloat(y)||210),this.markDirty()})).addText(m=>m.setPlaceholder("Height").setValue(String(r.customPageHeight)).onChange(y=>{r.customPageHeight=Math.max(10,parseFloat(y)||297),this.markDirty()})),i.settingEl.toggleClass("mpdf-is-hidden",r.pageSize!=="Custom"),new N.Setting(e).setName("Orientation").addDropdown(m=>m.addOptions({portrait:"Portrait",landscape:"Landscape"}).setValue(r.orientation).onChange(y=>{r.orientation=y,this.markDirty()})),new N.Setting(e).setName("Margin & Frame").setHeading(),new N.Setting(e).setName("Margins").setDesc("Top \xB7 Bottom \xB7 Left \xB7 Right").addText(m=>m.setPlaceholder("Top").setValue(String(r.marginTop)).onChange(y=>{r.marginTop=parseInt(y,10)||0,this.markDirty()})).addText(m=>m.setPlaceholder("Bottom").setValue(String(r.marginBottom)).onChange(y=>{r.marginBottom=parseInt(y,10)||0,this.markDirty()})).addText(m=>m.setPlaceholder("Left").setValue(String(r.marginLeft)).onChange(y=>{r.marginLeft=parseInt(y,10)||0,this.markDirty()})).addText(m=>m.setPlaceholder("Right").setValue(String(r.marginRight)).onChange(y=>{r.marginRight=parseInt(y,10)||0,this.markDirty()}));let a,s,f,l,c=m=>{[a,s,f,l].forEach(y=>y.settingEl.toggleClass("mpdf-is-hidden",!m))};new N.Setting(e).setName("Enable frame").setDesc("Draws a border around the outer edge of every page.").addToggle(m=>m.setValue(r.frameEnabled).onChange(y=>{r.frameEnabled=y,c(y),this.markDirty()})),a=o("Frame color","frameColor"),s=n("Frame thickness (px)","frameThickness",1),f=n("Frame margin (px)","frameMargin",0,"Gap between the page edge and the frame, applied equally on all four sides."),l=new N.Setting(e).setName("Frame style").addDropdown(m=>m.addOptions({solid:"Solid",dashed:"Dashed",dotted:"Dotted",double:"Double",groove:"Groove",ridge:"Ridge"}).setValue(r.frameStyle).onChange(y=>{r.frameStyle=y,this.markDirty()})),c(r.frameEnabled),new N.Setting(e).setName("Typography").setHeading();let u;new N.Setting(e).setName("Font family").addDropdown(m=>m.addOptions({"Georgia, serif":"Georgia (Serif)","'Times New Roman', Times, serif":"Times New Roman","'Palatino Linotype', Palatino, serif":"Palatino","Arial, sans-serif":"Arial","'Helvetica Neue', Helvetica, sans-serif":"Helvetica","'Trebuchet MS', sans-serif":"Trebuchet","'Courier New', monospace":"Courier New",__custom__:"Custom\u2026"}).setValue(r.fontFamily).onChange(y=>{r.fontFamily=y,u.settingEl.toggleClass("mpdf-is-hidden",y!=="__custom__"),this.markDirty()})),u=new N.Setting(e).setName("Custom font name").setDesc('CSS font-family value \u2014 e.g. "Inter, sans-serif". The font must be installed on your system.').addText(m=>m.setPlaceholder("e.g. Inter, sans-serif").setValue(r.customFontName).onChange(y=>{r.customFontName=y,this.markDirty()})),u.settingEl.toggleClass("mpdf-is-hidden",r.fontFamily!=="__custom__"),new N.Setting(e).setName("Font size (px)").addDropdown(m=>{["10","11","12","13","14","15","16"].forEach(y=>{m.addOption(y,y+"px")}),m.setValue(String(r.fontSize)).onChange(y=>{r.fontSize=parseInt(y),this.markDirty()})}),new N.Setting(e).setName("Code font size").addDropdown(m=>m.addOptions({"0.75":"0.75em","0.80":"0.80em","0.82":"0.82em","0.85":"0.85em","0.88":"0.88em","0.90":"0.90em","1.0":"1.00em"}).setValue(String(r.codeFontSize)).onChange(y=>{r.codeFontSize=parseFloat(y),this.markDirty()})),new N.Setting(e).setName("Line height").addDropdown(m=>m.addOptions({"1.4":"Tight (1.4)","1.6":"Compact (1.6)","1.75":"Normal (1.75)","1.85":"Relaxed (1.85)","2.0":"Double (2.0)"}).setValue(String(r.lineHeight)).onChange(y=>{r.lineHeight=parseFloat(y),this.markDirty()})),new N.Setting(e).setName("Paragraph spacing").addDropdown(m=>m.addOptions({0:"None","0.3":"Tight (0.3em)","0.5":"Normal (0.5em)","0.65":"Relaxed (0.65em)","1.0":"Wide (1em)"}).setValue(String(r.paragraphSpacing)).onChange(y=>{r.paragraphSpacing=parseFloat(y),this.markDirty()})),new N.Setting(e).setName("Heading scale").setDesc("Multiplier applied to all heading sizes.").addDropdown(m=>m.addOptions({"0.8":"Small (0.8\xD7)","0.88":"0.88\xD7","0.9":"Compact (0.9\xD7)","0.95":"0.95\xD7","1.0":"Normal (1.0\xD7)","1.05":"1.05\xD7","1.1":"Large (1.1\xD7)","1.2":"XLarge (1.2\xD7)"}).setValue(String(r.headingScale)).onChange(y=>{r.headingScale=parseFloat(y),this.markDirty()})),new N.Setting(e).setName("Background").setHeading();let d,p,h,b,F,x=m=>{d.settingEl.toggleClass("mpdf-is-hidden",m),[p,h,b,F].forEach(y=>y.settingEl.toggleClass("mpdf-is-hidden",!m))};new N.Setting(e).setName("Use image background").setDesc("When on, a background image is used instead of the solid background color.").addToggle(m=>m.setValue(r.backgroundImageEnabled).onChange(y=>{r.backgroundImageEnabled=y,x(y),this.markDirty()})),d=new N.Setting(e).setName("Page background color").addColorPicker(m=>m.setValue(r.pageBackground).onChange(y=>{r.pageBackground=y,this.markDirty()})),p=new N.Setting(e).setName("Background image").setDesc("Vault-relative path or https:// URL.").addText(m=>m.setPlaceholder("assets/background.png").setValue(r.backgroundImagePath).onChange(y=>{r.backgroundImagePath=y,this.markDirty()})),h=new N.Setting(e).setName("Fit").addDropdown(m=>m.addOptions({cover:"Cover (fill, crop edges)",contain:"Contain (fit, show gaps)",fill:"Fill (stretch to exact size)",tile:"Tile (repeat)"}).setValue(r.backgroundImageSize).onChange(y=>{r.backgroundImageSize=y,this.markDirty()})),b=new N.Setting(e).setName("Scope").setDesc("Full page includes header and footer bands. Content area only restricts the background to the text zone between them.").addDropdown(m=>m.addOptions({"full-page":"Full page","content-only":"Content area only"}).setValue(r.backgroundImageScope).onChange(y=>{r.backgroundImageScope=y,this.markDirty()})),F=new N.Setting(e).setName("Opacity").addDropdown(m=>m.addOptions({"0.05":"5%","0.1":"10%","0.15":"15%","0.2":"20%","0.3":"30%","0.4":"40%","0.5":"50%","0.6":"60%","0.7":"70%","0.8":"80%","0.9":"90%",1:"100%"}).setValue(String(r.backgroundImageOpacity)).onChange(y=>{r.backgroundImageOpacity=parseFloat(y),this.markDirty()})),x(r.backgroundImageEnabled),new N.Setting(e).setName("Colors").setHeading(),o("Accent color","accentColor"),o("Body text color","bodyColor"),o("Heading color","headingColor"),o("Blockquote background","blockquoteBg"),o("Blockquote border","blockquoteBorderColor"),o("Table header background","tableHeaderBg"),o("Code background","codeBackground"),new N.Setting(e).setName("Code syntax theme").setDesc('Independent of your Obsidian theme. "None" uses the body text color and code background above with no highlighting.').addDropdown(m=>{let y={};for(let[w,S]of Object.entries(Cs))y[w]=S.name;m.addOptions(y).setValue(r.codeTheme).onChange(w=>{r.codeTheme=w,this.markDirty()})}),new N.Setting(e).setName("Header").setHeading(),new N.Setting(e).setName("Show header").addToggle(m=>m.setValue(r.showHeader).onChange(y=>{r.showHeader=y,this.markDirty()})),new N.Setting(e).setName("Show on first page").setDesc("When off, the header is hidden on page 1. Useful for title pages.").addToggle(m=>m.setValue(r.showHeaderOnFirstPage).onChange(y=>{r.showHeaderOnFirstPage=y,this.markDirty()})),new N.Setting(e).setName("Header text").addText(m=>m.setValue(r.headerText).onChange(y=>{r.headerText=y,this.markDirty()})),new N.Setting(e).setName("Alignment").addDropdown(m=>m.addOptions({left:"Left",center:"Center",right:"Right"}).setValue(r.headerAlignment).onChange(y=>{r.headerAlignment=y,this.markDirty()})),n("Font size (px)","headerFontSize",1),n("Height (px)","headerHeight",0,"Explicit band height (0 = auto)."),o("Font color","headerFontColor"),new N.Setting(e).setName("Border").setDesc("Separator line below the header.").addToggle(m=>m.setValue(r.showHeaderBorder).onChange(y=>{r.showHeaderBorder=y,this.markDirty()})),new N.Setting(e).setName("Image").setDesc("Vault-relative path or https:// URL. Fills the header band as a background banner.").addText(m=>m.setPlaceholder("assets/header-banner.png").setValue(r.headerImagePath).onChange(y=>{r.headerImagePath=y,this.markDirty()})),n("Image left/right margin (px)","headerImageMargin",0,"Insets the banner from the left and right page edges."),new N.Setting(e).setName("Footer").setHeading(),new N.Setting(e).setName("Show footer").addToggle(m=>m.setValue(r.showFooter).onChange(y=>{r.showFooter=y,this.markDirty()})),new N.Setting(e).setName("Show on first page").setDesc("When off, the footer and page numbers are hidden on page 1. Page numbering starts from page 2.").addToggle(m=>m.setValue(r.showFooterOnFirstPage).onChange(y=>{r.showFooterOnFirstPage=y,this.markDirty()})),new N.Setting(e).setName("Footer text").addText(m=>m.setValue(r.footerText).onChange(y=>{r.footerText=y,this.markDirty()})),new N.Setting(e).setName("Alignment").addDropdown(m=>m.addOptions({left:"Left",center:"Center",right:"Right"}).setValue(r.footerTextAlignment).onChange(y=>{r.footerTextAlignment=y,this.markDirty()})),n("Font size (px)","footerFontSize",1),n("Height (px)","footerHeight",0,"Explicit band height (0 = auto)."),o("Font color","footerFontColor"),new N.Setting(e).setName("Border").setDesc("Separator line above the footer.").addToggle(m=>m.setValue(r.showFooterBorder).onChange(y=>{r.showFooterBorder=y,this.markDirty()})),new N.Setting(e).setName("Image").setDesc("Vault-relative path or https:// URL. Fills the footer band as a background banner.").addText(m=>m.setPlaceholder("assets/footer-banner.png").setValue(r.footerImagePath).onChange(y=>{r.footerImagePath=y,this.markDirty()})),n("Image left/right margin (px)","footerImageMargin",0,"Insets the banner from the left and right page edges."),new N.Setting(e).setName("Show page numbers").addToggle(m=>m.setValue(r.showPageNumbers).onChange(y=>{r.showPageNumbers=y,this.markDirty()})),new N.Setting(e).setName("Page number position").addDropdown(m=>m.addOptions({left:"Left",center:"Center",right:"Right"}).setValue(r.pageNumberPosition).onChange(y=>{r.pageNumberPosition=y,this.markDirty()})),new N.Setting(e).setName("Page number format").setDesc('Use {{current}} and {{total}} as placeholders, e.g. "Page {{current}} of {{total}}", "{{current}}/{{total}}", or just "{{current}}".').addText(m=>m.setPlaceholder("{{current}} / {{total}}").setValue(r.pageNumberFormat).onChange(y=>{r.pageNumberFormat=y,this.markDirty()})),new N.Setting(e).setName("Page number start").setDesc("Number assigned to the first visible page number.").addText(m=>m.setValue(String(r.pageNumberStart)).onChange(y=>{r.pageNumberStart=parseInt(y,10)||1,this.markDirty()})),new N.Setting(e).setName("Behaviour").setHeading(),new N.Setting(e).setName("Hide frontmatter").setDesc("Strip the YAML frontmatter block (--- \u2026 ---) from the preview and exported PDF.").addToggle(m=>m.setValue(r.hideFrontmatter).onChange(y=>{r.hideFrontmatter=y,this.markDirty()})),new N.Setting(e).setName("Include file name as title").setDesc("Prepend the note's file name as an H1 heading at the top of the PDF.").addToggle(m=>m.setValue(r.includeFilenameAsTitle).onChange(y=>{r.includeFilenameAsTitle=y,this.markDirty()})),new N.Setting(e).setName("Underline links").setDesc("Applies to both internal and external links.").addToggle(m=>m.setValue(r.linkUnderline).onChange(y=>{r.linkUnderline=y,this.markDirty()})),new N.Setting(e).setName("Auto page break before H1").addToggle(m=>m.setValue(r.autoBreakH1).onChange(y=>{r.autoBreakH1=y,this.markDirty()})),new N.Setting(e).setName("Auto page break before H2").addToggle(m=>m.setValue(r.autoBreakH2).onChange(y=>{r.autoBreakH2=y,this.markDirty()})),new N.Setting(e).setName("H1 bottom border").addToggle(m=>m.setValue(r.h1BorderBottom).onChange(y=>{r.h1BorderBottom=y,this.markDirty()})),new N.Setting(e).setName("H2 bottom border").addToggle(m=>m.setValue(r.h2BorderBottom).onChange(y=>{r.h2BorderBottom=y,this.markDirty()})),new N.Setting(e).setName("Center H1").addToggle(m=>m.setValue(r.centerH1).onChange(y=>{r.centerH1=y,this.markDirty()})),new N.Setting(e).setName("Striped table rows").addToggle(m=>m.setValue(r.tableStriped).onChange(y=>{r.tableStriped=y,this.markDirty()})),new N.Setting(e).setName("Include PDF outline (bookmarks)").setDesc("Embeds a bookmark tree into the exported PDF. Most PDF readers display it in a side panel for quick navigation.").addToggle(m=>m.setValue(r.includeOutline).onChange(y=>{r.includeOutline=y,this.markDirty()}))}}; +/*! Bundled license information: + +tslib/tslib.es6.js: + (*! ***************************************************************************** + Copyright (c) Microsoft Corporation. + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** *) +*/ diff --git a/main.ts b/main.ts index 260c5a4..4478263 100644 --- a/main.ts +++ b/main.ts @@ -114,8 +114,8 @@ interface PDFExportSettings extends DocStyle { showPageNumbers: boolean; pageNumberPosition: "center" | "left" | "right"; pageNumberStart: number; - /** Template for rendering the page number string. Supports {{page_current}} - * and {{page_total}} placeholders, e.g. "Page {{page_current}} of {{page_total}}". */ + /** Template for rendering the page number string. Supports {{current}} + * and {{total}} placeholders, e.g. "Page {{current}} of {{total}}". */ pageNumberFormat: string; showHeaderOnFirstPage: boolean; showFooterOnFirstPage: boolean; @@ -387,7 +387,7 @@ const DEFAULT_SETTINGS: PDFExportSettings = { showPageNumbers: true, pageNumberPosition: "right", pageNumberStart: 1, - pageNumberFormat: "{{page_current}} / {{page_total}}", + pageNumberFormat: "{{current}} / {{total}}", showHeaderOnFirstPage: true, showFooterOnFirstPage: true, headerAlignment: "right", @@ -1658,14 +1658,14 @@ function paginateEl( // ─── Page layout builder ────────────────────────────────────────────────────── -/** Resolves a page-number format template by substituting the {{page_current}} - * and {{page_total}} placeholders with the given values. Falls back to the +/** Resolves a page-number format template by substituting the {{current}} + * and {{total}} placeholders with the given values. Falls back to the * default "current / total" template when the format is empty. */ function resolvePageNumberFormat(format: string, current: number, total: number): string { - const template = format && format.trim() ? format : "{{page_current}} / {{page_total}}"; + const template = format && format.trim() ? format : "{{current}} / {{total}}"; return template - .replace(/\{\{\s*page_current\s*\}\}/g, String(current)) - .replace(/\{\{\s*page_total\s*\}\}/g, String(total)); + .replace(/\{\{\s*current\s*\}\}/g, String(current)) + .replace(/\{\{\s*total\s*\}\}/g, String(total)); } /** Converts paginated page-node arrays into fully-resolved PageLayout objects, @@ -3223,9 +3223,9 @@ class PDFExportSettingTab extends PluginSettingTab { ); new Setting(containerEl) .setName("Page number format") - .setDesc("Use {{page_current}} and {{page_total}} as placeholders, e.g. \"Page {{page_current}} of {{page_total}}\", \"{{page_current}}/{{page_total}}\", or just \"{{page_current}}\".") + .setDesc("Use {{current}} and {{total}} as placeholders, e.g. \"Page {{current}} of {{total}}\", \"{{current}}/{{total}}\", or just \"{{current}}\".") .addText((t) => - t.setPlaceholder("{{page_current}} / {{page_total}}").setValue(s.pageNumberFormat) + t.setPlaceholder("{{current}} / {{total}}").setValue(s.pageNumberFormat) .onChange((v) => { s.pageNumberFormat = v; void this.markDirty(); }), ); new Setting(containerEl) diff --git a/manifest.json b/manifest.json index c7c2cfa..0bafd28 100644 --- a/manifest.json +++ b/manifest.json @@ -1,7 +1,7 @@ { "id": "advanced-pdf-export", "name": "Advanced PDF Export", - "version": "4.1.8", + "version": "4.2.0", "minAppVersion": "1.11.1", "description": "Export notes as pixel-perfect PDFs with live preview, style presets, manual page breaks, tables, and full layout control.", "author": "ShrekBytes", diff --git a/package-lock.json b/package-lock.json index 20d12f2..1a66401 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "obsidian-advanced-pdf-export", - "version": "4.1.8", + "version": "4.2.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "obsidian-advanced-pdf-export", - "version": "4.1.8", + "version": "4.2.0", "dependencies": { "pdf-lib": "^1.17.1" }, diff --git a/package.json b/package.json index c65712f..571f369 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "obsidian-advanced-pdf-export", - "version": "4.1.8", + "version": "4.2.0", "description": "Obsidian plugin for advanced PDF export", "author": "ShrekBytes", "repository": { From 4da2511073436b0e0a8ed647647d15c638139f4c Mon Sep 17 00:00:00 2001 From: Walid Date: Sun, 12 Jul 2026 19:35:27 +0600 Subject: [PATCH 2/3] refactor: split main.ts into modular components --- data.json | 36 - esbuild.config.mjs | 2 +- main.js | 112 +- main.ts | 3287 ------------------------------------------- manifest.json | 2 +- package-lock.json | 4 +- package.json | 5 +- src/css-builder.ts | 578 ++++++++ src/export-modal.ts | 972 +++++++++++++ src/main.ts | 126 ++ src/markdown.ts | 261 ++++ src/paginator.ts | 655 +++++++++ src/settings-tab.ts | 453 ++++++ src/settings.ts | 354 +++++ tsconfig.json | 2 +- 15 files changed, 3464 insertions(+), 3385 deletions(-) delete mode 100644 data.json delete mode 100644 main.ts create mode 100644 src/css-builder.ts create mode 100644 src/export-modal.ts create mode 100644 src/main.ts create mode 100644 src/markdown.ts create mode 100644 src/paginator.ts create mode 100644 src/settings-tab.ts create mode 100644 src/settings.ts diff --git a/data.json b/data.json deleted file mode 100644 index 3d18e6a..0000000 --- a/data.json +++ /dev/null @@ -1,36 +0,0 @@ -{ - "pageSize": "A4", - "orientation": "portrait", - "preset": "colorful", - "name": "Colorful", - "fontFamily": "Georgia, serif", - "fontSize": 13, - "lineHeight": 1.85, - "paragraphSpacing": 0.65, - "headingScale": 1.05, - "accentColor": "#e84393", - "bodyColor": "#1a1a2e", - "headingColor": "#2d0a4e", - "h1BorderBottom": false, - "h2BorderBottom": false, - "centerH1": false, - "blockquoteBg": "#fdf0f8", - "blockquoteBorderColor": "#e84393", - "codeBackground": "#f0eaff", - "codeFontSize": 0.85, - "tableHeaderBg": "#2d0a4e", - "tableStriped": true, - "marginTop": 20, - "marginBottom": 20, - "marginLeft": 25, - "marginRight": 25, - "headerText": "", - "footerText": "", - "showHeader": true, - "showFooter": false, - "showPageNumbers": false, - "pageNumberPosition": "right", - "autoBreakH1": false, - "autoBreakH2": false, - "previewScale": 0.8 -} \ No newline at end of file diff --git a/esbuild.config.mjs b/esbuild.config.mjs index afb9ffe..3c1c4a9 100644 --- a/esbuild.config.mjs +++ b/esbuild.config.mjs @@ -19,7 +19,7 @@ const external = [ ]; const ctx = await esbuild.context({ - entryPoints: ["main.ts"], + entryPoints: ["src/main.ts"], bundle: true, outfile: "main.js", external, diff --git a/main.js b/main.js index b069885..c523745 100644 --- a/main.js +++ b/main.js @@ -1,42 +1,4 @@ -var td=Object.create;var Go=Object.defineProperty;var rd=Object.getOwnPropertyDescriptor;var nd=Object.getOwnPropertyNames;var od=Object.getPrototypeOf,id=Object.prototype.hasOwnProperty;var He=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),ad=(t,e)=>{for(var r in e)Go(t,r,{get:e[r],enumerable:!0})},Es=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of nd(e))!id.call(t,o)&&o!==r&&Go(t,o,{get:()=>e[o],enumerable:!(n=rd(e,o))||n.enumerable});return t};var Ko=(t,e,r)=>(r=t!=null?td(od(t)):{},Es(e||!t||!t.__esModule?Go(r,"default",{value:t,enumerable:!0}):r,t)),sd=t=>Es(Go({},"__esModule",{value:!0}),t);var It=He(Ke=>{"use strict";var vd=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Int32Array<"u";function md(t,e){return Object.prototype.hasOwnProperty.call(t,e)}Ke.assign=function(t){for(var e=Array.prototype.slice.call(arguments,1);e.length;){var r=e.shift();if(r){if(typeof r!="object")throw new TypeError(r+"must be non-object");for(var n in r)md(r,n)&&(t[n]=r[n])}}return t};Ke.shrinkBuf=function(t,e){return t.length===e?t:t.subarray?t.subarray(0,e):(t.length=e,t)};var gd={arraySet:function(t,e,r,n,o){if(e.subarray&&t.subarray){t.set(e.subarray(r,r+n),o);return}for(var i=0;i{"use strict";var bd=It(),xd=4,tl=0,rl=1,Fd=2;function Kr(t){for(var e=t.length;--e>=0;)t[e]=0}var wd=0,ll=1,Sd=2,Pd=3,Dd=258,oa=29,Hn=256,In=Hn+1+oa,Gr=30,ia=19,fl=2*In+1,yr=15,_i=16,Cd=7,aa=256,cl=16,ul=17,dl=18,ra=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],$o=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],kd=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],hl=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],Td=512,zt=new Array((In+2)*2);Kr(zt);var Mn=new Array(Gr*2);Kr(Mn);var zn=new Array(Td);Kr(zn);var jn=new Array(Dd-Pd+1);Kr(jn);var sa=new Array(oa);Kr(sa);var ei=new Array(Gr);Kr(ei);function $i(t,e,r,n,o){this.static_tree=t,this.extra_bits=e,this.extra_base=r,this.elems=n,this.max_length=o,this.has_stree=t&&t.length}var pl,vl,ml;function ea(t,e){this.dyn_tree=t,this.max_code=0,this.stat_desc=e}function gl(t){return t<256?zn[t]:zn[256+(t>>>7)]}function Ln(t,e){t.pending_buf[t.pending++]=e&255,t.pending_buf[t.pending++]=e>>>8&255}function _e(t,e,r){t.bi_valid>_i-r?(t.bi_buf|=e<>_i-t.bi_valid,t.bi_valid+=r-_i):(t.bi_buf|=e<>>=1,r<<=1;while(--e>0);return r>>>1}function Ed(t){t.bi_valid===16?(Ln(t,t.bi_buf),t.bi_buf=0,t.bi_valid=0):t.bi_valid>=8&&(t.pending_buf[t.pending++]=t.bi_buf&255,t.bi_buf>>=8,t.bi_valid-=8)}function Ad(t,e){var r=e.dyn_tree,n=e.max_code,o=e.stat_desc.static_tree,i=e.stat_desc.has_stree,a=e.stat_desc.extra_bits,s=e.stat_desc.extra_base,f=e.stat_desc.max_length,l,c,u,d,p,h,b=0;for(d=0;d<=yr;d++)t.bl_count[d]=0;for(r[t.heap[t.heap_max]*2+1]=0,l=t.heap_max+1;lf&&(d=f,b++),r[c*2+1]=d,!(c>n)&&(t.bl_count[d]++,p=0,c>=s&&(p=a[c-s]),h=r[c*2],t.opt_len+=h*(d+p),i&&(t.static_len+=h*(o[c*2+1]+p)));if(b!==0){do{for(d=f-1;t.bl_count[d]===0;)d--;t.bl_count[d]--,t.bl_count[d+1]+=2,t.bl_count[f]--,b-=2}while(b>0);for(d=f;d!==0;d--)for(c=t.bl_count[d];c!==0;)u=t.heap[--l],!(u>n)&&(r[u*2+1]!==d&&(t.opt_len+=(d-r[u*2+1])*r[u*2],r[u*2+1]=d),c--)}}function bl(t,e,r){var n=new Array(yr+1),o=0,i,a;for(i=1;i<=yr;i++)n[i]=o=o+r[i-1]<<1;for(a=0;a<=e;a++){var s=t[a*2+1];s!==0&&(t[a*2]=yl(n[s]++,s))}}function Rd(){var t,e,r,n,o,i=new Array(yr+1);for(r=0,n=0;n>=7;n8?Ln(t,t.bi_buf):t.bi_valid>0&&(t.pending_buf[t.pending++]=t.bi_buf),t.bi_buf=0,t.bi_valid=0}function Od(t,e,r,n){Fl(t),n&&(Ln(t,r),Ln(t,~r)),bd.arraySet(t.pending_buf,t.window,e,r,t.pending),t.pending+=r}function nl(t,e,r,n){var o=e*2,i=r*2;return t[o]>1;a>=1;a--)ta(t,r,a);l=i;do a=t.heap[1],t.heap[1]=t.heap[t.heap_len--],ta(t,r,1),s=t.heap[1],t.heap[--t.heap_max]=a,t.heap[--t.heap_max]=s,r[l*2]=r[a*2]+r[s*2],t.depth[l]=(t.depth[a]>=t.depth[s]?t.depth[a]:t.depth[s])+1,r[a*2+1]=r[s*2+1]=l,t.heap[1]=l++,ta(t,r,1);while(t.heap_len>=2);t.heap[--t.heap_max]=t.heap[1],Ad(t,e),bl(r,f,t.bl_count)}function il(t,e,r){var n,o=-1,i,a=e[0*2+1],s=0,f=7,l=4;for(a===0&&(f=138,l=3),e[(r+1)*2+1]=65535,n=0;n<=r;n++)i=a,a=e[(n+1)*2+1],!(++s=3&&t.bl_tree[hl[e]*2+1]===0;e--);return t.opt_len+=3*(e+1)+5+5+4,e}function Nd(t,e,r,n){var o;for(_e(t,e-257,5),_e(t,r-1,5),_e(t,n-4,4),o=0;o>>=1)if(e&1&&t.dyn_ltree[r*2]!==0)return tl;if(t.dyn_ltree[9*2]!==0||t.dyn_ltree[10*2]!==0||t.dyn_ltree[13*2]!==0)return rl;for(r=32;r0?(t.strm.data_type===Fd&&(t.strm.data_type=Md(t)),na(t,t.l_desc),na(t,t.d_desc),a=Bd(t),o=t.opt_len+3+7>>>3,i=t.static_len+3+7>>>3,i<=o&&(o=i)):o=i=r+5,r+4<=o&&e!==-1?wl(t,e,r,n):t.strategy===xd||i===o?(_e(t,(ll<<1)+(n?1:0),3),ol(t,zt,Mn)):(_e(t,(Sd<<1)+(n?1:0),3),Nd(t,t.l_desc.max_code+1,t.d_desc.max_code+1,a+1),ol(t,t.dyn_ltree,t.dyn_dtree)),xl(t),n&&Fl(t)}function Ld(t,e,r){return t.pending_buf[t.d_buf+t.last_lit*2]=e>>>8&255,t.pending_buf[t.d_buf+t.last_lit*2+1]=e&255,t.pending_buf[t.l_buf+t.last_lit]=r&255,t.last_lit++,e===0?t.dyn_ltree[r*2]++:(t.matches++,e--,t.dyn_ltree[(jn[r]+Hn+1)*2]++,t.dyn_dtree[gl(e)*2]++),t.last_lit===t.lit_bufsize-1}Xr._tr_init=Id;Xr._tr_stored_block=wl;Xr._tr_flush_block=jd;Xr._tr_tally=Ld;Xr._tr_align=zd});var la=He((_m,Pl)=>{"use strict";function Hd(t,e,r,n){for(var o=t&65535|0,i=t>>>16&65535|0,a=0;r!==0;){a=r>2e3?2e3:r,r-=a;do o=o+e[n++]|0,i=i+o|0;while(--a);o%=65521,i%=65521}return o|i<<16|0}Pl.exports=Hd});var fa=He(($m,Dl)=>{"use strict";function Ud(){for(var t,e=[],r=0;r<256;r++){t=r;for(var n=0;n<8;n++)t=t&1?3988292384^t>>>1:t>>>1;e[r]=t}return e}var Vd=Ud();function qd(t,e,r,n){var o=Vd,i=n+r;t^=-1;for(var a=n;a>>8^o[(t^e[a])&255];return t^-1}Dl.exports=qd});var ti=He((eg,Cl)=>{"use strict";Cl.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}});var Ml=He(kt=>{"use strict";var Xe=It(),at=Sl(),Al=la(),Kt=fa(),Wd=ti(),wr=0,Gd=1,Kd=3,Qt=4,kl=5,Ct=0,Tl=1,st=-2,Xd=-3,ca=-5,Zd=-1,Yd=1,ri=2,Jd=3,Qd=4,_d=0,$d=2,ai=8,eh=9,th=15,rh=8,nh=29,oh=256,da=oh+1+nh,ih=30,ah=19,sh=2*da+1,lh=15,de=3,Yt=258,mt=Yt+de+1,fh=32,si=42,ha=69,ni=73,oi=91,ii=103,br=113,Vn=666,Ne=1,qn=2,xr=3,Jr=4,ch=3;function Jt(t,e){return t.msg=Wd[e],e}function El(t){return(t<<1)-(t>4?9:0)}function Zt(t){for(var e=t.length;--e>=0;)t[e]=0}function Xt(t){var e=t.state,r=e.pending;r>t.avail_out&&(r=t.avail_out),r!==0&&(Xe.arraySet(t.output,e.pending_buf,e.pending_out,r,t.next_out),t.next_out+=r,e.pending_out+=r,t.total_out+=r,t.avail_out-=r,e.pending-=r,e.pending===0&&(e.pending_out=0))}function je(t,e){at._tr_flush_block(t,t.block_start>=0?t.block_start:-1,t.strstart-t.block_start,e),t.block_start=t.strstart,Xt(t.strm)}function he(t,e){t.pending_buf[t.pending++]=e}function Un(t,e){t.pending_buf[t.pending++]=e>>>8&255,t.pending_buf[t.pending++]=e&255}function uh(t,e,r,n){var o=t.avail_in;return o>n&&(o=n),o===0?0:(t.avail_in-=o,Xe.arraySet(e,t.input,t.next_in,o,r),t.state.wrap===1?t.adler=Al(t.adler,e,o,r):t.state.wrap===2&&(t.adler=Kt(t.adler,e,o,r)),t.next_in+=o,t.total_in+=o,o)}function Rl(t,e){var r=t.max_chain_length,n=t.strstart,o,i,a=t.prev_length,s=t.nice_match,f=t.strstart>t.w_size-mt?t.strstart-(t.w_size-mt):0,l=t.window,c=t.w_mask,u=t.prev,d=t.strstart+Yt,p=l[n+a-1],h=l[n+a];t.prev_length>=t.good_match&&(r>>=2),s>t.lookahead&&(s=t.lookahead);do if(o=e,!(l[o+a]!==h||l[o+a-1]!==p||l[o]!==l[n]||l[++o]!==l[n+1])){n+=2,o++;do;while(l[++n]===l[++o]&&l[++n]===l[++o]&&l[++n]===l[++o]&&l[++n]===l[++o]&&l[++n]===l[++o]&&l[++n]===l[++o]&&l[++n]===l[++o]&&l[++n]===l[++o]&&na){if(t.match_start=e,a=i,i>=s)break;p=l[n+a-1],h=l[n+a]}}while((e=u[e&c])>f&&--r!==0);return a<=t.lookahead?a:t.lookahead}function Fr(t){var e=t.w_size,r,n,o,i,a;do{if(i=t.window_size-t.lookahead-t.strstart,t.strstart>=e+(e-mt)){Xe.arraySet(t.window,t.window,e,e,0),t.match_start-=e,t.strstart-=e,t.block_start-=e,n=t.hash_size,r=n;do o=t.head[--r],t.head[r]=o>=e?o-e:0;while(--n);n=e,r=n;do o=t.prev[--r],t.prev[r]=o>=e?o-e:0;while(--n);i+=e}if(t.strm.avail_in===0)break;if(n=uh(t.strm,t.window,t.strstart+t.lookahead,i),t.lookahead+=n,t.lookahead+t.insert>=de)for(a=t.strstart-t.insert,t.ins_h=t.window[a],t.ins_h=(t.ins_h<t.pending_buf_size-5&&(r=t.pending_buf_size-5);;){if(t.lookahead<=1){if(Fr(t),t.lookahead===0&&e===wr)return Ne;if(t.lookahead===0)break}t.strstart+=t.lookahead,t.lookahead=0;var n=t.block_start+r;if((t.strstart===0||t.strstart>=n)&&(t.lookahead=t.strstart-n,t.strstart=n,je(t,!1),t.strm.avail_out===0)||t.strstart-t.block_start>=t.w_size-mt&&(je(t,!1),t.strm.avail_out===0))return Ne}return t.insert=0,e===Qt?(je(t,!0),t.strm.avail_out===0?xr:Jr):(t.strstart>t.block_start&&(je(t,!1),t.strm.avail_out===0),Ne)}function ua(t,e){for(var r,n;;){if(t.lookahead=de&&(t.ins_h=(t.ins_h<=de)if(n=at._tr_tally(t,t.strstart-t.match_start,t.match_length-de),t.lookahead-=t.match_length,t.match_length<=t.max_lazy_match&&t.lookahead>=de){t.match_length--;do t.strstart++,t.ins_h=(t.ins_h<=de&&(t.ins_h=(t.ins_h<4096)&&(t.match_length=de-1)),t.prev_length>=de&&t.match_length<=t.prev_length){o=t.strstart+t.lookahead-de,n=at._tr_tally(t,t.strstart-1-t.prev_match,t.prev_length-de),t.lookahead-=t.prev_length-1,t.prev_length-=2;do++t.strstart<=o&&(t.ins_h=(t.ins_h<=de&&t.strstart>0&&(o=t.strstart-1,n=a[o],n===a[++o]&&n===a[++o]&&n===a[++o])){i=t.strstart+Yt;do;while(n===a[++o]&&n===a[++o]&&n===a[++o]&&n===a[++o]&&n===a[++o]&&n===a[++o]&&n===a[++o]&&n===a[++o]&&ot.lookahead&&(t.match_length=t.lookahead)}if(t.match_length>=de?(r=at._tr_tally(t,1,t.match_length-de),t.lookahead-=t.match_length,t.strstart+=t.match_length,t.match_length=0):(r=at._tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++),r&&(je(t,!1),t.strm.avail_out===0))return Ne}return t.insert=0,e===Qt?(je(t,!0),t.strm.avail_out===0?xr:Jr):t.last_lit&&(je(t,!1),t.strm.avail_out===0)?Ne:qn}function ph(t,e){for(var r;;){if(t.lookahead===0&&(Fr(t),t.lookahead===0)){if(e===wr)return Ne;break}if(t.match_length=0,r=at._tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++,r&&(je(t,!1),t.strm.avail_out===0))return Ne}return t.insert=0,e===Qt?(je(t,!0),t.strm.avail_out===0?xr:Jr):t.last_lit&&(je(t,!1),t.strm.avail_out===0)?Ne:qn}function Dt(t,e,r,n,o){this.good_length=t,this.max_lazy=e,this.nice_length=r,this.max_chain=n,this.func=o}var Yr;Yr=[new Dt(0,0,0,0,dh),new Dt(4,4,8,4,ua),new Dt(4,5,16,8,ua),new Dt(4,6,32,32,ua),new Dt(4,4,16,16,Zr),new Dt(8,16,32,32,Zr),new Dt(8,16,128,128,Zr),new Dt(8,32,128,256,Zr),new Dt(32,128,258,1024,Zr),new Dt(32,258,258,4096,Zr)];function vh(t){t.window_size=2*t.w_size,Zt(t.head),t.max_lazy_match=Yr[t.level].max_lazy,t.good_match=Yr[t.level].good_length,t.nice_match=Yr[t.level].nice_length,t.max_chain_length=Yr[t.level].max_chain,t.strstart=0,t.block_start=0,t.lookahead=0,t.insert=0,t.match_length=t.prev_length=de-1,t.match_available=0,t.ins_h=0}function mh(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=ai,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new Xe.Buf16(sh*2),this.dyn_dtree=new Xe.Buf16((2*ih+1)*2),this.bl_tree=new Xe.Buf16((2*ah+1)*2),Zt(this.dyn_ltree),Zt(this.dyn_dtree),Zt(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Xe.Buf16(lh+1),this.heap=new Xe.Buf16(2*da+1),Zt(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Xe.Buf16(2*da+1),Zt(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function Ol(t){var e;return!t||!t.state?Jt(t,st):(t.total_in=t.total_out=0,t.data_type=$d,e=t.state,e.pending=0,e.pending_out=0,e.wrap<0&&(e.wrap=-e.wrap),e.status=e.wrap?si:br,t.adler=e.wrap===2?0:1,e.last_flush=wr,at._tr_init(e),Ct)}function Bl(t){var e=Ol(t);return e===Ct&&vh(t.state),e}function gh(t,e){return!t||!t.state||t.state.wrap!==2?st:(t.state.gzhead=e,Ct)}function Nl(t,e,r,n,o,i){if(!t)return st;var a=1;if(e===Zd&&(e=6),n<0?(a=0,n=-n):n>15&&(a=2,n-=16),o<1||o>eh||r!==ai||n<8||n>15||e<0||e>9||i<0||i>Qd)return Jt(t,st);n===8&&(n=9);var s=new mh;return t.state=s,s.strm=t,s.wrap=a,s.gzhead=null,s.w_bits=n,s.w_size=1<kl||e<0)return t?Jt(t,st):st;if(n=t.state,!t.output||!t.input&&t.avail_in!==0||n.status===Vn&&e!==Qt)return Jt(t,t.avail_out===0?ca:st);if(n.strm=t,r=n.last_flush,n.last_flush=e,n.status===si)if(n.wrap===2)t.adler=0,he(n,31),he(n,139),he(n,8),n.gzhead?(he(n,(n.gzhead.text?1:0)+(n.gzhead.hcrc?2:0)+(n.gzhead.extra?4:0)+(n.gzhead.name?8:0)+(n.gzhead.comment?16:0)),he(n,n.gzhead.time&255),he(n,n.gzhead.time>>8&255),he(n,n.gzhead.time>>16&255),he(n,n.gzhead.time>>24&255),he(n,n.level===9?2:n.strategy>=ri||n.level<2?4:0),he(n,n.gzhead.os&255),n.gzhead.extra&&n.gzhead.extra.length&&(he(n,n.gzhead.extra.length&255),he(n,n.gzhead.extra.length>>8&255)),n.gzhead.hcrc&&(t.adler=Kt(t.adler,n.pending_buf,n.pending,0)),n.gzindex=0,n.status=ha):(he(n,0),he(n,0),he(n,0),he(n,0),he(n,0),he(n,n.level===9?2:n.strategy>=ri||n.level<2?4:0),he(n,ch),n.status=br);else{var a=ai+(n.w_bits-8<<4)<<8,s=-1;n.strategy>=ri||n.level<2?s=0:n.level<6?s=1:n.level===6?s=2:s=3,a|=s<<6,n.strstart!==0&&(a|=fh),a+=31-a%31,n.status=br,Un(n,a),n.strstart!==0&&(Un(n,t.adler>>>16),Un(n,t.adler&65535)),t.adler=1}if(n.status===ha)if(n.gzhead.extra){for(o=n.pending;n.gzindex<(n.gzhead.extra.length&65535)&&!(n.pending===n.pending_buf_size&&(n.gzhead.hcrc&&n.pending>o&&(t.adler=Kt(t.adler,n.pending_buf,n.pending-o,o)),Xt(t),o=n.pending,n.pending===n.pending_buf_size));)he(n,n.gzhead.extra[n.gzindex]&255),n.gzindex++;n.gzhead.hcrc&&n.pending>o&&(t.adler=Kt(t.adler,n.pending_buf,n.pending-o,o)),n.gzindex===n.gzhead.extra.length&&(n.gzindex=0,n.status=ni)}else n.status=ni;if(n.status===ni)if(n.gzhead.name){o=n.pending;do{if(n.pending===n.pending_buf_size&&(n.gzhead.hcrc&&n.pending>o&&(t.adler=Kt(t.adler,n.pending_buf,n.pending-o,o)),Xt(t),o=n.pending,n.pending===n.pending_buf_size)){i=1;break}n.gzindexo&&(t.adler=Kt(t.adler,n.pending_buf,n.pending-o,o)),i===0&&(n.gzindex=0,n.status=oi)}else n.status=oi;if(n.status===oi)if(n.gzhead.comment){o=n.pending;do{if(n.pending===n.pending_buf_size&&(n.gzhead.hcrc&&n.pending>o&&(t.adler=Kt(t.adler,n.pending_buf,n.pending-o,o)),Xt(t),o=n.pending,n.pending===n.pending_buf_size)){i=1;break}n.gzindexo&&(t.adler=Kt(t.adler,n.pending_buf,n.pending-o,o)),i===0&&(n.status=ii)}else n.status=ii;if(n.status===ii&&(n.gzhead.hcrc?(n.pending+2>n.pending_buf_size&&Xt(t),n.pending+2<=n.pending_buf_size&&(he(n,t.adler&255),he(n,t.adler>>8&255),t.adler=0,n.status=br)):n.status=br),n.pending!==0){if(Xt(t),t.avail_out===0)return n.last_flush=-1,Ct}else if(t.avail_in===0&&El(e)<=El(r)&&e!==Qt)return Jt(t,ca);if(n.status===Vn&&t.avail_in!==0)return Jt(t,ca);if(t.avail_in!==0||n.lookahead!==0||e!==wr&&n.status!==Vn){var f=n.strategy===ri?ph(n,e):n.strategy===Jd?hh(n,e):Yr[n.level].func(n,e);if((f===xr||f===Jr)&&(n.status=Vn),f===Ne||f===xr)return t.avail_out===0&&(n.last_flush=-1),Ct;if(f===qn&&(e===Gd?at._tr_align(n):e!==kl&&(at._tr_stored_block(n,0,0,!1),e===Kd&&(Zt(n.head),n.lookahead===0&&(n.strstart=0,n.block_start=0,n.insert=0))),Xt(t),t.avail_out===0))return n.last_flush=-1,Ct}return e!==Qt?Ct:n.wrap<=0?Tl:(n.wrap===2?(he(n,t.adler&255),he(n,t.adler>>8&255),he(n,t.adler>>16&255),he(n,t.adler>>24&255),he(n,t.total_in&255),he(n,t.total_in>>8&255),he(n,t.total_in>>16&255),he(n,t.total_in>>24&255)):(Un(n,t.adler>>>16),Un(n,t.adler&65535)),Xt(t),n.wrap>0&&(n.wrap=-n.wrap),n.pending!==0?Ct:Tl)}function xh(t){var e;return!t||!t.state?st:(e=t.state.status,e!==si&&e!==ha&&e!==ni&&e!==oi&&e!==ii&&e!==br&&e!==Vn?Jt(t,st):(t.state=null,e===br?Jt(t,Xd):Ct))}function Fh(t,e){var r=e.length,n,o,i,a,s,f,l,c;if(!t||!t.state||(n=t.state,a=n.wrap,a===2||a===1&&n.status!==si||n.lookahead))return st;for(a===1&&(t.adler=Al(t.adler,e,r,0)),n.wrap=0,r>=n.w_size&&(a===0&&(Zt(n.head),n.strstart=0,n.block_start=0,n.insert=0),c=new Xe.Buf8(n.w_size),Xe.arraySet(c,e,r-n.w_size,n.w_size,0),e=c,r=n.w_size),s=t.avail_in,f=t.next_in,l=t.input,t.avail_in=r,t.next_in=0,t.input=e,Fr(n);n.lookahead>=de;){o=n.strstart,i=n.lookahead-(de-1);do n.ins_h=(n.ins_h<{"use strict";var li=It(),Il=!0,zl=!0;try{String.fromCharCode.apply(null,[0])}catch{Il=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch{zl=!1}var Wn=new li.Buf8(256);for(jt=0;jt<256;jt++)Wn[jt]=jt>=252?6:jt>=248?5:jt>=240?4:jt>=224?3:jt>=192?2:1;var jt;Wn[254]=Wn[254]=1;Qr.string2buf=function(t){var e,r,n,o,i,a=t.length,s=0;for(o=0;o>>6,e[i++]=128|r&63):r<65536?(e[i++]=224|r>>>12,e[i++]=128|r>>>6&63,e[i++]=128|r&63):(e[i++]=240|r>>>18,e[i++]=128|r>>>12&63,e[i++]=128|r>>>6&63,e[i++]=128|r&63);return e};function jl(t,e){if(e<65534&&(t.subarray&&zl||!t.subarray&&Il))return String.fromCharCode.apply(null,li.shrinkBuf(t,e));for(var r="",n=0;n4){s[n++]=65533,r+=i-1;continue}for(o&=i===2?31:i===3?15:7;i>1&&r1){s[n++]=65533;continue}o<65536?s[n++]=o:(o-=65536,s[n++]=55296|o>>10&1023,s[n++]=56320|o&1023)}return jl(s,n)};Qr.utf8border=function(t,e){var r;for(e=e||t.length,e>t.length&&(e=t.length),r=e-1;r>=0&&(t[r]&192)===128;)r--;return r<0||r===0?e:r+Wn[t[r]]>e?r:e}});var va=He((ng,Ll)=>{"use strict";function wh(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}Ll.exports=wh});var ql=He(Xn=>{"use strict";var Gn=Ml(),Kn=It(),ga=pa(),ya=ti(),Sh=va(),Vl=Object.prototype.toString,Ph=0,ma=4,_r=0,Hl=1,Ul=2,Dh=-1,Ch=0,kh=8;function Sr(t){if(!(this instanceof Sr))return new Sr(t);this.options=Kn.assign({level:Dh,method:kh,chunkSize:16384,windowBits:15,memLevel:8,strategy:Ch,to:""},t||{});var e=this.options;e.raw&&e.windowBits>0?e.windowBits=-e.windowBits:e.gzip&&e.windowBits>0&&e.windowBits<16&&(e.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new Sh,this.strm.avail_out=0;var r=Gn.deflateInit2(this.strm,e.level,e.method,e.windowBits,e.memLevel,e.strategy);if(r!==_r)throw new Error(ya[r]);if(e.header&&Gn.deflateSetHeader(this.strm,e.header),e.dictionary){var n;if(typeof e.dictionary=="string"?n=ga.string2buf(e.dictionary):Vl.call(e.dictionary)==="[object ArrayBuffer]"?n=new Uint8Array(e.dictionary):n=e.dictionary,r=Gn.deflateSetDictionary(this.strm,n),r!==_r)throw new Error(ya[r]);this._dict_set=!0}}Sr.prototype.push=function(t,e){var r=this.strm,n=this.options.chunkSize,o,i;if(this.ended)return!1;i=e===~~e?e:e===!0?ma:Ph,typeof t=="string"?r.input=ga.string2buf(t):Vl.call(t)==="[object ArrayBuffer]"?r.input=new Uint8Array(t):r.input=t,r.next_in=0,r.avail_in=r.input.length;do{if(r.avail_out===0&&(r.output=new Kn.Buf8(n),r.next_out=0,r.avail_out=n),o=Gn.deflate(r,i),o!==Hl&&o!==_r)return this.onEnd(o),this.ended=!0,!1;(r.avail_out===0||r.avail_in===0&&(i===ma||i===Ul))&&(this.options.to==="string"?this.onData(ga.buf2binstring(Kn.shrinkBuf(r.output,r.next_out))):this.onData(Kn.shrinkBuf(r.output,r.next_out)))}while((r.avail_in>0||r.avail_out===0)&&o!==Hl);return i===ma?(o=Gn.deflateEnd(this.strm),this.onEnd(o),this.ended=!0,o===_r):(i===Ul&&(this.onEnd(_r),r.avail_out=0),!0)};Sr.prototype.onData=function(t){this.chunks.push(t)};Sr.prototype.onEnd=function(t){t===_r&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=Kn.flattenChunks(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg};function ba(t,e){var r=new Sr(e);if(r.push(t,!0),r.err)throw r.msg||ya[r.err];return r.result}function Th(t,e){return e=e||{},e.raw=!0,ba(t,e)}function Eh(t,e){return e=e||{},e.gzip=!0,ba(t,e)}Xn.Deflate=Sr;Xn.deflate=ba;Xn.deflateRaw=Th;Xn.gzip=Eh});var Gl=He((ig,Wl)=>{"use strict";var fi=30,Ah=12;Wl.exports=function(e,r){var n,o,i,a,s,f,l,c,u,d,p,h,b,F,x,m,y,w,S,D,T,C,E,I,A;n=e.state,o=e.next_in,I=e.input,i=o+(e.avail_in-5),a=e.next_out,A=e.output,s=a-(r-e.avail_out),f=a+(e.avail_out-257),l=n.dmax,c=n.wsize,u=n.whave,d=n.wnext,p=n.window,h=n.hold,b=n.bits,F=n.lencode,x=n.distcode,m=(1<>>24,h>>>=S,b-=S,S=w>>>16&255,S===0)A[a++]=w&65535;else if(S&16){D=w&65535,S&=15,S&&(b>>=S,b-=S),b<15&&(h+=I[o++]<>>24,h>>>=S,b-=S,S=w>>>16&255,S&16){if(T=w&65535,S&=15,bl){e.msg="invalid distance too far back",n.mode=fi;break e}if(h>>>=S,b-=S,S=a-s,T>S){if(S=T-S,S>u&&n.sane){e.msg="invalid distance too far back",n.mode=fi;break e}if(C=0,E=p,d===0){if(C+=c-S,S2;)A[a++]=E[C++],A[a++]=E[C++],A[a++]=E[C++],D-=3;D&&(A[a++]=E[C++],D>1&&(A[a++]=E[C++]))}else{C=a-T;do A[a++]=A[C++],A[a++]=A[C++],A[a++]=A[C++],D-=3;while(D>2);D&&(A[a++]=A[C++],D>1&&(A[a++]=A[C++]))}}else if((S&64)===0){w=x[(w&65535)+(h&(1<>3,o-=D,b-=D<<3,h&=(1<{"use strict";var Kl=It(),$r=15,Xl=852,Zl=592,Yl=0,xa=1,Jl=2,Rh=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],Oh=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],Bh=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],Nh=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];Ql.exports=function(e,r,n,o,i,a,s,f){var l=f.bits,c=0,u=0,d=0,p=0,h=0,b=0,F=0,x=0,m=0,y=0,w,S,D,T,C,E=null,I=0,A,R=new Kl.Buf16($r+1),z=new Kl.Buf16($r+1),M=null,X=0,te,L,ue;for(c=0;c<=$r;c++)R[c]=0;for(u=0;u=1&&R[p]===0;p--);if(h>p&&(h=p),p===0)return i[a++]=1<<24|64<<16|0,i[a++]=1<<24|64<<16|0,f.bits=1,0;for(d=1;d0&&(e===Yl||p!==1))return-1;for(z[1]=0,c=1;c<$r;c++)z[c+1]=z[c]+R[c];for(u=0;uXl||e===Jl&&m>Zl)return 1;for(;;){te=c-F,s[u]A?(L=M[X+s[u]],ue=E[I+s[u]]):(L=96,ue=0),w=1<>F)+S]=te<<24|L<<16|ue|0;while(S!==0);for(w=1<>=1;if(w!==0?(y&=w-1,y+=w):y=0,u++,--R[c]===0){if(c===p)break;c=r[n+s[u]]}if(c>h&&(y&T)!==D){for(F===0&&(F=h),C+=d,b=c-F,x=1<Xl||e===Jl&&m>Zl)return 1;D=y&T,i[D]=h<<24|b<<16|C-a|0}}return y!==0&&(i[C+y]=c-F<<24|64<<16|0),f.bits=h,0}});var Nf=He(gt=>{"use strict";var nt=It(),Ca=la(),Tt=fa(),Mh=Gl(),Zn=_l(),Ih=0,Df=1,Cf=2,$l=4,zh=5,ci=6,Pr=0,jh=1,Lh=2,lt=-2,kf=-3,ka=-4,Hh=-5,ef=8,Tf=1,tf=2,rf=3,nf=4,of=5,af=6,sf=7,lf=8,ff=9,cf=10,hi=11,Lt=12,Fa=13,uf=14,wa=15,df=16,hf=17,pf=18,vf=19,ui=20,di=21,mf=22,gf=23,yf=24,bf=25,xf=26,Sa=27,Ff=28,wf=29,be=30,Ta=31,Uh=32,Vh=852,qh=592,Wh=15,Gh=Wh;function Sf(t){return(t>>>24&255)+(t>>>8&65280)+((t&65280)<<8)+((t&255)<<24)}function Kh(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new nt.Buf16(320),this.work=new nt.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function Ef(t){var e;return!t||!t.state?lt:(e=t.state,t.total_in=t.total_out=e.total=0,t.msg="",e.wrap&&(t.adler=e.wrap&1),e.mode=Tf,e.last=0,e.havedict=0,e.dmax=32768,e.head=null,e.hold=0,e.bits=0,e.lencode=e.lendyn=new nt.Buf32(Vh),e.distcode=e.distdyn=new nt.Buf32(qh),e.sane=1,e.back=-1,Pr)}function Af(t){var e;return!t||!t.state?lt:(e=t.state,e.wsize=0,e.whave=0,e.wnext=0,Ef(t))}function Rf(t,e){var r,n;return!t||!t.state||(n=t.state,e<0?(r=0,e=-e):(r=(e>>4)+1,e<48&&(e&=15)),e&&(e<8||e>15))?lt:(n.window!==null&&n.wbits!==e&&(n.window=null),n.wrap=r,n.wbits=e,Af(t))}function Of(t,e){var r,n;return t?(n=new Kh,t.state=n,n.window=null,r=Rf(t,e),r!==Pr&&(t.state=null),r):lt}function Xh(t){return Of(t,Gh)}var Pf=!0,Pa,Da;function Zh(t){if(Pf){var e;for(Pa=new nt.Buf32(512),Da=new nt.Buf32(32),e=0;e<144;)t.lens[e++]=8;for(;e<256;)t.lens[e++]=9;for(;e<280;)t.lens[e++]=7;for(;e<288;)t.lens[e++]=8;for(Zn(Df,t.lens,0,288,Pa,0,t.work,{bits:9}),e=0;e<32;)t.lens[e++]=5;Zn(Cf,t.lens,0,32,Da,0,t.work,{bits:5}),Pf=!1}t.lencode=Pa,t.lenbits=9,t.distcode=Da,t.distbits=5}function Bf(t,e,r,n){var o,i=t.state;return i.window===null&&(i.wsize=1<=i.wsize?(nt.arraySet(i.window,e,r-i.wsize,i.wsize,0),i.wnext=0,i.whave=i.wsize):(o=i.wsize-i.wnext,o>n&&(o=n),nt.arraySet(i.window,e,r-n,o,i.wnext),n-=o,n?(nt.arraySet(i.window,e,r-n,n,0),i.wnext=n,i.whave=i.wsize):(i.wnext+=o,i.wnext===i.wsize&&(i.wnext=0),i.whave>>8&255,r.check=Tt(r.check,E,2,0),l=0,c=0,r.mode=tf;break}if(r.flags=0,r.head&&(r.head.done=!1),!(r.wrap&1)||(((l&255)<<8)+(l>>8))%31){t.msg="incorrect header check",r.mode=be;break}if((l&15)!==ef){t.msg="unknown compression method",r.mode=be;break}if(l>>>=4,c-=4,T=(l&15)+8,r.wbits===0)r.wbits=T;else if(T>r.wbits){t.msg="invalid window size",r.mode=be;break}r.dmax=1<>8&1),r.flags&512&&(E[0]=l&255,E[1]=l>>>8&255,r.check=Tt(r.check,E,2,0)),l=0,c=0,r.mode=rf;case rf:for(;c<32;){if(s===0)break e;s--,l+=n[i++]<>>8&255,E[2]=l>>>16&255,E[3]=l>>>24&255,r.check=Tt(r.check,E,4,0)),l=0,c=0,r.mode=nf;case nf:for(;c<16;){if(s===0)break e;s--,l+=n[i++]<>8),r.flags&512&&(E[0]=l&255,E[1]=l>>>8&255,r.check=Tt(r.check,E,2,0)),l=0,c=0,r.mode=of;case of:if(r.flags&1024){for(;c<16;){if(s===0)break e;s--,l+=n[i++]<>>8&255,r.check=Tt(r.check,E,2,0)),l=0,c=0}else r.head&&(r.head.extra=null);r.mode=af;case af:if(r.flags&1024&&(p=r.length,p>s&&(p=s),p&&(r.head&&(T=r.head.extra_len-r.length,r.head.extra||(r.head.extra=new Array(r.head.extra_len)),nt.arraySet(r.head.extra,n,i,p,T)),r.flags&512&&(r.check=Tt(r.check,n,p,i)),s-=p,i+=p,r.length-=p),r.length))break e;r.length=0,r.mode=sf;case sf:if(r.flags&2048){if(s===0)break e;p=0;do T=n[i+p++],r.head&&T&&r.length<65536&&(r.head.name+=String.fromCharCode(T));while(T&&p>9&1,r.head.done=!0),t.adler=r.check=0,r.mode=Lt;break;case cf:for(;c<32;){if(s===0)break e;s--,l+=n[i++]<>>=c&7,c-=c&7,r.mode=Sa;break}for(;c<3;){if(s===0)break e;s--,l+=n[i++]<>>=1,c-=1,l&3){case 0:r.mode=uf;break;case 1:if(Zh(r),r.mode=ui,e===ci){l>>>=2,c-=2;break e}break;case 2:r.mode=hf;break;case 3:t.msg="invalid block type",r.mode=be}l>>>=2,c-=2;break;case uf:for(l>>>=c&7,c-=c&7;c<32;){if(s===0)break e;s--,l+=n[i++]<>>16^65535)){t.msg="invalid stored block lengths",r.mode=be;break}if(r.length=l&65535,l=0,c=0,r.mode=wa,e===ci)break e;case wa:r.mode=df;case df:if(p=r.length,p){if(p>s&&(p=s),p>f&&(p=f),p===0)break e;nt.arraySet(o,n,i,p,a),s-=p,i+=p,f-=p,a+=p,r.length-=p;break}r.mode=Lt;break;case hf:for(;c<14;){if(s===0)break e;s--,l+=n[i++]<>>=5,c-=5,r.ndist=(l&31)+1,l>>>=5,c-=5,r.ncode=(l&15)+4,l>>>=4,c-=4,r.nlen>286||r.ndist>30){t.msg="too many length or distance symbols",r.mode=be;break}r.have=0,r.mode=pf;case pf:for(;r.have>>=3,c-=3}for(;r.have<19;)r.lens[R[r.have++]]=0;if(r.lencode=r.lendyn,r.lenbits=7,I={bits:r.lenbits},C=Zn(Ih,r.lens,0,19,r.lencode,0,r.work,I),r.lenbits=I.bits,C){t.msg="invalid code lengths set",r.mode=be;break}r.have=0,r.mode=vf;case vf:for(;r.have>>24,m=F>>>16&255,y=F&65535,!(x<=c);){if(s===0)break e;s--,l+=n[i++]<>>=x,c-=x,r.lens[r.have++]=y;else{if(y===16){for(A=x+2;c>>=x,c-=x,r.have===0){t.msg="invalid bit length repeat",r.mode=be;break}T=r.lens[r.have-1],p=3+(l&3),l>>>=2,c-=2}else if(y===17){for(A=x+3;c>>=x,c-=x,T=0,p=3+(l&7),l>>>=3,c-=3}else{for(A=x+7;c>>=x,c-=x,T=0,p=11+(l&127),l>>>=7,c-=7}if(r.have+p>r.nlen+r.ndist){t.msg="invalid bit length repeat",r.mode=be;break}for(;p--;)r.lens[r.have++]=T}}if(r.mode===be)break;if(r.lens[256]===0){t.msg="invalid code -- missing end-of-block",r.mode=be;break}if(r.lenbits=9,I={bits:r.lenbits},C=Zn(Df,r.lens,0,r.nlen,r.lencode,0,r.work,I),r.lenbits=I.bits,C){t.msg="invalid literal/lengths set",r.mode=be;break}if(r.distbits=6,r.distcode=r.distdyn,I={bits:r.distbits},C=Zn(Cf,r.lens,r.nlen,r.ndist,r.distcode,0,r.work,I),r.distbits=I.bits,C){t.msg="invalid distances set",r.mode=be;break}if(r.mode=ui,e===ci)break e;case ui:r.mode=di;case di:if(s>=6&&f>=258){t.next_out=a,t.avail_out=f,t.next_in=i,t.avail_in=s,r.hold=l,r.bits=c,Mh(t,d),a=t.next_out,o=t.output,f=t.avail_out,i=t.next_in,n=t.input,s=t.avail_in,l=r.hold,c=r.bits,r.mode===Lt&&(r.back=-1);break}for(r.back=0;F=r.lencode[l&(1<>>24,m=F>>>16&255,y=F&65535,!(x<=c);){if(s===0)break e;s--,l+=n[i++]<>w)],x=F>>>24,m=F>>>16&255,y=F&65535,!(w+x<=c);){if(s===0)break e;s--,l+=n[i++]<>>=w,c-=w,r.back+=w}if(l>>>=x,c-=x,r.back+=x,r.length=y,m===0){r.mode=xf;break}if(m&32){r.back=-1,r.mode=Lt;break}if(m&64){t.msg="invalid literal/length code",r.mode=be;break}r.extra=m&15,r.mode=mf;case mf:if(r.extra){for(A=r.extra;c>>=r.extra,c-=r.extra,r.back+=r.extra}r.was=r.length,r.mode=gf;case gf:for(;F=r.distcode[l&(1<>>24,m=F>>>16&255,y=F&65535,!(x<=c);){if(s===0)break e;s--,l+=n[i++]<>w)],x=F>>>24,m=F>>>16&255,y=F&65535,!(w+x<=c);){if(s===0)break e;s--,l+=n[i++]<>>=w,c-=w,r.back+=w}if(l>>>=x,c-=x,r.back+=x,m&64){t.msg="invalid distance code",r.mode=be;break}r.offset=y,r.extra=m&15,r.mode=yf;case yf:if(r.extra){for(A=r.extra;c>>=r.extra,c-=r.extra,r.back+=r.extra}if(r.offset>r.dmax){t.msg="invalid distance too far back",r.mode=be;break}r.mode=bf;case bf:if(f===0)break e;if(p=d-f,r.offset>p){if(p=r.offset-p,p>r.whave&&r.sane){t.msg="invalid distance too far back",r.mode=be;break}p>r.wnext?(p-=r.wnext,h=r.wsize-p):h=r.wnext-p,p>r.length&&(p=r.length),b=r.window}else b=o,h=a-r.offset,p=r.length;p>f&&(p=f),f-=p,r.length-=p;do o[a++]=b[h++];while(--p);r.length===0&&(r.mode=di);break;case xf:if(f===0)break e;o[a++]=r.length,f--,r.mode=di;break;case Sa:if(r.wrap){for(;c<32;){if(s===0)break e;s--,l|=n[i++]<{"use strict";Mf.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}});var zf=He((fg,If)=>{"use strict";function $h(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}If.exports=$h});var Lf=He(Jn=>{"use strict";var en=Nf(),Yn=It(),pi=pa(),ke=Ea(),Aa=ti(),ep=va(),tp=zf(),jf=Object.prototype.toString;function Dr(t){if(!(this instanceof Dr))return new Dr(t);this.options=Yn.assign({chunkSize:16384,windowBits:0,to:""},t||{});var e=this.options;e.raw&&e.windowBits>=0&&e.windowBits<16&&(e.windowBits=-e.windowBits,e.windowBits===0&&(e.windowBits=-15)),e.windowBits>=0&&e.windowBits<16&&!(t&&t.windowBits)&&(e.windowBits+=32),e.windowBits>15&&e.windowBits<48&&(e.windowBits&15)===0&&(e.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new ep,this.strm.avail_out=0;var r=en.inflateInit2(this.strm,e.windowBits);if(r!==ke.Z_OK)throw new Error(Aa[r]);if(this.header=new tp,en.inflateGetHeader(this.strm,this.header),e.dictionary&&(typeof e.dictionary=="string"?e.dictionary=pi.string2buf(e.dictionary):jf.call(e.dictionary)==="[object ArrayBuffer]"&&(e.dictionary=new Uint8Array(e.dictionary)),e.raw&&(r=en.inflateSetDictionary(this.strm,e.dictionary),r!==ke.Z_OK)))throw new Error(Aa[r])}Dr.prototype.push=function(t,e){var r=this.strm,n=this.options.chunkSize,o=this.options.dictionary,i,a,s,f,l,c=!1;if(this.ended)return!1;a=e===~~e?e:e===!0?ke.Z_FINISH:ke.Z_NO_FLUSH,typeof t=="string"?r.input=pi.binstring2buf(t):jf.call(t)==="[object ArrayBuffer]"?r.input=new Uint8Array(t):r.input=t,r.next_in=0,r.avail_in=r.input.length;do{if(r.avail_out===0&&(r.output=new Yn.Buf8(n),r.next_out=0,r.avail_out=n),i=en.inflate(r,ke.Z_NO_FLUSH),i===ke.Z_NEED_DICT&&o&&(i=en.inflateSetDictionary(this.strm,o)),i===ke.Z_BUF_ERROR&&c===!0&&(i=ke.Z_OK,c=!1),i!==ke.Z_STREAM_END&&i!==ke.Z_OK)return this.onEnd(i),this.ended=!0,!1;r.next_out&&(r.avail_out===0||i===ke.Z_STREAM_END||r.avail_in===0&&(a===ke.Z_FINISH||a===ke.Z_SYNC_FLUSH))&&(this.options.to==="string"?(s=pi.utf8border(r.output,r.next_out),f=r.next_out-s,l=pi.buf2string(r.output,s),r.next_out=f,r.avail_out=n-f,f&&Yn.arraySet(r.output,r.output,s,f,0),this.onData(l)):this.onData(Yn.shrinkBuf(r.output,r.next_out))),r.avail_in===0&&r.avail_out===0&&(c=!0)}while((r.avail_in>0||r.avail_out===0)&&i!==ke.Z_STREAM_END);return i===ke.Z_STREAM_END&&(a=ke.Z_FINISH),a===ke.Z_FINISH?(i=en.inflateEnd(this.strm),this.onEnd(i),this.ended=!0,i===ke.Z_OK):(a===ke.Z_SYNC_FLUSH&&(this.onEnd(ke.Z_OK),r.avail_out=0),!0)};Dr.prototype.onData=function(t){this.chunks.push(t)};Dr.prototype.onEnd=function(t){t===ke.Z_OK&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=Yn.flattenChunks(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg};function Ra(t,e){var r=new Dr(e);if(r.push(t,!0),r.err)throw r.msg||Aa[r.err];return r.result}function rp(t,e){return e=e||{},e.raw=!0,Ra(t,e)}Jn.Inflate=Dr;Jn.inflate=Ra;Jn.inflateRaw=rp;Jn.ungzip=Ra});var Qn=He((ug,Uf)=>{"use strict";var np=It().assign,op=ql(),ip=Lf(),ap=Ea(),Hf={};np(Hf,op,ip,ap);Uf.exports=Hf});var Im={};ad(Im,{default:()=>Wi});module.exports=sd(Im);var N=require("obsidian");var Xi=function(t,e){return Xi=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,n){r.__proto__=n}||function(r,n){for(var o in n)n.hasOwnProperty(o)&&(r[o]=n[o])},Xi(t,e)};function k(t,e){Xi(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}var Y=function(){return Y=Object.assign||function(e){for(var r,n=1,o=arguments.length;n0&&i[i.length-1])&&(l[0]===6||l[0]===2)){r=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]>2],e+=Vr[(t[n]&3)<<4|t[n+1]>>4],e+=Vr[(t[n+1]&15)<<2|t[n+2]>>6],e+=Vr[t[n+2]&63];return r%3===2?e=e.substring(0,e.length-1)+"=":r%3===1&&(e=e.substring(0,e.length-2)+"=="),e},Rs=function(t){var e=t.length*.75,r=t.length,n,o=0,i,a,s,f;t[t.length-1]==="="&&(e--,t[t.length-2]==="="&&e--);var l=new Uint8Array(e);for(n=0;n>4,l[o++]=(a&15)<<4|s>>2,l[o++]=(s&3)<<6|f&63;return l},ld=/^(data)?:?([\w\/\+]+)?;?(charset=[\w-]+|base64)?.*,/i,Bs=function(t){var e=t.trim(),r=e.substring(0,100),n=r.match(ld);if(!n)return Rs(e);var o=n[0],i=e.substring(o.length);return Rs(i)};var Q=function(t){return t.charCodeAt(0)},Ns=function(t){return t.codePointAt(0)},Mt=function(t,e){return rt(t.toString(16),e,"0").toUpperCase()},Wt=function(t){return Mt(t,2)},tt=function(t){return String.fromCharCode(t)},Ms=function(t){return tt(parseInt(t,16))},rt=function(t,e,r){for(var n="",o=0,i=e-t.length;o=55296&&r<=56319&&t.length>o&&(n=t.charCodeAt(o),n>=56320&&n<=57343&&(i=2)),[t.slice(e,e+i),i]},zs=function(t){for(var e=[],r=0,n=t.length;rr&&l(),a+=d,s+=p}}return l(),f},dd=/^D:(\d\d\d\d)(\d\d)?(\d\d)?(\d\d)?(\d\d)?(\d\d)?([+\-Z])?(\d\d)?'?(\d\d)?'?$/,Zo=function(t){var e=t.match(dd);if(e){var r=e[1],n=e[2],o=n===void 0?"01":n,i=e[3],a=i===void 0?"01":i,s=e[4],f=s===void 0?"00":s,l=e[5],c=l===void 0?"00":l,u=e[6],d=u===void 0?"00":u,p=e[7],h=p===void 0?"Z":p,b=e[8],F=b===void 0?"00":b,x=e[9],m=x===void 0?"00":x,y=h==="Z"?"Z":""+h+F+":"+m,w=new Date(r+"-"+o+"-"+a+"T"+f+":"+c+":"+d+y);return w}},On=function(t,e){for(var r,n=0,o;n=0&&t<=65535},Qs=function(t){return t>=65536&&t<=1114111},Ji=function(t){return Math.floor((t-65536)/1024)+55296},Qi=function(t){return(t-65536)%1024+56320},Gt;(function(t){t.BigEndian="BigEndian",t.LittleEndian="LittleEndian"})(Gt||(Gt={}));var Bn="\uFFFD".codePointAt(0),Qo=function(t,e){if(e===void 0&&(e=!0),t.length<=1)return String.fromCodePoint(Bn);for(var r=e?pd(t):Gt.BigEndian,n=e?2:0,o=[];t.length-n>=2;){var i=Zs(t[n++],t[n++],r);if(hd(i))if(t.length-n<2)o.push(Bn);else{var a=Zs(t[n++],t[n++],r);Xs(a)?o.push(i,a):o.push(Bn)}else Xs(i)?(n+=2,o.push(Bn)):o.push(i)}return n=55296&&t<=56319},Xs=function(t){return t>=56320&&t<=57343},Zs=function(t,e,r){if(r===Gt.LittleEndian)return e<<8|t;if(r===Gt.BigEndian)return t<<8|e;throw new Error("Invalid byteOrder: "+r)},pd=function(t){return _s(t)?Gt.BigEndian:$s(t)?Gt.LittleEndian:Gt.BigEndian},_s=function(t){return t[0]===254&&t[1]===255},$s=function(t){return t[0]===255&&t[1]===254},_o=function(t){return _s(t)||$s(t)};var el=function(t){var e=String(t);if(Math.abs(t)<1){var r=parseInt(t.toString().split("e-")[1]);if(r){var n=t<0;n&&(t*=-1),t*=Math.pow(10,r-1),e="0."+new Array(r).join("0")+t.toString().substring(2),n&&(e="-"+e)}}else{var r=parseInt(t.toString().split("+")[1]);r>20&&(r-=20,t/=Math.pow(10,r),e=t.toString()+new Array(r+1).join("0"))}return e},Nn=function(t){return Math.ceil(t.toString(2).length/8)},mr=function(t){for(var e=new Uint8Array(Nn(t)),r=1;r<=e.length;r++)e[r-1]=t>>(e.length-r)*8;return e};var gr=function(t){throw new Error(t)};var qf=Ko(Qn()),Vf="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",$n=new Uint8Array(256);for(_n=0;_n>4,l[o++]=(a&15)<<4|s>>2,l[o++]=(s&3)<<6|f&63;return l},lp=function(t){for(var e="",r=0;rn)throw new Error(Me(e)+" must be at least "+r+" and at most "+n+", but was actually "+t)},ot=function(t,e,r,n){P(t,e,["number","undefined"]),typeof t=="number"&&Ue(t,e,r,n)},gi=function(t,e,r){if(P(t,e,["number"]),t%r!==0)throw new Error(Me(e)+" must be a multiple of "+r+", but was actually "+t)},cc=function(t,e){if(!Number.isInteger(t))throw new Error(Me(e)+" must be an integer, but was actually "+t)},_t=function(t,e){if(![1,0].includes(Math.sign(t)))throw new Error(Me(e)+" must be a positive number or 0, but was actually "+t)};var $=new Uint16Array(256);for(no=0;no<256;no++)$[no]=no;var no;$[22]=Q("");$[24]=Q("\u02D8");$[25]=Q("\u02C7");$[26]=Q("\u02C6");$[27]=Q("\u02D9");$[28]=Q("\u02DD");$[29]=Q("\u02DB");$[30]=Q("\u02DA");$[31]=Q("\u02DC");$[127]=Q("\uFFFD");$[128]=Q("\u2022");$[129]=Q("\u2020");$[130]=Q("\u2021");$[131]=Q("\u2026");$[132]=Q("\u2014");$[133]=Q("\u2013");$[134]=Q("\u0192");$[135]=Q("\u2044");$[136]=Q("\u2039");$[137]=Q("\u203A");$[138]=Q("\u2212");$[139]=Q("\u2030");$[140]=Q("\u201E");$[141]=Q("\u201C");$[142]=Q("\u201D");$[143]=Q("\u2018");$[144]=Q("\u2019");$[145]=Q("\u201A");$[146]=Q("\u2122");$[147]=Q("\uFB01");$[148]=Q("\uFB02");$[149]=Q("\u0141");$[150]=Q("\u0152");$[151]=Q("\u0160");$[152]=Q("\u0178");$[153]=Q("\u017D");$[154]=Q("\u0131");$[155]=Q("\u0142");$[156]=Q("\u0153");$[157]=Q("\u0161");$[158]=Q("\u017E");$[159]=Q("\uFFFD");$[160]=Q("\u20AC");$[173]=Q("\uFFFD");var yi=function(t){for(var e=new Array(t.length),r=0,n=t.length;r=g.ExclamationPoint&&t<=g.Tilde&&!xi[t]},Tc={},Ec=new Map,Hp=function(t){k(e,t);function e(r,n){var o=this;if(r!==Tc)throw new tn("PDFName");o=t.call(this)||this;for(var i="/",a=0,s=n.length;a=g.Zero&&l<=g.Nine||l>=g.a&&l<=g.f||l>=g.A&&l<=g.F?(n+=f,(n.length===2||!(c>="0"&&c<="9"||c>="a"&&c<="f"||c>="A"&&c<="F"))&&(i(parseInt(n,16)),n="")):i(l):l===g.Hash?o=!0:i(l)}return new Uint8Array(r)},e.prototype.decodeText=function(){var r=this.asBytes();return String.fromCharCode.apply(String,Array.from(r))},e.prototype.asString=function(){return this.encodedName},e.prototype.value=function(){return this.encodedName},e.prototype.clone=function(){return this},e.prototype.toString=function(){return this.encodedName},e.prototype.sizeInBytes=function(){return this.encodedName.length},e.prototype.copyBytesInto=function(r,n){return n+=me(this.encodedName,r,n),this.encodedName.length},e.of=function(r){var n=jp(r),o=Ec.get(n);return o||(o=new e(Tc,n),Ec.set(n,o)),o},e.Length=e.of("Length"),e.FlateDecode=e.of("FlateDecode"),e.Resources=e.of("Resources"),e.Font=e.of("Font"),e.XObject=e.of("XObject"),e.ExtGState=e.of("ExtGState"),e.Contents=e.of("Contents"),e.Type=e.of("Type"),e.Parent=e.of("Parent"),e.MediaBox=e.of("MediaBox"),e.Page=e.of("Page"),e.Annots=e.of("Annots"),e.TrimBox=e.of("TrimBox"),e.ArtBox=e.of("ArtBox"),e.BleedBox=e.of("BleedBox"),e.CropBox=e.of("CropBox"),e.Rotate=e.of("Rotate"),e.Title=e.of("Title"),e.Author=e.of("Author"),e.Subject=e.of("Subject"),e.Creator=e.of("Creator"),e.Keywords=e.of("Keywords"),e.Producer=e.of("Producer"),e.CreationDate=e.of("CreationDate"),e.ModDate=e.of("ModDate"),e}(ve),v=Hp;var Up=function(t){k(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.asNull=function(){return null},e.prototype.clone=function(){return this},e.prototype.toString=function(){return"null"},e.prototype.sizeInBytes=function(){return 4},e.prototype.copyBytesInto=function(r,n){return r[n++]=g.n,r[n++]=g.u,r[n++]=g.l,r[n++]=g.l,4},e}(ve),Te=new Up;var Vp=function(t){k(e,t);function e(r,n){var o=t.call(this)||this;return o.dict=r,o.context=n,o}return e.prototype.keys=function(){return Array.from(this.dict.keys())},e.prototype.values=function(){return Array.from(this.dict.values())},e.prototype.entries=function(){return Array.from(this.dict.entries())},e.prototype.set=function(r,n){this.dict.set(r,n)},e.prototype.get=function(r,n){n===void 0&&(n=!1);var o=this.dict.get(r);if(!(o===Te&&!n))return o},e.prototype.has=function(r){var n=this.dict.get(r);return n!==void 0&&n!==Te},e.prototype.lookupMaybe=function(r){for(var n,o=[],i=1;ithis.largestObjectNumber&&(this.largestObjectNumber=e.objectNumber)},t.prototype.nextRef=function(){return this.largestObjectNumber+=1,J.of(this.largestObjectNumber)},t.prototype.register=function(e){var r=this.nextRef();return this.assign(r,e),r},t.prototype.delete=function(e){return this.indirectObjects.delete(e)},t.prototype.lookupMaybe=function(e){for(var r=[],n=1;n1?(this.subsections.push([e]),this.chunkIdx+=1,this.chunkLength=1):(r.push(e),this.chunkLength+=1)},t.create=function(){return new t({ref:J.of(0,65535),offset:0,deleted:!0})},t.createEmpty=function(){return new t},t}(),oo=$p;var e0=function(){function t(e){this.lastXRefOffset=String(e)}return t.prototype.toString=function(){return`startxref -`+this.lastXRefOffset+` -%%EOF`},t.prototype.sizeInBytes=function(){return 16+this.lastXRefOffset.length},t.prototype.copyBytesInto=function(e,r){var n=r;return e[r++]=g.s,e[r++]=g.t,e[r++]=g.a,e[r++]=g.r,e[r++]=g.t,e[r++]=g.x,e[r++]=g.r,e[r++]=g.e,e[r++]=g.f,e[r++]=g.Newline,r+=me(this.lastXRefOffset,e,r),e[r++]=g.Newline,e[r++]=g.Percent,e[r++]=g.Percent,e[r++]=g.E,e[r++]=g.O,e[r++]=g.F,r-n},t.forLastCrossRefSectionOffset=function(e){return new t(e)},t}(),Er=e0;var t0=function(){function t(e){this.dict=e}return t.prototype.toString=function(){return`trailer -`+this.dict.toString()},t.prototype.sizeInBytes=function(){return 8+this.dict.sizeInBytes()},t.prototype.copyBytesInto=function(e,r){var n=r;return e[r++]=g.t,e[r++]=g.r,e[r++]=g.a,e[r++]=g.i,e[r++]=g.l,e[r++]=g.e,e[r++]=g.r,e[r++]=g.Newline,r+=this.dict.copyBytesInto(e,r),r-n},t.of=function(e){return new t(e)},t}(),Ua=t0;var r0=function(t){k(e,t);function e(r,n,o){o===void 0&&(o=!0);var i=t.call(this,r.obj({}),o)||this;return i.objects=n,i.offsets=i.computeObjectOffsets(),i.offsetsString=i.computeOffsetsString(),i.dict.set(v.of("Type"),v.of("ObjStm")),i.dict.set(v.of("N"),j.of(i.objects.length)),i.dict.set(v.of("First"),j.of(i.offsetsString.length)),i}return e.prototype.getObjectsCount=function(){return this.objects.length},e.prototype.clone=function(r){return e.withContextAndObjects(r||this.dict.context,this.objects.slice(),this.encode)},e.prototype.getContentsString=function(){for(var r=this.offsetsString,n=0,o=this.objects.length;n1&&(a.push(s),a.push(c.ref.objectNumber),s=0),s+=1}return a.push(s),a},i.computeEntryTuples=function(){for(var a=new Array(i.entries.length),s=0,f=i.entries.length;ss[0]&&(s[0]=h),b>s[1]&&(s[1]=b),F>s[2]&&(s[2]=F)}return s},i.entries=n||[],i.entryTuplesCache=Ve.populatedBy(i.computeEntryTuples),i.maxByteWidthsCache=Ve.populatedBy(i.computeMaxEntryByteWidths),i.indexCache=Ve.populatedBy(i.computeIndex),r.set(v.of("Type"),v.of("XRef")),i}return e.prototype.addDeletedEntry=function(r,n){var o=er.Deleted;this.entries.push({type:o,ref:r,nextFreeObjectNumber:n}),this.entryTuplesCache.invalidate(),this.maxByteWidthsCache.invalidate(),this.indexCache.invalidate(),this.contentsCache.invalidate()},e.prototype.addUncompressedEntry=function(r,n){var o=er.Uncompressed;this.entries.push({type:o,ref:r,offset:n}),this.entryTuplesCache.invalidate(),this.maxByteWidthsCache.invalidate(),this.indexCache.invalidate(),this.contentsCache.invalidate()},e.prototype.addCompressedEntry=function(r,n,o){var i=er.Compressed;this.entries.push({type:i,ref:r,objectStreamRef:n,index:o}),this.entryTuplesCache.invalidate(),this.maxByteWidthsCache.invalidate(),this.indexCache.invalidate(),this.contentsCache.invalidate()},e.prototype.clone=function(r){var n=this,o=n.dict,i=n.entries,a=n.encode;return e.of(o.clone(r),i.slice(),a)},e.prototype.getContentsString=function(){for(var r=this.entryTuplesCache.access(),n=this.maxByteWidthsCache.access(),o="",i=0,a=r.length;i=0;h--)o+=(u[h]||0).toString(2);for(var h=n[1]-1;h>=0;h--)o+=(d[h]||0).toString(2);for(var h=n[2]-1;h>=0;h--)o+=(p[h]||0).toString(2)}return o},e.prototype.getUnencodedContents=function(){for(var r=this.entryTuplesCache.access(),n=this.maxByteWidthsCache.access(),o=new Uint8Array(this.getUnencodedContentsSize()),i=0,a=0,s=r.length;a=0;b--)o[i++]=d[b]||0;for(var b=n[1]-1;b>=0;b--)o[i++]=p[b]||0;for(var b=n[2]-1;b>=0;b--)o[i++]=h[b]||0}return o},e.prototype.getUnencodedContentsSize=function(){var r=this.maxByteWidthsCache.access(),n=qs(r);return n*this.entries.length},e.prototype.updateDict=function(){t.prototype.updateDict.call(this);var r=this.maxByteWidthsCache.access(),n=this.indexCache.access(),o=this.dict.context;this.dict.set(v.of("W"),o.obj(r)),this.dict.set(v.of("Index"),o.obj(n))},e.create=function(r,n){n===void 0&&(n=!0);var o=new e(r,[],n);return o.addDeletedEntry(J.of(0,65535),0),o},e.of=function(r,n,o){return o===void 0&&(o=!0),new e(r,n,o)},e}(Tr),Va=i0;var a0=function(t){k(e,t);function e(r,n,o,i){var a=t.call(this,r,n)||this;return a.encodeStreams=o,a.objectsPerStream=i,a}return e.prototype.computeBufferSize=function(){return V(this,void 0,void 0,function(){var r,n,o,i,a,s,f,l,h,b,c,x,u,d,F,p,h,b,F,x,m,y,w,S;return q(this,function(D){switch(D.label){case 0:r=this.context.largestObjectNumber+1,n=Ht.forVersion(1,7),o=n.sizeInBytes()+2,i=Va.create(this.createTrailerDict(),this.encodeStreams),a=[],s=[],f=[],l=this.context.enumerateIndirectObjects(),h=0,b=l.length,D.label=1;case 1:return h"},e.prototype.sizeInBytes=function(){return this.value.length+2},e.prototype.copyBytesInto=function(r,n){return r[n++]=g.LessThan,n+=me(this.value,r,n),r[n++]=g.GreaterThan,this.value.length+2},e.of=function(r){return new e(r)},e.fromText=function(r){for(var n=Ys(r),o="",i=0,a=n.length;i> def -/CMapName /Adobe-Identity-UCS def -/CMapType 2 def -1 begincodespacerange -<0000> -endcodespacerange -`+t.length+` beginbfchar -`+t.map(function(e){var r=e[0],n=e[1];return r+" "+n}).join(` -`)+` -endbfchar -endcmap -CMapName currentdict /CMap defineresource pop -end -end`},Mc=function(){for(var t=[],e=0;e"},wi=function(t){return Mt(t,4)},c0=function(t){if(Js(t))return wi(t);if(Qs(t)){var e=Ji(t),r=Qi(t);return""+wi(e)+wi(r)}var n=Wt(t),o="0x"+n+" is not a valid UTF-8 or UTF-16 codepoint.";throw new Error(o)};var u0=function(t){var e=0,r=function(n){e|=1<=g.Zero&&l<=g.Seven?(n+=f,(n.length===3||!(c>="0"&&c<="7"))&&(i(parseInt(n,8)),n="")):i(l):l===g.BackSlash?o=!0:i(l)}return new Uint8Array(r)},e.prototype.decodeText=function(){var r=this.asBytes();return _o(r)?Qo(r):yi(r)},e.prototype.decodeDate=function(){var r=this.decodeText(),n=Zo(r);if(!n)throw new bi(r);return n},e.prototype.asString=function(){return this.value},e.prototype.clone=function(){return e.of(this.value)},e.prototype.toString=function(){return"("+this.value+")"},e.prototype.sizeInBytes=function(){return this.value.length+2},e.prototype.copyBytesInto=function(r,n){return r[n++]=g.LeftParen,n+=me(this.value,r,n),r[n++]=g.RightParen,this.value.length+2},e.of=function(r){return new e(r)},e.fromDate=function(r){var n=rt(String(r.getUTCFullYear()),4,"0"),o=rt(String(r.getUTCMonth()+1),2,"0"),i=rt(String(r.getUTCDate()),2,"0"),a=rt(String(r.getUTCHours()),2,"0"),s=rt(String(r.getUTCMinutes()),2,"0"),f=rt(String(r.getUTCSeconds()),2,"0");return new e("D:"+n+o+i+a+s+f+"Z")},e}(ve),ne=d0;var h0=function(){function t(e,r,n,o){var i=this;this.allGlyphsInFontSortedById=function(){for(var a=new Array(i.font.characterSet.length),s=0,f=a.length;s>3)]>>7-((h&7)<<0)&1,R=3*A;s[w]=S[R],s[w+1]=S[R+1],s[w+2]=S[R+2],s[w+3]=A>2)]>>6-((h&3)<<1)&3,R=3*A;s[w]=S[R],s[w+1]=S[R+1],s[w+2]=S[R+2],s[w+3]=A>1)]>>4-((h&1)<<2)&15,R=3*A;s[w]=S[R],s[w+1]=S[R+1],s[w+2]=S[R+2],s[w+3]=A>>3)]>>>7-(L&7)&1),ue=M==x*255?0:255;f[te+L]=ue<<24|M<<16|M<<8|M}else if(c==2)for(var L=0;L>>2)]>>>6-((L&3)<<1)&3),ue=M==x*85?0:255;f[te+L]=ue<<24|M<<16|M<<8|M}else if(c==4)for(var L=0;L>>1)]>>>4-((L&1)<<2)&15),ue=M==x*17?0:255;f[te+L]=ue<<24|M<<16|M<<8|M}else if(c==8)for(var L=0;L>>2<<3));o==0;){if(o=F(e,d,1),i=F(e,d+1,2),d+=3,i==0){(d&7)!=0&&(d+=8-(d&7));var C=(d>>>3)+4,E=e[C-4]|e[C-3]<<8;T&&(r=t.H.W(r,u+E)),r.set(new n(e.buffer,e.byteOffset+C,E),u),d=C+E<<3,u+=E;continue}if(T&&(r=t.H.W(r,u+(1<<17))),i==1&&(p=D.J,h=D.h,l=511,c=31),i==2){a=x(e,d,5)+257,s=x(e,d+5,5)+1,f=x(e,d+10,4)+4,d+=14;for(var I=d,A=1,R=0;R<38;R+=2)D.Q[R]=0,D.Q[R+1]=0;for(var R=0;RA&&(A=z)}d+=3*f,y(D.Q,A),w(D.Q,A,D.u),p=D.w,h=D.d,d=m(D.u,(1<>>4;if(!(L>>>8))r[u++]=L;else{if(L==256)break;var ue=u+L-254;if(L>264){var ye=D.q[L-257];ue=u+(ye>>>3)+x(e,d,ye&7),d+=ye&7}var oe=h[S(e,d)&c];d+=oe&15;var Fe=oe>>>4,Ce=D.c[Fe],Be=(Ce>>>4)+F(e,d,Ce&15);for(d+=Ce&15;u>>4;if(u<=15)a[l]=u,l++;else{var d=0,p=0;u==16?(p=3+s(o,i,2),i+=2,d=a[l-1]):u==17?(p=3+s(o,i,3),i+=3):u==18&&(p=11+s(o,i,7),i+=7);for(var h=l+p;l>>1;ai&&(i=f),a++}for(;a>1,l=e[s+1],c=f<<4|l,u=r-l,d=e[s]<>>15-r;n[h]=c,d++}},t.H.l=function(e,r){for(var n=t.H.m.r,o=15-r,i=0;i>>o}},t.H.M=function(e,r,n){n=n<<(r&7);var o=r>>>3;e[o]|=n,e[o+1]|=n>>>8},t.H.I=function(e,r,n){n=n<<(r&7);var o=r>>>3;e[o]|=n,e[o+1]|=n>>>8,e[o+2]|=n>>>16},t.H.e=function(e,r,n){return(e[r>>>3]|e[(r>>>3)+1]<<8)>>>(r&7)&(1<>>3]|e[(r>>>3)+1]<<8|e[(r>>>3)+2]<<16)>>>(r&7)&(1<>>3]|e[(r>>>3)+1]<<8|e[(r>>>3)+2]<<16)>>>(r&7)},t.H.i=function(e,r){return(e[r>>>3]|e[(r>>>3)+1]<<8|e[(r>>>3)+2]<<16|e[(r>>>3)+3]<<24)>>>(r&7)},t.H.m=function(){var e=Uint16Array,r=Uint32Array;return{K:new e(16),j:new e(16),X:[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],S:[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,999,999,999],T:[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0],q:new e(32),p:[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,65535,65535],z:[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0],c:new r(32),J:new e(512),_:[],h:new e(32),$:[],w:new e(32768),C:[],v:[],d:new e(32768),D:[],u:new e(512),Q:[],r:new e(32768),s:new r(286),Y:new r(30),a:new r(19),t:new r(15e3),k:new e(65536),g:new e(32768)}}(),function(){for(var e=t.H.m,r=32768,n=0;n>>1|(o&1431655765)<<1,o=(o&3435973836)>>>2|(o&858993459)<<2,o=(o&4042322160)>>>4|(o&252645135)<<4,o=(o&4278255360)>>>8|(o&16711935)<<8,e.r[n]=(o>>>16|o<<16)>>>17}function i(a,s,f){for(;s--!=0;)a.push(0,f)}for(var n=0;n<32;n++)e.q[n]=e.S[n]<<3|e.T[n],e.c[n]=e.p[n]<<4|e.z[n];i(e._,144,8),i(e._,112,9),i(e._,24,7),i(e._,8,8),t.H.n(e._,9),t.H.A(e._,9,e.J),t.H.l(e._,9),i(e.$,32,5),t.H.n(e.$,5),t.H.A(e.$,5,e.h),t.H.l(e.$,5),i(e.Q,19,0),i(e.C,286,0),i(e.D,30,0),i(e.v,320,0)}(),t.H.N}();B.decode._readInterlace=function(t,e){for(var r=e.width,n=e.height,o=B.decode._getBPP(e),i=o>>3,a=Math.ceil(r*o/8),s=new Uint8Array(n*a),f=0,l=[0,0,4,0,2,0,1],c=[0,4,0,2,0,1,0],u=[8,8,8,4,4,2,2],d=[8,8,4,4,2,2,1],p=0;p<7;){for(var h=u[p],b=d[p],F=0,x=0,m=l[p];m>3];E=E>>7-(C&7)&1,s[D*a+(T>>3)]|=E<<7-((T&7)<<0)}if(o==2){var E=t[C>>3];E=E>>6-(C&7)&3,s[D*a+(T>>2)]|=E<<6-((T&3)<<1)}if(o==4){var E=t[C>>3];E=E>>4-(C&7)&15,s[D*a+(T>>1)]|=E<<4-((T&1)<<2)}if(o>=8)for(var I=D*a+T*i,A=0;A>3)+A];C+=o,T+=b}S++,D+=h}F*x!=0&&(f+=x*(1+w)),p=p+1}return s};B.decode._getBPP=function(t){var e=[1,null,3,1,2,null,4][t.ctype];return e*t.depth};B.decode._filterZero=function(t,e,r,n,o){var i=B.decode._getBPP(e),a=Math.ceil(n*i/8),s=B.decode._paeth;i=Math.ceil(i/8);var f=0,l=1,c=t[r],u=0;if(c>1&&(t[r]=[0,0,1][c-2]),c==3)for(u=i;u>>1)&255;for(var d=0;d>>1);for(;u>>1)}else{for(;u>8&255,t[e+1]=r&255},readUint:function(t,e){return t[e]*(256*256*256)+(t[e+1]<<16|t[e+2]<<8|t[e+3])},writeUint:function(t,e,r){t[e]=r>>24&255,t[e+1]=r>>16&255,t[e+2]=r>>8&255,t[e+3]=r&255},readASCII:function(t,e,r){for(var n="",o=0;o=0&&s>=0?(u=p*e+h<<2,d=(s+p)*o+a+h<<2):(u=(-s+p)*e-a+h<<2,d=p*o+h<<2),f==0)n[d]=t[u],n[d+1]=t[u+1],n[d+2]=t[u+2],n[d+3]=t[u+3];else if(f==1){var b=t[u+3]*.00392156862745098,F=t[u]*b,x=t[u+1]*b,m=t[u+2]*b,y=n[d+3]*(1/255),w=n[d]*y,S=n[d+1]*y,D=n[d+2]*y,T=1-b,C=b+y*T,E=C==0?0:1/C;n[d+3]=255*C,n[d+0]=(F+w*T)*E,n[d+1]=(x+S*T)*E,n[d+2]=(m+D*T)*E}else if(f==2){var b=t[u+3],F=t[u],x=t[u+1],m=t[u+2],y=n[d+3],w=n[d],S=n[d+1],D=n[d+2];b==y&&F==w&&x==S&&m==D?(n[d]=0,n[d+1]=0,n[d+2]=0,n[d+3]=0):(n[d]=F,n[d+1]=x,n[d+2]=m,n[d+3]=b)}else if(f==3){var b=t[u+3],F=t[u],x=t[u+1],m=t[u+2],y=n[d+3],w=n[d],S=n[d+1],D=n[d+2];if(b==y&&F==w&&x==S&&m==D)continue;if(b<220&&y>20)return!1}return!0};B.encode=function(t,e,r,n,o,i,a){n==null&&(n=0),a==null&&(a=!1);var s=B.encode.compress(t,e,r,n,[!1,!1,!1,0,a]);return B.encode.compressPNG(s,-1),B.encode._main(s,e,r,o,i)};B.encodeLL=function(t,e,r,n,o,i,a,s){for(var f={ctype:0+(n==1?0:2)+(o==0?0:4),depth:i,frames:[]},l=Date.now(),c=(n+o)*i,u=c*e,d=0;d1,u=!1,d=33+(c?20:0);if(o.sRGB!=null&&(d+=13),o.pHYs!=null&&(d+=21),t.ctype==3){for(var p=t.plte.length,h=0;h>>24!=255&&(u=!0);d+=8+p*3+4+(u?8+p*1+4:0)}for(var b=0;b>>8&255,T=w>>>16&255;x[l+y+0]=S,x[l+y+1]=D,x[l+y+2]=T}if(l+=p*3,a(x,l,i(x,l-p*3-4,p*3+4)),l+=4,u){a(x,l,p),l+=4,f(x,l,"tRNS"),l+=4;for(var h=0;h>>24&255;l+=p,a(x,l,i(x,l-p-4,p+4)),l+=4}}for(var C=0,b=0;b>2,R>>2));for(var p=0;pX&&L==M[F-X])te[F]=te[F-X];else{var ue=y[L];if(ue==null&&(y[L]=ue=w.length,w.push(L),w.length>=300))break;te[F]=ue}}}var ye=w.length;ye<=256&&l==!1&&(ye<=2?u=1:ye<=4?u=2:ye<=16?u=4:u=8,u=Math.max(u,f));for(var p=0;p>1)]|=Vo[Wo+we]<<4-(we&1)*4;else if(u==2)for(var we=0;we>2)]|=Vo[Wo+we]<<6-(we&3)*2;else if(u==1)for(var we=0;we>3)]|=Vo[Wo+we]<<7-(we&7)*1}Be=wt,c=3,Gi=1}else if(x==!1&&m.length==1){for(var wt=new Uint8Array(X*Ce*3),ed=X*Ce,F=0;FT&&(T=I),EC&&(C=E))}T==-1&&(S=D=T=C=0),o&&((S&1)==1&&S--,(D&1)==1&&D--);var R=(T-S+1)*(C-D+1);RF&&(F=w),Sx&&(x=S))}F==-1&&(h=b=F=x=0),a&&((h&1)==1&&h--,(b&1)==1&&b--),i={x:h,y:b,width:F-h+1,height:x-b+1};var C=n[o];C.rect=i,C.blend=1,C.img=new Uint8Array(i.width*i.height*4),n[o-1].dispose==0?(B._copyTile(l,e,r,C.img,i.width,i.height,-i.x,-i.y,0),B.encode._prepareDiff(d,e,r,C.img,i)):B._copyTile(d,e,r,C.img,i.width,i.height,-i.x,-i.y,0)};B.encode._prepareDiff=function(t,e,r,n,o){B._copyTile(t,e,r,n,o.width,o.height,-o.x,-o.y,2)};B.encode._filterZero=function(t,e,r,n,o,i,a){var s=[],f=[0,1,2,3,4];i!=-1?f=[i]:(e*n>5e5||r==1)&&(f=[0]);var l;a&&(l={level:0});for(var c=a&&UZIP!=null?UZIP:Lc.default,u=0;u>1)+256&255;if(i==4)for(var l=o;l>1)&255;for(var l=o;l>1)&255}if(i==4){for(var l=0;l>>1:r=r>>>1;t[e]=r}return t}(),update:function(t,e,r,n){for(var o=0;o>>8;return t},crc:function(t,e,r){return B.crc.update(4294967295,t,e,r)^4294967295}};B.quantize=function(t,e){for(var r=new Uint8Array(t),n=r.slice(0),o=new Uint32Array(n.buffer),i=B.quantize.getKDtree(n,e),a=i[0],s=i[1],f=B.quantize.planeDst,l=r,c=o,u=l.length,d=new Uint8Array(r.length>>2),p=0;p>2]=m.ind,c[p>>2]=m.est.rgba}return{abuf:n.buffer,inds:d,plte:s}};B.quantize.getKDtree=function(t,e,r){r==null&&(r=1e-4);var n=new Uint32Array(t.buffer),o={i0:0,i1:t.length,bst:null,est:null,tdst:0,left:null,right:null};o.bst=B.quantize.stats(t,o.i0,o.i1),o.est=B.quantize.estats(o.bst);for(var i=[o];i.lengtha&&(a=i[f].est.L,s=f);if(a=c||l.i1<=c;if(u){l.est.L=0;continue}var d={i0:l.i0,i1:c,bst:null,est:null,tdst:0,left:null,right:null};d.bst=B.quantize.stats(t,d.i0,d.i1),d.est=B.quantize.estats(d.bst);var p={i0:c,i1:l.i1,bst:null,est:null,tdst:0,left:null,right:null};p.bst={R:[],m:[],N:l.bst.N-d.bst.N};for(var f=0;f<16;f++)p.bst.R[f]=l.bst.R[f]-d.bst.R[f];for(var f=0;f<4;f++)p.bst.m[f]=l.bst.m[f]-d.bst.m[f];p.est=B.quantize.estats(p.bst),l.left=d,l.right=p,i[s]=d,i.push(p)}i.sort(function(h,b){return b.bst.N-h.bst.N});for(var f=0;f0&&(a=t.right,s=t.left);var f=B.quantize.getNearest(a,e,r,n,o);if(f.tdst<=i*i)return f;var l=B.quantize.getNearest(s,e,r,n,o);return l.tdsti;)n-=4;if(r>=n)break;var f=e[r>>2];e[r>>2]=e[n>>2],e[n>>2]=f,r+=4,n-=4}for(;a(t,r,o)>i;)r-=4;return r+4};B.quantize.vecDot=function(t,e,r){return t[e]*r[0]+t[e+1]*r[1]+t[e+2]*r[2]+t[e+3]*r[3]};B.quantize.stats=function(t,e,r){for(var n=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],o=[0,0,0,0],i=r-e>>2,a=e;a>>0}};B.M4={multVec:function(t,e){return[t[0]*e[0]+t[1]*e[1]+t[2]*e[2]+t[3]*e[3],t[4]*e[0]+t[5]*e[1]+t[6]*e[2]+t[7]*e[3],t[8]*e[0]+t[9]*e[1]+t[10]*e[2]+t[11]*e[3],t[12]*e[0]+t[13]*e[1]+t[14]*e[2]+t[15]*e[3]]},dot:function(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]+t[3]*e[3]},sml:function(t,e){return[t*e[0],t*e[1],t*e[2],t*e[3]]}};B.encode.concatRGBA=function(t){for(var e=0,r=0;r1)throw new Error("Animated PNGs are not supported");var o=new Uint8Array(n[0]),i=b0(o),a=i.rgbChannel,s=i.alphaChannel;this.rgbChannel=a;var f=s.some(function(l){return l<255});f&&(this.alphaChannel=s),this.type=y0(r.ctype),this.width=r.width,this.height=r.height,this.bitsPerComponent=8}return t.load=function(e){return new t(e)},t}();var x0=function(){function t(e){this.image=e,this.bitsPerComponent=e.bitsPerComponent,this.width=e.width,this.height=e.height,this.colorSpace="DeviceRGB"}return t.for=function(e){return V(this,void 0,void 0,function(){var r;return q(this,function(n){return r=Hc.load(e),[2,new t(r)]})})},t.prototype.embedIntoContext=function(e,r){return V(this,void 0,void 0,function(){var n,o;return q(this,function(i){return n=this.embedAlphaChannel(e),o=e.flateStream(this.image.rgbChannel,{Type:"XObject",Subtype:"Image",BitsPerComponent:this.image.bitsPerComponent,Width:this.image.width,Height:this.image.height,ColorSpace:this.colorSpace,SMask:n}),r?(e.assign(r,o),[2,r]):[2,e.register(o)]})})},t.prototype.embedAlphaChannel=function(e){if(this.image.alphaChannel){var r=e.flateStream(this.image.alphaChannel,{Type:"XObject",Subtype:"Image",Height:this.image.height,Width:this.image.width,BitsPerComponent:this.image.bitsPerComponent,ColorSpace:"DeviceGray",Decode:[0,1]});return e.register(r)}},t}(),co=x0;var F0=function(){function t(e,r,n){this.bytes=e,this.start=r||0,this.pos=this.start,this.end=r&&n?r+n:this.bytes.length}return Object.defineProperty(t.prototype,"length",{get:function(){return this.end-this.start},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"isEmpty",{get:function(){return this.length===0},enumerable:!1,configurable:!0}),t.prototype.getByte=function(){return this.pos>=this.end?-1:this.bytes[this.pos++]},t.prototype.getUint16=function(){var e=this.getByte(),r=this.getByte();return e===-1||r===-1?-1:(e<<8)+r},t.prototype.getInt32=function(){var e=this.getByte(),r=this.getByte(),n=this.getByte(),o=this.getByte();return(e<<24)+(r<<16)+(n<<8)+o},t.prototype.getBytes=function(e,r){r===void 0&&(r=!1);var n=this.bytes,o=this.pos,i=this.end;if(e){var s=o+e;s>i&&(s=i),this.pos=s;var a=n.subarray(o,s);return r?new Uint8ClampedArray(a):a}else{var a=n.subarray(o,i);return r?new Uint8ClampedArray(a):a}},t.prototype.peekByte=function(){var e=this.getByte();return this.pos--,e},t.prototype.peekBytes=function(e,r){r===void 0&&(r=!1);var n=this.getBytes(e,r);return this.pos-=n.length,n},t.prototype.skip=function(e){e||(e=1),this.pos+=e},t.prototype.reset=function(){this.pos=this.start},t.prototype.moveStart=function(){this.start=this.pos},t.prototype.makeSubStream=function(e,r){return new t(this.bytes,e,r)},t.prototype.decode=function(){return this.bytes},t}(),Si=F0;var w0=new Uint8Array(0),S0=function(){function t(e){if(this.pos=0,this.bufferLength=0,this.eof=!1,this.buffer=w0,this.minBufferLength=512,e)for(;this.minBufferLengthi&&(n=i)}else{for(;!this.eof;)this.readBlock();n=this.bufferLength}this.pos=n;var a=this.buffer.subarray(o,n);return r&&!(a instanceof Uint8ClampedArray)?new Uint8ClampedArray(a):a},t.prototype.peekByte=function(){var e=this.getByte();return this.pos--,e},t.prototype.peekBytes=function(e,r){r===void 0&&(r=!1);var n=this.getBytes(e,r);return this.pos-=n.length,n},t.prototype.skip=function(e){e||(e=1),this.pos+=e},t.prototype.reset=function(){this.pos=0},t.prototype.makeSubStream=function(e,r){for(var n=e+r;this.bufferLength<=n&&!this.eof;)this.readBlock();return new Si(this.buffer,e,r)},t.prototype.decode=function(){for(;!this.eof;)this.readBlock();return this.buffer.subarray(0,this.bufferLength)},t.prototype.readBlock=function(){throw new Le(this.constructor.name,"readBlock")},t.prototype.ensureBuffer=function(e){var r=this.buffer;if(e<=r.byteLength)return r;for(var n=this.minBufferLength;n=0;--l)f[s+l]=u&255,u>>=8}},e}(At),Vc=P0;var D0=function(t){k(e,t);function e(r,n){var o=t.call(this,n)||this;return o.stream=r,o.firstDigit=-1,n&&(n=.5*n),o}return e.prototype.readBlock=function(){var r=8e3,n=this.stream.getBytes(r);if(!n.length){this.eof=!0;return}for(var o=n.length+1>>1,i=this.ensureBuffer(this.bufferLength+o),a=this.bufferLength,s=this.firstDigit,f=0,l=n.length;f=48&&c<=57)u=c&15;else if(c>=65&&c<=70||c>=97&&c<=102)u=(c&15)+9;else if(c===62){this.eof=!0;break}else continue;s<0?s=u:(i[a++]=s<<4|u,s=-1)}s>=0&&this.eof&&(i[a++]=s<<4,s=-1),this.firstDigit=s,this.bufferLength=a},e}(At),qc=D0;var Wc=new Int32Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),C0=new Int32Array([3,4,5,6,7,8,9,10,65547,65549,65551,65553,131091,131095,131099,131103,196643,196651,196659,196667,262211,262227,262243,262259,327811,327843,327875,327907,258,258,258]),k0=new Int32Array([1,2,3,4,65541,65543,131081,131085,196625,196633,262177,262193,327745,327777,393345,393409,459009,459137,524801,525057,590849,591361,657409,658433,724993,727041,794625,798721,868353,876545]),T0=[new Int32Array([459008,524368,524304,524568,459024,524400,524336,590016,459016,524384,524320,589984,524288,524416,524352,590048,459012,524376,524312,589968,459028,524408,524344,590032,459020,524392,524328,59e4,524296,524424,524360,590064,459010,524372,524308,524572,459026,524404,524340,590024,459018,524388,524324,589992,524292,524420,524356,590056,459014,524380,524316,589976,459030,524412,524348,590040,459022,524396,524332,590008,524300,524428,524364,590072,459009,524370,524306,524570,459025,524402,524338,590020,459017,524386,524322,589988,524290,524418,524354,590052,459013,524378,524314,589972,459029,524410,524346,590036,459021,524394,524330,590004,524298,524426,524362,590068,459011,524374,524310,524574,459027,524406,524342,590028,459019,524390,524326,589996,524294,524422,524358,590060,459015,524382,524318,589980,459031,524414,524350,590044,459023,524398,524334,590012,524302,524430,524366,590076,459008,524369,524305,524569,459024,524401,524337,590018,459016,524385,524321,589986,524289,524417,524353,590050,459012,524377,524313,589970,459028,524409,524345,590034,459020,524393,524329,590002,524297,524425,524361,590066,459010,524373,524309,524573,459026,524405,524341,590026,459018,524389,524325,589994,524293,524421,524357,590058,459014,524381,524317,589978,459030,524413,524349,590042,459022,524397,524333,590010,524301,524429,524365,590074,459009,524371,524307,524571,459025,524403,524339,590022,459017,524387,524323,589990,524291,524419,524355,590054,459013,524379,524315,589974,459029,524411,524347,590038,459021,524395,524331,590006,524299,524427,524363,590070,459011,524375,524311,524575,459027,524407,524343,590030,459019,524391,524327,589998,524295,524423,524359,590062,459015,524383,524319,589982,459031,524415,524351,590046,459023,524399,524335,590014,524303,524431,524367,590078,459008,524368,524304,524568,459024,524400,524336,590017,459016,524384,524320,589985,524288,524416,524352,590049,459012,524376,524312,589969,459028,524408,524344,590033,459020,524392,524328,590001,524296,524424,524360,590065,459010,524372,524308,524572,459026,524404,524340,590025,459018,524388,524324,589993,524292,524420,524356,590057,459014,524380,524316,589977,459030,524412,524348,590041,459022,524396,524332,590009,524300,524428,524364,590073,459009,524370,524306,524570,459025,524402,524338,590021,459017,524386,524322,589989,524290,524418,524354,590053,459013,524378,524314,589973,459029,524410,524346,590037,459021,524394,524330,590005,524298,524426,524362,590069,459011,524374,524310,524574,459027,524406,524342,590029,459019,524390,524326,589997,524294,524422,524358,590061,459015,524382,524318,589981,459031,524414,524350,590045,459023,524398,524334,590013,524302,524430,524366,590077,459008,524369,524305,524569,459024,524401,524337,590019,459016,524385,524321,589987,524289,524417,524353,590051,459012,524377,524313,589971,459028,524409,524345,590035,459020,524393,524329,590003,524297,524425,524361,590067,459010,524373,524309,524573,459026,524405,524341,590027,459018,524389,524325,589995,524293,524421,524357,590059,459014,524381,524317,589979,459030,524413,524349,590043,459022,524397,524333,590011,524301,524429,524365,590075,459009,524371,524307,524571,459025,524403,524339,590023,459017,524387,524323,589991,524291,524419,524355,590055,459013,524379,524315,589975,459029,524411,524347,590039,459021,524395,524331,590007,524299,524427,524363,590071,459011,524375,524311,524575,459027,524407,524343,590031,459019,524391,524327,589999,524295,524423,524359,590063,459015,524383,524319,589983,459031,524415,524351,590047,459023,524399,524335,590015,524303,524431,524367,590079]),9],E0=[new Int32Array([327680,327696,327688,327704,327684,327700,327692,327708,327682,327698,327690,327706,327686,327702,327694,0,327681,327697,327689,327705,327685,327701,327693,327709,327683,327699,327691,327707,327687,327703,327695,0]),5],A0=function(t){k(e,t);function e(r,n){var o=t.call(this,n)||this;o.stream=r;var i=r.getByte(),a=r.getByte();if(i===-1||a===-1)throw new Error("Invalid header in flate stream: "+i+", "+a);if((i&15)!==8)throw new Error("Unknown compression method in flate stream: "+i+", "+a);if(((i<<8)+a)%31!==0)throw new Error("Bad FCHECK in flate stream: "+i+", "+a);if(a&32)throw new Error("FDICT bit set in flate stream: "+i+", "+a);return o.codeSize=0,o.codeBuf=0,o}return e.prototype.readBlock=function(){var r,n,o=this.stream,i=this.getBits(3);if(i&1&&(this.eof=!0),i>>=1,i===0){var a=void 0;if((a=o.getByte())===-1)throw new Error("Bad block header in flate stream");var s=a;if((a=o.getByte())===-1)throw new Error("Bad block header in flate stream");if(s|=a<<8,(a=o.getByte())===-1)throw new Error("Bad block header in flate stream");var f=a;if((a=o.getByte())===-1)throw new Error("Bad block header in flate stream");if(f|=a<<8,f!==(~s&65535)&&(s!==0||f!==0))throw new Error("Bad uncompressed block length in flate stream");this.codeBuf=0,this.codeSize=0;var l=this.bufferLength;r=this.ensureBuffer(l+s);var c=l+s;if(this.bufferLength=c,s===0)o.peekByte()===-1&&(this.eof=!0);else for(var u=l;u0;)S[m++]=C}d=this.generateHuffmanTable(S.subarray(0,h)),p=this.generateHuffmanTable(S.subarray(h,w))}else throw new Error("Unknown block type in flate stream");r=this.buffer;for(var A=r?r.length:0,R=this.bufferLength;;){var z=this.getCode(d);if(z<256){R+1>=A&&(r=this.ensureBuffer(R+1),A=r.length),r[R++]=z;continue}if(z===256){this.bufferLength=R;return}z-=257,z=C0[z];var M=z>>16;M>0&&(M=this.getBits(M)),n=(z&65535)+M,z=this.getCode(p),z=k0[z],M=z>>16,M>0&&(M=this.getBits(M));var X=(z&65535)+M;R+n>=A&&(r=this.ensureBuffer(R+n),A=r.length);for(var te=0;te>r,this.codeSize=o-=r,a},e.prototype.getCode=function(r){for(var n=this.stream,o=r[0],i=r[1],a=this.codeSize,s=this.codeBuf,f;a>16,u=l&65535;if(c<1||a>c,this.codeSize=a-c,u},e.prototype.generateHuffmanTable=function(r){var n=r.length,o=0,i;for(i=0;io&&(o=r[i]);for(var a=1<>=1;for(i=d;i0;if(!S||S<256)F[0]=S,x=1;else if(S>=258)if(S=0;a--)F[a]=u[s],s=p[s];else F[x++]=F[0];else if(S===256){h=9,c=258,x=0;continue}else{this.eof=!0,delete this.lzwState;break}if(D&&(p[c]=b,d[c]=d[b]+1,u[c]=F[0],c++,h=c+l&c+l-1?h:Math.min(Math.log(c+l)/.6931471805599453+1,12)|0),b=S,m+=x,n>>n&(1<0){var a=this.stream.getBytes(i);n.set(a,o),o+=i}}else{i=257-i;var s=r[1];n=this.ensureBuffer(o+i+1);for(var f=0;fn.size())throw new nn(r,0,n.size());n.remove(r)}else{if(r!==0)throw new nn(r,0,0);this.setKids([])}},e.prototype.normalizedEntries=function(){var r=this.Kids();return r||(r=this.dict.context.obj([this.ref]),this.dict.set(v.of("Kids"),r)),{Kids:r}},e.fromDict=function(r,n){return new e(r,n)},e}(vo),it=q0;var W0=function(t){k(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.Opt=function(){return this.dict.lookupMaybe(v.of("Opt"),ne,H,Z)},e.prototype.setOpt=function(r){this.dict.set(v.of("Opt"),this.dict.context.obj(r))},e.prototype.getExportValues=function(){var r=this.Opt();if(r){if(r instanceof ne||r instanceof H)return[r];for(var n=[],o=0,i=r.size();on.size())throw new nn(r,0,n.size());n.remove(r)}},e.prototype.normalizeExportValues=function(){for(var r,n,o,i,a=(r=this.getExportValues())!==null&&r!==void 0?r:[],s=[],f=this.getWidgets(),l=0,c=f.length;l1){if(!this.hasFlag(le.MultiSelect))throw new mc;this.dict.set(v.of("V"),this.dict.context.obj(r))}this.updateSelectedIndices(r)},e.prototype.valuesAreValid=function(r){for(var n=this.getOptions(),o=function(f,l){var c=r[f].decodeText();if(!n.find(function(u){return c===(u.display||u.value).decodeText()}))return{value:!1}},i=0,a=r.length;i1){for(var n=new Array(r.length),o=this.getOptions(),i=function(f,l){var c=r[f].decodeText();n[f]=o.findIndex(function(u){return c===(u.display||u.value).decodeText()})},a=0,s=r.length;a0){var s=a.lookup(0,ne,H),f=a.lookupMaybe(1,ne,H);n.push({value:s,display:f||s})}}return n}return[]},e}(it),go=K0;var X0=function(t){k(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.fromDict=function(r,n){return new e(r,n)},e.create=function(r){var n=r.obj({FT:"Ch",Ff:le.Combo,Kids:[]}),o=r.register(n);return new e(n,o)},e}(go),rr=X0;var Z0=function(t){k(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.addField=function(r){var n=this.normalizedEntries().Kids;n?.push(r)},e.prototype.normalizedEntries=function(){var r=this.Kids();return r||(r=this.dict.context.obj([]),this.dict.set(v.of("Kids"),r)),{Kids:r}},e.fromDict=function(r,n){return new e(r,n)},e.create=function(r){var n=r.obj({}),o=r.register(n);return new e(n,o)},e}(vo),nr=Z0;var Y0=function(t){k(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.fromDict=function(r,n){return new e(r,n)},e}(it),Nr=Y0;var J0=function(t){k(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.MaxLen=function(){var r=this.dict.lookup(v.of("MaxLen"));if(r instanceof j)return r},e.prototype.Q=function(){var r=this.dict.lookup(v.of("Q"));if(r instanceof j)return r},e.prototype.setMaxLength=function(r){this.dict.set(v.of("MaxLen"),j.of(r))},e.prototype.removeMaxLength=function(){this.dict.delete(v.of("MaxLen"))},e.prototype.getMaxLength=function(){var r;return(r=this.MaxLen())===null||r===void 0?void 0:r.asNumber()},e.prototype.setQuadding=function(r){this.dict.set(v.of("Q"),j.of(r))},e.prototype.getQuadding=function(){var r;return(r=this.Q())===null||r===void 0?void 0:r.asNumber()},e.prototype.setValue=function(r){this.dict.set(v.of("V"),r)},e.prototype.removeValue=function(){this.dict.delete(v.of("V"))},e.prototype.getValue=function(){var r=this.V();if(r instanceof ne||r instanceof H)return r},e.fromDict=function(r,n){return new e(r,n)},e.create=function(r){var n=r.obj({FT:"Tx",Kids:[]}),o=r.register(n);return new e(n,o)},e}(it),or=J0;var Q0=function(t){k(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.fromDict=function(r,n){return new e(r,n)},e.create=function(r){var n=r.obj({FT:"Btn",Ff:qe.PushButton,Kids:[]}),o=r.register(n);return new e(n,o)},e}(Br),ir=Q0;var _0=function(t){k(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.setValue=function(r){var n=this.getOnValues();if(!n.includes(r)&&r!==v.of("Off"))throw new on;this.dict.set(v.of("V"),r);for(var o=this.getWidgets(),i=0,a=o.length;ii)throw new Ma(n,i);for(var a=n,s=0,f=o.size();sa)return c.insertLeafNode(r,a)||l;a-=c.Count().asNumber()}c instanceof Ze&&(a-=1)}if(a===0){this.insertLeafKid(o.size(),r);return}throw new Ia(n,"insertLeafNode")},e.prototype.removeLeafNode=function(r,n){n===void 0&&(n=!0);var o=this.Kids(),i=this.Count().asNumber();if(r>=i)throw new Ma(r,i);for(var a=r,s=0,f=o.size();sa){c.removeLeafNode(a,n),n&&c.Kids().size()===0&&o.remove(s);return}else a-=c.Count().asNumber();if(c instanceof Ze)if(a===0){this.removeKid(s);return}else a-=1}throw new Ia(r,"removeLeafNode")},e.prototype.ascend=function(r){r(this);var n=this.Parent();n&&n.ascend(r)},e.prototype.traverse=function(r){for(var n=this.Kids(),o=0,i=n.size();oNumber.MAX_SAFE_INTEGER)if(this.capNumbers){var o="Parsed number that is too large for some PDF readers: "+e+", using Number.MAX_SAFE_INTEGER instead.";return console.warn(o),Number.MAX_SAFE_INTEGER}else{var o="Parsed number that is too large for some PDF readers: "+e+", not capping.";console.warn(o)}return n},t.prototype.skipWhitespace=function(){for(;!this.bytes.done()&&ft[this.bytes.peek()];)this.bytes.next()},t.prototype.skipLine=function(){for(;!this.bytes.done();){var e=this.bytes.peek();if(e===Qc||e===_c)return;this.bytes.next()}},t.prototype.skipComment=function(){if(this.bytes.peek()!==g.Percent)return!1;for(;!this.bytes.done();){var e=this.bytes.peek();if(e===Qc||e===_c)return!0;this.bytes.next()}return!0},t.prototype.skipWhitespaceAndComments=function(){for(this.skipWhitespace();this.skipComment();)this.skipWhitespace()},t.prototype.matchKeyword=function(e){for(var r=this.bytes.offset(),n=0,o=e.length;n=this.length},t.prototype.offset=function(){return this.idx},t.prototype.slice=function(e,r){return this.bytes.slice(e,r)},t.prototype.position=function(){return{line:this.line,column:this.column,offset:this.idx}},t.of=function(e){return new t(e)},t.fromPDFRawStream=function(e){return t.of(uo(e).decode())},t}(),lr=lv;var fv=g.Space,wo=g.CarriageReturn,So=g.Newline,Po=[g.s,g.t,g.r,g.e,g.a,g.m],Ti=[g.e,g.n,g.d,g.s,g.t,g.r,g.e,g.a,g.m],pe={header:[g.Percent,g.P,g.D,g.F,g.Dash],eof:[g.Percent,g.Percent,g.E,g.O,g.F],obj:[g.o,g.b,g.j],endobj:[g.e,g.n,g.d,g.o,g.b,g.j],xref:[g.x,g.r,g.e,g.f],trailer:[g.t,g.r,g.a,g.i,g.l,g.e,g.r],startxref:[g.s,g.t,g.a,g.r,g.t,g.x,g.r,g.e,g.f],true:[g.t,g.r,g.u,g.e],false:[g.f,g.a,g.l,g.s,g.e],null:[g.n,g.u,g.l,g.l],stream:Po,streamEOF1:re(Po,[fv,wo,So]),streamEOF2:re(Po,[wo,So]),streamEOF3:re(Po,[wo]),streamEOF4:re(Po,[So]),endstream:Ti,EOF1endstream:re([wo,So],Ti),EOF2endstream:re([wo],Ti),EOF3endstream:re([So],Ti)};var cv=function(t){k(e,t);function e(r,n,o){o===void 0&&(o=!1);var i=t.call(this,r,o)||this;return i.context=n,i}return e.prototype.parseObject=function(){if(this.skipWhitespaceAndComments(),this.matchKeyword(pe.true))return Ut.True;if(this.matchKeyword(pe.false))return Ut.False;if(this.matchKeyword(pe.null))return Te;var r=this.bytes.peek();if(r===g.LessThan&&this.bytes.peekAhead(1)===g.LessThan)return this.parseDictOrStream();if(r===g.LessThan)return this.parseHexString();if(r===g.LeftParen)return this.parseString();if(r===g.ForwardSlash)return this.parseName();if(r===g.LeftSquareBracket)return this.parseArray();if(Fo[r])return this.parseNumberOrRef();throw new xc(this.bytes.position(),r)},e.prototype.parseNumberOrRef=function(){var r=this.parseRawNumber();this.skipWhitespaceAndComments();var n=this.bytes.offset();if(Ie[this.bytes.peek()]){var o=this.parseRawNumber();if(this.skipWhitespaceAndComments(),this.bytes.peek()===g.R)return this.bytes.assertNext(g.R),J.of(r,o)}return this.bytes.moveTo(n),j.of(r)},e.prototype.parseHexString=function(){var r="";for(this.bytes.assertNext(g.LessThan);!this.bytes.done()&&this.bytes.peek()!==g.GreaterThan;)r+=tt(this.bytes.next());return this.bytes.assertNext(g.GreaterThan),H.of(r)},e.prototype.parseString=function(){for(var r=0,n=!1,o="";!this.bytes.done();){var i=this.bytes.next();if(o+=tt(i),n||(i===g.LeftParen&&(r+=1),i===g.RightParen&&(r-=1)),i===g.BackSlash?n=!n:n&&(n=!1),r===0)return ne.of(o.substring(1,o.length-1))}throw new Sc(this.bytes.position())},e.prototype.parseName=function(){this.bytes.assertNext(g.ForwardSlash);for(var r="";!this.bytes.done();){var n=this.bytes.peek();if(ft[n]||et[n])break;r+=tt(n),this.bytes.next()}return v.of(r)},e.prototype.parseArray=function(){this.bytes.assertNext(g.LeftSquareBracket),this.skipWhitespaceAndComments();for(var r=Z.withContext(this.context);this.bytes.peek()!==g.RightSquareBracket;){var n=this.parseObject();r.push(n),this.skipWhitespaceAndComments()}return this.bytes.assertNext(g.RightSquareBracket),r},e.prototype.parseDict=function(){this.bytes.assertNext(g.LessThan),this.bytes.assertNext(g.LessThan),this.skipWhitespaceAndComments();for(var r=new Map;!this.bytes.done()&&this.bytes.peek()!==g.GreaterThan&&this.bytes.peekAhead(1)!==g.GreaterThan;){var n=this.parseName(),o=this.parseObject();r.set(n,o),this.skipWhitespaceAndComments()}this.skipWhitespaceAndComments(),this.bytes.assertNext(g.GreaterThan),this.bytes.assertNext(g.GreaterThan);var i=r.get(v.of("Type"));return i===v.of("Catalog")?bo.fromMapWithContext(r,this.context):i===v.of("Pages")?xo.fromMapWithContext(r,this.context):i===v.of("Page")?Ze.fromMapWithContext(r,this.context):U.fromMapWithContext(r,this.context)},e.prototype.parseDictOrStream=function(){var r=this.bytes.position(),n=this.parseDict();if(this.skipWhitespaceAndComments(),!this.matchKeyword(pe.streamEOF1)&&!this.matchKeyword(pe.streamEOF2)&&!this.matchKeyword(pe.streamEOF3)&&!this.matchKeyword(pe.streamEOF4)&&!this.matchKeyword(pe.stream))return n;var o=this.bytes.offset(),i,a=n.get(v.of("Length"));a instanceof j?(i=o+a.asNumber(),this.bytes.moveTo(i),this.skipWhitespaceAndComments(),this.matchKeyword(pe.endstream)||(this.bytes.moveTo(o),i=this.findEndOfStreamFallback(r))):i=this.findEndOfStreamFallback(r);var s=this.bytes.slice(o,i);return Et.of(n,s)},e.prototype.findEndOfStreamFallback=function(r){for(var n=1,o=this.bytes.offset();!this.bytes.done()&&(o=this.bytes.offset(),this.matchKeyword(pe.stream)?n+=1:this.matchKeyword(pe.EOF1endstream)||this.matchKeyword(pe.EOF2endstream)||this.matchKeyword(pe.EOF3endstream)||this.matchKeyword(pe.endstream)?n-=1:this.bytes.next(),n!==0););if(n!==0)throw new wc(r);return o},e.forBytes=function(r,n,o){return new e(lr.of(r),n,o)},e.forByteStream=function(r,n,o){return o===void 0&&(o=!1),new e(r,n,o)},e}($c),Do=cv;var uv=function(t){k(e,t);function e(r,n){var o=t.call(this,lr.fromPDFRawStream(r),r.dict.context)||this,i=r.dict;return o.alreadyParsed=!1,o.shouldWaitForTick=n||function(){return!1},o.firstOffset=i.lookup(v.of("First"),j).asNumber(),o.objectCount=i.lookup(v.of("N"),j).asNumber(),o}return e.prototype.parseIntoContext=function(){return V(this,void 0,void 0,function(){var r,n,o,i,a,s,f,l;return q(this,function(c){switch(c.label){case 0:if(this.alreadyParsed)throw new rn("PDFObjectStreamParser","parseIntoContext");this.alreadyParsed=!0,r=this.parseOffsetsAndObjectNumbers(),n=0,o=r.length,c.label=1;case 1:return n=g.Space&&n<=g.Tilde;if(o&&(this.matchKeyword(pe.xref)||this.matchKeyword(pe.trailer)||this.matchKeyword(pe.startxref)||this.matchIndirectObjectHeader())){this.bytes.moveTo(r);break}this.bytes.next()}},e.prototype.skipBinaryHeaderComment=function(){this.skipWhitespaceAndComments();try{var r=this.bytes.offset();this.parseIndirectObjectHeader(),this.bytes.moveTo(r)}catch{this.bytes.next(),this.skipWhitespaceAndComments()}},e.forBytesWithOptions=function(r,n,o,i){return new e(r,n,o,i)},e}(Do),$a=hv;var Rt=function(t){return 1<0&&(n[n.length]=+o),r[r.length]={cmd:e,args:n},n=[],o="",i=!1),e=l;else if([" ",","].includes(l)||l==="-"&&o.length>0&&o[o.length-1]!=="e"||l==="."&&i){if(o.length===0)continue;n.length===a?(r[r.length]={cmd:e,args:n},n=[+o],e==="M"&&(e="L"),e==="m"&&(e="l")):n[n.length]=+o,i=l===".",o=["-","."].includes(l)?l:""}else o+=l,l==="."&&(i=!0)}return o.length>0&&(n.length===a?(r[r.length]={cmd:e,args:n},n=[+o],e==="M"&&(e="L"),e==="m"&&(e="l")):n[n.length]=+o),r[r.length]={cmd:e,args:n},r},gv=function(t){G=K=fe=ce=No=Mo=0;for(var e=[],r=0;r1&&(d=Math.sqrt(d),r*=d,n*=d);var p=u/r,h=c/r,b=-c/n,F=u/n,x=p*s+h*f,m=b*s+F*f,y=p*t+h*e,w=b*t+F*e,S=(y-x)*(y-x)+(w-m)*(w-m),D=1/S-.25;D<0&&(D=0);var T=Math.sqrt(D);i===o&&(T=-T);var C=.5*(x+y)-T*(w-m),E=.5*(m+w)+T*(y-x),I=Math.atan2(m-E,x-C),A=Math.atan2(w-E,y-C),R=A-I;R<0&&i===1?R+=2*Math.PI:R>0&&i===0&&(R-=2*Math.PI);for(var z=Math.ceil(Math.abs(R/(Math.PI*.5+.001))),M=[],X=0;Xt.length)return o-1;var F=e.heightAtSize(o),x=F+F*.2,m=x*i;if(m>Math.abs(r.height))return o-1;o+=1}return o},Sv=function(t,e,r,n){for(var o=r.width/n,i=r.height,a=Ou,s=zs(t);ao*.75;if(u)return a-1}var d=e.heightAtSize(a,{descender:!1});if(d>i)return a-1;a+=1}return a},Pv=function(t){for(var e=t.length;e>0;e--)if(/\s/.test(t[e]))return e},Dv=function(t,e,r,n){for(var o,i=t.length;i>0;){var a=t.substring(0,i),s=r.encodeText(a),f=r.widthOfTextAtSize(a,n);if(fd&&(d=T+S),h+s>p&&(p=h+s),l.push({text:y,encoded:w,width:S,height:s,x:T,y:h}),x=D?.trim()}return{fontSize:n,lineHeight:f,lines:l,bounds:{x:c,y:u,width:d-c,height:p-u}}},Mu=function(t,e){var r=e.fontSize,n=e.font,o=e.bounds,i=e.cellCount,a=Zi(pr(t));if(a.length>i)throw new Eu(a.length,i);(r===void 0||r===0)&&(r=Sv(a,n,o,i));for(var s=o.width/i,f=n.heightAtSize(r,{descender:!1}),l=o.y+(o.height/2-f/2),c=[],u=o.x,d=o.y,p=o.x+o.width,h=o.y+o.height,b=0,F=0;bp&&(p=T+S),l+f>h&&(h=l+f),c.push({text:a,encoded:w,width:S,height:f,x:T,y:l}),b+=1,F+=y}return{fontSize:r,cells:c,bounds:{x:u,y:d,width:p-u,height:h-d}}},jo=function(t,e){var r=e.alignment,n=e.fontSize,o=e.font,i=e.bounds,a=Zi(pr(t));(n===void 0||n===0)&&(n=Nu([a],o,i));var s=o.encodeText(a),f=o.widthOfTextAtSize(a,n),l=o.heightAtSize(n,{descender:!1}),c=r===De.Left?i.x:r===De.Center?i.x+i.width/2-f/2:r===De.Right?i.x+i.width-f:i.x,u=i.y+(i.height/2-l/2);return{fontSize:n,line:{text:a,encoded:s,width:f,height:l,x:c,y:u},bounds:{x:c,y:u,width:f,height:l}}};var pt=function(t){return"normal"in t?t:{normal:t}},Cv=/\/([^\0\t\n\f\r\ ]+)[\0\t\n\f\r\ ]+(\d*\.\d+|\d+)[\0\t\n\f\r\ ]+Tf/,dr=function(t){var e,r,n=(e=t.getDefaultAppearance())!==null&&e!==void 0?e:"",o=(r=On(n,Cv).match)!==null&&r!==void 0?r:[],i=Number(o[2]);return isFinite(i)?i:void 0},kv=/(\d*\.\d+|\d+)[\0\t\n\f\r\ ]*(\d*\.\d+|\d+)?[\0\t\n\f\r\ ]*(\d*\.\d+|\d+)?[\0\t\n\f\r\ ]*(\d*\.\d+|\d+)?[\0\t\n\f\r\ ]+(g|rg|k)/,dt=function(t){var e,r=(e=t.getDefaultAppearance())!==null&&e!==void 0?e:"",n=On(r,kv).match,o=n??[],i=o[1],a=o[2],s=o[3],f=o[4],l=o[5];if(l==="g"&&i)return fs(Number(i));if(l==="rg"&&i&&a&&s)return ae(Number(i),Number(a),Number(s));if(l==="k"&&i&&a&&s&&f)return cs(Number(i),Number(a),Number(s),Number(f))},ht=function(t,e,r,n){var o;n===void 0&&(n=0);var i=[Bt(e).toString(),Oo((o=r?.name)!==null&&o!==void 0?o:"dummy__noop",n).toString()].join(` -`);t.setDefaultAppearance(i)},Iu=function(t,e){var r,n,o,i=dt(e),a=dt(t.acroField),s=e.getRectangle(),f=e.getAppearanceCharacteristics(),l=e.getBorderStyle(),c=(r=l?.getWidth())!==null&&r!==void 0?r:0,u=bt(f?.getRotation()),d=qt(s,u),p=d.width,h=d.height,b=xt(Y(Y({},s),{rotation:u})),F=ae(0,0,0),x=(n=We(f?.getBorderColor()))!==null&&n!==void 0?n:F,m=We(f?.getBackgroundColor()),y=We(f?.getBackgroundColor(),.8),w=(o=i??a)!==null&&o!==void 0?o:F;ht(i?e:t.acroField,w);var S={x:0+c/2,y:0+c/2,width:p-c,height:h-c,thickness:1.5,borderWidth:c,borderColor:x,markColor:w};return{normal:{on:re(b,Io(Y(Y({},S),{color:m,filled:!0}))),off:re(b,Io(Y(Y({},S),{color:m,filled:!1})))},down:{on:re(b,Io(Y(Y({},S),{color:y,filled:!0}))),off:re(b,Io(Y(Y({},S),{color:y,filled:!1})))}}},zu=function(t,e){var r,n,o,i=dt(e),a=dt(t.acroField),s=e.getRectangle(),f=e.getAppearanceCharacteristics(),l=e.getBorderStyle(),c=(r=l?.getWidth())!==null&&r!==void 0?r:0,u=bt(f?.getRotation()),d=qt(s,u),p=d.width,h=d.height,b=xt(Y(Y({},s),{rotation:u})),F=ae(0,0,0),x=(n=We(f?.getBorderColor()))!==null&&n!==void 0?n:F,m=We(f?.getBackgroundColor()),y=We(f?.getBackgroundColor(),.8),w=(o=i??a)!==null&&o!==void 0?o:F;ht(i?e:t.acroField,w);var S={x:p/2,y:h/2,width:p-c,height:h-c,borderWidth:c,borderColor:x,dotColor:w};return{normal:{on:re(b,zo(Y(Y({},S),{color:m,filled:!0}))),off:re(b,zo(Y(Y({},S),{color:m,filled:!1})))},down:{on:re(b,zo(Y(Y({},S),{color:y,filled:!0}))),off:re(b,zo(Y(Y({},S),{color:y,filled:!1})))}}},ju=function(t,e,r){var n,o,i,a,s,f=dt(e),l=dt(t.acroField),c=dr(e),u=dr(t.acroField),d=e.getRectangle(),p=e.getAppearanceCharacteristics(),h=e.getBorderStyle(),b=p?.getCaptions(),F=(n=b?.normal)!==null&&n!==void 0?n:"",x=(i=(o=b?.down)!==null&&o!==void 0?o:F)!==null&&i!==void 0?i:"",m=(a=h?.getWidth())!==null&&a!==void 0?a:0,y=bt(p?.getRotation()),w=qt(d,y),S=w.width,D=w.height,T=xt(Y(Y({},d),{rotation:y})),C=ae(0,0,0),E=We(p?.getBorderColor()),I=We(p?.getBackgroundColor()),A=We(p?.getBackgroundColor(),.8),R={x:m,y:m,width:S-m*2,height:D-m*2},z=jo(F,{alignment:De.Center,fontSize:c??u,font:r,bounds:R}),M=jo(x,{alignment:De.Center,fontSize:c??u,font:r,bounds:R}),X=Math.min(z.fontSize,M.fontSize),te=(s=f??l)!==null&&s!==void 0?s:C;ht(f||c!==void 0?e:t.acroField,te,r,X);var L={x:0+m/2,y:0+m/2,width:S-m,height:D-m,borderWidth:m,borderColor:E,textColor:te,font:r.name,fontSize:X};return{normal:re(T,vs(Y(Y({},L),{color:I,textLines:[z.line]}))),down:re(T,vs(Y(Y({},L),{color:A,textLines:[M.line]})))}},Lu=function(t,e,r){var n,o,i,a,s=dt(e),f=dt(t.acroField),l=dr(e),c=dr(t.acroField),u=e.getRectangle(),d=e.getAppearanceCharacteristics(),p=e.getBorderStyle(),h=(n=t.getText())!==null&&n!==void 0?n:"",b=(o=p?.getWidth())!==null&&o!==void 0?o:0,F=bt(d?.getRotation()),x=qt(u,F),m=x.width,y=x.height,w=xt(Y(Y({},u),{rotation:F})),S=ae(0,0,0),D=We(d?.getBorderColor()),T=We(d?.getBackgroundColor()),C,E,I=t.isCombed()?0:1,A={x:b+I,y:b+I,width:m-(b+I)*2,height:y-(b+I)*2};if(t.isMultiline()){var R=bs(h,{alignment:t.getAlignment(),fontSize:l??c,font:r,bounds:A});C=R.lines,E=R.fontSize}else if(t.isCombed()){var R=Mu(h,{fontSize:l??c,font:r,bounds:A,cellCount:(i=t.getMaxLength())!==null&&i!==void 0?i:0});C=R.cells,E=R.fontSize}else{var R=jo(h,{alignment:t.getAlignment(),fontSize:l??c,font:r,bounds:A});C=[R.line],E=R.fontSize}var z=(a=s??f)!==null&&a!==void 0?a:S;ht(s||l!==void 0?e:t.acroField,z,r,E);var M={x:0+b/2,y:0+b/2,width:m-b,height:y-b,borderWidth:b??0,borderColor:D,textColor:z,font:r.name,fontSize:E,color:T,textLines:C,padding:I};return re(w,gs(M))},Hu=function(t,e,r){var n,o,i,a=dt(e),s=dt(t.acroField),f=dr(e),l=dr(t.acroField),c=e.getRectangle(),u=e.getAppearanceCharacteristics(),d=e.getBorderStyle(),p=(n=t.getSelected()[0])!==null&&n!==void 0?n:"",h=(o=d?.getWidth())!==null&&o!==void 0?o:0,b=bt(u?.getRotation()),F=qt(c,b),x=F.width,m=F.height,y=xt(Y(Y({},c),{rotation:b})),w=ae(0,0,0),S=We(u?.getBorderColor()),D=We(u?.getBackgroundColor()),T=1,C={x:h+T,y:h+T,width:x-(h+T)*2,height:m-(h+T)*2},E=jo(p,{alignment:De.Left,fontSize:f??l,font:r,bounds:C}),I=E.line,A=E.fontSize,R=(i=a??s)!==null&&i!==void 0?i:w;ht(a||f!==void 0?e:t.acroField,R,r,A);var z={x:0+h/2,y:0+h/2,width:x-h,height:m-h,borderWidth:h??0,borderColor:S,textColor:R,font:r.name,fontSize:A,color:D,textLines:[I],padding:T};return re(y,gs(z))},Uu=function(t,e,r){var n,o,i=dt(e),a=dt(t.acroField),s=dr(e),f=dr(t.acroField),l=e.getRectangle(),c=e.getAppearanceCharacteristics(),u=e.getBorderStyle(),d=(n=u?.getWidth())!==null&&n!==void 0?n:0,p=bt(c?.getRotation()),h=qt(l,p),b=h.width,F=h.height,x=xt(Y(Y({},l),{rotation:p})),m=ae(0,0,0),y=We(c?.getBorderColor()),w=We(c?.getBackgroundColor()),S=t.getOptions(),D=t.getSelected();t.isSorted()&&S.sort();for(var T="",C=0,E=S.length;C1||o.length===1&&n)&&this.enableMultiselect();for(var s=new Array(o.length),f=0,l=o.length;f1||o.length===1&&n)&&this.enableMultiselect();for(var a=new Array(o.length),s=0,f=o.length;sn)throw new Au(r.length,n,this.getName());this.markAsDirty(),this.disableRichFormatting(),r?this.acroField.setValue(H.fromText(r)):this.acroField.removeValue()},e.prototype.getAlignment=function(){var r=this.acroField.getQuadding();return r===0?De.Left:r===1?De.Center:r===2?De.Right:De.Left},e.prototype.setAlignment=function(r){yt(r,"alignment",De),this.markAsDirty(),this.acroField.setQuadding(r)},e.prototype.getMaxLength=function(){return this.acroField.getMaxLength()},e.prototype.setMaxLength=function(r){if(ot(r,"maxLength",0,Number.MAX_SAFE_INTEGER),this.markAsDirty(),r===void 0)this.acroField.removeMaxLength();else{var n=this.getText();if(n&&n.length>r)throw new Ru(n.length,r,this.getName());this.acroField.setMaxLength(r)}},e.prototype.removeMaxLength=function(){this.markAsDirty(),this.acroField.removeMaxLength()},e.prototype.setImage=function(r){for(var n=this.getAlignment(),o=n===De.Center?Ft.Center:n===De.Right?Ft.Right:Ft.Left,i=this.acroField.getWidgets(),a=0,s=i.length;at/25.4*96;function Kv(t){return t.pageSize==="Custom"?{w:Math.max(1,Math.round(kn(t.customPageWidth))),h:Math.max(1,Math.round(kn(t.customPageHeight)))}:Vi[t.pageSize]??Vi.A4}function Ui(t){return t.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'")}function Gu(t){return t.replace(/<\/style/gi,"<\\/style")}function Cn(t,e){let r=e.trim();if(!r)return"";if(/^(https?:|data:)/i.test(r))return r;let n=t.vault.getAbstractFileByPath(r);if(n instanceof N.TFile)return t.vault.getResourcePath(n);let o=t.metadataCache.getFirstLinkpathDest(r,"");return o instanceof N.TFile?t.vault.getResourcePath(o):(console.warn("[advanced-pdf-export] Could not resolve image path:",r),r)}function Ku(t){return{size:t==="fill"?"100% 100%":t==="tile"?"auto":t,repeat:t==="tile"?"repeat":"no-repeat"}}var Xv=/[\u0590-\u08FF\uFB1D-\uFDFD\uFE70-\uFEFC]/g,Zv=/[A-Za-z\u0590-\u08FF\uFB1D-\uFDFD\uFE70-\uFEFC]/g;function Yv(t){let e=(t.match(Xv)??[]).length,r=(t.match(Zv)??[]).length;return r>0&&e/r>.1}function Jv(t){return t.replace(/\r\n|\r/g,` -`)}function Qv(t){return t.replace(/^---[ \t]*\n[\s\S]*?\n---[ \t]*(\n|$)/,"")}function _v(t){return t.split(/^\/\/\/\s*$/m).map(e=>e.trim()).filter(Boolean)}async function $v(t){let e=new N.Component;e.load();try{await Qu(t,"$\\mathbf{A}+\\mathfrak{A}+\\mathcal{A}+\\mathsf{A}+\\mathtt{A}+\\mathbb{A}+\\aleph+\\vec{v}$","",e)}catch(r){console.warn("[advanced-pdf-export] MathJax warm-up failed (non-fatal):",r)}finally{e.unload()}}async function Qu(t,e,r,n){let o=activeDocument.createElement("div");o.setCssStyles({position:"fixed",top:"0",left:"-99999px",visibility:"hidden",pointerEvents:"none"}),activeDocument.body.appendChild(o);try{await N.MarkdownRenderer.render(t,e,o,r,n);let i=3e3;try{let s;await Promise.race([(0,N.finishRenderMath)().finally(()=>window.clearTimeout(s)),new Promise(f=>{s=window.setTimeout(f,i)})])}catch(s){console.warn("[advanced-pdf-export] finishRenderMath failed:",s)}await om(o),await im(o);let a=activeDocument.fonts;if(a)try{await a.ready}catch{}}finally{activeDocument.body.removeChild(o)}return nm(o),o}var em=/[^\p{L}\p{N}\s-]/gu,tm=/\s+/g,rm=/-+/g;function Xu(t){return t.toLowerCase().replace(em,"").trim().replace(tm,"-").replace(rm,"-")}function nm(t){let e=new Map;t.querySelectorAll("h1,h2,h3,h4,h5,h6").forEach(r=>{let n=r.textContent||"",o=Xu(n);if(!o)return;let i=e.get(o)??0;e.set(o,i+1),r.id=i===0?o:`${o}-${i}`}),t.querySelectorAll("a").forEach(r=>{r.classList.remove("external-link");let n=r.getAttribute("data-href")??r.getAttribute("href");n?.startsWith("#")&&r.setAttribute("href","#"+Xu(n.slice(1)))}),t.querySelectorAll(".copy-code-button").forEach(r=>r.remove()),t.querySelectorAll(".callout").forEach(r=>{r.removeAttribute("data-callout-fold"),r.classList.remove("is-collapsed"),r.querySelectorAll(".callout-fold").forEach(n=>n.remove())}),t.querySelectorAll("style, script").forEach(r=>{r.closest("svg")||r.remove()})}async function om(t){let e=Array.from(t.querySelectorAll(".mermaid"));if(e.length===0)return;let r=5e3;await Promise.all(e.map(n=>new Promise(o=>{if(n.querySelector("svg")){o();return}let i=window.setTimeout(()=>{a.disconnect(),o()},r),a=new MutationObserver(()=>{n.querySelector("svg")&&(window.clearTimeout(i),a.disconnect(),o())});a.observe(n,{childList:!0,subtree:!0})})))}async function im(t){let e=Array.from(t.querySelectorAll(".math"));if(e.length===0)return;let r=window.MathJax;if(r?.startup?.promise)try{await r.startup.promise}catch{}let n=8e3;await Promise.all(e.filter(o=>!o.querySelector("mjx-container")).map(o=>new Promise(i=>{let a=window.setTimeout(()=>{s.disconnect(),i()},n),s=new MutationObserver(()=>{o.querySelector("mjx-container")&&(window.clearTimeout(a),s.disconnect(),i())});s.observe(o,{childList:!0,subtree:!0})}))),await Ds()}async function Ds(){let n=Date.now(),o=qi().length,i=0;for(;i<2&&Date.now()-n<2500;){await new Promise(s=>window.setTimeout(s,60));let a=qi().length;a===o?i++:(i=0,o=a)}}var am={comment:["comment","prolog","doctype","cdata"],punctuation:["punctuation"],property:["property","tag","boolean","number","constant","symbol","deleted","attr-name"],selector:["selector","string","char","builtin","inserted","attr-value"],operator:["operator","entity","url"],keyword:["atrule","keyword","important"],function:["function","class-name"],regex:["regex","variable"]},Cs={none:{name:"None (plain)"},"github-light":{name:"GitHub Light",background:"#f6f8fa",text:"#24292e",tokens:{comment:"#6a737d",punctuation:"#24292e",property:"#005cc5",selector:"#032f62",operator:"#d73a49",keyword:"#d73a49",function:"#6f42c1",regex:"#032f62"}},"github-dark":{name:"GitHub Dark",background:"#0d1117",text:"#c9d1d9",tokens:{comment:"#8b949e",punctuation:"#c9d1d9",property:"#79c0ff",selector:"#a5d6ff",operator:"#ff7b72",keyword:"#ff7b72",function:"#d2a8ff",regex:"#a5d6ff"}},"atom-one-light":{name:"Atom One Light",background:"#fafafa",text:"#383a42",tokens:{comment:"#a0a1a7",punctuation:"#383a42",property:"#986801",selector:"#50a14f",operator:"#0184bc",keyword:"#a626a4",function:"#4078f2",regex:"#50a14f"}},"atom-one-dark":{name:"Atom One Dark",background:"#282c34",text:"#abb2bf",tokens:{comment:"#5c6370",punctuation:"#abb2bf",property:"#d19a66",selector:"#98c379",operator:"#56b6c2",keyword:"#c678dd",function:"#61afef",regex:"#98c379"}},monokai:{name:"Monokai",background:"#272822",text:"#f8f8f2",tokens:{comment:"#75715e",punctuation:"#f8f8f2",property:"#ae81ff",selector:"#e6db74",operator:"#f92672",keyword:"#f92672",function:"#a6e22e",regex:"#e6db74"}},dracula:{name:"Dracula",background:"#282a36",text:"#f8f8f2",tokens:{comment:"#6272a4",punctuation:"#f8f8f2",property:"#bd93f9",selector:"#f1fa8c",operator:"#ff79c6",keyword:"#ff79c6",function:"#50fa7b",regex:"#ff79c6"}},"tokyo-night":{name:"Tokyo Night",background:"#1a1b26",text:"#a9b1d6",tokens:{comment:"#565f89",punctuation:"#89ddff",property:"#ff9e64",selector:"#9ece6a",operator:"#89ddff",keyword:"#bb9af7",function:"#7aa2f7",regex:"#b4f9f8"}},"solarized-light":{name:"Solarized Light",background:"#fdf6e3",text:"#586e75",tokens:{comment:"#93a1a1",punctuation:"#586e75",property:"#cb4b16",selector:"#2aa198",operator:"#859900",keyword:"#859900",function:"#268bd2",regex:"#2aa198"}},"catppuccin-macchiato":{name:"Catppuccin Macchiato",background:"#24273a",text:"#cad3f5",tokens:{comment:"#939ab7",punctuation:"#b8c0e0",property:"#f5a97f",selector:"#a6da95",operator:"#91d7e3",keyword:"#c6a0f6",function:"#8aadf4",regex:"#f5bde6"}},"catppuccin-mocha":{name:"Catppuccin Mocha",background:"#1e1e2e",text:"#cdd6f4",tokens:{comment:"#9399b2",punctuation:"#bac2de",property:"#fab387",selector:"#a6e3a1",operator:"#89dceb",keyword:"#cba6f7",function:"#89b4fa",regex:"#f5c2e7"}}};function sm(t){let e=Cs[t.codeTheme]??Cs.none,r=e.background??t.codeBackground,n=e.text??t.bodyColor,o=Object.entries(e.tokens??{}).map(([i,a])=>`${am[i].map(l=>`.mpdf-doc pre code .token.${l}`).join(", ")} { color: ${a};${i==="comment"?" font-style: italic;":""} }`).join(` +var bd=Object.create;var _o=Object.defineProperty;var xd=Object.getOwnPropertyDescriptor;var Fd=Object.getOwnPropertyNames;var wd=Object.getPrototypeOf,Sd=Object.prototype.hasOwnProperty;var Ue=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Pd=(t,e)=>{for(var r in e)_o(t,r,{get:e[r],enumerable:!0})},zs=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Fd(e))!Sd.call(t,o)&&o!==r&&_o(t,o,{get:()=>e[o],enumerable:!(n=xd(e,o))||n.enumerable});return t};var $o=(t,e,r)=>(r=t!=null?bd(wd(t)):{},zs(e||!t||!t.__esModule?_o(r,"default",{value:t,enumerable:!0}):r,t)),Dd=t=>zs(_o({},"__esModule",{value:!0}),t);var Lt=Ue(Xe=>{"use strict";var Wd=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Int32Array<"u";function Gd(t,e){return Object.prototype.hasOwnProperty.call(t,e)}Xe.assign=function(t){for(var e=Array.prototype.slice.call(arguments,1);e.length;){var r=e.shift();if(r){if(typeof r!="object")throw new TypeError(r+"must be non-object");for(var n in r)Gd(r,n)&&(t[n]=r[n])}}return t};Xe.shrinkBuf=function(t,e){return t.length===e?t:t.subarray?t.subarray(0,e):(t.length=e,t)};var Kd={arraySet:function(t,e,r,n,o){if(e.subarray&&t.subarray){t.set(e.subarray(r,r+n),o);return}for(var i=0;i{"use strict";var Zd=Lt(),Yd=4,Fl=0,wl=1,Jd=2;function _r(t){for(var e=t.length;--e>=0;)t[e]=0}var Qd=0,Tl=1,_d=2,$d=3,eh=258,ga=29,Xn=256,qn=Xn+1+ga,Qr=30,ya=19,El=2*qn+1,Sr=15,ua=16,th=7,ba=256,Al=16,Rl=17,Ol=18,va=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],li=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],rh=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],Bl=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],nh=512,jt=new Array((qn+2)*2);_r(jt);var Vn=new Array(Qr*2);_r(Vn);var Wn=new Array(nh);_r(Wn);var Gn=new Array(eh-$d+1);_r(Gn);var xa=new Array(ga);_r(xa);var fi=new Array(Qr);_r(fi);function da(t,e,r,n,o){this.static_tree=t,this.extra_bits=e,this.extra_base=r,this.elems=n,this.max_length=o,this.has_stree=t&&t.length}var Nl,Ml,Il;function ha(t,e){this.dyn_tree=t,this.max_code=0,this.stat_desc=e}function zl(t){return t<256?Wn[t]:Wn[256+(t>>>7)]}function Kn(t,e){t.pending_buf[t.pending++]=e&255,t.pending_buf[t.pending++]=e>>>8&255}function $e(t,e,r){t.bi_valid>ua-r?(t.bi_buf|=e<>ua-t.bi_valid,t.bi_valid+=r-ua):(t.bi_buf|=e<>>=1,r<<=1;while(--e>0);return r>>>1}function oh(t){t.bi_valid===16?(Kn(t,t.bi_buf),t.bi_buf=0,t.bi_valid=0):t.bi_valid>=8&&(t.pending_buf[t.pending++]=t.bi_buf&255,t.bi_buf>>=8,t.bi_valid-=8)}function ih(t,e){var r=e.dyn_tree,n=e.max_code,o=e.stat_desc.static_tree,i=e.stat_desc.has_stree,a=e.stat_desc.extra_bits,s=e.stat_desc.extra_base,f=e.stat_desc.max_length,l,c,u,d,p,h,b=0;for(d=0;d<=Sr;d++)t.bl_count[d]=0;for(r[t.heap[t.heap_max]*2+1]=0,l=t.heap_max+1;lf&&(d=f,b++),r[c*2+1]=d,!(c>n)&&(t.bl_count[d]++,p=0,c>=s&&(p=a[c-s]),h=r[c*2],t.opt_len+=h*(d+p),i&&(t.static_len+=h*(o[c*2+1]+p)));if(b!==0){do{for(d=f-1;t.bl_count[d]===0;)d--;t.bl_count[d]--,t.bl_count[d+1]+=2,t.bl_count[f]--,b-=2}while(b>0);for(d=f;d!==0;d--)for(c=t.bl_count[d];c!==0;)u=t.heap[--l],!(u>n)&&(r[u*2+1]!==d&&(t.opt_len+=(d-r[u*2+1])*r[u*2],r[u*2+1]=d),c--)}}function jl(t,e,r){var n=new Array(Sr+1),o=0,i,a;for(i=1;i<=Sr;i++)n[i]=o=o+r[i-1]<<1;for(a=0;a<=e;a++){var s=t[a*2+1];s!==0&&(t[a*2]=Ll(n[s]++,s))}}function ah(){var t,e,r,n,o,i=new Array(Sr+1);for(r=0,n=0;n>=7;n8?Kn(t,t.bi_buf):t.bi_valid>0&&(t.pending_buf[t.pending++]=t.bi_buf),t.bi_buf=0,t.bi_valid=0}function sh(t,e,r,n){Ul(t),n&&(Kn(t,r),Kn(t,~r)),Zd.arraySet(t.pending_buf,t.window,e,r,t.pending),t.pending+=r}function Sl(t,e,r,n){var o=e*2,i=r*2;return t[o]>1;a>=1;a--)pa(t,r,a);l=i;do a=t.heap[1],t.heap[1]=t.heap[t.heap_len--],pa(t,r,1),s=t.heap[1],t.heap[--t.heap_max]=a,t.heap[--t.heap_max]=s,r[l*2]=r[a*2]+r[s*2],t.depth[l]=(t.depth[a]>=t.depth[s]?t.depth[a]:t.depth[s])+1,r[a*2+1]=r[s*2+1]=l,t.heap[1]=l++,pa(t,r,1);while(t.heap_len>=2);t.heap[--t.heap_max]=t.heap[1],ih(t,e),jl(r,f,t.bl_count)}function Dl(t,e,r){var n,o=-1,i,a=e[0*2+1],s=0,f=7,l=4;for(a===0&&(f=138,l=3),e[(r+1)*2+1]=65535,n=0;n<=r;n++)i=a,a=e[(n+1)*2+1],!(++s=3&&t.bl_tree[Bl[e]*2+1]===0;e--);return t.opt_len+=3*(e+1)+5+5+4,e}function fh(t,e,r,n){var o;for($e(t,e-257,5),$e(t,r-1,5),$e(t,n-4,4),o=0;o>>=1)if(e&1&&t.dyn_ltree[r*2]!==0)return Fl;if(t.dyn_ltree[9*2]!==0||t.dyn_ltree[10*2]!==0||t.dyn_ltree[13*2]!==0)return wl;for(r=32;r0?(t.strm.data_type===Jd&&(t.strm.data_type=ch(t)),ma(t,t.l_desc),ma(t,t.d_desc),a=lh(t),o=t.opt_len+3+7>>>3,i=t.static_len+3+7>>>3,i<=o&&(o=i)):o=i=r+5,r+4<=o&&e!==-1?Vl(t,e,r,n):t.strategy===Yd||i===o?($e(t,(Tl<<1)+(n?1:0),3),Pl(t,jt,Vn)):($e(t,(_d<<1)+(n?1:0),3),fh(t,t.l_desc.max_code+1,t.d_desc.max_code+1,a+1),Pl(t,t.dyn_ltree,t.dyn_dtree)),Hl(t),n&&Ul(t)}function ph(t,e,r){return t.pending_buf[t.d_buf+t.last_lit*2]=e>>>8&255,t.pending_buf[t.d_buf+t.last_lit*2+1]=e&255,t.pending_buf[t.l_buf+t.last_lit]=r&255,t.last_lit++,e===0?t.dyn_ltree[r*2]++:(t.matches++,e--,t.dyn_ltree[(Gn[r]+Xn+1)*2]++,t.dyn_dtree[zl(e)*2]++),t.last_lit===t.lit_bufsize-1}$r._tr_init=uh;$r._tr_stored_block=Vl;$r._tr_flush_block=hh;$r._tr_tally=ph;$r._tr_align=dh});var Fa=Ue((cg,Wl)=>{"use strict";function vh(t,e,r,n){for(var o=t&65535|0,i=t>>>16&65535|0,a=0;r!==0;){a=r>2e3?2e3:r,r-=a;do o=o+e[n++]|0,i=i+o|0;while(--a);o%=65521,i%=65521}return o|i<<16|0}Wl.exports=vh});var wa=Ue((ug,Gl)=>{"use strict";function mh(){for(var t,e=[],r=0;r<256;r++){t=r;for(var n=0;n<8;n++)t=t&1?3988292384^t>>>1:t>>>1;e[r]=t}return e}var gh=mh();function yh(t,e,r,n){var o=gh,i=n+r;t^=-1;for(var a=n;a>>8^o[(t^e[a])&255];return t^-1}Gl.exports=yh});var ci=Ue((dg,Kl)=>{"use strict";Kl.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}});var tf=Ue(Tt=>{"use strict";var Ze=Lt(),st=ql(),Jl=Fa(),Zt=wa(),bh=ci(),kr=0,xh=1,Fh=3,$t=4,Xl=5,kt=0,Zl=1,lt=-2,wh=-3,Sa=-5,Sh=-1,Ph=1,ui=2,Dh=3,Ch=4,kh=0,Th=2,vi=8,Eh=9,Ah=15,Rh=8,Oh=29,Bh=256,Da=Bh+1+Oh,Nh=30,Mh=19,Ih=2*Da+1,zh=15,de=3,Qt=258,gt=Qt+de+1,Lh=32,mi=42,Ca=69,di=73,hi=91,pi=103,Pr=113,Yn=666,Ne=1,Jn=2,Dr=3,rn=4,jh=3;function _t(t,e){return t.msg=bh[e],e}function Yl(t){return(t<<1)-(t>4?9:0)}function Jt(t){for(var e=t.length;--e>=0;)t[e]=0}function Yt(t){var e=t.state,r=e.pending;r>t.avail_out&&(r=t.avail_out),r!==0&&(Ze.arraySet(t.output,e.pending_buf,e.pending_out,r,t.next_out),t.next_out+=r,e.pending_out+=r,t.total_out+=r,t.avail_out-=r,e.pending-=r,e.pending===0&&(e.pending_out=0))}function je(t,e){st._tr_flush_block(t,t.block_start>=0?t.block_start:-1,t.strstart-t.block_start,e),t.block_start=t.strstart,Yt(t.strm)}function he(t,e){t.pending_buf[t.pending++]=e}function Zn(t,e){t.pending_buf[t.pending++]=e>>>8&255,t.pending_buf[t.pending++]=e&255}function Hh(t,e,r,n){var o=t.avail_in;return o>n&&(o=n),o===0?0:(t.avail_in-=o,Ze.arraySet(e,t.input,t.next_in,o,r),t.state.wrap===1?t.adler=Jl(t.adler,e,o,r):t.state.wrap===2&&(t.adler=Zt(t.adler,e,o,r)),t.next_in+=o,t.total_in+=o,o)}function Ql(t,e){var r=t.max_chain_length,n=t.strstart,o,i,a=t.prev_length,s=t.nice_match,f=t.strstart>t.w_size-gt?t.strstart-(t.w_size-gt):0,l=t.window,c=t.w_mask,u=t.prev,d=t.strstart+Qt,p=l[n+a-1],h=l[n+a];t.prev_length>=t.good_match&&(r>>=2),s>t.lookahead&&(s=t.lookahead);do if(o=e,!(l[o+a]!==h||l[o+a-1]!==p||l[o]!==l[n]||l[++o]!==l[n+1])){n+=2,o++;do;while(l[++n]===l[++o]&&l[++n]===l[++o]&&l[++n]===l[++o]&&l[++n]===l[++o]&&l[++n]===l[++o]&&l[++n]===l[++o]&&l[++n]===l[++o]&&l[++n]===l[++o]&&na){if(t.match_start=e,a=i,i>=s)break;p=l[n+a-1],h=l[n+a]}}while((e=u[e&c])>f&&--r!==0);return a<=t.lookahead?a:t.lookahead}function Cr(t){var e=t.w_size,r,n,o,i,a;do{if(i=t.window_size-t.lookahead-t.strstart,t.strstart>=e+(e-gt)){Ze.arraySet(t.window,t.window,e,e,0),t.match_start-=e,t.strstart-=e,t.block_start-=e,n=t.hash_size,r=n;do o=t.head[--r],t.head[r]=o>=e?o-e:0;while(--n);n=e,r=n;do o=t.prev[--r],t.prev[r]=o>=e?o-e:0;while(--n);i+=e}if(t.strm.avail_in===0)break;if(n=Hh(t.strm,t.window,t.strstart+t.lookahead,i),t.lookahead+=n,t.lookahead+t.insert>=de)for(a=t.strstart-t.insert,t.ins_h=t.window[a],t.ins_h=(t.ins_h<t.pending_buf_size-5&&(r=t.pending_buf_size-5);;){if(t.lookahead<=1){if(Cr(t),t.lookahead===0&&e===kr)return Ne;if(t.lookahead===0)break}t.strstart+=t.lookahead,t.lookahead=0;var n=t.block_start+r;if((t.strstart===0||t.strstart>=n)&&(t.lookahead=t.strstart-n,t.strstart=n,je(t,!1),t.strm.avail_out===0)||t.strstart-t.block_start>=t.w_size-gt&&(je(t,!1),t.strm.avail_out===0))return Ne}return t.insert=0,e===$t?(je(t,!0),t.strm.avail_out===0?Dr:rn):(t.strstart>t.block_start&&(je(t,!1),t.strm.avail_out===0),Ne)}function Pa(t,e){for(var r,n;;){if(t.lookahead=de&&(t.ins_h=(t.ins_h<=de)if(n=st._tr_tally(t,t.strstart-t.match_start,t.match_length-de),t.lookahead-=t.match_length,t.match_length<=t.max_lazy_match&&t.lookahead>=de){t.match_length--;do t.strstart++,t.ins_h=(t.ins_h<=de&&(t.ins_h=(t.ins_h<4096)&&(t.match_length=de-1)),t.prev_length>=de&&t.match_length<=t.prev_length){o=t.strstart+t.lookahead-de,n=st._tr_tally(t,t.strstart-1-t.prev_match,t.prev_length-de),t.lookahead-=t.prev_length-1,t.prev_length-=2;do++t.strstart<=o&&(t.ins_h=(t.ins_h<=de&&t.strstart>0&&(o=t.strstart-1,n=a[o],n===a[++o]&&n===a[++o]&&n===a[++o])){i=t.strstart+Qt;do;while(n===a[++o]&&n===a[++o]&&n===a[++o]&&n===a[++o]&&n===a[++o]&&n===a[++o]&&n===a[++o]&&n===a[++o]&&ot.lookahead&&(t.match_length=t.lookahead)}if(t.match_length>=de?(r=st._tr_tally(t,1,t.match_length-de),t.lookahead-=t.match_length,t.strstart+=t.match_length,t.match_length=0):(r=st._tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++),r&&(je(t,!1),t.strm.avail_out===0))return Ne}return t.insert=0,e===$t?(je(t,!0),t.strm.avail_out===0?Dr:rn):t.last_lit&&(je(t,!1),t.strm.avail_out===0)?Ne:Jn}function qh(t,e){for(var r;;){if(t.lookahead===0&&(Cr(t),t.lookahead===0)){if(e===kr)return Ne;break}if(t.match_length=0,r=st._tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++,r&&(je(t,!1),t.strm.avail_out===0))return Ne}return t.insert=0,e===$t?(je(t,!0),t.strm.avail_out===0?Dr:rn):t.last_lit&&(je(t,!1),t.strm.avail_out===0)?Ne:Jn}function Ct(t,e,r,n,o){this.good_length=t,this.max_lazy=e,this.nice_length=r,this.max_chain=n,this.func=o}var tn;tn=[new Ct(0,0,0,0,Uh),new Ct(4,4,8,4,Pa),new Ct(4,5,16,8,Pa),new Ct(4,6,32,32,Pa),new Ct(4,4,16,16,en),new Ct(8,16,32,32,en),new Ct(8,16,128,128,en),new Ct(8,32,128,256,en),new Ct(32,128,258,1024,en),new Ct(32,258,258,4096,en)];function Wh(t){t.window_size=2*t.w_size,Jt(t.head),t.max_lazy_match=tn[t.level].max_lazy,t.good_match=tn[t.level].good_length,t.nice_match=tn[t.level].nice_length,t.max_chain_length=tn[t.level].max_chain,t.strstart=0,t.block_start=0,t.lookahead=0,t.insert=0,t.match_length=t.prev_length=de-1,t.match_available=0,t.ins_h=0}function Gh(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=vi,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new Ze.Buf16(Ih*2),this.dyn_dtree=new Ze.Buf16((2*Nh+1)*2),this.bl_tree=new Ze.Buf16((2*Mh+1)*2),Jt(this.dyn_ltree),Jt(this.dyn_dtree),Jt(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Ze.Buf16(zh+1),this.heap=new Ze.Buf16(2*Da+1),Jt(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Ze.Buf16(2*Da+1),Jt(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function _l(t){var e;return!t||!t.state?_t(t,lt):(t.total_in=t.total_out=0,t.data_type=Th,e=t.state,e.pending=0,e.pending_out=0,e.wrap<0&&(e.wrap=-e.wrap),e.status=e.wrap?mi:Pr,t.adler=e.wrap===2?0:1,e.last_flush=kr,st._tr_init(e),kt)}function $l(t){var e=_l(t);return e===kt&&Wh(t.state),e}function Kh(t,e){return!t||!t.state||t.state.wrap!==2?lt:(t.state.gzhead=e,kt)}function ef(t,e,r,n,o,i){if(!t)return lt;var a=1;if(e===Sh&&(e=6),n<0?(a=0,n=-n):n>15&&(a=2,n-=16),o<1||o>Eh||r!==vi||n<8||n>15||e<0||e>9||i<0||i>Ch)return _t(t,lt);n===8&&(n=9);var s=new Gh;return t.state=s,s.strm=t,s.wrap=a,s.gzhead=null,s.w_bits=n,s.w_size=1<Xl||e<0)return t?_t(t,lt):lt;if(n=t.state,!t.output||!t.input&&t.avail_in!==0||n.status===Yn&&e!==$t)return _t(t,t.avail_out===0?Sa:lt);if(n.strm=t,r=n.last_flush,n.last_flush=e,n.status===mi)if(n.wrap===2)t.adler=0,he(n,31),he(n,139),he(n,8),n.gzhead?(he(n,(n.gzhead.text?1:0)+(n.gzhead.hcrc?2:0)+(n.gzhead.extra?4:0)+(n.gzhead.name?8:0)+(n.gzhead.comment?16:0)),he(n,n.gzhead.time&255),he(n,n.gzhead.time>>8&255),he(n,n.gzhead.time>>16&255),he(n,n.gzhead.time>>24&255),he(n,n.level===9?2:n.strategy>=ui||n.level<2?4:0),he(n,n.gzhead.os&255),n.gzhead.extra&&n.gzhead.extra.length&&(he(n,n.gzhead.extra.length&255),he(n,n.gzhead.extra.length>>8&255)),n.gzhead.hcrc&&(t.adler=Zt(t.adler,n.pending_buf,n.pending,0)),n.gzindex=0,n.status=Ca):(he(n,0),he(n,0),he(n,0),he(n,0),he(n,0),he(n,n.level===9?2:n.strategy>=ui||n.level<2?4:0),he(n,jh),n.status=Pr);else{var a=vi+(n.w_bits-8<<4)<<8,s=-1;n.strategy>=ui||n.level<2?s=0:n.level<6?s=1:n.level===6?s=2:s=3,a|=s<<6,n.strstart!==0&&(a|=Lh),a+=31-a%31,n.status=Pr,Zn(n,a),n.strstart!==0&&(Zn(n,t.adler>>>16),Zn(n,t.adler&65535)),t.adler=1}if(n.status===Ca)if(n.gzhead.extra){for(o=n.pending;n.gzindex<(n.gzhead.extra.length&65535)&&!(n.pending===n.pending_buf_size&&(n.gzhead.hcrc&&n.pending>o&&(t.adler=Zt(t.adler,n.pending_buf,n.pending-o,o)),Yt(t),o=n.pending,n.pending===n.pending_buf_size));)he(n,n.gzhead.extra[n.gzindex]&255),n.gzindex++;n.gzhead.hcrc&&n.pending>o&&(t.adler=Zt(t.adler,n.pending_buf,n.pending-o,o)),n.gzindex===n.gzhead.extra.length&&(n.gzindex=0,n.status=di)}else n.status=di;if(n.status===di)if(n.gzhead.name){o=n.pending;do{if(n.pending===n.pending_buf_size&&(n.gzhead.hcrc&&n.pending>o&&(t.adler=Zt(t.adler,n.pending_buf,n.pending-o,o)),Yt(t),o=n.pending,n.pending===n.pending_buf_size)){i=1;break}n.gzindexo&&(t.adler=Zt(t.adler,n.pending_buf,n.pending-o,o)),i===0&&(n.gzindex=0,n.status=hi)}else n.status=hi;if(n.status===hi)if(n.gzhead.comment){o=n.pending;do{if(n.pending===n.pending_buf_size&&(n.gzhead.hcrc&&n.pending>o&&(t.adler=Zt(t.adler,n.pending_buf,n.pending-o,o)),Yt(t),o=n.pending,n.pending===n.pending_buf_size)){i=1;break}n.gzindexo&&(t.adler=Zt(t.adler,n.pending_buf,n.pending-o,o)),i===0&&(n.status=pi)}else n.status=pi;if(n.status===pi&&(n.gzhead.hcrc?(n.pending+2>n.pending_buf_size&&Yt(t),n.pending+2<=n.pending_buf_size&&(he(n,t.adler&255),he(n,t.adler>>8&255),t.adler=0,n.status=Pr)):n.status=Pr),n.pending!==0){if(Yt(t),t.avail_out===0)return n.last_flush=-1,kt}else if(t.avail_in===0&&Yl(e)<=Yl(r)&&e!==$t)return _t(t,Sa);if(n.status===Yn&&t.avail_in!==0)return _t(t,Sa);if(t.avail_in!==0||n.lookahead!==0||e!==kr&&n.status!==Yn){var f=n.strategy===ui?qh(n,e):n.strategy===Dh?Vh(n,e):tn[n.level].func(n,e);if((f===Dr||f===rn)&&(n.status=Yn),f===Ne||f===Dr)return t.avail_out===0&&(n.last_flush=-1),kt;if(f===Jn&&(e===xh?st._tr_align(n):e!==Xl&&(st._tr_stored_block(n,0,0,!1),e===Fh&&(Jt(n.head),n.lookahead===0&&(n.strstart=0,n.block_start=0,n.insert=0))),Yt(t),t.avail_out===0))return n.last_flush=-1,kt}return e!==$t?kt:n.wrap<=0?Zl:(n.wrap===2?(he(n,t.adler&255),he(n,t.adler>>8&255),he(n,t.adler>>16&255),he(n,t.adler>>24&255),he(n,t.total_in&255),he(n,t.total_in>>8&255),he(n,t.total_in>>16&255),he(n,t.total_in>>24&255)):(Zn(n,t.adler>>>16),Zn(n,t.adler&65535)),Yt(t),n.wrap>0&&(n.wrap=-n.wrap),n.pending!==0?kt:Zl)}function Yh(t){var e;return!t||!t.state?lt:(e=t.state.status,e!==mi&&e!==Ca&&e!==di&&e!==hi&&e!==pi&&e!==Pr&&e!==Yn?_t(t,lt):(t.state=null,e===Pr?_t(t,wh):kt))}function Jh(t,e){var r=e.length,n,o,i,a,s,f,l,c;if(!t||!t.state||(n=t.state,a=n.wrap,a===2||a===1&&n.status!==mi||n.lookahead))return lt;for(a===1&&(t.adler=Jl(t.adler,e,r,0)),n.wrap=0,r>=n.w_size&&(a===0&&(Jt(n.head),n.strstart=0,n.block_start=0,n.insert=0),c=new Ze.Buf8(n.w_size),Ze.arraySet(c,e,r-n.w_size,n.w_size,0),e=c,r=n.w_size),s=t.avail_in,f=t.next_in,l=t.input,t.avail_in=r,t.next_in=0,t.input=e,Cr(n);n.lookahead>=de;){o=n.strstart,i=n.lookahead-(de-1);do n.ins_h=(n.ins_h<{"use strict";var gi=Lt(),rf=!0,nf=!0;try{String.fromCharCode.apply(null,[0])}catch{rf=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch{nf=!1}var Qn=new gi.Buf8(256);for(Ht=0;Ht<256;Ht++)Qn[Ht]=Ht>=252?6:Ht>=248?5:Ht>=240?4:Ht>=224?3:Ht>=192?2:1;var Ht;Qn[254]=Qn[254]=1;nn.string2buf=function(t){var e,r,n,o,i,a=t.length,s=0;for(o=0;o>>6,e[i++]=128|r&63):r<65536?(e[i++]=224|r>>>12,e[i++]=128|r>>>6&63,e[i++]=128|r&63):(e[i++]=240|r>>>18,e[i++]=128|r>>>12&63,e[i++]=128|r>>>6&63,e[i++]=128|r&63);return e};function of(t,e){if(e<65534&&(t.subarray&&nf||!t.subarray&&rf))return String.fromCharCode.apply(null,gi.shrinkBuf(t,e));for(var r="",n=0;n4){s[n++]=65533,r+=i-1;continue}for(o&=i===2?31:i===3?15:7;i>1&&r1){s[n++]=65533;continue}o<65536?s[n++]=o:(o-=65536,s[n++]=55296|o>>10&1023,s[n++]=56320|o&1023)}return of(s,n)};nn.utf8border=function(t,e){var r;for(e=e||t.length,e>t.length&&(e=t.length),r=e-1;r>=0&&(t[r]&192)===128;)r--;return r<0||r===0?e:r+Qn[t[r]]>e?r:e}});var Ta=Ue((vg,af)=>{"use strict";function Qh(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}af.exports=Qh});var cf=Ue(eo=>{"use strict";var _n=tf(),$n=Lt(),Aa=ka(),Ra=ci(),_h=Ta(),ff=Object.prototype.toString,$h=0,Ea=4,on=0,sf=1,lf=2,ep=-1,tp=0,rp=8;function Tr(t){if(!(this instanceof Tr))return new Tr(t);this.options=$n.assign({level:ep,method:rp,chunkSize:16384,windowBits:15,memLevel:8,strategy:tp,to:""},t||{});var e=this.options;e.raw&&e.windowBits>0?e.windowBits=-e.windowBits:e.gzip&&e.windowBits>0&&e.windowBits<16&&(e.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new _h,this.strm.avail_out=0;var r=_n.deflateInit2(this.strm,e.level,e.method,e.windowBits,e.memLevel,e.strategy);if(r!==on)throw new Error(Ra[r]);if(e.header&&_n.deflateSetHeader(this.strm,e.header),e.dictionary){var n;if(typeof e.dictionary=="string"?n=Aa.string2buf(e.dictionary):ff.call(e.dictionary)==="[object ArrayBuffer]"?n=new Uint8Array(e.dictionary):n=e.dictionary,r=_n.deflateSetDictionary(this.strm,n),r!==on)throw new Error(Ra[r]);this._dict_set=!0}}Tr.prototype.push=function(t,e){var r=this.strm,n=this.options.chunkSize,o,i;if(this.ended)return!1;i=e===~~e?e:e===!0?Ea:$h,typeof t=="string"?r.input=Aa.string2buf(t):ff.call(t)==="[object ArrayBuffer]"?r.input=new Uint8Array(t):r.input=t,r.next_in=0,r.avail_in=r.input.length;do{if(r.avail_out===0&&(r.output=new $n.Buf8(n),r.next_out=0,r.avail_out=n),o=_n.deflate(r,i),o!==sf&&o!==on)return this.onEnd(o),this.ended=!0,!1;(r.avail_out===0||r.avail_in===0&&(i===Ea||i===lf))&&(this.options.to==="string"?this.onData(Aa.buf2binstring($n.shrinkBuf(r.output,r.next_out))):this.onData($n.shrinkBuf(r.output,r.next_out)))}while((r.avail_in>0||r.avail_out===0)&&o!==sf);return i===Ea?(o=_n.deflateEnd(this.strm),this.onEnd(o),this.ended=!0,o===on):(i===lf&&(this.onEnd(on),r.avail_out=0),!0)};Tr.prototype.onData=function(t){this.chunks.push(t)};Tr.prototype.onEnd=function(t){t===on&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=$n.flattenChunks(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg};function Oa(t,e){var r=new Tr(e);if(r.push(t,!0),r.err)throw r.msg||Ra[r.err];return r.result}function np(t,e){return e=e||{},e.raw=!0,Oa(t,e)}function op(t,e){return e=e||{},e.gzip=!0,Oa(t,e)}eo.Deflate=Tr;eo.deflate=Oa;eo.deflateRaw=np;eo.gzip=op});var df=Ue((gg,uf)=>{"use strict";var yi=30,ip=12;uf.exports=function(e,r){var n,o,i,a,s,f,l,c,u,d,p,h,b,F,x,m,y,w,S,D,T,C,E,M,A;n=e.state,o=e.next_in,M=e.input,i=o+(e.avail_in-5),a=e.next_out,A=e.output,s=a-(r-e.avail_out),f=a+(e.avail_out-257),l=n.dmax,c=n.wsize,u=n.whave,d=n.wnext,p=n.window,h=n.hold,b=n.bits,F=n.lencode,x=n.distcode,m=(1<>>24,h>>>=S,b-=S,S=w>>>16&255,S===0)A[a++]=w&65535;else if(S&16){D=w&65535,S&=15,S&&(b>>=S,b-=S),b<15&&(h+=M[o++]<>>24,h>>>=S,b-=S,S=w>>>16&255,S&16){if(T=w&65535,S&=15,bl){e.msg="invalid distance too far back",n.mode=yi;break e}if(h>>>=S,b-=S,S=a-s,T>S){if(S=T-S,S>u&&n.sane){e.msg="invalid distance too far back",n.mode=yi;break e}if(C=0,E=p,d===0){if(C+=c-S,S2;)A[a++]=E[C++],A[a++]=E[C++],A[a++]=E[C++],D-=3;D&&(A[a++]=E[C++],D>1&&(A[a++]=E[C++]))}else{C=a-T;do A[a++]=A[C++],A[a++]=A[C++],A[a++]=A[C++],D-=3;while(D>2);D&&(A[a++]=A[C++],D>1&&(A[a++]=A[C++]))}}else if((S&64)===0){w=x[(w&65535)+(h&(1<>3,o-=D,b-=D<<3,h&=(1<{"use strict";var hf=Lt(),an=15,pf=852,vf=592,mf=0,Ba=1,gf=2,ap=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],sp=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],lp=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],fp=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];yf.exports=function(e,r,n,o,i,a,s,f){var l=f.bits,c=0,u=0,d=0,p=0,h=0,b=0,F=0,x=0,m=0,y=0,w,S,D,T,C,E=null,M=0,A,R=new hf.Buf16(an+1),I=new hf.Buf16(an+1),N=null,X=0,te,L,ue;for(c=0;c<=an;c++)R[c]=0;for(u=0;u=1&&R[p]===0;p--);if(h>p&&(h=p),p===0)return i[a++]=1<<24|64<<16|0,i[a++]=1<<24|64<<16|0,f.bits=1,0;for(d=1;d0&&(e===mf||p!==1))return-1;for(I[1]=0,c=1;cpf||e===gf&&m>vf)return 1;for(;;){te=c-F,s[u]A?(L=N[X+s[u]],ue=E[M+s[u]]):(L=96,ue=0),w=1<>F)+S]=te<<24|L<<16|ue|0;while(S!==0);for(w=1<>=1;if(w!==0?(y&=w-1,y+=w):y=0,u++,--R[c]===0){if(c===p)break;c=r[n+s[u]]}if(c>h&&(y&T)!==D){for(F===0&&(F=h),C+=d,b=c-F,x=1<pf||e===gf&&m>vf)return 1;D=y&T,i[D]=h<<24|b<<16|C-a|0}}return y!==0&&(i[C+y]=c-F<<24|64<<16|0),f.bits=h,0}});var ec=Ue(yt=>{"use strict";var ot=Lt(),ja=Fa(),Et=wa(),cp=df(),to=bf(),up=0,Gf=1,Kf=2,xf=4,dp=5,bi=6,Er=0,hp=1,pp=2,ft=-2,Xf=-3,Ha=-4,vp=-5,Ff=8,Zf=1,wf=2,Sf=3,Pf=4,Df=5,Cf=6,kf=7,Tf=8,Ef=9,Af=10,wi=11,Ut=12,Na=13,Rf=14,Ma=15,Of=16,Bf=17,Nf=18,Mf=19,xi=20,Fi=21,If=22,zf=23,Lf=24,jf=25,Hf=26,Ia=27,Uf=28,Vf=29,be=30,Ua=31,mp=32,gp=852,yp=592,bp=15,xp=bp;function qf(t){return(t>>>24&255)+(t>>>8&65280)+((t&65280)<<8)+((t&255)<<24)}function Fp(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new ot.Buf16(320),this.work=new ot.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function Yf(t){var e;return!t||!t.state?ft:(e=t.state,t.total_in=t.total_out=e.total=0,t.msg="",e.wrap&&(t.adler=e.wrap&1),e.mode=Zf,e.last=0,e.havedict=0,e.dmax=32768,e.head=null,e.hold=0,e.bits=0,e.lencode=e.lendyn=new ot.Buf32(gp),e.distcode=e.distdyn=new ot.Buf32(yp),e.sane=1,e.back=-1,Er)}function Jf(t){var e;return!t||!t.state?ft:(e=t.state,e.wsize=0,e.whave=0,e.wnext=0,Yf(t))}function Qf(t,e){var r,n;return!t||!t.state||(n=t.state,e<0?(r=0,e=-e):(r=(e>>4)+1,e<48&&(e&=15)),e&&(e<8||e>15))?ft:(n.window!==null&&n.wbits!==e&&(n.window=null),n.wrap=r,n.wbits=e,Jf(t))}function _f(t,e){var r,n;return t?(n=new Fp,t.state=n,n.window=null,r=Qf(t,e),r!==Er&&(t.state=null),r):ft}function wp(t){return _f(t,xp)}var Wf=!0,za,La;function Sp(t){if(Wf){var e;for(za=new ot.Buf32(512),La=new ot.Buf32(32),e=0;e<144;)t.lens[e++]=8;for(;e<256;)t.lens[e++]=9;for(;e<280;)t.lens[e++]=7;for(;e<288;)t.lens[e++]=8;for(to(Gf,t.lens,0,288,za,0,t.work,{bits:9}),e=0;e<32;)t.lens[e++]=5;to(Kf,t.lens,0,32,La,0,t.work,{bits:5}),Wf=!1}t.lencode=za,t.lenbits=9,t.distcode=La,t.distbits=5}function $f(t,e,r,n){var o,i=t.state;return i.window===null&&(i.wsize=1<=i.wsize?(ot.arraySet(i.window,e,r-i.wsize,i.wsize,0),i.wnext=0,i.whave=i.wsize):(o=i.wsize-i.wnext,o>n&&(o=n),ot.arraySet(i.window,e,r-n,o,i.wnext),n-=o,n?(ot.arraySet(i.window,e,r-n,n,0),i.wnext=n,i.whave=i.wsize):(i.wnext+=o,i.wnext===i.wsize&&(i.wnext=0),i.whave>>8&255,r.check=Et(r.check,E,2,0),l=0,c=0,r.mode=wf;break}if(r.flags=0,r.head&&(r.head.done=!1),!(r.wrap&1)||(((l&255)<<8)+(l>>8))%31){t.msg="incorrect header check",r.mode=be;break}if((l&15)!==Ff){t.msg="unknown compression method",r.mode=be;break}if(l>>>=4,c-=4,T=(l&15)+8,r.wbits===0)r.wbits=T;else if(T>r.wbits){t.msg="invalid window size",r.mode=be;break}r.dmax=1<>8&1),r.flags&512&&(E[0]=l&255,E[1]=l>>>8&255,r.check=Et(r.check,E,2,0)),l=0,c=0,r.mode=Sf;case Sf:for(;c<32;){if(s===0)break e;s--,l+=n[i++]<>>8&255,E[2]=l>>>16&255,E[3]=l>>>24&255,r.check=Et(r.check,E,4,0)),l=0,c=0,r.mode=Pf;case Pf:for(;c<16;){if(s===0)break e;s--,l+=n[i++]<>8),r.flags&512&&(E[0]=l&255,E[1]=l>>>8&255,r.check=Et(r.check,E,2,0)),l=0,c=0,r.mode=Df;case Df:if(r.flags&1024){for(;c<16;){if(s===0)break e;s--,l+=n[i++]<>>8&255,r.check=Et(r.check,E,2,0)),l=0,c=0}else r.head&&(r.head.extra=null);r.mode=Cf;case Cf:if(r.flags&1024&&(p=r.length,p>s&&(p=s),p&&(r.head&&(T=r.head.extra_len-r.length,r.head.extra||(r.head.extra=new Array(r.head.extra_len)),ot.arraySet(r.head.extra,n,i,p,T)),r.flags&512&&(r.check=Et(r.check,n,p,i)),s-=p,i+=p,r.length-=p),r.length))break e;r.length=0,r.mode=kf;case kf:if(r.flags&2048){if(s===0)break e;p=0;do T=n[i+p++],r.head&&T&&r.length<65536&&(r.head.name+=String.fromCharCode(T));while(T&&p>9&1,r.head.done=!0),t.adler=r.check=0,r.mode=Ut;break;case Af:for(;c<32;){if(s===0)break e;s--,l+=n[i++]<>>=c&7,c-=c&7,r.mode=Ia;break}for(;c<3;){if(s===0)break e;s--,l+=n[i++]<>>=1,c-=1,l&3){case 0:r.mode=Rf;break;case 1:if(Sp(r),r.mode=xi,e===bi){l>>>=2,c-=2;break e}break;case 2:r.mode=Bf;break;case 3:t.msg="invalid block type",r.mode=be}l>>>=2,c-=2;break;case Rf:for(l>>>=c&7,c-=c&7;c<32;){if(s===0)break e;s--,l+=n[i++]<>>16^65535)){t.msg="invalid stored block lengths",r.mode=be;break}if(r.length=l&65535,l=0,c=0,r.mode=Ma,e===bi)break e;case Ma:r.mode=Of;case Of:if(p=r.length,p){if(p>s&&(p=s),p>f&&(p=f),p===0)break e;ot.arraySet(o,n,i,p,a),s-=p,i+=p,f-=p,a+=p,r.length-=p;break}r.mode=Ut;break;case Bf:for(;c<14;){if(s===0)break e;s--,l+=n[i++]<>>=5,c-=5,r.ndist=(l&31)+1,l>>>=5,c-=5,r.ncode=(l&15)+4,l>>>=4,c-=4,r.nlen>286||r.ndist>30){t.msg="too many length or distance symbols",r.mode=be;break}r.have=0,r.mode=Nf;case Nf:for(;r.have>>=3,c-=3}for(;r.have<19;)r.lens[R[r.have++]]=0;if(r.lencode=r.lendyn,r.lenbits=7,M={bits:r.lenbits},C=to(up,r.lens,0,19,r.lencode,0,r.work,M),r.lenbits=M.bits,C){t.msg="invalid code lengths set",r.mode=be;break}r.have=0,r.mode=Mf;case Mf:for(;r.have>>24,m=F>>>16&255,y=F&65535,!(x<=c);){if(s===0)break e;s--,l+=n[i++]<>>=x,c-=x,r.lens[r.have++]=y;else{if(y===16){for(A=x+2;c>>=x,c-=x,r.have===0){t.msg="invalid bit length repeat",r.mode=be;break}T=r.lens[r.have-1],p=3+(l&3),l>>>=2,c-=2}else if(y===17){for(A=x+3;c>>=x,c-=x,T=0,p=3+(l&7),l>>>=3,c-=3}else{for(A=x+7;c>>=x,c-=x,T=0,p=11+(l&127),l>>>=7,c-=7}if(r.have+p>r.nlen+r.ndist){t.msg="invalid bit length repeat",r.mode=be;break}for(;p--;)r.lens[r.have++]=T}}if(r.mode===be)break;if(r.lens[256]===0){t.msg="invalid code -- missing end-of-block",r.mode=be;break}if(r.lenbits=9,M={bits:r.lenbits},C=to(Gf,r.lens,0,r.nlen,r.lencode,0,r.work,M),r.lenbits=M.bits,C){t.msg="invalid literal/lengths set",r.mode=be;break}if(r.distbits=6,r.distcode=r.distdyn,M={bits:r.distbits},C=to(Kf,r.lens,r.nlen,r.ndist,r.distcode,0,r.work,M),r.distbits=M.bits,C){t.msg="invalid distances set",r.mode=be;break}if(r.mode=xi,e===bi)break e;case xi:r.mode=Fi;case Fi:if(s>=6&&f>=258){t.next_out=a,t.avail_out=f,t.next_in=i,t.avail_in=s,r.hold=l,r.bits=c,cp(t,d),a=t.next_out,o=t.output,f=t.avail_out,i=t.next_in,n=t.input,s=t.avail_in,l=r.hold,c=r.bits,r.mode===Ut&&(r.back=-1);break}for(r.back=0;F=r.lencode[l&(1<>>24,m=F>>>16&255,y=F&65535,!(x<=c);){if(s===0)break e;s--,l+=n[i++]<>w)],x=F>>>24,m=F>>>16&255,y=F&65535,!(w+x<=c);){if(s===0)break e;s--,l+=n[i++]<>>=w,c-=w,r.back+=w}if(l>>>=x,c-=x,r.back+=x,r.length=y,m===0){r.mode=Hf;break}if(m&32){r.back=-1,r.mode=Ut;break}if(m&64){t.msg="invalid literal/length code",r.mode=be;break}r.extra=m&15,r.mode=If;case If:if(r.extra){for(A=r.extra;c>>=r.extra,c-=r.extra,r.back+=r.extra}r.was=r.length,r.mode=zf;case zf:for(;F=r.distcode[l&(1<>>24,m=F>>>16&255,y=F&65535,!(x<=c);){if(s===0)break e;s--,l+=n[i++]<>w)],x=F>>>24,m=F>>>16&255,y=F&65535,!(w+x<=c);){if(s===0)break e;s--,l+=n[i++]<>>=w,c-=w,r.back+=w}if(l>>>=x,c-=x,r.back+=x,m&64){t.msg="invalid distance code",r.mode=be;break}r.offset=y,r.extra=m&15,r.mode=Lf;case Lf:if(r.extra){for(A=r.extra;c>>=r.extra,c-=r.extra,r.back+=r.extra}if(r.offset>r.dmax){t.msg="invalid distance too far back",r.mode=be;break}r.mode=jf;case jf:if(f===0)break e;if(p=d-f,r.offset>p){if(p=r.offset-p,p>r.whave&&r.sane){t.msg="invalid distance too far back",r.mode=be;break}p>r.wnext?(p-=r.wnext,h=r.wsize-p):h=r.wnext-p,p>r.length&&(p=r.length),b=r.window}else b=o,h=a-r.offset,p=r.length;p>f&&(p=f),f-=p,r.length-=p;do o[a++]=b[h++];while(--p);r.length===0&&(r.mode=Fi);break;case Hf:if(f===0)break e;o[a++]=r.length,f--,r.mode=Fi;break;case Ia:if(r.wrap){for(;c<32;){if(s===0)break e;s--,l|=n[i++]<{"use strict";tc.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}});var nc=Ue((Fg,rc)=>{"use strict";function Tp(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}rc.exports=Tp});var ic=Ue(no=>{"use strict";var sn=ec(),ro=Lt(),Si=ka(),ke=Va(),qa=ci(),Ep=Ta(),Ap=nc(),oc=Object.prototype.toString;function Ar(t){if(!(this instanceof Ar))return new Ar(t);this.options=ro.assign({chunkSize:16384,windowBits:0,to:""},t||{});var e=this.options;e.raw&&e.windowBits>=0&&e.windowBits<16&&(e.windowBits=-e.windowBits,e.windowBits===0&&(e.windowBits=-15)),e.windowBits>=0&&e.windowBits<16&&!(t&&t.windowBits)&&(e.windowBits+=32),e.windowBits>15&&e.windowBits<48&&(e.windowBits&15)===0&&(e.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new Ep,this.strm.avail_out=0;var r=sn.inflateInit2(this.strm,e.windowBits);if(r!==ke.Z_OK)throw new Error(qa[r]);if(this.header=new Ap,sn.inflateGetHeader(this.strm,this.header),e.dictionary&&(typeof e.dictionary=="string"?e.dictionary=Si.string2buf(e.dictionary):oc.call(e.dictionary)==="[object ArrayBuffer]"&&(e.dictionary=new Uint8Array(e.dictionary)),e.raw&&(r=sn.inflateSetDictionary(this.strm,e.dictionary),r!==ke.Z_OK)))throw new Error(qa[r])}Ar.prototype.push=function(t,e){var r=this.strm,n=this.options.chunkSize,o=this.options.dictionary,i,a,s,f,l,c=!1;if(this.ended)return!1;a=e===~~e?e:e===!0?ke.Z_FINISH:ke.Z_NO_FLUSH,typeof t=="string"?r.input=Si.binstring2buf(t):oc.call(t)==="[object ArrayBuffer]"?r.input=new Uint8Array(t):r.input=t,r.next_in=0,r.avail_in=r.input.length;do{if(r.avail_out===0&&(r.output=new ro.Buf8(n),r.next_out=0,r.avail_out=n),i=sn.inflate(r,ke.Z_NO_FLUSH),i===ke.Z_NEED_DICT&&o&&(i=sn.inflateSetDictionary(this.strm,o)),i===ke.Z_BUF_ERROR&&c===!0&&(i=ke.Z_OK,c=!1),i!==ke.Z_STREAM_END&&i!==ke.Z_OK)return this.onEnd(i),this.ended=!0,!1;r.next_out&&(r.avail_out===0||i===ke.Z_STREAM_END||r.avail_in===0&&(a===ke.Z_FINISH||a===ke.Z_SYNC_FLUSH))&&(this.options.to==="string"?(s=Si.utf8border(r.output,r.next_out),f=r.next_out-s,l=Si.buf2string(r.output,s),r.next_out=f,r.avail_out=n-f,f&&ro.arraySet(r.output,r.output,s,f,0),this.onData(l)):this.onData(ro.shrinkBuf(r.output,r.next_out))),r.avail_in===0&&r.avail_out===0&&(c=!0)}while((r.avail_in>0||r.avail_out===0)&&i!==ke.Z_STREAM_END);return i===ke.Z_STREAM_END&&(a=ke.Z_FINISH),a===ke.Z_FINISH?(i=sn.inflateEnd(this.strm),this.onEnd(i),this.ended=!0,i===ke.Z_OK):(a===ke.Z_SYNC_FLUSH&&(this.onEnd(ke.Z_OK),r.avail_out=0),!0)};Ar.prototype.onData=function(t){this.chunks.push(t)};Ar.prototype.onEnd=function(t){t===ke.Z_OK&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=ro.flattenChunks(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg};function Wa(t,e){var r=new Ar(e);if(r.push(t,!0),r.err)throw r.msg||qa[r.err];return r.result}function Rp(t,e){return e=e||{},e.raw=!0,Wa(t,e)}no.Inflate=Ar;no.inflate=Wa;no.inflateRaw=Rp;no.ungzip=Wa});var oo=Ue((Sg,sc)=>{"use strict";var Op=Lt().assign,Bp=cf(),Np=ic(),Mp=Va(),ac={};Op(ac,Bp,Np,Mp);sc.exports=ac});var Hm={};Pd(Hm,{default:()=>_i});module.exports=Dd(Hm);var $i=require("obsidian");var mr={A4:{w:794,h:1123},A3:{w:1123,h:1587},Letter:{w:816,h:1056},Legal:{w:816,h:1344},A5:{w:559,h:794}},It={default:{name:"Default",fontFamily:"Georgia, serif",fontSize:13,lineHeight:1.85,paragraphSpacing:.65,headingScale:1,accentColor:"#7c6af7",bodyColor:"#1a1a2e",headingColor:"#0d0d1a",h1BorderBottom:!1,h2BorderBottom:!0,centerH1:!1,blockquoteBg:"transparent",blockquoteBorderColor:"#7c6af7",codeBackground:"#f0f0f8",codeFontSize:.85,codeTheme:"github-light",tableHeaderBg:"#f0f0f8",tableStriped:!0,pageBackground:"#ffffff",marginTop:20,marginBottom:20,marginLeft:25,marginRight:25},minimal:{name:"Minimal",fontFamily:"'Helvetica Neue', Helvetica, sans-serif",fontSize:12,lineHeight:1.6,paragraphSpacing:.45,headingScale:.88,accentColor:"#333",bodyColor:"#222",headingColor:"#111",h1BorderBottom:!1,h2BorderBottom:!1,centerH1:!1,blockquoteBg:"#f8f8f8",blockquoteBorderColor:"#ccc",codeBackground:"#f4f4f4",codeFontSize:.82,codeTheme:"none",tableHeaderBg:"#efefef",tableStriped:!1,pageBackground:"#ffffff",marginTop:16,marginBottom:16,marginLeft:20,marginRight:20},academic:{name:"Academic",fontFamily:"'Times New Roman', Times, serif",fontSize:12,lineHeight:2,paragraphSpacing:0,headingScale:.95,accentColor:"#1a3a6b",bodyColor:"#000",headingColor:"#000",h1BorderBottom:!0,h2BorderBottom:!0,centerH1:!0,blockquoteBg:"transparent",blockquoteBorderColor:"#999",codeBackground:"#f9f9f9",codeFontSize:.88,codeTheme:"solarized-light",tableHeaderBg:"#e8e8e8",tableStriped:!1,pageBackground:"#ffffff",marginTop:25,marginBottom:25,marginLeft:30,marginRight:30},colorful:{name:"Colorful",fontFamily:"Georgia, serif",fontSize:13,lineHeight:1.85,paragraphSpacing:.65,headingScale:1.05,accentColor:"#e84393",bodyColor:"#1a1a2e",headingColor:"#2d0a4e",h1BorderBottom:!1,h2BorderBottom:!1,centerH1:!1,blockquoteBg:"#fdf0f8",blockquoteBorderColor:"#e84393",codeBackground:"#f0eaff",codeFontSize:.85,codeTheme:"dracula",tableHeaderBg:"#2d0a4e",tableStriped:!0,pageBackground:"#ffffff",marginTop:20,marginBottom:20,marginLeft:25,marginRight:25},modern:{name:"Modern",fontFamily:"Arial, sans-serif",fontSize:13,lineHeight:1.75,paragraphSpacing:.6,headingScale:1,accentColor:"#0070f3",bodyColor:"#111",headingColor:"#000",h1BorderBottom:!1,h2BorderBottom:!1,centerH1:!1,blockquoteBg:"#f0f7ff",blockquoteBorderColor:"#0070f3",codeBackground:"#f1f5f9",codeFontSize:.85,codeTheme:"github-dark",tableHeaderBg:"#0070f3",tableStriped:!0,pageBackground:"#ffffff",marginTop:20,marginBottom:20,marginLeft:25,marginRight:25},newspaper:{name:"Newspaper",fontFamily:"Georgia, serif",fontSize:12,lineHeight:1.7,paragraphSpacing:.4,headingScale:1.1,accentColor:"#111",bodyColor:"#111",headingColor:"#000",h1BorderBottom:!0,h2BorderBottom:!0,centerH1:!0,blockquoteBg:"transparent",blockquoteBorderColor:"#111",codeBackground:"#f4f4f4",codeFontSize:.82,codeTheme:"none",tableHeaderBg:"#111",tableStriped:!1,pageBackground:"#ffffff",marginTop:18,marginBottom:18,marginLeft:20,marginRight:20},dark:{name:"Dark",fontFamily:"Georgia, serif",fontSize:13,lineHeight:1.85,paragraphSpacing:.65,headingScale:1,accentColor:"#818cf8",bodyColor:"#d1d5db",headingColor:"#f1f5f9",h1BorderBottom:!1,h2BorderBottom:!0,centerH1:!1,blockquoteBg:"#1e293b",blockquoteBorderColor:"#818cf8",codeBackground:"#0f172a",codeFontSize:.85,codeTheme:"tokyo-night",tableHeaderBg:"#1e293b",tableStriped:!0,pageBackground:"#111827",marginTop:20,marginBottom:20,marginLeft:25,marginRight:25}},ei={pageSize:"A4",orientation:"portrait",preset:"default",...It.default,headerText:"",footerText:"",showHeader:!0,showFooter:!0,showHeaderBorder:!1,showFooterBorder:!1,showPageNumbers:!0,pageNumberPosition:"right",pageNumberStart:1,pageNumberFormat:"{{current}} / {{total}}",showHeaderOnFirstPage:!0,showFooterOnFirstPage:!0,headerAlignment:"right",footerTextAlignment:"left",headerFontSize:9,headerFontColor:"#999999",footerFontSize:9,footerFontColor:"#aaaaaa",linkUnderline:!0,frameEnabled:!1,frameColor:"#000000",frameThickness:4,frameMargin:8,frameStyle:"solid",hideFrontmatter:!1,customFontName:"",autoBreakH1:!1,autoBreakH2:!1,includeFilenameAsTitle:!1,previewScale:.9,customPageWidth:210,customPageHeight:297,headerHeight:0,footerHeight:0,headerImagePath:"",headerImageMargin:0,footerImagePath:"",footerImageMargin:0,backgroundImageEnabled:!1,backgroundImagePath:"",backgroundImageSize:"cover",backgroundImageScope:"full-page",backgroundImageOpacity:1,includeOutline:!0};function Ls(t){return{name:t.name,fontFamily:t.fontFamily,fontSize:t.fontSize,lineHeight:t.lineHeight,paragraphSpacing:t.paragraphSpacing,headingScale:t.headingScale,accentColor:t.accentColor,bodyColor:t.bodyColor,headingColor:t.headingColor,h1BorderBottom:t.h1BorderBottom,h2BorderBottom:t.h2BorderBottom,centerH1:t.centerH1,blockquoteBg:t.blockquoteBg,blockquoteBorderColor:t.blockquoteBorderColor,codeBackground:t.codeBackground,codeFontSize:t.codeFontSize,codeTheme:t.codeTheme,tableHeaderBg:t.tableHeaderBg,tableStriped:t.tableStriped,pageBackground:t.pageBackground,marginTop:t.marginTop,marginBottom:t.marginBottom,marginLeft:t.marginLeft,marginRight:t.marginRight}}var ze=require("obsidian");var Bn=require("obsidian");var gr=t=>t/25.4*96;function Hs(t){return t.pageSize==="Custom"?{w:Math.max(1,Math.round(gr(t.customPageWidth))),h:Math.max(1,Math.round(gr(t.customPageHeight)))}:mr[t.pageSize]??mr.A4}function Mn(t){return t.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'")}function ra(t){return t.replace(/<\/style/gi,"<\\/style")}function yr(t,e){let r=e.trim();if(!r)return"";if(/^(https?:|data:)/i.test(r))return r;let n=t.vault.getAbstractFileByPath(r);if(n instanceof Bn.TFile)return t.vault.getResourcePath(n);let o=t.metadataCache.getFirstLinkpathDest(r,"");return o instanceof Bn.TFile?t.vault.getResourcePath(o):(console.warn("[advanced-pdf-export] Could not resolve image path:",r),r)}function na(t){return{size:t==="fill"?"100% 100%":t==="tile"?"auto":t,repeat:t==="tile"?"repeat":"no-repeat"}}var Cd={comment:["comment","prolog","doctype","cdata"],punctuation:["punctuation"],property:["property","tag","boolean","number","constant","symbol","deleted","attr-name"],selector:["selector","string","char","builtin","inserted","attr-value"],operator:["operator","entity","url"],keyword:["atrule","keyword","important"],function:["function","class-name"],regex:["regex","variable"]},ti={none:{name:"None (plain)"},"github-light":{name:"GitHub Light",background:"#f6f8fa",text:"#24292e",tokens:{comment:"#6a737d",punctuation:"#24292e",property:"#005cc5",selector:"#032f62",operator:"#d73a49",keyword:"#d73a49",function:"#6f42c1",regex:"#032f62"}},"github-dark":{name:"GitHub Dark",background:"#0d1117",text:"#c9d1d9",tokens:{comment:"#8b949e",punctuation:"#c9d1d9",property:"#79c0ff",selector:"#a5d6ff",operator:"#ff7b72",keyword:"#ff7b72",function:"#d2a8ff",regex:"#a5d6ff"}},"atom-one-light":{name:"Atom One Light",background:"#fafafa",text:"#383a42",tokens:{comment:"#a0a1a7",punctuation:"#383a42",property:"#986801",selector:"#50a14f",operator:"#0184bc",keyword:"#a626a4",function:"#4078f2",regex:"#50a14f"}},"atom-one-dark":{name:"Atom One Dark",background:"#282c34",text:"#abb2bf",tokens:{comment:"#5c6370",punctuation:"#abb2bf",property:"#d19a66",selector:"#98c379",operator:"#56b6c2",keyword:"#c678dd",function:"#61afef",regex:"#98c379"}},monokai:{name:"Monokai",background:"#272822",text:"#f8f8f2",tokens:{comment:"#75715e",punctuation:"#f8f8f2",property:"#ae81ff",selector:"#e6db74",operator:"#f92672",keyword:"#f92672",function:"#a6e22e",regex:"#e6db74"}},dracula:{name:"Dracula",background:"#282a36",text:"#f8f8f2",tokens:{comment:"#6272a4",punctuation:"#f8f8f2",property:"#bd93f9",selector:"#f1fa8c",operator:"#ff79c6",keyword:"#ff79c6",function:"#50fa7b",regex:"#ff79c6"}},"tokyo-night":{name:"Tokyo Night",background:"#1a1b26",text:"#a9b1d6",tokens:{comment:"#565f89",punctuation:"#89ddff",property:"#ff9e64",selector:"#9ece6a",operator:"#89ddff",keyword:"#bb9af7",function:"#7aa2f7",regex:"#b4f9f8"}},"solarized-light":{name:"Solarized Light",background:"#fdf6e3",text:"#586e75",tokens:{comment:"#93a1a1",punctuation:"#586e75",property:"#cb4b16",selector:"#2aa198",operator:"#859900",keyword:"#859900",function:"#268bd2",regex:"#2aa198"}},"catppuccin-macchiato":{name:"Catppuccin Macchiato",background:"#24273a",text:"#cad3f5",tokens:{comment:"#939ab7",punctuation:"#b8c0e0",property:"#f5a97f",selector:"#a6da95",operator:"#91d7e3",keyword:"#c6a0f6",function:"#8aadf4",regex:"#f5bde6"}},"catppuccin-mocha":{name:"Catppuccin Mocha",background:"#1e1e2e",text:"#cdd6f4",tokens:{comment:"#9399b2",punctuation:"#bac2de",property:"#fab387",selector:"#a6e3a1",operator:"#89dceb",keyword:"#cba6f7",function:"#89b4fa",regex:"#f5c2e7"}}};function kd(t){let e=ti[t.codeTheme]??ti.none,r=e.background??t.codeBackground,n=e.text??t.bodyColor,o=Object.entries(e.tokens??{}).map(([i,a])=>`${Cd[i].map(l=>`.mpdf-doc pre code .token.${l}`).join(", ")} { color: ${a};${i==="comment"?" font-style: italic;":""} }`).join(` `);return` .mpdf-doc pre { background: ${r}; @@ -54,7 +16,7 @@ end`},Mc=function(){for(var t=[],e=0;e`#${s}${s}${f}${f}${l}${l}`);if(!/^#[\da-f]{6}$/i.test(e))return 1;let r=a=>a<=.04045?a/12.92:((a+.055)/1.055)**2.4,n=r(parseInt(e.slice(1,3),16)/255),o=r(parseInt(e.slice(3,5),16)/255),i=r(parseInt(e.slice(5,7),16)/255);return .2126*n+.7152*o+.0722*i}function _u(t){return t.fontFamily==="__custom__"?t.customFontName.trim()||"inherit":t.fontFamily}function fm(t,e=!1){let r=t.headingScale,n=_u(t),o=lm(t.tableHeaderBg)<.35?"#fff":t.headingColor;return` + ${o}`}function Td(t){let e=t.replace(/^#([\da-f])([\da-f])([\da-f])$/i,(a,s,f,l)=>`#${s}${s}${f}${f}${l}${l}`);if(!/^#[\da-f]{6}$/i.test(e))return 1;let r=a=>a<=.04045?a/12.92:((a+.055)/1.055)**2.4,n=r(parseInt(e.slice(1,3),16)/255),o=r(parseInt(e.slice(3,5),16)/255),i=r(parseInt(e.slice(5,7),16)/255);return .2126*n+.7152*o+.0722*i}function oa(t){return t.fontFamily==="__custom__"?t.customFontName.trim()||"inherit":t.fontFamily}function Us(t,e=!1){let r=t.headingScale,n=oa(t),o=Td(t.tableHeaderBg)<.35?"#fff":t.headingColor;return` .mpdf-doc { font-family: ${n}; font-size: ${t.fontSize}px; @@ -114,7 +76,7 @@ end`},Mc=function(){for(var t=[],e=0;e{try{if(n.sheet?.cssRules)return Array.from(n.sheet.cssRules).map(o=>o.cssText).join(` + `.trim()}function Nn(){let e=Array.from(activeDocument.head.querySelectorAll("style[id^='MJX-']")).map(n=>{try{if(n.sheet?.cssRules)return Array.from(n.sheet.cssRules).map(o=>o.cssText).join(` `)}catch{}return n.textContent??""}).join(` `),r="";try{r=(activeDocument.adoptedStyleSheets??[]).map(o=>{try{return Array.from(o.cssRules).map(i=>i.cssText).join(` `)}catch{return""}}).filter(Boolean).join(` `)}catch(n){console.warn("[advanced-pdf-export] adoptedStyleSheets read failed:",n)}return r?`${e} -${r}`:e}function um(t){return t.replace(/@font-face\s*\{[^{}]*(?:\{[^{}]*\}[^{}]*)?\}/g,"")}async function dm(){let t=qi();if(!t)return"";let e=new Set;for(let[,i]of t.matchAll(Zu)){let a=i.trim();a.startsWith("data:")||e.add(a)}if(!e.size)return t;let r=async i=>{try{let a=await(0,N.requestUrl)(i);if(a.status!==200)return i;let s=new Uint8Array(a.arrayBuffer),f="";for(let d=0;d[i,await r(i)])),o=new Map(n);return t.replace(Zu,(i,a)=>{let s=o.get(a.trim());return s&&s!==a.trim()?`url('${s}')`:i})}var Zu=/url\(\s*["']?([^"')]+)["']?\s*\)/g,hm=new Set(["P","LI","BLOCKQUOTE","TD","TH"]),pm=new Set(["P","DIV","SECTION","ARTICLE","ASIDE","NAV","HEADER","FOOTER","UL","OL","LI","TABLE","THEAD","TBODY","TFOOT","TR","TD","TH","PRE","BLOCKQUOTE","HR","IMG","H1","H2","H3","H4","H5","H6"]),vm=new Set(["CODE","IMG","HR","H1","H2","H3","H4","H5","H6"]),mm=2;function gm(t,e){e.empty();for(let r of t)e.appendChild(r.cloneNode(!0));return e.getBoundingClientRect().height}function ym(t,e,r){return n=>gm([...t,n],e)<=r-mm}function bm(t){let e=activeDocument.createTreeWalker(t,NodeFilter.SHOW_TEXT);for(;e.nextNode();){let r=e.currentNode,n=(r.textContent??"").replace(/^\s+/,"");if(n!==r.textContent&&(r.textContent=n),n.length>0)break}}function Uo(t,e,r=!0){let n=activeDocument.createTreeWalker(t,NodeFilter.SHOW_TEXT),o=0,i=null,a=0;for(;n.nextNode();){let u=n.currentNode,d=u.textContent?.length??0;if(o+d>=e){i=u,a=e-o;break}o+=d}if(!i)return null;let s=activeDocument.createRange();s.selectNodeContents(t),s.setEnd(i,a);let f=activeDocument.createRange();f.selectNodeContents(t),f.setStart(i,a);let l=t.cloneNode(!1);l.appendChild(s.cloneContents());let c=t.cloneNode(!1);return c.appendChild(f.cloneContents()),r&&bm(c),[l,c]}function xm(t){let e=[],r=/\s+/g,n;for(;n=r.exec(t);)n.index>0&&n.index0){let f=0,l=o.length-1,c=-1;for(;f<=l;){let u=Math.floor((f+l)/2),d=Uo(t,o[u]);if(!d){l=u-1;continue}e(d[0])?(c=u,f=u+1):l=u-1}if(c>=0)return Uo(t,o[c]);if(!r)return null}let i=1,a=n.length-1,s=0;for(;i<=a;){let f=Math.floor((i+a)/2),l=Uo(t,f);if(!l){a=f-1;continue}e(l[0])?(s=f,i=f+1):a=f-1}return s>0?Uo(t,s):null}function Ss(t,e,r){let n=t.cloneNode(!1);t.tagName==="OL"&&r!==void 0&&r>1&&(n.start=r);for(let o of e)n.appendChild(o.cloneNode(!0));return n}function wm(t,e,r){let n=Array.from(t.children).filter(a=>a.tagName==="LI");if(n.length===0)return null;let o=t.tagName==="OL"?t.start??1:1,i=0;for(let a=0;a=n.length?null:[Ss(t,n.slice(0,i),o),Ss(t,n.slice(i),o+i)]}function Ps(t,e){let r=t.cloneNode(!1),n=t.querySelector("caption");n&&r.appendChild(n.cloneNode(!0));let o=t.querySelector("colgroup");o&&r.appendChild(o.cloneNode(!0)),t.tHead&&r.appendChild(t.tHead.cloneNode(!0));let i=activeDocument.createElement("tbody");for(let a of e)i.appendChild(a.cloneNode(!0));return r.appendChild(i),r}function Sm(t,e,r){let n=t.tBodies[0],o=n?Array.from(n.rows):Array.from(t.rows).filter(a=>a.parentElement?.tagName!=="THEAD");if(o.length===0)return null;let i=0;for(let a=0;a=o.length?null:[Ps(t,o.slice(0,i)),Ps(t,o.slice(i))]}function Pm(t){let e=[],r=0;for(let n of t)r+=n.length+1,e.push(r);return e}function Dm(t,e,r){let n=t.querySelector("code"),o=(n??t).textContent?.split(` -`)??[];if(o.length>1&&o[o.length-1]===""&&o.pop(),o.length<2)return null;let i=Pm(o),a=l=>{if(!n){let p=h=>{let b=t.cloneNode(!1);return b.textContent=h,b};return[p(o.slice(0,l).join(` +${r}`:e}function Vs(t){return t.replace(/@font-face\s*\{[^{}]*(?:\{[^{}]*\}[^{}]*)?\}/g,"")}var js=/url\(\s*["']?([^"')]+)["']?\s*\)/g;async function qs(){let t=Nn();if(!t)return"";let e=new Set;for(let[,i]of t.matchAll(js)){let a=i.trim();a.startsWith("data:")||e.add(a)}if(!e.size)return t;let r=async i=>{try{let a=await(0,Bn.requestUrl)(i);if(a.status!==200)return i;let s=new Uint8Array(a.arrayBuffer),f="";for(let d=0;d[i,await r(i)])),o=new Map(n);return t.replace(js,(i,a)=>{let s=o.get(a.trim());return s&&s!==a.trim()?`url('${s}')`:i})}async function In(){let n=Date.now(),o=Nn().length,i=0;for(;i<2&&Date.now()-n<2500;){await new Promise(s=>window.setTimeout(s,60));let a=Nn().length;a===o?i++:(i=0,o=a)}}var Xr=require("obsidian");function Gs(t){return t.replace(/\r\n|\r/g,` +`)}function Ks(t){return t.replace(/^---[ \t]*\n[\s\S]*?\n---[ \t]*(\n|$)/,"")}function Xs(t){return t.split(/^\/\/\/\s*$/m).map(e=>e.trim()).filter(Boolean)}var Ed=/[\u0590-\u08FF\uFB1D-\uFDFD\uFE70-\uFEFC]/g,Ad=/[A-Za-z\u0590-\u08FF\uFB1D-\uFDFD\uFE70-\uFEFC]/g;function Zs(t){let e=(t.match(Ed)??[]).length,r=(t.match(Ad)??[]).length;return r>0&&e/r>.1}var Rd=/[^\p{L}\p{N}\s-]/gu,Od=/\s+/g,Bd=/-+/g;function Ws(t){return t.toLowerCase().replace(Rd,"").trim().replace(Od,"-").replace(Bd,"-")}function Nd(t){let e=new Map;t.querySelectorAll("h1,h2,h3,h4,h5,h6").forEach(r=>{let n=r.textContent||"",o=Ws(n);if(!o)return;let i=e.get(o)??0;e.set(o,i+1),r.id=i===0?o:`${o}-${i}`}),t.querySelectorAll("a").forEach(r=>{r.classList.remove("external-link");let n=r.getAttribute("data-href")??r.getAttribute("href");n?.startsWith("#")&&r.setAttribute("href","#"+Ws(n.slice(1)))}),t.querySelectorAll(".copy-code-button").forEach(r=>r.remove()),t.querySelectorAll(".callout").forEach(r=>{r.removeAttribute("data-callout-fold"),r.classList.remove("is-collapsed"),r.querySelectorAll(".callout-fold").forEach(n=>n.remove())}),t.querySelectorAll("style, script").forEach(r=>{r.closest("svg")||r.remove()})}async function Md(t){let e=Array.from(t.querySelectorAll(".mermaid"));if(e.length===0)return;let r=5e3;await Promise.all(e.map(n=>new Promise(o=>{if(n.querySelector("svg")){o();return}let i=window.setTimeout(()=>{a.disconnect(),o()},r),a=new MutationObserver(()=>{n.querySelector("svg")&&(window.clearTimeout(i),a.disconnect(),o())});a.observe(n,{childList:!0,subtree:!0})})))}async function Id(t){let e=Array.from(t.querySelectorAll(".math"));if(e.length===0)return;let r=window.MathJax;if(r?.startup?.promise)try{await r.startup.promise}catch{}let n=8e3;await Promise.all(e.filter(o=>!o.querySelector("mjx-container")).map(o=>new Promise(i=>{let a=window.setTimeout(()=>{s.disconnect(),i()},n),s=new MutationObserver(()=>{o.querySelector("mjx-container")&&(window.clearTimeout(a),s.disconnect(),i())});s.observe(o,{childList:!0,subtree:!0})}))),await In()}async function ia(t,e,r,n){let o=activeDocument.createElement("div");o.setCssStyles({position:"fixed",top:"0",left:"-99999px",visibility:"hidden",pointerEvents:"none"}),activeDocument.body.appendChild(o);try{await Xr.MarkdownRenderer.render(t,e,o,r,n);let i=3e3;try{let s;await Promise.race([(0,Xr.finishRenderMath)().finally(()=>window.clearTimeout(s)),new Promise(f=>{s=window.setTimeout(f,i)})])}catch(s){console.warn("[advanced-pdf-export] finishRenderMath failed:",s)}await Md(o),await Id(o);let a=activeDocument.fonts;if(a)try{await a.ready}catch{}}finally{activeDocument.body.removeChild(o)}return Nd(o),o}async function Ys(t){let e=new Xr.Component;e.load();try{await ia(t,"$\\mathbf{A}+\\mathfrak{A}+\\mathcal{A}+\\mathsf{A}+\\mathtt{A}+\\mathbb{A}+\\aleph+\\vec{v}$","",e)}catch(r){console.warn("[advanced-pdf-export] MathJax warm-up failed (non-fatal):",r)}finally{e.unload()}}var aa=function(t,e){return aa=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,n){r.__proto__=n}||function(r,n){for(var o in n)n.hasOwnProperty(o)&&(r[o]=n[o])},aa(t,e)};function k(t,e){aa(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}var Y=function(){return Y=Object.assign||function(e){for(var r,n=1,o=arguments.length;n0&&i[i.length-1])&&(l[0]===6||l[0]===2)){r=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]>2],e+=Zr[(t[n]&3)<<4|t[n+1]>>4],e+=Zr[(t[n+1]&15)<<2|t[n+2]>>6],e+=Zr[t[n+2]&63];return r%3===2?e=e.substring(0,e.length-1)+"=":r%3===1&&(e=e.substring(0,e.length-2)+"=="),e},Qs=function(t){var e=t.length*.75,r=t.length,n,o=0,i,a,s,f;t[t.length-1]==="="&&(e--,t[t.length-2]==="="&&e--);var l=new Uint8Array(e);for(n=0;n>4,l[o++]=(a&15)<<4|s>>2,l[o++]=(s&3)<<6|f&63;return l},zd=/^(data)?:?([\w\/\+]+)?;?(charset=[\w-]+|base64)?.*,/i,$s=function(t){var e=t.trim(),r=e.substring(0,100),n=r.match(zd);if(!n)return Qs(e);var o=n[0],i=e.substring(o.length);return Qs(i)};var Q=function(t){return t.charCodeAt(0)},el=function(t){return t.codePointAt(0)},zt=function(t,e){return nt(t.toString(16),e,"0").toUpperCase()},Kt=function(t){return zt(t,2)},rt=function(t){return String.fromCharCode(t)},tl=function(t){return rt(parseInt(t,16))},nt=function(t,e,r){for(var n="",o=0,i=e-t.length;o=55296&&r<=56319&&t.length>o&&(n=t.charCodeAt(o),n>=56320&&n<=57343&&(i=2)),[t.slice(e,e+i),i]},nl=function(t){for(var e=[],r=0,n=t.length;rr&&l(),a+=d,s+=p}}return l(),f},Ud=/^D:(\d\d\d\d)(\d\d)?(\d\d)?(\d\d)?(\d\d)?(\d\d)?([+\-Z])?(\d\d)?'?(\d\d)?'?$/,ni=function(t){var e=t.match(Ud);if(e){var r=e[1],n=e[2],o=n===void 0?"01":n,i=e[3],a=i===void 0?"01":i,s=e[4],f=s===void 0?"00":s,l=e[5],c=l===void 0?"00":l,u=e[6],d=u===void 0?"00":u,p=e[7],h=p===void 0?"Z":p,b=e[8],F=b===void 0?"00":b,x=e[9],m=x===void 0?"00":x,y=h==="Z"?"Z":""+h+F+":"+m,w=new Date(r+"-"+o+"-"+a+"T"+f+":"+c+":"+d+y);return w}},jn=function(t,e){for(var r,n=0,o;n=0&&t<=65535},gl=function(t){return t>=65536&&t<=1114111},fa=function(t){return Math.floor((t-65536)/1024)+55296},ca=function(t){return(t-65536)%1024+56320},Xt;(function(t){t.BigEndian="BigEndian",t.LittleEndian="LittleEndian"})(Xt||(Xt={}));var Hn="\uFFFD".codePointAt(0),ai=function(t,e){if(e===void 0&&(e=!0),t.length<=1)return String.fromCodePoint(Hn);for(var r=e?qd(t):Xt.BigEndian,n=e?2:0,o=[];t.length-n>=2;){var i=pl(t[n++],t[n++],r);if(Vd(i))if(t.length-n<2)o.push(Hn);else{var a=pl(t[n++],t[n++],r);hl(a)?o.push(i,a):o.push(Hn)}else hl(i)?(n+=2,o.push(Hn)):o.push(i)}return n=55296&&t<=56319},hl=function(t){return t>=56320&&t<=57343},pl=function(t,e,r){if(r===Xt.LittleEndian)return e<<8|t;if(r===Xt.BigEndian)return t<<8|e;throw new Error("Invalid byteOrder: "+r)},qd=function(t){return yl(t)?Xt.BigEndian:bl(t)?Xt.LittleEndian:Xt.BigEndian},yl=function(t){return t[0]===254&&t[1]===255},bl=function(t){return t[0]===255&&t[1]===254},si=function(t){return yl(t)||bl(t)};var xl=function(t){var e=String(t);if(Math.abs(t)<1){var r=parseInt(t.toString().split("e-")[1]);if(r){var n=t<0;n&&(t*=-1),t*=Math.pow(10,r-1),e="0."+new Array(r).join("0")+t.toString().substring(2),n&&(e="-"+e)}}else{var r=parseInt(t.toString().split("+")[1]);r>20&&(r-=20,t/=Math.pow(10,r),e=t.toString()+new Array(r+1).join("0"))}return e},Un=function(t){return Math.ceil(t.toString(2).length/8)},Fr=function(t){for(var e=new Uint8Array(Un(t)),r=1;r<=e.length;r++)e[r-1]=t>>(e.length-r)*8;return e};var wr=function(t){throw new Error(t)};var fc=$o(oo()),lc="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",ao=new Uint8Array(256);for(io=0;io>4,l[o++]=(a&15)<<4|s>>2,l[o++]=(s&3)<<6|f&63;return l},zp=function(t){for(var e="",r=0;rn)throw new Error(Me(e)+" must be at least "+r+" and at most "+n+", but was actually "+t)},it=function(t,e,r,n){P(t,e,["number","undefined"]),typeof t=="number"&&Ve(t,e,r,n)},Ci=function(t,e,r){if(P(t,e,["number"]),t%r!==0)throw new Error(Me(e)+" must be a multiple of "+r+", but was actually "+t)},Ac=function(t,e){if(!Number.isInteger(t))throw new Error(Me(e)+" must be an integer, but was actually "+t)},er=function(t,e){if(![1,0].includes(Math.sign(t)))throw new Error(Me(e)+" must be a positive number or 0, but was actually "+t)};var $=new Uint16Array(256);for(co=0;co<256;co++)$[co]=co;var co;$[22]=Q("");$[24]=Q("\u02D8");$[25]=Q("\u02C7");$[26]=Q("\u02C6");$[27]=Q("\u02D9");$[28]=Q("\u02DD");$[29]=Q("\u02DB");$[30]=Q("\u02DA");$[31]=Q("\u02DC");$[127]=Q("\uFFFD");$[128]=Q("\u2022");$[129]=Q("\u2020");$[130]=Q("\u2021");$[131]=Q("\u2026");$[132]=Q("\u2014");$[133]=Q("\u2013");$[134]=Q("\u0192");$[135]=Q("\u2044");$[136]=Q("\u2039");$[137]=Q("\u203A");$[138]=Q("\u2212");$[139]=Q("\u2030");$[140]=Q("\u201E");$[141]=Q("\u201C");$[142]=Q("\u201D");$[143]=Q("\u2018");$[144]=Q("\u2019");$[145]=Q("\u201A");$[146]=Q("\u2122");$[147]=Q("\uFB01");$[148]=Q("\uFB02");$[149]=Q("\u0141");$[150]=Q("\u0152");$[151]=Q("\u0160");$[152]=Q("\u0178");$[153]=Q("\u017D");$[154]=Q("\u0131");$[155]=Q("\u0142");$[156]=Q("\u0153");$[157]=Q("\u0161");$[158]=Q("\u017E");$[159]=Q("\uFFFD");$[160]=Q("\u20AC");$[173]=Q("\uFFFD");var ki=function(t){for(var e=new Array(t.length),r=0,n=t.length;r=g.ExclamationPoint&&t<=g.Tilde&&!Ei[t]},Zc={},Yc=new Map,v0=function(t){k(e,t);function e(r,n){var o=this;if(r!==Zc)throw new ln("PDFName");o=t.call(this)||this;for(var i="/",a=0,s=n.length;a=g.Zero&&l<=g.Nine||l>=g.a&&l<=g.f||l>=g.A&&l<=g.F?(n+=f,(n.length===2||!(c>="0"&&c<="9"||c>="a"&&c<="f"||c>="A"&&c<="F"))&&(i(parseInt(n,16)),n="")):i(l):l===g.Hash?o=!0:i(l)}return new Uint8Array(r)},e.prototype.decodeText=function(){var r=this.asBytes();return String.fromCharCode.apply(String,Array.from(r))},e.prototype.asString=function(){return this.encodedName},e.prototype.value=function(){return this.encodedName},e.prototype.clone=function(){return this},e.prototype.toString=function(){return this.encodedName},e.prototype.sizeInBytes=function(){return this.encodedName.length},e.prototype.copyBytesInto=function(r,n){return n+=me(this.encodedName,r,n),this.encodedName.length},e.of=function(r){var n=h0(r),o=Yc.get(n);return o||(o=new e(Zc,n),Yc.set(n,o)),o},e.Length=e.of("Length"),e.FlateDecode=e.of("FlateDecode"),e.Resources=e.of("Resources"),e.Font=e.of("Font"),e.XObject=e.of("XObject"),e.ExtGState=e.of("ExtGState"),e.Contents=e.of("Contents"),e.Type=e.of("Type"),e.Parent=e.of("Parent"),e.MediaBox=e.of("MediaBox"),e.Page=e.of("Page"),e.Annots=e.of("Annots"),e.TrimBox=e.of("TrimBox"),e.ArtBox=e.of("ArtBox"),e.BleedBox=e.of("BleedBox"),e.CropBox=e.of("CropBox"),e.Rotate=e.of("Rotate"),e.Title=e.of("Title"),e.Author=e.of("Author"),e.Subject=e.of("Subject"),e.Creator=e.of("Creator"),e.Keywords=e.of("Keywords"),e.Producer=e.of("Producer"),e.CreationDate=e.of("CreationDate"),e.ModDate=e.of("ModDate"),e}(ve),v=v0;var m0=function(t){k(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.asNull=function(){return null},e.prototype.clone=function(){return this},e.prototype.toString=function(){return"null"},e.prototype.sizeInBytes=function(){return 4},e.prototype.copyBytesInto=function(r,n){return r[n++]=g.n,r[n++]=g.u,r[n++]=g.l,r[n++]=g.l,4},e}(ve),Te=new m0;var g0=function(t){k(e,t);function e(r,n){var o=t.call(this)||this;return o.dict=r,o.context=n,o}return e.prototype.keys=function(){return Array.from(this.dict.keys())},e.prototype.values=function(){return Array.from(this.dict.values())},e.prototype.entries=function(){return Array.from(this.dict.entries())},e.prototype.set=function(r,n){this.dict.set(r,n)},e.prototype.get=function(r,n){n===void 0&&(n=!1);var o=this.dict.get(r);if(!(o===Te&&!n))return o},e.prototype.has=function(r){var n=this.dict.get(r);return n!==void 0&&n!==Te},e.prototype.lookupMaybe=function(r){for(var n,o=[],i=1;ithis.largestObjectNumber&&(this.largestObjectNumber=e.objectNumber)},t.prototype.nextRef=function(){return this.largestObjectNumber+=1,J.of(this.largestObjectNumber)},t.prototype.register=function(e){var r=this.nextRef();return this.assign(r,e),r},t.prototype.delete=function(e){return this.indirectObjects.delete(e)},t.prototype.lookupMaybe=function(e){for(var r=[],n=1;n1?(this.subsections.push([e]),this.chunkIdx+=1,this.chunkLength=1):(r.push(e),this.chunkLength+=1)},t.create=function(){return new t({ref:J.of(0,65535),offset:0,deleted:!0})},t.createEmpty=function(){return new t},t}(),uo=T0;var E0=function(){function t(e){this.lastXRefOffset=String(e)}return t.prototype.toString=function(){return`startxref +`+this.lastXRefOffset+` +%%EOF`},t.prototype.sizeInBytes=function(){return 16+this.lastXRefOffset.length},t.prototype.copyBytesInto=function(e,r){var n=r;return e[r++]=g.s,e[r++]=g.t,e[r++]=g.a,e[r++]=g.r,e[r++]=g.t,e[r++]=g.x,e[r++]=g.r,e[r++]=g.e,e[r++]=g.f,e[r++]=g.Newline,r+=me(this.lastXRefOffset,e,r),e[r++]=g.Newline,e[r++]=g.Percent,e[r++]=g.Percent,e[r++]=g.E,e[r++]=g.O,e[r++]=g.F,r-n},t.forLastCrossRefSectionOffset=function(e){return new t(e)},t}(),Nr=E0;var A0=function(){function t(e){this.dict=e}return t.prototype.toString=function(){return`trailer +`+this.dict.toString()},t.prototype.sizeInBytes=function(){return 8+this.dict.sizeInBytes()},t.prototype.copyBytesInto=function(e,r){var n=r;return e[r++]=g.t,e[r++]=g.r,e[r++]=g.a,e[r++]=g.i,e[r++]=g.l,e[r++]=g.e,e[r++]=g.r,e[r++]=g.Newline,r+=this.dict.copyBytesInto(e,r),r-n},t.of=function(e){return new t(e)},t}(),es=A0;var R0=function(t){k(e,t);function e(r,n,o){o===void 0&&(o=!0);var i=t.call(this,r.obj({}),o)||this;return i.objects=n,i.offsets=i.computeObjectOffsets(),i.offsetsString=i.computeOffsetsString(),i.dict.set(v.of("Type"),v.of("ObjStm")),i.dict.set(v.of("N"),z.of(i.objects.length)),i.dict.set(v.of("First"),z.of(i.offsetsString.length)),i}return e.prototype.getObjectsCount=function(){return this.objects.length},e.prototype.clone=function(r){return e.withContextAndObjects(r||this.dict.context,this.objects.slice(),this.encode)},e.prototype.getContentsString=function(){for(var r=this.offsetsString,n=0,o=this.objects.length;n1&&(a.push(s),a.push(c.ref.objectNumber),s=0),s+=1}return a.push(s),a},i.computeEntryTuples=function(){for(var a=new Array(i.entries.length),s=0,f=i.entries.length;ss[0]&&(s[0]=h),b>s[1]&&(s[1]=b),F>s[2]&&(s[2]=F)}return s},i.entries=n||[],i.entryTuplesCache=qe.populatedBy(i.computeEntryTuples),i.maxByteWidthsCache=qe.populatedBy(i.computeMaxEntryByteWidths),i.indexCache=qe.populatedBy(i.computeIndex),r.set(v.of("Type"),v.of("XRef")),i}return e.prototype.addDeletedEntry=function(r,n){var o=rr.Deleted;this.entries.push({type:o,ref:r,nextFreeObjectNumber:n}),this.entryTuplesCache.invalidate(),this.maxByteWidthsCache.invalidate(),this.indexCache.invalidate(),this.contentsCache.invalidate()},e.prototype.addUncompressedEntry=function(r,n){var o=rr.Uncompressed;this.entries.push({type:o,ref:r,offset:n}),this.entryTuplesCache.invalidate(),this.maxByteWidthsCache.invalidate(),this.indexCache.invalidate(),this.contentsCache.invalidate()},e.prototype.addCompressedEntry=function(r,n,o){var i=rr.Compressed;this.entries.push({type:i,ref:r,objectStreamRef:n,index:o}),this.entryTuplesCache.invalidate(),this.maxByteWidthsCache.invalidate(),this.indexCache.invalidate(),this.contentsCache.invalidate()},e.prototype.clone=function(r){var n=this,o=n.dict,i=n.entries,a=n.encode;return e.of(o.clone(r),i.slice(),a)},e.prototype.getContentsString=function(){for(var r=this.entryTuplesCache.access(),n=this.maxByteWidthsCache.access(),o="",i=0,a=r.length;i=0;h--)o+=(u[h]||0).toString(2);for(var h=n[1]-1;h>=0;h--)o+=(d[h]||0).toString(2);for(var h=n[2]-1;h>=0;h--)o+=(p[h]||0).toString(2)}return o},e.prototype.getUnencodedContents=function(){for(var r=this.entryTuplesCache.access(),n=this.maxByteWidthsCache.access(),o=new Uint8Array(this.getUnencodedContentsSize()),i=0,a=0,s=r.length;a=0;b--)o[i++]=d[b]||0;for(var b=n[1]-1;b>=0;b--)o[i++]=p[b]||0;for(var b=n[2]-1;b>=0;b--)o[i++]=h[b]||0}return o},e.prototype.getUnencodedContentsSize=function(){var r=this.maxByteWidthsCache.access(),n=fl(r);return n*this.entries.length},e.prototype.updateDict=function(){t.prototype.updateDict.call(this);var r=this.maxByteWidthsCache.access(),n=this.indexCache.access(),o=this.dict.context;this.dict.set(v.of("W"),o.obj(r)),this.dict.set(v.of("Index"),o.obj(n))},e.create=function(r,n){n===void 0&&(n=!0);var o=new e(r,[],n);return o.addDeletedEntry(J.of(0,65535),0),o},e.of=function(r,n,o){return o===void 0&&(o=!0),new e(r,n,o)},e}(Br),ts=N0;var M0=function(t){k(e,t);function e(r,n,o,i){var a=t.call(this,r,n)||this;return a.encodeStreams=o,a.objectsPerStream=i,a}return e.prototype.computeBufferSize=function(){return V(this,void 0,void 0,function(){var r,n,o,i,a,s,f,l,h,b,c,x,u,d,F,p,h,b,F,x,m,y,w,S;return q(this,function(D){switch(D.label){case 0:r=this.context.largestObjectNumber+1,n=Vt.forVersion(1,7),o=n.sizeInBytes()+2,i=ts.create(this.createTrailerDict(),this.encodeStreams),a=[],s=[],f=[],l=this.context.enumerateIndirectObjects(),h=0,b=l.length,D.label=1;case 1:return h"},e.prototype.sizeInBytes=function(){return this.value.length+2},e.prototype.copyBytesInto=function(r,n){return r[n++]=g.LessThan,n+=me(this.value,r,n),r[n++]=g.GreaterThan,this.value.length+2},e.of=function(r){return new e(r)},e.fromText=function(r){for(var n=vl(r),o="",i=0,a=n.length;i> def +/CMapName /Adobe-Identity-UCS def +/CMapType 2 def +1 begincodespacerange +<0000> +endcodespacerange +`+t.length+` beginbfchar +`+t.map(function(e){var r=e[0],n=e[1];return r+" "+n}).join(` +`)+` +endbfchar +endcmap +CMapName currentdict /CMap defineresource pop +end +end`},tu=function(){for(var t=[],e=0;e"},Ri=function(t){return zt(t,4)},j0=function(t){if(ml(t))return Ri(t);if(gl(t)){var e=fa(t),r=ca(t);return""+Ri(e)+Ri(r)}var n=Kt(t),o="0x"+n+" is not a valid UTF-8 or UTF-16 codepoint.";throw new Error(o)};var H0=function(t){var e=0,r=function(n){e|=1<=g.Zero&&l<=g.Seven?(n+=f,(n.length===3||!(c>="0"&&c<="7"))&&(i(parseInt(n,8)),n="")):i(l):l===g.BackSlash?o=!0:i(l)}return new Uint8Array(r)},e.prototype.decodeText=function(){var r=this.asBytes();return si(r)?ai(r):ki(r)},e.prototype.decodeDate=function(){var r=this.decodeText(),n=ni(r);if(!n)throw new Ti(r);return n},e.prototype.asString=function(){return this.value},e.prototype.clone=function(){return e.of(this.value)},e.prototype.toString=function(){return"("+this.value+")"},e.prototype.sizeInBytes=function(){return this.value.length+2},e.prototype.copyBytesInto=function(r,n){return r[n++]=g.LeftParen,n+=me(this.value,r,n),r[n++]=g.RightParen,this.value.length+2},e.of=function(r){return new e(r)},e.fromDate=function(r){var n=nt(String(r.getUTCFullYear()),4,"0"),o=nt(String(r.getUTCMonth()+1),2,"0"),i=nt(String(r.getUTCDate()),2,"0"),a=nt(String(r.getUTCHours()),2,"0"),s=nt(String(r.getUTCMinutes()),2,"0"),f=nt(String(r.getUTCSeconds()),2,"0");return new e("D:"+n+o+i+a+s+f+"Z")},e}(ve),ne=U0;var V0=function(){function t(e,r,n,o){var i=this;this.allGlyphsInFontSortedById=function(){for(var a=new Array(i.font.characterSet.length),s=0,f=a.length;s>3)]>>7-((h&7)<<0)&1,R=3*A;s[w]=S[R],s[w+1]=S[R+1],s[w+2]=S[R+2],s[w+3]=A>2)]>>6-((h&3)<<1)&3,R=3*A;s[w]=S[R],s[w+1]=S[R+1],s[w+2]=S[R+2],s[w+3]=A>1)]>>4-((h&1)<<2)&15,R=3*A;s[w]=S[R],s[w+1]=S[R+1],s[w+2]=S[R+2],s[w+3]=A>>3)]>>>7-(L&7)&1),ue=N==x*255?0:255;f[te+L]=ue<<24|N<<16|N<<8|N}else if(c==2)for(var L=0;L>>2)]>>>6-((L&3)<<1)&3),ue=N==x*85?0:255;f[te+L]=ue<<24|N<<16|N<<8|N}else if(c==4)for(var L=0;L>>1)]>>>4-((L&1)<<2)&15),ue=N==x*17?0:255;f[te+L]=ue<<24|N<<16|N<<8|N}else if(c==8)for(var L=0;L>>2<<3));o==0;){if(o=F(e,d,1),i=F(e,d+1,2),d+=3,i==0){(d&7)!=0&&(d+=8-(d&7));var C=(d>>>3)+4,E=e[C-4]|e[C-3]<<8;T&&(r=t.H.W(r,u+E)),r.set(new n(e.buffer,e.byteOffset+C,E),u),d=C+E<<3,u+=E;continue}if(T&&(r=t.H.W(r,u+(1<<17))),i==1&&(p=D.J,h=D.h,l=511,c=31),i==2){a=x(e,d,5)+257,s=x(e,d+5,5)+1,f=x(e,d+10,4)+4,d+=14;for(var M=d,A=1,R=0;R<38;R+=2)D.Q[R]=0,D.Q[R+1]=0;for(var R=0;RA&&(A=I)}d+=3*f,y(D.Q,A),w(D.Q,A,D.u),p=D.w,h=D.d,d=m(D.u,(1<>>4;if(!(L>>>8))r[u++]=L;else{if(L==256)break;var ue=u+L-254;if(L>264){var ye=D.q[L-257];ue=u+(ye>>>3)+x(e,d,ye&7),d+=ye&7}var oe=h[S(e,d)&c];d+=oe&15;var Fe=oe>>>4,Ce=D.c[Fe],Be=(Ce>>>4)+F(e,d,Ce&15);for(d+=Ce&15;u>>4;if(u<=15)a[l]=u,l++;else{var d=0,p=0;u==16?(p=3+s(o,i,2),i+=2,d=a[l-1]):u==17?(p=3+s(o,i,3),i+=3):u==18&&(p=11+s(o,i,7),i+=7);for(var h=l+p;l>>1;ai&&(i=f),a++}for(;a>1,l=e[s+1],c=f<<4|l,u=r-l,d=e[s]<>>15-r;n[h]=c,d++}},t.H.l=function(e,r){for(var n=t.H.m.r,o=15-r,i=0;i>>o}},t.H.M=function(e,r,n){n=n<<(r&7);var o=r>>>3;e[o]|=n,e[o+1]|=n>>>8},t.H.I=function(e,r,n){n=n<<(r&7);var o=r>>>3;e[o]|=n,e[o+1]|=n>>>8,e[o+2]|=n>>>16},t.H.e=function(e,r,n){return(e[r>>>3]|e[(r>>>3)+1]<<8)>>>(r&7)&(1<>>3]|e[(r>>>3)+1]<<8|e[(r>>>3)+2]<<16)>>>(r&7)&(1<>>3]|e[(r>>>3)+1]<<8|e[(r>>>3)+2]<<16)>>>(r&7)},t.H.i=function(e,r){return(e[r>>>3]|e[(r>>>3)+1]<<8|e[(r>>>3)+2]<<16|e[(r>>>3)+3]<<24)>>>(r&7)},t.H.m=function(){var e=Uint16Array,r=Uint32Array;return{K:new e(16),j:new e(16),X:[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],S:[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,999,999,999],T:[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0],q:new e(32),p:[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,65535,65535],z:[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0],c:new r(32),J:new e(512),_:[],h:new e(32),$:[],w:new e(32768),C:[],v:[],d:new e(32768),D:[],u:new e(512),Q:[],r:new e(32768),s:new r(286),Y:new r(30),a:new r(19),t:new r(15e3),k:new e(65536),g:new e(32768)}}(),function(){for(var e=t.H.m,r=32768,n=0;n>>1|(o&1431655765)<<1,o=(o&3435973836)>>>2|(o&858993459)<<2,o=(o&4042322160)>>>4|(o&252645135)<<4,o=(o&4278255360)>>>8|(o&16711935)<<8,e.r[n]=(o>>>16|o<<16)>>>17}function i(a,s,f){for(;s--!=0;)a.push(0,f)}for(var n=0;n<32;n++)e.q[n]=e.S[n]<<3|e.T[n],e.c[n]=e.p[n]<<4|e.z[n];i(e._,144,8),i(e._,112,9),i(e._,24,7),i(e._,8,8),t.H.n(e._,9),t.H.A(e._,9,e.J),t.H.l(e._,9),i(e.$,32,5),t.H.n(e.$,5),t.H.A(e.$,5,e.h),t.H.l(e.$,5),i(e.Q,19,0),i(e.C,286,0),i(e.D,30,0),i(e.v,320,0)}(),t.H.N}();B.decode._readInterlace=function(t,e){for(var r=e.width,n=e.height,o=B.decode._getBPP(e),i=o>>3,a=Math.ceil(r*o/8),s=new Uint8Array(n*a),f=0,l=[0,0,4,0,2,0,1],c=[0,4,0,2,0,1,0],u=[8,8,8,4,4,2,2],d=[8,8,4,4,2,2,1],p=0;p<7;){for(var h=u[p],b=d[p],F=0,x=0,m=l[p];m>3];E=E>>7-(C&7)&1,s[D*a+(T>>3)]|=E<<7-((T&7)<<0)}if(o==2){var E=t[C>>3];E=E>>6-(C&7)&3,s[D*a+(T>>2)]|=E<<6-((T&3)<<1)}if(o==4){var E=t[C>>3];E=E>>4-(C&7)&15,s[D*a+(T>>1)]|=E<<4-((T&1)<<2)}if(o>=8)for(var M=D*a+T*i,A=0;A>3)+A];C+=o,T+=b}S++,D+=h}F*x!=0&&(f+=x*(1+w)),p=p+1}return s};B.decode._getBPP=function(t){var e=[1,null,3,1,2,null,4][t.ctype];return e*t.depth};B.decode._filterZero=function(t,e,r,n,o){var i=B.decode._getBPP(e),a=Math.ceil(n*i/8),s=B.decode._paeth;i=Math.ceil(i/8);var f=0,l=1,c=t[r],u=0;if(c>1&&(t[r]=[0,0,1][c-2]),c==3)for(u=i;u>>1)&255;for(var d=0;d>>1);for(;u>>1)}else{for(;u>8&255,t[e+1]=r&255},readUint:function(t,e){return t[e]*(256*256*256)+(t[e+1]<<16|t[e+2]<<8|t[e+3])},writeUint:function(t,e,r){t[e]=r>>24&255,t[e+1]=r>>16&255,t[e+2]=r>>8&255,t[e+3]=r&255},readASCII:function(t,e,r){for(var n="",o=0;o=0&&s>=0?(u=p*e+h<<2,d=(s+p)*o+a+h<<2):(u=(-s+p)*e-a+h<<2,d=p*o+h<<2),f==0)n[d]=t[u],n[d+1]=t[u+1],n[d+2]=t[u+2],n[d+3]=t[u+3];else if(f==1){var b=t[u+3]*.00392156862745098,F=t[u]*b,x=t[u+1]*b,m=t[u+2]*b,y=n[d+3]*(1/255),w=n[d]*y,S=n[d+1]*y,D=n[d+2]*y,T=1-b,C=b+y*T,E=C==0?0:1/C;n[d+3]=255*C,n[d+0]=(F+w*T)*E,n[d+1]=(x+S*T)*E,n[d+2]=(m+D*T)*E}else if(f==2){var b=t[u+3],F=t[u],x=t[u+1],m=t[u+2],y=n[d+3],w=n[d],S=n[d+1],D=n[d+2];b==y&&F==w&&x==S&&m==D?(n[d]=0,n[d+1]=0,n[d+2]=0,n[d+3]=0):(n[d]=F,n[d+1]=x,n[d+2]=m,n[d+3]=b)}else if(f==3){var b=t[u+3],F=t[u],x=t[u+1],m=t[u+2],y=n[d+3],w=n[d],S=n[d+1],D=n[d+2];if(b==y&&F==w&&x==S&&m==D)continue;if(b<220&&y>20)return!1}return!0};B.encode=function(t,e,r,n,o,i,a){n==null&&(n=0),a==null&&(a=!1);var s=B.encode.compress(t,e,r,n,[!1,!1,!1,0,a]);return B.encode.compressPNG(s,-1),B.encode._main(s,e,r,o,i)};B.encodeLL=function(t,e,r,n,o,i,a,s){for(var f={ctype:0+(n==1?0:2)+(o==0?0:4),depth:i,frames:[]},l=Date.now(),c=(n+o)*i,u=c*e,d=0;d1,u=!1,d=33+(c?20:0);if(o.sRGB!=null&&(d+=13),o.pHYs!=null&&(d+=21),t.ctype==3){for(var p=t.plte.length,h=0;h>>24!=255&&(u=!0);d+=8+p*3+4+(u?8+p*1+4:0)}for(var b=0;b>>8&255,T=w>>>16&255;x[l+y+0]=S,x[l+y+1]=D,x[l+y+2]=T}if(l+=p*3,a(x,l,i(x,l-p*3-4,p*3+4)),l+=4,u){a(x,l,p),l+=4,f(x,l,"tRNS"),l+=4;for(var h=0;h>>24&255;l+=p,a(x,l,i(x,l-p-4,p+4)),l+=4}}for(var C=0,b=0;b>2,R>>2));for(var p=0;pX&&L==N[F-X])te[F]=te[F-X];else{var ue=y[L];if(ue==null&&(y[L]=ue=w.length,w.push(L),w.length>=300))break;te[F]=ue}}}var ye=w.length;ye<=256&&l==!1&&(ye<=2?u=1:ye<=4?u=2:ye<=16?u=4:u=8,u=Math.max(u,f));for(var p=0;p>1)]|=Yo[Qo+we]<<4-(we&1)*4;else if(u==2)for(var we=0;we>2)]|=Yo[Qo+we]<<6-(we&3)*2;else if(u==1)for(var we=0;we>3)]|=Yo[Qo+we]<<7-(we&7)*1}Be=St,c=3,ea=1}else if(x==!1&&m.length==1){for(var St=new Uint8Array(X*Ce*3),yd=X*Ce,F=0;FT&&(T=M),EC&&(C=E))}T==-1&&(S=D=T=C=0),o&&((S&1)==1&&S--,(D&1)==1&&D--);var R=(T-S+1)*(C-D+1);RF&&(F=w),Sx&&(x=S))}F==-1&&(h=b=F=x=0),a&&((h&1)==1&&h--,(b&1)==1&&b--),i={x:h,y:b,width:F-h+1,height:x-b+1};var C=n[o];C.rect=i,C.blend=1,C.img=new Uint8Array(i.width*i.height*4),n[o-1].dispose==0?(B._copyTile(l,e,r,C.img,i.width,i.height,-i.x,-i.y,0),B.encode._prepareDiff(d,e,r,C.img,i)):B._copyTile(d,e,r,C.img,i.width,i.height,-i.x,-i.y,0)};B.encode._prepareDiff=function(t,e,r,n,o){B._copyTile(t,e,r,n,o.width,o.height,-o.x,-o.y,2)};B.encode._filterZero=function(t,e,r,n,o,i,a){var s=[],f=[0,1,2,3,4];i!=-1?f=[i]:(e*n>5e5||r==1)&&(f=[0]);var l;a&&(l={level:0});for(var c=a&&UZIP!=null?UZIP:iu.default,u=0;u>1)+256&255;if(i==4)for(var l=o;l>1)&255;for(var l=o;l>1)&255}if(i==4){for(var l=0;l>>1:r=r>>>1;t[e]=r}return t}(),update:function(t,e,r,n){for(var o=0;o>>8;return t},crc:function(t,e,r){return B.crc.update(4294967295,t,e,r)^4294967295}};B.quantize=function(t,e){for(var r=new Uint8Array(t),n=r.slice(0),o=new Uint32Array(n.buffer),i=B.quantize.getKDtree(n,e),a=i[0],s=i[1],f=B.quantize.planeDst,l=r,c=o,u=l.length,d=new Uint8Array(r.length>>2),p=0;p>2]=m.ind,c[p>>2]=m.est.rgba}return{abuf:n.buffer,inds:d,plte:s}};B.quantize.getKDtree=function(t,e,r){r==null&&(r=1e-4);var n=new Uint32Array(t.buffer),o={i0:0,i1:t.length,bst:null,est:null,tdst:0,left:null,right:null};o.bst=B.quantize.stats(t,o.i0,o.i1),o.est=B.quantize.estats(o.bst);for(var i=[o];i.lengtha&&(a=i[f].est.L,s=f);if(a=c||l.i1<=c;if(u){l.est.L=0;continue}var d={i0:l.i0,i1:c,bst:null,est:null,tdst:0,left:null,right:null};d.bst=B.quantize.stats(t,d.i0,d.i1),d.est=B.quantize.estats(d.bst);var p={i0:c,i1:l.i1,bst:null,est:null,tdst:0,left:null,right:null};p.bst={R:[],m:[],N:l.bst.N-d.bst.N};for(var f=0;f<16;f++)p.bst.R[f]=l.bst.R[f]-d.bst.R[f];for(var f=0;f<4;f++)p.bst.m[f]=l.bst.m[f]-d.bst.m[f];p.est=B.quantize.estats(p.bst),l.left=d,l.right=p,i[s]=d,i.push(p)}i.sort(function(h,b){return b.bst.N-h.bst.N});for(var f=0;f0&&(a=t.right,s=t.left);var f=B.quantize.getNearest(a,e,r,n,o);if(f.tdst<=i*i)return f;var l=B.quantize.getNearest(s,e,r,n,o);return l.tdsti;)n-=4;if(r>=n)break;var f=e[r>>2];e[r>>2]=e[n>>2],e[n>>2]=f,r+=4,n-=4}for(;a(t,r,o)>i;)r-=4;return r+4};B.quantize.vecDot=function(t,e,r){return t[e]*r[0]+t[e+1]*r[1]+t[e+2]*r[2]+t[e+3]*r[3]};B.quantize.stats=function(t,e,r){for(var n=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],o=[0,0,0,0],i=r-e>>2,a=e;a>>0}};B.M4={multVec:function(t,e){return[t[0]*e[0]+t[1]*e[1]+t[2]*e[2]+t[3]*e[3],t[4]*e[0]+t[5]*e[1]+t[6]*e[2]+t[7]*e[3],t[8]*e[0]+t[9]*e[1]+t[10]*e[2]+t[11]*e[3],t[12]*e[0]+t[13]*e[1]+t[14]*e[2]+t[15]*e[3]]},dot:function(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]+t[3]*e[3]},sml:function(t,e){return[t*e[0],t*e[1],t*e[2],t*e[3]]}};B.encode.concatRGBA=function(t){for(var e=0,r=0;r1)throw new Error("Animated PNGs are not supported");var o=new Uint8Array(n[0]),i=Z0(o),a=i.rgbChannel,s=i.alphaChannel;this.rgbChannel=a;var f=s.some(function(l){return l<255});f&&(this.alphaChannel=s),this.type=X0(r.ctype),this.width=r.width,this.height=r.height,this.bitsPerComponent=8}return t.load=function(e){return new t(e)},t}();var Y0=function(){function t(e){this.image=e,this.bitsPerComponent=e.bitsPerComponent,this.width=e.width,this.height=e.height,this.colorSpace="DeviceRGB"}return t.for=function(e){return V(this,void 0,void 0,function(){var r;return q(this,function(n){return r=au.load(e),[2,new t(r)]})})},t.prototype.embedIntoContext=function(e,r){return V(this,void 0,void 0,function(){var n,o;return q(this,function(i){return n=this.embedAlphaChannel(e),o=e.flateStream(this.image.rgbChannel,{Type:"XObject",Subtype:"Image",BitsPerComponent:this.image.bitsPerComponent,Width:this.image.width,Height:this.image.height,ColorSpace:this.colorSpace,SMask:n}),r?(e.assign(r,o),[2,r]):[2,e.register(o)]})})},t.prototype.embedAlphaChannel=function(e){if(this.image.alphaChannel){var r=e.flateStream(this.image.alphaChannel,{Type:"XObject",Subtype:"Image",Height:this.image.height,Width:this.image.width,BitsPerComponent:this.image.bitsPerComponent,ColorSpace:"DeviceGray",Decode:[0,1]});return e.register(r)}},t}(),yo=Y0;var J0=function(){function t(e,r,n){this.bytes=e,this.start=r||0,this.pos=this.start,this.end=r&&n?r+n:this.bytes.length}return Object.defineProperty(t.prototype,"length",{get:function(){return this.end-this.start},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"isEmpty",{get:function(){return this.length===0},enumerable:!1,configurable:!0}),t.prototype.getByte=function(){return this.pos>=this.end?-1:this.bytes[this.pos++]},t.prototype.getUint16=function(){var e=this.getByte(),r=this.getByte();return e===-1||r===-1?-1:(e<<8)+r},t.prototype.getInt32=function(){var e=this.getByte(),r=this.getByte(),n=this.getByte(),o=this.getByte();return(e<<24)+(r<<16)+(n<<8)+o},t.prototype.getBytes=function(e,r){r===void 0&&(r=!1);var n=this.bytes,o=this.pos,i=this.end;if(e){var s=o+e;s>i&&(s=i),this.pos=s;var a=n.subarray(o,s);return r?new Uint8ClampedArray(a):a}else{var a=n.subarray(o,i);return r?new Uint8ClampedArray(a):a}},t.prototype.peekByte=function(){var e=this.getByte();return this.pos--,e},t.prototype.peekBytes=function(e,r){r===void 0&&(r=!1);var n=this.getBytes(e,r);return this.pos-=n.length,n},t.prototype.skip=function(e){e||(e=1),this.pos+=e},t.prototype.reset=function(){this.pos=this.start},t.prototype.moveStart=function(){this.start=this.pos},t.prototype.makeSubStream=function(e,r){return new t(this.bytes,e,r)},t.prototype.decode=function(){return this.bytes},t}(),Oi=J0;var Q0=new Uint8Array(0),_0=function(){function t(e){if(this.pos=0,this.bufferLength=0,this.eof=!1,this.buffer=Q0,this.minBufferLength=512,e)for(;this.minBufferLengthi&&(n=i)}else{for(;!this.eof;)this.readBlock();n=this.bufferLength}this.pos=n;var a=this.buffer.subarray(o,n);return r&&!(a instanceof Uint8ClampedArray)?new Uint8ClampedArray(a):a},t.prototype.peekByte=function(){var e=this.getByte();return this.pos--,e},t.prototype.peekBytes=function(e,r){r===void 0&&(r=!1);var n=this.getBytes(e,r);return this.pos-=n.length,n},t.prototype.skip=function(e){e||(e=1),this.pos+=e},t.prototype.reset=function(){this.pos=0},t.prototype.makeSubStream=function(e,r){for(var n=e+r;this.bufferLength<=n&&!this.eof;)this.readBlock();return new Oi(this.buffer,e,r)},t.prototype.decode=function(){for(;!this.eof;)this.readBlock();return this.buffer.subarray(0,this.bufferLength)},t.prototype.readBlock=function(){throw new He(this.constructor.name,"readBlock")},t.prototype.ensureBuffer=function(e){var r=this.buffer;if(e<=r.byteLength)return r;for(var n=this.minBufferLength;n=0;--l)f[s+l]=u&255,u>>=8}},e}(Rt),lu=$0;var ev=function(t){k(e,t);function e(r,n){var o=t.call(this,n)||this;return o.stream=r,o.firstDigit=-1,n&&(n=.5*n),o}return e.prototype.readBlock=function(){var r=8e3,n=this.stream.getBytes(r);if(!n.length){this.eof=!0;return}for(var o=n.length+1>>1,i=this.ensureBuffer(this.bufferLength+o),a=this.bufferLength,s=this.firstDigit,f=0,l=n.length;f=48&&c<=57)u=c&15;else if(c>=65&&c<=70||c>=97&&c<=102)u=(c&15)+9;else if(c===62){this.eof=!0;break}else continue;s<0?s=u:(i[a++]=s<<4|u,s=-1)}s>=0&&this.eof&&(i[a++]=s<<4,s=-1),this.firstDigit=s,this.bufferLength=a},e}(Rt),fu=ev;var cu=new Int32Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),tv=new Int32Array([3,4,5,6,7,8,9,10,65547,65549,65551,65553,131091,131095,131099,131103,196643,196651,196659,196667,262211,262227,262243,262259,327811,327843,327875,327907,258,258,258]),rv=new Int32Array([1,2,3,4,65541,65543,131081,131085,196625,196633,262177,262193,327745,327777,393345,393409,459009,459137,524801,525057,590849,591361,657409,658433,724993,727041,794625,798721,868353,876545]),nv=[new Int32Array([459008,524368,524304,524568,459024,524400,524336,590016,459016,524384,524320,589984,524288,524416,524352,590048,459012,524376,524312,589968,459028,524408,524344,590032,459020,524392,524328,59e4,524296,524424,524360,590064,459010,524372,524308,524572,459026,524404,524340,590024,459018,524388,524324,589992,524292,524420,524356,590056,459014,524380,524316,589976,459030,524412,524348,590040,459022,524396,524332,590008,524300,524428,524364,590072,459009,524370,524306,524570,459025,524402,524338,590020,459017,524386,524322,589988,524290,524418,524354,590052,459013,524378,524314,589972,459029,524410,524346,590036,459021,524394,524330,590004,524298,524426,524362,590068,459011,524374,524310,524574,459027,524406,524342,590028,459019,524390,524326,589996,524294,524422,524358,590060,459015,524382,524318,589980,459031,524414,524350,590044,459023,524398,524334,590012,524302,524430,524366,590076,459008,524369,524305,524569,459024,524401,524337,590018,459016,524385,524321,589986,524289,524417,524353,590050,459012,524377,524313,589970,459028,524409,524345,590034,459020,524393,524329,590002,524297,524425,524361,590066,459010,524373,524309,524573,459026,524405,524341,590026,459018,524389,524325,589994,524293,524421,524357,590058,459014,524381,524317,589978,459030,524413,524349,590042,459022,524397,524333,590010,524301,524429,524365,590074,459009,524371,524307,524571,459025,524403,524339,590022,459017,524387,524323,589990,524291,524419,524355,590054,459013,524379,524315,589974,459029,524411,524347,590038,459021,524395,524331,590006,524299,524427,524363,590070,459011,524375,524311,524575,459027,524407,524343,590030,459019,524391,524327,589998,524295,524423,524359,590062,459015,524383,524319,589982,459031,524415,524351,590046,459023,524399,524335,590014,524303,524431,524367,590078,459008,524368,524304,524568,459024,524400,524336,590017,459016,524384,524320,589985,524288,524416,524352,590049,459012,524376,524312,589969,459028,524408,524344,590033,459020,524392,524328,590001,524296,524424,524360,590065,459010,524372,524308,524572,459026,524404,524340,590025,459018,524388,524324,589993,524292,524420,524356,590057,459014,524380,524316,589977,459030,524412,524348,590041,459022,524396,524332,590009,524300,524428,524364,590073,459009,524370,524306,524570,459025,524402,524338,590021,459017,524386,524322,589989,524290,524418,524354,590053,459013,524378,524314,589973,459029,524410,524346,590037,459021,524394,524330,590005,524298,524426,524362,590069,459011,524374,524310,524574,459027,524406,524342,590029,459019,524390,524326,589997,524294,524422,524358,590061,459015,524382,524318,589981,459031,524414,524350,590045,459023,524398,524334,590013,524302,524430,524366,590077,459008,524369,524305,524569,459024,524401,524337,590019,459016,524385,524321,589987,524289,524417,524353,590051,459012,524377,524313,589971,459028,524409,524345,590035,459020,524393,524329,590003,524297,524425,524361,590067,459010,524373,524309,524573,459026,524405,524341,590027,459018,524389,524325,589995,524293,524421,524357,590059,459014,524381,524317,589979,459030,524413,524349,590043,459022,524397,524333,590011,524301,524429,524365,590075,459009,524371,524307,524571,459025,524403,524339,590023,459017,524387,524323,589991,524291,524419,524355,590055,459013,524379,524315,589975,459029,524411,524347,590039,459021,524395,524331,590007,524299,524427,524363,590071,459011,524375,524311,524575,459027,524407,524343,590031,459019,524391,524327,589999,524295,524423,524359,590063,459015,524383,524319,589983,459031,524415,524351,590047,459023,524399,524335,590015,524303,524431,524367,590079]),9],ov=[new Int32Array([327680,327696,327688,327704,327684,327700,327692,327708,327682,327698,327690,327706,327686,327702,327694,0,327681,327697,327689,327705,327685,327701,327693,327709,327683,327699,327691,327707,327687,327703,327695,0]),5],iv=function(t){k(e,t);function e(r,n){var o=t.call(this,n)||this;o.stream=r;var i=r.getByte(),a=r.getByte();if(i===-1||a===-1)throw new Error("Invalid header in flate stream: "+i+", "+a);if((i&15)!==8)throw new Error("Unknown compression method in flate stream: "+i+", "+a);if(((i<<8)+a)%31!==0)throw new Error("Bad FCHECK in flate stream: "+i+", "+a);if(a&32)throw new Error("FDICT bit set in flate stream: "+i+", "+a);return o.codeSize=0,o.codeBuf=0,o}return e.prototype.readBlock=function(){var r,n,o=this.stream,i=this.getBits(3);if(i&1&&(this.eof=!0),i>>=1,i===0){var a=void 0;if((a=o.getByte())===-1)throw new Error("Bad block header in flate stream");var s=a;if((a=o.getByte())===-1)throw new Error("Bad block header in flate stream");if(s|=a<<8,(a=o.getByte())===-1)throw new Error("Bad block header in flate stream");var f=a;if((a=o.getByte())===-1)throw new Error("Bad block header in flate stream");if(f|=a<<8,f!==(~s&65535)&&(s!==0||f!==0))throw new Error("Bad uncompressed block length in flate stream");this.codeBuf=0,this.codeSize=0;var l=this.bufferLength;r=this.ensureBuffer(l+s);var c=l+s;if(this.bufferLength=c,s===0)o.peekByte()===-1&&(this.eof=!0);else for(var u=l;u0;)S[m++]=C}d=this.generateHuffmanTable(S.subarray(0,h)),p=this.generateHuffmanTable(S.subarray(h,w))}else throw new Error("Unknown block type in flate stream");r=this.buffer;for(var A=r?r.length:0,R=this.bufferLength;;){var I=this.getCode(d);if(I<256){R+1>=A&&(r=this.ensureBuffer(R+1),A=r.length),r[R++]=I;continue}if(I===256){this.bufferLength=R;return}I-=257,I=tv[I];var N=I>>16;N>0&&(N=this.getBits(N)),n=(I&65535)+N,I=this.getCode(p),I=rv[I],N=I>>16,N>0&&(N=this.getBits(N));var X=(I&65535)+N;R+n>=A&&(r=this.ensureBuffer(R+n),A=r.length);for(var te=0;te>r,this.codeSize=o-=r,a},e.prototype.getCode=function(r){for(var n=this.stream,o=r[0],i=r[1],a=this.codeSize,s=this.codeBuf,f;a>16,u=l&65535;if(c<1||a>c,this.codeSize=a-c,u},e.prototype.generateHuffmanTable=function(r){var n=r.length,o=0,i;for(i=0;io&&(o=r[i]);for(var a=1<>=1;for(i=d;i0;if(!S||S<256)F[0]=S,x=1;else if(S>=258)if(S=0;a--)F[a]=u[s],s=p[s];else F[x++]=F[0];else if(S===256){h=9,c=258,x=0;continue}else{this.eof=!0,delete this.lzwState;break}if(D&&(p[c]=b,d[c]=d[b]+1,u[c]=F[0],c++,h=c+l&c+l-1?h:Math.min(Math.log(c+l)/.6931471805599453+1,12)|0),b=S,m+=x,n>>n&(1<0){var a=this.stream.getBytes(i);n.set(a,o),o+=i}}else{i=257-i;var s=r[1];n=this.ensureBuffer(o+i+1);for(var f=0;fn.size())throw new cn(r,0,n.size());n.remove(r)}else{if(r!==0)throw new cn(r,0,0);this.setKids([])}},e.prototype.normalizedEntries=function(){var r=this.Kids();return r||(r=this.dict.context.obj([this.ref]),this.dict.set(v.of("Kids"),r)),{Kids:r}},e.fromDict=function(r,n){return new e(r,n)},e}(wo),at=yv;var bv=function(t){k(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.Opt=function(){return this.dict.lookupMaybe(v.of("Opt"),ne,j,Z)},e.prototype.setOpt=function(r){this.dict.set(v.of("Opt"),this.dict.context.obj(r))},e.prototype.getExportValues=function(){var r=this.Opt();if(r){if(r instanceof ne||r instanceof j)return[r];for(var n=[],o=0,i=r.size();on.size())throw new cn(r,0,n.size());n.remove(r)}},e.prototype.normalizeExportValues=function(){for(var r,n,o,i,a=(r=this.getExportValues())!==null&&r!==void 0?r:[],s=[],f=this.getWidgets(),l=0,c=f.length;l1){if(!this.hasFlag(le.MultiSelect))throw new Ic;this.dict.set(v.of("V"),this.dict.context.obj(r))}this.updateSelectedIndices(r)},e.prototype.valuesAreValid=function(r){for(var n=this.getOptions(),o=function(f,l){var c=r[f].decodeText();if(!n.find(function(u){return c===(u.display||u.value).decodeText()}))return{value:!1}},i=0,a=r.length;i1){for(var n=new Array(r.length),o=this.getOptions(),i=function(f,l){var c=r[f].decodeText();n[f]=o.findIndex(function(u){return c===(u.display||u.value).decodeText()})},a=0,s=r.length;a0){var s=a.lookup(0,ne,j),f=a.lookupMaybe(1,ne,j);n.push({value:s,display:f||s})}}return n}return[]},e}(at),Po=Fv;var wv=function(t){k(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.fromDict=function(r,n){return new e(r,n)},e.create=function(r){var n=r.obj({FT:"Ch",Ff:le.Combo,Kids:[]}),o=r.register(n);return new e(n,o)},e}(Po),or=wv;var Sv=function(t){k(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.addField=function(r){var n=this.normalizedEntries().Kids;n?.push(r)},e.prototype.normalizedEntries=function(){var r=this.Kids();return r||(r=this.dict.context.obj([]),this.dict.set(v.of("Kids"),r)),{Kids:r}},e.fromDict=function(r,n){return new e(r,n)},e.create=function(r){var n=r.obj({}),o=r.register(n);return new e(n,o)},e}(wo),ir=Sv;var Pv=function(t){k(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.fromDict=function(r,n){return new e(r,n)},e}(at),jr=Pv;var Dv=function(t){k(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.MaxLen=function(){var r=this.dict.lookup(v.of("MaxLen"));if(r instanceof z)return r},e.prototype.Q=function(){var r=this.dict.lookup(v.of("Q"));if(r instanceof z)return r},e.prototype.setMaxLength=function(r){this.dict.set(v.of("MaxLen"),z.of(r))},e.prototype.removeMaxLength=function(){this.dict.delete(v.of("MaxLen"))},e.prototype.getMaxLength=function(){var r;return(r=this.MaxLen())===null||r===void 0?void 0:r.asNumber()},e.prototype.setQuadding=function(r){this.dict.set(v.of("Q"),z.of(r))},e.prototype.getQuadding=function(){var r;return(r=this.Q())===null||r===void 0?void 0:r.asNumber()},e.prototype.setValue=function(r){this.dict.set(v.of("V"),r)},e.prototype.removeValue=function(){this.dict.delete(v.of("V"))},e.prototype.getValue=function(){var r=this.V();if(r instanceof ne||r instanceof j)return r},e.fromDict=function(r,n){return new e(r,n)},e.create=function(r){var n=r.obj({FT:"Tx",Kids:[]}),o=r.register(n);return new e(n,o)},e}(at),ar=Dv;var Cv=function(t){k(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.fromDict=function(r,n){return new e(r,n)},e.create=function(r){var n=r.obj({FT:"Btn",Ff:We.PushButton,Kids:[]}),o=r.register(n);return new e(n,o)},e}(Lr),sr=Cv;var kv=function(t){k(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.setValue=function(r){var n=this.getOnValues();if(!n.includes(r)&&r!==v.of("Off"))throw new un;this.dict.set(v.of("V"),r);for(var o=this.getWidgets(),i=0,a=o.length;ii)throw new Za(n,i);for(var a=n,s=0,f=o.size();sa)return c.insertLeafNode(r,a)||l;a-=c.Count().asNumber()}c instanceof Ye&&(a-=1)}if(a===0){this.insertLeafKid(o.size(),r);return}throw new Ya(n,"insertLeafNode")},e.prototype.removeLeafNode=function(r,n){n===void 0&&(n=!0);var o=this.Kids(),i=this.Count().asNumber();if(r>=i)throw new Za(r,i);for(var a=r,s=0,f=o.size();sa){c.removeLeafNode(a,n),n&&c.Kids().size()===0&&o.remove(s);return}else a-=c.Count().asNumber();if(c instanceof Ye)if(a===0){this.removeKid(s);return}else a-=1}throw new Ya(r,"removeLeafNode")},e.prototype.ascend=function(r){r(this);var n=this.Parent();n&&n.ascend(r)},e.prototype.traverse=function(r){for(var n=this.Kids(),o=0,i=n.size();oNumber.MAX_SAFE_INTEGER)if(this.capNumbers){var o="Parsed number that is too large for some PDF readers: "+e+", using Number.MAX_SAFE_INTEGER instead.";return console.warn(o),Number.MAX_SAFE_INTEGER}else{var o="Parsed number that is too large for some PDF readers: "+e+", not capping.";console.warn(o)}return n},t.prototype.skipWhitespace=function(){for(;!this.bytes.done()&&ct[this.bytes.peek()];)this.bytes.next()},t.prototype.skipLine=function(){for(;!this.bytes.done();){var e=this.bytes.peek();if(e===gu||e===yu)return;this.bytes.next()}},t.prototype.skipComment=function(){if(this.bytes.peek()!==g.Percent)return!1;for(;!this.bytes.done();){var e=this.bytes.peek();if(e===gu||e===yu)return!0;this.bytes.next()}return!0},t.prototype.skipWhitespaceAndComments=function(){for(this.skipWhitespace();this.skipComment();)this.skipWhitespace()},t.prototype.matchKeyword=function(e){for(var r=this.bytes.offset(),n=0,o=e.length;n=this.length},t.prototype.offset=function(){return this.idx},t.prototype.slice=function(e,r){return this.bytes.slice(e,r)},t.prototype.position=function(){return{line:this.line,column:this.column,offset:this.idx}},t.of=function(e){return new t(e)},t.fromPDFRawStream=function(e){return t.of(bo(e).decode())},t}(),cr=zv;var Lv=g.Space,Eo=g.CarriageReturn,Ao=g.Newline,Ro=[g.s,g.t,g.r,g.e,g.a,g.m],zi=[g.e,g.n,g.d,g.s,g.t,g.r,g.e,g.a,g.m],pe={header:[g.Percent,g.P,g.D,g.F,g.Dash],eof:[g.Percent,g.Percent,g.E,g.O,g.F],obj:[g.o,g.b,g.j],endobj:[g.e,g.n,g.d,g.o,g.b,g.j],xref:[g.x,g.r,g.e,g.f],trailer:[g.t,g.r,g.a,g.i,g.l,g.e,g.r],startxref:[g.s,g.t,g.a,g.r,g.t,g.x,g.r,g.e,g.f],true:[g.t,g.r,g.u,g.e],false:[g.f,g.a,g.l,g.s,g.e],null:[g.n,g.u,g.l,g.l],stream:Ro,streamEOF1:re(Ro,[Lv,Eo,Ao]),streamEOF2:re(Ro,[Eo,Ao]),streamEOF3:re(Ro,[Eo]),streamEOF4:re(Ro,[Ao]),endstream:zi,EOF1endstream:re([Eo,Ao],zi),EOF2endstream:re([Eo],zi),EOF3endstream:re([Ao],zi)};var jv=function(t){k(e,t);function e(r,n,o){o===void 0&&(o=!1);var i=t.call(this,r,o)||this;return i.context=n,i}return e.prototype.parseObject=function(){if(this.skipWhitespaceAndComments(),this.matchKeyword(pe.true))return qt.True;if(this.matchKeyword(pe.false))return qt.False;if(this.matchKeyword(pe.null))return Te;var r=this.bytes.peek();if(r===g.LessThan&&this.bytes.peekAhead(1)===g.LessThan)return this.parseDictOrStream();if(r===g.LessThan)return this.parseHexString();if(r===g.LeftParen)return this.parseString();if(r===g.ForwardSlash)return this.parseName();if(r===g.LeftSquareBracket)return this.parseArray();if(To[r])return this.parseNumberOrRef();throw new Hc(this.bytes.position(),r)},e.prototype.parseNumberOrRef=function(){var r=this.parseRawNumber();this.skipWhitespaceAndComments();var n=this.bytes.offset();if(Ie[this.bytes.peek()]){var o=this.parseRawNumber();if(this.skipWhitespaceAndComments(),this.bytes.peek()===g.R)return this.bytes.assertNext(g.R),J.of(r,o)}return this.bytes.moveTo(n),z.of(r)},e.prototype.parseHexString=function(){var r="";for(this.bytes.assertNext(g.LessThan);!this.bytes.done()&&this.bytes.peek()!==g.GreaterThan;)r+=rt(this.bytes.next());return this.bytes.assertNext(g.GreaterThan),j.of(r)},e.prototype.parseString=function(){for(var r=0,n=!1,o="";!this.bytes.done();){var i=this.bytes.next();if(o+=rt(i),n||(i===g.LeftParen&&(r+=1),i===g.RightParen&&(r-=1)),i===g.BackSlash?n=!n:n&&(n=!1),r===0)return ne.of(o.substring(1,o.length-1))}throw new qc(this.bytes.position())},e.prototype.parseName=function(){this.bytes.assertNext(g.ForwardSlash);for(var r="";!this.bytes.done();){var n=this.bytes.peek();if(ct[n]||tt[n])break;r+=rt(n),this.bytes.next()}return v.of(r)},e.prototype.parseArray=function(){this.bytes.assertNext(g.LeftSquareBracket),this.skipWhitespaceAndComments();for(var r=Z.withContext(this.context);this.bytes.peek()!==g.RightSquareBracket;){var n=this.parseObject();r.push(n),this.skipWhitespaceAndComments()}return this.bytes.assertNext(g.RightSquareBracket),r},e.prototype.parseDict=function(){this.bytes.assertNext(g.LessThan),this.bytes.assertNext(g.LessThan),this.skipWhitespaceAndComments();for(var r=new Map;!this.bytes.done()&&this.bytes.peek()!==g.GreaterThan&&this.bytes.peekAhead(1)!==g.GreaterThan;){var n=this.parseName(),o=this.parseObject();r.set(n,o),this.skipWhitespaceAndComments()}this.skipWhitespaceAndComments(),this.bytes.assertNext(g.GreaterThan),this.bytes.assertNext(g.GreaterThan);var i=r.get(v.of("Type"));return i===v.of("Catalog")?Co.fromMapWithContext(r,this.context):i===v.of("Pages")?ko.fromMapWithContext(r,this.context):i===v.of("Page")?Ye.fromMapWithContext(r,this.context):H.fromMapWithContext(r,this.context)},e.prototype.parseDictOrStream=function(){var r=this.bytes.position(),n=this.parseDict();if(this.skipWhitespaceAndComments(),!this.matchKeyword(pe.streamEOF1)&&!this.matchKeyword(pe.streamEOF2)&&!this.matchKeyword(pe.streamEOF3)&&!this.matchKeyword(pe.streamEOF4)&&!this.matchKeyword(pe.stream))return n;var o=this.bytes.offset(),i,a=n.get(v.of("Length"));a instanceof z?(i=o+a.asNumber(),this.bytes.moveTo(i),this.skipWhitespaceAndComments(),this.matchKeyword(pe.endstream)||(this.bytes.moveTo(o),i=this.findEndOfStreamFallback(r))):i=this.findEndOfStreamFallback(r);var s=this.bytes.slice(o,i);return At.of(n,s)},e.prototype.findEndOfStreamFallback=function(r){for(var n=1,o=this.bytes.offset();!this.bytes.done()&&(o=this.bytes.offset(),this.matchKeyword(pe.stream)?n+=1:this.matchKeyword(pe.EOF1endstream)||this.matchKeyword(pe.EOF2endstream)||this.matchKeyword(pe.EOF3endstream)||this.matchKeyword(pe.endstream)?n-=1:this.bytes.next(),n!==0););if(n!==0)throw new Vc(r);return o},e.forBytes=function(r,n,o){return new e(cr.of(r),n,o)},e.forByteStream=function(r,n,o){return o===void 0&&(o=!1),new e(r,n,o)},e}(bu),Oo=jv;var Hv=function(t){k(e,t);function e(r,n){var o=t.call(this,cr.fromPDFRawStream(r),r.dict.context)||this,i=r.dict;return o.alreadyParsed=!1,o.shouldWaitForTick=n||function(){return!1},o.firstOffset=i.lookup(v.of("First"),z).asNumber(),o.objectCount=i.lookup(v.of("N"),z).asNumber(),o}return e.prototype.parseIntoContext=function(){return V(this,void 0,void 0,function(){var r,n,o,i,a,s,f,l;return q(this,function(c){switch(c.label){case 0:if(this.alreadyParsed)throw new fn("PDFObjectStreamParser","parseIntoContext");this.alreadyParsed=!0,r=this.parseOffsetsAndObjectNumbers(),n=0,o=r.length,c.label=1;case 1:return n=g.Space&&n<=g.Tilde;if(o&&(this.matchKeyword(pe.xref)||this.matchKeyword(pe.trailer)||this.matchKeyword(pe.startxref)||this.matchIndirectObjectHeader())){this.bytes.moveTo(r);break}this.bytes.next()}},e.prototype.skipBinaryHeaderComment=function(){this.skipWhitespaceAndComments();try{var r=this.bytes.offset();this.parseIndirectObjectHeader(),this.bytes.moveTo(r)}catch{this.bytes.next(),this.skipWhitespaceAndComments()}},e.forBytesWithOptions=function(r,n,o,i){return new e(r,n,o,i)},e}(Oo),ds=Vv;var Ot=function(t){return 1<0&&(n[n.length]=+o),r[r.length]={cmd:e,args:n},n=[],o="",i=!1),e=l;else if([" ",","].includes(l)||l==="-"&&o.length>0&&o[o.length-1]!=="e"||l==="."&&i){if(o.length===0)continue;n.length===a?(r[r.length]={cmd:e,args:n},n=[+o],e==="M"&&(e="L"),e==="m"&&(e="l")):n[n.length]=+o,i=l===".",o=["-","."].includes(l)?l:""}else o+=l,l==="."&&(i=!0)}return o.length>0&&(n.length===a?(r[r.length]={cmd:e,args:n},n=[+o],e==="M"&&(e="L"),e==="m"&&(e="l")):n[n.length]=+o),r[r.length]={cmd:e,args:n},r},Kv=function(t){G=K=fe=ce=Uo=Vo=0;for(var e=[],r=0;r1&&(d=Math.sqrt(d),r*=d,n*=d);var p=u/r,h=c/r,b=-c/n,F=u/n,x=p*s+h*f,m=b*s+F*f,y=p*t+h*e,w=b*t+F*e,S=(y-x)*(y-x)+(w-m)*(w-m),D=1/S-.25;D<0&&(D=0);var T=Math.sqrt(D);i===o&&(T=-T);var C=.5*(x+y)-T*(w-m),E=.5*(m+w)+T*(y-x),M=Math.atan2(m-E,x-C),A=Math.atan2(w-E,y-C),R=A-M;R<0&&i===1?R+=2*Math.PI:R>0&&i===0&&(R-=2*Math.PI);for(var I=Math.ceil(Math.abs(R/(Math.PI*.5+.001))),N=[],X=0;Xt.length)return o-1;var F=e.heightAtSize(o),x=F+F*.2,m=x*i;if(m>Math.abs(r.height))return o-1;o+=1}return o},_v=function(t,e,r,n){for(var o=r.width/n,i=r.height,a=_u,s=nl(t);a<$u;){for(var f=0,l=s.length;fo*.75;if(u)return a-1}var d=e.heightAtSize(a,{descender:!1});if(d>i)return a-1;a+=1}return a},$v=function(t){for(var e=t.length;e>0;e--)if(/\s/.test(t[e]))return e},em=function(t,e,r,n){for(var o,i=t.length;i>0;){var a=t.substring(0,i),s=r.encodeText(a),f=r.widthOfTextAtSize(a,n);if(fd&&(d=T+S),h+s>p&&(p=h+s),l.push({text:y,encoded:w,width:S,height:s,x:T,y:h}),x=D?.trim()}return{fontSize:n,lineHeight:f,lines:l,bounds:{x:c,y:u,width:d-c,height:p-u}}},td=function(t,e){var r=e.fontSize,n=e.font,o=e.bounds,i=e.cellCount,a=sa(br(t));if(a.length>i)throw new Yu(a.length,i);(r===void 0||r===0)&&(r=_v(a,n,o,i));for(var s=o.width/i,f=n.heightAtSize(r,{descender:!1}),l=o.y+(o.height/2-f/2),c=[],u=o.x,d=o.y,p=o.x+o.width,h=o.y+o.height,b=0,F=0;bp&&(p=T+S),l+f>h&&(h=l+f),c.push({text:a,encoded:w,width:S,height:f,x:T,y:l}),b+=1,F+=y}return{fontSize:r,cells:c,bounds:{x:u,y:d,width:p-u,height:h-d}}},Go=function(t,e){var r=e.alignment,n=e.fontSize,o=e.font,i=e.bounds,a=sa(br(t));(n===void 0||n===0)&&(n=ed([a],o,i));var s=o.encodeText(a),f=o.widthOfTextAtSize(a,n),l=o.heightAtSize(n,{descender:!1}),c=r===De.Left?i.x:r===De.Center?i.x+i.width/2-f/2:r===De.Right?i.x+i.width-f:i.x,u=i.y+(i.height/2-l/2);return{fontSize:n,line:{text:a,encoded:s,width:f,height:l,x:c,y:u},bounds:{x:c,y:u,width:f,height:l}}};var vt=function(t){return"normal"in t?t:{normal:t}},tm=/\/([^\0\t\n\f\r\ ]+)[\0\t\n\f\r\ ]+(\d*\.\d+|\d+)[\0\t\n\f\r\ ]+Tf/,pr=function(t){var e,r,n=(e=t.getDefaultAppearance())!==null&&e!==void 0?e:"",o=(r=jn(n,tm).match)!==null&&r!==void 0?r:[],i=Number(o[2]);return isFinite(i)?i:void 0},rm=/(\d*\.\d+|\d+)[\0\t\n\f\r\ ]*(\d*\.\d+|\d+)?[\0\t\n\f\r\ ]*(\d*\.\d+|\d+)?[\0\t\n\f\r\ ]*(\d*\.\d+|\d+)?[\0\t\n\f\r\ ]+(g|rg|k)/,ht=function(t){var e,r=(e=t.getDefaultAppearance())!==null&&e!==void 0?e:"",n=jn(r,rm).match,o=n??[],i=o[1],a=o[2],s=o[3],f=o[4],l=o[5];if(l==="g"&&i)return ws(Number(i));if(l==="rg"&&i&&a&&s)return ae(Number(i),Number(a),Number(s));if(l==="k"&&i&&a&&s&&f)return Ss(Number(i),Number(a),Number(s),Number(f))},pt=function(t,e,r,n){var o;n===void 0&&(n=0);var i=[Nt(e).toString(),jo((o=r?.name)!==null&&o!==void 0?o:"dummy__noop",n).toString()].join(` +`);t.setDefaultAppearance(i)},rd=function(t,e){var r,n,o,i=ht(e),a=ht(t.acroField),s=e.getRectangle(),f=e.getAppearanceCharacteristics(),l=e.getBorderStyle(),c=(r=l?.getWidth())!==null&&r!==void 0?r:0,u=xt(f?.getRotation()),d=Gt(s,u),p=d.width,h=d.height,b=Ft(Y(Y({},s),{rotation:u})),F=ae(0,0,0),x=(n=Ge(f?.getBorderColor()))!==null&&n!==void 0?n:F,m=Ge(f?.getBackgroundColor()),y=Ge(f?.getBackgroundColor(),.8),w=(o=i??a)!==null&&o!==void 0?o:F;pt(i?e:t.acroField,w);var S={x:0+c/2,y:0+c/2,width:p-c,height:h-c,thickness:1.5,borderWidth:c,borderColor:x,markColor:w};return{normal:{on:re(b,qo(Y(Y({},S),{color:m,filled:!0}))),off:re(b,qo(Y(Y({},S),{color:m,filled:!1})))},down:{on:re(b,qo(Y(Y({},S),{color:y,filled:!0}))),off:re(b,qo(Y(Y({},S),{color:y,filled:!1})))}}},nd=function(t,e){var r,n,o,i=ht(e),a=ht(t.acroField),s=e.getRectangle(),f=e.getAppearanceCharacteristics(),l=e.getBorderStyle(),c=(r=l?.getWidth())!==null&&r!==void 0?r:0,u=xt(f?.getRotation()),d=Gt(s,u),p=d.width,h=d.height,b=Ft(Y(Y({},s),{rotation:u})),F=ae(0,0,0),x=(n=Ge(f?.getBorderColor()))!==null&&n!==void 0?n:F,m=Ge(f?.getBackgroundColor()),y=Ge(f?.getBackgroundColor(),.8),w=(o=i??a)!==null&&o!==void 0?o:F;pt(i?e:t.acroField,w);var S={x:p/2,y:h/2,width:p-c,height:h-c,borderWidth:c,borderColor:x,dotColor:w};return{normal:{on:re(b,Wo(Y(Y({},S),{color:m,filled:!0}))),off:re(b,Wo(Y(Y({},S),{color:m,filled:!1})))},down:{on:re(b,Wo(Y(Y({},S),{color:y,filled:!0}))),off:re(b,Wo(Y(Y({},S),{color:y,filled:!1})))}}},od=function(t,e,r){var n,o,i,a,s,f=ht(e),l=ht(t.acroField),c=pr(e),u=pr(t.acroField),d=e.getRectangle(),p=e.getAppearanceCharacteristics(),h=e.getBorderStyle(),b=p?.getCaptions(),F=(n=b?.normal)!==null&&n!==void 0?n:"",x=(i=(o=b?.down)!==null&&o!==void 0?o:F)!==null&&i!==void 0?i:"",m=(a=h?.getWidth())!==null&&a!==void 0?a:0,y=xt(p?.getRotation()),w=Gt(d,y),S=w.width,D=w.height,T=Ft(Y(Y({},d),{rotation:y})),C=ae(0,0,0),E=Ge(p?.getBorderColor()),M=Ge(p?.getBackgroundColor()),A=Ge(p?.getBackgroundColor(),.8),R={x:m,y:m,width:S-m*2,height:D-m*2},I=Go(F,{alignment:De.Center,fontSize:c??u,font:r,bounds:R}),N=Go(x,{alignment:De.Center,fontSize:c??u,font:r,bounds:R}),X=Math.min(I.fontSize,N.fontSize),te=(s=f??l)!==null&&s!==void 0?s:C;pt(f||c!==void 0?e:t.acroField,te,r,X);var L={x:0+m/2,y:0+m/2,width:S-m,height:D-m,borderWidth:m,borderColor:E,textColor:te,font:r.name,fontSize:X};return{normal:re(T,Ts(Y(Y({},L),{color:M,textLines:[I.line]}))),down:re(T,Ts(Y(Y({},L),{color:A,textLines:[N.line]})))}},id=function(t,e,r){var n,o,i,a,s=ht(e),f=ht(t.acroField),l=pr(e),c=pr(t.acroField),u=e.getRectangle(),d=e.getAppearanceCharacteristics(),p=e.getBorderStyle(),h=(n=t.getText())!==null&&n!==void 0?n:"",b=(o=p?.getWidth())!==null&&o!==void 0?o:0,F=xt(d?.getRotation()),x=Gt(u,F),m=x.width,y=x.height,w=Ft(Y(Y({},u),{rotation:F})),S=ae(0,0,0),D=Ge(d?.getBorderColor()),T=Ge(d?.getBackgroundColor()),C,E,M=t.isCombed()?0:1,A={x:b+M,y:b+M,width:m-(b+M)*2,height:y-(b+M)*2};if(t.isMultiline()){var R=Os(h,{alignment:t.getAlignment(),fontSize:l??c,font:r,bounds:A});C=R.lines,E=R.fontSize}else if(t.isCombed()){var R=td(h,{fontSize:l??c,font:r,bounds:A,cellCount:(i=t.getMaxLength())!==null&&i!==void 0?i:0});C=R.cells,E=R.fontSize}else{var R=Go(h,{alignment:t.getAlignment(),fontSize:l??c,font:r,bounds:A});C=[R.line],E=R.fontSize}var I=(a=s??f)!==null&&a!==void 0?a:S;pt(s||l!==void 0?e:t.acroField,I,r,E);var N={x:0+b/2,y:0+b/2,width:m-b,height:y-b,borderWidth:b??0,borderColor:D,textColor:I,font:r.name,fontSize:E,color:T,textLines:C,padding:M};return re(w,As(N))},ad=function(t,e,r){var n,o,i,a=ht(e),s=ht(t.acroField),f=pr(e),l=pr(t.acroField),c=e.getRectangle(),u=e.getAppearanceCharacteristics(),d=e.getBorderStyle(),p=(n=t.getSelected()[0])!==null&&n!==void 0?n:"",h=(o=d?.getWidth())!==null&&o!==void 0?o:0,b=xt(u?.getRotation()),F=Gt(c,b),x=F.width,m=F.height,y=Ft(Y(Y({},c),{rotation:b})),w=ae(0,0,0),S=Ge(u?.getBorderColor()),D=Ge(u?.getBackgroundColor()),T=1,C={x:h+T,y:h+T,width:x-(h+T)*2,height:m-(h+T)*2},E=Go(p,{alignment:De.Left,fontSize:f??l,font:r,bounds:C}),M=E.line,A=E.fontSize,R=(i=a??s)!==null&&i!==void 0?i:w;pt(a||f!==void 0?e:t.acroField,R,r,A);var I={x:0+h/2,y:0+h/2,width:x-h,height:m-h,borderWidth:h??0,borderColor:S,textColor:R,font:r.name,fontSize:A,color:D,textLines:[M],padding:T};return re(y,As(I))},sd=function(t,e,r){var n,o,i=ht(e),a=ht(t.acroField),s=pr(e),f=pr(t.acroField),l=e.getRectangle(),c=e.getAppearanceCharacteristics(),u=e.getBorderStyle(),d=(n=u?.getWidth())!==null&&n!==void 0?n:0,p=xt(c?.getRotation()),h=Gt(l,p),b=h.width,F=h.height,x=Ft(Y(Y({},l),{rotation:p})),m=ae(0,0,0),y=Ge(c?.getBorderColor()),w=Ge(c?.getBackgroundColor()),S=t.getOptions(),D=t.getSelected();t.isSorted()&&S.sort();for(var T="",C=0,E=S.length;C1||o.length===1&&n)&&this.enableMultiselect();for(var s=new Array(o.length),f=0,l=o.length;f1||o.length===1&&n)&&this.enableMultiselect();for(var a=new Array(o.length),s=0,f=o.length;sn)throw new Ju(r.length,n,this.getName());this.markAsDirty(),this.disableRichFormatting(),r?this.acroField.setValue(j.fromText(r)):this.acroField.removeValue()},e.prototype.getAlignment=function(){var r=this.acroField.getQuadding();return r===0?De.Left:r===1?De.Center:r===2?De.Right:De.Left},e.prototype.setAlignment=function(r){bt(r,"alignment",De),this.markAsDirty(),this.acroField.setQuadding(r)},e.prototype.getMaxLength=function(){return this.acroField.getMaxLength()},e.prototype.setMaxLength=function(r){if(it(r,"maxLength",0,Number.MAX_SAFE_INTEGER),this.markAsDirty(),r===void 0)this.acroField.removeMaxLength();else{var n=this.getText();if(n&&n.length>r)throw new Qu(n.length,r,this.getName());this.acroField.setMaxLength(r)}},e.prototype.removeMaxLength=function(){this.markAsDirty(),this.acroField.removeMaxLength()},e.prototype.setImage=function(r){for(var n=this.getAlignment(),o=n===De.Center?wt.Center:n===De.Right?wt.Right:wt.Left,i=this.acroField.getWidgets(),a=0,s=i.length;aDm([...t,n],e)<=r-Pm}function km(t){let e=activeDocument.createTreeWalker(t,NodeFilter.SHOW_TEXT);for(;e.nextNode();){let r=e.currentNode,n=(r.textContent??"").replace(/^\s+/,"");if(n!==r.textContent&&(r.textContent=n),n.length>0)break}}function Zo(t,e,r=!0){let n=activeDocument.createTreeWalker(t,NodeFilter.SHOW_TEXT),o=0,i=null,a=0;for(;n.nextNode();){let u=n.currentNode,d=u.textContent?.length??0;if(o+d>=e){i=u,a=e-o;break}o+=d}if(!i)return null;let s=activeDocument.createRange();s.selectNodeContents(t),s.setEnd(i,a);let f=activeDocument.createRange();f.selectNodeContents(t),f.setStart(i,a);let l=t.cloneNode(!1);l.appendChild(s.cloneContents());let c=t.cloneNode(!1);return c.appendChild(f.cloneContents()),r&&km(c),[l,c]}function Tm(t){let e=[],r=/\s+/g,n;for(;n=r.exec(t);)n.index>0&&n.index0){let f=0,l=o.length-1,c=-1;for(;f<=l;){let u=Math.floor((f+l)/2),d=Zo(t,o[u]);if(!d){l=u-1;continue}e(d[0])?(c=u,f=u+1):l=u-1}if(c>=0)return Zo(t,o[c]);if(!r)return null}let i=1,a=n.length-1,s=0;for(;i<=a;){let f=Math.floor((i+a)/2),l=Zo(t,f);if(!l){a=f-1;continue}e(l[0])?(s=f,i=f+1):a=f-1}return s>0?Zo(t,s):null}function Ms(t,e,r){let n=t.cloneNode(!1);t.tagName==="OL"&&r!==void 0&&r>1&&(n.start=r);for(let o of e)n.appendChild(o.cloneNode(!0));return n}function Am(t,e,r){let n=Array.from(t.children).filter(a=>a.tagName==="LI");if(n.length===0)return null;let o=t.tagName==="OL"?t.start??1:1,i=0;for(let a=0;a=n.length?null:[Ms(t,n.slice(0,i),o),Ms(t,n.slice(i),o+i)]}function Is(t,e){let r=t.cloneNode(!1),n=t.querySelector("caption");n&&r.appendChild(n.cloneNode(!0));let o=t.querySelector("colgroup");o&&r.appendChild(o.cloneNode(!0)),t.tHead&&r.appendChild(t.tHead.cloneNode(!0));let i=activeDocument.createElement("tbody");for(let a of e)i.appendChild(a.cloneNode(!0));return r.appendChild(i),r}function Rm(t,e,r){let n=t.tBodies[0],o=n?Array.from(n.rows):Array.from(t.rows).filter(a=>a.parentElement?.tagName!=="THEAD");if(o.length===0)return null;let i=0;for(let a=0;a=o.length?null:[Is(t,o.slice(0,i)),Is(t,o.slice(i))]}function Om(t){let e=[],r=0;for(let n of t)r+=n.length+1,e.push(r);return e}function Bm(t,e,r){let n=t.querySelector("code"),o=(n??t).textContent?.split(` +`)??[];if(o.length>1&&o[o.length-1]===""&&o.pop(),o.length<2)return null;let i=Om(o),a=l=>{if(!n){let p=h=>{let b=t.cloneNode(!1);return b.textContent=h,b};return[p(o.slice(0,l).join(` `)),p(o.slice(l).join(` -`))]}let c=Uo(n,i[l-1],!1);if(!c)return null;let u=t.cloneNode(!1);u.appendChild(c[0]);let d=t.cloneNode(!1);return d.appendChild(c[1]),[u,d]},s=null,f=0;for(let l=1;l<=o.length;l++){let c=a(l);if(!c||!e(c[0]))break;s=c,f=l}if(f<=0){if(!r)return null;s=a(1),f=1}return f>=o.length||!s?null:s}function Cm(t){if(!hm.has(t.tagName))return!1;for(let e of Array.from(t.childNodes))if(e.nodeType===Node.ELEMENT_NODE&&pm.has(e.tagName))return!1;return!0}function km(t,e,r){return vm.has(t.tagName)?null:t.tagName==="PRE"?Dm(t,e,r):t.tagName==="TABLE"?Sm(t,e,r):t.tagName==="UL"||t.tagName==="OL"?wm(t,e,r):Cm(t)?Fm(t,e,r):null}function Tm(t,e,r,n){let o=activeDocument.createElement("div");o.setCssStyles({position:"fixed",top:"0",left:"-99999px",width:`${e}px`,visibility:"hidden",pointerEvents:"none",zIndex:"-1"});let i=o.attachShadow({mode:"open"}),a=new CSSStyleSheet;a.replaceSync(n),i.adoptedStyleSheets=[a];let s=activeDocument.createElement("div");s.className="mpdf-doc";for(let c of Array.from(t.children))s.appendChild(c.cloneNode(!0));i.appendChild(s);let f=activeDocument.createElement("div");f.className="mpdf-doc",f.setCssStyles({position:"absolute",top:"0",left:"0",width:`${e}px`,visibility:"hidden"}),i.appendChild(f),activeDocument.body.appendChild(o);let l=[];try{let c=[],u=Array.from(s.children),d=0;for(;d0?u[d]=x:d++;continue}if(c.length>0){l.push(c),c=[];continue}c.push(p.cloneNode(!0)),l.push(c),c=[],d++}c.length>0&&l.push(c)}finally{activeDocument.body.removeChild(o)}return l.length>0?l:[[]]}function Em(t,e,r){return(t&&t.trim()?t:"{{current}} / {{total}}").replace(/\{\{\s*current\s*\}\}/g,String(e)).replace(/\{\{\s*total\s*\}\}/g,String(r))}function Am(t,e){let r=t.length;return t.map((n,o)=>{let i=o+1,a=e.showHeaderOnFirstPage||o>0,s=e.showFooterOnFirstPage||o>0,f=e.showFooterOnFirstPage?e.pageNumberStart+o:e.pageNumberStart+(o-1),l=e.showFooterOnFirstPage?e.pageNumberStart+r-1:e.pageNumberStart+r-2,c=Em(e.pageNumberFormat,f,l),u="",d="",p="",h="",b="",F="";if(s&&(e.footerText&&(e.footerTextAlignment==="center"?p=e.footerText:e.footerTextAlignment==="left"?u=e.footerText:d=e.footerText),e.showPageNumbers)){let y=w=>w?w+" \u2014 "+c:c;e.pageNumberPosition==="center"?p=y(p):e.pageNumberPosition==="left"?u=y(u):d=y(d)}a&&e.headerText&&(e.headerAlignment==="center"?b=e.headerText:e.headerAlignment==="left"?h=e.headerText:F=e.headerText);let x=e.showHeader&&a&&!!(h||b||F||e.showHeaderBorder),m=e.showFooter&&s&&!!(u||d||p||e.showFooterBorder);return{pageNodes:n,pageNum:i,totalPages:r,pageShowsHeader:a,pageShowsFooter:s,hasHeader:x,hasFooter:m,headerLeft:h,headerCenter:b,headerRight:F,footerLeft:u,footerRight:d,footerCenter:p}})}function Rm(t){let e=[];for(let r of t)for(let n of r.pageNodes){let o=/^H[1-6]$/.test(n.tagName)?[n]:[],i=Array.from(n.querySelectorAll("h1,h2,h3,h4,h5,h6"));for(let a of[...o,...i]){let s=parseInt(a.tagName[1],10),f=(a.textContent??"").trim();f&&e.push({title:f,level:s,page:r.pageNum})}}return e}async function Om(t,e){if(!e.length)return t;let r=await Ge.load(t),n=r.getPages(),o=r.context,i=e.length,a=new Array(i).fill(-1);for(let m=1;m=0;y--)if(e[y].level=0;y--)if(a[y]===a[m]){s[m]=y;break}for(let y=m+1;y=0&&(l[y]<0&&(l[y]=m),c[y]=m,u[y]++)}let d=o.nextRef(),p=e.map(()=>o.nextRef());for(let m=0;m=0?p[a[m]]:d),S.set(v.of("Dest"),w),s[m]>=0&&S.set(v.of("Prev"),p[s[m]]),f[m]>=0&&S.set(v.of("Next"),p[f[m]]),l[m]>=0&&(S.set(v.of("First"),p[l[m]]),S.set(v.of("Last"),p[c[m]]),S.set(v.of("Count"),j.of(-u[m]))),o.assign(p[m],S)}let h=-1,b=-1,F=0;for(let m=0;m`}function Yu(t,e,r,n){if(!(!e&&!r&&!n))if(e){let o=activeDocument.createElement("span");o.className="mpdf-hf-center",o.textContent=e,t.appendChild(o)}else{let o=activeDocument.createElement("span");o.textContent=r,t.appendChild(o);let i=activeDocument.createElement("span");i.className="mpdf-hf-right",i.textContent=n,t.appendChild(i)}}function Ju(t,e,r){return!t&&!e&&!r?"":t?`${Ui(t)}`:`${Ui(e)}${Ui(r)}`}var Wi=class extends N.Plugin{activeModal=null;presetSnapshots={};async onload(){await this.loadSettings(),$v(this.app),this.addCommand({id:"open-panel",name:"Open Panel",callback:()=>this.openModal()}),this.registerEvent(this.app.workspace.on("file-menu",(e,r)=>{!(r instanceof N.TFile)||r.extension!=="md"||e.addItem(n=>n.setTitle("Advanced PDF Export: Open Panel").setIcon("file-output").onClick(()=>this.openModal(r)))})),this.addSettingTab(new Ts(this.app,this))}onunload(){this.activeModal?.close()}openModal(e){this.activeModal&&this.activeModal.close(),new ks(this.app,this,e).open()}async loadSettings(){let e=await this.loadData()??{};this.settings=Object.assign({},ws,e),e.codeTheme===void 0&&(this.settings.codeTheme=Tn[this.settings.preset]?.codeTheme??ws.codeTheme),this.presetSnapshots=e.presetSnapshots??{},this.validateSettings()}validateSettings(){let e=this.settings;e.preset in Tn||(console.warn(`[advanced-pdf-export] Unknown preset "${e.preset}", resetting to "default".`),e.preset="default"),e.fontSize=Math.max(1,e.fontSize),e.headerFontSize=Math.max(1,e.headerFontSize),e.footerFontSize=Math.max(1,e.footerFontSize),e.marginTop=Math.max(0,e.marginTop),e.marginBottom=Math.max(0,e.marginBottom),e.marginLeft=Math.max(0,e.marginLeft),e.marginRight=Math.max(0,e.marginRight),e.customPageWidth=Math.max(10,e.customPageWidth),e.customPageHeight=Math.max(10,e.customPageHeight),e.previewScale=Math.max(.1,Math.min(3,e.previewScale)),e.pageNumberStart=Math.max(1,e.pageNumberStart),(!e.pageNumberFormat||!e.pageNumberFormat.trim())&&(e.pageNumberFormat=ws.pageNumberFormat)}async saveSettings(){await this.saveData({...this.settings,presetSnapshots:this.presetSnapshots})}async saveSettingsAndRender(){await this.saveSettings(),this.activeModal?.render()}applyPreset(e,r=!1){let n=Tn[e];n&&(r?delete this.presetSnapshots[e]:this.presetSnapshots[this.settings.preset]=cm(this.settings),this.settings.preset=e,Object.assign(this.settings,n,r?{}:this.presetSnapshots[e]??{}))}};function Mm(t,e){if(e)return e;let r=t.workspace.getActiveFile();if(r?.extension==="md")return r;let n=t.workspace.getMostRecentLeaf();return n?.view instanceof N.MarkdownView?n.view.file??null:null}var ks=class t extends N.Modal{plugin;editorEl;previewEl;pageCountEl;noteTitleEl;renderBtn;exportBtn;loadingOverlayEl;renderComponent=new N.Component;initialFile;currentFile=null;renderToken=0;layoutCache=null;renderDebounceTimer=null;constructor(e,r,n){super(e),this.plugin=r,this.initialFile=n??null}async onOpen(){this.plugin.activeModal=this,this.renderComponent.load(),this.modalEl.addClass("mpdf-modal"),this.buildUI(this.contentEl);let e=Mm(this.app,this.initialFile);if(e){let r;try{r=await this.app.vault.read(e)}catch(n){let o=n instanceof Error?n.message:String(n);new N.Notice(`Failed to read file "${e.basename}": ${o}`);return}if(!this.plugin.activeModal)return;this.currentFile=e,this.editorEl.value=r,this.noteTitleEl.textContent=e.basename,this.noteTitleEl.title=e.path,this.render(!0)}}onClose(){this.renderDebounceTimer!==null&&(window.clearTimeout(this.renderDebounceTimer),this.renderDebounceTimer=null),this.renderComponent.unload(),this.plugin.activeModal=null,this.currentFile=null,this.layoutCache=null}buildUI(e){let r=this.plugin.settings;this.buildTopbar(e.createEl("div",{cls:"mpdf-topbar"}),r);let n=e.createEl("div",{cls:"mpdf-main"}),o=n.createEl("div",{cls:"mpdf-editor-panel"});this.editorEl=o.createEl("textarea",{cls:"mpdf-editor"}),this.editorEl.placeholder=`Type or paste markdown here to preview and export as PDF. +`))]}let c=Zo(n,i[l-1],!1);if(!c)return null;let u=t.cloneNode(!1);u.appendChild(c[0]);let d=t.cloneNode(!1);return d.appendChild(c[1]),[u,d]},s=null,f=0;for(let l=1;l<=o.length;l++){let c=a(l);if(!c||!e(c[0]))break;s=c,f=l}if(f<=0){if(!r)return null;s=a(1),f=1}return f>=o.length||!s?null:s}function Nm(t){if(!Fm.has(t.tagName))return!1;for(let e of Array.from(t.childNodes))if(e.nodeType===Node.ELEMENT_NODE&&wm.has(e.tagName))return!1;return!0}function Mm(t,e,r){return Sm.has(t.tagName)?null:t.tagName==="PRE"?Bm(t,e,r):t.tagName==="TABLE"?Rm(t,e,r):t.tagName==="UL"||t.tagName==="OL"?Am(t,e,r):Nm(t)?Em(t,e,r):null}function ud(t,e,r,n){let o=activeDocument.createElement("div");o.setCssStyles({position:"fixed",top:"0",left:"-99999px",width:`${e}px`,visibility:"hidden",pointerEvents:"none",zIndex:"-1"});let i=o.attachShadow({mode:"open"}),a=new CSSStyleSheet;a.replaceSync(n),i.adoptedStyleSheets=[a];let s=activeDocument.createElement("div");s.className="mpdf-doc";for(let c of Array.from(t.children))s.appendChild(c.cloneNode(!0));i.appendChild(s);let f=activeDocument.createElement("div");f.className="mpdf-doc",f.setCssStyles({position:"absolute",top:"0",left:"0",width:`${e}px`,visibility:"hidden"}),i.appendChild(f),activeDocument.body.appendChild(o);let l=[];try{let c=[],u=Array.from(s.children),d=0;for(;d0?u[d]=x:d++;continue}if(c.length>0){l.push(c),c=[];continue}c.push(p.cloneNode(!0)),l.push(c),c=[],d++}c.length>0&&l.push(c)}finally{activeDocument.body.removeChild(o)}return l.length>0?l:[[]]}function Im(t,e,r){return(t&&t.trim()?t:"{{current}} / {{total}}").replace(/\{\{\s*current\s*\}\}/g,String(e)).replace(/\{\{\s*total\s*\}\}/g,String(r))}function dd(t,e){let r=t.length;return t.map((n,o)=>{let i=o+1,a=e.showHeaderOnFirstPage||o>0,s=e.showFooterOnFirstPage||o>0,f=e.showFooterOnFirstPage?e.pageNumberStart+o:e.pageNumberStart+(o-1),l=e.showFooterOnFirstPage?e.pageNumberStart+r-1:e.pageNumberStart+r-2,c=Im(e.pageNumberFormat,f,l),u="",d="",p="",h="",b="",F="";if(s&&(e.footerText&&(e.footerTextAlignment==="center"?p=e.footerText:e.footerTextAlignment==="left"?u=e.footerText:d=e.footerText),e.showPageNumbers)){let y=w=>w?w+" \u2014 "+c:c;e.pageNumberPosition==="center"?p=y(p):e.pageNumberPosition==="left"?u=y(u):d=y(d)}a&&e.headerText&&(e.headerAlignment==="center"?b=e.headerText:e.headerAlignment==="left"?h=e.headerText:F=e.headerText);let x=e.showHeader&&a&&!!(h||b||F||e.showHeaderBorder),m=e.showFooter&&s&&!!(u||d||p||e.showFooterBorder);return{pageNodes:n,pageNum:i,totalPages:r,pageShowsHeader:a,pageShowsFooter:s,hasHeader:x,hasFooter:m,headerLeft:h,headerCenter:b,headerRight:F,footerLeft:u,footerRight:d,footerCenter:p}})}function hd(t){let e=[];for(let r of t)for(let n of r.pageNodes){let o=/^H[1-6]$/.test(n.tagName)?[n]:[],i=Array.from(n.querySelectorAll("h1,h2,h3,h4,h5,h6"));for(let a of[...o,...i]){let s=parseInt(a.tagName[1],10),f=(a.textContent??"").trim();f&&e.push({title:f,level:s,page:r.pageNum})}}return e}async function pd(t,e){if(!e.length)return t;let r=await Ke.load(t),n=r.getPages(),o=r.context,i=e.length,a=new Array(i).fill(-1);for(let m=1;m=0;y--)if(e[y].level=0;y--)if(a[y]===a[m]){s[m]=y;break}for(let y=m+1;y=0&&(l[y]<0&&(l[y]=m),c[y]=m,u[y]++)}let d=o.nextRef(),p=e.map(()=>o.nextRef());for(let m=0;m=0?p[a[m]]:d),S.set(v.of("Dest"),w),s[m]>=0&&S.set(v.of("Prev"),p[s[m]]),f[m]>=0&&S.set(v.of("Next"),p[f[m]]),l[m]>=0&&(S.set(v.of("First"),p[l[m]]),S.set(v.of("Last"),p[c[m]]),S.set(v.of("Count"),z.of(-u[m]))),o.assign(p[m],S)}let h=-1,b=-1,F=0;for(let m=0;m`}function vd(t,e,r,n){if(!(!e&&!r&&!n))if(e){let o=activeDocument.createElement("span");o.className="mpdf-hf-center",o.textContent=e,t.appendChild(o)}else{let o=activeDocument.createElement("span");o.textContent=r,t.appendChild(o);let i=activeDocument.createElement("span");i.className="mpdf-hf-right",i.textContent=n,t.appendChild(i)}}function md(t,e,r){return!t&&!e&&!r?"":t?`${Mn(t)}`:`${Mn(e)}${Mn(r)}`}function jm(t,e){if(e)return e;let r=t.workspace.getActiveFile();if(r?.extension==="md")return r;let n=t.workspace.getMostRecentLeaf();return n?.view instanceof ze.MarkdownView?n.view.file??null:null}var Ji=class t extends ze.Modal{plugin;editorEl;previewEl;pageCountEl;noteTitleEl;renderBtn;exportBtn;loadingOverlayEl;renderComponent=new ze.Component;initialFile;currentFile=null;renderToken=0;layoutCache=null;renderDebounceTimer=null;constructor(e,r,n){super(e),this.plugin=r,this.initialFile=n??null}async onOpen(){this.plugin.activeModal=this,this.renderComponent.load(),this.modalEl.addClass("mpdf-modal"),this.buildUI(this.contentEl);let e=jm(this.app,this.initialFile);if(e){let r;try{r=await this.app.vault.read(e)}catch(n){let o=n instanceof Error?n.message:String(n);new ze.Notice(`Failed to read file "${e.basename}": ${o}`);return}if(!this.plugin.activeModal)return;this.currentFile=e,this.editorEl.value=r,this.noteTitleEl.textContent=e.basename,this.noteTitleEl.title=e.path,this.render(!0)}}onClose(){this.renderDebounceTimer!==null&&(window.clearTimeout(this.renderDebounceTimer),this.renderDebounceTimer=null),this.renderComponent.unload(),this.plugin.activeModal=null,this.currentFile=null,this.layoutCache=null}buildUI(e){let r=this.plugin.settings;this.buildTopbar(e.createEl("div",{cls:"mpdf-topbar"}),r);let n=e.createEl("div",{cls:"mpdf-main"}),o=n.createEl("div",{cls:"mpdf-editor-panel"});this.editorEl=o.createEl("textarea",{cls:"mpdf-editor"}),this.editorEl.placeholder=`Type or paste markdown here to preview and export as PDF. Tip: open this panel from a note's right-click menu, command palette, or keyboard shortcut to auto-load the active note. @@ -244,14 +244,14 @@ flowchart LR Markdown tables: | Col A | Col B | |-------|-------| -| Cell | Cell |`;let i=n.createEl("div",{cls:"mpdf-preview-container"});this.previewEl=i.createEl("div",{cls:"mpdf-preview"}),this.loadingOverlayEl=i.createEl("div",{cls:"mpdf-loading-overlay"}),this.loadingOverlayEl.createEl("div",{cls:"mpdf-spinner"}),this.loadingOverlayEl.createEl("span",{cls:"mpdf-loading-text",text:"Rendering\u2026"}),this.editorEl.addEventListener("keydown",a=>{a.key==="Enter"&&(a.ctrlKey||a.metaKey)&&(a.preventDefault(),this.render(!0))})}buildTopbar(e,r){let n=e.createEl("div",{cls:"mpdf-topbar-left"}),o=e.createEl("div",{cls:"mpdf-topbar-right"}),i=(w,S,D,T)=>{let C=n.createEl("div",{cls:"mpdf-ctrl"});C.createEl("span",{cls:"mpdf-ctrl-label",text:w});let E=C.createEl("select",{cls:"mpdf-select"});for(let[I,A]of Object.entries(S)){let R=E.createEl("option",{text:A,value:I});I===D&&(R.selected=!0)}E.addEventListener("change",()=>void T(E.value))},a={};Object.entries(Tn).forEach(([w,S])=>a[w]=S.name),i("Style",a,r.preset,async w=>{this.plugin.applyPreset(w),await this.plugin.saveSettingsAndRender()});let s={};Object.keys(Vi).forEach(w=>s[w]=w),s.Custom="Custom";let f=n.createEl("div",{cls:"mpdf-ctrl"});f.createEl("span",{cls:"mpdf-ctrl-label",text:"Size"});let l=f.createEl("select",{cls:"mpdf-select"});for(let[w,S]of Object.entries(s)){let D=l.createEl("option",{text:S,value:w});w===r.pageSize&&(D.selected=!0)}let c=n.createEl("div",{cls:"mpdf-ctrl"});c.toggleClass("mpdf-is-hidden",r.pageSize!=="Custom");let u=(w,S)=>{c.createEl("span",{cls:"mpdf-ctrl-label",text:w});let D=c.createEl("input",{cls:"mpdf-custom-size-input"});return D.type="number",D.min="10",D.step="1",D.value=String(S),D},d=u("W",r.customPageWidth),p=u("H",r.customPageHeight);c.createEl("span",{cls:"mpdf-ctrl-label",text:"mm"}),l.addEventListener("change",()=>{this.plugin.settings.pageSize=l.value,c.toggleClass("mpdf-is-hidden",l.value!=="Custom"),this.plugin.saveSettingsAndRender()});let h=async()=>{this.plugin.settings.customPageWidth=Math.max(10,parseFloat(d.value)||210),this.plugin.settings.customPageHeight=Math.max(10,parseFloat(p.value)||297),await this.plugin.saveSettingsAndRender()};d.addEventListener("change",()=>void h()),p.addEventListener("change",()=>void h()),i("",{portrait:"Portrait",landscape:"Landscape"},r.orientation,async w=>{this.plugin.settings.orientation=w,await this.plugin.saveSettingsAndRender()});let b=n.createEl("div",{cls:"mpdf-ctrl"});b.createEl("span",{cls:"mpdf-ctrl-label",text:"Zoom"});let F=b.createEl("span",{cls:"mpdf-ctrl-label",text:Math.round(r.previewScale*100)+"%"}),x=b.createEl("input");x.type="range",x.min="0.35",x.max="1.0",x.step="0.05",x.value=String(r.previewScale),x.addClass("mpdf-zoom-slider"),x.addEventListener("input",()=>{let w=parseFloat(x.value);this.plugin.settings.previewScale=w,F.textContent=Math.round(w*100)+"%",this.plugin.saveSettings().then(()=>{this.renderPreviewOnly()})});let m=n.createEl("button",{cls:"mpdf-btn",text:"Insert Page Break"});m.title="Insert page break (///)",m.addEventListener("click",()=>this.insertAtCursor(` +| Cell | Cell |`;let i=n.createEl("div",{cls:"mpdf-preview-container"});this.previewEl=i.createEl("div",{cls:"mpdf-preview"}),this.loadingOverlayEl=i.createEl("div",{cls:"mpdf-loading-overlay"}),this.loadingOverlayEl.createEl("div",{cls:"mpdf-spinner"}),this.loadingOverlayEl.createEl("span",{cls:"mpdf-loading-text",text:"Rendering\u2026"}),this.editorEl.addEventListener("keydown",a=>{a.key==="Enter"&&(a.ctrlKey||a.metaKey)&&(a.preventDefault(),this.render(!0))})}buildTopbar(e,r){let n=e.createEl("div",{cls:"mpdf-topbar-left"}),o=e.createEl("div",{cls:"mpdf-topbar-right"}),i=(w,S,D,T)=>{let C=n.createEl("div",{cls:"mpdf-ctrl"});C.createEl("span",{cls:"mpdf-ctrl-label",text:w});let E=C.createEl("select",{cls:"mpdf-select"});for(let[M,A]of Object.entries(S)){let R=E.createEl("option",{text:A,value:M});M===D&&(R.selected=!0)}E.addEventListener("change",()=>void T(E.value))},a={};Object.entries(It).forEach(([w,S])=>a[w]=S.name),i("Style",a,r.preset,async w=>{this.plugin.applyPreset(w),await this.plugin.saveSettingsAndRender()});let s={};Object.keys(mr).forEach(w=>s[w]=w),s.Custom="Custom";let f=n.createEl("div",{cls:"mpdf-ctrl"});f.createEl("span",{cls:"mpdf-ctrl-label",text:"Size"});let l=f.createEl("select",{cls:"mpdf-select"});for(let[w,S]of Object.entries(s)){let D=l.createEl("option",{text:S,value:w});w===r.pageSize&&(D.selected=!0)}let c=n.createEl("div",{cls:"mpdf-ctrl"});c.toggleClass("mpdf-is-hidden",r.pageSize!=="Custom");let u=(w,S)=>{c.createEl("span",{cls:"mpdf-ctrl-label",text:w});let D=c.createEl("input",{cls:"mpdf-custom-size-input"});return D.type="number",D.min="10",D.step="1",D.value=String(S),D},d=u("W",r.customPageWidth),p=u("H",r.customPageHeight);c.createEl("span",{cls:"mpdf-ctrl-label",text:"mm"}),l.addEventListener("change",()=>{this.plugin.settings.pageSize=l.value,c.toggleClass("mpdf-is-hidden",l.value!=="Custom"),this.plugin.saveSettingsAndRender()});let h=async()=>{this.plugin.settings.customPageWidth=Math.max(10,parseFloat(d.value)||210),this.plugin.settings.customPageHeight=Math.max(10,parseFloat(p.value)||297),await this.plugin.saveSettingsAndRender()};d.addEventListener("change",()=>void h()),p.addEventListener("change",()=>void h()),i("",{portrait:"Portrait",landscape:"Landscape"},r.orientation,async w=>{this.plugin.settings.orientation=w,await this.plugin.saveSettingsAndRender()});let b=n.createEl("div",{cls:"mpdf-ctrl"});b.createEl("span",{cls:"mpdf-ctrl-label",text:"Zoom"});let F=b.createEl("span",{cls:"mpdf-ctrl-label",text:Math.round(r.previewScale*100)+"%"}),x=b.createEl("input");x.type="range",x.min="0.35",x.max="1.0",x.step="0.05",x.value=String(r.previewScale),x.addClass("mpdf-zoom-slider"),x.addEventListener("input",()=>{let w=parseFloat(x.value);this.plugin.settings.previewScale=w,F.textContent=Math.round(w*100)+"%",this.plugin.saveSettings().then(()=>{this.renderPreviewOnly()})});let m=n.createEl("button",{cls:"mpdf-btn",text:"Insert Page Break"});m.title="Insert page break (///)",m.addEventListener("click",()=>this.insertAtCursor(` /// -`)),this.noteTitleEl=n.createEl("div",{cls:"mpdf-topbar-title",text:"\u2014"}),this.pageCountEl=o.createEl("span",{cls:"mpdf-page-count",text:"\u2014 pages"});let y=o.createEl("button",{cls:"mpdf-btn mpdf-btn-icon"});y.setAttr("aria-label","Open Advanced PDF Export settings"),(0,N.setIcon)(y,"settings"),y.addEventListener("click",()=>{let w=this.app.setting;w?.open?.(),w?.openTabById?.("advanced-pdf-export")}),this.renderBtn=o.createEl("button",{cls:"mpdf-btn",text:"\u27F3 Render PDF"}),this.renderBtn.title="Render preview (Ctrl+Enter)",this.renderBtn.addEventListener("click",()=>this.render(!0)),this.exportBtn=o.createEl("button",{cls:"mpdf-btn mpdf-btn-primary",text:"\u2B07 Export PDF"}),this.exportBtn.addEventListener("click",()=>void this.exportPDF())}insertAtCursor(e){let r=this.editorEl,n=r.selectionStart,o=r.selectionEnd;r.value=r.value.slice(0,n)+e+r.value.slice(o),r.selectionStart=r.selectionEnd=n+e.length,r.focus()}render(e=!1){let r=++this.renderToken;this.renderDebounceTimer!==null&&(window.clearTimeout(this.renderDebounceTimer),this.renderDebounceTimer=null),this.showLoading();let n=()=>this.doRender(r).catch(o=>{let i=o instanceof Error?o.message:String(o);console.error("[advanced-pdf-export] render error:",o),this.hideLoading(),new N.Notice("Advanced PDF Export \u2014 render failed: "+i)});e?window.requestAnimationFrame(()=>window.requestAnimationFrame(()=>void n())):this.renderDebounceTimer=window.setTimeout(()=>{this.renderDebounceTimer=null,window.requestAnimationFrame(()=>window.requestAnimationFrame(()=>void n()))},150)}static insertAutoBreaks(e,r,n){if(!r&&!n)return e;let o=e.split(` +`)),this.noteTitleEl=n.createEl("div",{cls:"mpdf-topbar-title",text:"\u2014"}),this.pageCountEl=o.createEl("span",{cls:"mpdf-page-count",text:"\u2014 pages"});let y=o.createEl("button",{cls:"mpdf-btn mpdf-btn-icon"});y.setAttr("aria-label","Open Advanced PDF Export settings"),(0,ze.setIcon)(y,"settings"),y.addEventListener("click",()=>{let w=this.app.setting;w?.open?.(),w?.openTabById?.("advanced-pdf-export")}),this.renderBtn=o.createEl("button",{cls:"mpdf-btn",text:"\u27F3 Render PDF"}),this.renderBtn.title="Render preview (Ctrl+Enter)",this.renderBtn.addEventListener("click",()=>this.render(!0)),this.exportBtn=o.createEl("button",{cls:"mpdf-btn mpdf-btn-primary",text:"\u2B07 Export PDF"}),this.exportBtn.addEventListener("click",()=>void this.exportPDF())}insertAtCursor(e){let r=this.editorEl,n=r.selectionStart,o=r.selectionEnd;r.value=r.value.slice(0,n)+e+r.value.slice(o),r.selectionStart=r.selectionEnd=n+e.length,r.focus()}render(e=!1){let r=++this.renderToken;this.renderDebounceTimer!==null&&(window.clearTimeout(this.renderDebounceTimer),this.renderDebounceTimer=null),this.showLoading();let n=()=>this.doRender(r).catch(o=>{let i=o instanceof Error?o.message:String(o);console.error("[advanced-pdf-export] render error:",o),this.hideLoading(),new ze.Notice("Advanced PDF Export \u2014 render failed: "+i)});e?window.requestAnimationFrame(()=>window.requestAnimationFrame(()=>void n())):this.renderDebounceTimer=window.setTimeout(()=>{this.renderDebounceTimer=null,window.requestAnimationFrame(()=>window.requestAnimationFrame(()=>void n()))},150)}static insertAutoBreaks(e,r,n){if(!r&&!n)return e;let o=e.split(` `),i=[],a=!1,s="";for(let f of o){if(a){let l=f.match(/^(`{3,}|~{3,})\s*$/);l&&l[1][0]===s[0]&&l[1].length>=s.length&&(a=!1,s="")}else{let l=f.match(/^(`{3,}|~{3,})/);l?(a=!0,s=l[1]):i.length>0&&(r&&/^# /.test(f)||n&&/^## /.test(f))&&i.push("///")}i.push(f)}return i.join(` -`)}async doRender(e){let r=this.plugin.settings,n=Jv(this.editorEl.value);r.hideFrontmatter&&(n=Qv(n)),r.includeFilenameAsTitle&&this.currentFile&&(n=`# ${this.currentFile.basename} +`)}async doRender(e){let r=this.plugin.settings,n=Gs(this.editorEl.value);r.hideFrontmatter&&(n=Ks(n)),r.includeFilenameAsTitle&&this.currentFile&&(n=`# ${this.currentFile.basename} -${n}`),n=t.insertAutoBreaks(n,r.autoBreakH1,r.autoBreakH2);let o=_v(n),i=Kv(r),a=r.orientation==="landscape"?i.h:i.w,s=r.orientation==="landscape"?i.w:i.h,f=kn(r.marginTop),l=kn(r.marginBottom),c=kn(r.marginLeft),u=kn(r.marginRight),d=r.showFooter&&(r.showPageNumbers||r.footerText||r.showFooterBorder||r.footerImagePath)?r.footerHeight>0?r.footerHeight:Math.max(28,r.footerFontSize+14):0,p=r.showHeader&&(r.headerText||r.showHeaderBorder||r.headerImagePath)?r.headerHeight>0?r.headerHeight:Math.max(20,r.headerFontSize+10):0,h=Math.max(1,a-c-u),b=Math.max(1,s-f-l-d-p),F=Yv(this.editorEl.value),x=fm(r,F),m=this.currentFile?.path??"pdf-export",y=await Promise.all(o.map(E=>Qu(this.app,E,m,this.renderComponent)));if(e!==this.renderToken)return;await Ds();let w=qi(),S=w?um(w):"",D=S?`${S} -${x}`:x,T=[];for(let E of y)T.push(...Tm(E,h,b,D));let C=Am(T,r);this.layoutCache={layouts:C,pw:a,ph:s,mTop:f,mLeft:c,mRight:u,footerH:d,headerH:p,contentW:h,contentH:b,docCSS:D,fontFamily:_u(r),accentColor:r.accentColor,pageBackground:r.pageBackground,isRTL:F},this.drawPreview(this.layoutCache,r.previewScale),this.pageCountEl.textContent=`${C.length} page${C.length!==1?"s":""}`,this.hideLoading()}renderPreviewOnly(){this.layoutCache&&this.drawPreview(this.layoutCache,this.plugin.settings.previewScale)}showLoading(){this.loadingOverlayEl.addClass("mpdf-is-active"),this.renderBtn.disabled=!0,this.renderBtn.textContent="Rendering\u2026"}hideLoading(){this.loadingOverlayEl.removeClass("mpdf-is-active"),this.renderBtn.disabled=!1,this.renderBtn.textContent="\u27F3 Render PDF"}drawPreview(e,r){let{layouts:n,pw:o,ph:i,mTop:a,mLeft:s,mRight:f,footerH:l,headerH:c,contentW:u,contentH:d,docCSS:p,fontFamily:h,accentColor:b,pageBackground:F,isRTL:x}=e,m=this.plugin.settings;this.previewEl.empty();let y=new Map;n.forEach((T,C)=>{for(let E of T.pageNodes)E.querySelectorAll("[id]").forEach(I=>{y.has(I.id)||y.set(I.id,C)}),E.id&&!y.has(E.id)&&y.set(E.id,C)});let w=[],S=` +${n}`),n=t.insertAutoBreaks(n,r.autoBreakH1,r.autoBreakH2);let o=Xs(n),i=Hs(r),a=r.orientation==="landscape"?i.h:i.w,s=r.orientation==="landscape"?i.w:i.h,f=gr(r.marginTop),l=gr(r.marginBottom),c=gr(r.marginLeft),u=gr(r.marginRight),d=r.showFooter&&(r.showPageNumbers||r.footerText||r.showFooterBorder||r.footerImagePath)?r.footerHeight>0?r.footerHeight:Math.max(28,r.footerFontSize+14):0,p=r.showHeader&&(r.headerText||r.showHeaderBorder||r.headerImagePath)?r.headerHeight>0?r.headerHeight:Math.max(20,r.headerFontSize+10):0,h=Math.max(1,a-c-u),b=Math.max(1,s-f-l-d-p),F=Zs(this.editorEl.value),x=Us(r,F),m=this.currentFile?.path??"pdf-export",y=await Promise.all(o.map(E=>ia(this.app,E,m,this.renderComponent)));if(e!==this.renderToken)return;await In();let w=Nn(),S=w?Vs(w):"",D=S?`${S} +${x}`:x,T=[];for(let E of y)T.push(...ud(E,h,b,D));let C=dd(T,r);this.layoutCache={layouts:C,pw:a,ph:s,mTop:f,mLeft:c,mRight:u,footerH:d,headerH:p,contentW:h,contentH:b,docCSS:D,fontFamily:oa(r),accentColor:r.accentColor,pageBackground:r.pageBackground,isRTL:F},this.drawPreview(this.layoutCache,r.previewScale),this.pageCountEl.textContent=`${C.length} page${C.length!==1?"s":""}`,this.hideLoading()}renderPreviewOnly(){this.layoutCache&&this.drawPreview(this.layoutCache,this.plugin.settings.previewScale)}showLoading(){this.loadingOverlayEl.addClass("mpdf-is-active"),this.renderBtn.disabled=!0,this.renderBtn.textContent="Rendering\u2026"}hideLoading(){this.loadingOverlayEl.removeClass("mpdf-is-active"),this.renderBtn.disabled=!1,this.renderBtn.textContent="\u27F3 Render PDF"}drawPreview(e,r){let{layouts:n,pw:o,ph:i,mTop:a,mLeft:s,mRight:f,footerH:l,headerH:c,contentW:u,contentH:d,docCSS:p,fontFamily:h,accentColor:b,pageBackground:F,isRTL:x}=e,m=this.plugin.settings;this.previewEl.empty();let y=new Map;n.forEach((T,C)=>{for(let E of T.pageNodes)E.querySelectorAll("[id]").forEach(M=>{y.has(M.id)||y.set(M.id,C)}),E.id&&!y.has(E.id)&&y.set(E.id,C)});let w=[],S=` :host { display: block; width: ${o}px; @@ -266,8 +266,8 @@ ${x}`:x,T=[];for(let E of y)T.push(...Tm(E,h,b,D));let C=Am(T,r);this.layoutCach .mpdf-hf-center { flex: 1; text-align: center; } .mpdf-hf-right { margin-left: auto; } ${p} - `,D=new CSSStyleSheet;D.replaceSync(S);for(let T of n){let C=Math.round(o*r),E=Math.round(i*r),I=this.previewEl.createEl("div",{cls:"mpdf-page-wrap"});I.setCssStyles({width:`${C}px`,height:`${E}px`}),I.createEl("div",{cls:"mpdf-page-label",text:`Page ${T.pageNum} of ${T.totalPages}`}),w.push(I);let A=I.createEl("div",{cls:"mpdf-page-scale"});A.setCssStyles({width:`${C}px`,height:`${E}px`});let R=activeDocument.createElement("div");R.addClass("mpdf-shadow-host"),R.setCssStyles({width:`${o}px`,height:`${i}px`,transform:`scale(${r})`}),A.appendChild(R);let z=R.attachShadow({mode:"open"});if(z.adoptedStyleSheets=[D],m.backgroundImageEnabled&&m.backgroundImagePath){let oe=Cn(this.app,m.backgroundImagePath);if(oe){let Fe=m.backgroundImageScope==="content-only",Ce=activeDocument.createElement("div"),Be=Ku(m.backgroundImageSize);Ce.setCssStyles({position:"absolute",...Fe?{top:`${a+c}px`,left:`${s}px`,width:`${u}px`,height:`${d}px`}:{inset:"0"},backgroundImage:`url('${oe}')`,backgroundRepeat:Be.repeat,backgroundSize:Be.size,backgroundPosition:"center",opacity:String(m.backgroundImageOpacity),pointerEvents:"none"}),z.appendChild(Ce)}}let M=T.pageShowsHeader,X=T.pageShowsFooter;if(M&&m.showHeader&&m.headerImagePath){let oe=Cn(this.app,m.headerImagePath);if(oe){let Fe=activeDocument.createElement("div");Fe.setCssStyles({position:"absolute",top:`${a*.4}px`,left:`${m.headerImageMargin}px`,right:`${m.headerImageMargin}px`,height:`${c}px`,backgroundImage:`url('${oe}')`,backgroundSize:"cover",backgroundPosition:"center",backgroundRepeat:"no-repeat",pointerEvents:"none"}),z.appendChild(Fe)}}if(T.hasHeader){let oe=activeDocument.createElement("div");oe.setCssStyles({position:"absolute",top:`${a*.4}px`,left:`${s}px`,right:`${f}px`,height:`${c}px`,display:"flex",alignItems:"center",fontSize:`${m.headerFontSize}px`,color:m.headerFontColor,fontFamily:h,whiteSpace:"nowrap",...m.showHeaderBorder?{borderBottom:`0.5px solid ${b}33`}:{}}),Yu(oe,T.headerCenter,T.headerLeft,T.headerRight),z.appendChild(oe)}let L=activeDocument.createElement("div");L.className="mpdf-doc",x&&L.setAttribute("dir","rtl"),L.setCssStyles({position:"absolute",top:`${a+c}px`,left:`${s}px`,width:`${u}px`});for(let oe of T.pageNodes)L.appendChild(oe.cloneNode(!0));if(z.appendChild(L),L.querySelectorAll("a[href^='#']").forEach(oe=>{let Fe=decodeURIComponent((oe.getAttribute("href")??"").slice(1)),Ce=y.get(Fe);Ce!==void 0&&(oe.title=`Go to page ${Ce+1}`,oe.addEventListener("click",Be=>{Be.preventDefault(),w[Ce]?.scrollIntoView({behavior:"smooth",block:"start"})}))}),X&&m.showFooter&&m.footerImagePath){let oe=Cn(this.app,m.footerImagePath);if(oe){let Fe=activeDocument.createElement("div");Fe.setCssStyles({position:"absolute",bottom:"0",left:`${m.footerImageMargin}px`,right:`${m.footerImageMargin}px`,height:`${l}px`,backgroundImage:`url('${oe}')`,backgroundSize:"cover",backgroundPosition:"center",backgroundRepeat:"no-repeat",pointerEvents:"none"}),z.appendChild(Fe)}}if(T.hasFooter){let oe=activeDocument.createElement("div");oe.setCssStyles({position:"absolute",bottom:"0",left:"0",right:"0",height:`${l}px`,display:"flex",alignItems:"center",...m.showFooterBorder?{borderTop:`0.5px solid ${b}33`}:{},padding:`0 ${f}px 0 ${s}px`,fontSize:`${m.footerFontSize}px`,color:m.footerFontColor,fontFamily:h}),Yu(oe,T.footerCenter,T.footerLeft,T.footerRight),z.appendChild(oe)}let ye=Bm(m);ye&&z.appendChild(ye)}}async exportPDF(){let e=this.plugin.settings;this.exportBtn.disabled=!0,this.exportBtn.textContent="\u2B07 Exporting\u2026";let r=()=>{this.exportBtn.disabled=!1,this.exportBtn.textContent="\u2B07 Export PDF"};if(!this.layoutCache){this.renderDebounceTimer!==null&&(window.clearTimeout(this.renderDebounceTimer),this.renderDebounceTimer=null);let R=++this.renderToken;this.showLoading();try{await this.doRender(R)}catch(z){let M=z instanceof Error?z.message:String(z);new N.Notice("Advanced PDF Export \u2014 render failed: "+M),this.hideLoading(),r();return}}let n=this.layoutCache;if(!n||n.layouts.length===0){new N.Notice("Nothing to export."),r();return}let{layouts:o,pw:i,ph:a,mTop:s,mLeft:f,mRight:l,footerH:c,headerH:u,contentW:d,contentH:p,docCSS:h,fontFamily:b,accentColor:F,pageBackground:x,isRTL:m}=n,y=Nm(e),w=e.showHeader&&e.headerImagePath?Cn(this.app,e.headerImagePath):"",S=e.showFooter&&e.footerImagePath?Cn(this.app,e.footerImagePath):"",D=e.backgroundImageEnabled&&e.backgroundImagePath?Cn(this.app,e.backgroundImagePath):"",T=D?(()=>{let R=Ku(e.backgroundImageSize),z=e.backgroundImageScope==="content-only"?`top:${s+u}px;left:${f}px;width:${d}px;height:${p}px;`:"inset:0;",M=`background-image:url('${D}');background-size:${R.size};background-repeat:${R.repeat};background-position:center;opacity:${e.backgroundImageOpacity};pointer-events:none;`;return`
`})():"",C=o.map(R=>{let z=R.pageNodes.map(Be=>Be.outerHTML).join(` -`),M=R.hasHeader,X=e.showHeaderBorder?`border-bottom:0.5px solid ${F}33;`:"",te=M?`
${Ju(R.headerCenter,R.headerLeft,R.headerRight)}
`:"",L=R.hasFooter,ue=e.showFooterBorder?`border-top:0.5px solid ${F}33;`:"",ye=L?`
${Ju(R.footerCenter,R.footerLeft,R.footerRight)}
`:"",oe=`
${z}
`,Fe=R.pageShowsHeader&&w?`
`:"",Ce=R.pageShowsFooter&&S?`
`:"";return`
${T}${Fe}${te}${oe}${Ce}${ye}${y}
`});await Ds();let E=await dm(),I=` + `,D=new CSSStyleSheet;D.replaceSync(S);for(let T of n){let C=Math.round(o*r),E=Math.round(i*r),M=this.previewEl.createEl("div",{cls:"mpdf-page-wrap"});M.setCssStyles({width:`${C}px`,height:`${E}px`}),M.createEl("div",{cls:"mpdf-page-label",text:`Page ${T.pageNum} of ${T.totalPages}`}),w.push(M);let A=M.createEl("div",{cls:"mpdf-page-scale"});A.setCssStyles({width:`${C}px`,height:`${E}px`});let R=activeDocument.createElement("div");R.addClass("mpdf-shadow-host"),R.setCssStyles({width:`${o}px`,height:`${i}px`,transform:`scale(${r})`}),A.appendChild(R);let I=R.attachShadow({mode:"open"});if(I.adoptedStyleSheets=[D],m.backgroundImageEnabled&&m.backgroundImagePath){let oe=yr(this.app,m.backgroundImagePath);if(oe){let Fe=m.backgroundImageScope==="content-only",Ce=activeDocument.createElement("div"),Be=na(m.backgroundImageSize);Ce.setCssStyles({position:"absolute",...Fe?{top:`${a+c}px`,left:`${s}px`,width:`${u}px`,height:`${d}px`}:{inset:"0"},backgroundImage:`url('${oe}')`,backgroundRepeat:Be.repeat,backgroundSize:Be.size,backgroundPosition:"center",opacity:String(m.backgroundImageOpacity),pointerEvents:"none"}),I.appendChild(Ce)}}let N=T.pageShowsHeader,X=T.pageShowsFooter;if(N&&m.showHeader&&m.headerImagePath){let oe=yr(this.app,m.headerImagePath);if(oe){let Fe=activeDocument.createElement("div");Fe.setCssStyles({position:"absolute",top:`${a*.4}px`,left:`${m.headerImageMargin}px`,right:`${m.headerImageMargin}px`,height:`${c}px`,backgroundImage:`url('${oe}')`,backgroundSize:"cover",backgroundPosition:"center",backgroundRepeat:"no-repeat",pointerEvents:"none"}),I.appendChild(Fe)}}if(T.hasHeader){let oe=activeDocument.createElement("div");oe.setCssStyles({position:"absolute",top:`${a*.4}px`,left:`${s}px`,right:`${f}px`,height:`${c}px`,display:"flex",alignItems:"center",fontSize:`${m.headerFontSize}px`,color:m.headerFontColor,fontFamily:h,whiteSpace:"nowrap",...m.showHeaderBorder?{borderBottom:`0.5px solid ${b}33`}:{}}),vd(oe,T.headerCenter,T.headerLeft,T.headerRight),I.appendChild(oe)}let L=activeDocument.createElement("div");L.className="mpdf-doc",x&&L.setAttribute("dir","rtl"),L.setCssStyles({position:"absolute",top:`${a+c}px`,left:`${s}px`,width:`${u}px`});for(let oe of T.pageNodes)L.appendChild(oe.cloneNode(!0));if(I.appendChild(L),L.querySelectorAll("a[href^='#']").forEach(oe=>{let Fe=decodeURIComponent((oe.getAttribute("href")??"").slice(1)),Ce=y.get(Fe);Ce!==void 0&&(oe.title=`Go to page ${Ce+1}`,oe.addEventListener("click",Be=>{Be.preventDefault(),w[Ce]?.scrollIntoView({behavior:"smooth",block:"start"})}))}),X&&m.showFooter&&m.footerImagePath){let oe=yr(this.app,m.footerImagePath);if(oe){let Fe=activeDocument.createElement("div");Fe.setCssStyles({position:"absolute",bottom:"0",left:`${m.footerImageMargin}px`,right:`${m.footerImageMargin}px`,height:`${l}px`,backgroundImage:`url('${oe}')`,backgroundSize:"cover",backgroundPosition:"center",backgroundRepeat:"no-repeat",pointerEvents:"none"}),I.appendChild(Fe)}}if(T.hasFooter){let oe=activeDocument.createElement("div");oe.setCssStyles({position:"absolute",bottom:"0",left:"0",right:"0",height:`${l}px`,display:"flex",alignItems:"center",...m.showFooterBorder?{borderTop:`0.5px solid ${b}33`}:{},padding:`0 ${f}px 0 ${s}px`,fontSize:`${m.footerFontSize}px`,color:m.footerFontColor,fontFamily:h}),vd(oe,T.footerCenter,T.footerLeft,T.footerRight),I.appendChild(oe)}let ye=zm(m);ye&&I.appendChild(ye)}}async exportPDF(){let e=this.plugin.settings;this.exportBtn.disabled=!0,this.exportBtn.textContent="\u2B07 Exporting\u2026";let r=()=>{this.exportBtn.disabled=!1,this.exportBtn.textContent="\u2B07 Export PDF"};if(!this.layoutCache){this.renderDebounceTimer!==null&&(window.clearTimeout(this.renderDebounceTimer),this.renderDebounceTimer=null);let R=++this.renderToken;this.showLoading();try{await this.doRender(R)}catch(I){let N=I instanceof Error?I.message:String(I);new ze.Notice("Advanced PDF Export \u2014 render failed: "+N),this.hideLoading(),r();return}}let n=this.layoutCache;if(!n||n.layouts.length===0){new ze.Notice("Nothing to export."),r();return}let{layouts:o,pw:i,ph:a,mTop:s,mLeft:f,mRight:l,footerH:c,headerH:u,contentW:d,contentH:p,docCSS:h,fontFamily:b,accentColor:F,pageBackground:x,isRTL:m}=n,y=Lm(e),w=e.showHeader&&e.headerImagePath?yr(this.app,e.headerImagePath):"",S=e.showFooter&&e.footerImagePath?yr(this.app,e.footerImagePath):"",D=e.backgroundImageEnabled&&e.backgroundImagePath?yr(this.app,e.backgroundImagePath):"",T=D?(()=>{let R=na(e.backgroundImageSize),I=e.backgroundImageScope==="content-only"?`top:${s+u}px;left:${f}px;width:${d}px;height:${p}px;`:"inset:0;",N=`background-image:url('${D}');background-size:${R.size};background-repeat:${R.repeat};background-position:center;opacity:${e.backgroundImageOpacity};pointer-events:none;`;return`
`})():"",C=o.map(R=>{let I=R.pageNodes.map(Be=>Be.outerHTML).join(` +`),N=R.hasHeader,X=e.showHeaderBorder?`border-bottom:0.5px solid ${F}33;`:"",te=N?`
${md(R.headerCenter,R.headerLeft,R.headerRight)}
`:"",L=R.hasFooter,ue=e.showFooterBorder?`border-top:0.5px solid ${F}33;`:"",ye=L?`
${md(R.footerCenter,R.footerLeft,R.footerRight)}
`:"",oe=`
${I}
`,Fe=R.pageShowsHeader&&w?`
`:"",Ce=R.pageShowsFooter&&S?`
`:"";return`
${T}${Fe}${te}${oe}${Ce}${ye}${y}
`});await In();let E=await qs(),M=` *, *::before, *::after { box-sizing: border-box; } @page { size: ${i}px ${a}px; margin: 0; } html, body { margin: 0; padding: 0; background: ${x}; } @@ -284,15 +284,15 @@ ${x}`:x,T=[];for(let E of y)T.push(...Tm(E,h,b,D));let C=Am(T,r);this.layoutCach -${Ui(this.currentFile?.basename??"Export")} -${E?``:""} - +${Mn(this.currentFile?.basename??"Export")} +${E?``:""} + ${C.join(` `)} -`;try{let R=window,z=R.require("@electron/remote");if(!z?.dialog)throw new Error("no remote");let M=await z.dialog.showSaveDialog({title:"Save PDF",defaultPath:(this.currentFile?.basename??"export")+".pdf",filters:[{name:"PDF",extensions:["pdf"]}]});if(M.canceled||!M.filePath){r();return}new N.Notice("Advanced PDF Export \u2014 generating PDF\u2026");let X=new Blob([A],{type:"text/html"}),te=URL.createObjectURL(X),L=new z.BrowserWindow({show:!1,webPreferences:{nodeIntegration:!1}});L.loadURL(te);let ue=!1,ye=()=>{URL.revokeObjectURL(te),L.close(),r()};L.webContents.once("did-fail-load",(oe,Fe,Ce)=>{ue||(ue=!0,new N.Notice("Advanced PDF Export \u2014 failed to load page: "+Ce),ye())}),L.webContents.once("did-finish-load",()=>{ue||(ue=!0,L.webContents.executeJavaScript("document.fonts.ready.then(() => true)").catch(()=>!0).then(()=>{let oe=e.pageSize==="Custom";return L.webContents.printToPDF({pageSize:oe?"A4":e.pageSize,landscape:!oe&&e.orientation==="landscape",preferCSSPageSize:oe,printBackground:!0,margins:{marginType:"none"}})}).then(async oe=>{if(e.includeOutline)try{oe=await Om(oe,Rm(o))}catch(Fe){console.warn("[advanced-pdf-export] outline injection failed:",Fe)}R.require("fs").writeFile(M.filePath,oe,Fe=>{Fe?new N.Notice("Advanced PDF Export \u2014 failed to save: "+Fe.message):new N.Notice("\u2713 PDF saved \u2014 "+M.filePath),ye()})}).catch(oe=>{new N.Notice("Advanced PDF Export \u2014 failed to render: "+oe.message),ye()}))})}catch{new N.Notice("Advanced PDF Export requires the Obsidian desktop app."),r()}}},Ts=class extends N.PluginSettingTab{plugin;dirty=!1;constructor(e,r){super(e,r),this.plugin=r}display(){this.dirty=!1,this.buildSettings()}hide(){this.dirty&&(this.dirty=!1,this.plugin.activeModal?.render(!0))}async markDirty(){this.dirty=!0,await this.plugin.saveSettings()}buildSettings(){let{containerEl:e}=this;e.empty();let r=this.plugin.settings,n=(m,y,w,S)=>{let D=new N.Setting(e).setName(m);return S&&D.setDesc(S),D.addText(T=>T.setValue(String(r[y])).onChange(C=>{let E=parseInt(C,10)||0;r[y]=w!==void 0?Math.max(w,E):E,this.markDirty()}))},o=(m,y)=>new N.Setting(e).setName(m).addColorPicker(w=>w.setValue(r[y]).onChange(S=>{r[y]=S,this.markDirty()}));new N.Setting(e).setName("Style Preset").setHeading(),new N.Setting(e).setName("Preset").setDesc("Pick a preset to configure the overall document style. Fine-tune any setting below.").addDropdown(m=>{Object.entries(Tn).forEach(([y,w])=>{m.addOption(y,w.name)}),m.setValue(r.preset).onChange(y=>{this.plugin.applyPreset(y),this.markDirty().then(()=>{this.buildSettings()})})}).addButton(m=>m.setButtonText("Reset Preset").setTooltip("Reset current preset to its default values").onClick(()=>{this.plugin.applyPreset(r.preset,!0),this.markDirty().then(()=>{this.buildSettings()})})),new N.Setting(e).setName("Page").setHeading();let i;new N.Setting(e).setName("Page size").addDropdown(m=>{Object.keys(Vi).forEach(y=>{m.addOption(y,y)}),m.addOption("Custom","Custom\u2026"),m.setValue(r.pageSize).onChange(y=>{r.pageSize=y,i.settingEl.toggleClass("mpdf-is-hidden",y!=="Custom"),this.markDirty()})}),i=new N.Setting(e).setName("Custom page size (mm)").setDesc("Width \xD7 Height in millimetres.").addText(m=>m.setPlaceholder("Width").setValue(String(r.customPageWidth)).onChange(y=>{r.customPageWidth=Math.max(10,parseFloat(y)||210),this.markDirty()})).addText(m=>m.setPlaceholder("Height").setValue(String(r.customPageHeight)).onChange(y=>{r.customPageHeight=Math.max(10,parseFloat(y)||297),this.markDirty()})),i.settingEl.toggleClass("mpdf-is-hidden",r.pageSize!=="Custom"),new N.Setting(e).setName("Orientation").addDropdown(m=>m.addOptions({portrait:"Portrait",landscape:"Landscape"}).setValue(r.orientation).onChange(y=>{r.orientation=y,this.markDirty()})),new N.Setting(e).setName("Margin & Frame").setHeading(),new N.Setting(e).setName("Margins").setDesc("Top \xB7 Bottom \xB7 Left \xB7 Right").addText(m=>m.setPlaceholder("Top").setValue(String(r.marginTop)).onChange(y=>{r.marginTop=parseInt(y,10)||0,this.markDirty()})).addText(m=>m.setPlaceholder("Bottom").setValue(String(r.marginBottom)).onChange(y=>{r.marginBottom=parseInt(y,10)||0,this.markDirty()})).addText(m=>m.setPlaceholder("Left").setValue(String(r.marginLeft)).onChange(y=>{r.marginLeft=parseInt(y,10)||0,this.markDirty()})).addText(m=>m.setPlaceholder("Right").setValue(String(r.marginRight)).onChange(y=>{r.marginRight=parseInt(y,10)||0,this.markDirty()}));let a,s,f,l,c=m=>{[a,s,f,l].forEach(y=>y.settingEl.toggleClass("mpdf-is-hidden",!m))};new N.Setting(e).setName("Enable frame").setDesc("Draws a border around the outer edge of every page.").addToggle(m=>m.setValue(r.frameEnabled).onChange(y=>{r.frameEnabled=y,c(y),this.markDirty()})),a=o("Frame color","frameColor"),s=n("Frame thickness (px)","frameThickness",1),f=n("Frame margin (px)","frameMargin",0,"Gap between the page edge and the frame, applied equally on all four sides."),l=new N.Setting(e).setName("Frame style").addDropdown(m=>m.addOptions({solid:"Solid",dashed:"Dashed",dotted:"Dotted",double:"Double",groove:"Groove",ridge:"Ridge"}).setValue(r.frameStyle).onChange(y=>{r.frameStyle=y,this.markDirty()})),c(r.frameEnabled),new N.Setting(e).setName("Typography").setHeading();let u;new N.Setting(e).setName("Font family").addDropdown(m=>m.addOptions({"Georgia, serif":"Georgia (Serif)","'Times New Roman', Times, serif":"Times New Roman","'Palatino Linotype', Palatino, serif":"Palatino","Arial, sans-serif":"Arial","'Helvetica Neue', Helvetica, sans-serif":"Helvetica","'Trebuchet MS', sans-serif":"Trebuchet","'Courier New', monospace":"Courier New",__custom__:"Custom\u2026"}).setValue(r.fontFamily).onChange(y=>{r.fontFamily=y,u.settingEl.toggleClass("mpdf-is-hidden",y!=="__custom__"),this.markDirty()})),u=new N.Setting(e).setName("Custom font name").setDesc('CSS font-family value \u2014 e.g. "Inter, sans-serif". The font must be installed on your system.').addText(m=>m.setPlaceholder("e.g. Inter, sans-serif").setValue(r.customFontName).onChange(y=>{r.customFontName=y,this.markDirty()})),u.settingEl.toggleClass("mpdf-is-hidden",r.fontFamily!=="__custom__"),new N.Setting(e).setName("Font size (px)").addDropdown(m=>{["10","11","12","13","14","15","16"].forEach(y=>{m.addOption(y,y+"px")}),m.setValue(String(r.fontSize)).onChange(y=>{r.fontSize=parseInt(y),this.markDirty()})}),new N.Setting(e).setName("Code font size").addDropdown(m=>m.addOptions({"0.75":"0.75em","0.80":"0.80em","0.82":"0.82em","0.85":"0.85em","0.88":"0.88em","0.90":"0.90em","1.0":"1.00em"}).setValue(String(r.codeFontSize)).onChange(y=>{r.codeFontSize=parseFloat(y),this.markDirty()})),new N.Setting(e).setName("Line height").addDropdown(m=>m.addOptions({"1.4":"Tight (1.4)","1.6":"Compact (1.6)","1.75":"Normal (1.75)","1.85":"Relaxed (1.85)","2.0":"Double (2.0)"}).setValue(String(r.lineHeight)).onChange(y=>{r.lineHeight=parseFloat(y),this.markDirty()})),new N.Setting(e).setName("Paragraph spacing").addDropdown(m=>m.addOptions({0:"None","0.3":"Tight (0.3em)","0.5":"Normal (0.5em)","0.65":"Relaxed (0.65em)","1.0":"Wide (1em)"}).setValue(String(r.paragraphSpacing)).onChange(y=>{r.paragraphSpacing=parseFloat(y),this.markDirty()})),new N.Setting(e).setName("Heading scale").setDesc("Multiplier applied to all heading sizes.").addDropdown(m=>m.addOptions({"0.8":"Small (0.8\xD7)","0.88":"0.88\xD7","0.9":"Compact (0.9\xD7)","0.95":"0.95\xD7","1.0":"Normal (1.0\xD7)","1.05":"1.05\xD7","1.1":"Large (1.1\xD7)","1.2":"XLarge (1.2\xD7)"}).setValue(String(r.headingScale)).onChange(y=>{r.headingScale=parseFloat(y),this.markDirty()})),new N.Setting(e).setName("Background").setHeading();let d,p,h,b,F,x=m=>{d.settingEl.toggleClass("mpdf-is-hidden",m),[p,h,b,F].forEach(y=>y.settingEl.toggleClass("mpdf-is-hidden",!m))};new N.Setting(e).setName("Use image background").setDesc("When on, a background image is used instead of the solid background color.").addToggle(m=>m.setValue(r.backgroundImageEnabled).onChange(y=>{r.backgroundImageEnabled=y,x(y),this.markDirty()})),d=new N.Setting(e).setName("Page background color").addColorPicker(m=>m.setValue(r.pageBackground).onChange(y=>{r.pageBackground=y,this.markDirty()})),p=new N.Setting(e).setName("Background image").setDesc("Vault-relative path or https:// URL.").addText(m=>m.setPlaceholder("assets/background.png").setValue(r.backgroundImagePath).onChange(y=>{r.backgroundImagePath=y,this.markDirty()})),h=new N.Setting(e).setName("Fit").addDropdown(m=>m.addOptions({cover:"Cover (fill, crop edges)",contain:"Contain (fit, show gaps)",fill:"Fill (stretch to exact size)",tile:"Tile (repeat)"}).setValue(r.backgroundImageSize).onChange(y=>{r.backgroundImageSize=y,this.markDirty()})),b=new N.Setting(e).setName("Scope").setDesc("Full page includes header and footer bands. Content area only restricts the background to the text zone between them.").addDropdown(m=>m.addOptions({"full-page":"Full page","content-only":"Content area only"}).setValue(r.backgroundImageScope).onChange(y=>{r.backgroundImageScope=y,this.markDirty()})),F=new N.Setting(e).setName("Opacity").addDropdown(m=>m.addOptions({"0.05":"5%","0.1":"10%","0.15":"15%","0.2":"20%","0.3":"30%","0.4":"40%","0.5":"50%","0.6":"60%","0.7":"70%","0.8":"80%","0.9":"90%",1:"100%"}).setValue(String(r.backgroundImageOpacity)).onChange(y=>{r.backgroundImageOpacity=parseFloat(y),this.markDirty()})),x(r.backgroundImageEnabled),new N.Setting(e).setName("Colors").setHeading(),o("Accent color","accentColor"),o("Body text color","bodyColor"),o("Heading color","headingColor"),o("Blockquote background","blockquoteBg"),o("Blockquote border","blockquoteBorderColor"),o("Table header background","tableHeaderBg"),o("Code background","codeBackground"),new N.Setting(e).setName("Code syntax theme").setDesc('Independent of your Obsidian theme. "None" uses the body text color and code background above with no highlighting.').addDropdown(m=>{let y={};for(let[w,S]of Object.entries(Cs))y[w]=S.name;m.addOptions(y).setValue(r.codeTheme).onChange(w=>{r.codeTheme=w,this.markDirty()})}),new N.Setting(e).setName("Header").setHeading(),new N.Setting(e).setName("Show header").addToggle(m=>m.setValue(r.showHeader).onChange(y=>{r.showHeader=y,this.markDirty()})),new N.Setting(e).setName("Show on first page").setDesc("When off, the header is hidden on page 1. Useful for title pages.").addToggle(m=>m.setValue(r.showHeaderOnFirstPage).onChange(y=>{r.showHeaderOnFirstPage=y,this.markDirty()})),new N.Setting(e).setName("Header text").addText(m=>m.setValue(r.headerText).onChange(y=>{r.headerText=y,this.markDirty()})),new N.Setting(e).setName("Alignment").addDropdown(m=>m.addOptions({left:"Left",center:"Center",right:"Right"}).setValue(r.headerAlignment).onChange(y=>{r.headerAlignment=y,this.markDirty()})),n("Font size (px)","headerFontSize",1),n("Height (px)","headerHeight",0,"Explicit band height (0 = auto)."),o("Font color","headerFontColor"),new N.Setting(e).setName("Border").setDesc("Separator line below the header.").addToggle(m=>m.setValue(r.showHeaderBorder).onChange(y=>{r.showHeaderBorder=y,this.markDirty()})),new N.Setting(e).setName("Image").setDesc("Vault-relative path or https:// URL. Fills the header band as a background banner.").addText(m=>m.setPlaceholder("assets/header-banner.png").setValue(r.headerImagePath).onChange(y=>{r.headerImagePath=y,this.markDirty()})),n("Image left/right margin (px)","headerImageMargin",0,"Insets the banner from the left and right page edges."),new N.Setting(e).setName("Footer").setHeading(),new N.Setting(e).setName("Show footer").addToggle(m=>m.setValue(r.showFooter).onChange(y=>{r.showFooter=y,this.markDirty()})),new N.Setting(e).setName("Show on first page").setDesc("When off, the footer and page numbers are hidden on page 1. Page numbering starts from page 2.").addToggle(m=>m.setValue(r.showFooterOnFirstPage).onChange(y=>{r.showFooterOnFirstPage=y,this.markDirty()})),new N.Setting(e).setName("Footer text").addText(m=>m.setValue(r.footerText).onChange(y=>{r.footerText=y,this.markDirty()})),new N.Setting(e).setName("Alignment").addDropdown(m=>m.addOptions({left:"Left",center:"Center",right:"Right"}).setValue(r.footerTextAlignment).onChange(y=>{r.footerTextAlignment=y,this.markDirty()})),n("Font size (px)","footerFontSize",1),n("Height (px)","footerHeight",0,"Explicit band height (0 = auto)."),o("Font color","footerFontColor"),new N.Setting(e).setName("Border").setDesc("Separator line above the footer.").addToggle(m=>m.setValue(r.showFooterBorder).onChange(y=>{r.showFooterBorder=y,this.markDirty()})),new N.Setting(e).setName("Image").setDesc("Vault-relative path or https:// URL. Fills the footer band as a background banner.").addText(m=>m.setPlaceholder("assets/footer-banner.png").setValue(r.footerImagePath).onChange(y=>{r.footerImagePath=y,this.markDirty()})),n("Image left/right margin (px)","footerImageMargin",0,"Insets the banner from the left and right page edges."),new N.Setting(e).setName("Show page numbers").addToggle(m=>m.setValue(r.showPageNumbers).onChange(y=>{r.showPageNumbers=y,this.markDirty()})),new N.Setting(e).setName("Page number position").addDropdown(m=>m.addOptions({left:"Left",center:"Center",right:"Right"}).setValue(r.pageNumberPosition).onChange(y=>{r.pageNumberPosition=y,this.markDirty()})),new N.Setting(e).setName("Page number format").setDesc('Use {{current}} and {{total}} as placeholders, e.g. "Page {{current}} of {{total}}", "{{current}}/{{total}}", or just "{{current}}".').addText(m=>m.setPlaceholder("{{current}} / {{total}}").setValue(r.pageNumberFormat).onChange(y=>{r.pageNumberFormat=y,this.markDirty()})),new N.Setting(e).setName("Page number start").setDesc("Number assigned to the first visible page number.").addText(m=>m.setValue(String(r.pageNumberStart)).onChange(y=>{r.pageNumberStart=parseInt(y,10)||1,this.markDirty()})),new N.Setting(e).setName("Behaviour").setHeading(),new N.Setting(e).setName("Hide frontmatter").setDesc("Strip the YAML frontmatter block (--- \u2026 ---) from the preview and exported PDF.").addToggle(m=>m.setValue(r.hideFrontmatter).onChange(y=>{r.hideFrontmatter=y,this.markDirty()})),new N.Setting(e).setName("Include file name as title").setDesc("Prepend the note's file name as an H1 heading at the top of the PDF.").addToggle(m=>m.setValue(r.includeFilenameAsTitle).onChange(y=>{r.includeFilenameAsTitle=y,this.markDirty()})),new N.Setting(e).setName("Underline links").setDesc("Applies to both internal and external links.").addToggle(m=>m.setValue(r.linkUnderline).onChange(y=>{r.linkUnderline=y,this.markDirty()})),new N.Setting(e).setName("Auto page break before H1").addToggle(m=>m.setValue(r.autoBreakH1).onChange(y=>{r.autoBreakH1=y,this.markDirty()})),new N.Setting(e).setName("Auto page break before H2").addToggle(m=>m.setValue(r.autoBreakH2).onChange(y=>{r.autoBreakH2=y,this.markDirty()})),new N.Setting(e).setName("H1 bottom border").addToggle(m=>m.setValue(r.h1BorderBottom).onChange(y=>{r.h1BorderBottom=y,this.markDirty()})),new N.Setting(e).setName("H2 bottom border").addToggle(m=>m.setValue(r.h2BorderBottom).onChange(y=>{r.h2BorderBottom=y,this.markDirty()})),new N.Setting(e).setName("Center H1").addToggle(m=>m.setValue(r.centerH1).onChange(y=>{r.centerH1=y,this.markDirty()})),new N.Setting(e).setName("Striped table rows").addToggle(m=>m.setValue(r.tableStriped).onChange(y=>{r.tableStriped=y,this.markDirty()})),new N.Setting(e).setName("Include PDF outline (bookmarks)").setDesc("Embeds a bookmark tree into the exported PDF. Most PDF readers display it in a side panel for quick navigation.").addToggle(m=>m.setValue(r.includeOutline).onChange(y=>{r.includeOutline=y,this.markDirty()}))}}; +`;try{let R=window,I=R.require("@electron/remote");if(!I?.dialog)throw new Error("no remote");let N=await I.dialog.showSaveDialog({title:"Save PDF",defaultPath:(this.currentFile?.basename??"export")+".pdf",filters:[{name:"PDF",extensions:["pdf"]}]});if(N.canceled||!N.filePath){r();return}new ze.Notice("Advanced PDF Export \u2014 generating PDF\u2026");let X=new Blob([A],{type:"text/html"}),te=URL.createObjectURL(X),L=new I.BrowserWindow({show:!1,webPreferences:{nodeIntegration:!1}});L.loadURL(te);let ue=!1,ye=()=>{URL.revokeObjectURL(te),L.close(),r()};L.webContents.once("did-fail-load",(oe,Fe,Ce)=>{ue||(ue=!0,new ze.Notice("Advanced PDF Export \u2014 failed to load page: "+Ce),ye())}),L.webContents.once("did-finish-load",()=>{ue||(ue=!0,L.webContents.executeJavaScript("document.fonts.ready.then(() => true)").catch(()=>!0).then(()=>{let oe=e.pageSize==="Custom";return L.webContents.printToPDF({pageSize:oe?"A4":e.pageSize,landscape:!oe&&e.orientation==="landscape",preferCSSPageSize:oe,printBackground:!0,margins:{marginType:"none"}})}).then(async oe=>{if(e.includeOutline)try{oe=await pd(oe,hd(o))}catch(Fe){console.warn("[advanced-pdf-export] outline injection failed:",Fe)}R.require("fs").writeFile(N.filePath,oe,Fe=>{Fe?new ze.Notice("Advanced PDF Export \u2014 failed to save: "+Fe.message):new ze.Notice("\u2713 PDF saved \u2014 "+N.filePath),ye()})}).catch(oe=>{new ze.Notice("Advanced PDF Export \u2014 failed to render: "+oe.message),ye()}))})}catch{new ze.Notice("Advanced PDF Export requires the Obsidian desktop app."),r()}}};var U=require("obsidian");var Qi=class extends U.PluginSettingTab{plugin;dirty=!1;constructor(e,r){super(e,r),this.plugin=r}display(){this.dirty=!1,this.buildSettings()}hide(){this.dirty&&(this.dirty=!1,this.plugin.activeModal?.render(!0))}async markDirty(){this.dirty=!0,await this.plugin.saveSettings()}buildSettings(){let{containerEl:e}=this;e.empty();let r=this.plugin.settings,n=(m,y,w,S)=>{let D=new U.Setting(e).setName(m);return S&&D.setDesc(S),D.addText(T=>T.setValue(String(r[y])).onChange(C=>{let E=parseInt(C,10)||0;r[y]=w!==void 0?Math.max(w,E):E,this.markDirty()}))},o=(m,y)=>new U.Setting(e).setName(m).addColorPicker(w=>w.setValue(r[y]).onChange(S=>{r[y]=S,this.markDirty()}));new U.Setting(e).setName("Style Preset").setHeading(),new U.Setting(e).setName("Preset").setDesc("Pick a preset to configure the overall document style. Fine-tune any setting below.").addDropdown(m=>{Object.entries(It).forEach(([y,w])=>{m.addOption(y,w.name)}),m.setValue(r.preset).onChange(y=>{this.plugin.applyPreset(y),this.markDirty().then(()=>{this.buildSettings()})})}).addButton(m=>m.setButtonText("Reset Preset").setTooltip("Reset current preset to its default values").onClick(()=>{this.plugin.applyPreset(r.preset,!0),this.markDirty().then(()=>{this.buildSettings()})})),new U.Setting(e).setName("Page").setHeading();let i;new U.Setting(e).setName("Page size").addDropdown(m=>{Object.keys(mr).forEach(y=>{m.addOption(y,y)}),m.addOption("Custom","Custom\u2026"),m.setValue(r.pageSize).onChange(y=>{r.pageSize=y,i.settingEl.toggleClass("mpdf-is-hidden",y!=="Custom"),this.markDirty()})}),i=new U.Setting(e).setName("Custom page size (mm)").setDesc("Width \xD7 Height in millimetres.").addText(m=>m.setPlaceholder("Width").setValue(String(r.customPageWidth)).onChange(y=>{r.customPageWidth=Math.max(10,parseFloat(y)||210),this.markDirty()})).addText(m=>m.setPlaceholder("Height").setValue(String(r.customPageHeight)).onChange(y=>{r.customPageHeight=Math.max(10,parseFloat(y)||297),this.markDirty()})),i.settingEl.toggleClass("mpdf-is-hidden",r.pageSize!=="Custom"),new U.Setting(e).setName("Orientation").addDropdown(m=>m.addOptions({portrait:"Portrait",landscape:"Landscape"}).setValue(r.orientation).onChange(y=>{r.orientation=y,this.markDirty()})),new U.Setting(e).setName("Margin & Frame").setHeading(),new U.Setting(e).setName("Margins").setDesc("Top \xB7 Bottom \xB7 Left \xB7 Right").addText(m=>m.setPlaceholder("Top").setValue(String(r.marginTop)).onChange(y=>{r.marginTop=parseInt(y,10)||0,this.markDirty()})).addText(m=>m.setPlaceholder("Bottom").setValue(String(r.marginBottom)).onChange(y=>{r.marginBottom=parseInt(y,10)||0,this.markDirty()})).addText(m=>m.setPlaceholder("Left").setValue(String(r.marginLeft)).onChange(y=>{r.marginLeft=parseInt(y,10)||0,this.markDirty()})).addText(m=>m.setPlaceholder("Right").setValue(String(r.marginRight)).onChange(y=>{r.marginRight=parseInt(y,10)||0,this.markDirty()}));let a,s,f,l,c=m=>{[a,s,f,l].forEach(y=>y.settingEl.toggleClass("mpdf-is-hidden",!m))};new U.Setting(e).setName("Enable frame").setDesc("Draws a border around the outer edge of every page.").addToggle(m=>m.setValue(r.frameEnabled).onChange(y=>{r.frameEnabled=y,c(y),this.markDirty()})),a=o("Frame color","frameColor"),s=n("Frame thickness (px)","frameThickness",1),f=n("Frame margin (px)","frameMargin",0,"Gap between the page edge and the frame, applied equally on all four sides."),l=new U.Setting(e).setName("Frame style").addDropdown(m=>m.addOptions({solid:"Solid",dashed:"Dashed",dotted:"Dotted",double:"Double",groove:"Groove",ridge:"Ridge"}).setValue(r.frameStyle).onChange(y=>{r.frameStyle=y,this.markDirty()})),c(r.frameEnabled),new U.Setting(e).setName("Typography").setHeading();let u;new U.Setting(e).setName("Font family").addDropdown(m=>m.addOptions({"Georgia, serif":"Georgia (Serif)","'Times New Roman', Times, serif":"Times New Roman","'Palatino Linotype', Palatino, serif":"Palatino","Arial, sans-serif":"Arial","'Helvetica Neue', Helvetica, sans-serif":"Helvetica","'Trebuchet MS', sans-serif":"Trebuchet","'Courier New', monospace":"Courier New",__custom__:"Custom\u2026"}).setValue(r.fontFamily).onChange(y=>{r.fontFamily=y,u.settingEl.toggleClass("mpdf-is-hidden",y!=="__custom__"),this.markDirty()})),u=new U.Setting(e).setName("Custom font name").setDesc('CSS font-family value \u2014 e.g. "Inter, sans-serif". The font must be installed on your system.').addText(m=>m.setPlaceholder("e.g. Inter, sans-serif").setValue(r.customFontName).onChange(y=>{r.customFontName=y,this.markDirty()})),u.settingEl.toggleClass("mpdf-is-hidden",r.fontFamily!=="__custom__"),new U.Setting(e).setName("Font size (px)").addDropdown(m=>{["10","11","12","13","14","15","16"].forEach(y=>{m.addOption(y,y+"px")}),m.setValue(String(r.fontSize)).onChange(y=>{r.fontSize=parseInt(y),this.markDirty()})}),new U.Setting(e).setName("Code font size").addDropdown(m=>m.addOptions({"0.75":"0.75em","0.80":"0.80em","0.82":"0.82em","0.85":"0.85em","0.88":"0.88em","0.90":"0.90em","1.0":"1.00em"}).setValue(String(r.codeFontSize)).onChange(y=>{r.codeFontSize=parseFloat(y),this.markDirty()})),new U.Setting(e).setName("Line height").addDropdown(m=>m.addOptions({"1.4":"Tight (1.4)","1.6":"Compact (1.6)","1.75":"Normal (1.75)","1.85":"Relaxed (1.85)","2.0":"Double (2.0)"}).setValue(String(r.lineHeight)).onChange(y=>{r.lineHeight=parseFloat(y),this.markDirty()})),new U.Setting(e).setName("Paragraph spacing").addDropdown(m=>m.addOptions({0:"None","0.3":"Tight (0.3em)","0.5":"Normal (0.5em)","0.65":"Relaxed (0.65em)","1.0":"Wide (1em)"}).setValue(String(r.paragraphSpacing)).onChange(y=>{r.paragraphSpacing=parseFloat(y),this.markDirty()})),new U.Setting(e).setName("Heading scale").setDesc("Multiplier applied to all heading sizes.").addDropdown(m=>m.addOptions({"0.8":"Small (0.8\xD7)","0.88":"0.88\xD7","0.9":"Compact (0.9\xD7)","0.95":"0.95\xD7","1.0":"Normal (1.0\xD7)","1.05":"1.05\xD7","1.1":"Large (1.1\xD7)","1.2":"XLarge (1.2\xD7)"}).setValue(String(r.headingScale)).onChange(y=>{r.headingScale=parseFloat(y),this.markDirty()})),new U.Setting(e).setName("Background").setHeading();let d,p,h,b,F,x=m=>{d.settingEl.toggleClass("mpdf-is-hidden",m),[p,h,b,F].forEach(y=>y.settingEl.toggleClass("mpdf-is-hidden",!m))};new U.Setting(e).setName("Use image background").setDesc("When on, a background image is used instead of the solid background color.").addToggle(m=>m.setValue(r.backgroundImageEnabled).onChange(y=>{r.backgroundImageEnabled=y,x(y),this.markDirty()})),d=new U.Setting(e).setName("Page background color").addColorPicker(m=>m.setValue(r.pageBackground).onChange(y=>{r.pageBackground=y,this.markDirty()})),p=new U.Setting(e).setName("Background image").setDesc("Vault-relative path or https:// URL.").addText(m=>m.setPlaceholder("assets/background.png").setValue(r.backgroundImagePath).onChange(y=>{r.backgroundImagePath=y,this.markDirty()})),h=new U.Setting(e).setName("Fit").addDropdown(m=>m.addOptions({cover:"Cover (fill, crop edges)",contain:"Contain (fit, show gaps)",fill:"Fill (stretch to exact size)",tile:"Tile (repeat)"}).setValue(r.backgroundImageSize).onChange(y=>{r.backgroundImageSize=y,this.markDirty()})),b=new U.Setting(e).setName("Scope").setDesc("Full page includes header and footer bands. Content area only restricts the background to the text zone between them.").addDropdown(m=>m.addOptions({"full-page":"Full page","content-only":"Content area only"}).setValue(r.backgroundImageScope).onChange(y=>{r.backgroundImageScope=y,this.markDirty()})),F=new U.Setting(e).setName("Opacity").addDropdown(m=>m.addOptions({"0.05":"5%","0.1":"10%","0.15":"15%","0.2":"20%","0.3":"30%","0.4":"40%","0.5":"50%","0.6":"60%","0.7":"70%","0.8":"80%","0.9":"90%",1:"100%"}).setValue(String(r.backgroundImageOpacity)).onChange(y=>{r.backgroundImageOpacity=parseFloat(y),this.markDirty()})),x(r.backgroundImageEnabled),new U.Setting(e).setName("Colors").setHeading(),o("Accent color","accentColor"),o("Body text color","bodyColor"),o("Heading color","headingColor"),o("Blockquote background","blockquoteBg"),o("Blockquote border","blockquoteBorderColor"),o("Table header background","tableHeaderBg"),o("Code background","codeBackground"),new U.Setting(e).setName("Code syntax theme").setDesc('Independent of your Obsidian theme. "None" uses the body text color and code background above with no highlighting.').addDropdown(m=>{let y={};for(let[w,S]of Object.entries(ti))y[w]=S.name;m.addOptions(y).setValue(r.codeTheme).onChange(w=>{r.codeTheme=w,this.markDirty()})}),new U.Setting(e).setName("Header").setHeading(),new U.Setting(e).setName("Show header").addToggle(m=>m.setValue(r.showHeader).onChange(y=>{r.showHeader=y,this.markDirty()})),new U.Setting(e).setName("Show on first page").setDesc("When off, the header is hidden on page 1. Useful for title pages.").addToggle(m=>m.setValue(r.showHeaderOnFirstPage).onChange(y=>{r.showHeaderOnFirstPage=y,this.markDirty()})),new U.Setting(e).setName("Header text").addText(m=>m.setValue(r.headerText).onChange(y=>{r.headerText=y,this.markDirty()})),new U.Setting(e).setName("Alignment").addDropdown(m=>m.addOptions({left:"Left",center:"Center",right:"Right"}).setValue(r.headerAlignment).onChange(y=>{r.headerAlignment=y,this.markDirty()})),n("Font size (px)","headerFontSize",1),n("Height (px)","headerHeight",0,"Explicit band height (0 = auto)."),o("Font color","headerFontColor"),new U.Setting(e).setName("Border").setDesc("Separator line below the header.").addToggle(m=>m.setValue(r.showHeaderBorder).onChange(y=>{r.showHeaderBorder=y,this.markDirty()})),new U.Setting(e).setName("Image").setDesc("Vault-relative path or https:// URL. Fills the header band as a background banner.").addText(m=>m.setPlaceholder("assets/header-banner.png").setValue(r.headerImagePath).onChange(y=>{r.headerImagePath=y,this.markDirty()})),n("Image left/right margin (px)","headerImageMargin",0,"Insets the banner from the left and right page edges."),new U.Setting(e).setName("Footer").setHeading(),new U.Setting(e).setName("Show footer").addToggle(m=>m.setValue(r.showFooter).onChange(y=>{r.showFooter=y,this.markDirty()})),new U.Setting(e).setName("Show on first page").setDesc("When off, the footer and page numbers are hidden on page 1. Page numbering starts from page 2.").addToggle(m=>m.setValue(r.showFooterOnFirstPage).onChange(y=>{r.showFooterOnFirstPage=y,this.markDirty()})),new U.Setting(e).setName("Footer text").addText(m=>m.setValue(r.footerText).onChange(y=>{r.footerText=y,this.markDirty()})),new U.Setting(e).setName("Alignment").addDropdown(m=>m.addOptions({left:"Left",center:"Center",right:"Right"}).setValue(r.footerTextAlignment).onChange(y=>{r.footerTextAlignment=y,this.markDirty()})),n("Font size (px)","footerFontSize",1),n("Height (px)","footerHeight",0,"Explicit band height (0 = auto)."),o("Font color","footerFontColor"),new U.Setting(e).setName("Border").setDesc("Separator line above the footer.").addToggle(m=>m.setValue(r.showFooterBorder).onChange(y=>{r.showFooterBorder=y,this.markDirty()})),new U.Setting(e).setName("Image").setDesc("Vault-relative path or https:// URL. Fills the footer band as a background banner.").addText(m=>m.setPlaceholder("assets/footer-banner.png").setValue(r.footerImagePath).onChange(y=>{r.footerImagePath=y,this.markDirty()})),n("Image left/right margin (px)","footerImageMargin",0,"Insets the banner from the left and right page edges."),new U.Setting(e).setName("Show page numbers").addToggle(m=>m.setValue(r.showPageNumbers).onChange(y=>{r.showPageNumbers=y,this.markDirty()})),new U.Setting(e).setName("Page number position").addDropdown(m=>m.addOptions({left:"Left",center:"Center",right:"Right"}).setValue(r.pageNumberPosition).onChange(y=>{r.pageNumberPosition=y,this.markDirty()})),new U.Setting(e).setName("Page number format").setDesc('Use {{current}} and {{total}} as placeholders, e.g. "Page {{current}} of {{total}}", "{{current}}/{{total}}", or just "{{current}}".').addText(m=>m.setPlaceholder("{{current}} / {{total}}").setValue(r.pageNumberFormat).onChange(y=>{r.pageNumberFormat=y,this.markDirty()})),new U.Setting(e).setName("Page number start").setDesc("Number assigned to the first visible page number.").addText(m=>m.setValue(String(r.pageNumberStart)).onChange(y=>{r.pageNumberStart=parseInt(y,10)||1,this.markDirty()})),new U.Setting(e).setName("Behaviour").setHeading(),new U.Setting(e).setName("Hide frontmatter").setDesc("Strip the YAML frontmatter block (--- \u2026 ---) from the preview and exported PDF.").addToggle(m=>m.setValue(r.hideFrontmatter).onChange(y=>{r.hideFrontmatter=y,this.markDirty()})),new U.Setting(e).setName("Include file name as title").setDesc("Prepend the note's file name as an H1 heading at the top of the PDF.").addToggle(m=>m.setValue(r.includeFilenameAsTitle).onChange(y=>{r.includeFilenameAsTitle=y,this.markDirty()})),new U.Setting(e).setName("Underline links").setDesc("Applies to both internal and external links.").addToggle(m=>m.setValue(r.linkUnderline).onChange(y=>{r.linkUnderline=y,this.markDirty()})),new U.Setting(e).setName("Auto page break before H1").addToggle(m=>m.setValue(r.autoBreakH1).onChange(y=>{r.autoBreakH1=y,this.markDirty()})),new U.Setting(e).setName("Auto page break before H2").addToggle(m=>m.setValue(r.autoBreakH2).onChange(y=>{r.autoBreakH2=y,this.markDirty()})),new U.Setting(e).setName("H1 bottom border").addToggle(m=>m.setValue(r.h1BorderBottom).onChange(y=>{r.h1BorderBottom=y,this.markDirty()})),new U.Setting(e).setName("H2 bottom border").addToggle(m=>m.setValue(r.h2BorderBottom).onChange(y=>{r.h2BorderBottom=y,this.markDirty()})),new U.Setting(e).setName("Center H1").addToggle(m=>m.setValue(r.centerH1).onChange(y=>{r.centerH1=y,this.markDirty()})),new U.Setting(e).setName("Striped table rows").addToggle(m=>m.setValue(r.tableStriped).onChange(y=>{r.tableStriped=y,this.markDirty()})),new U.Setting(e).setName("Include PDF outline (bookmarks)").setDesc("Embeds a bookmark tree into the exported PDF. Most PDF readers display it in a side panel for quick navigation.").addToggle(m=>m.setValue(r.includeOutline).onChange(y=>{r.includeOutline=y,this.markDirty()}))}};var _i=class extends $i.Plugin{activeModal=null;presetSnapshots={};async onload(){await this.loadSettings(),Ys(this.app),this.addCommand({id:"open-panel",name:"Open Panel",callback:()=>this.openModal()}),this.registerEvent(this.app.workspace.on("file-menu",(e,r)=>{!(r instanceof $i.TFile)||r.extension!=="md"||e.addItem(n=>n.setTitle("Advanced PDF Export: Open Panel").setIcon("file-output").onClick(()=>this.openModal(r)))})),this.addSettingTab(new Qi(this.app,this))}onunload(){this.activeModal?.close()}openModal(e){this.activeModal&&this.activeModal.close(),new Ji(this.app,this,e).open()}async loadSettings(){let e=await this.loadData()??{};this.settings=Object.assign({},ei,e),e.codeTheme===void 0&&(this.settings.codeTheme=It[this.settings.preset]?.codeTheme??ei.codeTheme),this.presetSnapshots=e.presetSnapshots??{},this.validateSettings()}validateSettings(){let e=this.settings;e.preset in It||(console.warn(`[advanced-pdf-export] Unknown preset "${e.preset}", resetting to "default".`),e.preset="default"),e.fontSize=Math.max(1,e.fontSize),e.headerFontSize=Math.max(1,e.headerFontSize),e.footerFontSize=Math.max(1,e.footerFontSize),e.marginTop=Math.max(0,e.marginTop),e.marginBottom=Math.max(0,e.marginBottom),e.marginLeft=Math.max(0,e.marginLeft),e.marginRight=Math.max(0,e.marginRight),e.customPageWidth=Math.max(10,e.customPageWidth),e.customPageHeight=Math.max(10,e.customPageHeight),e.previewScale=Math.max(.1,Math.min(3,e.previewScale)),e.pageNumberStart=Math.max(1,e.pageNumberStart),(!e.pageNumberFormat||!e.pageNumberFormat.trim())&&(e.pageNumberFormat=ei.pageNumberFormat)}async saveSettings(){await this.saveData({...this.settings,presetSnapshots:this.presetSnapshots})}async saveSettingsAndRender(){await this.saveSettings(),this.activeModal?.render()}applyPreset(e,r=!1){let n=It[e];n&&(r?delete this.presetSnapshots[e]:this.presetSnapshots[this.settings.preset]=Ls(this.settings),this.settings.preset=e,Object.assign(this.settings,n,r?{}:this.presetSnapshots[e]??{}))}}; /*! Bundled license information: tslib/tslib.es6.js: diff --git a/main.ts b/main.ts deleted file mode 100644 index 4478263..0000000 --- a/main.ts +++ /dev/null @@ -1,3287 +0,0 @@ -import { - App, Component, MarkdownRenderer, MarkdownView, Menu, Modal, Notice, - Plugin, PluginSettingTab, Setting, TFile, requestUrl, setIcon, - finishRenderMath, -} from "obsidian"; -import { PDFArray, PDFDict, PDFDocument, PDFHexString, PDFName, PDFNull, PDFNumber } from "pdf-lib"; - -// ─── Constants ──────────────────────────────────────────────────────────────── - -const PAGE_SIZES: Record = { - A4: { w: 794, h: 1123 }, - A3: { w: 1123, h: 1587 }, - Letter: { w: 816, h: 1056 }, - Legal: { w: 816, h: 1344 }, - A5: { w: 559, h: 794 }, -}; - -// ─── Interfaces ─────────────────────────────────────────────────────────────── - -interface DocStyle { - name: string; - fontFamily: string; - fontSize: number; - lineHeight: number; - paragraphSpacing: number; - headingScale: number; - accentColor: string; - bodyColor: string; - headingColor: string; - h1BorderBottom: boolean; - h2BorderBottom: boolean; - centerH1: boolean; - blockquoteBg: string; - blockquoteBorderColor: string; - codeBackground: string; - codeFontSize: number; - codeTheme: string; - tableHeaderBg: string; - tableStriped: boolean; - pageBackground: string; - marginTop: number; - marginBottom: number; - marginLeft: number; - marginRight: number; -} - -// Minimal Electron type shims — just enough for the PDF export path. - -interface ElectronBrowserWindow { - loadURL(url: string): void; - close(): void; - webContents: { - once(event: "did-fail-load", listener: (event: unknown, code: number, desc: string) => void): void; - once(event: "did-finish-load", listener: () => void): void; - executeJavaScript(code: string): Promise; - printToPDF(options: { - pageSize: string; - landscape: boolean; - printBackground: boolean; - preferCSSPageSize?: boolean; - margins: { marginType: string }; - }): Promise; - }; -} - -interface ElectronRemote { - dialog: { - showSaveDialog(options: { - title: string; - defaultPath: string; - filters: { name: string; extensions: string[] }[]; - }): Promise<{ canceled: boolean; filePath?: string }>; - }; - BrowserWindow: new (options: { - show: boolean; - webPreferences: { nodeIntegration: boolean }; - }) => ElectronBrowserWindow; -} - -interface ElectronFs { - writeFile(path: string, data: Uint8Array, cb: (err: Error | null) => void): void; -} - -interface ElectronBridge { - require(module: "@electron/remote"): ElectronRemote; - require(module: "fs"): ElectronFs; - require(module: string): unknown; -} - -/** One entry in the PDF outline/bookmark tree, extracted from the heading nodes. */ -interface OutlineEntry { - title: string; - level: number; // 1–6 matching H1–H6 - page: number; // 1-indexed page number in the exported PDF -} - -interface AppWithSettings { - setting?: { - open?: () => void; - openTabById?: (id: string) => void; - }; -} - -interface PDFExportSettings extends DocStyle { - pageSize: string; - orientation: "portrait" | "landscape"; - preset: string; - headerText: string; - footerText: string; - showHeader: boolean; - showFooter: boolean; - showHeaderBorder: boolean; - showFooterBorder: boolean; - showPageNumbers: boolean; - pageNumberPosition: "center" | "left" | "right"; - pageNumberStart: number; - /** Template for rendering the page number string. Supports {{current}} - * and {{total}} placeholders, e.g. "Page {{current}} of {{total}}". */ - pageNumberFormat: string; - showHeaderOnFirstPage: boolean; - showFooterOnFirstPage: boolean; - headerAlignment: "left" | "center" | "right"; - footerTextAlignment: "left" | "center" | "right"; - headerFontSize: number; - headerFontColor: string; - footerFontSize: number; - footerFontColor: string; - linkUnderline: boolean; - frameEnabled: boolean; - frameColor: string; - frameThickness: number; - frameMargin: number; - frameStyle: "solid" | "dashed" | "dotted" | "double" | "groove" | "ridge"; - hideFrontmatter: boolean; - customFontName: string; - autoBreakH1: boolean; - autoBreakH2: boolean; - includeFilenameAsTitle: boolean; - previewScale: number; - /** Width in mm, used only when pageSize === "Custom". */ - customPageWidth: number; - /** Height in mm, used only when pageSize === "Custom". */ - customPageHeight: number; - - // ── Header/footer band sizing ───────────────────────────────────────────────── - /** Explicit header band height in px. 0 = auto (derived from headerFontSize). */ - headerHeight: number; - /** Explicit footer band height in px. 0 = auto (derived from footerFontSize). */ - footerHeight: number; - - // ── Header/footer banner images ────────────────────────────────────────────── - /** Vault-relative path or https:// URL for a banner image behind the header text. */ - headerImagePath: string; - /** Left/right gap in px between the banner image and the page edges (0 = edge-to-edge). */ - headerImageMargin: number; - footerImagePath: string; - /** Left/right gap in px between the banner image and the page edges. */ - footerImageMargin: number; - - // ── Page background (color OR image — mutually exclusive) ───────────────────── - /** When true, backgroundImagePath is used instead of the pageBackground color. */ - backgroundImageEnabled: boolean; - backgroundImagePath: string; - /** How the image fills the background zone. */ - backgroundImageSize: "cover" | "contain" | "fill" | "tile"; - /** "full-page": behind header+content+footer. "content-only": text zone only. */ - backgroundImageScope: "full-page" | "content-only"; - /** 0–1 opacity for the background image layer. */ - backgroundImageOpacity: number; - /** When true, headings H1–H6 are embedded as a bookmark tree in the exported PDF. */ - includeOutline: boolean; -} - -// Cached layout — holds everything drawPreview and exportPDF need so that -// zoom changes can redraw without re-paginating. -interface LayoutCache { - layouts: PageLayout[]; - pw: number; - ph: number; - mTop: number; - mLeft: number; - mRight: number; - footerH: number; - headerH: number; - contentW: number; - contentH: number; - docCSS: string; - fontFamily: string; - accentColor: string; - pageBackground: string; - isRTL: boolean; -} - -interface PageLayout { - pageNodes: HTMLElement[]; - pageNum: number; - totalPages: number; - pageShowsHeader: boolean; - pageShowsFooter: boolean; - hasHeader: boolean; - hasFooter: boolean; - headerLeft: string; - headerCenter: string; - headerRight: string; - footerLeft: string; - footerRight: string; - footerCenter: string; -} - -// ─── Style Presets ──────────────────────────────────────────────────────────── - -const PRESETS: Record = { - default: { - name: "Default", - fontFamily: "Georgia, serif", - fontSize: 13, - lineHeight: 1.85, - paragraphSpacing: 0.65, - headingScale: 1.0, - accentColor: "#7c6af7", - bodyColor: "#1a1a2e", - headingColor: "#0d0d1a", - h1BorderBottom: false, - h2BorderBottom: true, - centerH1: false, - blockquoteBg: "transparent", - blockquoteBorderColor: "#7c6af7", - codeBackground: "#f0f0f8", - codeFontSize: 0.85, - codeTheme: "github-light", - tableHeaderBg: "#f0f0f8", - tableStriped: true, - pageBackground: "#ffffff", - marginTop: 20, marginBottom: 20, marginLeft: 25, marginRight: 25, - }, - minimal: { - name: "Minimal", - fontFamily: "'Helvetica Neue', Helvetica, sans-serif", - fontSize: 12, - lineHeight: 1.6, - paragraphSpacing: 0.45, - headingScale: 0.88, - accentColor: "#333", - bodyColor: "#222", - headingColor: "#111", - h1BorderBottom: false, - h2BorderBottom: false, - centerH1: false, - blockquoteBg: "#f8f8f8", - blockquoteBorderColor: "#ccc", - codeBackground: "#f4f4f4", - codeFontSize: 0.82, - codeTheme: "none", - tableHeaderBg: "#efefef", - tableStriped: false, - pageBackground: "#ffffff", - marginTop: 16, marginBottom: 16, marginLeft: 20, marginRight: 20, - }, - academic: { - name: "Academic", - fontFamily: "'Times New Roman', Times, serif", - fontSize: 12, - lineHeight: 2.0, - paragraphSpacing: 0.0, - headingScale: 0.95, - accentColor: "#1a3a6b", - bodyColor: "#000", - headingColor: "#000", - h1BorderBottom: true, - h2BorderBottom: true, - centerH1: true, - blockquoteBg: "transparent", - blockquoteBorderColor: "#999", - codeBackground: "#f9f9f9", - codeFontSize: 0.88, - codeTheme: "solarized-light", - tableHeaderBg: "#e8e8e8", - tableStriped: false, - pageBackground: "#ffffff", - marginTop: 25, marginBottom: 25, marginLeft: 30, marginRight: 30, - }, - colorful: { - name: "Colorful", - fontFamily: "Georgia, serif", - fontSize: 13, - lineHeight: 1.85, - paragraphSpacing: 0.65, - headingScale: 1.05, - accentColor: "#e84393", - bodyColor: "#1a1a2e", - headingColor: "#2d0a4e", - h1BorderBottom: false, - h2BorderBottom: false, - centerH1: false, - blockquoteBg: "#fdf0f8", - blockquoteBorderColor: "#e84393", - codeBackground: "#f0eaff", - codeFontSize: 0.85, - codeTheme: "dracula", - tableHeaderBg: "#2d0a4e", - tableStriped: true, - pageBackground: "#ffffff", - marginTop: 20, marginBottom: 20, marginLeft: 25, marginRight: 25, - }, - modern: { - name: "Modern", - fontFamily: "Arial, sans-serif", - fontSize: 13, - lineHeight: 1.75, - paragraphSpacing: 0.6, - headingScale: 1.0, - accentColor: "#0070f3", - bodyColor: "#111", - headingColor: "#000", - h1BorderBottom: false, - h2BorderBottom: false, - centerH1: false, - blockquoteBg: "#f0f7ff", - blockquoteBorderColor: "#0070f3", - codeBackground: "#f1f5f9", - codeFontSize: 0.85, - codeTheme: "github-dark", - tableHeaderBg: "#0070f3", - tableStriped: true, - pageBackground: "#ffffff", - marginTop: 20, marginBottom: 20, marginLeft: 25, marginRight: 25, - }, - newspaper: { - name: "Newspaper", - fontFamily: "Georgia, serif", - fontSize: 12, - lineHeight: 1.7, - paragraphSpacing: 0.4, - headingScale: 1.1, - accentColor: "#111", - bodyColor: "#111", - headingColor: "#000", - h1BorderBottom: true, - h2BorderBottom: true, - centerH1: true, - blockquoteBg: "transparent", - blockquoteBorderColor: "#111", - codeBackground: "#f4f4f4", - codeFontSize: 0.82, - codeTheme: "none", - tableHeaderBg: "#111", - tableStriped: false, - pageBackground: "#ffffff", - marginTop: 18, marginBottom: 18, marginLeft: 20, marginRight: 20, - }, - dark: { - name: "Dark", - fontFamily: "Georgia, serif", - fontSize: 13, - lineHeight: 1.85, - paragraphSpacing: 0.65, - headingScale: 1.0, - accentColor: "#818cf8", - bodyColor: "#d1d5db", - headingColor: "#f1f5f9", - h1BorderBottom: false, - h2BorderBottom: true, - centerH1: false, - blockquoteBg: "#1e293b", - blockquoteBorderColor: "#818cf8", - codeBackground: "#0f172a", - codeFontSize: 0.85, - codeTheme: "tokyo-night", - tableHeaderBg: "#1e293b", - tableStriped: true, - pageBackground: "#111827", - marginTop: 20, marginBottom: 20, marginLeft: 25, marginRight: 25, - }, -}; - -const DEFAULT_SETTINGS: PDFExportSettings = { - pageSize: "A4", - orientation: "portrait", - preset: "default", - ...PRESETS["default"], - headerText: "", - footerText: "", - showHeader: true, - showFooter: true, - showHeaderBorder: false, - showFooterBorder: false, - showPageNumbers: true, - pageNumberPosition: "right", - pageNumberStart: 1, - pageNumberFormat: "{{current}} / {{total}}", - showHeaderOnFirstPage: true, - showFooterOnFirstPage: true, - headerAlignment: "right", - footerTextAlignment: "left", - headerFontSize: 9, - headerFontColor: "#999999", - footerFontSize: 9, - footerFontColor: "#aaaaaa", - linkUnderline: true, - frameEnabled: false, - frameColor: "#000000", - frameThickness: 4, - frameMargin: 8, - frameStyle: "solid", - hideFrontmatter: false, - customFontName: "", - autoBreakH1: false, - autoBreakH2: false, - includeFilenameAsTitle: false, - previewScale: 0.9, - customPageWidth: 210, // A4 width in mm - customPageHeight: 297, // A4 height in mm - // Band sizing (0 = auto from font size) - headerHeight: 0, - footerHeight: 0, - // Banner images (header / footer background) - headerImagePath: "", - headerImageMargin: 0, - footerImagePath: "", - footerImageMargin: 0, - // Page background - backgroundImageEnabled: false, - backgroundImagePath: "", - backgroundImageSize: "cover", - backgroundImageScope: "full-page", - backgroundImageOpacity: 1, - // Outline / bookmarks - includeOutline: true, -}; - -// ─── Utilities ──────────────────────────────────────────────────────────────── - -/** mm → px at 96 dpi, matching Electron's print pipeline. */ -const mmToPx = (mm: number) => (mm / 25.4) * 96; - -/** - * Returns the page dimensions in px for the current settings. - * For "Custom", converts the user-entered mm values; for named sizes, looks up - * PAGE_SIZES directly. Orientation swapping is handled by callers (doRender). - */ -function resolvePageDims(s: PDFExportSettings): { w: number; h: number } { - if (s.pageSize === "Custom") { - return { - w: Math.max(1, Math.round(mmToPx(s.customPageWidth))), - h: Math.max(1, Math.round(mmToPx(s.customPageHeight))), - }; - } - return PAGE_SIZES[s.pageSize] ?? PAGE_SIZES["A4"]; -} - -function escapeHTML(s: string): string { - return s - .replace(/&/g, "&") - .replace(//g, ">") - .replace(/"/g, """) - .replace(/'/g, "'"); -} - -// Escapes ` block early, regardless of where the sequence appears. -function escapeCSSForStyle(css: string): string { - return css.replace(/<\/style/gi, "<\\/style"); -} - -/** Converts a vault-relative path or bare filename to an app:// resource URL, - * or passes https:// / data: URLs through unchanged. Returns "" for blank input. */ -function resolveImageUrl(app: App, imagePath: string): string { - const trimmed = imagePath.trim(); - if (!trimmed) return ""; - if (/^(https?:|data:)/i.test(trimmed)) return trimmed; - const direct = app.vault.getAbstractFileByPath(trimmed); - if (direct instanceof TFile) return app.vault.getResourcePath(direct); - const resolved = app.metadataCache.getFirstLinkpathDest(trimmed, ""); - if (resolved instanceof TFile) return app.vault.getResourcePath(resolved); - console.warn("[advanced-pdf-export] Could not resolve image path:", trimmed); - return trimmed; -} - -/** Maps a `backgroundImageSize` setting value to its CSS `background-size` - * and `background-repeat` values. Centralises logic that would otherwise be - * duplicated across the preview and export render paths. */ -function bgImageCssProps(size: PDFExportSettings["backgroundImageSize"]): { size: string; repeat: string } { - return { - size: size === "fill" ? "100% 100%" : size === "tile" ? "auto" : size, // "cover" | "contain" pass through - repeat: size === "tile" ? "repeat" : "no-repeat", - }; -} - -/** True when RTL script chars (Arabic, Hebrew, etc.) exceed 10 % of all - * alpha chars — ratio-based so mixed-script notes lean toward the majority. */ -const RTL_CHARS = /[\u0590-\u08FF\uFB1D-\uFDFD\uFE70-\uFEFC]/g; -const TOTAL_ALPHA = /[A-Za-z\u0590-\u08FF\uFB1D-\uFDFD\uFE70-\uFEFC]/g; -function isRTLContent(text: string): boolean { - const rtl = (text.match(RTL_CHARS) ?? []).length; - const total = (text.match(TOTAL_ALPHA) ?? []).length; - return total > 0 && rtl / total > 0.1; -} - -// ─── Markdown helpers ───────────────────────────────────────────────────────── - -/** Normalises line endings to LF so the rest of the pipeline never sees CRLF or CR. */ -function normalizeMarkdown(raw: string): string { - return raw.replace(/\r\n|\r/g, "\n"); -} - -/** Strips an opening YAML frontmatter block (--- … ---). Input must be LF-normalised. */ -function stripFrontmatter(md: string): string { - return md.replace(/^---[ \t]*\n[\s\S]*?\n---[ \t]*(\n|$)/, ""); -} - -/** Splits on `///` manual page-break markers, trimming and dropping empty sections. */ -function splitMarkdownSections(md: string): string[] { - return md - .split(/^\/\/\/\s*$/m) - .map((s) => s.trim()) - .filter(Boolean); -} - -/** Fires MathJax's one-time cold-start boot and `adaptiveCSS` setup for the - * font families most often missing on a session's first real render (bold, - * AMS symbols, blackboard-bold, fraktur, calligraphic, sans-serif, - * typewriter, vector) as soon as the plugin loads, in the background — - * rather than paying that cost the first time the user actually renders. - * - * Deliberately goes through the same `renderMarkdownToEl` pipeline used for - * real renders instead of calling `renderMath()`/`finishRenderMath()` - * directly: Obsidian only creates its global `MathJax` object lazily, the - * first time something is typeset through its markdown post-processor - * pipeline. Calling `renderMath()` directly before that has happened throws - * `ReferenceError: MathJax is not defined` instead of triggering the load. - * - * Fire-and-forget: nothing downstream awaits this, and the real render path - * still verifies completion correctly on its own regardless of whether this - * has finished. */ -async function warmUpMathJax(app: App): Promise { - const component = new Component(); - component.load(); - try { - await renderMarkdownToEl( - app, - "$\\mathbf{A}+\\mathfrak{A}+\\mathcal{A}+\\mathsf{A}+\\mathtt{A}+\\mathbb{A}+\\aleph+\\vec{v}$", - "", - component, - ); - } catch (err) { - console.warn("[advanced-pdf-export] MathJax warm-up failed (non-fatal):", err); - } finally { - component.unload(); - } -} - -async function renderMarkdownToEl( - app: App, - markdown: string, - sourcePath: string, - component: Component, -): Promise { - const temp = activeDocument.createElement("div"); - // Attached offscreen so Obsidian's async post-processors (mermaid, math) run in a real DOM context. - temp.setCssStyles({ position: "fixed", top: "0", left: "-99999px", visibility: "hidden", pointerEvents: "none" }); - activeDocument.body.appendChild(temp); - try { - await MarkdownRenderer.render(app, markdown, temp, sourcePath, component); - // Flushes Obsidian's MathJax render queue — MarkdownRenderer.render()'s own - // promise can resolve before queued math has actually finished typesetting. - // Bounded with a race: on a cold Obsidian session (MathJax not yet used - // anywhere in this window), this has been observed to hang far longer than - // expected instead of resolving, blocking the whole render indefinitely. - // waitForMathRendering()/waitForMathJaxStylesheetStable() below are the - // real, already-bounded correctness check regardless of whether this - // resolves in time — so there's no harm in giving up on it early. - const FINISH_RENDER_MATH_TIMEOUT_MS = 3000; - try { - let timer: number; - await Promise.race([ - finishRenderMath().finally(() => window.clearTimeout(timer)), - new Promise((resolve) => { timer = window.setTimeout(resolve, FINISH_RENDER_MATH_TIMEOUT_MS); }), - ]); - } catch (err) { - console.warn("[advanced-pdf-export] finishRenderMath failed:", err); - } - await waitForMermaidDiagrams(temp); - await waitForMathRendering(temp); - // Wait for MathJax's lazily-loaded @font-face files to arrive before we - // clone nodes; glyphs in unloaded font ranges render as invisible characters. - const docFonts = (activeDocument as Document & { fonts?: { ready?: Promise } }).fonts; - if (docFonts) { - try { await docFonts.ready; } catch { /* non-critical */ } - } - } finally { - activeDocument.body.removeChild(temp); - } - postProcessRenderedHTML(temp); - return temp; -} - -// Pre-compiled once. String.replace() and String.matchAll() both reset a -// regex's lastIndex to 0 on each call, so module-level g-flagged constants are safe. -const SLUG_STRIP = /[^\p{L}\p{N}\s-]/gu; -const SLUG_SPACE = /\s+/g; -const SLUG_DASH = /-+/g; - -function slugifyHeading(text: string): string { - return text - .toLowerCase() - .replace(SLUG_STRIP, "") - .trim() - .replace(SLUG_SPACE, "-") - .replace(SLUG_DASH, "-"); -} - -// Strips Obsidian-specific artefacts from rendered HTML so the output is -// clean for pagination and export: assigns stable heading IDs for anchor -// links, removes external-link decorators and copy-code buttons, force-expands -// callouts, and strips top-level theme `, and are not needed in the PDF. - // Styles inside are kept: mermaid embeds its theme CSS directly there. - root.querySelectorAll("style, script").forEach((el) => { - if (!el.closest("svg")) el.remove(); - }); -} - -/** Waits for mermaid code blocks to be converted to SVGs by Obsidian's post-processor. - * Resolves immediately if already rendered; times out per diagram after 5 s. */ -async function waitForMermaidDiagrams(el: HTMLElement): Promise { - const containers = Array.from(el.querySelectorAll(".mermaid")); - if (containers.length === 0) return; - const TIMEOUT_MS = 5000; - await Promise.all( - containers.map( - (m) => - new Promise((resolve) => { - if (m.querySelector("svg")) { resolve(); return; } - const timer = window.setTimeout(() => { obs.disconnect(); resolve(); }, TIMEOUT_MS); - const obs = new MutationObserver(() => { - if (m.querySelector("svg")) { - window.clearTimeout(timer); - obs.disconnect(); - resolve(); - } - }); - obs.observe(m, { childList: true, subtree: true }); - }), - ), - ); -} - -/** Waits for MathJax to finish typesetting `.math` spans (native math and - * Latex Suite equations share the same renderer). - * - * `MathJax.startup.promise` is awaited first as a cheap early gate — it - * resolves once, at MathJax's initial boot, so it proves nothing about - * whether this particular render pass is finished. The real wait is a - * per-element `mjx-container` observer, followed by - * `waitForMathJaxStylesheetStable()`: MathJax's CHTML `adaptiveCSS` mode - * writes per-glyph rules to a shared stylesheet incrementally as new - * characters are encountered, and DOM insertion of `mjx-container` alone - * doesn't guarantee that write has landed yet. Bounded at 8s + 2.5s so a - * stuck render can't hang the export indefinitely. */ -async function waitForMathRendering(el: HTMLElement): Promise { - const containers = Array.from(el.querySelectorAll(".math")); - if (containers.length === 0) return; - - const mathJax = (window as unknown as { - MathJax?: { startup?: { promise?: Promise } }; - }).MathJax; - if (mathJax?.startup?.promise) { - try { await mathJax.startup.promise; } catch { /* fall through to per-element wait */ } - } - - const TIMEOUT_MS = 8000; - await Promise.all( - containers - .filter((m) => !m.querySelector("mjx-container")) - .map( - (m) => - new Promise((resolve) => { - const timer = window.setTimeout(() => { obs.disconnect(); resolve(); }, TIMEOUT_MS); - const obs = new MutationObserver(() => { - if (m.querySelector("mjx-container")) { - window.clearTimeout(timer); - obs.disconnect(); - resolve(); - } - }); - obs.observe(m, { childList: true, subtree: true }); - }), - ), - ); - - await waitForMathJaxStylesheetStable(); -} - -/** Polls `getMathJaxCSS()`'s output size until it stops changing for two - * consecutive checks, confirming MathJax's `adaptiveCSS` has finished writing - * per-glyph rules for this render pass — DOM insertion of `mjx-container` - * alone doesn't guarantee that. Bounded by MAX_WAIT_MS so an already-settled - * stylesheet doesn't stall the export; resolves in ~2 polls in that case. */ -async function waitForMathJaxStylesheetStable(): Promise { - const POLL_MS = 60; - const STABLE_ROUNDS = 2; - const MAX_WAIT_MS = 2500; - - const start = Date.now(); - let lastLen = getMathJaxCSS().length; - let stableRounds = 0; - - while (stableRounds < STABLE_ROUNDS && Date.now() - start < MAX_WAIT_MS) { - await new Promise((resolve) => window.setTimeout(resolve, POLL_MS)); - const len = getMathJaxCSS().length; - if (len === lastLen) { - stableRounds++; - } else { - stableRounds = 0; - lastLen = len; - } - } -} - -// ─── Code block syntax highlighting ──────────────────────────────────────── -// Obsidian highlights fenced code with Prism `.token.` spans, but the -// theme CSS that colours them is stripped for export — colours are reapplied -// here independently via the same classes. - -type TokenGroup = - | "comment" | "punctuation" | "property" | "selector" - | "operator" | "keyword" | "function" | "regex"; - -// Groups Prism's token classes into the small set of categories most colour -// schemes distinguish. Multiple Prism classes commonly share one colour. -const TOKEN_GROUP_CLASSES: Record = { - comment: ["comment", "prolog", "doctype", "cdata"], - punctuation: ["punctuation"], - property: ["property", "tag", "boolean", "number", "constant", "symbol", "deleted", "attr-name"], - selector: ["selector", "string", "char", "builtin", "inserted", "attr-value"], - operator: ["operator", "entity", "url"], - keyword: ["atrule", "keyword", "important"], - function: ["function", "class-name"], - regex: ["regex", "variable"], -}; - -interface CodeColorTheme { - name: string; - /** `
` background. Falls back to the doc style's "Code background" when unset. */
-  background?: string;
-  /** Base `
` text color. Falls back to the doc style's "Body text color" when unset. */
-  text?: string;
-  tokens?: Partial>;
-}
-
-const CODE_THEMES: Record = {
-  none: { name: "None (plain)" },
-  "github-light": {
-    name: "GitHub Light",
-    background: "#f6f8fa", text: "#24292e",
-    tokens: {
-      comment: "#6a737d", punctuation: "#24292e", property: "#005cc5",
-      selector: "#032f62", operator: "#d73a49", keyword: "#d73a49",
-      function: "#6f42c1", regex: "#032f62",
-    },
-  },
-  "github-dark": {
-    name: "GitHub Dark",
-    background: "#0d1117", text: "#c9d1d9",
-    tokens: {
-      comment: "#8b949e", punctuation: "#c9d1d9", property: "#79c0ff",
-      selector: "#a5d6ff", operator: "#ff7b72", keyword: "#ff7b72",
-      function: "#d2a8ff", regex: "#a5d6ff",
-    },
-  },
-  "atom-one-light": {
-    name: "Atom One Light",
-    background: "#fafafa", text: "#383a42",
-    tokens: {
-      comment: "#a0a1a7", punctuation: "#383a42", property: "#986801",
-      selector: "#50a14f", operator: "#0184bc", keyword: "#a626a4",
-      function: "#4078f2", regex: "#50a14f",
-    },
-  },
-  "atom-one-dark": {
-    name: "Atom One Dark",
-    background: "#282c34", text: "#abb2bf",
-    tokens: {
-      comment: "#5c6370", punctuation: "#abb2bf", property: "#d19a66",
-      selector: "#98c379", operator: "#56b6c2", keyword: "#c678dd",
-      function: "#61afef", regex: "#98c379",
-    },
-  },
-  monokai: {
-    name: "Monokai",
-    background: "#272822", text: "#f8f8f2",
-    tokens: {
-      comment: "#75715e", punctuation: "#f8f8f2", property: "#ae81ff",
-      selector: "#e6db74", operator: "#f92672", keyword: "#f92672",
-      function: "#a6e22e", regex: "#e6db74",
-    },
-  },
-  dracula: {
-    name: "Dracula",
-    background: "#282a36", text: "#f8f8f2",
-    tokens: {
-      comment: "#6272a4", punctuation: "#f8f8f2", property: "#bd93f9",
-      selector: "#f1fa8c", operator: "#ff79c6", keyword: "#ff79c6",
-      function: "#50fa7b", regex: "#ff79c6",
-    },
-  },
-  "tokyo-night": {
-    name: "Tokyo Night",
-    background: "#1a1b26", text: "#a9b1d6",
-    tokens: {
-      comment: "#565f89", punctuation: "#89ddff", property: "#ff9e64",
-      selector: "#9ece6a", operator: "#89ddff", keyword: "#bb9af7",
-      function: "#7aa2f7", regex: "#b4f9f8",
-    },
-  },
-  "solarized-light": {
-    name: "Solarized Light",
-    background: "#fdf6e3", text: "#586e75",
-    tokens: {
-      comment: "#93a1a1", punctuation: "#586e75", property: "#cb4b16",
-      selector: "#2aa198", operator: "#859900", keyword: "#859900",
-      function: "#268bd2", regex: "#2aa198",
-    },
-  },
-  "catppuccin-macchiato": {
-    name: "Catppuccin Macchiato",
-    background: "#24273a", text: "#cad3f5",
-    tokens: {
-      comment: "#939ab7", punctuation: "#b8c0e0", property: "#f5a97f",
-      selector: "#a6da95", operator: "#91d7e3", keyword: "#c6a0f6",
-      function: "#8aadf4", regex: "#f5bde6",
-    },
-  },
-  "catppuccin-mocha": {
-    name: "Catppuccin Mocha",
-    background: "#1e1e2e", text: "#cdd6f4",
-    tokens: {
-      comment: "#9399b2", punctuation: "#bac2de", property: "#fab387",
-      selector: "#a6e3a1", operator: "#89dceb", keyword: "#cba6f7",
-      function: "#89b4fa", regex: "#f5c2e7",
-    },
-  },
-};
-
-/** Builds the `
`/`
` rules plus Prism `.token.*` colour mappings
- *  for the selected code theme. "None" keeps the previous plain styling
- *  (code background + body color, no token colours). */
-function buildCodeBlockCSS(s: PDFExportSettings): string {
-  const theme = CODE_THEMES[s.codeTheme] ?? CODE_THEMES.none;
-  const background = theme.background ?? s.codeBackground;
-  const text = theme.text ?? s.bodyColor;
-
-  const tokenRules = Object.entries(theme.tokens ?? {})
-    .map(([group, color]) => {
-      const selector = TOKEN_GROUP_CLASSES[group as TokenGroup]
-        .map((cls) => `.mpdf-doc pre code .token.${cls}`)
-        .join(", ");
-      const italic = group === "comment" ? " font-style: italic;" : "";
-      return `${selector} { color: ${color};${italic} }`;
-    })
-    .join("\n  ");
-
-  return `
-  .mpdf-doc pre {
-    background: ${background};
-    border-radius: 4px;
-    padding: 10px 12px;
-    margin: 0 0 ${s.paragraphSpacing}em;
-    overflow: hidden;
-  }
-  .mpdf-doc pre code {
-    font-family: 'Courier New', monospace;
-    font-size: ${s.codeFontSize}em;
-    color: ${text};
-    white-space: pre-wrap;
-    overflow-wrap: break-word;
-    background: none;
-    padding: 0;
-  }
-  ${tokenRules}`;
-}
-
-// ─── CSS generator ────────────────────────────────────────────────────────────
-
-/** Returns relative luminance (0–1) of a CSS hex color; non-hex values return 1 (treat as light). */
-function hexLuminance(hex: string): number {
-  const full = hex.replace(
-    /^#([\da-f])([\da-f])([\da-f])$/i,
-    (_, r, g, b) => `#${r}${r}${g}${g}${b}${b}`,
-  );
-  if (!/^#[\da-f]{6}$/i.test(full)) return 1;
-  const linearize = (c: number) =>
-    c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
-  const r = linearize(parseInt(full.slice(1, 3), 16) / 255);
-  const g = linearize(parseInt(full.slice(3, 5), 16) / 255);
-  const b = linearize(parseInt(full.slice(5, 7), 16) / 255);
-  return 0.2126 * r + 0.7152 * g + 0.0722 * b;
-}
-
-/** Returns the resolved CSS font-family string for the current settings. */
-function resolveFont(s: PDFExportSettings): string {
-  return s.fontFamily === "__custom__" ? (s.customFontName.trim() || "inherit") : s.fontFamily;
-}
-
-function buildDocCSS(s: PDFExportSettings, isRTL = false): string {
-  const hs = s.headingScale;
-  const fontFamily = resolveFont(s);
-  const tableHeaderTextColor =
-    hexLuminance(s.tableHeaderBg) < 0.35 ? "#fff" : s.headingColor;
-
-  return `
-  .mpdf-doc {
-    font-family: ${fontFamily};
-    font-size: ${s.fontSize}px;
-    line-height: ${s.lineHeight};
-    color: ${s.bodyColor};
-    box-sizing: border-box;
-    ${isRTL ? "direction: rtl;" : ""}
-  }
-  .mpdf-doc *, .mpdf-doc *::before, .mpdf-doc *::after { box-sizing: border-box; }
-  .mpdf-doc strong, .mpdf-doc b { font-weight: 700; font-style: normal; }
-  .mpdf-doc em, .mpdf-doc i { font-style: italic; font-weight: inherit; }
-  .mpdf-doc mark { background: #ffe066; color: inherit; padding: 0 2px; border-radius: 2px; }
-  .mpdf-doc del, .mpdf-doc s { text-decoration: line-through; }
-  .mpdf-doc h1 {
-    font-size: ${Math.round(22 * hs)}px;
-    font-weight: 700;
-    color: ${s.headingColor};
-    margin: 0 0 ${Math.round(12 * hs)}px;
-    line-height: 1.2;
-    ${s.h1BorderBottom ? `border-bottom: 2px solid ${s.accentColor}; padding-bottom: 6px;` : ""}
-    ${s.centerH1 ? "text-align: center;" : ""}
-  }
-  .mpdf-doc h2 {
-    font-size: ${Math.round(17 * hs)}px;
-    font-weight: 600;
-    color: ${s.headingColor};
-    margin: ${Math.round(20 * hs)}px 0 ${Math.round(10 * hs)}px;
-    ${s.h2BorderBottom ? `border-bottom: 0.5px solid ${s.accentColor}55; padding-bottom: 5px;` : ""}
-  }
-  .mpdf-doc h3 {
-    font-size: ${Math.round(15 * hs)}px;
-    font-weight: 700;
-    color: ${s.headingColor};
-    margin: ${Math.round(16 * hs)}px 0 ${Math.round(8 * hs)}px;
-    letter-spacing: 0.01em;
-  }
-  .mpdf-doc h4 { font-size: ${Math.round(13 * hs)}px; font-weight: 700; color: ${s.headingColor}; margin: 12px 0 6px; text-transform: uppercase; letter-spacing: 0.04em; }
-  .mpdf-doc h5 { font-size: ${Math.round(12 * hs)}px; font-weight: 600; color: ${s.headingColor}; margin: 10px 0 4px; font-style: italic; }
-  .mpdf-doc h6 { font-size: ${Math.round(11 * hs)}px; font-weight: 600; color: ${s.bodyColor}; margin: 8px 0 4px; font-style: italic; opacity: 0.75; }
-  .mpdf-doc p { margin: 0 0 ${s.paragraphSpacing}em; }
-  .mpdf-doc ul, .mpdf-doc ol { padding-inline-start: 1.4em; margin: 0 0 ${s.paragraphSpacing}em; }
-  .mpdf-doc li { margin-bottom: 0.2em; line-height: ${s.lineHeight}; }
-  .mpdf-doc blockquote {
-    border-inline-start: 3px solid ${s.blockquoteBorderColor};
-    background: ${s.blockquoteBg};
-    padding-block: 4px;
-    padding-inline: 1em 0;
-    margin: ${s.paragraphSpacing}em 0;
-    font-style: italic;
-    color: ${s.bodyColor}cc;
-  }
-  .mpdf-doc code {
-    font-family: 'Courier New', monospace;
-    font-size: ${s.codeFontSize}em;
-    background: ${s.codeBackground};
-    padding: 1px 4px;
-    border-radius: 3px;
-    color: ${s.accentColor};
-  }
-  ${buildCodeBlockCSS(s)}
-  .mpdf-doc hr {
-    border: none;
-    border-top: 0.5px solid ${s.accentColor}44;
-    margin: ${s.paragraphSpacing * 1.5}em 0;
-  }
-  .mpdf-doc img { max-width: 100%; height: auto; display: block; margin: ${s.paragraphSpacing}em auto; }
-  .mpdf-doc a { color: ${s.accentColor}; ${s.linkUnderline ? "" : "text-decoration: none;"} }
-  /* postProcessRenderedHTML removes the external-link class, but some themes
-     re-inject it at render time. This rule is cheap defense-in-depth. */
-  .mpdf-doc a.external-link::after { display: none !important; content: none !important; }
-  /* Hide copy-code buttons that survive postProcessRenderedHTML (e.g. re-injected by themes). */
-  .mpdf-doc .copy-code-button { display: none !important; }
-  .mpdf-doc table { width: 100%; border-collapse: collapse; margin: 0 0 ${s.paragraphSpacing}em; font-size: 0.92em; }
-  .mpdf-doc th {
-    background: ${s.tableHeaderBg};
-    color: ${tableHeaderTextColor};
-    padding: 6px 10px;
-    text-align: start;
-    font-weight: 600;
-    border: 0.5px solid ${s.accentColor}33;
-    font-size: 0.9em;
-  }
-  .mpdf-doc td { padding: 5px 10px; border: 0.5px solid ${s.bodyColor}22; vertical-align: top; }
-  ${s.tableStriped ? `.mpdf-doc tbody tr:nth-child(even) { background: ${s.tableHeaderBg}55; }` : ""}
-
-  /* Callouts — override theme styles with !important so preview and export are
-   * identical regardless of the active Obsidian theme. */
-  .mpdf-doc .callout {
-    border-inline-start: 4px solid ${s.accentColor} !important;
-    border-start-start-radius: 0 !important;
-    border-start-end-radius: 5px !important;
-    border-end-end-radius: 5px !important;
-    border-end-start-radius: 0 !important;
-    background: ${s.accentColor}12 !important;
-    margin: ${s.paragraphSpacing * 1.2}em 0 !important;
-    padding: 0 !important;
-    overflow: hidden !important;
-    box-shadow: inset 0 0 0 1px ${s.accentColor}22 !important;
-    font-style: normal !important;
-  }
-  .mpdf-doc .callout-title {
-    display: flex !important;
-    align-items: center !important;
-    gap: 7px !important;
-    padding: 7px 12px !important;
-    background: ${s.accentColor}28 !important;
-    border-bottom: 1px solid ${s.accentColor}33 !important;
-    font-family: ${fontFamily} !important;
-    font-size: 0.8em !important;
-    font-weight: 800 !important;
-    font-style: normal !important;
-    letter-spacing: 0.08em !important;
-    text-transform: uppercase !important;
-    color: ${s.accentColor} !important;
-    line-height: 1.3 !important;
-  }
-  .mpdf-doc .callout-icon {
-    display: inline-flex !important;
-    align-items: center !important;
-    flex-shrink: 0 !important;
-    width: 15px !important;
-    height: 15px !important;
-    color: ${s.accentColor} !important;
-  }
-  .mpdf-doc .callout-icon svg {
-    width: 15px !important;
-    height: 15px !important;
-    stroke: ${s.accentColor} !important;
-    fill: none !important;
-    stroke-width: 2 !important;
-  }
-  .mpdf-doc .callout-title-inner {
-    flex: 1 !important;
-    min-width: 0 !important;
-  }
-  .mpdf-doc .callout-fold { display: none !important; }
-  .mpdf-doc .callout-content {
-    padding: 9px 14px !important;
-    color: ${s.bodyColor} !important;
-    font-style: normal !important;
-    background: transparent !important;
-  }
-  .mpdf-doc .callout-content > p:first-child { margin-top: 0 !important; }
-  .mpdf-doc .callout-content > p:last-child  { margin-bottom: 0 !important; }
-  /* Nested blockquotes inside callout content keep a subtler indent */
-  .mpdf-doc .callout-content blockquote {
-    border-inline-start-color: ${s.accentColor}66 !important;
-    background: transparent !important;
-  }
-
-  /* Mermaid diagrams — centre the SVG and prevent it overflowing the content
-   * column.  The ` : ""}
-
-
-
-${pageHTMLParts.join("\n")}
-
-`;
-
-    try {
-      // Obsidian uses @electron/remote; the legacy `electron.remote` property is
-      // undefined in the renderer process of modern Electron versions.
-      const electron = window as unknown as ElectronBridge;
-      const remote = electron.require("@electron/remote") as ElectronRemote | null;
-      if (!remote?.dialog) throw new Error("no remote");
-
-      const res = await remote.dialog.showSaveDialog({
-        title: "Save PDF",
-        defaultPath: (this.currentFile?.basename ?? "export") + ".pdf",
-        filters: [{ name: "PDF", extensions: ["pdf"] }],
-      });
-      if (res.canceled || !res.filePath) {
-        resetExportBtn();
-        return;
-      }
-
-      new Notice("Advanced PDF Export — generating PDF…");
-
-      const blob = new Blob([fullHTML], { type: "text/html" });
-      const url  = URL.createObjectURL(blob);
-      const win  = new remote.BrowserWindow({ show: false, webPreferences: { nodeIntegration: false } });
-
-      win.loadURL(url);
-
-      // Both events can fire for the same load — a flag ensures only the first one acts.
-      let exportHandled = false;
-      const cleanupWin = () => { URL.revokeObjectURL(url); win.close(); resetExportBtn(); };
-
-      win.webContents.once("did-fail-load", (_event: unknown, _code: number, desc: string) => {
-        if (exportHandled) return;
-        exportHandled = true;
-        new Notice("Advanced PDF Export — failed to load page: " + desc);
-        cleanupWin();
-      });
-
-      win.webContents.once("did-finish-load", () => {
-        if (exportHandled) return;
-        exportHandled = true;
-
-        // Ensure all @font-face fonts (including inlined MathJax fonts) are loaded
-        // before capturing the PDF so math characters are not invisible.
-        win.webContents
-          .executeJavaScript("document.fonts.ready.then(() => true)")
-          .catch(() => true)
-          .then(() => {
-            // Custom sizes embed @page dimensions in the HTML; preferCSSPageSize lets
-            // Electron honour that rule. Named sizes pass the size string directly.
-            const isCustom = s.pageSize === "Custom";
-            return win.webContents.printToPDF({
-              pageSize:          isCustom ? "A4" : s.pageSize,
-              landscape:         !isCustom && s.orientation === "landscape",
-              preferCSSPageSize: isCustom,
-              printBackground:   true,
-              margins:           { marginType: "none" },
-            });
-          })
-          .then(async (data: Uint8Array) => {
-            // printToPDF produces a flat PDF with no outline; inject one via pdf-lib.
-            if (s.includeOutline) {
-              try {
-                data = await injectPDFOutline(data, extractOutlineEntries(layouts));
-              } catch (outlineErr) {
-                console.warn("[advanced-pdf-export] outline injection failed:", outlineErr);
-              }
-            }
-            electron.require("fs").writeFile(res.filePath!, data, (err: Error | null) => {
-              if (err) new Notice("Advanced PDF Export — failed to save: " + err.message);
-              else     new Notice("✓ PDF saved — " + res.filePath);
-              cleanupWin();
-            });
-          })
-          .catch((err: Error) => {
-            new Notice("Advanced PDF Export — failed to render: " + err.message);
-            cleanupWin();
-          });
-      });
-    } catch {
-      new Notice("Advanced PDF Export requires the Obsidian desktop app.");
-      resetExportBtn();
-    }
-  }
-}
-
-// ─── Settings tab ─────────────────────────────────────────────────────────────
-
-class PDFExportSettingTab extends PluginSettingTab {
-  plugin: MarkdownPDFPlugin;
-
-  /** True when any setting changed while this tab is open; triggers a single render on hide(). */
-  private dirty = false;
-
-  constructor(app: App, plugin: MarkdownPDFPlugin) {
-    super(app, plugin);
-    this.plugin = plugin;
-  }
-
-  display(): void {
-    // Start fresh: if nothing changes before hide(), no render will happen.
-    this.dirty = false;
-    this.buildSettings();
-  }
-
-  /** Called by Obsidian when the user leaves this tab. Fires one render if settings changed. */
-  hide(): void {
-    if (this.dirty) {
-      this.dirty = false;
-      this.plugin.activeModal?.render(true);
-    }
-  }
-
-  private async markDirty(): Promise {
-    this.dirty = true;
-    await this.plugin.saveSettings();
-  }
-
-  /** Builds (or rebuilds) the settings UI. Separated from display() so preset/reset
-   *  handlers can refresh the form without resetting the dirty flag. */
-  private buildSettings(): void {
-    const { containerEl } = this;
-    containerEl.empty();
-    const s = this.plugin.settings;
-
-    // Shared helpers ────────────────────────────────────────────────────────────
-    type NumericFieldKey = "marginTop" | "marginBottom" | "marginLeft" | "marginRight"
-      | "headerFontSize" | "footerFontSize" | "frameThickness" | "frameMargin"
-      | "headerHeight" | "footerHeight" | "headerImageMargin" | "footerImageMargin";
-    const numberSetting = (name: string, key: NumericFieldKey, min?: number, desc?: string) => {
-      const st = new Setting(containerEl).setName(name);
-      if (desc) st.setDesc(desc);
-      return st.addText((t) =>
-        t.setValue(String(s[key])).onChange((v) => {
-          const n = parseInt(v, 10) || 0;
-          s[key] = min !== undefined ? Math.max(min, n) : n;
-          void this.markDirty();
-        }),
-      );
-    };
-
-    type ColorKey = "accentColor" | "bodyColor" | "headingColor" | "pageBackground"
-      | "blockquoteBg" | "blockquoteBorderColor" | "tableHeaderBg" | "codeBackground"
-      | "headerFontColor" | "footerFontColor" | "frameColor";
-    const colorSetting = (name: string, key: ColorKey) =>
-      new Setting(containerEl).setName(name).addColorPicker((cp) =>
-        cp.setValue(s[key]).onChange((v) => { s[key] = v; void this.markDirty(); }),
-      );
-
-    // ── 1. Style Preset ───────────────────────────────────────────────────────
-    new Setting(containerEl).setName("Style Preset").setHeading();
-    new Setting(containerEl)
-      .setName("Preset")
-      .setDesc("Pick a preset to configure the overall document style. Fine-tune any setting below.")
-      .addDropdown((d) => {
-        Object.entries(PRESETS).forEach(([k, v]) => { d.addOption(k, v.name); });
-        d.setValue(s.preset).onChange((v) => {
-          this.plugin.applyPreset(v);
-          void this.markDirty().then(() => { this.buildSettings(); });
-        });
-      })
-      .addButton((b) =>
-        b.setButtonText("Reset Preset")
-         .setTooltip("Reset current preset to its default values")
-         .onClick(() => {
-           this.plugin.applyPreset(s.preset, true);
-           void this.markDirty().then(() => { this.buildSettings(); });
-         }),
-      );
-
-    // ── 2. Page ───────────────────────────────────────────────────────────────
-    new Setting(containerEl).setName("Page").setHeading();
-    let customPageSizeSetting: Setting;
-    new Setting(containerEl).setName("Page size").addDropdown((d) => {
-      Object.keys(PAGE_SIZES).forEach((k) => { d.addOption(k, k); });
-      d.addOption("Custom", "Custom…");
-      d.setValue(s.pageSize).onChange((v) => {
-        s.pageSize = v;
-        customPageSizeSetting.settingEl.toggleClass("mpdf-is-hidden", v !== "Custom");
-        void this.markDirty();
-      });
-    });
-    customPageSizeSetting = new Setting(containerEl)
-      .setName("Custom page size (mm)")
-      .setDesc("Width × Height in millimetres.")
-      .addText((t) =>
-        t.setPlaceholder("Width").setValue(String(s.customPageWidth))
-         .onChange((v) => { s.customPageWidth  = Math.max(10, parseFloat(v) || 210); void this.markDirty(); }),
-      )
-      .addText((t) =>
-        t.setPlaceholder("Height").setValue(String(s.customPageHeight))
-         .onChange((v) => { s.customPageHeight = Math.max(10, parseFloat(v) || 297); void this.markDirty(); }),
-      );
-    customPageSizeSetting.settingEl.toggleClass("mpdf-is-hidden", s.pageSize !== "Custom");
-    new Setting(containerEl).setName("Orientation").addDropdown((d) =>
-      d.addOptions({ portrait: "Portrait", landscape: "Landscape" })
-       .setValue(s.orientation)
-       .onChange((v) => { s.orientation = v as "portrait" | "landscape"; void this.markDirty(); }),
-    );
-
-    // ── 3. Margin & Frame ─────────────────────────────────────────────────────
-    new Setting(containerEl).setName("Margin & Frame").setHeading();
-    new Setting(containerEl)
-      .setName("Margins")
-      .setDesc("Top · Bottom · Left · Right")
-      .addText((t) =>
-        t.setPlaceholder("Top").setValue(String(s.marginTop))
-         .onChange((v) => { s.marginTop    = parseInt(v, 10) || 0; void this.markDirty(); }),
-      )
-      .addText((t) =>
-        t.setPlaceholder("Bottom").setValue(String(s.marginBottom))
-         .onChange((v) => { s.marginBottom = parseInt(v, 10) || 0; void this.markDirty(); }),
-      )
-      .addText((t) =>
-        t.setPlaceholder("Left").setValue(String(s.marginLeft))
-         .onChange((v) => { s.marginLeft   = parseInt(v, 10) || 0; void this.markDirty(); }),
-      )
-      .addText((t) =>
-        t.setPlaceholder("Right").setValue(String(s.marginRight))
-         .onChange((v) => { s.marginRight  = parseInt(v, 10) || 0; void this.markDirty(); }),
-      );
-
-    let frameColorSetting: Setting;
-    let frameThicknessSetting: Setting;
-    let frameMarginSetting: Setting;
-    let frameStyleSetting: Setting;
-    const toggleFrameSettings = (visible: boolean) => {
-      [frameColorSetting, frameThicknessSetting, frameMarginSetting, frameStyleSetting]
-        .forEach((st) => st.settingEl.toggleClass("mpdf-is-hidden", !visible));
-    };
-    new Setting(containerEl)
-      .setName("Enable frame")
-      .setDesc("Draws a border around the outer edge of every page.")
-      .addToggle((t) =>
-        t.setValue(s.frameEnabled).onChange((v) => {
-          s.frameEnabled = v;
-          toggleFrameSettings(v);
-          void this.markDirty();
-        }),
-      );
-    frameColorSetting     = colorSetting("Frame color", "frameColor");
-    frameThicknessSetting = numberSetting("Frame thickness (px)", "frameThickness", 1);
-    frameMarginSetting    = numberSetting(
-      "Frame margin (px)", "frameMargin", 0,
-      "Gap between the page edge and the frame, applied equally on all four sides.",
-    );
-    frameStyleSetting = new Setting(containerEl).setName("Frame style").addDropdown((d) =>
-      d.addOptions({ solid: "Solid", dashed: "Dashed", dotted: "Dotted", double: "Double", groove: "Groove", ridge: "Ridge" })
-       .setValue(s.frameStyle)
-       .onChange((v) => { s.frameStyle = v as PDFExportSettings["frameStyle"]; void this.markDirty(); }),
-    );
-    toggleFrameSettings(s.frameEnabled);
-
-    // ── 4. Typography ─────────────────────────────────────────────────────────
-    new Setting(containerEl).setName("Typography").setHeading();
-    let customFontSetting: Setting;
-    new Setting(containerEl).setName("Font family").addDropdown((d) =>
-      d.addOptions({
-        "Georgia, serif":                          "Georgia (Serif)",
-        "'Times New Roman', Times, serif":         "Times New Roman",
-        "'Palatino Linotype', Palatino, serif":    "Palatino",
-        "Arial, sans-serif":                       "Arial",
-        "'Helvetica Neue', Helvetica, sans-serif": "Helvetica",
-        "'Trebuchet MS', sans-serif":              "Trebuchet",
-        "'Courier New', monospace":                "Courier New",
-        "__custom__":                              "Custom…",
-      }).setValue(s.fontFamily)
-       .onChange((v) => {
-         s.fontFamily = v;
-         customFontSetting.settingEl.toggleClass("mpdf-is-hidden", v !== "__custom__");
-         void this.markDirty();
-       }),
-    );
-    customFontSetting = new Setting(containerEl)
-      .setName("Custom font name")
-      .setDesc("CSS font-family value — e.g. \"Inter, sans-serif\". The font must be installed on your system.")
-      .addText((t) =>
-        t.setPlaceholder("e.g. Inter, sans-serif")
-         .setValue(s.customFontName)
-         .onChange((v) => { s.customFontName = v; void this.markDirty(); }),
-      );
-    customFontSetting.settingEl.toggleClass("mpdf-is-hidden", s.fontFamily !== "__custom__");
-    new Setting(containerEl).setName("Font size (px)").addDropdown((d) => {
-      ["10","11","12","13","14","15","16"].forEach((v) => { d.addOption(v, v + "px"); });
-      d.setValue(String(s.fontSize)).onChange((v) => { s.fontSize = parseInt(v); void this.markDirty(); });
-    });
-    new Setting(containerEl).setName("Code font size").addDropdown((d) =>
-      d.addOptions({ "0.75": "0.75em", "0.80": "0.80em", "0.82": "0.82em", "0.85": "0.85em", "0.88": "0.88em", "0.90": "0.90em", "1.0": "1.00em" })
-       .setValue(String(s.codeFontSize))
-       .onChange((v) => { s.codeFontSize = parseFloat(v); void this.markDirty(); }),
-    );
-    new Setting(containerEl).setName("Line height").addDropdown((d) =>
-      d.addOptions({ "1.4": "Tight (1.4)", "1.6": "Compact (1.6)", "1.75": "Normal (1.75)", "1.85": "Relaxed (1.85)", "2.0": "Double (2.0)" })
-       .setValue(String(s.lineHeight))
-       .onChange((v) => { s.lineHeight = parseFloat(v); void this.markDirty(); }),
-    );
-    new Setting(containerEl).setName("Paragraph spacing").addDropdown((d) =>
-      d.addOptions({ "0": "None", "0.3": "Tight (0.3em)", "0.5": "Normal (0.5em)", "0.65": "Relaxed (0.65em)", "1.0": "Wide (1em)" })
-       .setValue(String(s.paragraphSpacing))
-       .onChange((v) => { s.paragraphSpacing = parseFloat(v); void this.markDirty(); }),
-    );
-    new Setting(containerEl)
-      .setName("Heading scale")
-      .setDesc("Multiplier applied to all heading sizes.")
-      .addDropdown((d) =>
-        d.addOptions({ "0.8": "Small (0.8×)", "0.88": "0.88×", "0.9": "Compact (0.9×)", "0.95": "0.95×", "1.0": "Normal (1.0×)", "1.05": "1.05×", "1.1": "Large (1.1×)", "1.2": "XLarge (1.2×)" })
-         .setValue(String(s.headingScale))
-         .onChange((v) => { s.headingScale = parseFloat(v); void this.markDirty(); }),
-      );
-
-    // ── 5. Background ─────────────────────────────────────────────────────────
-    new Setting(containerEl).setName("Background").setHeading();
-    let bgColorSetting: Setting;
-    let bgImgPathSetting: Setting;
-    let bgImgSizeSetting: Setting;
-    let bgImgScopeSetting: Setting;
-    let bgImgOpacitySetting: Setting;
-    const showBgMode = (useImage: boolean) => {
-      bgColorSetting.settingEl.toggleClass("mpdf-is-hidden", useImage);
-      [bgImgPathSetting, bgImgSizeSetting, bgImgScopeSetting, bgImgOpacitySetting]
-        .forEach((st) => st.settingEl.toggleClass("mpdf-is-hidden", !useImage));
-    };
-    new Setting(containerEl)
-      .setName("Use image background")
-      .setDesc("When on, a background image is used instead of the solid background color.")
-      .addToggle((t) =>
-        t.setValue(s.backgroundImageEnabled).onChange((v) => {
-          s.backgroundImageEnabled = v;
-          showBgMode(v);
-          void this.markDirty();
-        }),
-      );
-    bgColorSetting = new Setting(containerEl)
-      .setName("Page background color")
-      .addColorPicker((cp) =>
-        cp.setValue(s.pageBackground).onChange((v) => { s.pageBackground = v; void this.markDirty(); }),
-      );
-    bgImgPathSetting = new Setting(containerEl)
-      .setName("Background image")
-      .setDesc("Vault-relative path or https:// URL.")
-      .addText((t) =>
-        t.setPlaceholder("assets/background.png").setValue(s.backgroundImagePath)
-         .onChange((v) => { s.backgroundImagePath = v; void this.markDirty(); }),
-      );
-    bgImgSizeSetting = new Setting(containerEl).setName("Fit").addDropdown((d) =>
-      d.addOptions({
-        cover:   "Cover (fill, crop edges)",
-        contain: "Contain (fit, show gaps)",
-        fill:    "Fill (stretch to exact size)",
-        tile:    "Tile (repeat)",
-      })
-       .setValue(s.backgroundImageSize)
-       .onChange((v) => { s.backgroundImageSize = v as PDFExportSettings["backgroundImageSize"]; void this.markDirty(); }),
-    );
-    bgImgScopeSetting = new Setting(containerEl)
-      .setName("Scope")
-      .setDesc("Full page includes header and footer bands. Content area only restricts the background to the text zone between them.")
-      .addDropdown((d) =>
-        d.addOptions({ "full-page": "Full page", "content-only": "Content area only" })
-         .setValue(s.backgroundImageScope)
-         .onChange((v) => { s.backgroundImageScope = v as PDFExportSettings["backgroundImageScope"]; void this.markDirty(); }),
-      );
-    bgImgOpacitySetting = new Setting(containerEl).setName("Opacity").addDropdown((d) =>
-      d.addOptions({ "0.05": "5%", "0.1": "10%", "0.15": "15%", "0.2": "20%", "0.3": "30%", "0.4": "40%", "0.5": "50%", "0.6": "60%", "0.7": "70%", "0.8": "80%", "0.9": "90%", "1": "100%" })
-       .setValue(String(s.backgroundImageOpacity))
-       .onChange((v) => { s.backgroundImageOpacity = parseFloat(v); void this.markDirty(); }),
-    );
-    showBgMode(s.backgroundImageEnabled);
-
-    // ── 6. Colors ─────────────────────────────────────────────────────────────
-    new Setting(containerEl).setName("Colors").setHeading();
-    colorSetting("Accent color",            "accentColor");
-    colorSetting("Body text color",         "bodyColor");
-    colorSetting("Heading color",           "headingColor");
-    colorSetting("Blockquote background",   "blockquoteBg");
-    colorSetting("Blockquote border",       "blockquoteBorderColor");
-    colorSetting("Table header background", "tableHeaderBg");
-    colorSetting("Code background",         "codeBackground");
-    new Setting(containerEl)
-      .setName("Code syntax theme")
-      .setDesc("Independent of your Obsidian theme. \"None\" uses the body text color and code background above with no highlighting.")
-      .addDropdown((d) => {
-        const opts: Record = {};
-        for (const [key, theme] of Object.entries(CODE_THEMES)) opts[key] = theme.name;
-        d.addOptions(opts).setValue(s.codeTheme).onChange((v) => { s.codeTheme = v; void this.markDirty(); });
-      });
-
-    // ── 7. Header ─────────────────────────────────────────────────────────────
-    new Setting(containerEl).setName("Header").setHeading();
-    new Setting(containerEl).setName("Show header").addToggle((t) =>
-      t.setValue(s.showHeader).onChange((v) => { s.showHeader = v; void this.markDirty(); }),
-    );
-    new Setting(containerEl)
-      .setName("Show on first page")
-      .setDesc("When off, the header is hidden on page 1. Useful for title pages.")
-      .addToggle((t) =>
-        t.setValue(s.showHeaderOnFirstPage).onChange((v) => { s.showHeaderOnFirstPage = v; void this.markDirty(); }),
-      );
-    new Setting(containerEl)
-      .setName("Header text")
-      .addText((t) => t.setValue(s.headerText).onChange((v) => { s.headerText = v; void this.markDirty(); }));
-    new Setting(containerEl).setName("Alignment").addDropdown((d) =>
-      d.addOptions({ left: "Left", center: "Center", right: "Right" })
-       .setValue(s.headerAlignment)
-       .onChange((v) => { s.headerAlignment = v as "left"|"center"|"right"; void this.markDirty(); }),
-    );
-    numberSetting("Font size (px)", "headerFontSize", 1);
-    numberSetting("Height (px)", "headerHeight", 0, "Explicit band height (0 = auto).");
-    colorSetting("Font color", "headerFontColor");
-    new Setting(containerEl).setName("Border").setDesc("Separator line below the header.").addToggle((t) =>
-      t.setValue(s.showHeaderBorder).onChange((v) => { s.showHeaderBorder = v; void this.markDirty(); }),
-    );
-    new Setting(containerEl)
-      .setName("Image")
-      .setDesc("Vault-relative path or https:// URL. Fills the header band as a background banner.")
-      .addText((t) =>
-        t.setPlaceholder("assets/header-banner.png").setValue(s.headerImagePath)
-         .onChange((v) => { s.headerImagePath = v; void this.markDirty(); }),
-      );
-    numberSetting("Image left/right margin (px)", "headerImageMargin", 0, "Insets the banner from the left and right page edges.");
-
-    // ── 8. Footer ─────────────────────────────────────────────────────────────
-    new Setting(containerEl).setName("Footer").setHeading();
-    new Setting(containerEl).setName("Show footer").addToggle((t) =>
-      t.setValue(s.showFooter).onChange((v) => { s.showFooter = v; void this.markDirty(); }),
-    );
-    new Setting(containerEl)
-      .setName("Show on first page")
-      .setDesc("When off, the footer and page numbers are hidden on page 1. Page numbering starts from page 2.")
-      .addToggle((t) =>
-        t.setValue(s.showFooterOnFirstPage).onChange((v) => { s.showFooterOnFirstPage = v; void this.markDirty(); }),
-      );
-    new Setting(containerEl)
-      .setName("Footer text")
-      .addText((t) => t.setValue(s.footerText).onChange((v) => { s.footerText = v; void this.markDirty(); }));
-    new Setting(containerEl).setName("Alignment").addDropdown((d) =>
-      d.addOptions({ left: "Left", center: "Center", right: "Right" })
-       .setValue(s.footerTextAlignment)
-       .onChange((v) => { s.footerTextAlignment = v as "left" | "center" | "right"; void this.markDirty(); }),
-    );
-    numberSetting("Font size (px)", "footerFontSize", 1);
-    numberSetting("Height (px)", "footerHeight", 0, "Explicit band height (0 = auto).");
-    colorSetting("Font color", "footerFontColor");
-    new Setting(containerEl).setName("Border").setDesc("Separator line above the footer.").addToggle((t) =>
-      t.setValue(s.showFooterBorder).onChange((v) => { s.showFooterBorder = v; void this.markDirty(); }),
-    );
-    new Setting(containerEl)
-      .setName("Image")
-      .setDesc("Vault-relative path or https:// URL. Fills the footer band as a background banner.")
-      .addText((t) =>
-        t.setPlaceholder("assets/footer-banner.png").setValue(s.footerImagePath)
-         .onChange((v) => { s.footerImagePath = v; void this.markDirty(); }),
-      );
-    numberSetting("Image left/right margin (px)", "footerImageMargin", 0, "Insets the banner from the left and right page edges.");
-    new Setting(containerEl).setName("Show page numbers").addToggle((t) =>
-      t.setValue(s.showPageNumbers).onChange((v) => { s.showPageNumbers = v; void this.markDirty(); }),
-    );
-    new Setting(containerEl).setName("Page number position").addDropdown((d) =>
-      d.addOptions({ left: "Left", center: "Center", right: "Right" })
-       .setValue(s.pageNumberPosition)
-       .onChange((v) => { s.pageNumberPosition = v as "left"|"center"|"right"; void this.markDirty(); }),
-    );
-    new Setting(containerEl)
-      .setName("Page number format")
-      .setDesc("Use {{current}} and {{total}} as placeholders, e.g. \"Page {{current}} of {{total}}\", \"{{current}}/{{total}}\", or just \"{{current}}\".")
-      .addText((t) =>
-        t.setPlaceholder("{{current}} / {{total}}").setValue(s.pageNumberFormat)
-         .onChange((v) => { s.pageNumberFormat = v; void this.markDirty(); }),
-      );
-    new Setting(containerEl)
-      .setName("Page number start")
-      .setDesc("Number assigned to the first visible page number.")
-      .addText((t) =>
-        t.setValue(String(s.pageNumberStart))
-         .onChange((v) => { s.pageNumberStart = parseInt(v, 10) || 1; void this.markDirty(); }),
-      );
-
-    // ── 9. Behaviour ──────────────────────────────────────────────────────────
-    new Setting(containerEl).setName("Behaviour").setHeading();
-    new Setting(containerEl)
-      .setName("Hide frontmatter")
-      .setDesc("Strip the YAML frontmatter block (--- … ---) from the preview and exported PDF.")
-      .addToggle((t) =>
-        t.setValue(s.hideFrontmatter).onChange((v) => { s.hideFrontmatter = v; void this.markDirty(); }),
-      );
-    new Setting(containerEl)
-      .setName("Include file name as title")
-      .setDesc("Prepend the note's file name as an H1 heading at the top of the PDF.")
-      .addToggle((t) =>
-        t.setValue(s.includeFilenameAsTitle).onChange((v) => { s.includeFilenameAsTitle = v; void this.markDirty(); }),
-      );
-    new Setting(containerEl)
-      .setName("Underline links")
-      .setDesc("Applies to both internal and external links.")
-      .addToggle((t) =>
-        t.setValue(s.linkUnderline).onChange((v) => { s.linkUnderline = v; void this.markDirty(); }),
-      );
-    new Setting(containerEl).setName("Auto page break before H1").addToggle((t) =>
-      t.setValue(s.autoBreakH1).onChange((v) => { s.autoBreakH1 = v; void this.markDirty(); }),
-    );
-    new Setting(containerEl).setName("Auto page break before H2").addToggle((t) =>
-      t.setValue(s.autoBreakH2).onChange((v) => { s.autoBreakH2 = v; void this.markDirty(); }),
-    );
-    new Setting(containerEl).setName("H1 bottom border").addToggle((t) =>
-      t.setValue(s.h1BorderBottom).onChange((v) => { s.h1BorderBottom = v; void this.markDirty(); }),
-    );
-    new Setting(containerEl).setName("H2 bottom border").addToggle((t) =>
-      t.setValue(s.h2BorderBottom).onChange((v) => { s.h2BorderBottom = v; void this.markDirty(); }),
-    );
-    new Setting(containerEl).setName("Center H1").addToggle((t) =>
-      t.setValue(s.centerH1).onChange((v) => { s.centerH1 = v; void this.markDirty(); }),
-    );
-    new Setting(containerEl).setName("Striped table rows").addToggle((t) =>
-      t.setValue(s.tableStriped).onChange((v) => { s.tableStriped = v; void this.markDirty(); }),
-    );
-    new Setting(containerEl)
-      .setName("Include PDF outline (bookmarks)")
-      .setDesc(
-        "Embeds a bookmark tree into the exported PDF. " +
-        "Most PDF readers display it in a side panel for quick navigation.",
-      )
-      .addToggle((t) =>
-        t.setValue(s.includeOutline).onChange((v) => { s.includeOutline = v; void this.markDirty(); }),
-      );
-  }
-}
diff --git a/manifest.json b/manifest.json
index 0bafd28..85caa92 100644
--- a/manifest.json
+++ b/manifest.json
@@ -1,7 +1,7 @@
 {
   "id": "advanced-pdf-export",
   "name": "Advanced PDF Export",
-  "version": "4.2.0",
+  "version": "4.2.1",
   "minAppVersion": "1.11.1",
   "description": "Export notes as pixel-perfect PDFs with live preview, style presets, manual page breaks, tables, and full layout control.",
   "author": "ShrekBytes",
diff --git a/package-lock.json b/package-lock.json
index 1a66401..6b7eee2 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
 {
   "name": "obsidian-advanced-pdf-export",
-  "version": "4.2.0",
+  "version": "4.2.1",
   "lockfileVersion": 3,
   "requires": true,
   "packages": {
     "": {
       "name": "obsidian-advanced-pdf-export",
-      "version": "4.2.0",
+      "version": "4.2.1",
       "dependencies": {
         "pdf-lib": "^1.17.1"
       },
diff --git a/package.json b/package.json
index 571f369..b0aca2d 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
 {
   "name": "obsidian-advanced-pdf-export",
-  "version": "4.2.0",
+  "version": "4.2.1",
   "description": "Obsidian plugin for advanced PDF export",
   "author": "ShrekBytes",
   "repository": {
@@ -21,5 +21,8 @@
   },
   "dependencies": {
     "pdf-lib": "^1.17.1"
+  },
+  "allowScripts": {
+    "esbuild@0.25.5": true
   }
 }
diff --git a/src/css-builder.ts b/src/css-builder.ts
new file mode 100644
index 0000000..f6f0330
--- /dev/null
+++ b/src/css-builder.ts
@@ -0,0 +1,578 @@
+// ─────────────────────────────────────────────────────────────────────────────
+// CSS generation.
+//
+// Turns a PDFExportSettings object into the actual CSS strings the preview
+// (shadow DOM) and export (print HTML) paths both consume — plus the MathJax
+// stylesheet-extraction helpers needed to make typeset formulas show up
+// correctly in either path. Everything here is pure string-building; it
+// doesn't touch the DOM beyond reading already-rendered MathJax stylesheets.
+// ─────────────────────────────────────────────────────────────────────────────
+
+import { App, TFile, requestUrl } from "obsidian";
+import { PAGE_SIZES, PDFExportSettings } from "./settings";
+
+// ─── Small utilities ──────────────────────────────────────────────────────────
+
+/** mm → px at 96 dpi, matching Electron's print pipeline. */
+export const mmToPx = (mm: number) => (mm / 25.4) * 96;
+
+/**
+ * Returns the page dimensions in px for the current settings.
+ * For "Custom", converts the user-entered mm values; for named sizes, looks up
+ * PAGE_SIZES directly. Orientation swapping is handled by callers (doRender).
+ */
+export function resolvePageDims(s: PDFExportSettings): { w: number; h: number } {
+  if (s.pageSize === "Custom") {
+    return {
+      w: Math.max(1, Math.round(mmToPx(s.customPageWidth))),
+      h: Math.max(1, Math.round(mmToPx(s.customPageHeight))),
+    };
+  }
+  return PAGE_SIZES[s.pageSize] ?? PAGE_SIZES["A4"];
+}
+
+export function escapeHTML(s: string): string {
+  return s
+    .replace(/&/g, "&")
+    .replace(//g, ">")
+    .replace(/"/g, """)
+    .replace(/'/g, "'");
+}
+
+// Escapes ` block early, regardless of where the sequence appears.
+export function escapeCSSForStyle(css: string): string {
+  return css.replace(/<\/style/gi, "<\\/style");
+}
+
+/** Converts a vault-relative path or bare filename to an app:// resource URL,
+ *  or passes https:// / data: URLs through unchanged. Returns "" for blank input. */
+export function resolveImageUrl(app: App, imagePath: string): string {
+  const trimmed = imagePath.trim();
+  if (!trimmed) return "";
+  if (/^(https?:|data:)/i.test(trimmed)) return trimmed;
+  const direct = app.vault.getAbstractFileByPath(trimmed);
+  if (direct instanceof TFile) return app.vault.getResourcePath(direct);
+  const resolved = app.metadataCache.getFirstLinkpathDest(trimmed, "");
+  if (resolved instanceof TFile) return app.vault.getResourcePath(resolved);
+  console.warn("[advanced-pdf-export] Could not resolve image path:", trimmed);
+  return trimmed;
+}
+
+/** Maps a `backgroundImageSize` setting value to its CSS `background-size`
+ *  and `background-repeat` values. Centralises logic that would otherwise be
+ *  duplicated across the preview and export render paths. */
+export function bgImageCssProps(size: PDFExportSettings["backgroundImageSize"]): { size: string; repeat: string } {
+  return {
+    size:   size === "fill" ? "100% 100%" : size === "tile" ? "auto" : size, // "cover" | "contain" pass through
+    repeat: size === "tile" ? "repeat" : "no-repeat",
+  };
+}
+
+// ─── Code block syntax highlighting ────────────────────────────────────────
+// Obsidian highlights fenced code with Prism `.token.` spans, but the
+// theme CSS that colours them is stripped for export — colours are reapplied
+// here independently via the same classes.
+
+type TokenGroup =
+  | "comment" | "punctuation" | "property" | "selector"
+  | "operator" | "keyword" | "function" | "regex";
+
+// Groups Prism's token classes into the small set of categories most colour
+// schemes distinguish. Multiple Prism classes commonly share one colour.
+const TOKEN_GROUP_CLASSES: Record = {
+  comment:     ["comment", "prolog", "doctype", "cdata"],
+  punctuation: ["punctuation"],
+  property:    ["property", "tag", "boolean", "number", "constant", "symbol", "deleted", "attr-name"],
+  selector:    ["selector", "string", "char", "builtin", "inserted", "attr-value"],
+  operator:    ["operator", "entity", "url"],
+  keyword:     ["atrule", "keyword", "important"],
+  function:    ["function", "class-name"],
+  regex:       ["regex", "variable"],
+};
+
+interface CodeColorTheme {
+  name: string;
+  /** `
` background. Falls back to the doc style's "Code background" when unset. */
+  background?: string;
+  /** Base `
` text color. Falls back to the doc style's "Body text color" when unset. */
+  text?: string;
+  tokens?: Partial>;
+}
+
+export const CODE_THEMES: Record = {
+  none: { name: "None (plain)" },
+  "github-light": {
+    name: "GitHub Light",
+    background: "#f6f8fa", text: "#24292e",
+    tokens: {
+      comment: "#6a737d", punctuation: "#24292e", property: "#005cc5",
+      selector: "#032f62", operator: "#d73a49", keyword: "#d73a49",
+      function: "#6f42c1", regex: "#032f62",
+    },
+  },
+  "github-dark": {
+    name: "GitHub Dark",
+    background: "#0d1117", text: "#c9d1d9",
+    tokens: {
+      comment: "#8b949e", punctuation: "#c9d1d9", property: "#79c0ff",
+      selector: "#a5d6ff", operator: "#ff7b72", keyword: "#ff7b72",
+      function: "#d2a8ff", regex: "#a5d6ff",
+    },
+  },
+  "atom-one-light": {
+    name: "Atom One Light",
+    background: "#fafafa", text: "#383a42",
+    tokens: {
+      comment: "#a0a1a7", punctuation: "#383a42", property: "#986801",
+      selector: "#50a14f", operator: "#0184bc", keyword: "#a626a4",
+      function: "#4078f2", regex: "#50a14f",
+    },
+  },
+  "atom-one-dark": {
+    name: "Atom One Dark",
+    background: "#282c34", text: "#abb2bf",
+    tokens: {
+      comment: "#5c6370", punctuation: "#abb2bf", property: "#d19a66",
+      selector: "#98c379", operator: "#56b6c2", keyword: "#c678dd",
+      function: "#61afef", regex: "#98c379",
+    },
+  },
+  monokai: {
+    name: "Monokai",
+    background: "#272822", text: "#f8f8f2",
+    tokens: {
+      comment: "#75715e", punctuation: "#f8f8f2", property: "#ae81ff",
+      selector: "#e6db74", operator: "#f92672", keyword: "#f92672",
+      function: "#a6e22e", regex: "#e6db74",
+    },
+  },
+  dracula: {
+    name: "Dracula",
+    background: "#282a36", text: "#f8f8f2",
+    tokens: {
+      comment: "#6272a4", punctuation: "#f8f8f2", property: "#bd93f9",
+      selector: "#f1fa8c", operator: "#ff79c6", keyword: "#ff79c6",
+      function: "#50fa7b", regex: "#ff79c6",
+    },
+  },
+  "tokyo-night": {
+    name: "Tokyo Night",
+    background: "#1a1b26", text: "#a9b1d6",
+    tokens: {
+      comment: "#565f89", punctuation: "#89ddff", property: "#ff9e64",
+      selector: "#9ece6a", operator: "#89ddff", keyword: "#bb9af7",
+      function: "#7aa2f7", regex: "#b4f9f8",
+    },
+  },
+  "solarized-light": {
+    name: "Solarized Light",
+    background: "#fdf6e3", text: "#586e75",
+    tokens: {
+      comment: "#93a1a1", punctuation: "#586e75", property: "#cb4b16",
+      selector: "#2aa198", operator: "#859900", keyword: "#859900",
+      function: "#268bd2", regex: "#2aa198",
+    },
+  },
+  "catppuccin-macchiato": {
+    name: "Catppuccin Macchiato",
+    background: "#24273a", text: "#cad3f5",
+    tokens: {
+      comment: "#939ab7", punctuation: "#b8c0e0", property: "#f5a97f",
+      selector: "#a6da95", operator: "#91d7e3", keyword: "#c6a0f6",
+      function: "#8aadf4", regex: "#f5bde6",
+    },
+  },
+  "catppuccin-mocha": {
+    name: "Catppuccin Mocha",
+    background: "#1e1e2e", text: "#cdd6f4",
+    tokens: {
+      comment: "#9399b2", punctuation: "#bac2de", property: "#fab387",
+      selector: "#a6e3a1", operator: "#89dceb", keyword: "#cba6f7",
+      function: "#89b4fa", regex: "#f5c2e7",
+    },
+  },
+};
+
+/** Builds the `
`/`
` rules plus Prism `.token.*` colour mappings
+ *  for the selected code theme. "None" keeps the previous plain styling
+ *  (code background + body color, no token colours). */
+function buildCodeBlockCSS(s: PDFExportSettings): string {
+  const theme = CODE_THEMES[s.codeTheme] ?? CODE_THEMES.none;
+  const background = theme.background ?? s.codeBackground;
+  const text = theme.text ?? s.bodyColor;
+
+  const tokenRules = Object.entries(theme.tokens ?? {})
+    .map(([group, color]) => {
+      const selector = TOKEN_GROUP_CLASSES[group as TokenGroup]
+        .map((cls) => `.mpdf-doc pre code .token.${cls}`)
+        .join(", ");
+      const italic = group === "comment" ? " font-style: italic;" : "";
+      return `${selector} { color: ${color};${italic} }`;
+    })
+    .join("\n  ");
+
+  return `
+  .mpdf-doc pre {
+    background: ${background};
+    border-radius: 4px;
+    padding: 10px 12px;
+    margin: 0 0 ${s.paragraphSpacing}em;
+    overflow: hidden;
+  }
+  .mpdf-doc pre code {
+    font-family: 'Courier New', monospace;
+    font-size: ${s.codeFontSize}em;
+    color: ${text};
+    white-space: pre-wrap;
+    overflow-wrap: break-word;
+    background: none;
+    padding: 0;
+  }
+  ${tokenRules}`;
+}
+
+// ─── Doc CSS builder ──────────────────────────────────────────────────────────
+
+/** Returns relative luminance (0–1) of a CSS hex color; non-hex values return 1 (treat as light). */
+function hexLuminance(hex: string): number {
+  const full = hex.replace(
+    /^#([\da-f])([\da-f])([\da-f])$/i,
+    (_, r, g, b) => `#${r}${r}${g}${g}${b}${b}`,
+  );
+  if (!/^#[\da-f]{6}$/i.test(full)) return 1;
+  const linearize = (c: number) =>
+    c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
+  const r = linearize(parseInt(full.slice(1, 3), 16) / 255);
+  const g = linearize(parseInt(full.slice(3, 5), 16) / 255);
+  const b = linearize(parseInt(full.slice(5, 7), 16) / 255);
+  return 0.2126 * r + 0.7152 * g + 0.0722 * b;
+}
+
+/** Returns the resolved CSS font-family string for the current settings. */
+export function resolveFont(s: PDFExportSettings): string {
+  return s.fontFamily === "__custom__" ? (s.customFontName.trim() || "inherit") : s.fontFamily;
+}
+
+/** Builds the full `.mpdf-doc` stylesheet (typography, tables, callouts,
+ *  mermaid, code blocks) shared verbatim by the preview shadow DOM and the
+ *  export print HTML. */
+export function buildDocCSS(s: PDFExportSettings, isRTL = false): string {
+  const hs = s.headingScale;
+  const fontFamily = resolveFont(s);
+  const tableHeaderTextColor =
+    hexLuminance(s.tableHeaderBg) < 0.35 ? "#fff" : s.headingColor;
+
+  return `
+  .mpdf-doc {
+    font-family: ${fontFamily};
+    font-size: ${s.fontSize}px;
+    line-height: ${s.lineHeight};
+    color: ${s.bodyColor};
+    box-sizing: border-box;
+    ${isRTL ? "direction: rtl;" : ""}
+  }
+  .mpdf-doc *, .mpdf-doc *::before, .mpdf-doc *::after { box-sizing: border-box; }
+  .mpdf-doc strong, .mpdf-doc b { font-weight: 700; font-style: normal; }
+  .mpdf-doc em, .mpdf-doc i { font-style: italic; font-weight: inherit; }
+  .mpdf-doc mark { background: #ffe066; color: inherit; padding: 0 2px; border-radius: 2px; }
+  .mpdf-doc del, .mpdf-doc s { text-decoration: line-through; }
+  .mpdf-doc h1 {
+    font-size: ${Math.round(22 * hs)}px;
+    font-weight: 700;
+    color: ${s.headingColor};
+    margin: 0 0 ${Math.round(12 * hs)}px;
+    line-height: 1.2;
+    ${s.h1BorderBottom ? `border-bottom: 2px solid ${s.accentColor}; padding-bottom: 6px;` : ""}
+    ${s.centerH1 ? "text-align: center;" : ""}
+  }
+  .mpdf-doc h2 {
+    font-size: ${Math.round(17 * hs)}px;
+    font-weight: 600;
+    color: ${s.headingColor};
+    margin: ${Math.round(20 * hs)}px 0 ${Math.round(10 * hs)}px;
+    ${s.h2BorderBottom ? `border-bottom: 0.5px solid ${s.accentColor}55; padding-bottom: 5px;` : ""}
+  }
+  .mpdf-doc h3 {
+    font-size: ${Math.round(15 * hs)}px;
+    font-weight: 700;
+    color: ${s.headingColor};
+    margin: ${Math.round(16 * hs)}px 0 ${Math.round(8 * hs)}px;
+    letter-spacing: 0.01em;
+  }
+  .mpdf-doc h4 { font-size: ${Math.round(13 * hs)}px; font-weight: 700; color: ${s.headingColor}; margin: 12px 0 6px; text-transform: uppercase; letter-spacing: 0.04em; }
+  .mpdf-doc h5 { font-size: ${Math.round(12 * hs)}px; font-weight: 600; color: ${s.headingColor}; margin: 10px 0 4px; font-style: italic; }
+  .mpdf-doc h6 { font-size: ${Math.round(11 * hs)}px; font-weight: 600; color: ${s.bodyColor}; margin: 8px 0 4px; font-style: italic; opacity: 0.75; }
+  .mpdf-doc p { margin: 0 0 ${s.paragraphSpacing}em; }
+  .mpdf-doc ul, .mpdf-doc ol { padding-inline-start: 1.4em; margin: 0 0 ${s.paragraphSpacing}em; }
+  .mpdf-doc li { margin-bottom: 0.2em; line-height: ${s.lineHeight}; }
+  .mpdf-doc blockquote {
+    border-inline-start: 3px solid ${s.blockquoteBorderColor};
+    background: ${s.blockquoteBg};
+    padding-block: 4px;
+    padding-inline: 1em 0;
+    margin: ${s.paragraphSpacing}em 0;
+    font-style: italic;
+    color: ${s.bodyColor}cc;
+  }
+  .mpdf-doc code {
+    font-family: 'Courier New', monospace;
+    font-size: ${s.codeFontSize}em;
+    background: ${s.codeBackground};
+    padding: 1px 4px;
+    border-radius: 3px;
+    color: ${s.accentColor};
+  }
+  ${buildCodeBlockCSS(s)}
+  .mpdf-doc hr {
+    border: none;
+    border-top: 0.5px solid ${s.accentColor}44;
+    margin: ${s.paragraphSpacing * 1.5}em 0;
+  }
+  .mpdf-doc img { max-width: 100%; height: auto; display: block; margin: ${s.paragraphSpacing}em auto; }
+  .mpdf-doc a { color: ${s.accentColor}; ${s.linkUnderline ? "" : "text-decoration: none;"} }
+  /* postProcessRenderedHTML removes the external-link class, but some themes
+     re-inject it at render time. This rule is cheap defense-in-depth. */
+  .mpdf-doc a.external-link::after { display: none !important; content: none !important; }
+  /* Hide copy-code buttons that survive postProcessRenderedHTML (e.g. re-injected by themes). */
+  .mpdf-doc .copy-code-button { display: none !important; }
+  .mpdf-doc table { width: 100%; border-collapse: collapse; margin: 0 0 ${s.paragraphSpacing}em; font-size: 0.92em; }
+  .mpdf-doc th {
+    background: ${s.tableHeaderBg};
+    color: ${tableHeaderTextColor};
+    padding: 6px 10px;
+    text-align: start;
+    font-weight: 600;
+    border: 0.5px solid ${s.accentColor}33;
+    font-size: 0.9em;
+  }
+  .mpdf-doc td { padding: 5px 10px; border: 0.5px solid ${s.bodyColor}22; vertical-align: top; }
+  ${s.tableStriped ? `.mpdf-doc tbody tr:nth-child(even) { background: ${s.tableHeaderBg}55; }` : ""}
+
+  /* Callouts — override theme styles with !important so preview and export are
+   * identical regardless of the active Obsidian theme. */
+  .mpdf-doc .callout {
+    border-inline-start: 4px solid ${s.accentColor} !important;
+    border-start-start-radius: 0 !important;
+    border-start-end-radius: 5px !important;
+    border-end-end-radius: 5px !important;
+    border-end-start-radius: 0 !important;
+    background: ${s.accentColor}12 !important;
+    margin: ${s.paragraphSpacing * 1.2}em 0 !important;
+    padding: 0 !important;
+    overflow: hidden !important;
+    box-shadow: inset 0 0 0 1px ${s.accentColor}22 !important;
+    font-style: normal !important;
+  }
+  .mpdf-doc .callout-title {
+    display: flex !important;
+    align-items: center !important;
+    gap: 7px !important;
+    padding: 7px 12px !important;
+    background: ${s.accentColor}28 !important;
+    border-bottom: 1px solid ${s.accentColor}33 !important;
+    font-family: ${fontFamily} !important;
+    font-size: 0.8em !important;
+    font-weight: 800 !important;
+    font-style: normal !important;
+    letter-spacing: 0.08em !important;
+    text-transform: uppercase !important;
+    color: ${s.accentColor} !important;
+    line-height: 1.3 !important;
+  }
+  .mpdf-doc .callout-icon {
+    display: inline-flex !important;
+    align-items: center !important;
+    flex-shrink: 0 !important;
+    width: 15px !important;
+    height: 15px !important;
+    color: ${s.accentColor} !important;
+  }
+  .mpdf-doc .callout-icon svg {
+    width: 15px !important;
+    height: 15px !important;
+    stroke: ${s.accentColor} !important;
+    fill: none !important;
+    stroke-width: 2 !important;
+  }
+  .mpdf-doc .callout-title-inner {
+    flex: 1 !important;
+    min-width: 0 !important;
+  }
+  .mpdf-doc .callout-fold { display: none !important; }
+  .mpdf-doc .callout-content {
+    padding: 9px 14px !important;
+    color: ${s.bodyColor} !important;
+    font-style: normal !important;
+    background: transparent !important;
+  }
+  .mpdf-doc .callout-content > p:first-child { margin-top: 0 !important; }
+  .mpdf-doc .callout-content > p:last-child  { margin-bottom: 0 !important; }
+  /* Nested blockquotes inside callout content keep a subtler indent */
+  .mpdf-doc .callout-content blockquote {
+    border-inline-start-color: ${s.accentColor}66 !important;
+    background: transparent !important;
+  }
+
+  /* Mermaid diagrams — centre the SVG and prevent it overflowing the content
+   * column.  The ` : ""}
+
+
+
+${pageHTMLParts.join("\n")}
+
+`;
+
+    try {
+      // Obsidian uses @electron/remote; the legacy `electron.remote` property is
+      // undefined in the renderer process of modern Electron versions.
+      const electron = window as unknown as ElectronBridge;
+      const remote = electron.require("@electron/remote") as ElectronRemote | null;
+      if (!remote?.dialog) throw new Error("no remote");
+
+      const res = await remote.dialog.showSaveDialog({
+        title: "Save PDF",
+        defaultPath: (this.currentFile?.basename ?? "export") + ".pdf",
+        filters: [{ name: "PDF", extensions: ["pdf"] }],
+      });
+      if (res.canceled || !res.filePath) {
+        resetExportBtn();
+        return;
+      }
+
+      new Notice("Advanced PDF Export — generating PDF…");
+
+      const blob = new Blob([fullHTML], { type: "text/html" });
+      const url  = URL.createObjectURL(blob);
+      const win  = new remote.BrowserWindow({ show: false, webPreferences: { nodeIntegration: false } });
+
+      win.loadURL(url);
+
+      // Both events can fire for the same load — a flag ensures only the first one acts.
+      let exportHandled = false;
+      const cleanupWin = () => { URL.revokeObjectURL(url); win.close(); resetExportBtn(); };
+
+      win.webContents.once("did-fail-load", (_event: unknown, _code: number, desc: string) => {
+        if (exportHandled) return;
+        exportHandled = true;
+        new Notice("Advanced PDF Export — failed to load page: " + desc);
+        cleanupWin();
+      });
+
+      win.webContents.once("did-finish-load", () => {
+        if (exportHandled) return;
+        exportHandled = true;
+
+        // Ensure all @font-face fonts (including inlined MathJax fonts) are loaded
+        // before capturing the PDF so math characters are not invisible.
+        win.webContents
+          .executeJavaScript("document.fonts.ready.then(() => true)")
+          .catch(() => true)
+          .then(() => {
+            // Custom sizes embed @page dimensions in the HTML; preferCSSPageSize lets
+            // Electron honour that rule. Named sizes pass the size string directly.
+            const isCustom = s.pageSize === "Custom";
+            return win.webContents.printToPDF({
+              pageSize:          isCustom ? "A4" : s.pageSize,
+              landscape:         !isCustom && s.orientation === "landscape",
+              preferCSSPageSize: isCustom,
+              printBackground:   true,
+              margins:           { marginType: "none" },
+            });
+          })
+          .then(async (data: Uint8Array) => {
+            // printToPDF produces a flat PDF with no outline; inject one via pdf-lib.
+            if (s.includeOutline) {
+              try {
+                data = await injectPDFOutline(data, extractOutlineEntries(layouts));
+              } catch (outlineErr) {
+                console.warn("[advanced-pdf-export] outline injection failed:", outlineErr);
+              }
+            }
+            electron.require("fs").writeFile(res.filePath!, data, (err: Error | null) => {
+              if (err) new Notice("Advanced PDF Export — failed to save: " + err.message);
+              else     new Notice("✓ PDF saved — " + res.filePath);
+              cleanupWin();
+            });
+          })
+          .catch((err: Error) => {
+            new Notice("Advanced PDF Export — failed to render: " + err.message);
+            cleanupWin();
+          });
+      });
+    } catch {
+      new Notice("Advanced PDF Export requires the Obsidian desktop app.");
+      resetExportBtn();
+    }
+  }
+}
diff --git a/src/main.ts b/src/main.ts
new file mode 100644
index 0000000..0ef8530
--- /dev/null
+++ b/src/main.ts
@@ -0,0 +1,126 @@
+// ─────────────────────────────────────────────────────────────────────────────
+// Plugin entry point.
+//
+// Thin bootstrap: registers the command/context-menu entry, owns the loaded
+// settings object, and hands off to PDFExportModal (export-modal.ts) and
+// PDFExportSettingTab (settings-tab.ts) for everything UI-related.
+// ─────────────────────────────────────────────────────────────────────────────
+
+import { Menu, Plugin, TFile } from "obsidian";
+import {
+  DocStyle, PDFExportSettings, PRESETS, DEFAULT_SETTINGS, extractDocStyle,
+} from "./settings";
+import { PDFExportModal } from "./export-modal";
+import { PDFExportSettingTab } from "./settings-tab";
+import { warmUpMathJax } from "./markdown";
+
+export default class MarkdownPDFPlugin extends Plugin {
+  declare settings: PDFExportSettings;
+  activeModal: PDFExportModal | null = null;
+  presetSnapshots: Record = {};
+
+  async onload() {
+    await this.loadSettings();
+    // Fire-and-forget: pay MathJax's one-time cold-start cost now, in the
+    // background, so it's already done by the time the user opens the export
+    // modal instead of adding several seconds to their first real render.
+    void warmUpMathJax(this.app);
+    this.addCommand({
+      id: "open-panel",
+      name: "Open Panel",
+      callback: () => this.openModal(),
+    });
+    this.registerEvent(
+      this.app.workspace.on("file-menu", (menu: Menu, file) => {
+        if (!(file instanceof TFile) || file.extension !== "md") return;
+        menu.addItem((item) =>
+          item.setTitle("Advanced PDF Export: Open Panel").setIcon("file-output")
+              .onClick(() => this.openModal(file)),
+        );
+      }),
+    );
+    this.addSettingTab(new PDFExportSettingTab(this.app, this));
+  }
+
+  onunload() {
+    this.activeModal?.close();
+  }
+
+  openModal(file?: TFile) {
+    if (this.activeModal) this.activeModal.close();
+    new PDFExportModal(this.app, this, file).open();
+  }
+
+  async loadSettings() {
+    const data = (await this.loadData() ?? {}) as Partial & { presetSnapshots?: Record };
+    this.settings = Object.assign({}, DEFAULT_SETTINGS, data);
+
+    // Migration: codeTheme was added per-preset; absent value adopts the active preset's default.
+    if (data.codeTheme === undefined) {
+      this.settings.codeTheme = PRESETS[this.settings.preset]?.codeTheme ?? DEFAULT_SETTINGS.codeTheme;
+    }
+
+    this.presetSnapshots = data.presetSnapshots ?? {};
+    this.validateSettings();
+  }
+
+  /** Clamps critical numeric settings to safe ranges and repairs invalid
+   *  enum values. Called after load so corrupt or manually-edited JSON
+   *  cannot produce invisible text, zero-size pages, or bad layout. */
+  private validateSettings(): void {
+    const s = this.settings;
+
+    // Unknown preset key → fall back to default.
+    if (!(s.preset in PRESETS)) {
+      console.warn(`[advanced-pdf-export] Unknown preset "${s.preset}", resetting to "default".`);
+      s.preset = "default";
+    }
+
+    // Font sizes must be positive to produce visible text.
+    s.fontSize         = Math.max(1,  s.fontSize);
+    s.headerFontSize   = Math.max(1,  s.headerFontSize);
+    s.footerFontSize   = Math.max(1,  s.footerFontSize);
+
+    // Margins must be non-negative; zero is allowed (full-bleed layouts).
+    s.marginTop        = Math.max(0,  s.marginTop);
+    s.marginBottom     = Math.max(0,  s.marginBottom);
+    s.marginLeft       = Math.max(0,  s.marginLeft);
+    s.marginRight      = Math.max(0,  s.marginRight);
+
+    // Custom page dimensions need a printable minimum.
+    s.customPageWidth  = Math.max(10, s.customPageWidth);
+    s.customPageHeight = Math.max(10, s.customPageHeight);
+
+    // Preview scale must be a usable positive fraction.
+    s.previewScale     = Math.max(0.1, Math.min(3, s.previewScale));
+
+    // Page-number start must be at least 1.
+    s.pageNumberStart  = Math.max(1,  s.pageNumberStart);
+
+    // Page-number format: fall back to default when cleared.
+    if (!s.pageNumberFormat || !s.pageNumberFormat.trim()) {
+      s.pageNumberFormat = DEFAULT_SETTINGS.pageNumberFormat;
+    }
+  }
+
+  async saveSettings() {
+    await this.saveData({ ...this.settings, presetSnapshots: this.presetSnapshots });
+  }
+
+  async saveSettingsAndRender() {
+    await this.saveSettings();
+    this.activeModal?.render();
+  }
+
+  applyPreset(key: string, reset = false) {
+    const p = PRESETS[key];
+    if (!p) return;
+    if (reset) {
+      delete this.presetSnapshots[key];
+    } else {
+      this.presetSnapshots[this.settings.preset] = extractDocStyle(this.settings);
+    }
+    this.settings.preset = key;
+    Object.assign(this.settings, p, reset ? {} : (this.presetSnapshots[key] ?? {}));
+  }
+}
diff --git a/src/markdown.ts b/src/markdown.ts
new file mode 100644
index 0000000..0c067d5
--- /dev/null
+++ b/src/markdown.ts
@@ -0,0 +1,261 @@
+// ─────────────────────────────────────────────────────────────────────────────
+// Markdown preprocessing + render pipeline.
+//
+// Everything involved in turning a note's raw markdown text into clean,
+// paginator-ready HTML: text-level prep (line-ending normalisation,
+// frontmatter stripping, manual page-break splitting, RTL detection),
+// then handing sections off to Obsidian's MarkdownRenderer and waiting out
+// its async post-processors (Mermaid, MathJax) before cleaning up the result.
+// ─────────────────────────────────────────────────────────────────────────────
+
+import { App, Component, MarkdownRenderer, finishRenderMath } from "obsidian";
+import { waitForMathJaxStylesheetStable } from "./css-builder";
+
+// ─── Markdown text helpers ─────────────────────────────────────────────────────
+
+/** Normalises line endings to LF so the rest of the pipeline never sees CRLF or CR. */
+export function normalizeMarkdown(raw: string): string {
+  return raw.replace(/\r\n|\r/g, "\n");
+}
+
+/** Strips an opening YAML frontmatter block (--- … ---). Input must be LF-normalised. */
+export function stripFrontmatter(md: string): string {
+  return md.replace(/^---[ \t]*\n[\s\S]*?\n---[ \t]*(\n|$)/, "");
+}
+
+/** Splits on `///` manual page-break markers, trimming and dropping empty sections. */
+export function splitMarkdownSections(md: string): string[] {
+  return md
+    .split(/^\/\/\/\s*$/m)
+    .map((s) => s.trim())
+    .filter(Boolean);
+}
+
+/** True when RTL script chars (Arabic, Hebrew, etc.) exceed 10 % of all
+ *  alpha chars — ratio-based so mixed-script notes lean toward the majority. */
+const RTL_CHARS   = /[\u0590-\u08FF\uFB1D-\uFDFD\uFE70-\uFEFC]/g;
+const TOTAL_ALPHA = /[A-Za-z\u0590-\u08FF\uFB1D-\uFDFD\uFE70-\uFEFC]/g;
+export function isRTLContent(text: string): boolean {
+  const rtl   = (text.match(RTL_CHARS)   ?? []).length;
+  const total = (text.match(TOTAL_ALPHA) ?? []).length;
+  return total > 0 && rtl / total > 0.1;
+}
+
+// ─── Rendered-HTML cleanup ──────────────────────────────────────────────────────
+
+// Pre-compiled once. String.replace() and String.matchAll() both reset a
+// regex's lastIndex to 0 on each call, so module-level g-flagged constants are safe.
+const SLUG_STRIP = /[^\p{L}\p{N}\s-]/gu;
+const SLUG_SPACE = /\s+/g;
+const SLUG_DASH  = /-+/g;
+
+function slugifyHeading(text: string): string {
+  return text
+    .toLowerCase()
+    .replace(SLUG_STRIP, "")
+    .trim()
+    .replace(SLUG_SPACE, "-")
+    .replace(SLUG_DASH,  "-");
+}
+
+// Strips Obsidian-specific artefacts from rendered HTML so the output is
+// clean for pagination and export: assigns stable heading IDs for anchor
+// links, removes external-link decorators and copy-code buttons, force-expands
+// callouts, and strips top-level theme `, and are not needed in the PDF.
+  // Styles inside  are kept: mermaid embeds its theme CSS directly there.
+  root.querySelectorAll("style, script").forEach((el) => {
+    if (!el.closest("svg")) el.remove();
+  });
+}
+
+// ─── Async post-processor waits ────────────────────────────────────────────────
+
+/** Waits for mermaid code blocks to be converted to SVGs by Obsidian's post-processor.
+ *  Resolves immediately if already rendered; times out per diagram after 5 s. */
+async function waitForMermaidDiagrams(el: HTMLElement): Promise {
+  const containers = Array.from(el.querySelectorAll(".mermaid"));
+  if (containers.length === 0) return;
+  const TIMEOUT_MS = 5000;
+  await Promise.all(
+    containers.map(
+      (m) =>
+        new Promise((resolve) => {
+          if (m.querySelector("svg")) { resolve(); return; }
+          const timer = window.setTimeout(() => { obs.disconnect(); resolve(); }, TIMEOUT_MS);
+          const obs = new MutationObserver(() => {
+            if (m.querySelector("svg")) {
+              window.clearTimeout(timer);
+              obs.disconnect();
+              resolve();
+            }
+          });
+          obs.observe(m, { childList: true, subtree: true });
+        }),
+    ),
+  );
+}
+
+/** Waits for MathJax to finish typesetting `.math` spans (native math and
+ *  Latex Suite equations share the same renderer).
+ *
+ *  `MathJax.startup.promise` is awaited first as a cheap early gate — it
+ *  resolves once, at MathJax's initial boot, so it proves nothing about
+ *  whether this particular render pass is finished. The real wait is a
+ *  per-element `mjx-container` observer, followed by
+ *  `waitForMathJaxStylesheetStable()`: MathJax's CHTML `adaptiveCSS` mode
+ *  writes per-glyph rules to a shared stylesheet incrementally as new
+ *  characters are encountered, and DOM insertion of `mjx-container` alone
+ *  doesn't guarantee that write has landed yet. Bounded at 8s + 2.5s so a
+ *  stuck render can't hang the export indefinitely. */
+async function waitForMathRendering(el: HTMLElement): Promise {
+  const containers = Array.from(el.querySelectorAll(".math"));
+  if (containers.length === 0) return;
+
+  const mathJax = (window as unknown as {
+    MathJax?: { startup?: { promise?: Promise } };
+  }).MathJax;
+  if (mathJax?.startup?.promise) {
+    try { await mathJax.startup.promise; } catch { /* fall through to per-element wait */ }
+  }
+
+  const TIMEOUT_MS = 8000;
+  await Promise.all(
+    containers
+      .filter((m) => !m.querySelector("mjx-container"))
+      .map(
+        (m) =>
+          new Promise((resolve) => {
+            const timer = window.setTimeout(() => { obs.disconnect(); resolve(); }, TIMEOUT_MS);
+            const obs = new MutationObserver(() => {
+              if (m.querySelector("mjx-container")) {
+                window.clearTimeout(timer);
+                obs.disconnect();
+                resolve();
+              }
+            });
+            obs.observe(m, { childList: true, subtree: true });
+          }),
+      ),
+  );
+
+  await waitForMathJaxStylesheetStable();
+}
+
+// ─── Render pipeline ────────────────────────────────────────────────────────────
+
+/** Renders a markdown string to a detached HTML element via Obsidian's
+ *  MarkdownRenderer, waiting for Mermaid/MathJax post-processors and web
+ *  fonts to finish before returning the cleaned-up result. */
+export async function renderMarkdownToEl(
+  app: App,
+  markdown: string,
+  sourcePath: string,
+  component: Component,
+): Promise {
+  const temp = activeDocument.createElement("div");
+  // Attached offscreen so Obsidian's async post-processors (mermaid, math) run in a real DOM context.
+  temp.setCssStyles({ position: "fixed", top: "0", left: "-99999px", visibility: "hidden", pointerEvents: "none" });
+  activeDocument.body.appendChild(temp);
+  try {
+    await MarkdownRenderer.render(app, markdown, temp, sourcePath, component);
+    // Flushes Obsidian's MathJax render queue — MarkdownRenderer.render()'s own
+    // promise can resolve before queued math has actually finished typesetting.
+    // Bounded with a race: on a cold Obsidian session (MathJax not yet used
+    // anywhere in this window), this has been observed to hang far longer than
+    // expected instead of resolving, blocking the whole render indefinitely.
+    // waitForMathRendering()/waitForMathJaxStylesheetStable() below are the
+    // real, already-bounded correctness check regardless of whether this
+    // resolves in time — so there's no harm in giving up on it early.
+    const FINISH_RENDER_MATH_TIMEOUT_MS = 3000;
+    try {
+      let timer: number;
+      await Promise.race([
+        finishRenderMath().finally(() => window.clearTimeout(timer)),
+        new Promise((resolve) => { timer = window.setTimeout(resolve, FINISH_RENDER_MATH_TIMEOUT_MS); }),
+      ]);
+    } catch (err) {
+      console.warn("[advanced-pdf-export] finishRenderMath failed:", err);
+    }
+    await waitForMermaidDiagrams(temp);
+    await waitForMathRendering(temp);
+    // Wait for MathJax's lazily-loaded @font-face files to arrive before we
+    // clone nodes; glyphs in unloaded font ranges render as invisible characters.
+    const docFonts = (activeDocument as Document & { fonts?: { ready?: Promise } }).fonts;
+    if (docFonts) {
+      try { await docFonts.ready; } catch { /* non-critical */ }
+    }
+  } finally {
+    activeDocument.body.removeChild(temp);
+  }
+  postProcessRenderedHTML(temp);
+  return temp;
+}
+
+/** Fires MathJax's one-time cold-start boot and `adaptiveCSS` setup for the
+ *  font families most often missing on a session's first real render (bold,
+ *  AMS symbols, blackboard-bold, fraktur, calligraphic, sans-serif,
+ *  typewriter, vector) as soon as the plugin loads, in the background —
+ *  rather than paying that cost the first time the user actually renders.
+ *
+ *  Deliberately goes through the same `renderMarkdownToEl` pipeline used for
+ *  real renders instead of calling `renderMath()`/`finishRenderMath()`
+ *  directly: Obsidian only creates its global `MathJax` object lazily, the
+ *  first time something is typeset through its markdown post-processor
+ *  pipeline. Calling `renderMath()` directly before that has happened throws
+ *  `ReferenceError: MathJax is not defined` instead of triggering the load.
+ *
+ *  Fire-and-forget: nothing downstream awaits this, and the real render path
+ *  still verifies completion correctly on its own regardless of whether this
+ *  has finished. */
+export async function warmUpMathJax(app: App): Promise {
+  const component = new Component();
+  component.load();
+  try {
+    await renderMarkdownToEl(
+      app,
+      "$\\mathbf{A}+\\mathfrak{A}+\\mathcal{A}+\\mathsf{A}+\\mathtt{A}+\\mathbb{A}+\\aleph+\\vec{v}$",
+      "",
+      component,
+    );
+  } catch (err) {
+    console.warn("[advanced-pdf-export] MathJax warm-up failed (non-fatal):", err);
+  } finally {
+    component.unload();
+  }
+}
diff --git a/src/paginator.ts b/src/paginator.ts
new file mode 100644
index 0000000..235a094
--- /dev/null
+++ b/src/paginator.ts
@@ -0,0 +1,655 @@
+// ─────────────────────────────────────────────────────────────────────────────
+// Pagination engine + PDF outline (bookmarks).
+//
+// Takes rendered HTML sections and distributes their block children into
+// page-height buckets, splitting oversized elements by natural unit (line,
+// row, list item, word/character). Also builds the per-page header/footer
+// text (buildPageLayouts) and, for export, injects a bookmark tree into the
+// finished PDF bytes derived from the same paginated headings. This is one
+// self-contained algorithm — nothing here talks to Obsidian or the DOM
+// outside of measuring already-rendered elements.
+// ─────────────────────────────────────────────────────────────────────────────
+
+import { PDFArray, PDFDict, PDFDocument, PDFHexString, PDFName, PDFNull, PDFNumber } from "pdf-lib";
+import { PDFExportSettings } from "./settings";
+
+/** One entry in the PDF outline/bookmark tree, extracted from the heading nodes. */
+export interface OutlineEntry {
+  title: string;
+  level: number; // 1–6 matching H1–H6
+  page:  number; // 1-indexed page number in the exported PDF
+}
+
+export interface PageLayout {
+  pageNodes: HTMLElement[];
+  pageNum: number;
+  totalPages: number;
+  pageShowsHeader: boolean;
+  pageShowsFooter: boolean;
+  hasHeader: boolean;
+  hasFooter: boolean;
+  headerLeft: string;
+  headerCenter: string;
+  headerRight: string;
+  footerLeft: string;
+  footerRight: string;
+  footerCenter: string;
+}
+
+// ─── Shared measurement helpers ─────────────────────────────────────────────────
+
+const INLINE_SPLIT_TAGS = new Set(["P", "LI", "BLOCKQUOTE", "TD", "TH"]);
+
+const BLOCK_TAGS = new Set([
+  "P", "DIV", "SECTION", "ARTICLE", "ASIDE", "NAV", "HEADER", "FOOTER",
+  "UL", "OL", "LI", "TABLE", "THEAD", "TBODY", "TFOOT", "TR", "TD", "TH",
+  "PRE", "BLOCKQUOTE", "HR", "IMG",
+  "H1", "H2", "H3", "H4", "H5", "H6",
+]);
+
+// PRE is absent — it gets its own line-based splitter.
+const UNSPLITTABLE_TAGS = new Set([
+  "CODE", "IMG", "HR", "H1", "H2", "H3", "H4", "H5", "H6",
+]);
+
+// 2px guards against sub-pixel rendering differences between the light-DOM
+// paginator sandbox and the shadow DOM preview context.
+const HEIGHT_EPS = 2;
+
+function measureNodesHeight(nodes: HTMLElement[], measureEl: HTMLElement): number {
+  measureEl.empty();
+  for (const node of nodes) measureEl.appendChild(node.cloneNode(true));
+  return measureEl.getBoundingClientRect().height;
+}
+
+function makeFitFn(
+  currentPage: HTMLElement[],
+  measureEl: HTMLElement,
+  contentHeightPx: number,
+): (node: HTMLElement) => boolean {
+  return (node: HTMLElement) =>
+    measureNodesHeight([...currentPage, node], measureEl) <= contentHeightPx - HEIGHT_EPS;
+}
+
+// ── Inline (text) splitter ───────────────────────────────────────────────────
+
+function trimLeadingWhitespace(el: HTMLElement): void {
+  const walker = activeDocument.createTreeWalker(el, NodeFilter.SHOW_TEXT);
+  while (walker.nextNode()) {
+    const node = walker.currentNode as Text;
+    const trimmed = (node.textContent ?? "").replace(/^\s+/, "");
+    if (trimmed !== node.textContent) node.textContent = trimmed;
+    if (trimmed.length > 0) break;
+  }
+}
+
+function buildInlineSplitAt(
+  el: HTMLElement,
+  splitOffset: number,
+  trimSecond = true,
+): [HTMLElement, HTMLElement] | null {
+  const walker = activeDocument.createTreeWalker(el, NodeFilter.SHOW_TEXT);
+  let count = 0;
+  let target: Text | null = null;
+  let localOffset = 0;
+
+  while (walker.nextNode()) {
+    const node = walker.currentNode as Text;
+    const len = node.textContent?.length ?? 0;
+    if (count + len >= splitOffset) {
+      target = node;
+      localOffset = splitOffset - count;
+      break;
+    }
+    count += len;
+  }
+
+  if (!target) return null;
+
+  const range1 = activeDocument.createRange();
+  range1.selectNodeContents(el);
+  range1.setEnd(target, localOffset);
+
+  const range2 = activeDocument.createRange();
+  range2.selectNodeContents(el);
+  range2.setStart(target, localOffset);
+
+  const first = el.cloneNode(false) as HTMLElement;
+  first.appendChild(range1.cloneContents());
+
+  const second = el.cloneNode(false) as HTMLElement;
+  second.appendChild(range2.cloneContents());
+  if (trimSecond) trimLeadingWhitespace(second);
+
+  return [first, second];
+}
+
+function getWordBoundaryOffsets(text: string): number[] {
+  const offsets: number[] = [];
+  const re = /\s+/g;
+  let match: RegExpExecArray | null;
+  while ((match = re.exec(text))) {
+    if (match.index > 0 && match.index < text.length) offsets.push(match.index);
+  }
+  return offsets;
+}
+
+function splitInlineElement(
+  el: HTMLElement,
+  fits: (node: HTMLElement) => boolean,
+  forceSplit: boolean,
+): [HTMLElement, HTMLElement] | null {
+  const text = el.textContent ?? "";
+  if (text.length < 2) return null;
+
+  // First attempt: binary-search for the latest word boundary that fits.
+  const offsets = getWordBoundaryOffsets(text);
+  if (offsets.length > 0) {
+    let lo = 0, hi = offsets.length - 1, bestIdx = -1;
+    while (lo <= hi) {
+      const mid = Math.floor((lo + hi) / 2);
+      const split = buildInlineSplitAt(el, offsets[mid]);
+      if (!split) { hi = mid - 1; continue; }
+      if (fits(split[0])) { bestIdx = mid; lo = mid + 1; }
+      else                { hi = mid - 1; }
+    }
+    if (bestIdx >= 0) return buildInlineSplitAt(el, offsets[bestIdx]);
+    if (!forceSplit) return null;
+  }
+
+  // Fallback: character-level binary search (oversized single word, or forced).
+  let lo = 1, hi = text.length - 1, best = 0;
+  while (lo <= hi) {
+    const mid = Math.floor((lo + hi) / 2);
+    const split = buildInlineSplitAt(el, mid);
+    if (!split) { hi = mid - 1; continue; }
+    if (fits(split[0])) { best = mid; lo = mid + 1; }
+    else                { hi = mid - 1; }
+  }
+  return best > 0 ? buildInlineSplitAt(el, best) : null;
+}
+
+// ── List splitter ────────────────────────────────────────────────────────────
+
+function buildListWithItems(listEl: HTMLElement, items: HTMLElement[], startAt?: number): HTMLElement {
+  const clone = listEl.cloneNode(false) as HTMLElement;
+  // Preserve OL numbering across page breaks.
+  if (listEl.tagName === "OL" && startAt !== undefined && startAt > 1) {
+    (clone as HTMLOListElement).start = startAt;
+  }
+  for (const item of items) clone.appendChild(item.cloneNode(true));
+  return clone;
+}
+
+function splitListElement(
+  listEl: HTMLElement,
+  fits: (node: HTMLElement) => boolean,
+  forceSplit: boolean,
+): [HTMLElement, HTMLElement] | null {
+  const items = Array.from(listEl.children).filter(
+    (c) => (c as HTMLElement).tagName === "LI",
+  ) as HTMLElement[];
+  if (items.length === 0) return null;
+
+  // Respect an existing start attribute on continuation fragments.
+  const existingStart = listEl.tagName === "OL"
+    ? ((listEl as HTMLOListElement).start ?? 1)
+    : 1;
+
+  let fitCount = 0;
+  for (let i = 0; i < items.length; i++) {
+    if (fits(buildListWithItems(listEl, items.slice(0, i + 1), existingStart))) fitCount = i + 1;
+    else break;
+  }
+
+  // When forced (alone on empty page), guarantee at least 1 item moves forward.
+  if (fitCount <= 0) {
+    if (!forceSplit || items.length < 2) return null;
+    fitCount = 1;
+  }
+  if (fitCount >= items.length) return null;
+
+  return [
+    buildListWithItems(listEl, items.slice(0, fitCount), existingStart),
+    // Second fragment starts at existingStart + fitCount so numbering is continuous.
+    buildListWithItems(listEl, items.slice(fitCount), existingStart + fitCount),
+  ];
+}
+
+// ── Table splitter ───────────────────────────────────────────────────────────
+
+function buildTableWithRows(tableEl: HTMLTableElement, rows: HTMLTableRowElement[]): HTMLTableElement {
+  const clone = tableEl.cloneNode(false) as HTMLTableElement;
+  const caption = tableEl.querySelector("caption");
+  if (caption) clone.appendChild(caption.cloneNode(true));
+  const colgroup = tableEl.querySelector("colgroup");
+  if (colgroup) clone.appendChild(colgroup.cloneNode(true));
+  if (tableEl.tHead) clone.appendChild(tableEl.tHead.cloneNode(true));
+  const tbody = activeDocument.createElement("tbody");
+  for (const row of rows) tbody.appendChild(row.cloneNode(true));
+  clone.appendChild(tbody);
+  return clone;
+}
+
+function splitTableElement(
+  tableEl: HTMLTableElement,
+  fits: (node: HTMLElement) => boolean,
+  forceSplit: boolean,
+): [HTMLElement, HTMLElement] | null {
+  const body = tableEl.tBodies[0];
+  const rows = body
+    ? Array.from(body.rows)
+    : Array.from(tableEl.rows).filter((r) => r.parentElement?.tagName !== "THEAD");
+  if (rows.length === 0) return null;
+
+  let fitCount = 0;
+  for (let i = 0; i < rows.length; i++) {
+    if (fits(buildTableWithRows(tableEl, rows.slice(0, i + 1)))) fitCount = i + 1;
+    else break;
+  }
+
+  // When forced (alone on empty page), guarantee at least 1 row moves forward.
+  if (fitCount <= 0) {
+    if (!forceSplit || rows.length < 2) return null;
+    fitCount = 1;
+  }
+  if (fitCount >= rows.length) return null;
+
+  return [
+    buildTableWithRows(tableEl, rows.slice(0, fitCount)),
+    buildTableWithRows(tableEl, rows.slice(fitCount)),
+  ];
+}
+
+// ── PRE splitter ─────────────────────────────────────────────────────────────
+// Splits a code block by line. When a  child is present (true for all
+// fenced code blocks), buildInlineSplitAt's Range-based split preserves the
+// nested Prism `.token.*` span structure across the break.
+
+/** Character offsets (within the element's full text content) marking the
+ *  start of the line *after* each line — i.e. valid split points. */
+function getLineEndOffsets(lines: string[]): number[] {
+  const offsets: number[] = [];
+  let offset = 0;
+  for (const line of lines) {
+    offset += line.length + 1; // +1 for the newline separating this line from the next
+    offsets.push(offset);
+  }
+  return offsets;
+}
+
+function splitPreElement(
+  preEl: HTMLElement,
+  fits: (node: HTMLElement) => boolean,
+  forceSplit: boolean,
+): [HTMLElement, HTMLElement] | null {
+  const codeEl = preEl.querySelector("code");
+  const lines = (codeEl ?? preEl).textContent?.split("\n") ?? [];
+  // Drop the trailing empty string that String.split() produces.
+  if (lines.length > 1 && lines[lines.length - 1] === "") lines.pop();
+  if (lines.length < 2) return null;
+
+  const lineEndOffsets = getLineEndOffsets(lines);
+
+  // Splits at the boundary after the first `n` lines, preserving syntax
+  // highlighting via Range.cloneContents() when a  child is present.
+  const buildSplit = (n: number): [HTMLElement, HTMLElement] | null => {
+    if (!codeEl) {
+      const clone = (text: string) => {
+        const el = preEl.cloneNode(false) as HTMLElement;
+        el.textContent = text;
+        return el;
+      };
+      return [clone(lines.slice(0, n).join("\n")), clone(lines.slice(n).join("\n"))];
+    }
+    const split = buildInlineSplitAt(codeEl, lineEndOffsets[n - 1], false);
+    if (!split) return null;
+    const first = preEl.cloneNode(false) as HTMLElement;
+    first.appendChild(split[0]);
+    const second = preEl.cloneNode(false) as HTMLElement;
+    second.appendChild(split[1]);
+    return [first, second];
+  };
+
+  let best: [HTMLElement, HTMLElement] | null = null;
+  let fitCount = 0;
+  for (let i = 1; i <= lines.length; i++) {
+    const candidate = buildSplit(i);
+    if (!candidate || !fits(candidate[0])) break;
+    best = candidate;
+    fitCount = i;
+  }
+
+  if (fitCount <= 0) {
+    if (!forceSplit) return null;
+    best = buildSplit(1);
+    fitCount = 1;
+  }
+  if (fitCount >= lines.length || !best) return null;
+
+  return best;
+}
+
+// ── Element splitter dispatcher ──────────────────────────────────────────────
+
+function isInlineSplitCandidate(el: HTMLElement): boolean {
+  if (!INLINE_SPLIT_TAGS.has(el.tagName)) return false;
+  for (const child of Array.from(el.childNodes)) {
+    if (child.nodeType === Node.ELEMENT_NODE && BLOCK_TAGS.has((child as HTMLElement).tagName))
+      return false;
+  }
+  return true;
+}
+
+function splitElement(
+  el: HTMLElement,
+  fits: (node: HTMLElement) => boolean,
+  forceSplit: boolean,
+): [HTMLElement, HTMLElement] | null {
+  if (UNSPLITTABLE_TAGS.has(el.tagName)) return null;
+  if (el.tagName === "PRE")   return splitPreElement(el, fits, forceSplit);
+  if (el.tagName === "TABLE") return splitTableElement(el as HTMLTableElement, fits, forceSplit);
+  if (el.tagName === "UL" || el.tagName === "OL") return splitListElement(el, fits, forceSplit);
+  if (isInlineSplitCandidate(el)) return splitInlineElement(el, fits, forceSplit);
+  return null;
+}
+
+// ── Main pagination loop ─────────────────────────────────────────────────────
+
+/** Distributes a rendered section's block children into page-height buckets,
+ *  splitting oversized elements by natural unit (line, row, list item, word,
+ *  or character) when they don't fit whole. Returns one HTMLElement[] per page. */
+export function paginateEl(
+  sourceEl: HTMLElement,
+  contentWidthPx: number,
+  contentHeightPx: number,
+  docCSS: string,
+): HTMLElement[][] {
+  // Hidden shadow-root sandbox: scoped CSS prevents host-document pollution.
+  const sandboxHost = activeDocument.createElement("div");
+  sandboxHost.setCssStyles({
+    position: "fixed", top: "0", left: "-99999px",
+    width: `${contentWidthPx}px`,
+    visibility: "hidden", pointerEvents: "none", zIndex: "-1",
+  });
+
+  const sandboxShadow = sandboxHost.attachShadow({ mode: "open" });
+
+  const sandboxSheet = new CSSStyleSheet();
+  sandboxSheet.replaceSync(docCSS);
+  sandboxShadow.adoptedStyleSheets = [sandboxSheet];
+
+  const inner = activeDocument.createElement("div");
+  inner.className = "mpdf-doc";
+  for (const child of Array.from(sourceEl.children)) {
+    inner.appendChild(child.cloneNode(true));
+  }
+  sandboxShadow.appendChild(inner);
+
+  // Measurement div: same width, always empty before each measurement.
+  const measure = activeDocument.createElement("div");
+  measure.className = "mpdf-doc";
+  measure.setCssStyles({ position: "absolute", top: "0", left: "0", width: `${contentWidthPx}px`, visibility: "hidden" });
+  sandboxShadow.appendChild(measure);
+
+  activeDocument.body.appendChild(sandboxHost);
+
+  const pages: HTMLElement[][] = [];
+  try {
+    let currentPage: HTMLElement[] = [];
+    const children = Array.from(inner.children) as HTMLElement[];
+    let idx = 0;
+
+    while (idx < children.length) {
+      const child = children[idx];
+      const fits = makeFitFn(currentPage, measure, contentHeightPx);
+
+      if (fits(child)) {
+        currentPage.push(child.cloneNode(true) as HTMLElement);
+        idx++;
+        continue;
+      }
+
+      // Element doesn't fit. Try to split it across the page boundary.
+      const forceSplit = currentPage.length === 0;
+      const split = splitElement(child, fits, forceSplit);
+      if (split) {
+        currentPage.push(split[0]);
+        pages.push(currentPage);
+        currentPage = [];
+        // Replace current child with the remainder for re-processing.
+        const remainder = split[1];
+        if (remainder.textContent?.trim() || remainder.children.length > 0) {
+          children[idx] = remainder;
+        } else {
+          idx++;
+        }
+        continue;
+      }
+
+      // Can't split. If there's content on this page, flush it and retry the
+      // same element on a fresh full-height page.
+      if (currentPage.length > 0) {
+        pages.push(currentPage);
+        currentPage = [];
+        continue;
+      }
+
+      // Element is alone on an empty page and truly unsplittable (e.g. a giant
+      // image). Force it onto its own page and advance so we never stall.
+      currentPage.push(child.cloneNode(true) as HTMLElement);
+      pages.push(currentPage);
+      currentPage = [];
+      idx++;
+    }
+
+    if (currentPage.length > 0) pages.push(currentPage);
+  } finally {
+    activeDocument.body.removeChild(sandboxHost);
+  }
+  return pages.length > 0 ? pages : [[]];
+}
+
+// ─── Page layout builder ──────────────────────────────────────────────────────
+
+/** Resolves a page-number format template by substituting the {{current}}
+ *  and {{total}} placeholders with the given values. Falls back to the
+ *  default "current / total" template when the format is empty. */
+function resolvePageNumberFormat(format: string, current: number, total: number): string {
+  const template = format && format.trim() ? format : "{{current}} / {{total}}";
+  return template
+    .replace(/\{\{\s*current\s*\}\}/g, String(current))
+    .replace(/\{\{\s*total\s*\}\}/g, String(total));
+}
+
+/** Converts paginated page-node arrays into fully-resolved PageLayout objects,
+ *  computing header/footer text and page number strings for each page. */
+export function buildPageLayouts(allPages: HTMLElement[][], s: PDFExportSettings): PageLayout[] {
+  const totalPages = allPages.length;
+  return allPages.map((pageNodes, i) => {
+    const pageNum = i + 1;
+    const pageShowsHeader = s.showHeaderOnFirstPage || i > 0;
+    const pageShowsFooter = s.showFooterOnFirstPage || i > 0;
+
+    // Page-number offset: when footer is hidden on page 1 the numbering shifts by 1.
+    const displayNum   = s.showFooterOnFirstPage ? s.pageNumberStart + i       : s.pageNumberStart + (i - 1);
+    const displayTotal = s.showFooterOnFirstPage ? s.pageNumberStart + totalPages - 1 : s.pageNumberStart + totalPages - 2;
+    const numStr = resolvePageNumberFormat(s.pageNumberFormat, displayNum, displayTotal);
+
+    let footerLeft = "", footerRight = "", footerCenter = "";
+    let headerLeft = "", headerCenter = "", headerRight = "";
+
+    if (pageShowsFooter) {
+      if (s.footerText) {
+        if      (s.footerTextAlignment === "center") footerCenter = s.footerText;
+        else if (s.footerTextAlignment === "left")   footerLeft   = s.footerText;
+        else                                          footerRight  = s.footerText;
+      }
+      // Place page number in its own zone; merge with a separator when both land in the same slot.
+      if (s.showPageNumbers) {
+        const join = (existing: string) => existing ? existing + " — " + numStr : numStr;
+        if      (s.pageNumberPosition === "center") footerCenter = join(footerCenter);
+        else if (s.pageNumberPosition === "left")   footerLeft   = join(footerLeft);
+        else                                         footerRight  = join(footerRight);
+      }
+    }
+
+    if (pageShowsHeader) {
+      if (s.headerText) {
+        if (s.headerAlignment === "center") {
+          headerCenter = s.headerText;
+        } else if (s.headerAlignment === "left") {
+          headerLeft = s.headerText;
+        } else {
+          headerRight = s.headerText;
+        }
+      }
+    }
+
+    // Compute once here so both preview and export paths can read directly from
+    // the layout object instead of re-deriving the same boolean expressions.
+    const hasHeader = s.showHeader && pageShowsHeader && !!(headerLeft || headerCenter || headerRight || s.showHeaderBorder);
+    const hasFooter = s.showFooter && pageShowsFooter && !!(footerLeft || footerRight || footerCenter || s.showFooterBorder);
+
+    return { pageNodes, pageNum, totalPages, pageShowsHeader, pageShowsFooter, hasHeader, hasFooter, headerLeft, headerCenter, headerRight, footerLeft, footerRight, footerCenter };
+  });
+}
+
+// ─── PDF outline (bookmarks) ──────────────────────────────────────────────────
+// Electron's printToPDF does not generate bookmarks — we post-process the raw
+// PDF bytes with pdf-lib to inject a hierarchical outline derived from the
+// heading elements already present in the paginated layout.
+
+/**
+ * Walks every page's node list and collects heading elements in document order.
+ * Headings can sit at the top level of pageNodes (the common case) or be nested
+ * inside a container fragment produced by the page-splitter.
+ */
+export function extractOutlineEntries(layouts: PageLayout[]): OutlineEntry[] {
+  const entries: OutlineEntry[] = [];
+  for (const layout of layouts) {
+    for (const node of layout.pageNodes) {
+      const topLevel: HTMLElement[] = /^H[1-6]$/.test(node.tagName) ? [node] : [];
+      const nested = Array.from(node.querySelectorAll("h1,h2,h3,h4,h5,h6"));
+      for (const el of [...topLevel, ...nested]) {
+        const level = parseInt(el.tagName[1], 10);
+        const title = (el.textContent ?? "").trim();
+        if (title) entries.push({ title, level, page: layout.pageNum });
+      }
+    }
+  }
+  return entries;
+}
+
+/**
+ * Post-processes a PDF buffer produced by `printToPDF` and injects a
+ * hierarchical bookmark outline built from the supplied entries.
+ *
+ * Heading nesting (H1 → H2 → H3 …) is preserved. Each item links to its page
+ * via an XYZ destination that inherits the reader's current zoom. Sub-trees are
+ * collapsed by default (negative /Count per PDF spec). PageMode is set to
+ * UseOutlines so readers open the bookmarks panel on load.
+ */
+export async function injectPDFOutline(pdfBuffer: Uint8Array, entries: OutlineEntry[]): Promise {
+  if (!entries.length) return pdfBuffer;
+
+  const pdfDoc = await PDFDocument.load(pdfBuffer);
+  const pages  = pdfDoc.getPages();
+  const ctx    = pdfDoc.context;
+  const n      = entries.length;
+
+  // ── Compute tree relationships ───────────────────────────────────────────
+  // parentIdx[i] = index of the nearest ancestor entry with a lower heading
+  // level, or -1 when the entry sits at the root of the outline.
+  const parentIdx  = new Array(n).fill(-1);
+  for (let i = 1; i < n; i++) {
+    for (let j = i - 1; j >= 0; j--) {
+      if (entries[j].level < entries[i].level) { parentIdx[i] = j; break; }
+    }
+  }
+
+  // Sibling linkage (prev / next among entries that share the same parent).
+  const prevSib    = new Array(n).fill(-1);
+  const nextSib    = new Array(n).fill(-1);
+  for (let i = 0; i < n; i++) {
+    for (let j = i - 1; j >= 0; j--) {
+      if (parentIdx[j] === parentIdx[i]) { prevSib[i] = j; break; }
+    }
+    for (let j = i + 1; j < n; j++) {
+      if (parentIdx[j] === parentIdx[i]) { nextSib[i] = j; break; }
+    }
+  }
+
+  // First / last direct child of each entry, and direct child count.
+  // directChildCount is computed here in O(n) so the item-building loop
+  // below doesn't need an inner scan (which would be O(n²) overall).
+  const firstChild       = new Array(n).fill(-1);
+  const lastChild        = new Array(n).fill(-1);
+  const directChildCount = new Array(n).fill(0);
+  for (let i = 0; i < n; i++) {
+    const p = parentIdx[i];
+    if (p >= 0) {
+      if (firstChild[p] < 0) firstChild[p] = i;
+      lastChild[p] = i;
+      directChildCount[p]++;
+    }
+  }
+
+  // ── Allocate PDF indirect references ─────────────────────────────────────
+  const outlineRef = ctx.nextRef();
+  const itemRefs   = entries.map(() => ctx.nextRef());
+
+  // ── Build each outline item object ───────────────────────────────────────
+  for (let i = 0; i < n; i++) {
+    const pageIdx = Math.min(entries[i].page - 1, pages.length - 1);
+
+    // XYZ destination: navigate to this page, null left/top inherits scroll, 0 zoom inherits zoom.
+    const dest = PDFArray.withContext(ctx);
+    dest.push(pages[pageIdx].ref);
+    dest.push(PDFName.of("XYZ"));
+    dest.push(PDFNull);
+    dest.push(PDFNull);
+    dest.push(PDFNumber.of(0));
+
+    const itemDict = PDFDict.withContext(ctx);
+    itemDict.set(PDFName.of("Title"),  PDFHexString.fromText(entries[i].title)); // UTF-16 → full Unicode
+    itemDict.set(PDFName.of("Parent"), parentIdx[i] >= 0 ? itemRefs[parentIdx[i]] : outlineRef);
+    itemDict.set(PDFName.of("Dest"),   dest);
+    if (prevSib[i]    >= 0) itemDict.set(PDFName.of("Prev"),  itemRefs[prevSib[i]]);
+    if (nextSib[i]    >= 0) itemDict.set(PDFName.of("Next"),  itemRefs[nextSib[i]]);
+    if (firstChild[i] >= 0) {
+      itemDict.set(PDFName.of("First"), itemRefs[firstChild[i]]);
+      itemDict.set(PDFName.of("Last"),  itemRefs[lastChild[i]]);
+      // Negative /Count = subtree is collapsed by default in the PDF reader.
+      itemDict.set(PDFName.of("Count"), PDFNumber.of(-directChildCount[i]));
+    }
+    ctx.assign(itemRefs[i], itemDict);
+  }
+
+  // ── Build the outline root dictionary ────────────────────────────────────
+  let rootFirst = -1, rootLast = -1, rootCount = 0;
+  for (let i = 0; i < n; i++) {
+    if (parentIdx[i] < 0) {
+      if (rootFirst < 0) rootFirst = i;
+      rootLast = i;
+      rootCount++;
+    }
+  }
+  // Safety: if every entry has a parent (e.g. the document starts with H2 and
+  // never has an H1), there are no root-level items. Injecting an empty or
+  // half-wired outline dict would produce a malformed PDF — bail out instead.
+  if (rootFirst < 0) return pdfBuffer;
+
+  const rootDict = PDFDict.withContext(ctx);
+  rootDict.set(PDFName.of("Type"),  PDFName.of("Outlines"));
+  rootDict.set(PDFName.of("First"), itemRefs[rootFirst]);
+  rootDict.set(PDFName.of("Last"),  itemRefs[rootLast]);
+  rootDict.set(PDFName.of("Count"), PDFNumber.of(rootCount));
+  ctx.assign(outlineRef, rootDict);
+
+  // ── Wire into the document catalog ───────────────────────────────────────
+  pdfDoc.catalog.set(PDFName.of("Outlines"), outlineRef);
+  pdfDoc.catalog.set(PDFName.of("PageMode"), PDFName.of("UseOutlines"));
+
+  return await pdfDoc.save();
+}
diff --git a/src/settings-tab.ts b/src/settings-tab.ts
new file mode 100644
index 0000000..bdf9e0e
--- /dev/null
+++ b/src/settings-tab.ts
@@ -0,0 +1,453 @@
+// ─────────────────────────────────────────────────────────────────────────────
+// Plugin settings tab (Settings → Advanced PDF Export).
+//
+// One long, linear form grouped into the same sections shown in the README
+// (Style Preset, Page, Margin & Frame, Typography, Background, Colors,
+// Header, Footer, Behaviour). Kept separate from export-modal.ts: this is a
+// different UI surface (global defaults vs. a single export session) that
+// doesn't share rendering logic with the modal, only the settings object.
+// ─────────────────────────────────────────────────────────────────────────────
+
+import { App, PluginSettingTab, Setting } from "obsidian";
+import type MarkdownPDFPlugin from "./main";
+import { PAGE_SIZES, PRESETS, PDFExportSettings } from "./settings";
+import { CODE_THEMES } from "./css-builder";
+
+export class PDFExportSettingTab extends PluginSettingTab {
+  plugin: MarkdownPDFPlugin;
+
+  /** True when any setting changed while this tab is open; triggers a single render on hide(). */
+  private dirty = false;
+
+  constructor(app: App, plugin: MarkdownPDFPlugin) {
+    super(app, plugin);
+    this.plugin = plugin;
+  }
+
+  display(): void {
+    // Start fresh: if nothing changes before hide(), no render will happen.
+    this.dirty = false;
+    this.buildSettings();
+  }
+
+  /** Called by Obsidian when the user leaves this tab. Fires one render if settings changed. */
+  hide(): void {
+    if (this.dirty) {
+      this.dirty = false;
+      this.plugin.activeModal?.render(true);
+    }
+  }
+
+  private async markDirty(): Promise {
+    this.dirty = true;
+    await this.plugin.saveSettings();
+  }
+
+  /** Builds (or rebuilds) the settings UI. Separated from display() so preset/reset
+   *  handlers can refresh the form without resetting the dirty flag. */
+  private buildSettings(): void {
+    const { containerEl } = this;
+    containerEl.empty();
+    const s = this.plugin.settings;
+
+    // Shared helpers ────────────────────────────────────────────────────────────
+    type NumericFieldKey = "marginTop" | "marginBottom" | "marginLeft" | "marginRight"
+      | "headerFontSize" | "footerFontSize" | "frameThickness" | "frameMargin"
+      | "headerHeight" | "footerHeight" | "headerImageMargin" | "footerImageMargin";
+    const numberSetting = (name: string, key: NumericFieldKey, min?: number, desc?: string) => {
+      const st = new Setting(containerEl).setName(name);
+      if (desc) st.setDesc(desc);
+      return st.addText((t) =>
+        t.setValue(String(s[key])).onChange((v) => {
+          const n = parseInt(v, 10) || 0;
+          s[key] = min !== undefined ? Math.max(min, n) : n;
+          void this.markDirty();
+        }),
+      );
+    };
+
+    type ColorKey = "accentColor" | "bodyColor" | "headingColor" | "pageBackground"
+      | "blockquoteBg" | "blockquoteBorderColor" | "tableHeaderBg" | "codeBackground"
+      | "headerFontColor" | "footerFontColor" | "frameColor";
+    const colorSetting = (name: string, key: ColorKey) =>
+      new Setting(containerEl).setName(name).addColorPicker((cp) =>
+        cp.setValue(s[key]).onChange((v) => { s[key] = v; void this.markDirty(); }),
+      );
+
+    // ── 1. Style Preset ───────────────────────────────────────────────────────
+    new Setting(containerEl).setName("Style Preset").setHeading();
+    new Setting(containerEl)
+      .setName("Preset")
+      .setDesc("Pick a preset to configure the overall document style. Fine-tune any setting below.")
+      .addDropdown((d) => {
+        Object.entries(PRESETS).forEach(([k, v]) => { d.addOption(k, v.name); });
+        d.setValue(s.preset).onChange((v) => {
+          this.plugin.applyPreset(v);
+          void this.markDirty().then(() => { this.buildSettings(); });
+        });
+      })
+      .addButton((b) =>
+        b.setButtonText("Reset Preset")
+         .setTooltip("Reset current preset to its default values")
+         .onClick(() => {
+           this.plugin.applyPreset(s.preset, true);
+           void this.markDirty().then(() => { this.buildSettings(); });
+         }),
+      );
+
+    // ── 2. Page ───────────────────────────────────────────────────────────────
+    new Setting(containerEl).setName("Page").setHeading();
+    let customPageSizeSetting: Setting;
+    new Setting(containerEl).setName("Page size").addDropdown((d) => {
+      Object.keys(PAGE_SIZES).forEach((k) => { d.addOption(k, k); });
+      d.addOption("Custom", "Custom…");
+      d.setValue(s.pageSize).onChange((v) => {
+        s.pageSize = v;
+        customPageSizeSetting.settingEl.toggleClass("mpdf-is-hidden", v !== "Custom");
+        void this.markDirty();
+      });
+    });
+    customPageSizeSetting = new Setting(containerEl)
+      .setName("Custom page size (mm)")
+      .setDesc("Width × Height in millimetres.")
+      .addText((t) =>
+        t.setPlaceholder("Width").setValue(String(s.customPageWidth))
+         .onChange((v) => { s.customPageWidth  = Math.max(10, parseFloat(v) || 210); void this.markDirty(); }),
+      )
+      .addText((t) =>
+        t.setPlaceholder("Height").setValue(String(s.customPageHeight))
+         .onChange((v) => { s.customPageHeight = Math.max(10, parseFloat(v) || 297); void this.markDirty(); }),
+      );
+    customPageSizeSetting.settingEl.toggleClass("mpdf-is-hidden", s.pageSize !== "Custom");
+    new Setting(containerEl).setName("Orientation").addDropdown((d) =>
+      d.addOptions({ portrait: "Portrait", landscape: "Landscape" })
+       .setValue(s.orientation)
+       .onChange((v) => { s.orientation = v as "portrait" | "landscape"; void this.markDirty(); }),
+    );
+
+    // ── 3. Margin & Frame ─────────────────────────────────────────────────────
+    new Setting(containerEl).setName("Margin & Frame").setHeading();
+    new Setting(containerEl)
+      .setName("Margins")
+      .setDesc("Top · Bottom · Left · Right")
+      .addText((t) =>
+        t.setPlaceholder("Top").setValue(String(s.marginTop))
+         .onChange((v) => { s.marginTop    = parseInt(v, 10) || 0; void this.markDirty(); }),
+      )
+      .addText((t) =>
+        t.setPlaceholder("Bottom").setValue(String(s.marginBottom))
+         .onChange((v) => { s.marginBottom = parseInt(v, 10) || 0; void this.markDirty(); }),
+      )
+      .addText((t) =>
+        t.setPlaceholder("Left").setValue(String(s.marginLeft))
+         .onChange((v) => { s.marginLeft   = parseInt(v, 10) || 0; void this.markDirty(); }),
+      )
+      .addText((t) =>
+        t.setPlaceholder("Right").setValue(String(s.marginRight))
+         .onChange((v) => { s.marginRight  = parseInt(v, 10) || 0; void this.markDirty(); }),
+      );
+
+    let frameColorSetting: Setting;
+    let frameThicknessSetting: Setting;
+    let frameMarginSetting: Setting;
+    let frameStyleSetting: Setting;
+    const toggleFrameSettings = (visible: boolean) => {
+      [frameColorSetting, frameThicknessSetting, frameMarginSetting, frameStyleSetting]
+        .forEach((st) => st.settingEl.toggleClass("mpdf-is-hidden", !visible));
+    };
+    new Setting(containerEl)
+      .setName("Enable frame")
+      .setDesc("Draws a border around the outer edge of every page.")
+      .addToggle((t) =>
+        t.setValue(s.frameEnabled).onChange((v) => {
+          s.frameEnabled = v;
+          toggleFrameSettings(v);
+          void this.markDirty();
+        }),
+      );
+    frameColorSetting     = colorSetting("Frame color", "frameColor");
+    frameThicknessSetting = numberSetting("Frame thickness (px)", "frameThickness", 1);
+    frameMarginSetting    = numberSetting(
+      "Frame margin (px)", "frameMargin", 0,
+      "Gap between the page edge and the frame, applied equally on all four sides.",
+    );
+    frameStyleSetting = new Setting(containerEl).setName("Frame style").addDropdown((d) =>
+      d.addOptions({ solid: "Solid", dashed: "Dashed", dotted: "Dotted", double: "Double", groove: "Groove", ridge: "Ridge" })
+       .setValue(s.frameStyle)
+       .onChange((v) => { s.frameStyle = v as PDFExportSettings["frameStyle"]; void this.markDirty(); }),
+    );
+    toggleFrameSettings(s.frameEnabled);
+
+    // ── 4. Typography ─────────────────────────────────────────────────────────
+    new Setting(containerEl).setName("Typography").setHeading();
+    let customFontSetting: Setting;
+    new Setting(containerEl).setName("Font family").addDropdown((d) =>
+      d.addOptions({
+        "Georgia, serif":                          "Georgia (Serif)",
+        "'Times New Roman', Times, serif":         "Times New Roman",
+        "'Palatino Linotype', Palatino, serif":    "Palatino",
+        "Arial, sans-serif":                       "Arial",
+        "'Helvetica Neue', Helvetica, sans-serif": "Helvetica",
+        "'Trebuchet MS', sans-serif":              "Trebuchet",
+        "'Courier New', monospace":                "Courier New",
+        "__custom__":                              "Custom…",
+      }).setValue(s.fontFamily)
+       .onChange((v) => {
+         s.fontFamily = v;
+         customFontSetting.settingEl.toggleClass("mpdf-is-hidden", v !== "__custom__");
+         void this.markDirty();
+       }),
+    );
+    customFontSetting = new Setting(containerEl)
+      .setName("Custom font name")
+      .setDesc("CSS font-family value — e.g. \"Inter, sans-serif\". The font must be installed on your system.")
+      .addText((t) =>
+        t.setPlaceholder("e.g. Inter, sans-serif")
+         .setValue(s.customFontName)
+         .onChange((v) => { s.customFontName = v; void this.markDirty(); }),
+      );
+    customFontSetting.settingEl.toggleClass("mpdf-is-hidden", s.fontFamily !== "__custom__");
+    new Setting(containerEl).setName("Font size (px)").addDropdown((d) => {
+      ["10","11","12","13","14","15","16"].forEach((v) => { d.addOption(v, v + "px"); });
+      d.setValue(String(s.fontSize)).onChange((v) => { s.fontSize = parseInt(v); void this.markDirty(); });
+    });
+    new Setting(containerEl).setName("Code font size").addDropdown((d) =>
+      d.addOptions({ "0.75": "0.75em", "0.80": "0.80em", "0.82": "0.82em", "0.85": "0.85em", "0.88": "0.88em", "0.90": "0.90em", "1.0": "1.00em" })
+       .setValue(String(s.codeFontSize))
+       .onChange((v) => { s.codeFontSize = parseFloat(v); void this.markDirty(); }),
+    );
+    new Setting(containerEl).setName("Line height").addDropdown((d) =>
+      d.addOptions({ "1.4": "Tight (1.4)", "1.6": "Compact (1.6)", "1.75": "Normal (1.75)", "1.85": "Relaxed (1.85)", "2.0": "Double (2.0)" })
+       .setValue(String(s.lineHeight))
+       .onChange((v) => { s.lineHeight = parseFloat(v); void this.markDirty(); }),
+    );
+    new Setting(containerEl).setName("Paragraph spacing").addDropdown((d) =>
+      d.addOptions({ "0": "None", "0.3": "Tight (0.3em)", "0.5": "Normal (0.5em)", "0.65": "Relaxed (0.65em)", "1.0": "Wide (1em)" })
+       .setValue(String(s.paragraphSpacing))
+       .onChange((v) => { s.paragraphSpacing = parseFloat(v); void this.markDirty(); }),
+    );
+    new Setting(containerEl)
+      .setName("Heading scale")
+      .setDesc("Multiplier applied to all heading sizes.")
+      .addDropdown((d) =>
+        d.addOptions({ "0.8": "Small (0.8×)", "0.88": "0.88×", "0.9": "Compact (0.9×)", "0.95": "0.95×", "1.0": "Normal (1.0×)", "1.05": "1.05×", "1.1": "Large (1.1×)", "1.2": "XLarge (1.2×)" })
+         .setValue(String(s.headingScale))
+         .onChange((v) => { s.headingScale = parseFloat(v); void this.markDirty(); }),
+      );
+
+    // ── 5. Background ─────────────────────────────────────────────────────────
+    new Setting(containerEl).setName("Background").setHeading();
+    let bgColorSetting: Setting;
+    let bgImgPathSetting: Setting;
+    let bgImgSizeSetting: Setting;
+    let bgImgScopeSetting: Setting;
+    let bgImgOpacitySetting: Setting;
+    const showBgMode = (useImage: boolean) => {
+      bgColorSetting.settingEl.toggleClass("mpdf-is-hidden", useImage);
+      [bgImgPathSetting, bgImgSizeSetting, bgImgScopeSetting, bgImgOpacitySetting]
+        .forEach((st) => st.settingEl.toggleClass("mpdf-is-hidden", !useImage));
+    };
+    new Setting(containerEl)
+      .setName("Use image background")
+      .setDesc("When on, a background image is used instead of the solid background color.")
+      .addToggle((t) =>
+        t.setValue(s.backgroundImageEnabled).onChange((v) => {
+          s.backgroundImageEnabled = v;
+          showBgMode(v);
+          void this.markDirty();
+        }),
+      );
+    bgColorSetting = new Setting(containerEl)
+      .setName("Page background color")
+      .addColorPicker((cp) =>
+        cp.setValue(s.pageBackground).onChange((v) => { s.pageBackground = v; void this.markDirty(); }),
+      );
+    bgImgPathSetting = new Setting(containerEl)
+      .setName("Background image")
+      .setDesc("Vault-relative path or https:// URL.")
+      .addText((t) =>
+        t.setPlaceholder("assets/background.png").setValue(s.backgroundImagePath)
+         .onChange((v) => { s.backgroundImagePath = v; void this.markDirty(); }),
+      );
+    bgImgSizeSetting = new Setting(containerEl).setName("Fit").addDropdown((d) =>
+      d.addOptions({
+        cover:   "Cover (fill, crop edges)",
+        contain: "Contain (fit, show gaps)",
+        fill:    "Fill (stretch to exact size)",
+        tile:    "Tile (repeat)",
+      })
+       .setValue(s.backgroundImageSize)
+       .onChange((v) => { s.backgroundImageSize = v as PDFExportSettings["backgroundImageSize"]; void this.markDirty(); }),
+    );
+    bgImgScopeSetting = new Setting(containerEl)
+      .setName("Scope")
+      .setDesc("Full page includes header and footer bands. Content area only restricts the background to the text zone between them.")
+      .addDropdown((d) =>
+        d.addOptions({ "full-page": "Full page", "content-only": "Content area only" })
+         .setValue(s.backgroundImageScope)
+         .onChange((v) => { s.backgroundImageScope = v as PDFExportSettings["backgroundImageScope"]; void this.markDirty(); }),
+      );
+    bgImgOpacitySetting = new Setting(containerEl).setName("Opacity").addDropdown((d) =>
+      d.addOptions({ "0.05": "5%", "0.1": "10%", "0.15": "15%", "0.2": "20%", "0.3": "30%", "0.4": "40%", "0.5": "50%", "0.6": "60%", "0.7": "70%", "0.8": "80%", "0.9": "90%", "1": "100%" })
+       .setValue(String(s.backgroundImageOpacity))
+       .onChange((v) => { s.backgroundImageOpacity = parseFloat(v); void this.markDirty(); }),
+    );
+    showBgMode(s.backgroundImageEnabled);
+
+    // ── 6. Colors ─────────────────────────────────────────────────────────────
+    new Setting(containerEl).setName("Colors").setHeading();
+    colorSetting("Accent color",            "accentColor");
+    colorSetting("Body text color",         "bodyColor");
+    colorSetting("Heading color",           "headingColor");
+    colorSetting("Blockquote background",   "blockquoteBg");
+    colorSetting("Blockquote border",       "blockquoteBorderColor");
+    colorSetting("Table header background", "tableHeaderBg");
+    colorSetting("Code background",         "codeBackground");
+    new Setting(containerEl)
+      .setName("Code syntax theme")
+      .setDesc("Independent of your Obsidian theme. \"None\" uses the body text color and code background above with no highlighting.")
+      .addDropdown((d) => {
+        const opts: Record = {};
+        for (const [key, theme] of Object.entries(CODE_THEMES)) opts[key] = theme.name;
+        d.addOptions(opts).setValue(s.codeTheme).onChange((v) => { s.codeTheme = v; void this.markDirty(); });
+      });
+
+    // ── 7. Header ─────────────────────────────────────────────────────────────
+    new Setting(containerEl).setName("Header").setHeading();
+    new Setting(containerEl).setName("Show header").addToggle((t) =>
+      t.setValue(s.showHeader).onChange((v) => { s.showHeader = v; void this.markDirty(); }),
+    );
+    new Setting(containerEl)
+      .setName("Show on first page")
+      .setDesc("When off, the header is hidden on page 1. Useful for title pages.")
+      .addToggle((t) =>
+        t.setValue(s.showHeaderOnFirstPage).onChange((v) => { s.showHeaderOnFirstPage = v; void this.markDirty(); }),
+      );
+    new Setting(containerEl)
+      .setName("Header text")
+      .addText((t) => t.setValue(s.headerText).onChange((v) => { s.headerText = v; void this.markDirty(); }));
+    new Setting(containerEl).setName("Alignment").addDropdown((d) =>
+      d.addOptions({ left: "Left", center: "Center", right: "Right" })
+       .setValue(s.headerAlignment)
+       .onChange((v) => { s.headerAlignment = v as "left"|"center"|"right"; void this.markDirty(); }),
+    );
+    numberSetting("Font size (px)", "headerFontSize", 1);
+    numberSetting("Height (px)", "headerHeight", 0, "Explicit band height (0 = auto).");
+    colorSetting("Font color", "headerFontColor");
+    new Setting(containerEl).setName("Border").setDesc("Separator line below the header.").addToggle((t) =>
+      t.setValue(s.showHeaderBorder).onChange((v) => { s.showHeaderBorder = v; void this.markDirty(); }),
+    );
+    new Setting(containerEl)
+      .setName("Image")
+      .setDesc("Vault-relative path or https:// URL. Fills the header band as a background banner.")
+      .addText((t) =>
+        t.setPlaceholder("assets/header-banner.png").setValue(s.headerImagePath)
+         .onChange((v) => { s.headerImagePath = v; void this.markDirty(); }),
+      );
+    numberSetting("Image left/right margin (px)", "headerImageMargin", 0, "Insets the banner from the left and right page edges.");
+
+    // ── 8. Footer ─────────────────────────────────────────────────────────────
+    new Setting(containerEl).setName("Footer").setHeading();
+    new Setting(containerEl).setName("Show footer").addToggle((t) =>
+      t.setValue(s.showFooter).onChange((v) => { s.showFooter = v; void this.markDirty(); }),
+    );
+    new Setting(containerEl)
+      .setName("Show on first page")
+      .setDesc("When off, the footer and page numbers are hidden on page 1. Page numbering starts from page 2.")
+      .addToggle((t) =>
+        t.setValue(s.showFooterOnFirstPage).onChange((v) => { s.showFooterOnFirstPage = v; void this.markDirty(); }),
+      );
+    new Setting(containerEl)
+      .setName("Footer text")
+      .addText((t) => t.setValue(s.footerText).onChange((v) => { s.footerText = v; void this.markDirty(); }));
+    new Setting(containerEl).setName("Alignment").addDropdown((d) =>
+      d.addOptions({ left: "Left", center: "Center", right: "Right" })
+       .setValue(s.footerTextAlignment)
+       .onChange((v) => { s.footerTextAlignment = v as "left" | "center" | "right"; void this.markDirty(); }),
+    );
+    numberSetting("Font size (px)", "footerFontSize", 1);
+    numberSetting("Height (px)", "footerHeight", 0, "Explicit band height (0 = auto).");
+    colorSetting("Font color", "footerFontColor");
+    new Setting(containerEl).setName("Border").setDesc("Separator line above the footer.").addToggle((t) =>
+      t.setValue(s.showFooterBorder).onChange((v) => { s.showFooterBorder = v; void this.markDirty(); }),
+    );
+    new Setting(containerEl)
+      .setName("Image")
+      .setDesc("Vault-relative path or https:// URL. Fills the footer band as a background banner.")
+      .addText((t) =>
+        t.setPlaceholder("assets/footer-banner.png").setValue(s.footerImagePath)
+         .onChange((v) => { s.footerImagePath = v; void this.markDirty(); }),
+      );
+    numberSetting("Image left/right margin (px)", "footerImageMargin", 0, "Insets the banner from the left and right page edges.");
+    new Setting(containerEl).setName("Show page numbers").addToggle((t) =>
+      t.setValue(s.showPageNumbers).onChange((v) => { s.showPageNumbers = v; void this.markDirty(); }),
+    );
+    new Setting(containerEl).setName("Page number position").addDropdown((d) =>
+      d.addOptions({ left: "Left", center: "Center", right: "Right" })
+       .setValue(s.pageNumberPosition)
+       .onChange((v) => { s.pageNumberPosition = v as "left"|"center"|"right"; void this.markDirty(); }),
+    );
+    new Setting(containerEl)
+      .setName("Page number format")
+      .setDesc("Use {{current}} and {{total}} as placeholders, e.g. \"Page {{current}} of {{total}}\", \"{{current}}/{{total}}\", or just \"{{current}}\".")
+      .addText((t) =>
+        t.setPlaceholder("{{current}} / {{total}}").setValue(s.pageNumberFormat)
+         .onChange((v) => { s.pageNumberFormat = v; void this.markDirty(); }),
+      );
+    new Setting(containerEl)
+      .setName("Page number start")
+      .setDesc("Number assigned to the first visible page number.")
+      .addText((t) =>
+        t.setValue(String(s.pageNumberStart))
+         .onChange((v) => { s.pageNumberStart = parseInt(v, 10) || 1; void this.markDirty(); }),
+      );
+
+    // ── 9. Behaviour ──────────────────────────────────────────────────────────
+    new Setting(containerEl).setName("Behaviour").setHeading();
+    new Setting(containerEl)
+      .setName("Hide frontmatter")
+      .setDesc("Strip the YAML frontmatter block (--- … ---) from the preview and exported PDF.")
+      .addToggle((t) =>
+        t.setValue(s.hideFrontmatter).onChange((v) => { s.hideFrontmatter = v; void this.markDirty(); }),
+      );
+    new Setting(containerEl)
+      .setName("Include file name as title")
+      .setDesc("Prepend the note's file name as an H1 heading at the top of the PDF.")
+      .addToggle((t) =>
+        t.setValue(s.includeFilenameAsTitle).onChange((v) => { s.includeFilenameAsTitle = v; void this.markDirty(); }),
+      );
+    new Setting(containerEl)
+      .setName("Underline links")
+      .setDesc("Applies to both internal and external links.")
+      .addToggle((t) =>
+        t.setValue(s.linkUnderline).onChange((v) => { s.linkUnderline = v; void this.markDirty(); }),
+      );
+    new Setting(containerEl).setName("Auto page break before H1").addToggle((t) =>
+      t.setValue(s.autoBreakH1).onChange((v) => { s.autoBreakH1 = v; void this.markDirty(); }),
+    );
+    new Setting(containerEl).setName("Auto page break before H2").addToggle((t) =>
+      t.setValue(s.autoBreakH2).onChange((v) => { s.autoBreakH2 = v; void this.markDirty(); }),
+    );
+    new Setting(containerEl).setName("H1 bottom border").addToggle((t) =>
+      t.setValue(s.h1BorderBottom).onChange((v) => { s.h1BorderBottom = v; void this.markDirty(); }),
+    );
+    new Setting(containerEl).setName("H2 bottom border").addToggle((t) =>
+      t.setValue(s.h2BorderBottom).onChange((v) => { s.h2BorderBottom = v; void this.markDirty(); }),
+    );
+    new Setting(containerEl).setName("Center H1").addToggle((t) =>
+      t.setValue(s.centerH1).onChange((v) => { s.centerH1 = v; void this.markDirty(); }),
+    );
+    new Setting(containerEl).setName("Striped table rows").addToggle((t) =>
+      t.setValue(s.tableStriped).onChange((v) => { s.tableStriped = v; void this.markDirty(); }),
+    );
+    new Setting(containerEl)
+      .setName("Include PDF outline (bookmarks)")
+      .setDesc(
+        "Embeds a bookmark tree into the exported PDF. " +
+        "Most PDF readers display it in a side panel for quick navigation.",
+      )
+      .addToggle((t) =>
+        t.setValue(s.includeOutline).onChange((v) => { s.includeOutline = v; void this.markDirty(); }),
+      );
+  }
+}
diff --git a/src/settings.ts b/src/settings.ts
new file mode 100644
index 0000000..6bbe5b1
--- /dev/null
+++ b/src/settings.ts
@@ -0,0 +1,354 @@
+// ─────────────────────────────────────────────────────────────────────────────
+// Settings schema, style presets, and defaults.
+//
+// This is the plugin's data model: the shape of a saved settings object, the
+// seven built-in style presets, and the values a fresh install starts with.
+// Pure data + types — no Obsidian imports, no rendering logic. Anything that
+// *turns* these settings into CSS lives in css-builder.ts; anything that
+// *edits* them lives in settings-tab.ts.
+// ─────────────────────────────────────────────────────────────────────────────
+
+export const PAGE_SIZES: Record = {
+  A4:     { w: 794,  h: 1123 },
+  A3:     { w: 1123, h: 1587 },
+  Letter: { w: 816,  h: 1056 },
+  Legal:  { w: 816,  h: 1344 },
+  A5:     { w: 559,  h: 794  },
+};
+
+export interface DocStyle {
+  name: string;
+  fontFamily: string;
+  fontSize: number;
+  lineHeight: number;
+  paragraphSpacing: number;
+  headingScale: number;
+  accentColor: string;
+  bodyColor: string;
+  headingColor: string;
+  h1BorderBottom: boolean;
+  h2BorderBottom: boolean;
+  centerH1: boolean;
+  blockquoteBg: string;
+  blockquoteBorderColor: string;
+  codeBackground: string;
+  codeFontSize: number;
+  codeTheme: string;
+  tableHeaderBg: string;
+  tableStriped: boolean;
+  pageBackground: string;
+  marginTop: number;
+  marginBottom: number;
+  marginLeft: number;
+  marginRight: number;
+}
+
+export interface PDFExportSettings extends DocStyle {
+  pageSize: string;
+  orientation: "portrait" | "landscape";
+  preset: string;
+  headerText: string;
+  footerText: string;
+  showHeader: boolean;
+  showFooter: boolean;
+  showHeaderBorder: boolean;
+  showFooterBorder: boolean;
+  showPageNumbers: boolean;
+  pageNumberPosition: "center" | "left" | "right";
+  pageNumberStart: number;
+  /** Template for rendering the page number string. Supports {{current}}
+   *  and {{total}} placeholders, e.g. "Page {{current}} of {{total}}". */
+  pageNumberFormat: string;
+  showHeaderOnFirstPage: boolean;
+  showFooterOnFirstPage: boolean;
+  headerAlignment: "left" | "center" | "right";
+  footerTextAlignment: "left" | "center" | "right";
+  headerFontSize: number;
+  headerFontColor: string;
+  footerFontSize: number;
+  footerFontColor: string;
+  linkUnderline: boolean;
+  frameEnabled: boolean;
+  frameColor: string;
+  frameThickness: number;
+  frameMargin: number;
+  frameStyle: "solid" | "dashed" | "dotted" | "double" | "groove" | "ridge";
+  hideFrontmatter: boolean;
+  customFontName: string;
+  autoBreakH1: boolean;
+  autoBreakH2: boolean;
+  includeFilenameAsTitle: boolean;
+  previewScale: number;
+  /** Width in mm, used only when pageSize === "Custom". */
+  customPageWidth: number;
+  /** Height in mm, used only when pageSize === "Custom". */
+  customPageHeight: number;
+
+  // ── Header/footer band sizing ─────────────────────────────────────────────
+  /** Explicit header band height in px. 0 = auto (derived from headerFontSize). */
+  headerHeight: number;
+  /** Explicit footer band height in px. 0 = auto (derived from footerFontSize). */
+  footerHeight: number;
+
+  // ── Header/footer banner images ───────────────────────────────────────────
+  /** Vault-relative path or https:// URL for a banner image behind the header text. */
+  headerImagePath: string;
+  /** Left/right gap in px between the banner image and the page edges (0 = edge-to-edge). */
+  headerImageMargin: number;
+  footerImagePath: string;
+  /** Left/right gap in px between the banner image and the page edges. */
+  footerImageMargin: number;
+
+  // ── Page background (color OR image — mutually exclusive) ────────────────
+  /** When true, backgroundImagePath is used instead of the pageBackground color. */
+  backgroundImageEnabled: boolean;
+  backgroundImagePath: string;
+  /** How the image fills the background zone. */
+  backgroundImageSize: "cover" | "contain" | "fill" | "tile";
+  /** "full-page": behind header+content+footer. "content-only": text zone only. */
+  backgroundImageScope: "full-page" | "content-only";
+  /** 0–1 opacity for the background image layer. */
+  backgroundImageOpacity: number;
+  /** When true, headings H1–H6 are embedded as a bookmark tree in the exported PDF. */
+  includeOutline: boolean;
+}
+
+// ─── Style Presets ────────────────────────────────────────────────────────────
+
+export const PRESETS: Record = {
+  default: {
+    name: "Default",
+    fontFamily: "Georgia, serif",
+    fontSize: 13,
+    lineHeight: 1.85,
+    paragraphSpacing: 0.65,
+    headingScale: 1.0,
+    accentColor: "#7c6af7",
+    bodyColor: "#1a1a2e",
+    headingColor: "#0d0d1a",
+    h1BorderBottom: false,
+    h2BorderBottom: true,
+    centerH1: false,
+    blockquoteBg: "transparent",
+    blockquoteBorderColor: "#7c6af7",
+    codeBackground: "#f0f0f8",
+    codeFontSize: 0.85,
+    codeTheme: "github-light",
+    tableHeaderBg: "#f0f0f8",
+    tableStriped: true,
+    pageBackground: "#ffffff",
+    marginTop: 20, marginBottom: 20, marginLeft: 25, marginRight: 25,
+  },
+  minimal: {
+    name: "Minimal",
+    fontFamily: "'Helvetica Neue', Helvetica, sans-serif",
+    fontSize: 12,
+    lineHeight: 1.6,
+    paragraphSpacing: 0.45,
+    headingScale: 0.88,
+    accentColor: "#333",
+    bodyColor: "#222",
+    headingColor: "#111",
+    h1BorderBottom: false,
+    h2BorderBottom: false,
+    centerH1: false,
+    blockquoteBg: "#f8f8f8",
+    blockquoteBorderColor: "#ccc",
+    codeBackground: "#f4f4f4",
+    codeFontSize: 0.82,
+    codeTheme: "none",
+    tableHeaderBg: "#efefef",
+    tableStriped: false,
+    pageBackground: "#ffffff",
+    marginTop: 16, marginBottom: 16, marginLeft: 20, marginRight: 20,
+  },
+  academic: {
+    name: "Academic",
+    fontFamily: "'Times New Roman', Times, serif",
+    fontSize: 12,
+    lineHeight: 2.0,
+    paragraphSpacing: 0.0,
+    headingScale: 0.95,
+    accentColor: "#1a3a6b",
+    bodyColor: "#000",
+    headingColor: "#000",
+    h1BorderBottom: true,
+    h2BorderBottom: true,
+    centerH1: true,
+    blockquoteBg: "transparent",
+    blockquoteBorderColor: "#999",
+    codeBackground: "#f9f9f9",
+    codeFontSize: 0.88,
+    codeTheme: "solarized-light",
+    tableHeaderBg: "#e8e8e8",
+    tableStriped: false,
+    pageBackground: "#ffffff",
+    marginTop: 25, marginBottom: 25, marginLeft: 30, marginRight: 30,
+  },
+  colorful: {
+    name: "Colorful",
+    fontFamily: "Georgia, serif",
+    fontSize: 13,
+    lineHeight: 1.85,
+    paragraphSpacing: 0.65,
+    headingScale: 1.05,
+    accentColor: "#e84393",
+    bodyColor: "#1a1a2e",
+    headingColor: "#2d0a4e",
+    h1BorderBottom: false,
+    h2BorderBottom: false,
+    centerH1: false,
+    blockquoteBg: "#fdf0f8",
+    blockquoteBorderColor: "#e84393",
+    codeBackground: "#f0eaff",
+    codeFontSize: 0.85,
+    codeTheme: "dracula",
+    tableHeaderBg: "#2d0a4e",
+    tableStriped: true,
+    pageBackground: "#ffffff",
+    marginTop: 20, marginBottom: 20, marginLeft: 25, marginRight: 25,
+  },
+  modern: {
+    name: "Modern",
+    fontFamily: "Arial, sans-serif",
+    fontSize: 13,
+    lineHeight: 1.75,
+    paragraphSpacing: 0.6,
+    headingScale: 1.0,
+    accentColor: "#0070f3",
+    bodyColor: "#111",
+    headingColor: "#000",
+    h1BorderBottom: false,
+    h2BorderBottom: false,
+    centerH1: false,
+    blockquoteBg: "#f0f7ff",
+    blockquoteBorderColor: "#0070f3",
+    codeBackground: "#f1f5f9",
+    codeFontSize: 0.85,
+    codeTheme: "github-dark",
+    tableHeaderBg: "#0070f3",
+    tableStriped: true,
+    pageBackground: "#ffffff",
+    marginTop: 20, marginBottom: 20, marginLeft: 25, marginRight: 25,
+  },
+  newspaper: {
+    name: "Newspaper",
+    fontFamily: "Georgia, serif",
+    fontSize: 12,
+    lineHeight: 1.7,
+    paragraphSpacing: 0.4,
+    headingScale: 1.1,
+    accentColor: "#111",
+    bodyColor: "#111",
+    headingColor: "#000",
+    h1BorderBottom: true,
+    h2BorderBottom: true,
+    centerH1: true,
+    blockquoteBg: "transparent",
+    blockquoteBorderColor: "#111",
+    codeBackground: "#f4f4f4",
+    codeFontSize: 0.82,
+    codeTheme: "none",
+    tableHeaderBg: "#111",
+    tableStriped: false,
+    pageBackground: "#ffffff",
+    marginTop: 18, marginBottom: 18, marginLeft: 20, marginRight: 20,
+  },
+  dark: {
+    name: "Dark",
+    fontFamily: "Georgia, serif",
+    fontSize: 13,
+    lineHeight: 1.85,
+    paragraphSpacing: 0.65,
+    headingScale: 1.0,
+    accentColor: "#818cf8",
+    bodyColor: "#d1d5db",
+    headingColor: "#f1f5f9",
+    h1BorderBottom: false,
+    h2BorderBottom: true,
+    centerH1: false,
+    blockquoteBg: "#1e293b",
+    blockquoteBorderColor: "#818cf8",
+    codeBackground: "#0f172a",
+    codeFontSize: 0.85,
+    codeTheme: "tokyo-night",
+    tableHeaderBg: "#1e293b",
+    tableStriped: true,
+    pageBackground: "#111827",
+    marginTop: 20, marginBottom: 20, marginLeft: 25, marginRight: 25,
+  },
+};
+
+export const DEFAULT_SETTINGS: PDFExportSettings = {
+  pageSize: "A4",
+  orientation: "portrait",
+  preset: "default",
+  ...PRESETS["default"],
+  headerText: "",
+  footerText: "",
+  showHeader: true,
+  showFooter: true,
+  showHeaderBorder: false,
+  showFooterBorder: false,
+  showPageNumbers: true,
+  pageNumberPosition: "right",
+  pageNumberStart: 1,
+  pageNumberFormat: "{{current}} / {{total}}",
+  showHeaderOnFirstPage: true,
+  showFooterOnFirstPage: true,
+  headerAlignment:     "right",
+  footerTextAlignment: "left",
+  headerFontSize: 9,
+  headerFontColor: "#999999",
+  footerFontSize: 9,
+  footerFontColor: "#aaaaaa",
+  linkUnderline: true,
+  frameEnabled: false,
+  frameColor: "#000000",
+  frameThickness: 4,
+  frameMargin: 8,
+  frameStyle: "solid",
+  hideFrontmatter: false,
+  customFontName: "",
+  autoBreakH1: false,
+  autoBreakH2: false,
+  includeFilenameAsTitle: false,
+  previewScale: 0.9,
+  customPageWidth: 210,   // A4 width in mm
+  customPageHeight: 297,  // A4 height in mm
+  // Band sizing (0 = auto from font size)
+  headerHeight: 0,
+  footerHeight: 0,
+  // Banner images (header / footer background)
+  headerImagePath: "",
+  headerImageMargin: 0,
+  footerImagePath: "",
+  footerImageMargin: 0,
+  // Page background
+  backgroundImageEnabled: false,
+  backgroundImagePath: "",
+  backgroundImageSize: "cover",
+  backgroundImageScope: "full-page",
+  backgroundImageOpacity: 1,
+  // Outline / bookmarks
+  includeOutline: true,
+};
+
+/** Extracts only the DocStyle fields from the broader settings object.
+ *  Used to snapshot the current look before switching presets, so each
+ *  preset can remember per-user tweaks independently. */
+export function extractDocStyle(s: PDFExportSettings): DocStyle {
+  return {
+    name: s.name, fontFamily: s.fontFamily, fontSize: s.fontSize,
+    lineHeight: s.lineHeight, paragraphSpacing: s.paragraphSpacing,
+    headingScale: s.headingScale, accentColor: s.accentColor,
+    bodyColor: s.bodyColor, headingColor: s.headingColor,
+    h1BorderBottom: s.h1BorderBottom, h2BorderBottom: s.h2BorderBottom,
+    centerH1: s.centerH1, blockquoteBg: s.blockquoteBg,
+    blockquoteBorderColor: s.blockquoteBorderColor, codeBackground: s.codeBackground,
+    codeFontSize: s.codeFontSize, codeTheme: s.codeTheme, tableHeaderBg: s.tableHeaderBg,
+    tableStriped: s.tableStriped, pageBackground: s.pageBackground,
+    marginTop: s.marginTop, marginBottom: s.marginBottom,
+    marginLeft: s.marginLeft, marginRight: s.marginRight,
+  };
+}
diff --git a/tsconfig.json b/tsconfig.json
index e6c0a37..4671d13 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -13,5 +13,5 @@
     "skipLibCheck": true,
     "lib": ["ES2022", "DOM", "DOM.Iterable"]
   },
-  "include": ["**/*.ts"]
+  "include": ["src/**/*.ts"]
 }

From 63824fea5d1bb88a67633517a5173d1c7cc35e59 Mon Sep 17 00:00:00 2001
From: Walid 
Date: Sun, 12 Jul 2026 19:38:19 +0600
Subject: [PATCH 3/3] Update .gitignore

---
 .gitignore | 8 ++++++++
 1 file changed, 8 insertions(+)

diff --git a/.gitignore b/.gitignore
index 7845401..2c7d486 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,4 +1,12 @@
+# Dependencies
 node_modules/
+
+# Obsidian vault
 .obsidian/
+
+# Logs
 *.log
+
+# OS files
 .DS_Store
+Thumbs.db