@zumer/snapdom 2.1.0 → 2.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -76,25 +76,22 @@ await result.download({ format: 'jpg', filename: 'card.jpg' });
76
76
 
77
77
  SnapDOM transforms your DOM element through these stages:
78
78
 
79
- ```mermaid
80
- flowchart LR
81
- subgraph Input
82
- A[DOM Element]
83
- end
84
-
85
- subgraph Capture
86
- B[Clone] --> C[Styles & Pseudo]
87
- C --> D[Images & Backgrounds]
88
- D --> E[Fonts]
89
- E --> F[SVG foreignObject]
90
- end
91
-
92
- subgraph Output
93
- F --> G[data:image/svg+xml]
94
- G --> H[toPng / toSvg / toBlob / download]
95
- end
96
-
97
- A --> B
79
+ ```
80
+ DOM Element
81
+ ↓
82
+ Clone
83
+ ↓
84
+ Styles & Pseudo
85
+ ↓
86
+ Images & Backgrounds
87
+ ↓
88
+ Fonts
89
+ ↓
90
+ SVG foreignObject
91
+ ↓
92
+ data:image/svg+xml
93
+ ↓
94
+ toPng / toSvg / toBlob / download
98
95
  ```
99
96
 
100
97
  | Stage | What happens |
@@ -126,6 +123,7 @@ Plugin hooks: `beforeSnap` → `beforeClone` → `afterClone` → `beforeRender`
126
123
  - [snapdom(el, options?)](#snapdomel-options)
127
124
  - [Shortcut methods](#shortcut-methods)
128
125
  - [Options](#options)
126
+ - [debug](#debug)
129
127
  - [Fallback image on `<img>` load failure](#fallback-image-on-img-load-failure)
130
128
  - [Dimensions (`scale`, `width`, `height`)](#dimensions-scale-width-height)
131
129
  - [Cross-Origin Images & Fonts (`useProxy`)](#cross-origin-images--fonts-useproxy)
@@ -334,6 +332,7 @@ All capture methods accept an `options` object:
334
332
 
335
333
  | Option | Type | Default | Description |
336
334
  | ----------------- | -------- | -------- | ----------------------------------------------- |
335
+ | `debug` | boolean | `false` | When `true`, logs suppressed errors to `console.warn` for troubleshooting |
337
336
  | `fast` | boolean | `true` | Skips small idle delays for faster results |
338
337
  | `embedFonts` | boolean | `false` | Inlines non-icon fonts (icon fonts always on) |
339
338
  | `localFonts` | array | `[]` | Local fonts `{ family, src, weight?, style? }` |
@@ -356,6 +355,16 @@ All capture methods accept an `options` object:
356
355
  | `outerTransforms` | boolean | `true` | When `false` removes `translate/rotate` but preserves `scale/skew`, producing a flat, reusable capture |
357
356
  | `outerShadows` | boolean | `false` | Do not expand the root’s bounding box for shadows/blur/outline, and strip those visual effects from the cloned root |
358
357
 
358
+ | `safariWarmupAttempts` | number | `3` | Safari only: iterations to prime font/decode (WebKit #219770). Use `1` if 3 causes lag |
359
+
360
+ ### debug
361
+
362
+ When `debug: true`, SnapDOM logs normally suppressed errors to `console.warn` (with the `[snapdom]` prefix). Useful for troubleshooting capture issues (canvas failures, blob resolution, style stripping, etc.) without noisy output in production.
363
+
364
+ ```js
365
+ await snapdom.toPng(el, { debug: true });
366
+ ```
367
+
359
368
  ### Fallback image on `<img>` load failure
360
369
 
361
370
  Provide a default image for failed `<img>` loads. You can pass a fixed URL or a callback that receives measured dimensions and returns a URL (handy to generate dynamic placeholders).
@@ -600,7 +609,7 @@ Hooks run in capture order (see [Capture Flow](#capture-flow)):
600
609
  Every hook receives a single `context` object that contains normalized capture state:
601
610
 
602
611
  * **Input & options:**
603
- `element`, `debug`, `fast`, `scale`, `dpr`, `width`, `height`, `backgroundColor`, `quality`, `useProxy`, `cache`, `outerTransforms`, `outerShadows`, `embedFonts`, `localFonts`, `iconFonts`, `excludeFonts`, `exclude`, `excludeMode`, `filter`, `filterMode`, `fallbackURL`.
612
+ `element`, `debug`, `fast`, `scale`, `dpr`, `width`, `height`, `backgroundColor`, `quality`, `useProxy`, `cache`, `outerTransforms`, `outerShadows`, `safariWarmupAttempts`, `embedFonts`, `localFonts`, `iconFonts`, `excludeFonts`, `exclude`, `excludeMode`, `filter`, `filterMode`, `fallbackURL`.
604
613
 
605
614
  * **Intermediate values (depending on stage):**
606
615
  `clone`, `classCSS`, `styleCache`, `fontsCSS`, `baseCSS`, `svgString`, `dataURL`.
@@ -770,6 +779,8 @@ export function myPlugin(options = {}) {
770
779
  * External images should be CORS-accessible (use `useProxy` option for handling CORS denied)
771
780
  * When WebP format is used on Safari, it will fallback to PNG rendering.
772
781
  * `@font-face` CSS rule is well supported, but if need to use JS `FontFace()`, see this workaround [`#43`](https://github.com/zumerlab/snapdom/issues/43)
782
+ * **Safari**: captures with `embedFonts` or background/mask images run slower due to [WebKit #219770](https://bugs.webkit.org/show_bug.cgi?id=219770) (font decode timing). SnapDOM does pre-captures + `drawImage` to prime the pipeline; configurable via `safariWarmupAttempts` (default 3).
783
+ * **Custom scrollbar styles** (`::-webkit-scrollbar`): Applied only when the element has *not* been scrolled. When scrolled, the viewport content is captured without the scrollbar.
773
784
 
774
785
 
775
786
  ## Performance Benchmarks
@@ -885,6 +896,7 @@ For detailed guidelines, see [CONTRIBUTING](https://github.com/zumerlab/snapdom/
885
896
  <a href="https://github.com/pedrocateexte" title="pedrocateexte"><img src="https://avatars.githubusercontent.com/u/207524750?v=4&s=100" style="border-radius:10px; width:60px; height:60px; object-fit:cover; margin:5px;" alt="pedrocateexte"/></a>
886
897
  <a href="https://github.com/domialex" title="domialex"><img src="https://avatars.githubusercontent.com/u/4694217?v=4&s=100" style="border-radius:10px; width:60px; height:60px; object-fit:cover; margin:5px;" alt="domialex"/></a>
887
898
  <a href="https://github.com/elliots" title="elliots"><img src="https://avatars.githubusercontent.com/u/622455?v=4&s=100" style="border-radius:10px; width:60px; height:60px; object-fit:cover; margin:5px;" alt="elliots"/></a>
899
+ <a href="https://github.com/stypr" title="stypr"><img src="https://avatars.githubusercontent.com/u/6625978?v=4&s=100" style="border-radius:10px; width:60px; height:60px; object-fit:cover; margin:5px;" alt="stypr"/></a>
888
900
  <a href="https://github.com/mon-jai" title="mon-jai"><img src="https://avatars.githubusercontent.com/u/91261297?v=4&s=100" style="border-radius:10px; width:60px; height:60px; object-fit:cover; margin:5px;" alt="mon-jai"/></a>
889
901
  <a href="https://github.com/sharuzzaman" title="sharuzzaman"><img src="https://avatars.githubusercontent.com/u/7421941?v=4&s=100" style="border-radius:10px; width:60px; height:60px; object-fit:cover; margin:5px;" alt="sharuzzaman"/></a>
890
902
  <a href="https://github.com/simon1uo" title="simon1uo"><img src="https://avatars.githubusercontent.com/u/60037549?v=4&s=100" style="border-radius:10px; width:60px; height:60px; object-fit:cover; margin:5px;" alt="simon1uo"/></a>
@@ -897,7 +909,6 @@ For detailed guidelines, see [CONTRIBUTING](https://github.com/zumerlab/snapdom/
897
909
  <a href="https://github.com/miusuncle" title="miusuncle"><img src="https://avatars.githubusercontent.com/u/7549857?v=4&s=100" style="border-radius:10px; width:60px; height:60px; object-fit:cover; margin:5px;" alt="miusuncle"/></a>
898
910
  <a href="https://github.com/rbbydotdev" title="rbbydotdev"><img src="https://avatars.githubusercontent.com/u/101137670?v=4&s=100" style="border-radius:10px; width:60px; height:60px; object-fit:cover; margin:5px;" alt="rbbydotdev"/></a>
899
911
  <a href="https://github.com/zhanghaotian2018" title="zhanghaotian2018"><img src="https://avatars.githubusercontent.com/u/169218899?v=4&s=100" style="border-radius:10px; width:60px; height:60px; object-fit:cover; margin:5px;" alt="zhanghaotian2018"/></a>
900
- <a href="https://github.com/fu050409" title="fu050409"><img src="https://avatars.githubusercontent.com/u/46275354?v=4&s=100" style="border-radius:10px; width:60px; height:60px; object-fit:cover; margin:5px;" alt="fu050409"/></a>
901
912
  </p>
902
913
  <!-- CONTRIBUTORS:END -->
903
914
 
package/dist/plugins.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  /*
2
2
  * SnapDOM
3
- * v2.1.0
3
+ * v2.6.0
4
4
  * Author: Juan Martin Muda
5
5
  * License: MIT
6
6
  */
package/dist/preCache.mjs CHANGED
@@ -1,10 +1,10 @@
1
1
  /*
2
2
  * SnapDOM
3
- * v2.1.0
3
+ * v2.6.0
4
4
  * Author: Juan Martin Muda
5
5
  * License: MIT
6
6
  */
7
- var f={image:new Map,background:new Map,resource:new Map,defaultStyle:new Map,baseStyle:new Map,computedStyle:new WeakMap,font:new Set,session:{styleMap:new Map,styleCache:new WeakMap,nodeMap:new Map}};function X(t="soft"){switch(f.session.__counterEpoch=(f.session.__counterEpoch||0)+1,t){case"auto":{f.session.styleMap=new Map,f.session.nodeMap=new Map;return}case"soft":{f.session.styleMap=new Map,f.session.nodeMap=new Map,f.session.styleCache=new WeakMap;return}case"full":return;case"disabled":{f.session.styleMap=new Map,f.session.nodeMap=new Map,f.session.styleCache=new WeakMap,f.computedStyle=new WeakMap,f.baseStyle=new Map,f.defaultStyle=new Map,f.image=new Map,f.background=new Map,f.resource=new Map,f.font=new Set;return}default:{f.session.styleMap=new Map,f.session.nodeMap=new Map,f.session.styleCache=new WeakMap;return}}}function N(t){let e=t.match(/url\((['"]?)(.*?)(\1)\)/);if(!e)return null;let n=e[2].trim();return n.startsWith("#")?null:n}function O(t){if(/%[0-9A-Fa-f]{2}/.test(t))return t;try{return encodeURI(t)}catch{return t}}function dt(t="[snapDOM]",{ttlMs:e=5*6e4,maxEntries:n=12}={}){let r=new Map,o=0;function i(s,u,c){if(o>=n)return;let m=Date.now();(r.get(u)||0)>m||(r.set(u,m+e),o++,s==="warn"&&console&&console.warn?console.warn(`${t} ${c}`):console&&console.error&&console.error(`${t} ${c}`))}return{warnOnce(s,u){i("warn",s,u)},errorOnce(s,u){i("error",s,u)},reset(){r.clear(),o=0}}}var Y=dt("[snapDOM]",{ttlMs:3*6e4,maxEntries:10}),j=new Map,W=new Map;function pt(t){return/^data:|^blob:|^about:blank$/i.test(t)}function ht(t,e){try{let n=typeof location<"u"&&location.href?location.href:"http://localhost/",r=e.includes("{url}")?e.split("{url}")[0]:e,o=new URL(r||".",n),i=new URL(t,n);if(i.origin===o.origin)return!0;let s=i.searchParams;if(s&&(s.has("url")||s.has("target")))return!0}catch{}return!1}function gt(t,e){if(!e||pt(t)||ht(t,e))return!1;try{let n=typeof location<"u"&&location.href?location.href:"http://localhost/",r=new URL(t,n);return typeof location<"u"?r.origin!==location.origin:!0}catch{return!!e}}function yt(t,e){if(!e)return t;if(e.includes("{url}"))return e.replace("{urlRaw}",O(t)).replace("{url}",encodeURIComponent(t));if(/[?&]url=?$/.test(e))return`${e}${encodeURIComponent(t)}`;if(e.endsWith("?"))return`${e}url=${encodeURIComponent(t)}`;if(e.endsWith("/"))return`${e}${O(t)}`;let n=e.includes("?")?"&":"?";return`${e}${n}url=${encodeURIComponent(t)}`}function J(t){return new Promise((e,n)=>{let r=new FileReader;r.onload=()=>e(String(r.result||"")),r.onerror=()=>n(new Error("read_failed")),r.readAsDataURL(t)})}function wt(t,e){return[e.as||"blob",e.timeout??3e3,e.useProxy||"",e.errorTTL??8e3,t].join("|")}async function R(t,e={}){let n=e.as??"blob",r=e.timeout??3e3,o=e.useProxy||"",i=e.errorTTL??8e3,s=e.headers||{},u=!!e.silent;if(/^data:/i.test(t))try{if(n==="text")return{ok:!0,data:String(t),status:200,url:t,fromCache:!1};if(n==="dataURL")return{ok:!0,data:String(t),status:200,url:t,fromCache:!1,mime:String(t).slice(5).split(";")[0]||""};let[,l="",d=""]=String(t).match(/^data:([^,]*),(.*)$/)||[],h=/;base64/i.test(l)?atob(d):decodeURIComponent(d),S=new Uint8Array([...h].map(A=>A.charCodeAt(0))),k=new Blob([S],{type:(l||"").split(";")[0]||""});return{ok:!0,data:k,status:200,url:t,fromCache:!1,mime:k.type||""}}catch{return{ok:!1,data:null,status:0,url:t,fromCache:!1,reason:"special_url_error"}}if(/^blob:/i.test(t))try{let l=await fetch(t);if(!l.ok)return{ok:!1,data:null,status:l.status,url:t,fromCache:!1,reason:"http_error"};let d=await l.blob(),y=d.type||l.headers.get("content-type")||"";return n==="dataURL"?{ok:!0,data:await J(d),status:l.status,url:t,fromCache:!1,mime:y}:n==="text"?{ok:!0,data:await d.text(),status:l.status,url:t,fromCache:!1,mime:y}:{ok:!0,data:d,status:l.status,url:t,fromCache:!1,mime:y}}catch{return{ok:!1,data:null,status:0,url:t,fromCache:!1,reason:"network"}}if(/^about:blank$/i.test(t))return n==="dataURL"?{ok:!0,data:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR4nGMAAQAABQABDQottAAAAABJRU5ErkJggg==",status:200,url:t,fromCache:!1,mime:"image/png"}:{ok:!0,data:n==="text"?"":new Blob([]),status:200,url:t,fromCache:!1};let c=wt(t,{as:n,timeout:r,useProxy:o,errorTTL:i}),m=W.get(c);if(m&&m.until>Date.now())return{...m.result,fromCache:!0};m&&W.delete(c);let p=j.get(c);if(p)return p;let g=gt(t,o)?yt(t,o):t,w=e.credentials;if(!w)try{let l=typeof location<"u"&&location.href?location.href:"http://localhost/",d=new URL(t,l);w=typeof location<"u"&&d.origin===location.origin?"include":"omit"}catch{w="omit"}let b=new AbortController,C=setTimeout(()=>b.abort("timeout"),r),a=(async()=>{try{let l=await fetch(g,{signal:b.signal,credentials:w,headers:s});if(!l.ok){let h={ok:!1,data:null,status:l.status,url:g,fromCache:!1,reason:"http_error"};if(i>0&&W.set(c,{until:Date.now()+i,result:h}),!u){let S=`${l.status} ${l.statusText||""}`.trim();Y.warnOnce(`http:${l.status}:${n}:${new URL(t,location?.href??"http://localhost/").origin}`,`HTTP error ${S} while fetching ${n} ${t}`)}return e.onError&&e.onError(h),h}if(n==="text")return{ok:!0,data:await l.text(),status:l.status,url:g,fromCache:!1};let d=await l.blob(),y=d.type||l.headers.get("content-type")||"";return n==="dataURL"?{ok:!0,data:await J(d),status:l.status,url:g,fromCache:!1,mime:y}:{ok:!0,data:d,status:l.status,url:g,fromCache:!1,mime:y}}catch(l){let d=l&&typeof l=="object"&&"name"in l&&l.name==="AbortError"?String(l.message||"").includes("timeout")?"timeout":"abort":"network",y={ok:!1,data:null,status:0,url:g,fromCache:!1,reason:d};if(!/^blob:/i.test(t)&&i>0&&W.set(c,{until:Date.now()+i,result:y}),!u){let h=`${d}:${n}:${new URL(t,location?.href??"http://localhost/").origin}`,S=d==="timeout"?`Timeout after ${r}ms. Consider increasing timeout or using a proxy for ${t}`:d==="abort"?`Request aborted while fetching ${n} ${t}`:`Network/CORS issue while fetching ${n} ${t}. A proxy may be required`;Y.errorOnce(h,S)}return e.onError&&e.onError(y),y}finally{clearTimeout(C),j.delete(c)}})();return j.set(c,a),a}async function T(t,e={}){if(/^((repeating-)?(linear|radial|conic)-gradient)\(/i.test(t)||t.trim()==="none")return t;let r=N(t);if(!r)return t;let o=O(r);if(f.background.has(o)){let i=f.background.get(o);return i?`url("${i}")`:"none"}try{let i=await R(o,{as:"dataURL",useProxy:e.useProxy});return i.ok?(f.background.set(o,i.data),`url("${i.data}")`):(f.background.set(o,null),"none")}catch{return f.background.set(o,null),"none"}}var Z=new Set(["meta","script","noscript","title","link","template"]),z=new Set(["meta","link","style","title","noscript","script","template","g","defs","use","marker","mask","clipPath","pattern","path","polygon","polyline","line","circle","ellipse","rect","filter","lineargradient","radialgradient","stop"]),St=["div","span","p","a","img","ul","li","button","input","select","textarea","label","section","article","header","footer","nav","main","aside","h1","h2","h3","h4","h5","h6","table","thead","tbody","tr","td","th"];function G(){for(let t of St){let e=String(t).toLowerCase();Z.has(e)||z.has(e)||tt(e)}}function tt(t){if(t=String(t).toLowerCase(),z.has(t)){let i={};return f.defaultStyle.set(t,i),i}if(f.defaultStyle.has(t))return f.defaultStyle.get(t);let e=document.getElementById("snapdom-sandbox");e||(e=document.createElement("div"),e.id="snapdom-sandbox",e.setAttribute("data-snapdom-sandbox","true"),e.setAttribute("aria-hidden","true"),e.style.position="absolute",e.style.left="-9999px",e.style.top="-9999px",e.style.width="0px",e.style.height="0px",e.style.overflow="hidden",document.body.appendChild(e));let n=document.createElement(t);n.style.all="initial",e.appendChild(n);let r=getComputedStyle(n),o={};for(let i of r){if(xt(i))continue;let s=r.getPropertyValue(i);o[i]=s}return e.removeChild(n),f.defaultStyle.set(t,o),o}var bt=/(?:^|-)(animation|transition)(?:-|$)/i,Ct=/^(--|view-timeline|scroll-timeline|animation-trigger|offset-|position-try|app-region|interactivity|overlay|view-transition|-webkit-locale|-webkit-user-(?:drag|modify)|-webkit-tap-highlight-color|-webkit-text-security)$/i,kt=new Set(["cursor","pointer-events","touch-action","user-select","print-color-adjust","speak","reading-flow","reading-order","anchor-name","anchor-scope","container-name","container-type","timeline-scope"]);function xt(t){let e=String(t).toLowerCase();return!!(kt.has(e)||Ct.test(e)||bt.test(e))}function P(t,e=null){if(!(t instanceof Element))return window.getComputedStyle(t,e);let n=f.computedStyle.get(t);if(n||(n=new Map,f.computedStyle.set(t,n)),!n.has(e)){let r=window.getComputedStyle(t,e);n.set(e,r)}return n.get(e)}function K(t){let e=[],n=0,r=0;for(let o=0;o<t.length;o++){let i=t[o];i==="("&&n++,i===")"&&n--,i===","&&n===0&&(e.push(t.slice(r,o).trim()),r=o+1)}return e.push(t.slice(r).trim()),e}function v(){if(typeof navigator>"u")return!1;let t=navigator.userAgent||"",e=t.toLowerCase(),n=e.includes("safari")&&!e.includes("chrome")&&!e.includes("crios")&&!e.includes("fxios")&&!e.includes("android"),r=/applewebkit/i.test(t),o=/mobile/i.test(t),i=!/safari/i.test(t),s=r&&o&&i,u=/(micromessenger|wxwork|wecom|windowswechat|macwechat)/i.test(t),c=/(baiduboxapp|baidubrowser|baidusearch|baiduboxlite)/i.test(e),m=/ipad|iphone|ipod/.test(e)&&r;return n||s||u||c||m}var At=[/font\s*awesome/i,/material\s*icons/i,/ionicons/i,/glyphicons/i,/feather/i,/bootstrap\s*icons/i,/remix\s*icons/i,/heroicons/i,/layui/i,/lucide/i],ie=Object.assign({materialIconsFilled:"https://fonts.gstatic.com/s/materialicons/v48/flUhRq6tzZclQEJ-Vdg-IuiaDsNcIhQ8tQ.woff2",materialIconsOutlined:"https://fonts.gstatic.com/s/materialiconsoutlined/v110/gok-H7zzDkdnRel8-DQ6KAXJ69wP1tGnf4ZGhUcel5euIg.woff2",materialIconsRound:"https://fonts.gstatic.com/s/materialiconsround/v109/LDItaoyNOAY6Uewc665JcIzCKsKc_M9flwmPq_HTTw.woff2",materialIconsSharp:"https://fonts.gstatic.com/s/materialiconssharp/v110/oPWQ_lt5nv4pWNJpghLP75WiFR4kLh3kvmvRImcycg.woff2"},typeof window<"u"&&window.__SNAPDOM_ICON_FONTS__||{}),$t=[];function M(t){let e=typeof t=="string"?t:"",n=[...At,...$t];for(let r of n)if(r instanceof RegExp&&r.test(e))return!0;return!!(/icon/i.test(e)||/glyph/i.test(e)||/symbols/i.test(e)||/feather/i.test(e)||/fontawesome/i.test(e))}var Rt=new Set(["serif","sans-serif","monospace","cursive","fantasy","system-ui","emoji","math","fangsong","ui-serif","ui-sans-serif","ui-monospace","ui-rounded"]),Mt=["katex","mathjax","mathml"];function V(t){if(!t)return"";for(let e of t.split(",")){let n=e.trim().replace(/^['"]+|['"]+$/g,"");if(n&&!Rt.has(n.toLowerCase()))return n}return""}function B(t){let e=String(t??"400").trim().toLowerCase();if(e==="normal")return 400;if(e==="bold")return 700;let n=parseInt(e,10);return Number.isFinite(n)?Math.min(900,Math.max(100,n)):400}function D(t){let e=String(t??"normal").trim().toLowerCase();return e.startsWith("italic")?"italic":e.startsWith("oblique")?"oblique":"normal"}function Lt(t){let e=String(t??"100%").match(/(\d+(?:\.\d+)?)\s*%/);return e?Math.max(50,Math.min(200,parseFloat(e[1]))):100}function Ft(t){let e=String(t||"400").trim(),n=e.match(/^(\d{2,3})\s+(\d{2,3})$/);if(n){let o=B(n[1]),i=B(n[2]);return{min:Math.min(o,i),max:Math.max(o,i)}}let r=B(e);return{min:r,max:r}}function Et(t){let e=String(t||"normal").trim().toLowerCase();return e==="italic"?{kind:"italic"}:e.startsWith("oblique")?{kind:"oblique"}:{kind:"normal"}}function Ut(t){let e=String(t||"100%").trim(),n=e.match(/(\d+(?:\.\d+)?)\s*%\s+(\d+(?:\.\d+)?)\s*%/);if(n){let i=parseFloat(n[1]),s=parseFloat(n[2]);return{min:Math.min(i,s),max:Math.max(i,s)}}let r=e.match(/(\d+(?:\.\d+)?)\s*%/),o=r?parseFloat(r[1]):100;return{min:o,max:o}}function _t(t,e){if(!t)return!1;try{let n=new URL(t,location.href);if(n.origin===location.origin)return!0;let o=n.host.toLowerCase();if(["fonts.googleapis.com","fonts.gstatic.com","use.typekit.net","p.typekit.net","kit.fontawesome.com","use.fontawesome.com"].some(u=>o.endsWith(u)))return!0;let s=(n.pathname+n.search).toLowerCase();if(/\bfont(s)?\b/.test(s)||/\.woff2?(\b|$)/.test(s)||Mt.some(u=>s.includes(u)))return!0;for(let u of e){let c=u.toLowerCase().replace(/\s+/g,"+"),m=u.toLowerCase().replace(/\s+/g,"-");if(s.includes(c)||s.includes(m))return!0}return!1}catch{return!1}}function It(t){let e=new Set;for(let n of t||[]){let r=String(n).split("__")[0]?.trim();r&&e.add(r)}return e}function et(t,e){return t&&t.replace(/url\(\s*(['"]?)([^)'"]+)\1\s*\)/g,(n,r,o)=>{let i=(o||"").trim();if(!i||/^data:|^blob:|^https?:|^file:|^about:/i.test(i))return n;let s=i;try{s=new URL(i,e||location.href).href}catch{}return`url("${s}")`})}var H=/@import\s+(?:url\(\s*(['"]?)([^)"']+)\1\s*\)|(['"])([^"']+)\3)([^;]*);/g,q=4;async function Ot(t,e,n){if(!t)return t;let r=new Set;function o(u,c){try{return new URL(u,c||location.href).href}catch{return u}}async function i(u,c,m=0){if(m>q)return console.warn(`[snapDOM] @import depth exceeded (${q}) at ${c}`),u;let p="",g=0,w;for(;w=H.exec(u);){p+=u.slice(g,w.index),g=H.lastIndex;let b=(w[2]||w[4]||"").trim(),C=o(b,c);if(r.has(C)){console.warn(`[snapDOM] Skipping circular @import: ${C}`);continue}r.add(C);let a="";try{let l=await R(C,{as:"text",useProxy:n,silent:!0});l.ok&&typeof l.data=="string"&&(a=l.data)}catch{}a?(a=et(a,C),a=await i(a,C,m+1),p+=`
8
- /* inlined: ${C} */
9
- ${a}
10
- `):p+=w[0]}return p+=u.slice(g),p}let s=et(t,e||location.href);return s=await i(s,e||location.href,0),s}var ot=/url\((["']?)([^"')]+)\1\)/g,Tt=/@font-face[^{}]*\{[^}]*\}/g;function rt(t){if(!t)return[];let e=[],n=t.split(",").map(r=>r.trim()).filter(Boolean);for(let r of n){let o=r.match(/^U\+([0-9A-Fa-f?]+)(?:-([0-9A-Fa-f?]+))?$/);if(!o)continue;let i=o[1],s=o[2],u=c=>{if(!c.includes("?"))return parseInt(c,16);let m=parseInt(c.replace(/\?/g,"0"),16),p=parseInt(c.replace(/\?/g,"F"),16);return[m,p]};if(s){let c=u(i),m=u(s),p=Array.isArray(c)?c[0]:c,g=Array.isArray(m)?m[1]:m;e.push([Math.min(p,g),Math.max(p,g)])}else{let c=u(i);Array.isArray(c)?e.push([c[0],c[1]]):e.push([c,c])}}return e}function st(t,e){if(!e.length||!t||t.size===0)return!0;for(let n of t)for(let[r,o]of e)if(n>=r&&n<=o)return!0;return!1}function Q(t,e){let n=[];if(!t)return n;for(let r of t.matchAll(ot)){let o=(r[2]||"").trim();if(!(!o||o.startsWith("data:"))){if(!/^https?:/i.test(o))try{o=new URL(o,e||location.href).href}catch{}n.push(o)}}return n}async function at(t,e,n=""){let r=t;for(let o of t.matchAll(ot)){let i=N(o[0]);if(!i)continue;let s=i;if(!s.startsWith("http")&&!s.startsWith("data:"))try{s=new URL(s,e||location.href).href}catch{}if(!M(s)){if(f.resource?.has(s)){f.font?.add(s),r=r.replace(o[0],`url(${f.resource.get(s)})`);continue}if(!f.font?.has(s))try{let u=await R(s,{as:"dataURL",useProxy:n,silent:!0});if(u.ok&&typeof u.data=="string"){let c=u.data;f.resource?.set(s,c),f.font?.add(s),r=r.replace(o[0],`url(${c})`)}}catch{console.warn("[snapDOM] Failed to fetch font resource:",s)}}}return r}function Pt(t){if(!t.length)return null;let e=(u,c)=>t.some(([m,p])=>!(p<u||m>c)),n=e(0,255)||e(305,305),r=e(256,591)||e(7680,7935),o=e(880,1023),i=e(1024,1279);return e(7840,7929)||e(258,259)||e(416,417)||e(431,432)?"vietnamese":i?"cyrillic":o?"greek":r?"latin-ext":n?"latin":null}function nt(t={}){let e=new Set((t.families||[]).map(o=>String(o).toLowerCase())),n=new Set((t.domains||[]).map(o=>String(o).toLowerCase())),r=new Set((t.subsets||[]).map(o=>String(o).toLowerCase()));return(o,i)=>{if(e.size&&e.has(o.family.toLowerCase()))return!0;if(n.size)for(let s of o.srcUrls)try{if(n.has(new URL(s).host.toLowerCase()))return!0}catch{}if(r.size){let s=Pt(i);if(s&&r.has(s))return!0}return!1}}function vt(t){if(!t)return t;let e=/@font-face[^{}]*\{[^}]*\}/gi,n=new Set,r=[];for(let i of t.match(e)||[]){let s=i.match(/font-family:\s*([^;]+);/i)?.[1]||"",u=V(s),c=(i.match(/font-weight:\s*([^;]+);/i)?.[1]||"400").trim(),m=(i.match(/font-style:\s*([^;]+);/i)?.[1]||"normal").trim(),p=(i.match(/font-stretch:\s*([^;]+);/i)?.[1]||"100%").trim(),g=(i.match(/unicode-range:\s*([^;]+);/i)?.[1]||"").trim(),w=(i.match(/src\s*:\s*([^;}]+)[;}]/i)?.[1]||"").trim(),b=Q(w,location.href),C=b.length?b.map(l=>String(l).toLowerCase()).sort().join("|"):w.toLowerCase(),a=[String(u||"").toLowerCase(),c,m,p,g.toLowerCase(),C].join("|");n.has(a)||(n.add(a),r.push(i))}if(r.length===0)return t;let o=0;return t.replace(e,()=>r[o++]||"")}function Nt(t,e,n,r){let o=Array.from(t||[]).sort().join("|"),i=e?JSON.stringify({families:(e.families||[]).map(c=>String(c).toLowerCase()).sort(),domains:(e.domains||[]).map(c=>String(c).toLowerCase()).sort(),subsets:(e.subsets||[]).map(c=>String(c).toLowerCase()).sort()}):"",s=(n||[]).map(c=>`${(c.family||"").toLowerCase()}::${c.weight||"normal"}::${c.style||"normal"}::${c.src||""}`).sort().join("|");return`fonts-embed-css::req=${o}::ex=${i}::lf=${s}::px=${r||""}`}async function it(t,e,n,r){let o;try{o=t.cssRules||[]}catch{return}let i=(s,u)=>{try{return new URL(s,u||location.href).href}catch{return s}};for(let s of o){if(s.type===CSSRule.IMPORT_RULE&&s.styleSheet){let u=s.href?i(s.href,e):e;if(r.depth>=q){console.warn(`[snapDOM] CSSOM import depth exceeded (${q}) at ${u}`);continue}if(u&&r.visitedSheets.has(u)){console.warn(`[snapDOM] Skipping circular CSSOM import: ${u}`);continue}u&&r.visitedSheets.add(u);let c={...r,depth:(r.depth||0)+1};await it(s.styleSheet,u,n,c);continue}if(s.type===CSSRule.FONT_FACE_RULE){let u=(s.style.getPropertyValue("font-family")||"").trim(),c=V(u);if(!c||M(c))continue;let m=(s.style.getPropertyValue("font-weight")||"400").trim(),p=(s.style.getPropertyValue("font-style")||"normal").trim(),g=(s.style.getPropertyValue("font-stretch")||"100%").trim(),w=(s.style.getPropertyValue("src")||"").trim(),b=(s.style.getPropertyValue("unicode-range")||"").trim();if(!r.faceMatchesRequired(c,p,m,g))continue;let C=rt(b);if(!st(r.usedCodepoints,C))continue;let a={family:c,weightSpec:m,styleSpec:p,stretchSpec:g,unicodeRange:b,srcRaw:w,srcUrls:Q(w,e||location.href),href:e||location.href};if(r.simpleExcluder&&r.simpleExcluder(a,C))continue;if(/url\(/i.test(w)){let l=await at(w,e||location.href,r.useProxy);await n(`@font-face{font-family:${c};src:${l};font-style:${p};font-weight:${m};font-stretch:${g};${b?`unicode-range:${b};`:""}}`)}else await n(`@font-face{font-family:${c};src:${w};font-style:${p};font-weight:${m};font-stretch:${g};${b?`unicode-range:${b};`:""}}`)}}}async function ct({required:t,usedCodepoints:e,exclude:n=void 0,localFonts:r=[],useProxy:o=""}={}){t instanceof Set||(t=new Set),e instanceof Set||(e=new Set);let i=new Map;for(let a of t){let[l,d,y,h]=String(a).split("__");if(!l)continue;let S=i.get(l)||[];S.push({w:parseInt(d,10),s:y,st:parseInt(h,10)}),i.set(l,S)}function s(a,l,d,y){if(!i.has(a))return!1;let h=i.get(a),S=Ft(d),k=Et(l),A=Ut(y),F=S.min!==S.max,E=S.min,I=x=>k.kind==="normal"&&x==="normal"||k.kind!=="normal"&&(x==="italic"||x==="oblique"),U=!1;for(let x of h){let $=F?x.w>=S.min&&x.w<=S.max:x.w===E,L=I(D(x.s)),_=x.st>=A.min&&x.st<=A.max;if($&&L&&_){U=!0;break}}if(U)return!0;if(!F)for(let x of h){let $=I(D(x.s)),L=x.st>=A.min&&x.st<=A.max;if(Math.abs(E-x.w)<=300&&$&&L)return!0}if(!F&&k.kind==="normal"&&h.some($=>D($.s)!=="normal"))for(let $ of h){let L=Math.abs(E-$.w)<=300,_=$.st>=A.min&&$.st<=A.max;if(L&&_)return!0}return!1}let u=nt(n),c=Nt(t,n,r,o);if(f.resource?.has(c))return f.resource.get(c);let m=It(t),p=[],g=H;for(let a of document.querySelectorAll("style")){let l=a.textContent||"";for(let d of l.matchAll(g)){let y=(d[2]||d[4]||"").trim();if(!y||M(y))continue;!!document.querySelector(`link[rel="stylesheet"][href="${y}"]`)||p.push(y)}}p.length&&await Promise.all(p.map(a=>new Promise(l=>{if(document.querySelector(`link[rel="stylesheet"][href="${a}"]`))return l(null);let d=document.createElement("link");d.rel="stylesheet",d.href=a,d.setAttribute("data-snapdom","injected-import"),d.onload=()=>l(d),d.onerror=()=>l(null),document.head.appendChild(d)})));let w="",b=Array.from(document.querySelectorAll('link[rel="stylesheet"]')).filter(a=>!!a.href);for(let a of b)try{if(M(a.href))continue;let l="",d=!1;try{d=new URL(a.href,location.href).origin===location.origin}catch{}if(!d&&!_t(a.href,m))continue;if(d){let h=Array.from(document.styleSheets).find(S=>S.href===a.href);if(h)try{let S=h.cssRules||[];l=Array.from(S).map(k=>k.cssText).join("")}catch{}}if(!l){let h=await R(a.href,{as:"text",useProxy:o});if(h?.ok&&typeof h.data=="string"&&(l=h.data),M(a.href))continue}l=await Ot(l,a.href,o);let y="";for(let h of l.match(Tt)||[]){let S=(h.match(/font-family:\s*([^;]+);/i)?.[1]||"").trim(),k=V(S);if(!k||M(k))continue;let A=(h.match(/font-weight:\s*([^;]+);/i)?.[1]||"400").trim(),F=(h.match(/font-style:\s*([^;]+);/i)?.[1]||"normal").trim(),E=(h.match(/font-stretch:\s*([^;]+);/i)?.[1]||"100%").trim(),I=(h.match(/unicode-range:\s*([^;]+);/i)?.[1]||"").trim(),U=(h.match(/src\s*:\s*([^;}]+)[;}]/i)?.[1]||"").trim(),x=Q(U,a.href);if(!s(k,F,A,E))continue;let $=rt(I);if(!st(e,$))continue;let L={family:k,weightSpec:A,styleSpec:F,stretchSpec:E,unicodeRange:I,srcRaw:U,srcUrls:x,href:a.href};if(n&&u(L,$))continue;let _=/url\(/i.test(U)?await at(h,a.href,o):h;y+=_}y.trim()&&(w+=y)}catch{console.warn("[snapDOM] Failed to process stylesheet:",a.href)}let C={requiredIndex:i,usedCodepoints:e,faceMatchesRequired:s,simpleExcluder:n?nt(n):null,useProxy:o,visitedSheets:new Set,depth:0};for(let a of document.styleSheets)if(!(a.href&&b.some(l=>l.href===a.href)))try{let l=a.href||location.origin+"/";l&&C.visitedSheets.add(l),await it(a,l,async d=>{w+=d},C)}catch{}try{for(let a of document.fonts||[]){if(!a||!a.family||a.status!=="loaded"||!a._snapdomSrc)continue;let l=String(a.family).replace(/^['"]+|['"]+$/g,"");if(M(l)||!i.has(l)||n?.families&&n.families.some(y=>String(y).toLowerCase()===l.toLowerCase()))continue;let d=a._snapdomSrc;if(!String(d).startsWith("data:")){if(f.resource?.has(a._snapdomSrc))d=f.resource.get(a._snapdomSrc),f.font?.add(a._snapdomSrc);else if(!f.font?.has(a._snapdomSrc))try{let y=await R(a._snapdomSrc,{as:"dataURL",useProxy:o,silent:!0});if(y.ok&&typeof y.data=="string")d=y.data,f.resource?.set(a._snapdomSrc,d),f.font?.add(a._snapdomSrc);else continue}catch{console.warn("[snapDOM] Failed to fetch dynamic font src:",a._snapdomSrc);continue}}w+=`@font-face{font-family:'${l}';src:url(${d});font-style:${a.style||"normal"};font-weight:${a.weight||"normal"};}`}}catch{}for(let a of r){if(!a||typeof a!="object")continue;let l=String(a.family||"").replace(/^['"]+|['"]+$/g,"");if(!l||M(l)||!i.has(l)||n?.families&&n.families.some(A=>String(A).toLowerCase()===l.toLowerCase()))continue;let d=a.weight!=null?String(a.weight):"normal",y=a.style!=null?String(a.style):"normal",h=a.stretchPct!=null?`${a.stretchPct}%`:"100%",S=String(a.src||""),k=S;if(!k.startsWith("data:")){if(f.resource?.has(S))k=f.resource.get(S),f.font?.add(S);else if(!f.font?.has(S))try{let A=await R(S,{as:"dataURL",useProxy:o,silent:!0});if(A.ok&&typeof A.data=="string")k=A.data,f.resource?.set(S,k),f.font?.add(S);else continue}catch{console.warn("[snapDOM] Failed to fetch localFonts src:",S);continue}}w+=`@font-face{font-family:'${l}';src:url(${k});font-style:${y};font-weight:${d};font-stretch:${h};}`}return w&&(w=vt(w),f.resource?.set(c,w)),w}function lt(t){let e=new Set;if(!t)return e;let n=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),r=s=>{let u=V(s.fontFamily);if(!u)return;let c=(m,p,g)=>`${u}__${B(m)}__${D(p)}__${Lt(g)}`;e.add(c(s.fontWeight,s.fontStyle,s.fontStretch))};r(getComputedStyle(t));let o=getComputedStyle(t,"::before");o&&o.content&&o.content!=="none"&&r(o);let i=getComputedStyle(t,"::after");for(i&&i.content&&i.content!=="none"&&r(i);n.nextNode();){let s=n.currentNode,u=getComputedStyle(s);r(u);let c=getComputedStyle(s,"::before");c&&c.content&&c.content!=="none"&&r(c);let m=getComputedStyle(s,"::after");m&&m.content&&m.content!=="none"&&r(m)}return e}function ft(t){let e=new Set,n=o=>{if(o)for(let i of o)e.add(i.codePointAt(0))},r=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_TEXT,null);for(;r.nextNode();){let o=r.currentNode;if(o.nodeType===Node.TEXT_NODE)n(o.nodeValue||"");else if(o.nodeType===Node.ELEMENT_NODE){let i=o;for(let s of["::before","::after"]){let c=getComputedStyle(i,s)?.getPropertyValue("content");if(!(!c||c==="none"))if(/^"/.test(c)||/^'/.test(c))n(c.slice(1,-1));else{let m=c.match(/\\[0-9A-Fa-f]{1,6}/g);if(m)for(let p of m)try{e.add(parseInt(p.slice(1),16))}catch{}}}}}return e}async function ut(t,e=2){try{await document.fonts.ready}catch{}let n=Array.from(t||[]).filter(Boolean);if(n.length===0)return;let r=()=>{let o=document.createElement("div");o.style.cssText="position:absolute!important;left:-9999px!important;top:0!important;opacity:0!important;pointer-events:none!important;contain:layout size style;";for(let i of n){let s=document.createElement("span");s.textContent="AaBbGg1234\xC1\xC9\xCD\xD3\xDA\xE7\xF1\u2014\u221E",s.style.fontFamily=`"${i}"`,s.style.fontWeight="700",s.style.fontStyle="italic",s.style.fontSize="32px",s.style.lineHeight="1",s.style.whiteSpace="nowrap",s.style.margin="0",s.style.padding="0",o.appendChild(s)}document.body.appendChild(o),o.offsetWidth,document.body.removeChild(o)};for(let o=0;o<Math.max(1,e);o++)r(),await new Promise(i=>requestAnimationFrame(()=>requestAnimationFrame(i)))}async function mt(t,e,n,r={}){let o=[[t,e]],i=["background-image","mask","mask-image","-webkit-mask","-webkit-mask-image","mask-source","mask-box-image-source","mask-border-source","-webkit-mask-box-image-source","border-image","border-image-source"],s=["mask-position","mask-size","mask-repeat","-webkit-mask-position","-webkit-mask-size","-webkit-mask-repeat","mask-origin","mask-clip","-webkit-mask-origin","-webkit-mask-clip","-webkit-mask-position-x","-webkit-mask-position-y"],u=["background-position","background-position-x","background-position-y","background-size","background-repeat","background-origin","background-clip","background-attachment","background-blend-mode"],c=["border-image-slice","border-image-width","border-image-outset","border-image-repeat"];for(;o.length;){let[m,p]=o.shift();if(!p)continue;let g=n.get(m)||P(m);n.has(m)||n.set(m,g);let w=(()=>{let a=g.getPropertyValue("border-image"),l=g.getPropertyValue("border-image-source");return a&&a!=="none"||l&&l!=="none"})();for(let a of u){let l=g.getPropertyValue(a);l&&p.style.setProperty(a,l)}for(let a of i){let l=g.getPropertyValue(a);if(!l||l==="none")continue;let d=K(l),y=await Promise.all(d.map(h=>T(h,r)));y.some(h=>h&&h!=="none"&&!/^url\(undefined/.test(h))&&p.style.setProperty(a,y.join(", "))}for(let a of s){let l=g.getPropertyValue(a);!l||l==="initial"||p.style.setProperty(a,l)}if(w)for(let a of c){let l=g.getPropertyValue(a);!l||l==="initial"||p.style.setProperty(a,l)}let b=m.shadowRoot?Array.from(m.shadowRoot.children).filter(a=>a.tagName!=="STYLE"):Array.from(m.children),C=Array.from(p.children).filter(a=>!(a.dataset?.snapdomPseudo||a.tagName==="STYLE"&&a.dataset?.sd));for(let a=0;a<Math.min(b.length,C.length);a++)o.push([b[a],C[a]])}}async function Ce(t=document,e={}){let{embedFonts:n=!0,useProxy:r=""}=e,o=e.cache??e.cacheOpt??"full";X(o);try{await document.fonts?.ready}catch{}try{G()}catch{}f.session=f.session||{},f.session.styleCache||(f.session.styleCache=new WeakMap),f.image=f.image||new Map,f.background=f.background||new Map;try{await mt(t,void 0,f.session.styleCache,{useProxy:r})}catch{}let i=[],s=[];try{if(t&&t.nodeType===1){let c=t.querySelectorAll?Array.from(t.querySelectorAll("*")):[];s=[t,...c],i=[],t.tagName==="IMG"&&t.getAttribute("src")&&i.push(t),i.push(...Array.from(t.querySelectorAll?.("img[src]")||[]))}else t?.querySelectorAll&&(i=Array.from(t.querySelectorAll("img[src]")),s=Array.from(t.querySelectorAll("*")))}catch{}let u=[];for(let c of i){let m=c?.currentSrc||c?.src;if(m&&!f.image.has(m)){let p=Promise.resolve().then(async()=>{let g=await R(m,{as:"dataURL",useProxy:r});g?.ok&&typeof g.data=="string"&&f.image.set(m,g.data)}).catch(()=>{});u.push(p)}}for(let c of s){let m="";try{m=c?.style?.backgroundImage||"",(!m||m==="none")&&(m=P(c).backgroundImage)}catch{}if(m&&m!=="none"){let p=m.match(/url\((?:[^()"']+|"(?:[^"]*)"|'(?:[^']*)')\)/gi)||[];for(let g of p){let w=Promise.resolve().then(()=>T(g,{...e,useProxy:r})).catch(()=>{});u.push(w)}}}if(n)try{let c=lt(t),m=ft(t);if(typeof v=="function"?v():!!v){let g=new Set(Array.from(c).map(w=>String(w).split("__")[0]).filter(Boolean));await ut(g,3)}await ct({required:c,usedCodepoints:m,exclude:e.excludeFonts,localFonts:e.localFonts,useProxy:e.useProxy??r})}catch{}await Promise.allSettled(u)}export{Ce as preCache};
7
+ var L=class extends Map{constructor(e=100,...n){super(...n),this._maxSize=e}set(e,n){if(this.size>=this._maxSize&&!this.has(e)){let o=this.keys().next().value;o!==void 0&&this.delete(o)}return super.set(e,n)}},u={image:new L(100),background:new L(100),resource:new L(150),defaultStyle:new L(30),baseStyle:new L(50),computedStyle:new WeakMap,measureHints:new WeakMap,font:new Set,session:{styleMap:new Map,styleCache:new WeakMap,nodeMap:new Map}};function J(t="soft"){switch(u.session.__counterEpoch=(u.session.__counterEpoch||0)+1,t){case"auto":{u.session.styleMap=new Map,u.session.nodeMap=new Map;return}case"soft":{u.session.styleMap=new Map,u.session.nodeMap=new Map,u.session.styleCache=new WeakMap;return}case"full":return;case"disabled":{u.session.styleMap=new Map,u.session.nodeMap=new Map,u.session.styleCache=new WeakMap,u.computedStyle=new WeakMap,u.baseStyle=new L(50),u.defaultStyle=new L(30),u.image=new L(100),u.background=new L(100),u.resource=new L(150),u.font=new Set;return}default:{u.session.styleMap=new Map,u.session.nodeMap=new Map,u.session.styleCache=new WeakMap;return}}}function W(t){let e=t.match(/url\((['"]?)(.*?)(\1)\)/);if(!e)return null;let n=e[2].trim();return n.startsWith("#")?null:n}function v(t){if(/%[0-9A-Fa-f]{2}/.test(t))return t;try{return encodeURI(t)}catch{return t}}function Z(t,e){if(!t||/^(data|blob|about|#)/i.test(t.trim()))return t;try{let n=e||typeof document<"u"&&(document.baseURI||document.location?.href)||"http://localhost/";return new URL(t,n).href}catch{return t}}function wt(t="[snapDOM]",{ttlMs:e=5*6e4,maxEntries:n=12}={}){let o=new Map,a=0;function i(r,f,c){if(a>=n)return;let l=Date.now();(o.get(f)||0)>l||(o.set(f,l+e),a++,r==="warn"&&console&&console.warn?console.warn(`${t} ${c}`):console&&console.error&&console.error(`${t} ${c}`))}return{warnOnce(r,f){i("warn",r,f)},errorOnce(r,f){i("error",r,f)},reset(){o.clear(),a=0}}}var tt=wt("[snapDOM]",{ttlMs:3*6e4,maxEntries:10}),X=new Map,B=new Map;function St(t){return/^data:|^blob:|^about:blank$/i.test(t)}function bt(t,e){try{let n=typeof location<"u"&&location.href?location.href:"http://localhost/",o=e.includes("{url}")?e.split("{url}")[0]:e,a=new URL(o||".",n),i=new URL(t,n);if(i.origin===a.origin)return!0;let r=i.searchParams;if(r&&(r.has("url")||r.has("target")))return!0}catch{}return!1}function Ct(t,e){if(!e||St(t)||bt(t,e))return!1;try{let n=typeof location<"u"&&location.href?location.href:"http://localhost/",o=new URL(t,n);return typeof location<"u"?o.origin!==location.origin:!0}catch{return!!e}}function xt(t,e){if(!e)return t;if(e.includes("{url}"))return e.replace("{urlRaw}",v(t)).replace("{url}",encodeURIComponent(t));if(/[?&]url=?$/.test(e))return`${e}${encodeURIComponent(t)}`;if(e.endsWith("?"))return`${e}url=${encodeURIComponent(t)}`;if(e.endsWith("/"))return`${e}${v(t)}`;let n=e.includes("?")?"&":"?";return`${e}${n}url=${encodeURIComponent(t)}`}function et(t){return new Promise((e,n)=>{let o=new FileReader;o.onload=()=>e(String(o.result||"")),o.onerror=()=>n(new Error("read_failed")),o.readAsDataURL(t)})}function kt(t,e){return[e.as||"blob",e.timeout??3e3,e.useProxy||"",e.errorTTL??8e3,t].join("|")}async function M(t,e={}){let n=e.as??"blob",o=e.timeout??3e3,a=e.useProxy||"",i=e.errorTTL??8e3,r=e.headers||{},f=!!e.silent;if(/^data:/i.test(t))try{if(n==="text")return{ok:!0,data:String(t),status:200,url:t,fromCache:!1};if(n==="dataURL")return{ok:!0,data:String(t),status:200,url:t,fromCache:!1,mime:String(t).slice(5).split(";")[0]||""};let[,s="",d=""]=String(t).match(/^data:([^,]*),(.*)$/)||[],y=/;base64/i.test(s)?atob(d):decodeURIComponent(d),w=new Uint8Array([...y].map(k=>k.charCodeAt(0))),C=new Blob([w],{type:(s||"").split(";")[0]||""});return{ok:!0,data:C,status:200,url:t,fromCache:!1,mime:C.type||""}}catch{return{ok:!1,data:null,status:0,url:t,fromCache:!1,reason:"special_url_error"}}if(/^blob:/i.test(t))try{let s=await fetch(t);if(!s.ok)return{ok:!1,data:null,status:s.status,url:t,fromCache:!1,reason:"http_error"};let d=await s.blob(),g=d.type||s.headers.get("content-type")||"";return n==="dataURL"?{ok:!0,data:await et(d),status:s.status,url:t,fromCache:!1,mime:g}:n==="text"?{ok:!0,data:await d.text(),status:s.status,url:t,fromCache:!1,mime:g}:{ok:!0,data:d,status:s.status,url:t,fromCache:!1,mime:g}}catch{return{ok:!1,data:null,status:0,url:t,fromCache:!1,reason:"network"}}if(/^about:blank$/i.test(t))return n==="dataURL"?{ok:!0,data:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR4nGMAAQAABQABDQottAAAAABJRU5ErkJggg==",status:200,url:t,fromCache:!1,mime:"image/png"}:{ok:!0,data:n==="text"?"":new Blob([]),status:200,url:t,fromCache:!1};let c=kt(t,{as:n,timeout:o,useProxy:a,errorTTL:i}),l=B.get(c);if(l&&l.until>Date.now())return{...l.result,fromCache:!0};l&&B.delete(c);let m=X.get(c);if(m)return m;let p=Ct(t,a)?xt(t,a):t,S=e.credentials;if(!S)try{let s=typeof location<"u"&&location.href?location.href:"http://localhost/",d=new URL(t,s);S=typeof location<"u"&&d.origin===location.origin?"include":"omit"}catch{S="omit"}let b=new AbortController,x=setTimeout(()=>b.abort("timeout"),o),h=(async()=>{try{let s=await fetch(p,{signal:b.signal,credentials:S,headers:r});if(!s.ok){let y={ok:!1,data:null,status:s.status,url:p,fromCache:!1,reason:"http_error"};if(i>0&&B.set(c,{until:Date.now()+i,result:y}),!f){let w=`${s.status} ${s.statusText||""}`.trim();tt.warnOnce(`http:${s.status}:${n}:${new URL(t,location?.href??"http://localhost/").origin}`,`HTTP error ${w} while fetching ${n} ${t}`)}return e.onError&&e.onError(y),y}if(n==="text")return{ok:!0,data:await s.text(),status:s.status,url:p,fromCache:!1};let d=await s.blob(),g=d.type||s.headers.get("content-type")||"";return n==="dataURL"?{ok:!0,data:await et(d),status:s.status,url:p,fromCache:!1,mime:g}:{ok:!0,data:d,status:s.status,url:p,fromCache:!1,mime:g}}catch(s){let d=s&&typeof s=="object"&&"name"in s&&s.name==="AbortError"?String(s.message||"").includes("timeout")?"timeout":"abort":"network",g={ok:!1,data:null,status:0,url:p,fromCache:!1,reason:d};if(!/^blob:/i.test(t)&&i>0&&B.set(c,{until:Date.now()+i,result:g}),!f){let y=`${d}:${n}:${new URL(t,location?.href??"http://localhost/").origin}`,w=d==="timeout"?`Timeout after ${o}ms. Consider increasing timeout or using a proxy for ${t}`:d==="abort"?`Request aborted while fetching ${n} ${t}`:`Network/CORS issue while fetching ${n} ${t}. A proxy may be required`;tt.errorOnce(y,w)}return e.onError&&e.onError(g),g}finally{clearTimeout(x),X.delete(c)}})();return X.set(c,h),h}async function P(t,e={}){if(/^((repeating-)?(linear|radial|conic)-gradient)\(/i.test(t)||t.trim()==="none")return t;let o=W(t);if(!o)return t;let a=Z(o),i=v(a);if(u.background.has(i)){let r=u.background.get(i);return r?`url("${r}")`:"none"}try{let r=await M(i,{as:"dataURL",useProxy:e.useProxy});return r.ok?(u.background.set(i,r.data),`url("${r.data}")`):(u.background.set(i,null),"none")}catch{return u.background.set(i,null),"none"}}var nt=new Set(["meta","script","noscript","title","link","template"]),z=new Set(["meta","link","style","title","noscript","script","template","g","defs","use","marker","mask","clipPath","pattern","path","polygon","polyline","line","circle","ellipse","rect","filter","lineargradient","radialgradient","stop"]),At=["div","span","p","a","img","ul","li","button","input","select","textarea","label","section","article","header","footer","nav","main","aside","h1","h2","h3","h4","h5","h6","table","thead","tbody","tr","td","th"];function K(){for(let t of At){let e=String(t).toLowerCase();nt.has(e)||z.has(e)||ot(e)}}function ot(t){if(t=String(t).toLowerCase(),z.has(t)){let i={};return u.defaultStyle.set(t,i),i}if(u.defaultStyle.has(t))return u.defaultStyle.get(t);let e=document.getElementById("snapdom-sandbox");e||(e=document.createElement("div"),e.id="snapdom-sandbox",e.setAttribute("data-snapdom-sandbox","true"),e.setAttribute("aria-hidden","true"),e.style.position="absolute",e.style.left="-9999px",e.style.top="-9999px",e.style.width="0px",e.style.height="0px",e.style.overflow="hidden",document.body.appendChild(e));let n=document.createElement(t);n.style.all="initial",e.appendChild(n);let o=getComputedStyle(n),a={};for(let i of o){if(rt(i))continue;let r=o.getPropertyValue(i);a[i]=r}return e.removeChild(n),u.defaultStyle.set(t,a),a}var Rt=/(?:^|-)(animation|transition)(?:-|$)/i,Lt=/^(--.+|view-timeline|scroll-timeline|animation-trigger|offset-|position-try|app-region|interactivity|overlay|view-transition|-webkit-locale|-webkit-user-(?:drag|modify)|-webkit-tap-highlight-color|-webkit-text-security)$/i,$t=new Set(["cursor","pointer-events","touch-action","user-select","print-color-adjust","speak","reading-flow","reading-order","anchor-name","anchor-scope","container-name","container-type","timeline-scope","zoom"]);function rt(t){let e=String(t).toLowerCase();return!!($t.has(e)||Lt.test(e)||Rt.test(e))}function Mt(t){try{let e=t?.ownerDocument;if(!e)return typeof window<"u"?window:null;let n=e.defaultView;if(n&&typeof n.getComputedStyle=="function")return n;if(typeof window<"u"&&window.frames)for(let o=0;o<window.frames.length;o++)try{if(window.frames[o]?.document===e)return window.frames[o]}catch{}}catch{}return typeof window<"u"?window:null}function N(t,e=null){let n=()=>{let i={length:0,getPropertyValue:()=>"",item:()=>""};return i[Symbol.iterator]=function*(){},i};if(!(t instanceof Element)){let i=typeof window<"u"?window:null;if(i&&typeof i.getComputedStyle=="function")try{return i.getComputedStyle(t,e)||n()}catch{return n()}return n()}let o=u.computedStyle.get(t);o||(o=new Map,u.computedStyle.set(t,o));let a=o.get(e);if(!a){let i=Mt(t),r=null;try{r=i&&typeof i.getComputedStyle=="function"?i.getComputedStyle(t,e):null}catch{}if(!r&&typeof window<"u"&&typeof window.getComputedStyle=="function")try{t.ownerDocument===document&&(r=window.getComputedStyle(t,e))}catch{}a=r||n(),o.set(e,a)}return a}function q(t){let e=[],n=0,o=0;for(let a=0;a<t.length;a++){let i=t[a];i==="("&&n++,i===")"&&n--,i===","&&n===0&&(e.push(t.slice(o,a).trim()),o=a+1)}return e.push(t.slice(o).trim()),e}function D(){if(typeof navigator>"u")return!1;let t=navigator.userAgent||"",e=t.toLowerCase(),n=e.includes("safari")&&!e.includes("chrome")&&!e.includes("crios")&&!e.includes("fxios")&&!e.includes("android"),o=/applewebkit/i.test(t),a=/mobile/i.test(t),i=!/safari/i.test(t),r=o&&a&&i,f=/(micromessenger|wxwork|wecom|windowswechat|macwechat)/i.test(t),c=/(baiduboxapp|baidubrowser|baidusearch|baiduboxlite)/i.test(e),l=/ipad|iphone|ipod/.test(e)&&o;return n||r||f||c||l}var Et=[/font\s*awesome/i,/material\s*icons/i,/ionicons/i,/glyphicons/i,/feather/i,/bootstrap\s*icons/i,/remix\s*icons/i,/heroicons/i,/layui/i,/lucide/i],pe=Object.assign({materialIconsFilled:"https://fonts.gstatic.com/s/materialicons/v48/flUhRq6tzZclQEJ-Vdg-IuiaDsNcIhQ8tQ.woff2",materialIconsOutlined:"https://fonts.gstatic.com/s/materialiconsoutlined/v110/gok-H7zzDkdnRel8-DQ6KAXJ69wP1tGnf4ZGhUcel5euIg.woff2",materialIconsRound:"https://fonts.gstatic.com/s/materialiconsround/v109/LDItaoyNOAY6Uewc665JcIzCKsKc_M9flwmPq_HTTw.woff2",materialIconsSharp:"https://fonts.gstatic.com/s/materialiconssharp/v110/oPWQ_lt5nv4pWNJpghLP75WiFR4kLh3kvmvRImcycg.woff2"},typeof window<"u"&&window.__SNAPDOM_ICON_FONTS__||{}),_t=[];function E(t){let e=typeof t=="string"?t:"",n=[...Et,..._t];for(let o of n)if(o instanceof RegExp&&o.test(e))return!0;return!!(/icon/i.test(e)||/glyph/i.test(e)||/symbols/i.test(e)||/feather/i.test(e)||/fontawesome/i.test(e))}var it=new Set(["serif","sans-serif","monospace","cursive","fantasy","system-ui","emoji","math","fangsong","ui-serif","ui-sans-serif","ui-monospace","ui-rounded"]),Ft=["katex","mathjax","mathml"];function H(t){if(!t)return"";for(let e of t.split(",")){let n=e.trim().replace(/^['"]+|['"]+$/g,"");if(n&&!it.has(n.toLowerCase()))return n}return""}function Ut(t){if(!t)return[];let e=[];for(let n of t.split(",")){let o=n.trim().replace(/^['"]+|['"]+$/g,"");o&&(it.has(o.toLowerCase())||e.push(o))}return e}function V(t){let e=String(t??"400").trim().toLowerCase();if(e==="normal")return 400;if(e==="bold")return 700;let n=parseInt(e,10);return Number.isFinite(n)?Math.min(900,Math.max(100,n)):400}function j(t){let e=String(t??"normal").trim().toLowerCase();return e.startsWith("italic")?"italic":e.startsWith("oblique")?"oblique":"normal"}function It(t){let e=String(t??"100%").match(/(\d+(?:\.\d+)?)\s*%/);return e?Math.max(50,Math.min(200,parseFloat(e[1]))):100}function Ot(t){let e=String(t||"400").trim(),n=e.match(/^(\d{2,3})\s+(\d{2,3})$/);if(n){let a=V(n[1]),i=V(n[2]);return{min:Math.min(a,i),max:Math.max(a,i)}}let o=V(e);return{min:o,max:o}}function Tt(t){let e=String(t||"normal").trim().toLowerCase();return e==="italic"?{kind:"italic"}:e.startsWith("oblique")?{kind:"oblique"}:{kind:"normal"}}function vt(t){let e=String(t||"100%").trim(),n=e.match(/(\d+(?:\.\d+)?)\s*%\s+(\d+(?:\.\d+)?)\s*%/);if(n){let i=parseFloat(n[1]),r=parseFloat(n[2]);return{min:Math.min(i,r),max:Math.max(i,r)}}let o=e.match(/(\d+(?:\.\d+)?)\s*%/),a=o?parseFloat(o[1]):100;return{min:a,max:a}}function Pt(t){return!t||typeof t!="string"?"":t.replace(/\s+(variable|vf|v[0-9]+)$/i,"").trim().toLowerCase().replace(/\s+/g,"-")}function Nt(t,e,n=[]){if(!t)return!1;try{let o=new URL(t,location.href);if(o.origin===location.origin)return!0;let i=o.host.toLowerCase();if(["fonts.googleapis.com","fonts.gstatic.com","use.typekit.net","p.typekit.net","kit.fontawesome.com","use.fontawesome.com","cdn.jsdelivr.net","unpkg.com","cdnjs.cloudflare.com","esm.sh"].some(c=>i.endsWith(c))||n.some(c=>i===c.toLowerCase()||i.endsWith("."+c.toLowerCase())))return!0;let f=(o.pathname+o.search).toLowerCase();if(/\bfont(s)?\b/.test(f)||/\.woff2?(\b|$)/.test(f)||Ft.some(c=>f.includes(c)))return!0;for(let c of e){let l=c.toLowerCase().replace(/\s+/g,"+"),m=c.toLowerCase().replace(/\s+/g,"-"),p=Pt(c);if(f.includes(l)||f.includes(m)||p&&f.includes(p))return!0}return!1}catch{return!1}}function Dt(t){let e=new Set;for(let n of t||[]){let o=String(n).split("__")[0]?.trim();o&&e.add(o)}return e}function st(t,e){return t&&t.replace(/url\(\s*(['"]?)([^)'"]+)\1\s*\)/g,(n,o,a)=>{let i=(a||"").trim();if(!i||/^data:|^blob:|^https?:|^file:|^about:/i.test(i))return n;let r=i;try{r=new URL(i,e||location.href).href}catch{}return`url("${r}")`})}var Y=/@import\s+(?:url\(\s*(['"]?)([^)"']+)\1\s*\)|(['"])([^"']+)\3)([^;]*);/g,G=4;async function Wt(t,e,n){if(!t)return t;let o=new Set;function a(f,c){try{return new URL(f,c||location.href).href}catch{return f}}async function i(f,c,l=0){if(l>G)return console.warn(`[snapDOM] @import depth exceeded (${G}) at ${c}`),f;let m="",p=0,S;for(;S=Y.exec(f);){m+=f.slice(p,S.index),p=Y.lastIndex;let b=(S[2]||S[4]||"").trim(),x=a(b,c);if(o.has(x)){console.warn(`[snapDOM] Skipping circular @import: ${x}`);continue}o.add(x);let h="";try{let s=await M(x,{as:"text",useProxy:n,silent:!0});s.ok&&typeof s.data=="string"&&(h=s.data)}catch{}h?(h=st(h,x),h=await i(h,x,l+1),m+=`
8
+ /* inlined: ${x} */
9
+ ${h}
10
+ `):m+=S[0]}return m+=f.slice(p),m}let r=st(t,e||location.href);return r=await i(r,e||location.href,0),r}var ct=/url\((["']?)([^"')]+)\1\)/g,Bt=/@font-face[^{}]*\{[^}]*\}/g;function lt(t){if(!t)return[];let e=[],n=t.split(",").map(o=>o.trim()).filter(Boolean);for(let o of n){let a=o.match(/^U\+([0-9A-Fa-f?]+)(?:-([0-9A-Fa-f?]+))?$/);if(!a)continue;let i=a[1],r=a[2],f=c=>{if(!c.includes("?"))return parseInt(c,16);let l=parseInt(c.replace(/\?/g,"0"),16),m=parseInt(c.replace(/\?/g,"F"),16);return[l,m]};if(r){let c=f(i),l=f(r),m=Array.isArray(c)?c[0]:c,p=Array.isArray(l)?l[1]:l;e.push([Math.min(m,p),Math.max(m,p)])}else{let c=f(i);Array.isArray(c)?e.push([c[0],c[1]]):e.push([c,c])}}return e}function ft(t,e){if(!e.length||!t||t.size===0)return!0;for(let n of t)for(let[o,a]of e)if(n>=o&&n<=a)return!0;return!1}function Q(t,e){let n=[];if(!t)return n;for(let o of t.matchAll(ct)){let a=(o[2]||"").trim();if(!(!a||a.startsWith("data:"))){if(!/^https?:/i.test(a))try{a=new URL(a,e||location.href).href}catch{}n.push(a)}}return n}async function ut(t,e,n=""){let o=t;for(let a of t.matchAll(ct)){let i=W(a[0]);if(!i)continue;let r=i;if(!r.startsWith("http")&&!r.startsWith("data:"))try{r=new URL(r,e||location.href).href}catch{}if(!E(r)){if(u.resource?.has(r)){u.font?.add(r),o=o.replace(a[0],`url(${u.resource.get(r)})`);continue}if(!u.font?.has(r))try{let f=await M(r,{as:"dataURL",useProxy:n,silent:!0});if(f.ok&&typeof f.data=="string"){let c=f.data;u.resource?.set(r,c),u.font?.add(r),o=o.replace(a[0],`url(${c})`)}}catch{console.warn("[snapDOM] Failed to fetch font resource:",r)}}}return o}function qt(t){if(!t.length)return null;let e=(f,c)=>t.some(([l,m])=>!(m<f||l>c)),n=e(0,255)||e(305,305),o=e(256,591)||e(7680,7935),a=e(880,1023),i=e(1024,1279);return e(7840,7929)||e(258,259)||e(416,417)||e(431,432)?"vietnamese":i?"cyrillic":a?"greek":o?"latin-ext":n?"latin":null}function at(t={}){let e=new Set((t.families||[]).map(a=>String(a).toLowerCase())),n=new Set((t.domains||[]).map(a=>String(a).toLowerCase())),o=new Set((t.subsets||[]).map(a=>String(a).toLowerCase()));return(a,i)=>{if(e.size&&e.has(a.family.toLowerCase()))return!0;if(n.size)for(let r of a.srcUrls)try{if(n.has(new URL(r).host.toLowerCase()))return!0}catch{}if(o.size){let r=qt(i);if(r&&o.has(r))return!0}return!1}}function Vt(t){if(!t)return t;let e=/@font-face[^{}]*\{[^}]*\}/gi,n=new Set,o=[];for(let i of t.match(e)||[]){let r=i.match(/font-family:\s*([^;]+);/i)?.[1]||"",f=H(r),c=(i.match(/font-weight:\s*([^;]+);/i)?.[1]||"400").trim(),l=(i.match(/font-style:\s*([^;]+);/i)?.[1]||"normal").trim(),m=(i.match(/font-stretch:\s*([^;]+);/i)?.[1]||"100%").trim(),p=(i.match(/unicode-range:\s*([^;]+);/i)?.[1]||"").trim(),S=(i.match(/src\s*:\s*([^;}]+)[;}]/i)?.[1]||"").trim(),b=Q(S,location.href),x=b.length?b.map(s=>String(s).toLowerCase()).sort().join("|"):S.toLowerCase(),h=[String(f||"").toLowerCase(),c,l,m,p.toLowerCase(),x].join("|");n.has(h)||(n.add(h),o.push(i))}if(o.length===0)return t;let a=0;return t.replace(e,()=>o[a++]||"")}function jt(t,e,n,o,a){let i=Array.from(t||[]).sort().join("|"),r=e?JSON.stringify({families:(e.families||[]).map(m=>String(m).toLowerCase()).sort(),domains:(e.domains||[]).map(m=>String(m).toLowerCase()).sort(),subsets:(e.subsets||[]).map(m=>String(m).toLowerCase()).sort()}):"",f=(n||[]).map(m=>`${(m.family||"").toLowerCase()}::${m.weight||"normal"}::${m.style||"normal"}::${m.src||""}`).sort().join("|"),c=o||"",l=(a||[]).map(m=>String(m).toLowerCase()).sort().join("|");return`fonts-embed-css::req=${i}::ex=${r}::lf=${f}::px=${c}::fd=${l}`}async function mt(t,e,n,o){let a;try{a=t.cssRules||[]}catch{return}let i=(r,f)=>{try{return new URL(r,f||location.href).href}catch{return r}};for(let r of a){if(r.type===CSSRule.IMPORT_RULE&&r.styleSheet){let f=r.href?i(r.href,e):e;if(o.depth>=G){console.warn(`[snapDOM] CSSOM import depth exceeded (${G}) at ${f}`);continue}if(f&&o.visitedSheets.has(f)){console.warn(`[snapDOM] Skipping circular CSSOM import: ${f}`);continue}f&&o.visitedSheets.add(f);let c={...o,depth:(o.depth||0)+1};await mt(r.styleSheet,f,n,c);continue}if(r.type===CSSRule.FONT_FACE_RULE){let f=(r.style.getPropertyValue("font-family")||"").trim(),c=H(f);if(!c||E(c))continue;let l=(r.style.getPropertyValue("font-weight")||"400").trim(),m=(r.style.getPropertyValue("font-style")||"normal").trim(),p=(r.style.getPropertyValue("font-stretch")||"100%").trim(),S=(r.style.getPropertyValue("src")||"").trim(),b=(r.style.getPropertyValue("unicode-range")||"").trim();if(!o.faceMatchesRequired(c,m,l,p))continue;let x=lt(b);if(!ft(o.usedCodepoints,x))continue;let h={family:c,weightSpec:l,styleSpec:m,stretchSpec:p,unicodeRange:b,srcRaw:S,srcUrls:Q(S,e||location.href),href:e||location.href};if(o.simpleExcluder&&o.simpleExcluder(h,x))continue;if(/url\(/i.test(S)){let s=await ut(S,e||location.href,o.useProxy);await n(`@font-face{font-family:${c};src:${s};font-style:${m};font-weight:${l};font-stretch:${p};${b?`unicode-range:${b};`:""}}`)}else await n(`@font-face{font-family:${c};src:${S};font-style:${m};font-weight:${l};font-stretch:${p};${b?`unicode-range:${b};`:""}}`)}}}async function dt({required:t,usedCodepoints:e,exclude:n=void 0,localFonts:o=[],useProxy:a="",fontStylesheetDomains:i=[]}={}){t instanceof Set||(t=new Set),e instanceof Set||(e=new Set);let r=new Map;for(let s of t){let[d,g,y,w]=String(s).split("__");if(!d)continue;let C=r.get(d)||[];C.push({w:parseInt(g,10),s:y,st:parseInt(w,10)}),r.set(d,C)}function f(s,d,g,y){if(!r.has(s))return!1;let w=r.get(s),C=Ot(g),k=Tt(d),R=vt(y),F=C.min!==C.max,U=C.min,T=A=>k.kind==="normal"&&A==="normal"||k.kind!=="normal"&&(A==="italic"||A==="oblique"),I=!1;for(let A of w){let $=F?A.w>=C.min&&A.w<=C.max:A.w===U,_=T(j(A.s)),O=A.st>=R.min&&A.st<=R.max;if($&&_&&O){I=!0;break}}if(I)return!0;if(!F)for(let A of w){let $=T(j(A.s)),_=A.st>=R.min&&A.st<=R.max;if(Math.abs(U-A.w)<=300&&$&&_)return!0}if(!F&&k.kind==="normal"&&w.some($=>j($.s)!=="normal"))for(let $ of w){let _=Math.abs(U-$.w)<=300,O=$.st>=R.min&&$.st<=R.max;if(_&&O)return!0}return!1}let c=at(n),l=jt(t,n,o,a,i);if(u.resource?.has(l))return u.resource.get(l);let m=Dt(t),p=[],S=Y;for(let s of document.querySelectorAll("style")){let d=s.textContent||"";for(let g of d.matchAll(S)){let y=(g[2]||g[4]||"").trim();if(!y||E(y))continue;!!document.querySelector(`link[rel="stylesheet"][href="${y}"]`)||p.push(y)}}p.length&&await Promise.all(p.map(s=>new Promise(d=>{if(document.querySelector(`link[rel="stylesheet"][href="${s}"]`))return d(null);let g=document.createElement("link");g.rel="stylesheet",g.href=s,g.setAttribute("data-snapdom","injected-import"),g.onload=()=>d(g),g.onerror=()=>d(null),document.head.appendChild(g)})));let b="",x=Array.from(document.querySelectorAll('link[rel="stylesheet"]')).filter(s=>!!s.href);for(let s of x)try{if(E(s.href))continue;let d="",g=!1;try{g=new URL(s.href,location.href).origin===location.origin}catch{}if(!g){let w=Array.isArray(i)?i:[];if(!Nt(s.href,m,w))continue}if(g){let w=Array.from(document.styleSheets).find(C=>C.href===s.href);if(w)try{let C=w.cssRules||[];d=Array.from(C).map(k=>k.cssText).join("")}catch{}}if(!d){let w=await M(s.href,{as:"text",useProxy:a});if(w?.ok&&typeof w.data=="string"&&(d=w.data),E(s.href))continue}d=await Wt(d,s.href,a);let y="";for(let w of d.match(Bt)||[]){let C=(w.match(/font-family:\s*([^;]+);/i)?.[1]||"").trim(),k=H(C);if(!k||E(k))continue;let R=(w.match(/font-weight:\s*([^;]+);/i)?.[1]||"400").trim(),F=(w.match(/font-style:\s*([^;]+);/i)?.[1]||"normal").trim(),U=(w.match(/font-stretch:\s*([^;]+);/i)?.[1]||"100%").trim(),T=(w.match(/unicode-range:\s*([^;]+);/i)?.[1]||"").trim(),I=(w.match(/src\s*:\s*([^;}]+)[;}]/i)?.[1]||"").trim(),A=Q(I,s.href);if(!f(k,F,R,U))continue;let $=lt(T);if(!ft(e,$))continue;let _={family:k,weightSpec:R,styleSpec:F,stretchSpec:U,unicodeRange:T,srcRaw:I,srcUrls:A,href:s.href};if(n&&c(_,$))continue;let O=/url\(/i.test(I)?await ut(w,s.href,a):w;y+=O}y.trim()&&(b+=y)}catch{console.warn("[snapDOM] Failed to process stylesheet:",s.href)}let h={requiredIndex:r,usedCodepoints:e,faceMatchesRequired:f,simpleExcluder:n?at(n):null,useProxy:a,visitedSheets:new Set,depth:0};for(let s of document.styleSheets)if(!(s.href&&x.some(d=>d.href===s.href)))try{let d=s.href||location.origin+"/";d&&h.visitedSheets.add(d),await mt(s,d,async g=>{b+=g},h)}catch{}try{for(let s of document.fonts||[]){if(!s||!s.family||s.status!=="loaded"||!s._snapdomSrc)continue;let d=String(s.family).replace(/^['"]+|['"]+$/g,"");if(E(d)||!r.has(d)||n?.families&&n.families.some(y=>String(y).toLowerCase()===d.toLowerCase()))continue;let g=s._snapdomSrc;if(!String(g).startsWith("data:")){if(u.resource?.has(s._snapdomSrc))g=u.resource.get(s._snapdomSrc),u.font?.add(s._snapdomSrc);else if(!u.font?.has(s._snapdomSrc))try{let y=await M(s._snapdomSrc,{as:"dataURL",useProxy:a,silent:!0});if(y.ok&&typeof y.data=="string")g=y.data,u.resource?.set(s._snapdomSrc,g),u.font?.add(s._snapdomSrc);else continue}catch{console.warn("[snapDOM] Failed to fetch dynamic font src:",s._snapdomSrc);continue}}b+=`@font-face{font-family:'${d}';src:url(${g});font-style:${s.style||"normal"};font-weight:${s.weight||"normal"};}`}}catch{}for(let s of o){if(!s||typeof s!="object")continue;let d=String(s.family||"").replace(/^['"]+|['"]+$/g,"");if(!d||E(d)||!r.has(d)||n?.families&&n.families.some(R=>String(R).toLowerCase()===d.toLowerCase()))continue;let g=s.weight!=null?String(s.weight):"normal",y=s.style!=null?String(s.style):"normal",w=s.stretchPct!=null?`${s.stretchPct}%`:"100%",C=String(s.src||""),k=C;if(!k.startsWith("data:")){if(u.resource?.has(C))k=u.resource.get(C),u.font?.add(C);else if(!u.font?.has(C))try{let R=await M(C,{as:"dataURL",useProxy:a,silent:!0});if(R.ok&&typeof R.data=="string")k=R.data,u.resource?.set(C,k),u.font?.add(C);else continue}catch{console.warn("[snapDOM] Failed to fetch localFonts src:",C);continue}}b+=`@font-face{font-family:'${d}';src:url(${k});font-style:${y};font-weight:${g};font-stretch:${w};}`}return b&&(b=Vt(b),u.resource?.set(l,b)),b}function pt(t){let e=new Set;if(!t)return e;let n=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),o=r=>{let f=Ut(r.fontFamily);if(f.length)for(let c of f){let l=(m,p,S)=>`${c}__${V(m)}__${j(p)}__${It(S)}`;e.add(l(r.fontWeight,r.fontStyle,r.fontStretch))}};o(getComputedStyle(t));let a=getComputedStyle(t,"::before");a&&a.content&&a.content!=="none"&&o(a);let i=getComputedStyle(t,"::after");for(i&&i.content&&i.content!=="none"&&o(i);n.nextNode();){let r=n.currentNode,f=getComputedStyle(r);o(f);let c=getComputedStyle(r,"::before");c&&c.content&&c.content!=="none"&&o(c);let l=getComputedStyle(r,"::after");l&&l.content&&l.content!=="none"&&o(l)}return e}function ht(t){let e=new Set,n=a=>{if(a)for(let i of a)e.add(i.codePointAt(0))},o=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_TEXT,null);for(;o.nextNode();){let a=o.currentNode;if(a.nodeType===Node.TEXT_NODE)n(a.nodeValue||"");else if(a.nodeType===Node.ELEMENT_NODE){let i=a;for(let r of["::before","::after"]){let c=getComputedStyle(i,r)?.getPropertyValue("content");if(!(!c||c==="none"))if(/^"/.test(c)||/^'/.test(c))n(c.slice(1,-1));else{let l=c.match(/\\[0-9A-Fa-f]{1,6}/g);if(l)for(let m of l)try{e.add(parseInt(m.slice(1),16))}catch{}}}}}return e}async function gt(t,e=2){try{await document.fonts.ready}catch{}let n=Array.from(t||[]).filter(Boolean);if(n.length===0)return;let o=()=>{let a=document.createElement("div");a.style.cssText="position:absolute!important;left:-9999px!important;top:0!important;opacity:0!important;pointer-events:none!important;contain:layout size style;";for(let i of n){let r=document.createElement("span");r.textContent="AaBbGg1234\xC1\xC9\xCD\xD3\xDA\xE7\xF1\u2014\u221E",r.style.fontFamily=`"${i}"`,r.style.fontWeight="700",r.style.fontStyle="italic",r.style.fontSize="32px",r.style.lineHeight="1",r.style.whiteSpace="nowrap",r.style.margin="0",r.style.padding="0",a.appendChild(r)}document.body.appendChild(a),a.offsetWidth,document.body.removeChild(a)};for(let a=0;a<Math.max(1,e);a++)o(),await new Promise(i=>requestAnimationFrame(()=>requestAnimationFrame(i)))}async function yt(t,e,n,o={}){let a=[[t,e]],i=["background-image","mask","mask-image","-webkit-mask","-webkit-mask-image","mask-source","mask-box-image-source","mask-border-source","-webkit-mask-box-image-source","border-image","border-image-source"],r=["mask-position","mask-size","mask-repeat","-webkit-mask-position","-webkit-mask-size","-webkit-mask-repeat","mask-origin","mask-clip","-webkit-mask-origin","-webkit-mask-clip","-webkit-mask-position-x","-webkit-mask-position-y"],f=["background-position","background-position-x","background-position-y","background-size","background-repeat","background-origin","background-clip","background-attachment","background-blend-mode"],c=["border-image-slice","border-image-width","border-image-outset","border-image-repeat"];for(;a.length;){let[l,m]=a.shift();if(!m)continue;let p=n.get(l)||N(l);n.has(l)||n.set(l,p);let S=(()=>{let h=p.getPropertyValue("border-image"),s=p.getPropertyValue("border-image-source");return h&&h!=="none"||s&&s!=="none"})();for(let h of f){let s=p.getPropertyValue(h);s&&m.style.setProperty(h,s)}for(let h of i){let s=p.getPropertyValue(h);if(h==="background-image"&&(!s||s==="none")){let y=p.getPropertyValue("background");y&&/url\s*\(/.test(y)&&(s=q(y).filter(w=>/url\s*\(/.test(w)).join(", ")||s)}if(!s||s==="none")continue;let d=q(s),g=await Promise.all(d.map(y=>P(y,o)));g.some(y=>y&&y!=="none"&&!/^url\(undefined/.test(y))&&m.style.setProperty(h,g.join(", "))}for(let h of r){let s=p.getPropertyValue(h);!s||s==="initial"||m.style.setProperty(h,s)}if(S)for(let h of c){let s=p.getPropertyValue(h);!s||s==="initial"||m.style.setProperty(h,s)}let b=l.shadowRoot?Array.from(l.shadowRoot.children).filter(h=>h.tagName!=="STYLE"):Array.from(l.children),x=Array.from(m.children).filter(h=>!(h.dataset?.snapdomPseudo||h.tagName==="STYLE"&&h.dataset?.sd));for(let h=0;h<Math.min(b.length,x.length);h++)a.push([b[h],x[h]])}}async function Me(t=document,e={}){let{embedFonts:n=!0,useProxy:o=""}=e,a=e.cache??e.cacheOpt??"full";J(a);try{await document.fonts?.ready}catch{}try{K()}catch{}u.session=u.session||{},u.session.styleCache||(u.session.styleCache=new WeakMap),u.image=u.image||new L(100),u.background=u.background||new L(100);try{await yt(t,void 0,u.session.styleCache,{useProxy:o})}catch{}let i=[],r=[];try{if(t&&t.nodeType===1){let c=t.querySelectorAll?Array.from(t.querySelectorAll("*")):[];r=[t,...c],i=[],t.tagName==="IMG"&&t.getAttribute("src")&&i.push(t),i.push(...Array.from(t.querySelectorAll?.("img[src]")||[]))}else t?.querySelectorAll&&(i=Array.from(t.querySelectorAll("img[src]")),r=Array.from(t.querySelectorAll("*")))}catch{}let f=[];for(let c of i){let l=c?.currentSrc||c?.src;if(l&&!u.image.has(l)){let m=Promise.resolve().then(async()=>{let p=await M(l,{as:"dataURL",useProxy:o});p?.ok&&typeof p.data=="string"&&u.image.set(l,p.data)}).catch(()=>{});f.push(m)}}for(let c of r){let l="";try{l=c?.style?.backgroundImage||"",(!l||l==="none")&&(l=N(c).backgroundImage)}catch{}if(l&&l!=="none"){let m=l.match(/url\((?:[^()"']+|"(?:[^"]*)"|'(?:[^']*)')\)/gi)||[];for(let p of m){let S=Promise.resolve().then(()=>P(p,{...e,useProxy:o})).catch(()=>{});f.push(S)}}}if(n)try{let c=pt(t),l=ht(t);if(typeof D=="function"?D():!!D){let p=new Set(Array.from(c).map(S=>String(S).split("__")[0]).filter(Boolean));await gt(p,3)}await dt({required:c,usedCodepoints:l,exclude:e.excludeFonts,localFonts:e.localFonts,useProxy:e.useProxy??o,fontStylesheetDomains:e.fontStylesheetDomains})}catch{}await Promise.allSettled(f)}export{Me as preCache};