leesto-connect 0.8.1 → 0.9.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
@@ -4,14 +4,18 @@ Drop-in connector for the **Leesto / Livery** test shell. Add it to the app you
4
4
  want testers to review so Livery can take **screenshots** and record **rrweb
5
5
  sessions** of your pages.
6
6
 
7
- - **Keyless** — carries no secret; the project binding lives in the Livery test
8
- session, not in your app. Safe to ship publicly.
7
+ - **No secret** — the only value you paste is the public key of your Leesto
8
+ workspace (`data-leesto-key`). It grants nothing; it says which workspace may
9
+ capture your app. Safe to ship publicly.
9
10
  - **No-op unless embedded** — does nothing when your page isn't loaded inside the
10
11
  Livery shell, so it's harmless on production.
11
- - **Lazy** — rrweb / screenshot code load only when a recording or capture
12
- actually starts, so a normal page load only fetches a ~7.2 kB (gzip) entry.
13
- Inside a consented Livery test session, rrweb loads at connect time and keeps
14
- the last ~2 minutes in memory; nothing leaves the page until Livery asks.
12
+ - **Lazy** — a normal page load only fetches one file, the entry: about 14 kB
13
+ gzip (35 kB minified). Everything else is a separate chunk, fetched on first
14
+ use: rrweb when a recording starts (56 kB gzip), the screenshot code on the
15
+ first capture (11 kB), auto-login when the Lab asks for it (6 kB), the element
16
+ picker when a tester points at the page (2 kB). Inside a consented Livery test
17
+ session, rrweb loads at connect time and keeps the last ~2 minutes in memory;
18
+ nothing leaves the page until Livery asks.
15
19
  - **Origin-locked** — the connector only answers a shell on its allowlist, so a
16
20
  third-party page that frames your app cannot drive capture or recording.
17
21
 
@@ -20,17 +24,26 @@ sessions** of your pages.
20
24
  ```html
21
25
  <script type="module"
22
26
  src="https://unpkg.com/leesto-connect@0/dist/leesto-connect.js"
23
- data-leesto-connect></script>
27
+ data-leesto-connect
28
+ data-leesto-key="lk_…"></script>
24
29
  ```
25
30
 
31
+ Copy the tag from your project's connector settings in Leesto: it already
32
+ carries your workspace key.
33
+
26
34
  `@0` pins the **major**: patches and minors reach you automatically, a breaking
27
35
  release needs a new tag. unpkg resolves the range by redirecting to the exact
28
36
  version, so the entry and its lazy chunks always come from the same build
29
37
  (avoid CDNs that serve ranges without redirecting). To freeze a build instead,
30
- pin it exactly: `https://unpkg.com/leesto-connect@0.8.1/dist/leesto-connect.js`.
38
+ pin it exactly: `https://unpkg.com/leesto-connect@0.9.0/dist/leesto-connect.js`.
31
39
 
32
40
  Options via data attributes:
33
41
 
42
+ - `data-leesto-key="lk_…"` — public key of your Leesto workspace (from 0.9.0).
43
+ With it, screenshots, session replay and diagnostics are only served to that
44
+ workspace's projects. Several workspaces test the same app: list their keys,
45
+ comma-separated. Without it the connector serves any Leesto project, as
46
+ before 0.9.0. See [Security model](#security-model).
34
47
  - `data-highlight-color="#6B8E23"` — outline color of the element picker.
35
48
  - `data-leesto-manual` — skip auto-init; call `window.LeestoConnect.connect()` yourself.
36
49
  - `data-shell-origin="https://qa.acme.test"` — **self-hosted shell only.**
@@ -59,16 +72,47 @@ saved entries don't open over the Lab's list. Your value is kept in
59
72
  `data-leesto-autocomplete` and restored as soon as the Lab lets go. Nothing else is
60
73
  added to your page.
61
74
 
75
+ ## Keyboard: back to the Lab
76
+
77
+ While the keyboard focus is inside your app, the Lab receives no key at all: the
78
+ browser delivers keystrokes to your page only. A keyboard user would have to tab
79
+ through your whole app to reach the Lab's sidebar. From 0.9.0 the connector
80
+ gives them a way back, the Lab's own "open the sidebar" shortcut:
81
+
82
+ - **⌘B** on macOS, **Ctrl+B** elsewhere. The Lab opens its sidebar if needed and
83
+ puts the focus in it.
84
+ - It is the only chord the connector looks for. Each keydown is compared to it
85
+ and dropped; nothing is stored, counted or sent. The message to the Lab
86
+ (`leesto:shell-focus`) carries no content: no key, no target, no text.
87
+ - No key listener exists until the Lab asks for the relay
88
+ (`leesto:shell-focus-watch`, sent to connectors that announce the
89
+ `shell-focus` capability), and it is removed on `leesto:shell-focus-unwatch`
90
+ or when the connector disconnects. Nothing is listened to outside an
91
+ authorised Leesto shell, nor for a Lab of another workspace when you declare
92
+ `data-leesto-key`.
93
+ - Your app comes first. The connector stays out when your own code handled the
94
+ chord (it called `preventDefault()`, like a rich-text editor binding ⌘B to
95
+ bold) and when the focus is in a `contenteditable` area, where the browser
96
+ itself makes the selection bold. In a plain input or textarea the chord goes
97
+ back to the Lab. When the connector relays the chord it calls
98
+ `preventDefault()` on it, so the browser's own shortcut (Firefox opens its
99
+ bookmarks sidebar on Ctrl+B) does not fire as well.
100
+
62
101
  ## Install (React / bundled app)
63
102
 
64
103
  If your app bundles its own dependencies, import the package once in your client
65
104
  entry — before mounting React, so startup errors are captured too. The import
66
- auto-connects; there is no API to call.
105
+ auto-connects. Call `connect` right after it to declare your workspace key (it
106
+ replaces the automatic connection, it does not add a second one):
67
107
 
68
108
  ```ts
69
- import "leesto-connect";
109
+ import { connect } from "leesto-connect";
110
+
111
+ connect({ key: "lk_…" });
70
112
  ```
71
113
 
114
+ Without a key, the import alone is enough: `import "leesto-connect";`.
115
+
72
116
  ## Privacy: what the replay captures
73
117
 
74
118
  Masking happens **in the browser, at capture time**, before anything leaves the
@@ -125,13 +169,29 @@ mobile), nor when your page is framed by any other site.
125
169
 
126
170
  ## Security model
127
171
 
128
- The connector is keyless, so it does **not** authenticate the shell — it
172
+ The connector holds no secret, so it does **not** authenticate the shell — it
129
173
  authorizes it *by origin*. It answers only origins on its allowlist (the Leesto
130
174
  shell by default, or whatever `data-shell-origin` declares) and never posts to a
131
175
  wildcard target. That check is what keeps a hostile page that manages to frame
132
176
  your app from requesting screenshots, starting a recording, or reading the
133
177
  diagnostic buffers.
134
178
 
179
+ The Leesto shell has one origin for every workspace, so the origin check alone
180
+ does not say *which* workspace is looking. That is what the **workspace key**
181
+ is for. When your app declares `data-leesto-key`:
182
+
183
+ - the shell tells the connector which workspace owns the project being tested
184
+ (in the iframe name, which only the shell sets, never in your app's URL);
185
+ - if that workspace is not one you declared, the connector arms nothing and
186
+ refuses every request: no session replay buffer, no diagnostics, no
187
+ screenshot, no element picker, no auto-login. It only keeps answering the
188
+ handshake, so the shell can say why;
189
+ - the shell, on its side, refuses to display your app in that project.
190
+
191
+ A declaration that holds no readable key (a typo) refuses everyone rather than
192
+ silently opening up. An app that declares no key is served as before 0.9.0: any
193
+ Leesto workspace that frames it can capture it, so declare your key.
194
+
135
195
  `frame-ancestors` below is still worth setting: it is defence in depth, and the
136
196
  only thing that stops an unrelated site from framing your app at all.
137
197
 
@@ -147,10 +207,12 @@ and remove any restrictive `X-Frame-Options`.
147
207
 
148
208
  ## Releasing
149
209
 
150
- `dist/` is built from `@leesto/react` (`build:connect`). To publish a new version:
210
+ `dist/` is built from `src/` (`bun run build`). Publishing is done by CI, never by a manual
211
+ `npm publish`: bump `version` in `package.json`, merge, then push the tag that matches it.
151
212
 
152
213
  ```sh
153
- cd packages/leesto-connect
154
- npm version <patch|minor|major>
155
- npm publish # prepublishOnly rebuilds dist/ from @leesto/react
214
+ git tag leesto-connect-v0.9.0 && git push origin leesto-connect-v0.9.0
156
215
  ```
216
+
217
+ Deploy the Leesto shell first. Sites that load `leesto-connect@0` follow the publication within
218
+ minutes, and an app that declares a workspace key refuses a shell that does not announce one.
@@ -0,0 +1,15 @@
1
+ function e(e,t){return e[13]=1,e[14]=t>>8,e[15]=t&255,e[16]=t>>8,e[17]=t&255,e}var t;function n(){let e=/* @__PURE__ */ new Int32Array(256);for(let t=0;t<256;t++){let n=t;for(let e=0;e<8;e++)n=n&1?3988292384^n>>>1:n>>>1;e[t]=n}return e}function r(e){let r=-1;t||(t=n());for(let n=0;n<e.length;n++)r=t[(r^e[n])&255]^r>>>8;return r^-1}function i(e){let t=e.length-1;for(let n=t;n>=4;n--)if(e[n-4]===9&&e[n-3]===112&&e[n-2]===72&&e[n-1]===89&&e[n]===115)return n-3;return 0}function a(e,t,n=!1){let a=/* @__PURE__ */ new Uint8Array(13);t*=39.3701,a[0]=112,a[1]=72,a[2]=89,a[3]=115,a[4]=t>>>24,a[5]=t>>>16,a[6]=t>>>8,a[7]=t&255,a[8]=a[4],a[9]=a[5],a[10]=a[6],a[11]=a[7],a[12]=1;let o=r(a),s=/* @__PURE__ */ new Uint8Array(4);if(s[0]=o>>>24,s[1]=o>>>16,s[2]=o>>>8,s[3]=o&255,n){let t=i(e);return e.set(a,t),e.set(s,t+13),e}{let t=/* @__PURE__ */ new Uint8Array(4);t[0]=0,t[1]=0,t[2]=0,t[3]=9;let n=/* @__PURE__ */ new Uint8Array(54);return n.set(e,0),n.set(t,33),n.set(a,37),n.set(s,50),n}}function o(e){let t=e.indexOf(`AAlwSFlz`);return t===-1&&(t=e.indexOf(`AAAJcEhZ`)),t===-1&&(t=e.indexOf(`AAAACXBI`)),t}var s=`[modern-screenshot]`,c=typeof window<`u`,l=c&&`Worker`in window,u=c&&`atob`in window,d=c&&`btoa`in window,f=c?window.navigator?.userAgent:``,p=f.includes(`Chrome`),m=f.includes(`AppleWebKit`)&&!p,h=f.includes(`Firefox`),g=e=>e&&`__CONTEXT__`in e,_=e=>e.constructor.name===`CSSFontFaceRule`,v=e=>e.constructor.name===`CSSImportRule`,y=e=>e.constructor.name===`CSSLayerBlockRule`,b=e=>e.nodeType===1,x=e=>typeof e.className==`object`,ee=e=>e.tagName===`image`,te=e=>e.tagName===`use`,S=e=>b(e)&&e.style!==void 0&&!x(e),ne=e=>e.nodeType===8,re=e=>e.nodeType===3,C=e=>e.tagName===`IMG`,w=e=>e.tagName===`VIDEO`,ie=e=>e.tagName===`CANVAS`,ae=e=>e.tagName===`TEXTAREA`,oe=e=>e.tagName===`INPUT`,se=e=>e.tagName===`STYLE`,ce=e=>e.tagName===`SCRIPT`,le=e=>e.tagName===`SELECT`,ue=e=>e.tagName===`SLOT`,de=e=>e.tagName===`IFRAME`,fe=(...e)=>console.warn(s,...e);function pe(e){let t=e?.createElement?.(`canvas`);return t&&(t.height=t.width=1),!!t&&`toDataURL`in t&&!!t.toDataURL(`image/webp`).includes(`image/webp`)}var T=e=>e.startsWith(`data:`);function E(e,t){if(e.match(/^[a-z]+:\/\//i))return e;if(c&&e.match(/^\/\//))return window.location.protocol+e;if(e.match(/^[a-z]+:/i)||!c)return e;let n=D().implementation.createHTMLDocument(),r=n.createElement(`base`),i=n.createElement(`a`);return n.head.appendChild(r),n.body.appendChild(i),t&&(r.href=t),i.href=e,i.href}function D(e){return(e&&b(e)?e?.ownerDocument:e)??window.document}var O=`http://www.w3.org/2000/svg`;function me(e,t,n){let r=D(n).createElementNS(O,`svg`);return r.setAttributeNS(null,`width`,e.toString()),r.setAttributeNS(null,`height`,t.toString()),r.setAttributeNS(null,`viewBox`,`0 0 ${e} ${t}`),r}function he(e,t){let n=new XMLSerializer().serializeToString(e);return t&&(n=n.replace(/[\u0000-\u0008\v\f\u000E-\u001F\uD800-\uDFFF\uFFFE\uFFFF]/gu,``)),`data:image/svg+xml;charset=utf-8,${encodeURIComponent(n)}`}function ge(e,t){return new Promise((n,r)=>{let i=new FileReader;i.onload=()=>n(i.result),i.onerror=()=>r(i.error),i.onabort=()=>r(/* @__PURE__ */ Error(`Failed read blob to ${t}`)),t===`dataUrl`?i.readAsDataURL(e):t===`arrayBuffer`&&i.readAsArrayBuffer(e)})}var _e=e=>ge(e,`dataUrl`);function k(e,t){let n=D(t).createElement(`img`);return n.decoding=`sync`,n.loading=`eager`,n.src=e,n}function A(e,t){return new Promise(n=>{let{timeout:r,ownerDocument:i,onError:a,onWarn:o}=t??{},s=typeof e==`string`?k(e,D(i)):e,c=null,l=null;function u(){n(s),c&&clearTimeout(c),l?.()}if(r&&(c=setTimeout(u,r)),w(s)){let e=s.currentSrc||s.src;if(!e)return s.poster?A(s.poster,t).then(n):u();if(s.readyState>=2)return u();let r=u,i=t=>{o?.(`Failed video load`,e,t),a?.(t),u()};l=()=>{s.removeEventListener(`loadeddata`,r),s.removeEventListener(`error`,i)},s.addEventListener(`loadeddata`,r,{once:!0}),s.addEventListener(`error`,i,{once:!0})}else{let e=ee(s)?s.href.baseVal:s.currentSrc||s.src;if(!e)return u();let t=async()=>{if(C(s)&&`decode`in s)try{await s.decode()}catch(t){o?.(`Failed to decode image, trying to render anyway`,s.dataset.originalSrc||e,t)}u()},n=t=>{o?.(`Failed image load`,s.dataset.originalSrc||e,t),u()};if(C(s)&&s.complete)return t();l=()=>{s.removeEventListener(`load`,t),s.removeEventListener(`error`,n)},s.addEventListener(`load`,t,{once:!0}),s.addEventListener(`error`,n,{once:!0})}})}async function ve(e,t){S(e)&&(C(e)||w(e)?await A(e,t):await Promise.all([`img`,`video`].flatMap(n=>Array.from(e.querySelectorAll(n)).map(e=>A(e,t)))))}var ye=/* @__PURE__ */ function(){let e=0,t=()=>`0000${(Math.random()*36**4|0).toString(36)}`.slice(-4);return()=>(e+=1,`u${t()}${e}`)}();function j(e){return e?.split(`,`).map(e=>e.trim().replace(/"|'/g,``).toLowerCase()).filter(Boolean)}var M=0;function be(e){let t=`${s}[#${M}]`;return M++,{time:n=>e&&console.time(`${t} ${n}`),timeEnd:n=>e&&console.timeEnd(`${t} ${n}`),warn:(...t)=>e&&fe(...t)}}function xe(e){return{cache:e?`no-cache`:`force-cache`}}async function N(e,t){return g(e)?e:Se(e,{...t,autoDestruct:!0})}async function Se(e,t){let{scale:n=1,workerUrl:r,workerNumber:i=1}=t||{},a=!!t?.debug,o=t?.features??!0,s=e.ownerDocument??(c?window.document:void 0),u=e.ownerDocument?.defaultView??(c?window:void 0),d=/* @__PURE__ */ new Map,f={width:0,height:0,quality:1,type:`image/png`,scale:n,backgroundColor:null,style:null,filter:null,maximumCanvasSize:0,timeout:3e4,progress:null,debug:a,fetch:{requestInit:xe(t?.fetch?.bypassingCache),placeholderImage:`data:image/png;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7`,bypassingCache:!1,...t?.fetch},fetchFn:null,font:{},drawImageInterval:100,workerUrl:null,workerNumber:i,onCloneEachNode:null,onCloneNode:null,onEmbedNode:null,onCreateForeignObjectSvg:null,includeStyleProperties:null,autoDestruct:!1,...t,__CONTEXT__:!0,log:be(a),node:e,ownerDocument:s,ownerWindow:u,dpi:n===1?null:96*n,svgStyleElement:P(s),svgDefsElement:s?.createElementNS(O,`defs`),svgStyles:/* @__PURE__ */ new Map,defaultComputedStyles:/* @__PURE__ */ new Map,workers:[...Array.from({length:l&&r&&i?i:0})].map(()=>{try{let e=new Worker(r);return e.onmessage=async e=>{let{url:t,result:n}=e.data;n?d.get(t)?.resolve?.(n):d.get(t)?.reject?.(/* @__PURE__ */ Error(`Error receiving message from worker: ${t}`))},e.onmessageerror=e=>{let{url:t}=e.data;d.get(t)?.reject?.(/* @__PURE__ */ Error(`Error receiving message from worker: ${t}`))},e}catch(e){return f.log.warn(`Failed to new Worker`,e),null}}).filter(Boolean),fontFamilies:/* @__PURE__ */ new Map,fontCssTexts:/* @__PURE__ */ new Map,acceptOfImage:`${[pe(s)&&`image/webp`,`image/svg+xml`,`image/*`,`*/*`].filter(Boolean).join(`,`)};q=0.8`,requests:d,drawImageCount:0,tasks:[],features:o,isEnable:e=>e===`restoreScrollPosition`?typeof o==`boolean`?!1:o[e]??!1:typeof o==`boolean`?o:o[e]??!0,shadowRoots:[]};f.log.time(`wait until load`),await ve(e,{timeout:f.timeout,onWarn:f.log.warn}),f.log.timeEnd(`wait until load`);let{width:p,height:m}=Ce(e,f);return f.width=p,f.height=m,f}function P(e){if(!e)return;let t=e.createElement(`style`),n=t.ownerDocument.createTextNode(`
2
+ .______background-clip--text {
3
+ background-clip: text;
4
+ -webkit-background-clip: text;
5
+ }
6
+ `);return t.appendChild(n),t}function Ce(e,t){let{width:n,height:r}=t;if(b(e)&&(!n||!r)){let t=e.getBoundingClientRect();n=n||t.width||Number(e.getAttribute(`width`))||0,r=r||t.height||Number(e.getAttribute(`height`))||0}return{width:n,height:r}}async function we(e,t){let{log:n,timeout:r,drawImageCount:i,drawImageInterval:a}=t;n.time(`image to canvas`);let o=await A(e,{timeout:r,onWarn:t.log.warn}),{canvas:s,context2d:c}=Te(e.ownerDocument,t),l=()=>{try{c?.drawImage(o,0,0,s.width,s.height)}catch(e){t.log.warn(`Failed to drawImage`,e)}};if(l(),t.isEnable(`fixSvgXmlDecode`))for(let e=0;e<i;e++)await new Promise(t=>{setTimeout(()=>{c?.clearRect(0,0,s.width,s.height),l(),t()},e+a)});return t.drawImageCount=0,n.timeEnd(`image to canvas`),s}function Te(e,t){let{width:n,height:r,scale:i,backgroundColor:a,maximumCanvasSize:o}=t,s=e.createElement(`canvas`);s.width=Math.floor(n*i),s.height=Math.floor(r*i),s.style.width=`${n}px`,s.style.height=`${r}px`,o&&(s.width>o||s.height>o)&&(s.width>o&&s.height>o?s.width>s.height?(s.height*=o/s.width,s.width=o):(s.width*=o/s.height,s.height=o):s.width>o?(s.height*=o/s.width,s.width=o):(s.width*=o/s.height,s.height=o));let c=s.getContext(`2d`);return c&&a&&(c.fillStyle=a,c.fillRect(0,0,s.width,s.height)),{canvas:s,context2d:c}}function F(e,t){if(e.ownerDocument)try{let t=e.toDataURL();if(t!==`data:,`)return k(t,e.ownerDocument)}catch(e){t.log.warn(`Failed to clone canvas`,e)}let n=e.cloneNode(!1),r=e.getContext(`2d`),i=n.getContext(`2d`);try{return r&&i&&i.putImageData(r.getImageData(0,0,e.width,e.height),0,0),n}catch(e){t.log.warn(`Failed to clone canvas`,e)}return n}function Ee(e,t){try{if(e?.contentDocument?.documentElement)return V(e.contentDocument.documentElement,t)}catch(e){t.log.warn(`Failed to clone iframe`,e)}return e.cloneNode(!1)}function De(e){let t=e.cloneNode(!1);return e.currentSrc&&e.currentSrc!==e.src&&(t.src=e.currentSrc,t.srcset=``),t.loading===`lazy`&&(t.loading=`eager`),t}async function Oe(e,t){if(e.ownerDocument&&!e.currentSrc&&e.poster)return k(e.poster,e.ownerDocument);let n=e.cloneNode(!1);n.crossOrigin=`anonymous`,e.currentSrc&&e.currentSrc!==e.src&&(n.src=e.currentSrc);let r=n.ownerDocument;if(r){let i=!0;if(await A(n,{onError:()=>i=!1,onWarn:t.log.warn}),!i)return e.poster?k(e.poster,e.ownerDocument):n;n.currentTime=e.currentTime,await new Promise(e=>{n.addEventListener(`seeked`,e,{once:!0})});let a=r.createElement(`canvas`);a.width=e.offsetWidth,a.height=e.offsetHeight;try{let e=a.getContext(`2d`);e&&e.drawImage(n,0,0,a.width,a.height)}catch(r){return t.log.warn(`Failed to clone video`,r),e.poster?k(e.poster,e.ownerDocument):n}return F(a,t)}return n}function ke(e,t){return ie(e)?F(e,t):de(e)?Ee(e,t):C(e)?De(e):w(e)?Oe(e,t):e.cloneNode(!1)}function Ae(e){let t=e.sandbox;if(!t){let{ownerDocument:n}=e;try{n&&(t=n.createElement(`iframe`),t.id=`__SANDBOX__${ye()}`,t.width=`0`,t.height=`0`,t.style.visibility=`hidden`,t.style.position=`fixed`,n.body.appendChild(t),t.srcdoc=`<!DOCTYPE html><meta charset="UTF-8"><title></title><body>`,e.sandbox=t)}catch(t){e.log.warn(`Failed to getSandBox`,t)}}return t}var je=[`width`,`height`,`-webkit-text-fill-color`],Me=[`stroke`,`fill`];function I(e,t,n){let{defaultComputedStyles:r}=n,i=e.nodeName.toLowerCase(),a=x(e)&&i!==`svg`,o=a?Me.map(t=>[t,e.getAttribute(t)]).filter(([,e])=>e!==null):[],s=[a&&`svg`,i,o.map((e,t)=>`${e}=${t}`).join(`,`),t].filter(Boolean).join(`:`);if(r.has(s))return r.get(s);let c=Ae(n)?.contentWindow;if(!c)return/* @__PURE__ */ new Map;let l=c?.document,u,d;a?(u=l.createElementNS(O,`svg`),d=u.ownerDocument.createElementNS(u.namespaceURI,i),o.forEach(([e,t])=>{d.setAttributeNS(null,e,t)}),u.appendChild(d)):u=d=l.createElement(i),d.textContent=` `,l.body.appendChild(u);let f=c.getComputedStyle(d,t),p=/* @__PURE__ */ new Map;for(let e=f.length,t=0;t<e;t++){let e=f.item(t);je.includes(e)||p.set(e,f.getPropertyValue(e))}return l.body.removeChild(u),r.set(s,p),p}function L(e,t,n){let r=/* @__PURE__ */ new Map,i=[],a=/* @__PURE__ */ new Map;if(n)for(let e of n)o(e);else for(let t=e.length,n=0;n<t;n++)o(e.item(n));for(let e=i.length,t=0;t<e;t++)a.get(i[t])?.forEach((e,t)=>r.set(t,e));function o(n){let o=e.getPropertyValue(n),s=e.getPropertyPriority(n),c=n.lastIndexOf(`-`),l=c>-1?n.substring(0,c):void 0;if(l){let e=a.get(l);e||(e=/* @__PURE__ */ new Map,a.set(l,e)),e.set(n,[o,s])}(t.get(n)!==o||s)&&(l?i.push(l):r.set(n,[o,s]))}return r}function Ne(e,t,n,r){let{ownerWindow:i,includeStyleProperties:a,currentParentNodeStyle:o}=r,s=t.style,c=i.getComputedStyle(e),l=I(e,null,r);o?.forEach((e,t)=>{l.delete(t)});let u=L(c,l,a);u.delete(`transition-property`),u.delete(`all`),u.delete(`d`),u.delete(`content`),n&&(u.delete(`position`),u.delete(`margin-top`),u.delete(`margin-right`),u.delete(`margin-bottom`),u.delete(`margin-left`),u.delete(`margin-block-start`),u.delete(`margin-block-end`),u.delete(`margin-inline-start`),u.delete(`margin-inline-end`),u.set(`box-sizing`,[`border-box`,``])),u.get(`background-clip`)?.[0]===`text`&&t.classList.add(`______background-clip--text`),p&&(u.has(`font-kerning`)||u.set(`font-kerning`,[`normal`,``]),(u.get(`overflow-x`)?.[0]===`hidden`||u.get(`overflow-y`)?.[0]===`hidden`)&&u.get(`text-overflow`)?.[0]===`ellipsis`&&e.scrollWidth===e.clientWidth&&u.set(`text-overflow`,[`clip`,``]));for(let e=s.length,t=0;t<e;t++)s.removeProperty(s.item(t));return u.forEach(([e,t],n)=>{s.setProperty(n,e,t)}),u}function Pe(e,t){(ae(e)||oe(e)||le(e))&&t.setAttribute(`value`,e.value)}var Fe=[`::before`,`::after`],Ie=[`::-webkit-scrollbar`,`::-webkit-scrollbar-button`,`::-webkit-scrollbar-thumb`,`::-webkit-scrollbar-track`,`::-webkit-scrollbar-track-piece`,`::-webkit-scrollbar-corner`,`::-webkit-resizer`];function Le(e,t,n,r,i){let{ownerWindow:a,svgStyleElement:o,svgStyles:s,currentNodeStyle:c}=r;if(!o||!a)return;function l(n){let o=a.getComputedStyle(e,n),l=o.getPropertyValue(`content`);if(!l||l===`none`)return;i?.(l),l=l.replace(/(')|(")|(counter\(.+\))/g,``);let u=[ye()],d=I(e,n,r);c?.forEach((e,t)=>{d.delete(t)});let f=L(o,d,r.includeStyleProperties);f.delete(`content`),f.delete(`-webkit-locale`),f.get(`background-clip`)?.[0]===`text`&&t.classList.add(`______background-clip--text`);let p=[`content: '${l}';`];if(f.forEach(([e,t],n)=>{p.push(`${n}: ${e}${t?` !important`:``};`)}),p.length===1)return;try{t.className=[t.className,...u].join(` `)}catch(e){r.log.warn(`Failed to copyPseudoClass`,e);return}let m=p.join(`
7
+ `),h=s.get(m);h||(h=[],s.set(m,h)),h.push(`.${u[0]}${n}`)}Fe.forEach(l),n&&Ie.forEach(l)}var R=/* @__PURE__ */ new Set([`symbol`]);async function z(e,t,n,r,i){if(b(n)&&(se(n)||ce(n))||r.filter&&!r.filter(n))return;r.currentParentNodeStyle=R.has(t.nodeName)||R.has(n.nodeName)?void 0:r.currentNodeStyle;let a=await V(n,r,!1,i);r.isEnable(`restoreScrollPosition`)&&Re(e,a),t.appendChild(a)}async function B(e,t,n,r){let i=e.firstChild;b(e)&&e.shadowRoot&&(i=e.shadowRoot?.firstChild,n.shadowRoots.push(e.shadowRoot));for(let a=i;a;a=a.nextSibling)if(!ne(a)){if(b(a)&&ue(a)&&typeof a.assignedNodes==`function`){let i=a.assignedNodes();for(let a=0;a<i.length;a++)await z(e,t,i[a],n,r)}else await z(e,t,a,n,r)}}function Re(e,t){if(!S(e)||!S(t))return;let{scrollTop:n,scrollLeft:r}=e;if(!n&&!r)return;let{transform:i}=t.style,a=new DOMMatrix(i),{a:o,b:s,c,d:l}=a;a.a=1,a.b=0,a.c=0,a.d=1,a.translateSelf(-r,-n),a.a=o,a.b=s,a.c=c,a.d=l,t.style.transform=a.toString()}function ze(e,t){let{backgroundColor:n,width:r,height:i,style:a}=t,o=e.style;if(n&&o.setProperty(`background-color`,n,`important`),r&&o.setProperty(`width`,`${r}px`,`important`),i&&o.setProperty(`height`,`${i}px`,`important`),a)for(let e in a)o[e]=a[e]}var Be=/^[\w-:]+$/;async function V(e,t,n=!1,r){let{ownerDocument:i,ownerWindow:a,fontFamilies:o,onCloneEachNode:s}=t;if(i&&re(e))return r&&/\S/.test(e.data)&&r(e.data),i.createTextNode(e.data);if(i&&a&&b(e)&&(S(e)||x(e))){let r=await ke(e,t);if(t.isEnable(`removeAbnormalAttributes`)){let e=r.getAttributeNames();for(let t=e.length,n=0;n<t;n++){let t=e[n];Be.test(t)||r.removeAttribute(t)}}let i=t.currentNodeStyle=Ne(e,r,n,t);n&&ze(r,t);let a=!1;if(t.isEnable(`copyScrollbar`)){let t=[i.get(`overflow-x`)?.[0],i.get(`overflow-y`)?.[0]];a=t.includes(`scroll`)||(t.includes(`auto`)||t.includes(`overlay`))&&(e.scrollHeight>e.clientHeight||e.scrollWidth>e.clientWidth)}let c=i.get(`text-transform`)?.[0],l=j(i.get(`font-family`)?.[0]),u=l?e=>{c===`uppercase`?e=e.toUpperCase():c===`lowercase`?e=e.toLowerCase():c===`capitalize`&&(e=e[0].toUpperCase()+e.substring(1)),l.forEach(t=>{let n=o.get(t);n||o.set(t,n=/* @__PURE__ */ new Set),e.split(``).forEach(e=>n.add(e))})}:void 0;return Le(e,r,a,t,u),Pe(e,r),w(e)||await B(e,r,t,u),await s?.(r),r}let c=e.cloneNode(!1);return await B(e,c,t),await s?.(c),c}function Ve(e){if(e.ownerDocument=void 0,e.ownerWindow=void 0,e.svgStyleElement=void 0,e.svgDefsElement=void 0,e.svgStyles.clear(),e.defaultComputedStyles.clear(),e.sandbox){try{e.sandbox.remove()}catch(t){e.log.warn(`Failed to destroyContext`,t)}e.sandbox=void 0}e.workers=[],e.fontFamilies.clear(),e.fontCssTexts.clear(),e.requests.clear(),e.tasks=[],e.shadowRoots=[]}function He(e){let{url:t,timeout:n,responseType:r,...i}=e,a=new AbortController,o=n?setTimeout(()=>a.abort(),n):void 0;return fetch(t,{signal:a.signal,...i}).then(e=>{if(!e.ok)throw Error(`Failed fetch, not 2xx response`,{cause:e});switch(r){case`arrayBuffer`:return e.arrayBuffer();case`dataUrl`:return e.blob().then(_e);default:return e.text()}}).finally(()=>clearTimeout(o))}function H(e,t){let{url:n,requestType:r=`text`,responseType:i=`text`,imageDom:a}=t,o=n,{timeout:s,acceptOfImage:c,requests:l,fetchFn:u,fetch:{requestInit:d,bypassingCache:f,placeholderImage:p},font:g,workers:_,fontFamilies:v}=e;r===`image`&&(m||h)&&e.drawImageCount++;let y=l.get(n);if(!y){f&&f instanceof RegExp&&f.test(o)&&(o+=(/\?/.test(o)?`&`:`?`)+(/* @__PURE__ */ new Date()).getTime());let t=r.startsWith(`font`)&&g&&g.minify,h=/* @__PURE__ */ new Set;t&&r.split(`;`)[1].split(`,`).forEach(e=>{v.has(e)&&v.get(e).forEach(e=>h.add(e))});let b=t&&h.size,x={url:o,timeout:s,responseType:b?`arrayBuffer`:i,headers:r===`image`?{accept:c}:void 0,...d};y={type:r,resolve:void 0,reject:void 0,response:null},y.response=(async()=>{if(u&&r===`image`){let e=await u(n);if(e)return e}return!m&&n.startsWith(`http`)&&_.length?new Promise((e,t)=>{_[l.size&_.length-1].postMessage({rawUrl:n,...x}),y.resolve=e,y.reject=t}):He(x)})().catch(t=>{if(l.delete(n),r===`image`&&p)return e.log.warn(`Failed to fetch image base64, trying to use placeholder image`,o),typeof p==`string`?p:p(a);throw t}),l.set(n,y)}return y.response}async function U(e,t,n,r){if(!W(e))return e;for(let[i,a]of Ue(e,t))try{let t=await H(n,{url:a,requestType:r?`image`:`text`,responseType:`dataUrl`});e=e.replace(We(i),`$1${t}$3`)}catch(e){n.log.warn(`Failed to fetch css data url`,i,e)}return e}function W(e){return/url\((['"]?)([^'"]+?)\1\)/.test(e)}var G=/url\((['"]?)([^'"]+?)\1\)/g;function Ue(e,t){let n=[];return e.replace(G,(e,r,i)=>(n.push([i,E(i,t)]),e)),n.filter(([e])=>!T(e))}function We(e){let t=e.replace(/([.*+?^${}()|\[\]\/\\])/g,`\\$1`);return RegExp(`(url\\(['"]?)(${t})(['"]?\\))`,`g`)}var Ge=[`background-image`,`border-image-source`,`-webkit-border-image`,`-webkit-mask-image`,`list-style-image`];function Ke(e,t){return Ge.map(n=>{let r=e.getPropertyValue(n);return!r||r===`none`?null:((m||h)&&t.drawImageCount++,U(r,null,t,!0).then(t=>{t&&r!==t&&e.setProperty(n,t,e.getPropertyPriority(n))}))}).filter(Boolean)}function qe(e,t){if(C(e)){let n=e.currentSrc||e.src;if(!T(n))return[H(t,{url:n,imageDom:e,requestType:`image`,responseType:`dataUrl`}).then(t=>{t&&(e.srcset=``,e.dataset.originalSrc=n,e.src=t||``)})];(m||h)&&t.drawImageCount++}else if(x(e)&&!T(e.href.baseVal)){let n=e.href.baseVal;return[H(t,{url:n,imageDom:e,requestType:`image`,responseType:`dataUrl`}).then(t=>{t&&(e.dataset.originalSrc=n,e.href.baseVal=t||``)})]}return[]}function Je(e,t){let{ownerDocument:n,svgDefsElement:r}=t,i=e.getAttribute(`href`)??e.getAttribute(`xlink:href`);if(!i)return[];let[a,o]=i.split(`#`);if(o){let i=`#${o}`,s=t.shadowRoots.reduce((e,t)=>e??t.querySelector(`svg ${i}`),n?.querySelector(`svg ${i}`));if(a&&e.setAttribute(`href`,i),r?.querySelector(i))return[];if(s)return r?.appendChild(s.cloneNode(!0)),[];if(a)return[H(t,{url:a,responseType:`text`}).then(e=>{r?.insertAdjacentHTML(`beforeend`,e)})]}return[]}function K(e,t){let{tasks:n}=t;b(e)&&((C(e)||ee(e))&&n.push(...qe(e,t)),te(e)&&n.push(...Je(e,t))),S(e)&&n.push(...Ke(e.style,t)),e.childNodes.forEach(e=>{K(e,t)})}async function Ye(e,t){let{ownerDocument:n,svgStyleElement:r,fontFamilies:i,fontCssTexts:a,tasks:o,font:s}=t;if(n&&r&&i.size){if(s&&s.cssText){let e=J(s.cssText,t);r.appendChild(n.createTextNode(`${e}
8
+ `))}else{let e=Array.from(n.styleSheets).filter(e=>{try{return`cssRules`in e&&!!e.cssRules.length}catch(n){return t.log.warn(`Error while reading CSS rules from ${e.href}`,n),!1}}),s=n.implementation.createHTMLDocument(``),c=s.createElement(`style`);s.head.appendChild(c);let l=c.sheet;await Promise.all(e.flatMap(e=>Array.from(e.cssRules).map(async e=>{if(v(e)){let n=e.href,r=``;try{r=await H(t,{url:n,requestType:`text`,responseType:`text`})}catch(e){t.log.warn(`Error fetch remote css import from ${n}`,e)}let i=r.replace(G,(e,t,r)=>e.replace(r,E(r,n)));for(let e of Ze(i))try{l.insertRule(e,l.cssRules.length)}catch(n){t.log.warn(`Error inserting rule from remote css import`,{rule:e,error:n})}}}))),l.cssRules.length&&e.push(l);let u=[];e.forEach(e=>{Y(e.cssRules,u)}),u.filter(e=>_(e)&&W(e.style.getPropertyValue(`src`))&&j(e.style.getPropertyValue(`font-family`))?.some(e=>i.has(e))).forEach(e=>{let i=e,s=a.get(i.cssText);s?r.appendChild(n.createTextNode(`${s}
9
+ `)):o.push(U(i.cssText,i.parentStyleSheet?i.parentStyleSheet.href:null,t).then(e=>{e=J(e,t),a.set(i.cssText,e),r.appendChild(n.createTextNode(`${e}
10
+ `))}))})}}}var Xe=/(\/\*[\s\S]*?\*\/)/g,q=/((@.*?keyframes [\s\S]*?){([\s\S]*?}\s*?)})/gi;function Ze(e){if(e==null)return[];let t=[],n=e.replace(Xe,``);for(;;){let e=q.exec(n);if(!e)break;t.push(e[0])}n=n.replace(q,``);let r=/@import[\s\S]*?url\([^)]*\)[\s\S]*?;/gi,i=/* @__PURE__ */ RegExp(`((\\s*?(?:\\/\\*[\\s\\S]*?\\*\\/)?\\s*?@media[\\s\\S]*?){([\\s\\S]*?)}\\s*?})|(([\\s\\S]*?){([\\s\\S]*?)})`,`gi`);for(;;){let e=r.exec(n);if(e)i.lastIndex=r.lastIndex;else if(e=i.exec(n),e)r.lastIndex=i.lastIndex;else break;t.push(e[0])}return t}var Qe=/url\([^)]+\)\s*format\((["']?)([^"']+)\1\)/g,$e=/src:\s*(?:url\([^)]+\)\s*format\([^)]+\)[,;]\s*)+/g;function J(e,t){let{font:n}=t,r=n?n?.preferredFormat:void 0;return r?e.replace($e,e=>{for(;;){let[t,,n]=Qe.exec(e)||[];if(!n)return``;if(n===r)return`src: ${t};`}}):e}function Y(e,t=[]){for(let n of Array.from(e))y(n)?t.push(...Y(n.cssRules)):`cssRules`in n?Y(n.cssRules,t):t.push(n);return t}var et=/\bx?link:?href\s*=\s*["'](?!data:)[^"']+["']/i;function tt(e){return et.test(e.innerHTML)}async function nt(e,t){let n=await N(e,t);if(b(n.node)&&x(n.node)&&!tt(n.node))return n.node;let{ownerDocument:r,log:i,tasks:a,svgStyleElement:o,svgDefsElement:s,svgStyles:c,font:l,progress:u,autoDestruct:d,onCloneNode:f,onEmbedNode:p,onCreateForeignObjectSvg:m}=n;i.time(`clone node`);let h=await V(n.node,n,!0);if(o&&r){let e=``;c.forEach((t,n)=>{e+=`${t.join(`,
11
+ `)} {
12
+ ${n}
13
+ }
14
+ `}),o.appendChild(r.createTextNode(e))}i.timeEnd(`clone node`),await f?.(h),l!==!1&&b(h)&&(i.time(`embed web font`),await Ye(h,n),i.timeEnd(`embed web font`)),i.time(`embed node`),K(h,n);let g=a.length,_=0,v=async()=>{for(;;){let e=a.pop();if(!e)break;try{await e}catch(e){n.log.warn(`Failed to run task`,e)}u?.(++_,g)}};u?.(_,g),await Promise.all([...Array.from({length:4})].map(v)),i.timeEnd(`embed node`),await p?.(h);let y=rt(h,n);return s&&y.insertBefore(s,y.children[0]),o&&y.insertBefore(o,y.children[0]),d&&Ve(n),await m?.(y),y}function rt(e,t){let{width:n,height:r}=t,i=me(n,r,e.ownerDocument),a=i.ownerDocument.createElementNS(i.namespaceURI,`foreignObject`);return a.setAttributeNS(null,`x`,`0%`),a.setAttributeNS(null,`y`,`0%`),a.setAttributeNS(null,`width`,`100%`),a.setAttributeNS(null,`height`,`100%`),a.append(e),i.appendChild(a),i}async function it(e,t){let n=await N(e,t),r=await nt(n),i=he(r,n.isEnable(`removeControlCharacter`));return n.autoDestruct||(n.svgStyleElement=P(n.ownerDocument),n.svgDefsElement=n.ownerDocument?.createElementNS(O,`defs`),n.svgStyles.clear()),await we(k(i,r.ownerDocument),n)}async function at(t,n){let r=await N(t,n),{log:i,quality:s,type:c,dpi:l}=r,f=await it(r);i.time(`canvas to data url`);let p=f.toDataURL(c,s);if([`image/png`,`image/jpeg`].includes(c)&&l&&u&&d){let[t,n]=p.split(`,`),r=0,i=!1;if(c===`image/png`){let e=o(n);e>=0?(r=Math.ceil((e+28)/3)*4,i=!0):r=44}else c===`image/jpeg`&&(r=24);let s=n.substring(0,r),u=n.substring(r),d=window.atob(s),f=new Uint8Array(d.length);for(let e=0;e<f.length;e++)f[e]=d.charCodeAt(e);let m=c===`image/png`?a(f,l,i):e(f,l);p=[t,`,`,window.btoa(String.fromCharCode(...m)),u].join(``)}return i.timeEnd(`canvas to data url`),p}async function ot(e,t){return at(await N(e,{...t,type:`image/png`}))}var st=`leesto-mask`,ct=`[data-leesto-block]`,lt=`leesto-mask-text`,ut=`[data-private]`;function dt(e){return e.replace(/\S/g,`*`)}var X=`data-leesto-capture-field`,Z=`data-leesto-capture-text`,Q=`data-leesto-capture-block`,ft=`.${st}, ${ct}`,pt=`input:not([type="button"]):not([type="submit"]):not([type="reset"]):not([type="hidden"]):not([type="checkbox"]):not([type="radio"]):not([type="range"]):not([type="color"]):not([type="image"]), textarea, select`,mt=`.${lt}, ${ut}`;function ht(e,t={}){let n=[],r=(e,t,r=``)=>{e.hasAttribute(t)||(e.setAttribute(t,r),n.push([e,t]))},i=t=>[...e.matches(t)?[e]:[],...e.querySelectorAll(t)];for(let e of i(pt))r(e,X);for(let e of i(mt))r(e,Z);if(t.blocks)for(let t of e.querySelectorAll(ft)){let e=t.getBoundingClientRect();r(t,Q,`${Math.round(e.width)}x${Math.round(e.height)}`)}return()=>{for(let[e,t]of n)e.removeAttribute(t)}}function $(e){let t=e.ownerDocument.createTreeWalker(e,4);for(let e=t.nextNode();e;e=t.nextNode()){let t=e;t.data=dt(t.data)}}function gt(e){let t=e.tagName.toLowerCase();if(t===`select`){for(let t of e.querySelectorAll(`option`))$(t);return}let n=e.getAttribute(`value`);n&&e.setAttribute(`value`,dt(n)),t===`textarea`&&$(e)}function _t(e){if(e.nodeType!==1)return;let t=e,n=e=>[...t.hasAttribute(e)?[t]:[],...t.querySelectorAll(`[${e}]`)];for(let e of n(X))gt(e),e.removeAttribute(X);for(let e of n(Z))$(e),e.removeAttribute(Z);for(let e of t.querySelectorAll(`[${Q}]`)){let[t,n]=(e.getAttribute(Q)??`0x0`).split(`x`),r=e.ownerDocument.createElement(`div`);r.setAttribute(`style`,`display:inline-block;width:${t}px;height:${n}px;background:#a1a1aa`),e.replaceWith(r)}}function vt(){let e=e=>!!e&&e!==`transparent`&&!/^rgba\(\s*0,\s*0,\s*0,\s*0\s*\)$/.test(e),t=getComputedStyle(document.body).backgroundColor;if(e(t))return t;let n=getComputedStyle(document.documentElement).backgroundColor;return e(n)?n:`#ffffff`}var yt=Promise.resolve();function bt(e){let t=yt.then(()=>St(e));return yt=t.catch(()=>{}),t}function xt(e,t,n,r){if(t!==`sticky`)return[n,r];let i=e.getBoundingClientRect(),a=e.style.position;e.style.position=`static`;let o=e.getBoundingClientRect();return e.style.position=a,[i.x-o.x,i.y-o.y]}async function St(e){if(e){let t=document.querySelector(e);if(!t)throw Error(`element_not_found`);if(t.closest(ft))throw Error(`capture_blocked`);let n=ht(t,{blocks:!0});try{return await ot(t,{quality:.92,onCloneNode:_t})}finally{n()}}let t=document.documentElement,n=window.scrollX,r=window.scrollY,i=[],a=[],o=()=>{};try{o=ht(t);for(let e of t.querySelectorAll(`.${st}, ${ct}`)){let n=e.getBoundingClientRect();if(n.width<=0||n.height<=0)continue;let r=document.createElement(`div`);r.dataset.leestoCaptureCover=``,Object.assign(r.style,{position:`fixed`,left:`${n.x}px`,top:`${n.y}px`,width:`${n.width}px`,height:`${n.height}px`,background:`#a1a1aa`,zIndex:`2147483647`,pointerEvents:`none`}),t.append(r),i.push(r)}for(let e of t.querySelectorAll(`*`)){let t=getComputedStyle(e).position;if(t===`fixed`||t===`sticky`){let[i,o]=xt(e,t,n,r),s=e.style.transform;a.push([e,s]),e.style.transform=`translate(${i}px, ${o}px)${s?` ${s}`:``}`}}return await ot(t,{quality:.92,backgroundColor:vt(),width:t.clientWidth,height:t.clientHeight,style:{transform:`translate(${-n}px, ${-r}px)`,transformOrigin:`top left`},onCloneNode:_t})}finally{o();for(let e of i)e.remove();for(let[e,t]of a)e.style.transform=t}}export{bt as defaultCapture};
15
+ //# sourceMappingURL=capture-DWs25Qj7.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"capture-DWs25Qj7.js","names":["changeJpegDpi","dpi","uint8Array","pngDataTable","createPngDataTable","crcTable","n","c","k","calcCrc","searchStartOfPhys","length","i","changePngDpi","physChunk","crc","crcChunk","overwritepHYs","startingIndex","chunkLength","finalHeader","detectPhysChunkFromDataUrl","b64index","dataUrl","PREFIX","IN_BROWSER","SUPPORT_WEB_WORKER","SUPPORT_ATOB","SUPPORT_BTOA","USER_AGENT","IN_CHROME","IN_SAFARI","IN_FIREFOX","isContext","value","isCssFontFaceRule","rule","isCSSImportRule","isLayerBlockRule","isElementNode","node","isSVGElementNode","isSVGImageElementNode","isSVGUseElementNode","isHTMLElementNode","isCommentNode","isTextNode","isImageElement","isVideoElement","isCanvasElement","isTextareaElement","isInputElement","isStyleElement","isScriptElement","isSelectElement","isSlotElement","isIFrameElement","consoleWarn","args","supportWebp","canvas","ownerDocument","isDataUrl","url","resolveUrl","doc","getDocument","base","a","baseUrl","target","XMLNS","createSvg","svg","width","height","svgToDataUrl","xhtml","removeControlCharacter","readBlob","reader","resolve","reject","type","blob","blobToDataUrl","createImage","img","loadMedia","userOnError","options","media","timer","removeEventListeners","onResolve","timeout","currentSrc","onLoadeddata","onError","onWarn","error","onLoad","waitUntilLoad","selectors","el","uuid","counter","random","splitFontFamily","fontFamily","val","uid","createLogger","prefix","debug","label","getDefaultRequestInit","bypassingCache","orCreateContext","createContext","features","ownerWindow","requests","context","scale","createStyleElement","workerUrl","workerNumber","worker","event","result","key","resolveBoundingBox","style","cssText","box","imageToCanvas","log","loaded","image","createCanvas","drawImage","context2d","drawImageCount","drawImageInterval","max","backgroundColor","cloneCanvas","dataURL","cloned","ctx","clonedCtx","cloneIframe","iframe","cloneNode","cloneImage","cloneVideo","video","canPlay","cloneElement","getSandBox","sandbox","ignoredStyles","includedAttributes","getDefaultStyle","nodeName","isSvgNode","attributes","name","pseudoElement","defaultComputedStyles","sandboxWindow","sandboxDocument","root","computedStyle","styles","len","getDiffStyle","diffStyle","prefixs","prefixTree","includeStyleProperties","applyTo","priority","subIndex","map","defaultStyle","copyCssStyles","clonedStyle","currentParentNodeStyle","isRoot","copyInputValue","pseudoClasses","scrollbarPseudoClasses","copyPseudoClass","svgStyleElement","copyBy","pseudoClass","content","addWordToFontFamilies","klasses","currentNodeStyle","cloneStyle","err","allClasses","svgStyles","copyScrollbar","excludeParentNodes","appendChildNode","child","childCloned","restoreScrollPosition","cloneChildNodes","firstChild","nodes","chlidCloned","scrollTop","scrollLeft","matrix","transform","b","d","applyCssStyleWithOptions","NORMAL_ATTRIBUTE_RE","cloned2","names","overflow","textTransform","families","addWordToFontFamilies2","word","fontFamilies","family","text","onCloneEachNode","destroyContext","baseFetch","requestInit","controller","response","responseType","contextFetch","rawUrl","requestType","request","canFontMinify","font","fontTexts","needFontMinify","baseFetchOptions","acceptOfImage","fetchFn","workers","placeholderImage","imageDom","replaceCssUrlToDataUrl","hasCssUrl","parseCssUrls","isImage","toRE","URL_RE","raw","escaped","properties","embedCssStyleImage","property","newValue","embedImageElement","originalSrc","embedSvgUse","href","svgUrl","id","query","definition","res","svgDefsElement","svgData","embedNode","tasks","embedWebFont","filterPreferredFormat","styleSheets","styleSheet","tempDoc","tempStyleEl","tempStyleSheet","cssRule","replacedCssText","parseCss","cssRules","unwrapCssLayers","sheet","fontCssTexts","cssText2","COMMENTS_RE","KEYFRAMES_RE","source","matches","IMPORT_RE","UNIFIED_RE","URL_WITH_FORMAT_RE","FONT_SRC_RE","preferredFormat","str","src","format","match","rules","out","SVG_EXTERNAL_RESOURCE_REGEX","svgHasExternalResources","domToForeignObjectSvg","clone","allCssText","onCloneNode","count","current","runTask","task","progress","onEmbedNode","createForeignObjectSvg","autoDestruct","onCreateForeignObjectSvg","foreignObject","domToCanvas","domToDataUrl","quality","body","headerLength","b64Index","stringHeader","restOfData","headerBytes","finalArray","domToPng","CLIENT_BLOCK_CLASS","CLIENT_BLOCK_SELECTOR","CLIENT_MASK_TEXT_CLASS","CLIENT_MASK_TEXT_SELECTOR","maskText","FIELD_MARK","TEXT_MARK","BLOCK_MARK","CLIENT_BLOCKED","CAPTURED_FIELD_SELECTOR","CLIENT_TEXT_MASKED","markCaptureMasks","marked","mark","attribute","within","selector","maskTextNodes","walker","maskField","tag","option","maskCapturedClone","find","cover","pageBackgroundColor","isOpaque","bodyBg","htmlBg","captureQueue","defaultCapture","run","captureNow","pinOffset","position","sx","sy","onScreen","prev","inFlow","element","unmark","covers","pinned","r","pos","dx","dy"],"sources":["../../../../node_modules/.bun/modern-screenshot@4.7.0/node_modules/modern-screenshot/dist/index.mjs","../../src/rrweb-mask.ts?lazy=capture","../../src/capture-mask.ts?lazy=capture","../../src/capture.ts?lazy=capture"],"sourcesContent":["function changeJpegDpi(uint8Array, dpi) {\n uint8Array[13] = 1;\n uint8Array[14] = dpi >> 8;\n uint8Array[15] = dpi & 255;\n uint8Array[16] = dpi >> 8;\n uint8Array[17] = dpi & 255;\n return uint8Array;\n}\n\nconst _P = \"p\".charCodeAt(0);\nconst _H = \"H\".charCodeAt(0);\nconst _Y = \"Y\".charCodeAt(0);\nconst _S = \"s\".charCodeAt(0);\nlet pngDataTable;\nfunction createPngDataTable() {\n const crcTable = new Int32Array(256);\n for (let n = 0; n < 256; n++) {\n let c = n;\n for (let k = 0; k < 8; k++) {\n c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1;\n }\n crcTable[n] = c;\n }\n return crcTable;\n}\nfunction calcCrc(uint8Array) {\n let c = -1;\n if (!pngDataTable)\n pngDataTable = createPngDataTable();\n for (let n = 0; n < uint8Array.length; n++) {\n c = pngDataTable[(c ^ uint8Array[n]) & 255] ^ c >>> 8;\n }\n return c ^ -1;\n}\nfunction searchStartOfPhys(uint8Array) {\n const length = uint8Array.length - 1;\n for (let i = length; i >= 4; i--) {\n if (uint8Array[i - 4] === 9 && uint8Array[i - 3] === _P && uint8Array[i - 2] === _H && uint8Array[i - 1] === _Y && uint8Array[i] === _S) {\n return i - 3;\n }\n }\n return 0;\n}\nfunction changePngDpi(uint8Array, dpi, overwritepHYs = false) {\n const physChunk = new Uint8Array(13);\n dpi *= 39.3701;\n physChunk[0] = _P;\n physChunk[1] = _H;\n physChunk[2] = _Y;\n physChunk[3] = _S;\n physChunk[4] = dpi >>> 24;\n physChunk[5] = dpi >>> 16;\n physChunk[6] = dpi >>> 8;\n physChunk[7] = dpi & 255;\n physChunk[8] = physChunk[4];\n physChunk[9] = physChunk[5];\n physChunk[10] = physChunk[6];\n physChunk[11] = physChunk[7];\n physChunk[12] = 1;\n const crc = calcCrc(physChunk);\n const crcChunk = new Uint8Array(4);\n crcChunk[0] = crc >>> 24;\n crcChunk[1] = crc >>> 16;\n crcChunk[2] = crc >>> 8;\n crcChunk[3] = crc & 255;\n if (overwritepHYs) {\n const startingIndex = searchStartOfPhys(uint8Array);\n uint8Array.set(physChunk, startingIndex);\n uint8Array.set(crcChunk, startingIndex + 13);\n return uint8Array;\n } else {\n const chunkLength = new Uint8Array(4);\n chunkLength[0] = 0;\n chunkLength[1] = 0;\n chunkLength[2] = 0;\n chunkLength[3] = 9;\n const finalHeader = new Uint8Array(54);\n finalHeader.set(uint8Array, 0);\n finalHeader.set(chunkLength, 33);\n finalHeader.set(physChunk, 37);\n finalHeader.set(crcChunk, 50);\n return finalHeader;\n }\n}\nconst b64PhysSignature1 = \"AAlwSFlz\";\nconst b64PhysSignature2 = \"AAAJcEhZ\";\nconst b64PhysSignature3 = \"AAAACXBI\";\nfunction detectPhysChunkFromDataUrl(dataUrl) {\n let b64index = dataUrl.indexOf(b64PhysSignature1);\n if (b64index === -1) {\n b64index = dataUrl.indexOf(b64PhysSignature2);\n }\n if (b64index === -1) {\n b64index = dataUrl.indexOf(b64PhysSignature3);\n }\n return b64index;\n}\n\nconst PREFIX = \"[modern-screenshot]\";\nconst IN_BROWSER = typeof window !== \"undefined\";\nconst SUPPORT_WEB_WORKER = IN_BROWSER && \"Worker\" in window;\nconst SUPPORT_ATOB = IN_BROWSER && \"atob\" in window;\nconst SUPPORT_BTOA = IN_BROWSER && \"btoa\" in window;\nconst USER_AGENT = IN_BROWSER ? window.navigator?.userAgent : \"\";\nconst IN_CHROME = USER_AGENT.includes(\"Chrome\");\nconst IN_SAFARI = USER_AGENT.includes(\"AppleWebKit\") && !IN_CHROME;\nconst IN_FIREFOX = USER_AGENT.includes(\"Firefox\");\nconst isContext = (value) => value && \"__CONTEXT__\" in value;\nconst isCssFontFaceRule = (rule) => rule.constructor.name === \"CSSFontFaceRule\";\nconst isCSSImportRule = (rule) => rule.constructor.name === \"CSSImportRule\";\nconst isLayerBlockRule = (rule) => rule.constructor.name === \"CSSLayerBlockRule\";\nconst isElementNode = (node) => node.nodeType === 1;\nconst isSVGElementNode = (node) => typeof node.className === \"object\";\nconst isSVGImageElementNode = (node) => node.tagName === \"image\";\nconst isSVGUseElementNode = (node) => node.tagName === \"use\";\nconst isHTMLElementNode = (node) => isElementNode(node) && typeof node.style !== \"undefined\" && !isSVGElementNode(node);\nconst isCommentNode = (node) => node.nodeType === 8;\nconst isTextNode = (node) => node.nodeType === 3;\nconst isImageElement = (node) => node.tagName === \"IMG\";\nconst isVideoElement = (node) => node.tagName === \"VIDEO\";\nconst isCanvasElement = (node) => node.tagName === \"CANVAS\";\nconst isTextareaElement = (node) => node.tagName === \"TEXTAREA\";\nconst isInputElement = (node) => node.tagName === \"INPUT\";\nconst isStyleElement = (node) => node.tagName === \"STYLE\";\nconst isScriptElement = (node) => node.tagName === \"SCRIPT\";\nconst isSelectElement = (node) => node.tagName === \"SELECT\";\nconst isSlotElement = (node) => node.tagName === \"SLOT\";\nconst isIFrameElement = (node) => node.tagName === \"IFRAME\";\nconst consoleWarn = (...args) => console.warn(PREFIX, ...args);\nfunction supportWebp(ownerDocument) {\n const canvas = ownerDocument?.createElement?.(\"canvas\");\n if (canvas) {\n canvas.height = canvas.width = 1;\n }\n return Boolean(canvas) && \"toDataURL\" in canvas && Boolean(canvas.toDataURL(\"image/webp\").includes(\"image/webp\"));\n}\nconst isDataUrl = (url) => url.startsWith(\"data:\");\nfunction resolveUrl(url, baseUrl) {\n if (url.match(/^[a-z]+:\\/\\//i))\n return url;\n if (IN_BROWSER && url.match(/^\\/\\//))\n return window.location.protocol + url;\n if (url.match(/^[a-z]+:/i))\n return url;\n if (!IN_BROWSER)\n return url;\n const doc = getDocument().implementation.createHTMLDocument();\n const base = doc.createElement(\"base\");\n const a = doc.createElement(\"a\");\n doc.head.appendChild(base);\n doc.body.appendChild(a);\n if (baseUrl)\n base.href = baseUrl;\n a.href = url;\n return a.href;\n}\nfunction getDocument(target) {\n return (target && isElementNode(target) ? target?.ownerDocument : target) ?? window.document;\n}\nconst XMLNS = \"http://www.w3.org/2000/svg\";\nfunction createSvg(width, height, ownerDocument) {\n const svg = getDocument(ownerDocument).createElementNS(XMLNS, \"svg\");\n svg.setAttributeNS(null, \"width\", width.toString());\n svg.setAttributeNS(null, \"height\", height.toString());\n svg.setAttributeNS(null, \"viewBox\", `0 0 ${width} ${height}`);\n return svg;\n}\nfunction svgToDataUrl(svg, removeControlCharacter) {\n let xhtml = new XMLSerializer().serializeToString(svg);\n if (removeControlCharacter) {\n xhtml = xhtml.replace(/[\\u0000-\\u0008\\v\\f\\u000E-\\u001F\\uD800-\\uDFFF\\uFFFE\\uFFFF]/gu, \"\");\n }\n return `data:image/svg+xml;charset=utf-8,${encodeURIComponent(xhtml)}`;\n}\nasync function canvasToBlob(canvas, type = \"image/png\", quality = 1) {\n try {\n return await new Promise((resolve, reject) => {\n canvas.toBlob((blob) => {\n if (blob) {\n resolve(blob);\n } else {\n reject(new Error(\"Blob is null\"));\n }\n }, type, quality);\n });\n } catch (error) {\n if (SUPPORT_ATOB) {\n return dataUrlToBlob(canvas.toDataURL(type, quality));\n }\n throw error;\n }\n}\nfunction dataUrlToBlob(dataUrl) {\n const [header, base64] = dataUrl.split(\",\");\n const type = header.match(/data:(.+);/)?.[1] ?? void 0;\n const decoded = window.atob(base64);\n const length = decoded.length;\n const buffer = new Uint8Array(length);\n for (let i = 0; i < length; i += 1) {\n buffer[i] = decoded.charCodeAt(i);\n }\n return new Blob([buffer], { type });\n}\nfunction readBlob(blob, type) {\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n reader.onload = () => resolve(reader.result);\n reader.onerror = () => reject(reader.error);\n reader.onabort = () => reject(new Error(`Failed read blob to ${type}`));\n if (type === \"dataUrl\") {\n reader.readAsDataURL(blob);\n } else if (type === \"arrayBuffer\") {\n reader.readAsArrayBuffer(blob);\n }\n });\n}\nconst blobToDataUrl = (blob) => readBlob(blob, \"dataUrl\");\nconst blobToArrayBuffer = (blob) => readBlob(blob, \"arrayBuffer\");\nfunction createImage(url, ownerDocument) {\n const img = getDocument(ownerDocument).createElement(\"img\");\n img.decoding = \"sync\";\n img.loading = \"eager\";\n img.src = url;\n return img;\n}\nfunction loadMedia(media, options) {\n return new Promise((resolve) => {\n const { timeout, ownerDocument, onError: userOnError, onWarn } = options ?? {};\n const node = typeof media === \"string\" ? createImage(media, getDocument(ownerDocument)) : media;\n let timer = null;\n let removeEventListeners = null;\n function onResolve() {\n resolve(node);\n timer && clearTimeout(timer);\n removeEventListeners?.();\n }\n if (timeout) {\n timer = setTimeout(onResolve, timeout);\n }\n if (isVideoElement(node)) {\n const currentSrc = node.currentSrc || node.src;\n if (!currentSrc) {\n if (node.poster) {\n return loadMedia(node.poster, options).then(resolve);\n }\n return onResolve();\n }\n if (node.readyState >= 2) {\n return onResolve();\n }\n const onLoadeddata = onResolve;\n const onError = (error) => {\n onWarn?.(\n \"Failed video load\",\n currentSrc,\n error\n );\n userOnError?.(error);\n onResolve();\n };\n removeEventListeners = () => {\n node.removeEventListener(\"loadeddata\", onLoadeddata);\n node.removeEventListener(\"error\", onError);\n };\n node.addEventListener(\"loadeddata\", onLoadeddata, { once: true });\n node.addEventListener(\"error\", onError, { once: true });\n } else {\n const currentSrc = isSVGImageElementNode(node) ? node.href.baseVal : node.currentSrc || node.src;\n if (!currentSrc) {\n return onResolve();\n }\n const onLoad = async () => {\n if (isImageElement(node) && \"decode\" in node) {\n try {\n await node.decode();\n } catch (error) {\n onWarn?.(\n \"Failed to decode image, trying to render anyway\",\n node.dataset.originalSrc || currentSrc,\n error\n );\n }\n }\n onResolve();\n };\n const onError = (error) => {\n onWarn?.(\n \"Failed image load\",\n node.dataset.originalSrc || currentSrc,\n error\n );\n onResolve();\n };\n if (isImageElement(node) && node.complete) {\n return onLoad();\n }\n removeEventListeners = () => {\n node.removeEventListener(\"load\", onLoad);\n node.removeEventListener(\"error\", onError);\n };\n node.addEventListener(\"load\", onLoad, { once: true });\n node.addEventListener(\"error\", onError, { once: true });\n }\n });\n}\nasync function waitUntilLoad(node, options) {\n if (isHTMLElementNode(node)) {\n if (isImageElement(node) || isVideoElement(node)) {\n await loadMedia(node, options);\n } else {\n await Promise.all(\n [\"img\", \"video\"].flatMap((selectors) => {\n return Array.from(node.querySelectorAll(selectors)).map((el) => loadMedia(el, options));\n })\n );\n }\n }\n}\nconst uuid = /* @__PURE__ */ function uuid2() {\n let counter = 0;\n const random = () => `0000${(Math.random() * 36 ** 4 << 0).toString(36)}`.slice(-4);\n return () => {\n counter += 1;\n return `u${random()}${counter}`;\n };\n}();\nfunction splitFontFamily(fontFamily) {\n return fontFamily?.split(\",\").map((val) => val.trim().replace(/\"|'/g, \"\").toLowerCase()).filter(Boolean);\n}\n\nlet uid = 0;\nfunction createLogger(debug) {\n const prefix = `${PREFIX}[#${uid}]`;\n uid++;\n return {\n // eslint-disable-next-line no-console\n time: (label) => debug && console.time(`${prefix} ${label}`),\n // eslint-disable-next-line no-console\n timeEnd: (label) => debug && console.timeEnd(`${prefix} ${label}`),\n warn: (...args) => debug && consoleWarn(...args)\n };\n}\n\nfunction getDefaultRequestInit(bypassingCache) {\n return {\n cache: bypassingCache ? \"no-cache\" : \"force-cache\"\n };\n}\n\nasync function orCreateContext(node, options) {\n return isContext(node) ? node : createContext(node, { ...options, autoDestruct: true });\n}\nasync function createContext(node, options) {\n const { scale = 1, workerUrl, workerNumber = 1 } = options || {};\n const debug = Boolean(options?.debug);\n const features = options?.features ?? true;\n const ownerDocument = node.ownerDocument ?? (IN_BROWSER ? window.document : void 0);\n const ownerWindow = node.ownerDocument?.defaultView ?? (IN_BROWSER ? window : void 0);\n const requests = /* @__PURE__ */ new Map();\n const context = {\n // Options\n width: 0,\n height: 0,\n quality: 1,\n type: \"image/png\",\n scale,\n backgroundColor: null,\n style: null,\n filter: null,\n maximumCanvasSize: 0,\n timeout: 3e4,\n progress: null,\n debug,\n fetch: {\n requestInit: getDefaultRequestInit(options?.fetch?.bypassingCache),\n placeholderImage: \"data:image/png;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7\",\n bypassingCache: false,\n ...options?.fetch\n },\n fetchFn: null,\n font: {},\n drawImageInterval: 100,\n workerUrl: null,\n workerNumber,\n onCloneEachNode: null,\n onCloneNode: null,\n onEmbedNode: null,\n onCreateForeignObjectSvg: null,\n includeStyleProperties: null,\n autoDestruct: false,\n ...options,\n // InternalContext\n __CONTEXT__: true,\n log: createLogger(debug),\n node,\n ownerDocument,\n ownerWindow,\n dpi: scale === 1 ? null : 96 * scale,\n svgStyleElement: createStyleElement(ownerDocument),\n svgDefsElement: ownerDocument?.createElementNS(XMLNS, \"defs\"),\n svgStyles: /* @__PURE__ */ new Map(),\n defaultComputedStyles: /* @__PURE__ */ new Map(),\n workers: [\n ...Array.from({\n length: SUPPORT_WEB_WORKER && workerUrl && workerNumber ? workerNumber : 0\n })\n ].map(() => {\n try {\n const worker = new Worker(workerUrl);\n worker.onmessage = async (event) => {\n const { url, result } = event.data;\n if (result) {\n requests.get(url)?.resolve?.(result);\n } else {\n requests.get(url)?.reject?.(new Error(`Error receiving message from worker: ${url}`));\n }\n };\n worker.onmessageerror = (event) => {\n const { url } = event.data;\n requests.get(url)?.reject?.(new Error(`Error receiving message from worker: ${url}`));\n };\n return worker;\n } catch (error) {\n context.log.warn(\"Failed to new Worker\", error);\n return null;\n }\n }).filter(Boolean),\n fontFamilies: /* @__PURE__ */ new Map(),\n fontCssTexts: /* @__PURE__ */ new Map(),\n acceptOfImage: `${[\n supportWebp(ownerDocument) && \"image/webp\",\n \"image/svg+xml\",\n \"image/*\",\n \"*/*\"\n ].filter(Boolean).join(\",\")};q=0.8`,\n requests,\n drawImageCount: 0,\n tasks: [],\n features,\n isEnable: (key) => {\n if (key === \"restoreScrollPosition\") {\n return typeof features === \"boolean\" ? false : features[key] ?? false;\n }\n if (typeof features === \"boolean\") {\n return features;\n }\n return features[key] ?? true;\n },\n shadowRoots: []\n };\n context.log.time(\"wait until load\");\n await waitUntilLoad(node, { timeout: context.timeout, onWarn: context.log.warn });\n context.log.timeEnd(\"wait until load\");\n const { width, height } = resolveBoundingBox(node, context);\n context.width = width;\n context.height = height;\n return context;\n}\nfunction createStyleElement(ownerDocument) {\n if (!ownerDocument)\n return void 0;\n const style = ownerDocument.createElement(\"style\");\n const cssText = style.ownerDocument.createTextNode(`\n.______background-clip--text {\n background-clip: text;\n -webkit-background-clip: text;\n}\n`);\n style.appendChild(cssText);\n return style;\n}\nfunction resolveBoundingBox(node, context) {\n let { width, height } = context;\n if (isElementNode(node) && (!width || !height)) {\n const box = node.getBoundingClientRect();\n width = width || box.width || Number(node.getAttribute(\"width\")) || 0;\n height = height || box.height || Number(node.getAttribute(\"height\")) || 0;\n }\n return { width, height };\n}\n\nasync function imageToCanvas(image, context) {\n const {\n log,\n timeout,\n drawImageCount,\n drawImageInterval\n } = context;\n log.time(\"image to canvas\");\n const loaded = await loadMedia(image, { timeout, onWarn: context.log.warn });\n const { canvas, context2d } = createCanvas(image.ownerDocument, context);\n const drawImage = () => {\n try {\n context2d?.drawImage(loaded, 0, 0, canvas.width, canvas.height);\n } catch (error) {\n context.log.warn(\"Failed to drawImage\", error);\n }\n };\n drawImage();\n if (context.isEnable(\"fixSvgXmlDecode\")) {\n for (let i = 0; i < drawImageCount; i++) {\n await new Promise((resolve) => {\n setTimeout(() => {\n context2d?.clearRect(0, 0, canvas.width, canvas.height);\n drawImage();\n resolve();\n }, i + drawImageInterval);\n });\n }\n }\n context.drawImageCount = 0;\n log.timeEnd(\"image to canvas\");\n return canvas;\n}\nfunction createCanvas(ownerDocument, context) {\n const { width, height, scale, backgroundColor, maximumCanvasSize: max } = context;\n const canvas = ownerDocument.createElement(\"canvas\");\n canvas.width = Math.floor(width * scale);\n canvas.height = Math.floor(height * scale);\n canvas.style.width = `${width}px`;\n canvas.style.height = `${height}px`;\n if (max) {\n if (canvas.width > max || canvas.height > max) {\n if (canvas.width > max && canvas.height > max) {\n if (canvas.width > canvas.height) {\n canvas.height *= max / canvas.width;\n canvas.width = max;\n } else {\n canvas.width *= max / canvas.height;\n canvas.height = max;\n }\n } else if (canvas.width > max) {\n canvas.height *= max / canvas.width;\n canvas.width = max;\n } else {\n canvas.width *= max / canvas.height;\n canvas.height = max;\n }\n }\n }\n const context2d = canvas.getContext(\"2d\");\n if (context2d && backgroundColor) {\n context2d.fillStyle = backgroundColor;\n context2d.fillRect(0, 0, canvas.width, canvas.height);\n }\n return { canvas, context2d };\n}\n\nfunction cloneCanvas(canvas, context) {\n if (canvas.ownerDocument) {\n try {\n const dataURL = canvas.toDataURL();\n if (dataURL !== \"data:,\") {\n return createImage(dataURL, canvas.ownerDocument);\n }\n } catch (error) {\n context.log.warn(\"Failed to clone canvas\", error);\n }\n }\n const cloned = canvas.cloneNode(false);\n const ctx = canvas.getContext(\"2d\");\n const clonedCtx = cloned.getContext(\"2d\");\n try {\n if (ctx && clonedCtx) {\n clonedCtx.putImageData(\n ctx.getImageData(0, 0, canvas.width, canvas.height),\n 0,\n 0\n );\n }\n return cloned;\n } catch (error) {\n context.log.warn(\"Failed to clone canvas\", error);\n }\n return cloned;\n}\n\nfunction cloneIframe(iframe, context) {\n try {\n if (iframe?.contentDocument?.documentElement) {\n return cloneNode(iframe.contentDocument.documentElement, context);\n }\n } catch (error) {\n context.log.warn(\"Failed to clone iframe\", error);\n }\n return iframe.cloneNode(false);\n}\n\nfunction cloneImage(image) {\n const cloned = image.cloneNode(false);\n if (image.currentSrc && image.currentSrc !== image.src) {\n cloned.src = image.currentSrc;\n cloned.srcset = \"\";\n }\n if (cloned.loading === \"lazy\") {\n cloned.loading = \"eager\";\n }\n return cloned;\n}\n\nasync function cloneVideo(video, context) {\n if (video.ownerDocument && !video.currentSrc && video.poster) {\n return createImage(video.poster, video.ownerDocument);\n }\n const cloned = video.cloneNode(false);\n cloned.crossOrigin = \"anonymous\";\n if (video.currentSrc && video.currentSrc !== video.src) {\n cloned.src = video.currentSrc;\n }\n const ownerDocument = cloned.ownerDocument;\n if (ownerDocument) {\n let canPlay = true;\n await loadMedia(cloned, { onError: () => canPlay = false, onWarn: context.log.warn });\n if (!canPlay) {\n if (video.poster) {\n return createImage(video.poster, video.ownerDocument);\n }\n return cloned;\n }\n cloned.currentTime = video.currentTime;\n await new Promise((resolve) => {\n cloned.addEventListener(\"seeked\", resolve, { once: true });\n });\n const canvas = ownerDocument.createElement(\"canvas\");\n canvas.width = video.offsetWidth;\n canvas.height = video.offsetHeight;\n try {\n const ctx = canvas.getContext(\"2d\");\n if (ctx)\n ctx.drawImage(cloned, 0, 0, canvas.width, canvas.height);\n } catch (error) {\n context.log.warn(\"Failed to clone video\", error);\n if (video.poster) {\n return createImage(video.poster, video.ownerDocument);\n }\n return cloned;\n }\n return cloneCanvas(canvas, context);\n }\n return cloned;\n}\n\nfunction cloneElement(node, context) {\n if (isCanvasElement(node)) {\n return cloneCanvas(node, context);\n }\n if (isIFrameElement(node)) {\n return cloneIframe(node, context);\n }\n if (isImageElement(node)) {\n return cloneImage(node);\n }\n if (isVideoElement(node)) {\n return cloneVideo(node, context);\n }\n return node.cloneNode(false);\n}\n\nfunction getSandBox(context) {\n let sandbox = context.sandbox;\n if (!sandbox) {\n const { ownerDocument } = context;\n try {\n if (ownerDocument) {\n sandbox = ownerDocument.createElement(\"iframe\");\n sandbox.id = `__SANDBOX__${uuid()}`;\n sandbox.width = \"0\";\n sandbox.height = \"0\";\n sandbox.style.visibility = \"hidden\";\n sandbox.style.position = \"fixed\";\n ownerDocument.body.appendChild(sandbox);\n sandbox.srcdoc = '<!DOCTYPE html><meta charset=\"UTF-8\"><title></title><body>';\n context.sandbox = sandbox;\n }\n } catch (error) {\n context.log.warn(\"Failed to getSandBox\", error);\n }\n }\n return sandbox;\n}\n\nconst ignoredStyles = [\n \"width\",\n \"height\",\n \"-webkit-text-fill-color\"\n];\nconst includedAttributes = [\n \"stroke\",\n \"fill\"\n];\nfunction getDefaultStyle(node, pseudoElement, context) {\n const { defaultComputedStyles } = context;\n const nodeName = node.nodeName.toLowerCase();\n const isSvgNode = isSVGElementNode(node) && nodeName !== \"svg\";\n const attributes = isSvgNode ? includedAttributes.map((name) => [name, node.getAttribute(name)]).filter(([, value]) => value !== null) : [];\n const key = [\n isSvgNode && \"svg\",\n nodeName,\n attributes.map((name, value) => `${name}=${value}`).join(\",\"),\n pseudoElement\n ].filter(Boolean).join(\":\");\n if (defaultComputedStyles.has(key))\n return defaultComputedStyles.get(key);\n const sandbox = getSandBox(context);\n const sandboxWindow = sandbox?.contentWindow;\n if (!sandboxWindow)\n return /* @__PURE__ */ new Map();\n const sandboxDocument = sandboxWindow?.document;\n let root;\n let el;\n if (isSvgNode) {\n root = sandboxDocument.createElementNS(XMLNS, \"svg\");\n el = root.ownerDocument.createElementNS(root.namespaceURI, nodeName);\n attributes.forEach(([name, value]) => {\n el.setAttributeNS(null, name, value);\n });\n root.appendChild(el);\n } else {\n root = el = sandboxDocument.createElement(nodeName);\n }\n el.textContent = \" \";\n sandboxDocument.body.appendChild(root);\n const computedStyle = sandboxWindow.getComputedStyle(el, pseudoElement);\n const styles = /* @__PURE__ */ new Map();\n for (let len = computedStyle.length, i = 0; i < len; i++) {\n const name = computedStyle.item(i);\n if (ignoredStyles.includes(name))\n continue;\n styles.set(name, computedStyle.getPropertyValue(name));\n }\n sandboxDocument.body.removeChild(root);\n defaultComputedStyles.set(key, styles);\n return styles;\n}\n\nfunction getDiffStyle(style, defaultStyle, includeStyleProperties) {\n const diffStyle = /* @__PURE__ */ new Map();\n const prefixs = [];\n const prefixTree = /* @__PURE__ */ new Map();\n if (includeStyleProperties) {\n for (const name of includeStyleProperties) {\n applyTo(name);\n }\n } else {\n for (let len = style.length, i = 0; i < len; i++) {\n const name = style.item(i);\n applyTo(name);\n }\n }\n for (let len = prefixs.length, i = 0; i < len; i++) {\n prefixTree.get(prefixs[i])?.forEach((value, name) => diffStyle.set(name, value));\n }\n function applyTo(name) {\n const value = style.getPropertyValue(name);\n const priority = style.getPropertyPriority(name);\n const subIndex = name.lastIndexOf(\"-\");\n const prefix = subIndex > -1 ? name.substring(0, subIndex) : void 0;\n if (prefix) {\n let map = prefixTree.get(prefix);\n if (!map) {\n map = /* @__PURE__ */ new Map();\n prefixTree.set(prefix, map);\n }\n map.set(name, [value, priority]);\n }\n if (defaultStyle.get(name) === value && !priority)\n return;\n if (prefix) {\n prefixs.push(prefix);\n } else {\n diffStyle.set(name, [value, priority]);\n }\n }\n return diffStyle;\n}\n\nfunction copyCssStyles(node, cloned, isRoot, context) {\n const { ownerWindow, includeStyleProperties, currentParentNodeStyle } = context;\n const clonedStyle = cloned.style;\n const computedStyle = ownerWindow.getComputedStyle(node);\n const defaultStyle = getDefaultStyle(node, null, context);\n currentParentNodeStyle?.forEach((_, key) => {\n defaultStyle.delete(key);\n });\n const style = getDiffStyle(computedStyle, defaultStyle, includeStyleProperties);\n style.delete(\"transition-property\");\n style.delete(\"all\");\n style.delete(\"d\");\n style.delete(\"content\");\n if (isRoot) {\n style.delete(\"position\");\n style.delete(\"margin-top\");\n style.delete(\"margin-right\");\n style.delete(\"margin-bottom\");\n style.delete(\"margin-left\");\n style.delete(\"margin-block-start\");\n style.delete(\"margin-block-end\");\n style.delete(\"margin-inline-start\");\n style.delete(\"margin-inline-end\");\n style.set(\"box-sizing\", [\"border-box\", \"\"]);\n }\n if (style.get(\"background-clip\")?.[0] === \"text\") {\n cloned.classList.add(\"______background-clip--text\");\n }\n if (IN_CHROME) {\n if (!style.has(\"font-kerning\"))\n style.set(\"font-kerning\", [\"normal\", \"\"]);\n if ((style.get(\"overflow-x\")?.[0] === \"hidden\" || style.get(\"overflow-y\")?.[0] === \"hidden\") && style.get(\"text-overflow\")?.[0] === \"ellipsis\" && node.scrollWidth === node.clientWidth) {\n style.set(\"text-overflow\", [\"clip\", \"\"]);\n }\n }\n for (let len = clonedStyle.length, i = 0; i < len; i++) {\n clonedStyle.removeProperty(clonedStyle.item(i));\n }\n style.forEach(([value, priority], name) => {\n clonedStyle.setProperty(name, value, priority);\n });\n return style;\n}\n\nfunction copyInputValue(node, cloned) {\n if (isTextareaElement(node) || isInputElement(node) || isSelectElement(node)) {\n cloned.setAttribute(\"value\", node.value);\n }\n}\n\nconst pseudoClasses = [\n \"::before\",\n \"::after\"\n // '::placeholder', TODO\n];\nconst scrollbarPseudoClasses = [\n \"::-webkit-scrollbar\",\n \"::-webkit-scrollbar-button\",\n // '::-webkit-scrollbar:horizontal', TODO\n \"::-webkit-scrollbar-thumb\",\n \"::-webkit-scrollbar-track\",\n \"::-webkit-scrollbar-track-piece\",\n // '::-webkit-scrollbar:vertical', TODO\n \"::-webkit-scrollbar-corner\",\n \"::-webkit-resizer\"\n];\nfunction copyPseudoClass(node, cloned, copyScrollbar, context, addWordToFontFamilies) {\n const { ownerWindow, svgStyleElement, svgStyles, currentNodeStyle } = context;\n if (!svgStyleElement || !ownerWindow)\n return;\n function copyBy(pseudoClass) {\n const computedStyle = ownerWindow.getComputedStyle(node, pseudoClass);\n let content = computedStyle.getPropertyValue(\"content\");\n if (!content || content === \"none\")\n return;\n addWordToFontFamilies?.(content);\n content = content.replace(/(')|(\")|(counter\\(.+\\))/g, \"\");\n const klasses = [uuid()];\n const defaultStyle = getDefaultStyle(node, pseudoClass, context);\n currentNodeStyle?.forEach((_, key) => {\n defaultStyle.delete(key);\n });\n const style = getDiffStyle(computedStyle, defaultStyle, context.includeStyleProperties);\n style.delete(\"content\");\n style.delete(\"-webkit-locale\");\n if (style.get(\"background-clip\")?.[0] === \"text\") {\n cloned.classList.add(\"______background-clip--text\");\n }\n const cloneStyle = [\n `content: '${content}';`\n ];\n style.forEach(([value, priority], name) => {\n cloneStyle.push(`${name}: ${value}${priority ? \" !important\" : \"\"};`);\n });\n if (cloneStyle.length === 1)\n return;\n try {\n cloned.className = [cloned.className, ...klasses].join(\" \");\n } catch (err) {\n context.log.warn(\"Failed to copyPseudoClass\", err);\n return;\n }\n const cssText = cloneStyle.join(\"\\n \");\n let allClasses = svgStyles.get(cssText);\n if (!allClasses) {\n allClasses = [];\n svgStyles.set(cssText, allClasses);\n }\n allClasses.push(`.${klasses[0]}${pseudoClass}`);\n }\n pseudoClasses.forEach(copyBy);\n if (copyScrollbar)\n scrollbarPseudoClasses.forEach(copyBy);\n}\n\nconst excludeParentNodes = /* @__PURE__ */ new Set([\n \"symbol\"\n // test/fixtures/svg.symbol.html\n]);\nasync function appendChildNode(node, cloned, child, context, addWordToFontFamilies) {\n if (isElementNode(child) && (isStyleElement(child) || isScriptElement(child)))\n return;\n if (context.filter && !context.filter(child))\n return;\n if (excludeParentNodes.has(cloned.nodeName) || excludeParentNodes.has(child.nodeName)) {\n context.currentParentNodeStyle = void 0;\n } else {\n context.currentParentNodeStyle = context.currentNodeStyle;\n }\n const childCloned = await cloneNode(child, context, false, addWordToFontFamilies);\n if (context.isEnable(\"restoreScrollPosition\")) {\n restoreScrollPosition(node, childCloned);\n }\n cloned.appendChild(childCloned);\n}\nasync function cloneChildNodes(node, cloned, context, addWordToFontFamilies) {\n let firstChild = node.firstChild;\n if (isElementNode(node)) {\n if (node.shadowRoot) {\n firstChild = node.shadowRoot?.firstChild;\n context.shadowRoots.push(node.shadowRoot);\n }\n }\n for (let child = firstChild; child; child = child.nextSibling) {\n if (isCommentNode(child))\n continue;\n if (isElementNode(child) && isSlotElement(child) && typeof child.assignedNodes === \"function\") {\n const nodes = child.assignedNodes();\n for (let i = 0; i < nodes.length; i++) {\n await appendChildNode(node, cloned, nodes[i], context, addWordToFontFamilies);\n }\n } else {\n await appendChildNode(node, cloned, child, context, addWordToFontFamilies);\n }\n }\n}\nfunction restoreScrollPosition(node, chlidCloned) {\n if (!isHTMLElementNode(node) || !isHTMLElementNode(chlidCloned))\n return;\n const { scrollTop, scrollLeft } = node;\n if (!scrollTop && !scrollLeft) {\n return;\n }\n const { transform } = chlidCloned.style;\n const matrix = new DOMMatrix(transform);\n const { a, b, c, d } = matrix;\n matrix.a = 1;\n matrix.b = 0;\n matrix.c = 0;\n matrix.d = 1;\n matrix.translateSelf(-scrollLeft, -scrollTop);\n matrix.a = a;\n matrix.b = b;\n matrix.c = c;\n matrix.d = d;\n chlidCloned.style.transform = matrix.toString();\n}\nfunction applyCssStyleWithOptions(cloned, context) {\n const { backgroundColor, width, height, style: styles } = context;\n const clonedStyle = cloned.style;\n if (backgroundColor)\n clonedStyle.setProperty(\"background-color\", backgroundColor, \"important\");\n if (width)\n clonedStyle.setProperty(\"width\", `${width}px`, \"important\");\n if (height)\n clonedStyle.setProperty(\"height\", `${height}px`, \"important\");\n if (styles) {\n for (const name in styles) clonedStyle[name] = styles[name];\n }\n}\nconst NORMAL_ATTRIBUTE_RE = /^[\\w-:]+$/;\nasync function cloneNode(node, context, isRoot = false, addWordToFontFamilies) {\n const { ownerDocument, ownerWindow, fontFamilies, onCloneEachNode } = context;\n if (ownerDocument && isTextNode(node)) {\n if (addWordToFontFamilies && /\\S/.test(node.data)) {\n addWordToFontFamilies(node.data);\n }\n return ownerDocument.createTextNode(node.data);\n }\n if (ownerDocument && ownerWindow && isElementNode(node) && (isHTMLElementNode(node) || isSVGElementNode(node))) {\n const cloned2 = await cloneElement(node, context);\n if (context.isEnable(\"removeAbnormalAttributes\")) {\n const names = cloned2.getAttributeNames();\n for (let len = names.length, i = 0; i < len; i++) {\n const name = names[i];\n if (!NORMAL_ATTRIBUTE_RE.test(name)) {\n cloned2.removeAttribute(name);\n }\n }\n }\n const style = context.currentNodeStyle = copyCssStyles(node, cloned2, isRoot, context);\n if (isRoot)\n applyCssStyleWithOptions(cloned2, context);\n let copyScrollbar = false;\n if (context.isEnable(\"copyScrollbar\")) {\n const overflow = [\n style.get(\"overflow-x\")?.[0],\n style.get(\"overflow-y\")?.[0]\n ];\n copyScrollbar = overflow.includes(\"scroll\") || (overflow.includes(\"auto\") || overflow.includes(\"overlay\")) && (node.scrollHeight > node.clientHeight || node.scrollWidth > node.clientWidth);\n }\n const textTransform = style.get(\"text-transform\")?.[0];\n const families = splitFontFamily(style.get(\"font-family\")?.[0]);\n const addWordToFontFamilies2 = families ? (word) => {\n if (textTransform === \"uppercase\") {\n word = word.toUpperCase();\n } else if (textTransform === \"lowercase\") {\n word = word.toLowerCase();\n } else if (textTransform === \"capitalize\") {\n word = word[0].toUpperCase() + word.substring(1);\n }\n families.forEach((family) => {\n let fontFamily = fontFamilies.get(family);\n if (!fontFamily) {\n fontFamilies.set(family, fontFamily = /* @__PURE__ */ new Set());\n }\n word.split(\"\").forEach((text) => fontFamily.add(text));\n });\n } : void 0;\n copyPseudoClass(\n node,\n cloned2,\n copyScrollbar,\n context,\n addWordToFontFamilies2\n );\n copyInputValue(node, cloned2);\n if (!isVideoElement(node)) {\n await cloneChildNodes(\n node,\n cloned2,\n context,\n addWordToFontFamilies2\n );\n }\n await onCloneEachNode?.(cloned2);\n return cloned2;\n }\n const cloned = node.cloneNode(false);\n await cloneChildNodes(node, cloned, context);\n await onCloneEachNode?.(cloned);\n return cloned;\n}\n\nfunction destroyContext(context) {\n context.ownerDocument = void 0;\n context.ownerWindow = void 0;\n context.svgStyleElement = void 0;\n context.svgDefsElement = void 0;\n context.svgStyles.clear();\n context.defaultComputedStyles.clear();\n if (context.sandbox) {\n try {\n context.sandbox.remove();\n } catch (err) {\n context.log.warn(\"Failed to destroyContext\", err);\n }\n context.sandbox = void 0;\n }\n context.workers = [];\n context.fontFamilies.clear();\n context.fontCssTexts.clear();\n context.requests.clear();\n context.tasks = [];\n context.shadowRoots = [];\n}\n\nfunction baseFetch(options) {\n const { url, timeout, responseType, ...requestInit } = options;\n const controller = new AbortController();\n const timer = timeout ? setTimeout(() => controller.abort(), timeout) : void 0;\n return fetch(url, { signal: controller.signal, ...requestInit }).then((response) => {\n if (!response.ok) {\n throw new Error(\"Failed fetch, not 2xx response\", { cause: response });\n }\n switch (responseType) {\n case \"arrayBuffer\":\n return response.arrayBuffer();\n case \"dataUrl\":\n return response.blob().then(blobToDataUrl);\n case \"text\":\n default:\n return response.text();\n }\n }).finally(() => clearTimeout(timer));\n}\nfunction contextFetch(context, options) {\n const { url: rawUrl, requestType = \"text\", responseType = \"text\", imageDom } = options;\n let url = rawUrl;\n const {\n timeout,\n acceptOfImage,\n requests,\n fetchFn,\n fetch: {\n requestInit,\n bypassingCache,\n placeholderImage\n },\n font,\n workers,\n fontFamilies\n } = context;\n if (requestType === \"image\" && (IN_SAFARI || IN_FIREFOX)) {\n context.drawImageCount++;\n }\n let request = requests.get(rawUrl);\n if (!request) {\n if (bypassingCache) {\n if (bypassingCache instanceof RegExp && bypassingCache.test(url)) {\n url += (/\\?/.test(url) ? \"&\" : \"?\") + (/* @__PURE__ */ new Date()).getTime();\n }\n }\n const canFontMinify = requestType.startsWith(\"font\") && font && font.minify;\n const fontTexts = /* @__PURE__ */ new Set();\n if (canFontMinify) {\n const families = requestType.split(\";\")[1].split(\",\");\n families.forEach((family) => {\n if (!fontFamilies.has(family))\n return;\n fontFamilies.get(family).forEach((text) => fontTexts.add(text));\n });\n }\n const needFontMinify = canFontMinify && fontTexts.size;\n const baseFetchOptions = {\n url,\n timeout,\n responseType: needFontMinify ? \"arrayBuffer\" : responseType,\n headers: requestType === \"image\" ? { accept: acceptOfImage } : void 0,\n ...requestInit\n };\n request = {\n type: requestType,\n resolve: void 0,\n reject: void 0,\n response: null\n };\n request.response = (async () => {\n if (fetchFn && requestType === \"image\") {\n const result = await fetchFn(rawUrl);\n if (result)\n return result;\n }\n if (!IN_SAFARI && rawUrl.startsWith(\"http\") && workers.length) {\n return new Promise((resolve, reject) => {\n const worker = workers[requests.size & workers.length - 1];\n worker.postMessage({ rawUrl, ...baseFetchOptions });\n request.resolve = resolve;\n request.reject = reject;\n });\n }\n return baseFetch(baseFetchOptions);\n })().catch((error) => {\n requests.delete(rawUrl);\n if (requestType === \"image\" && placeholderImage) {\n context.log.warn(\"Failed to fetch image base64, trying to use placeholder image\", url);\n return typeof placeholderImage === \"string\" ? placeholderImage : placeholderImage(imageDom);\n }\n throw error;\n });\n requests.set(rawUrl, request);\n }\n return request.response;\n}\n\nasync function replaceCssUrlToDataUrl(cssText, baseUrl, context, isImage) {\n if (!hasCssUrl(cssText))\n return cssText;\n for (const [rawUrl, url] of parseCssUrls(cssText, baseUrl)) {\n try {\n const dataUrl = await contextFetch(\n context,\n {\n url,\n requestType: isImage ? \"image\" : \"text\",\n responseType: \"dataUrl\"\n }\n );\n cssText = cssText.replace(toRE(rawUrl), `$1${dataUrl}$3`);\n } catch (error) {\n context.log.warn(\"Failed to fetch css data url\", rawUrl, error);\n }\n }\n return cssText;\n}\nfunction hasCssUrl(cssText) {\n return /url\\((['\"]?)([^'\"]+?)\\1\\)/.test(cssText);\n}\nconst URL_RE = /url\\((['\"]?)([^'\"]+?)\\1\\)/g;\nfunction parseCssUrls(cssText, baseUrl) {\n const result = [];\n cssText.replace(URL_RE, (raw, quotation, url) => {\n result.push([url, resolveUrl(url, baseUrl)]);\n return raw;\n });\n return result.filter(([url]) => !isDataUrl(url));\n}\nfunction toRE(url) {\n const escaped = url.replace(/([.*+?^${}()|\\[\\]\\/\\\\])/g, \"\\\\$1\");\n return new RegExp(`(url\\\\(['\"]?)(${escaped})(['\"]?\\\\))`, \"g\");\n}\n\nconst properties = [\n \"background-image\",\n \"border-image-source\",\n \"-webkit-border-image\",\n \"-webkit-mask-image\",\n \"list-style-image\"\n];\nfunction embedCssStyleImage(style, context) {\n return properties.map((property) => {\n const value = style.getPropertyValue(property);\n if (!value || value === \"none\") {\n return null;\n }\n if (IN_SAFARI || IN_FIREFOX) {\n context.drawImageCount++;\n }\n return replaceCssUrlToDataUrl(value, null, context, true).then((newValue) => {\n if (!newValue || value === newValue)\n return;\n style.setProperty(\n property,\n newValue,\n style.getPropertyPriority(property)\n );\n });\n }).filter(Boolean);\n}\n\nfunction embedImageElement(cloned, context) {\n if (isImageElement(cloned)) {\n const originalSrc = cloned.currentSrc || cloned.src;\n if (!isDataUrl(originalSrc)) {\n return [\n contextFetch(context, {\n url: originalSrc,\n imageDom: cloned,\n requestType: \"image\",\n responseType: \"dataUrl\"\n }).then((url) => {\n if (!url)\n return;\n cloned.srcset = \"\";\n cloned.dataset.originalSrc = originalSrc;\n cloned.src = url || \"\";\n })\n ];\n }\n if (IN_SAFARI || IN_FIREFOX) {\n context.drawImageCount++;\n }\n } else if (isSVGElementNode(cloned) && !isDataUrl(cloned.href.baseVal)) {\n const originalSrc = cloned.href.baseVal;\n return [\n contextFetch(context, {\n url: originalSrc,\n imageDom: cloned,\n requestType: \"image\",\n responseType: \"dataUrl\"\n }).then((url) => {\n if (!url)\n return;\n cloned.dataset.originalSrc = originalSrc;\n cloned.href.baseVal = url || \"\";\n })\n ];\n }\n return [];\n}\n\nfunction embedSvgUse(cloned, context) {\n const { ownerDocument, svgDefsElement } = context;\n const href = cloned.getAttribute(\"href\") ?? cloned.getAttribute(\"xlink:href\");\n if (!href)\n return [];\n const [svgUrl, id] = href.split(\"#\");\n if (id) {\n const query = `#${id}`;\n const definition = context.shadowRoots.reduce(\n (res, root) => {\n return res ?? root.querySelector(`svg ${query}`);\n },\n ownerDocument?.querySelector(`svg ${query}`)\n );\n if (svgUrl) {\n cloned.setAttribute(\"href\", query);\n }\n if (svgDefsElement?.querySelector(query))\n return [];\n if (definition) {\n svgDefsElement?.appendChild(definition.cloneNode(true));\n return [];\n } else if (svgUrl) {\n return [\n contextFetch(context, {\n url: svgUrl,\n responseType: \"text\"\n }).then((svgData) => {\n svgDefsElement?.insertAdjacentHTML(\"beforeend\", svgData);\n })\n ];\n }\n }\n return [];\n}\n\nfunction embedNode(cloned, context) {\n const { tasks } = context;\n if (isElementNode(cloned)) {\n if (isImageElement(cloned) || isSVGImageElementNode(cloned)) {\n tasks.push(...embedImageElement(cloned, context));\n }\n if (isSVGUseElementNode(cloned)) {\n tasks.push(...embedSvgUse(cloned, context));\n }\n }\n if (isHTMLElementNode(cloned)) {\n tasks.push(...embedCssStyleImage(cloned.style, context));\n }\n cloned.childNodes.forEach((child) => {\n embedNode(child, context);\n });\n}\n\nasync function embedWebFont(clone, context) {\n const {\n ownerDocument,\n svgStyleElement,\n fontFamilies,\n fontCssTexts,\n tasks,\n font\n } = context;\n if (!ownerDocument || !svgStyleElement || !fontFamilies.size) {\n return;\n }\n if (font && font.cssText) {\n const cssText = filterPreferredFormat(font.cssText, context);\n svgStyleElement.appendChild(ownerDocument.createTextNode(`${cssText}\n`));\n } else {\n const styleSheets = Array.from(ownerDocument.styleSheets).filter((styleSheet) => {\n try {\n return \"cssRules\" in styleSheet && Boolean(styleSheet.cssRules.length);\n } catch (error) {\n context.log.warn(`Error while reading CSS rules from ${styleSheet.href}`, error);\n return false;\n }\n });\n const tempDoc = ownerDocument.implementation.createHTMLDocument(\"\");\n const tempStyleEl = tempDoc.createElement(\"style\");\n tempDoc.head.appendChild(tempStyleEl);\n const tempStyleSheet = tempStyleEl.sheet;\n await Promise.all(\n styleSheets.flatMap((styleSheet) => {\n return Array.from(styleSheet.cssRules).map(async (cssRule) => {\n if (isCSSImportRule(cssRule)) {\n const baseUrl = cssRule.href;\n let cssText = \"\";\n try {\n cssText = await contextFetch(context, {\n url: baseUrl,\n requestType: \"text\",\n responseType: \"text\"\n });\n } catch (error) {\n context.log.warn(`Error fetch remote css import from ${baseUrl}`, error);\n }\n const replacedCssText = cssText.replace(\n URL_RE,\n (raw, quotation, url) => raw.replace(url, resolveUrl(url, baseUrl))\n );\n for (const rule of parseCss(replacedCssText)) {\n try {\n tempStyleSheet.insertRule(rule, tempStyleSheet.cssRules.length);\n } catch (error) {\n context.log.warn(\"Error inserting rule from remote css import\", { rule, error });\n }\n }\n }\n });\n })\n );\n if (tempStyleSheet.cssRules.length)\n styleSheets.push(tempStyleSheet);\n const cssRules = [];\n styleSheets.forEach((sheet) => {\n unwrapCssLayers(sheet.cssRules, cssRules);\n });\n cssRules.filter((cssRule) => isCssFontFaceRule(cssRule) && hasCssUrl(cssRule.style.getPropertyValue(\"src\")) && splitFontFamily(cssRule.style.getPropertyValue(\"font-family\"))?.some((val) => fontFamilies.has(val))).forEach((value) => {\n const rule = value;\n const cssText = fontCssTexts.get(rule.cssText);\n if (cssText) {\n svgStyleElement.appendChild(ownerDocument.createTextNode(`${cssText}\n`));\n } else {\n tasks.push(\n replaceCssUrlToDataUrl(\n rule.cssText,\n rule.parentStyleSheet ? rule.parentStyleSheet.href : null,\n context\n ).then((cssText2) => {\n cssText2 = filterPreferredFormat(cssText2, context);\n fontCssTexts.set(rule.cssText, cssText2);\n svgStyleElement.appendChild(ownerDocument.createTextNode(`${cssText2}\n`));\n })\n );\n }\n });\n }\n}\nconst COMMENTS_RE = /(\\/\\*[\\s\\S]*?\\*\\/)/g;\nconst KEYFRAMES_RE = /((@.*?keyframes [\\s\\S]*?){([\\s\\S]*?}\\s*?)})/gi;\nfunction parseCss(source) {\n if (source == null)\n return [];\n const result = [];\n let cssText = source.replace(COMMENTS_RE, \"\");\n while (true) {\n const matches = KEYFRAMES_RE.exec(cssText);\n if (!matches)\n break;\n result.push(matches[0]);\n }\n cssText = cssText.replace(KEYFRAMES_RE, \"\");\n const IMPORT_RE = /@import[\\s\\S]*?url\\([^)]*\\)[\\s\\S]*?;/gi;\n const UNIFIED_RE = new RegExp(\n // eslint-disable-next-line\n \"((\\\\s*?(?:\\\\/\\\\*[\\\\s\\\\S]*?\\\\*\\\\/)?\\\\s*?@media[\\\\s\\\\S]*?){([\\\\s\\\\S]*?)}\\\\s*?})|(([\\\\s\\\\S]*?){([\\\\s\\\\S]*?)})\",\n \"gi\"\n );\n while (true) {\n let matches = IMPORT_RE.exec(cssText);\n if (!matches) {\n matches = UNIFIED_RE.exec(cssText);\n if (!matches) {\n break;\n } else {\n IMPORT_RE.lastIndex = UNIFIED_RE.lastIndex;\n }\n } else {\n UNIFIED_RE.lastIndex = IMPORT_RE.lastIndex;\n }\n result.push(matches[0]);\n }\n return result;\n}\nconst URL_WITH_FORMAT_RE = /url\\([^)]+\\)\\s*format\\(([\"']?)([^\"']+)\\1\\)/g;\nconst FONT_SRC_RE = /src:\\s*(?:url\\([^)]+\\)\\s*format\\([^)]+\\)[,;]\\s*)+/g;\nfunction filterPreferredFormat(str, context) {\n const { font } = context;\n const preferredFormat = font ? font?.preferredFormat : void 0;\n return preferredFormat ? str.replace(FONT_SRC_RE, (match) => {\n while (true) {\n const [src, , format] = URL_WITH_FORMAT_RE.exec(match) || [];\n if (!format)\n return \"\";\n if (format === preferredFormat)\n return `src: ${src};`;\n }\n }) : str;\n}\nfunction unwrapCssLayers(rules, out = []) {\n for (const rule of Array.from(rules)) {\n if (isLayerBlockRule(rule)) {\n out.push(...unwrapCssLayers(rule.cssRules));\n } else if (\"cssRules\" in rule) {\n unwrapCssLayers(rule.cssRules, out);\n } else {\n out.push(rule);\n }\n }\n return out;\n}\n\nconst SVG_EXTERNAL_RESOURCE_REGEX = /\\bx?link:?href\\s*=\\s*[\"'](?!data:)[^\"']+[\"']/i;\nfunction svgHasExternalResources(svg) {\n return SVG_EXTERNAL_RESOURCE_REGEX.test(svg.innerHTML);\n}\nasync function domToForeignObjectSvg(node, options) {\n const context = await orCreateContext(node, options);\n if (isElementNode(context.node) && isSVGElementNode(context.node) && !svgHasExternalResources(context.node))\n return context.node;\n const {\n ownerDocument,\n log,\n tasks,\n svgStyleElement,\n svgDefsElement,\n svgStyles,\n font,\n progress,\n autoDestruct,\n onCloneNode,\n onEmbedNode,\n onCreateForeignObjectSvg\n } = context;\n log.time(\"clone node\");\n const clone = await cloneNode(context.node, context, true);\n if (svgStyleElement && ownerDocument) {\n let allCssText = \"\";\n svgStyles.forEach((klasses, cssText) => {\n allCssText += `${klasses.join(\",\\n\")} {\n ${cssText}\n}\n`;\n });\n svgStyleElement.appendChild(ownerDocument.createTextNode(allCssText));\n }\n log.timeEnd(\"clone node\");\n await onCloneNode?.(clone);\n if (font !== false && isElementNode(clone)) {\n log.time(\"embed web font\");\n await embedWebFont(clone, context);\n log.timeEnd(\"embed web font\");\n }\n log.time(\"embed node\");\n embedNode(clone, context);\n const count = tasks.length;\n let current = 0;\n const runTask = async () => {\n while (true) {\n const task = tasks.pop();\n if (!task)\n break;\n try {\n await task;\n } catch (error) {\n context.log.warn(\"Failed to run task\", error);\n }\n progress?.(++current, count);\n }\n };\n progress?.(current, count);\n await Promise.all([...Array.from({ length: 4 })].map(runTask));\n log.timeEnd(\"embed node\");\n await onEmbedNode?.(clone);\n const svg = createForeignObjectSvg(clone, context);\n svgDefsElement && svg.insertBefore(svgDefsElement, svg.children[0]);\n svgStyleElement && svg.insertBefore(svgStyleElement, svg.children[0]);\n autoDestruct && destroyContext(context);\n await onCreateForeignObjectSvg?.(svg);\n return svg;\n}\nfunction createForeignObjectSvg(clone, context) {\n const { width, height } = context;\n const svg = createSvg(width, height, clone.ownerDocument);\n const foreignObject = svg.ownerDocument.createElementNS(svg.namespaceURI, \"foreignObject\");\n foreignObject.setAttributeNS(null, \"x\", \"0%\");\n foreignObject.setAttributeNS(null, \"y\", \"0%\");\n foreignObject.setAttributeNS(null, \"width\", \"100%\");\n foreignObject.setAttributeNS(null, \"height\", \"100%\");\n foreignObject.append(clone);\n svg.appendChild(foreignObject);\n return svg;\n}\n\nasync function domToCanvas(node, options) {\n const context = await orCreateContext(node, options);\n const svg = await domToForeignObjectSvg(context);\n const dataUrl = svgToDataUrl(svg, context.isEnable(\"removeControlCharacter\"));\n if (!context.autoDestruct) {\n context.svgStyleElement = createStyleElement(context.ownerDocument);\n context.svgDefsElement = context.ownerDocument?.createElementNS(XMLNS, \"defs\");\n context.svgStyles.clear();\n }\n const image = createImage(dataUrl, svg.ownerDocument);\n return await imageToCanvas(image, context);\n}\n\nasync function domToBlob(node, options) {\n const context = await orCreateContext(node, options);\n const { log, type, quality, dpi } = context;\n const canvas = await domToCanvas(context);\n log.time(\"canvas to blob\");\n const blob = await canvasToBlob(canvas, type, quality);\n if ([\"image/png\", \"image/jpeg\"].includes(type) && dpi) {\n const arrayBuffer = await blobToArrayBuffer(blob.slice(0, 33));\n let uint8Array = new Uint8Array(arrayBuffer);\n if (type === \"image/png\") {\n uint8Array = changePngDpi(uint8Array, dpi);\n } else if (type === \"image/jpeg\") {\n uint8Array = changeJpegDpi(uint8Array, dpi);\n }\n log.timeEnd(\"canvas to blob\");\n return new Blob([uint8Array, blob.slice(33)], { type });\n }\n log.timeEnd(\"canvas to blob\");\n return blob;\n}\n\nasync function domToDataUrl(node, options) {\n const context = await orCreateContext(node, options);\n const { log, quality, type, dpi } = context;\n const canvas = await domToCanvas(context);\n log.time(\"canvas to data url\");\n let dataUrl = canvas.toDataURL(type, quality);\n if ([\"image/png\", \"image/jpeg\"].includes(type) && dpi && SUPPORT_ATOB && SUPPORT_BTOA) {\n const [format, body] = dataUrl.split(\",\");\n let headerLength = 0;\n let overwritepHYs = false;\n if (type === \"image/png\") {\n const b64Index = detectPhysChunkFromDataUrl(body);\n if (b64Index >= 0) {\n headerLength = Math.ceil((b64Index + 28) / 3) * 4;\n overwritepHYs = true;\n } else {\n headerLength = 33 / 3 * 4;\n }\n } else if (type === \"image/jpeg\") {\n headerLength = 18 / 3 * 4;\n }\n const stringHeader = body.substring(0, headerLength);\n const restOfData = body.substring(headerLength);\n const headerBytes = window.atob(stringHeader);\n const uint8Array = new Uint8Array(headerBytes.length);\n for (let i = 0; i < uint8Array.length; i++) {\n uint8Array[i] = headerBytes.charCodeAt(i);\n }\n const finalArray = type === \"image/png\" ? changePngDpi(uint8Array, dpi, overwritepHYs) : changeJpegDpi(uint8Array, dpi);\n const base64Header = window.btoa(String.fromCharCode(...finalArray));\n dataUrl = [format, \",\", base64Header, restOfData].join(\"\");\n }\n log.timeEnd(\"canvas to data url\");\n return dataUrl;\n}\n\nasync function domToSvg(node, options) {\n const context = await orCreateContext(node, options);\n const { width, height, ownerDocument } = context;\n const dataUrl = await domToDataUrl(context);\n const svg = createSvg(width, height, ownerDocument);\n const svgImage = svg.ownerDocument.createElementNS(svg.namespaceURI, \"image\");\n svgImage.setAttributeNS(null, \"href\", dataUrl);\n svgImage.setAttributeNS(null, \"height\", \"100%\");\n svgImage.setAttributeNS(null, \"width\", \"100%\");\n svg.appendChild(svgImage);\n return svgToDataUrl(svg, context.isEnable(\"removeControlCharacter\"));\n}\n\nasync function domToImage(node, options) {\n const context = await orCreateContext(node, options);\n const { ownerDocument, width, height, scale, type } = context;\n const url = type === \"image/svg+xml\" ? await domToSvg(context) : await domToDataUrl(context);\n const image = createImage(url, ownerDocument);\n image.width = Math.floor(width * scale);\n image.height = Math.floor(height * scale);\n image.style.width = `${width}px`;\n image.style.height = `${height}px`;\n return image;\n}\n\nasync function domToJpeg(node, options) {\n return domToDataUrl(\n await orCreateContext(node, { ...options, type: \"image/jpeg\" })\n );\n}\n\nasync function domToPixel(node, options) {\n const context = await orCreateContext(node, options);\n const canvas = await domToCanvas(context);\n return canvas.getContext(\"2d\").getImageData(0, 0, canvas.width, canvas.height).data;\n}\n\nasync function domToPng(node, options) {\n return domToDataUrl(\n await orCreateContext(node, { ...options, type: \"image/png\" })\n );\n}\n\nasync function domToWebp(node, options) {\n return domToDataUrl(\n await orCreateContext(node, { ...options, type: \"image/webp\" })\n );\n}\n\nexport { createContext, destroyContext, domToBlob, domToCanvas, domToDataUrl, domToForeignObjectSvg, domToImage, domToJpeg, domToPixel, domToPng, domToSvg, domToWebp, loadMedia, waitUntilLoad };\n","// Masquage du replay rrweb À LA CAPTURE (ECH-383), selon la politique du projet\n// (ECH-382) transmise par le Lab avec l'armement (`leesto_mask`, lu au boot).\n//\n// Masquer seulement à l'affichage du replay ne protégerait rien : les données\n// en clair auraient déjà quitté le navigateur. Tout se joue donc ici, avant que\n// l'event n'entre dans le tampon ou ne soit posté au shell :\n// 1. les options de `record()` (texte, saisies, médias bloqués) ;\n// 2. une passe sur chaque event émis pour les ATTRIBUTS porteurs de texte\n// (`placeholder`, `title`, `alt`, `aria-label`…) que rrweb 2.1 ne masque\n// jamais, pour les ATTRIBUTS porteurs d'adresse (`href`, `src`, `srcset`,\n// `url()` d'un `style`, à tous les niveaux : query et fragment portent des\n// jetons, un `mailto:` une adresse), pour les `data-*` (données\n// personnelles repérées par `redactPII`), et pour l'URL du Meta.\n//\n// Invariant : les exclusions posées par le client (`CLIENT_MASK_SELECTORS`)\n// s'appliquent à TOUS les niveaux. Un niveau ne fait qu'élargir le masquage.\n\nimport { redactUrl } from \"@leesto/shared/diagnostics\";\nimport { redactPII } from \"@leesto/shared/redact\";\nimport type { ReplayMaskPolicy } from \"@leesto/shared/replayMask\";\nimport { redactLink, redactSrcset, redactStyleUrls } from \"@leesto/shared/urlRedact\";\n\n// --- Contrat client (cf. `CLIENT_MASK_SELECTORS`) ---------------------------\n/** Élément ENTIER jamais capturé (placeholder aux dimensions de l'élément). */\nexport const CLIENT_BLOCK_CLASS = \"leesto-mask\";\nexport const CLIENT_BLOCK_SELECTOR = \"[data-leesto-block]\";\n/** Structure gardée, TEXTE masqué. */\nexport const CLIENT_MASK_TEXT_CLASS = \"leesto-mask-text\";\nexport const CLIENT_MASK_TEXT_SELECTOR = \"[data-private]\";\nconst CLIENT_TEXT_MASKED = `.${CLIENT_MASK_TEXT_CLASS}, ${CLIENT_MASK_TEXT_SELECTOR}`;\n\n/** Médias bloqués quand le texte est masqué : rrweb les remplace par un\n * placeholder aux dimensions de l'élément (`rr_width`/`rr_height`), la mise\n * en page du replay reste juste. Une photo de profil ou un document scanné\n * en dit autant qu'un texte. Les images de fond CSS ne sont pas couvertes. */\nexport const MEDIA_BLOCK_SELECTOR =\n 'img, picture, video, canvas, object, embed, svg image, input[type=\"image\"]';\n\n/** Libellés gardés en clair par `labels_visible` : boutons et liens. */\nexport const LABEL_SELECTOR =\n 'button, a, [role=\"button\"], [role=\"link\"], input[type=\"button\"], input[type=\"submit\"], input[type=\"reset\"]';\n\n/** Au-delà, l'élément « bouton/lien » n'est pas un libellé mais un conteneur\n * (carte entière cliquable, ligne de tableau en lien…) : son texte est masqué. */\nexport const MAX_LABEL_CHARS = 80;\n\n/** Champs de saisie : leur contenu est masqué à tous les niveaux. */\nconst FORM_FIELD_SELECTOR =\n 'input:not([type=\"button\"]):not([type=\"submit\"]):not([type=\"reset\"]), textarea, select';\n\n/** Même règle que le masquage natif de rrweb : chaque caractère visible\n * devient `*`, les espaces restent (la mise en page du replay est gardée). */\nexport function maskText(text: string): string {\n return text.replace(/\\S/g, \"*\");\n}\n\nfunction closestSafe(el: Element, selector: string): Element | null {\n try {\n return el.closest(selector);\n } catch {\n return null;\n }\n}\n\n/** Texte rendu illisible par une exclusion posée par le client. */\nexport function isClientMasked(el: Element): boolean {\n return closestSafe(el, CLIENT_TEXT_MASKED) !== null;\n}\n\nconst CLIENT_EXCLUDED = `.${CLIENT_BLOCK_CLASS}, ${CLIENT_BLOCK_SELECTOR}, ${CLIENT_TEXT_MASKED}`;\n\n/** Sous une exclusion client, quelle qu'elle soit : zone exclue en entier\n * (`.leesto-mask`, `[data-leesto-block]`) ou texte masqué. Rien de ce qui s'y\n * trouve (texte, adresse d'image) ne quitte l'app. Toute erreur ⇒ true (exclu). */\nexport function isClientExcluded(el: Element): boolean {\n try {\n return el.closest(CLIENT_EXCLUDED) !== null;\n } catch {\n return true;\n }\n}\n\n/** True si `el` (ou son ancêtre bouton/lien) est un libellé court, hors\n * exclusion client et hors champ de saisie. Toute erreur ⇒ false (masqué). */\nexport function isClearLabel(el: Element | null | undefined): boolean {\n if (!el || typeof el.closest !== \"function\") return false;\n try {\n if (isClientMasked(el) || el.matches(FORM_FIELD_SELECTOR)) return false;\n const label = el.closest(LABEL_SELECTOR);\n if (!label) return false;\n const text = label.textContent ?? \"\";\n return text.trim().length <= MAX_LABEL_CHARS;\n } catch {\n return false;\n }\n}\n\nexport type RrwebMaskOptions = {\n maskAllInputs: true;\n maskInputOptions: { password: true; email: true; tel: true; text: true };\n blockClass: string;\n blockSelector: string;\n maskTextClass: string;\n maskTextSelector: string;\n maskTextFn?: (text: string, element: HTMLElement | null) => string;\n};\n\nconst BASE_OPTIONS = {\n maskAllInputs: true,\n maskInputOptions: { password: true, email: true, tel: true, text: true },\n blockClass: CLIENT_BLOCK_CLASS,\n maskTextClass: CLIENT_MASK_TEXT_CLASS,\n} as const;\n\n/**\n * Options de masquage de `record()` pour une politique. Fonction pure, utilisée\n * par les DEUX recorders (tampon glissant et enregistrement manuel).\n *\n * - `mask_all` : tout le texte (`maskTextSelector: \"*\"`, appliqué par rrweb au\n * full snapshot ET aux mutations), toutes les saisies, médias bloqués.\n * - `labels_visible` : idem, sauf le texte des boutons et des liens, rendu en\n * clair par `maskTextFn` (rrweb n'a pas de « sauf » dans ses sélecteurs : le\n * sélecteur `*` désigne tout le texte à masquer, `maskTextFn` reçoit l'élément\n * parent et décide).\n * - `inputs_only` : comportement historique, saisies masquées, texte visible.\n *\n * Une valeur inconnue (appel non typé) donne `mask_all`.\n */\nexport function recordMaskOptions(policy: ReplayMaskPolicy): RrwebMaskOptions {\n if (policy === \"inputs_only\") {\n return {\n ...BASE_OPTIONS,\n blockSelector: CLIENT_BLOCK_SELECTOR,\n maskTextSelector: CLIENT_MASK_TEXT_SELECTOR,\n };\n }\n const strict = {\n ...BASE_OPTIONS,\n blockSelector: `${CLIENT_BLOCK_SELECTOR}, ${MEDIA_BLOCK_SELECTOR}`,\n maskTextSelector: \"*\",\n };\n if (policy === \"labels_visible\") {\n return {\n ...strict,\n maskTextFn: (text, element) => (isClearLabel(element) ? text : maskText(text)),\n };\n }\n return strict;\n}\n\n// --- Attributs porteurs de texte ---------------------------------------------\n// rrweb 2.1 recopie les attributs tels quels (seule la `value` des champs est\n// masquée) : un `placeholder=\"Jean Dupont\"` ou un `title` d'avatar partiraient\n// en clair même avec `maskTextSelector: \"*\"`.\n\n/** Attributs affichés ou lus à l'écran, masqués selon la même règle que le texte. */\nexport const TEXT_ATTRIBUTES = new Set([\n \"placeholder\",\n \"title\",\n \"alt\",\n \"label\",\n \"aria-label\",\n \"aria-description\",\n \"aria-placeholder\",\n \"aria-roledescription\",\n \"aria-valuetext\",\n]);\n\n/** Attributs porteurs d'adresse (ECH-506) : réduits à origine et chemin. */\nexport const URL_ATTRIBUTES = new Set([\n \"href\",\n \"src\",\n \"action\",\n \"formaction\",\n \"poster\",\n \"cite\",\n \"background\",\n \"data\",\n \"ping\",\n \"longdesc\",\n \"xlink:href\",\n]);\n\n/** Valeur expurgée d'un attribut d'adresse, de style ou `data-*` ; `undefined`\n * pour un autre attribut. Indépendant de la politique : un niveau n'élargit\n * que le masquage du texte. */\nexport function redactAddressAttribute(name: string, value: string): string | undefined {\n if (name === \"srcset\") return redactSrcset(value);\n if (name === \"style\") return redactStyleUrls(value);\n if (URL_ATTRIBUTES.has(name)) return redactLink(value);\n // `data-state=\"open\"` sert au CSS : seules les données personnelles partent.\n if (name.startsWith(\"data-\")) return redactPII(value);\n return undefined;\n}\n\ntype SerializedNode = {\n type?: number;\n id?: number;\n tagName?: string;\n attributes?: Record<string, unknown>;\n childNodes?: SerializedNode[];\n};\n\ntype RrwebEventLike = {\n type?: number;\n data?: {\n source?: number;\n href?: unknown;\n node?: SerializedNode;\n adds?: { node?: SerializedNode }[];\n attributes?: { id?: number; attributes?: Record<string, unknown> }[];\n };\n};\n\nconst EVENT_FULL_SNAPSHOT = 2;\nconst EVENT_INCREMENTAL = 3;\nconst EVENT_META = 4;\nconst SOURCE_MUTATION = 0;\nconst NODE_ELEMENT = 2;\n\nfunction isFormField(el: Element | null, tagName: string, attrs: Record<string, unknown>): boolean {\n if (el) {\n try {\n return el.matches(FORM_FIELD_SELECTOR);\n } catch {\n return true;\n }\n }\n const tag = tagName.toLowerCase();\n if (tag === \"textarea\" || tag === \"select\") return true;\n if (tag !== \"input\") return false;\n const type = String(attrs.type ?? \"\").toLowerCase();\n return type !== \"button\" && type !== \"submit\" && type !== \"reset\";\n}\n\n/**\n * Masque les attributs porteurs de texte d'un event rrweb, EN PLACE (l'event\n * sort tout juste de rrweb, personne d'autre ne le tient). Retire aussi les\n * paramètres techniques du Lab de l'URL du Meta.\n *\n * `getNode` résout l'élément vivant d'un id rrweb (`record.mirror.getNode`) :\n * la décision se prend sur le vrai DOM (ancêtres compris), comme `maskTextFn`.\n * Élément introuvable ⇒ masqué.\n */\nexport function redactRrwebEvent<T>(\n event: T,\n policy: ReplayMaskPolicy,\n getNode: (id: number) => Node | null | undefined,\n): T {\n const e = event as RrwebEventLike;\n if (!e || typeof e !== \"object\" || !e.data) return event;\n\n const elementOf = (id: unknown): Element | null => {\n if (typeof id !== \"number\") return null;\n try {\n const node = getNode(id);\n return node && node.nodeType === 1 ? (node as Element) : null;\n } catch {\n return null;\n }\n };\n\n /** True si l'attribut peut rester en clair. */\n const keep = (\n el: Element | null,\n name: string,\n tagName: string,\n attrs: Record<string, unknown>,\n ) => {\n // `value` d'un champ : une saisie, masquée à tous les niveaux (rrweb l'a\n // déjà fait pour la valeur courante ; l'attribut initial peut différer).\n if (name === \"value\") {\n if (isFormField(el, tagName, attrs)) return false;\n } else if (!TEXT_ATTRIBUTES.has(name)) {\n return true;\n }\n if (!el || isClientMasked(el)) return false;\n if (policy === \"inputs_only\") return true;\n if (policy === \"labels_visible\") return isClearLabel(el);\n return false;\n };\n\n const redactAttrs = (\n el: Element | null,\n tagName: string,\n attrs: Record<string, unknown> | undefined,\n ) => {\n if (!attrs) return;\n for (const name of Object.keys(attrs)) {\n const value = attrs[name];\n if (typeof value !== \"string\" || !value) continue;\n const address = redactAddressAttribute(name, value);\n if (address !== undefined) {\n attrs[name] = address;\n continue;\n }\n if (name !== \"value\" && !TEXT_ATTRIBUTES.has(name)) continue;\n if (!keep(el, name, tagName, attrs)) attrs[name] = maskText(value);\n }\n };\n\n const walk = (root: SerializedNode | undefined) => {\n const stack = root ? [root] : [];\n while (stack.length > 0) {\n const node = stack.pop() as SerializedNode;\n if (node.type === NODE_ELEMENT && node.attributes) {\n redactAttrs(elementOf(node.id), String(node.tagName ?? \"\"), node.attributes);\n }\n if (Array.isArray(node.childNodes)) stack.push(...node.childNodes);\n }\n };\n\n const d = e.data;\n if (e.type === EVENT_META && typeof d.href === \"string\") {\n d.href = redactUrl(d.href);\n } else if (e.type === EVENT_FULL_SNAPSHOT) {\n walk(d.node);\n } else if (e.type === EVENT_INCREMENTAL && d.source === SOURCE_MUTATION) {\n for (const add of d.adds ?? []) walk(add.node);\n for (const change of d.attributes ?? []) {\n const el = elementOf(change.id);\n redactAttrs(el, el?.tagName ?? \"\", change.attributes);\n }\n }\n return event;\n}\n","// Masquage de la capture d'écran (ECH-506). Même contrat client que rrweb :\n// valeurs des champs masquées partout, texte des zones `[data-private]` /\n// `.leesto-mask-text` masqué ; les zones `.leesto-mask` / `[data-leesto-block]`\n// sont recouvertes : par un cache posé sur la page pour la capture de l'écran\n// (`captureNow`), par un cache dans le clone pour la capture d'un élément\n// (`{ blocks: true }`).\n//\n// Le reste du texte de la page reste lisible, quelle que soit la politique du\n// projet : le testeur prend la capture lui-même, la voit et peut flouter avant\n// d'envoyer, et une capture sans texte ne montrerait plus le problème.\n//\n// modern-screenshot ne relie pas un clone à son nœud d'origine : les éléments\n// à masquer reçoivent une marque le temps de la capture (recopiée par le\n// clone), puis `maskCapturedClone` agit sur le CLONE seulement. Le DOM du\n// client n'est jamais réécrit ; les marques sont retirées dans le `finally`.\n\nimport {\n CLIENT_BLOCK_CLASS,\n CLIENT_BLOCK_SELECTOR,\n CLIENT_MASK_TEXT_CLASS,\n CLIENT_MASK_TEXT_SELECTOR,\n maskText,\n} from \"./rrweb-mask\";\n\nconst FIELD_MARK = \"data-leesto-capture-field\";\nconst TEXT_MARK = \"data-leesto-capture-text\";\n/** Valeur : « largeur x hauteur » du bloc, pour un cache de même taille. */\nconst BLOCK_MARK = \"data-leesto-capture-block\";\n\n/** Zones que le client exclut de toute capture (même contrat que rrweb). */\nexport const CLIENT_BLOCKED = `.${CLIENT_BLOCK_CLASS}, ${CLIENT_BLOCK_SELECTOR}`;\n\n/** Champs dont la valeur est une saisie : cases, curseurs et boutons exclus. */\nconst CAPTURED_FIELD_SELECTOR =\n 'input:not([type=\"button\"]):not([type=\"submit\"]):not([type=\"reset\"]):not([type=\"hidden\"]):not([type=\"checkbox\"]):not([type=\"radio\"]):not([type=\"range\"]):not([type=\"color\"]):not([type=\"image\"]), textarea, select';\n\nconst CLIENT_TEXT_MASKED = `.${CLIENT_MASK_TEXT_CLASS}, ${CLIENT_MASK_TEXT_SELECTOR}`;\n\n/** Marque, sous `root` (inclus), ce que la capture doit masquer. Avec\n * `blocks`, marque aussi les zones exclues sous `root`, que le clone remplace\n * par un cache. Renvoie la fonction qui retire les marques posées. */\nexport function markCaptureMasks(root: Element, options: { blocks?: boolean } = {}): () => void {\n const marked: Array<[Element, string]> = [];\n const mark = (el: Element, attribute: string, value = \"\") => {\n if (el.hasAttribute(attribute)) return;\n el.setAttribute(attribute, value);\n marked.push([el, attribute]);\n };\n const within = (selector: string) => [\n ...(root.matches(selector) ? [root] : []),\n ...root.querySelectorAll(selector),\n ];\n for (const el of within(CAPTURED_FIELD_SELECTOR)) mark(el, FIELD_MARK);\n for (const el of within(CLIENT_TEXT_MASKED)) mark(el, TEXT_MARK);\n if (options.blocks) {\n for (const el of root.querySelectorAll(CLIENT_BLOCKED)) {\n const box = el.getBoundingClientRect();\n mark(el, BLOCK_MARK, `${Math.round(box.width)}x${Math.round(box.height)}`);\n }\n }\n return () => {\n for (const [el, attribute] of marked) el.removeAttribute(attribute);\n };\n}\n\nfunction maskTextNodes(el: Element): void {\n const doc = el.ownerDocument;\n const walker = doc.createTreeWalker(el, 4 /* NodeFilter.SHOW_TEXT */);\n for (let node = walker.nextNode(); node; node = walker.nextNode()) {\n const text = node as Text;\n text.data = maskText(text.data);\n }\n}\n\nfunction maskField(el: Element): void {\n const tag = el.tagName.toLowerCase();\n if (tag === \"select\") {\n for (const option of el.querySelectorAll(\"option\")) maskTextNodes(option);\n return;\n }\n // modern-screenshot recopie la valeur courante dans l'attribut `value`.\n const value = el.getAttribute(\"value\");\n if (value) el.setAttribute(\"value\", maskText(value));\n if (tag === \"textarea\") maskTextNodes(el);\n}\n\n/** Masque, dans l'arbre CLONÉ que va rendre la capture, les champs et les\n * zones marqués par `markCaptureMasks`, et retire les marques du clone. */\nexport function maskCapturedClone(clone: Node): void {\n if (clone.nodeType !== 1) return;\n const root = clone as Element;\n const find = (attribute: string) => [\n ...(root.hasAttribute(attribute) ? [root] : []),\n ...root.querySelectorAll(`[${attribute}]`),\n ];\n for (const el of find(FIELD_MARK)) {\n maskField(el);\n el.removeAttribute(FIELD_MARK);\n }\n for (const el of find(TEXT_MARK)) {\n maskTextNodes(el);\n el.removeAttribute(TEXT_MARK);\n }\n for (const el of root.querySelectorAll(`[${BLOCK_MARK}]`)) {\n const [width, height] = (el.getAttribute(BLOCK_MARK) ?? \"0x0\").split(\"x\");\n const cover = el.ownerDocument.createElement(\"div\");\n cover.setAttribute(\n \"style\",\n `display:inline-block;width:${width}px;height:${height}px;background:#a1a1aa`,\n );\n el.replaceWith(cover);\n }\n}\n","// Capture d'écran par défaut du connecteur. Module chargé à la demande\n// (`import(\"./capture\")` dans app-client.ts) : avec modern-screenshot, il forme\n// un chunk que seule la première capture télécharge.\n\nimport { domToPng } from \"modern-screenshot\";\nimport { CLIENT_BLOCKED, markCaptureMasks, maskCapturedClone } from \"./capture-mask\";\nimport { CLIENT_BLOCK_CLASS, CLIENT_BLOCK_SELECTOR } from \"./rrweb-mask\";\n\n/** Effective page background: dark apps usually paint it on <html> (or a root\n * container), leaving <body> transparent. Forcing white here would bleed\n * through wherever body doesn't paint — the \"white band\" around the capture.\n * Resolve body → html → white so the shot matches what the user sees. */\nfunction pageBackgroundColor(): string {\n const isOpaque = (c: string) =>\n !!c && c !== \"transparent\" && !/^rgba\\(\\s*0,\\s*0,\\s*0,\\s*0\\s*\\)$/.test(c);\n const bodyBg = getComputedStyle(document.body).backgroundColor;\n if (isOpaque(bodyBg)) return bodyBg;\n const htmlBg = getComputedStyle(document.documentElement).backgroundColor;\n if (isOpaque(htmlBg)) return htmlBg;\n return \"#ffffff\";\n}\n\n/** Default self-screenshot: render the app's own DOM to a PNG data URL — the\n * VISIBLE VIEWPORT at the current scroll, i.e. what the tester actually sees.\n *\n * We capture <html> cropped to the viewport box and translate it up by the\n * scroll offset (`style.transform`). modern-screenshot clones the DOM into an\n * SVG foreignObject where `position: fixed`/`sticky` no longer resolves against\n * the viewport — and our root translate would drag those elements off-screen —\n * so we re-pin them with an opposite translate for the duration of the capture.\n * A fixed element moves back by the whole scroll; a sticky one only by the gap\n * between its place in the flow and its place on screen (zero when not stuck).\n * (Capturing `document.body` full-height instead left fixed sidebars/headers\n * collapsed and the main content visually offset.)\n *\n * Captures run one at a time: two overlapping runs would stack their re-pin\n * translates, and the second would restore the first's translate into the\n * client's DOM.\n *\n * The app runs in its own document, so this captures ONLY the app — no Livery\n * chrome (that lives in the parent shell). */\nlet captureQueue: Promise<unknown> = Promise.resolve();\n\nexport function defaultCapture(selector?: string): Promise<string> {\n const run = captureQueue.then(() => captureNow(selector));\n captureQueue = run.catch(() => {});\n return run;\n}\n\n/** Translate that puts a fixed/sticky element of the unscrolled clone back where\n * the tester sees it. */\nfunction pinOffset(el: HTMLElement, position: string, sx: number, sy: number): [number, number] {\n if (position !== \"sticky\") return [sx, sy];\n const onScreen = el.getBoundingClientRect();\n const prev = el.style.position;\n el.style.position = \"static\";\n const inFlow = el.getBoundingClientRect();\n el.style.position = prev;\n return [onScreen.x - inFlow.x, onScreen.y - inFlow.y];\n}\n\nasync function captureNow(selector?: string): Promise<string> {\n if (selector) {\n // Chemin hérité, appelé seulement par un ancien Lab. Mêmes règles que la\n // capture de l'écran (capture-mask.ts) : champs et texte privé masqués,\n // zones exclues remplacées par un cache, et rien si l'élément est dans\n // une zone exclue.\n const element = document.querySelector(selector);\n if (!element) throw new Error(\"element_not_found\");\n if (element.closest(CLIENT_BLOCKED)) throw new Error(\"capture_blocked\");\n const unmark = markCaptureMasks(element, { blocks: true });\n try {\n return await domToPng(element, { quality: 0.92, onCloneNode: maskCapturedClone });\n } finally {\n unmark();\n }\n }\n const root = document.documentElement;\n const sx = window.scrollX;\n const sy = window.scrollY;\n\n // Zones exclues par le client (même contrat que rrweb) : un cache gris posé\n // par-dessus le temps de la capture. Rien n'est retiré : la mise en page de\n // la capture reste celle que le testeur voit. Posés DANS le `try` : le\n // `finally` les retire quoi qu'il arrive, jamais laissés dans le DOM client.\n const covers: HTMLElement[] = [];\n const pinned: Array<[HTMLElement, string]> = [];\n let unmark = () => {};\n try {\n // Valeurs des champs et texte privé : masqués dans le clone rendu (ECH-506).\n unmark = markCaptureMasks(root);\n for (const el of root.querySelectorAll(`.${CLIENT_BLOCK_CLASS}, ${CLIENT_BLOCK_SELECTOR}`)) {\n const r = el.getBoundingClientRect();\n if (r.width <= 0 || r.height <= 0) continue;\n const cover = document.createElement(\"div\");\n cover.dataset.leestoCaptureCover = \"\";\n Object.assign(cover.style, {\n position: \"fixed\",\n left: `${r.x}px`,\n top: `${r.y}px`,\n width: `${r.width}px`,\n height: `${r.height}px`,\n background: \"#a1a1aa\",\n zIndex: \"2147483647\",\n pointerEvents: \"none\",\n });\n root.append(cover);\n covers.push(cover);\n }\n\n // Re-pin fixed/sticky elements so they don't ride the root translate.\n for (const el of root.querySelectorAll<HTMLElement>(\"*\")) {\n const pos = getComputedStyle(el).position;\n if (pos === \"fixed\" || pos === \"sticky\") {\n const [dx, dy] = pinOffset(el, pos, sx, sy);\n const prev = el.style.transform;\n pinned.push([el, prev]);\n el.style.transform = `translate(${dx}px, ${dy}px)${prev ? ` ${prev}` : \"\"}`;\n }\n }\n\n return await domToPng(root, {\n quality: 0.92,\n backgroundColor: pageBackgroundColor(),\n width: root.clientWidth,\n height: root.clientHeight,\n style: { transform: `translate(${-sx}px, ${-sy}px)`, transformOrigin: \"top left\" },\n onCloneNode: maskCapturedClone,\n });\n } finally {\n unmark();\n for (const cover of covers) cover.remove();\n for (const [el, prev] of pinned) el.style.transform = prev;\n }\n}\n"],"ignoreList":[0],"mappings":"AAAA,SAASA,EAAc,EAAY,EAAK,CAMtC,MALA,GAAW,IAAM,EACjB,EAAW,IAAMC,GAAO,EACxB,EAAW,IAAMA,EAAM,IACvB,EAAW,IAAMA,GAAO,EACxB,EAAW,IAAMA,EAAM,IAChBC,CACT,CAEA,IAIIC,EACJ,SAASC,GAAqB,CAC5B,IAAMC,kBAAW,IAAI,WAAW,GAAG,EACnC,IAAK,IAAIC,EAAI,EAAGA,EAAI,IAAK,IAAK,CAC5B,IAAIC,EAAID,EACR,IAAK,IAAIE,EAAI,EAAGA,EAAI,EAAG,IACrB,EAAID,EAAI,EAAI,WAAaA,IAAM,EAAIA,IAAM,EAE3C,EAASD,GAAKC,CAChB,CACA,OAAOF,CACT,CACA,SAASI,EAAQ,EAAY,CAC3B,IAAIF,EAAI,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,OAAO,EACzC,IAAK,GAAM,CAACjQ,EAAI+Q,KAASK,EAAQ,EAAG,MAAM,UAAYL,CACxD,CACF,C"}
@@ -0,0 +1,2 @@
1
+ var e=`data-leesto-autocomplete`;function t(t){return`input[autocomplete="${t}"], input[${e}="${t}"]`}function n(t){return t.getAttribute(e)??t.autocomplete}function r(t){t.type===`password`||t.hasAttribute(e)||(t.setAttribute(e,t.getAttribute(`autocomplete`)??``),t.setAttribute(`autocomplete`,`off`))}function i(t){let n=t.getAttribute(e);n!==null&&(t.removeAttribute(e),n?t.setAttribute(`autocomplete`,n):t.removeAttribute(`autocomplete`))}function a(){let e=null;return{follow(t){t!==e&&(e&&i(e),e=t,t&&r(t))}}}var o=[`ArrowDown`,`Escape`];function s(e){return o.includes(e)}var c=6e3,l=3e3,u=/\b(se deconnecter|deconnexion|log ?out|sign ?out)\b/,d=/\/(logout|log-out|signout|sign-out|deconnexion)\b/i,f=`a, button, [role="button"], [role="menuitem"], input[type="submit"], input[type="button"]`,p=3;function m(e){return(e??``).normalize(`NFD`).replace(/[̀-ͯ]/g,``).replace(/\s+/g,` `).trim().toLowerCase()}function h(e){return e.getAttribute(`aria-label`)||(e instanceof HTMLInputElement?e.value:e.textContent??``)}function g(e){for(let t of Array.from(e.querySelectorAll(f))){if(u.test(m(h(t))))return!0;let e=t.getAttribute(`href`);if(e&&d.test(e))return!0}return!1}function _(e,t){let n=m(t);return n.length<p||!e.body?!1:m(e.body.innerText??e.body.textContent).includes(n)}function v(e,t){return _(e,t)?`same-account`:g(e)?`signed-in`:`unknown`}var y=100,b=800,x=[`hidden`,`class`,`style`,`type`,`disabled`,`aria-hidden`],S=`input[type="password"]`,C=t(`username`),w=t(`email`),T=`${C}, ${w}, input[type="email"]`,E=`${S}, ${T}`,D=/\b(connexion|se connecter|connectez[- ]vous|s'identifier|identifiez[- ]vous|login|log ?in|sign ?in)\b/,O=/\b(inscription|s'inscrire|inscrivez|creer (un|votre|mon) compte|sign ?up|register|create (an |your )?account|mot de passe oublie|oublie|reinitialiser|forgot|reset|lien de connexion|magic link|envoyer (un|le) lien|send (me )?(a |the )?link|code|newsletter|abonner|subscribe|enregistrer|sauvegarder|mettre a jour|save|update|confirmer|confirm|supprimer mon compte|delete account|payer|pay)\b/,k=/\b(inscription|s'inscrire|inscrivez|creer (un|votre|mon) compte|sign ?up|create (an |your )?account|mot de passe oublie|reinitialiser|forgot|lien de connexion|magic link|envoyer (un|le) lien|send (me )?(a |the )?link|newsletter|abonner|subscribe)\b/,A=/\b(afficher|masquer|voir|show|hide|toggle)\b/,j=/\b(effacer|vider|supprimer|clear|reset)\b/,M=/[\u{1F441}\u{1F576}\u{1F440}]/u;function N(e){return(e??``).normalize(`NFD`).replace(/[̀-ͯ]/g,``).replace(/[’‘]/g,`'`).replace(/\s+/g,` `).trim().toLowerCase()}function P(e){let t=e;for(;t;){if(t.hasAttribute(`hidden`)||t.getAttribute(`aria-hidden`)===`true`||t instanceof HTMLInputElement&&t.type===`hidden`)return!1;let e=t.ownerDocument.defaultView?.getComputedStyle(t);if(e&&(e.display===`none`||e.visibility===`hidden`))return!1;t=t.parentElement}return!0}function F(e,t){return Array.from(e.querySelectorAll(t)).filter(P)}function I(e){return e?e instanceof HTMLInputElement?e.value:e.textContent??``:``}function L(e,t){return!e.outsideForms||!t.closest(`form`)}function R(e,t){return Array.from(e.scope.querySelectorAll(t)).filter(t=>P(t)&&L(e,t))}function z(e){return N(e.getAttribute(`aria-label`)??e.getAttribute(`title`)??e.textContent)}function ee(e){let t=z(e);return A.test(t)||M.test(t)}function te(e,t){if(e.getAttribute(`type`)===`submit`||!t)return!1;let n=e.parentElement;return!n||F(n,E).length===0?!1:!n.contains(t)}var ne=`button, input[type="submit"], input[type="button"], input[type="image"], a[href]`;function re(e){return Array.from(e.querySelectorAll(ne)).some(P)}function B(e,t){let n=e.parentElement;for(;n&&!n.contains(t);){if(re(n))return!0;n=n.parentElement}return!1}function ie(e){let t=[e.getAttribute(`name`),e.getAttribute(`id`),e.getAttribute(`placeholder`),e.getAttribute(`aria-label`),e.closest(`label`)?.textContent??null],n=e.getAttribute(`id`);if(n){let r=e.ownerDocument.querySelector(`label[for="${CSS.escape(n)}"]`);r&&t.push(r.textContent)}return N(t.filter(Boolean).join(` `))}function ae(e,t){let n=e.parentElement;if(!n)return null;let r=e.ownerDocument.body,i=n=>t?G({scope:n,outsideForms:!0},t):e,a=t=>H({scope:t,outsideForms:!0},e,i(t)),o=e=>!!i(e)&&!!a(e),s=n,c=null,l=e=>{let t=a(e);t&&!c&&D.test(z(t))&&(c=e)};for(l(n);s!==r&&!o(s);){let t=s.parentElement;if(!t||t.querySelector(`form`))break;let n=[e],r=i(s);r&&r!==e&&n.push(r);let a=!!r;if(F(t,E).filter(e=>!e.closest(`form`)&&!n.includes(e)).some(t=>t.matches(S)||a||O.test(ie(t))?!0:B(t,e)))break;s=t,l(t)}return{scope:o(s)?s:c??n,outsideForms:!0}}function V(e,t,n){return e?{scope:e,outsideForms:!1}:ae(t,n)}function oe(e,t){let n=e.parentElement;for(;n&&n!==t.scope;){if(F(n,E).length===1)return!0;n=n.parentElement}return!1}function H(e,t,n){let r=e=>!!(t.compareDocumentPosition(e)&Node.DOCUMENT_POSITION_FOLLOWING),i=Array.from(e.scope.querySelectorAll(`button, input[type="submit"]`)).filter(t=>P(t)&&L(e,t)&&(t.getAttribute(`type`)===`submit`||r(t))&&!ee(t)&&!j.test(z(t))&&!te(t,n));if(i.length===0)return null;let a=(t,n)=>{let i=r(t);return[+!!oe(t,e),+!D.test(z(t)),t.getAttribute(`type`)===`submit`?0:1,+!i,i?n:-n]},o=i[0],s=a(o,0);return i.forEach((e,t)=>{let n=a(e,t);for(let t=0;t<n.length;t++){let r=n[t],i=s[t];if(r!==i){r<i&&(o=e,s=n);return}}}),o}function U(e){return e.querySelectorAll(`form`).length+ +!!F(e,E).some(e=>!e.closest(`form`))===1}function se(e,t){if(e){let t=e.getAttribute(`aria-label`);if(t)return t;let n=e.getAttribute(`aria-labelledby`);if(n){let t=e.ownerDocument.getElementById(n);if(t)return t.textContent??``}let r=e.querySelector(`h1, h2, h3, legend`);if(r)return r.textContent??``;let i=e.previousElementSibling;for(;i;){let t=/^(h1|h2|h3|legend)$/i.test(i.tagName)?i:i.querySelector(`h1, h2, h3, legend`);if(t){let n=e.parentElement;return n&&U(n)?t.textContent??``:``}i=i.previousElementSibling}let a=e.closest(`section, article, aside, dialog, fieldset, [role='dialog'], [role='region']`);if(a&&a!==e){let e=a.querySelector(`h1, h2, h3, legend`);if(e)return U(a)?e.textContent??``:``}return``}return(t instanceof Document?t.body:t)?.querySelector(`h1, h2, h3`)?.textContent??``}function W(e,t,n){let r=N(I(n)),i=N(se(e,t)),a=(e?.getAttribute(`action`)??``).split(`?`)[0],o=N([e?.id,e?.getAttribute(`name`),e?.className,a].filter(Boolean).join(` `));return{positive:D.test(r)||D.test(i),negative:O.test(r)||O.test(i)||k.test(o)}}function G(e,t){let n=R(e,C)[0]??R(e,w)[0]??R(e,`input[type="email"]`)[0];if(n)return n;if(!t)return null;let r=R(e,`input[type="text"], input:not([type])`).filter(e=>e.compareDocumentPosition(t)&Node.DOCUMENT_POSITION_FOLLOWING);return r[r.length-1]??null}function K(e,t){if(t.querySelector(`input[autocomplete="new-password"]`))return null;let r=F(t,S);if(r.length>1)return null;if(r.length===1){let n=r[0],i=V(e,n,n);if(!i)return null;let a=G(i,n),o=H(i,n,a),s=W(e,t,o);return!(n.autocomplete===`current-password`||s.positive)||s.negative?null:{kind:`password`,form:e,identifier:a,password:n,submit:o}}let i=F(t,T);if(i.length!==1)return null;let a=i[0],o=V(e,a,null);if(!o)return null;let s=H(o,a,a),c=W(e,t,s);return!(n(a)===`username`||c.positive)||c.negative?null:{kind:`identifier`,form:e,identifier:a,password:null,submit:s}}function q(e=document){let t=Array.from(e.querySelectorAll(`form`));for(let e of t){let t=K(e,e);if(t)return t}return t.length===0||F(e,S).find(e=>!e.closest(`form`))?K(null,e):null}function J(e,t){let n=Object.getPrototypeOf(e),r=Object.getOwnPropertyDescriptor(n,`value`)?.set??Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,`value`)?.set;r?r.call(e,t):e.value=t,e.dispatchEvent(new Event(`input`,{bubbles:!0})),e.dispatchEvent(new Event(`change`,{bubbles:!0}))}function ce(e){return!!e.form||!!e.submit}function le(e){let t=e.form,n=t?.noValidate;t&&(t.noValidate=!0);try{return t&&typeof t.requestSubmit==`function`?(t.requestSubmit(),!0):e.submit?(e.submit.click(),!0):t?(t.submit(),!0):!1}finally{t&&(t.noValidate=n??!1)}}var ue={identifier:null,password:null};function Y(e,t){return!e||e.disabled||e.readOnly?!1:e.value===``||t!==null&&e.value===t}function X(e,t,n){return{identifier:Y(e.identifier,n.identifier)&&!t.identifier,password:Y(e.password,n.password)&&!t.password}}function de(e,t,n){let r=e.identifier;return!r||n.identifier?!1:r.value!==``&&r.value!==t.login}function fe(e,t,n,r=ue){let i=X(e,n,r);return!i.identifier&&!i.password?{error:`nothing-to-fill`}:de(e,t,i)?{error:`identifier-mismatch`}:!ce(e)||(i.identifier&&J(e.identifier,t.login),i.password&&J(e.password,t.password),!le(e))?{error:`no-submit`}:{step:i.identifier&&i.password?`both`:i.password?`password`:`identifier`}}function pe(e){if(typeof window>`u`||typeof MutationObserver>`u`)return{watch(){},fill(){},cancel(){},teardown(){}};let t=null,n={identifier:!1,password:!1},r={identifier:null,password:null},i=!1,a=null,o=null,s=null,u=null,d=0,f=()=>{s&&clearTimeout(s),s=null},p=()=>{u&&clearTimeout(u),u=null,d=0},m=()=>{if(u=null,d=0,!t||n.identifier||n.password||q(document))return;let r=v(document,t.login);t=null,e.onNoForm(r)},h=()=>{if(!d)return;u&&clearTimeout(u);let e=Math.max(0,d-Date.now());u=setTimeout(m,Math.min(b,e))},g=()=>{a?.disconnect(),a=null,f(),p(),o&&clearTimeout(o),o=null},_=()=>{let a=q(document);if(e.onMatch?.(a),!a)i=!1,r={identifier:null,password:null},f();else if(!t)i||(i=!0,e.onDetected());else{let o=X(a,n,r),l=fe(a,t,n,r);if(`error`in l||(o.identifier&&(n={...n,identifier:!0},r={...r,identifier:t.login}),o.password&&(n={...n,password:!0},r={...r,password:t.password})),`error`in l){let r=l.error===`nothing-to-fill`?!n.identifier&&!n.password?`already-filled`:null:l.error;r&&(e.onError(r),t=null,g())}else e.onFilled(l.step),n.password&&(t=null,f(),s=setTimeout(()=>{s=null,q(document)&&(i=!0,e.onDetected())},c))}},S=()=>{h(),o&&clearTimeout(o),o=setTimeout(()=>{o=null,_()},y)},C=()=>{a||(a=new MutationObserver(S),a.observe(document.body,{childList:!0,subtree:!0,attributes:!0,attributeFilter:x}))};return{watch(){a||(i=!1,C()),_()},fill(e){p(),t=e,C(),_(),t&&!n.identifier&&!n.password&&!q(document)&&(d=Date.now()+l,h())},cancel(){t=null,n={identifier:!1,password:!1},i=!1,g(),e.onMatch?.(null)},teardown(){t=null,g(),e.onMatch?.(null)}}}var me=500,Z=.5;function Q(e){let t=e?.identifier??e?.password??null;if(!e||!t)return null;let n=[e.identifier,e.password].filter(e=>e!==null);return{field:t,scope:e.form,inputs:n}}var $=e=>Math.round(e*2)/2;function he(e,t){return e===null||t===null?e===t:e.crowded===t.crowded&&Math.abs(e.x-t.x)<=Z&&Math.abs(e.y-t.y)<=Z&&Math.abs(e.width-t.width)<=Z&&Math.abs(e.height-t.height)<=Z}function ge(e,t){if(typeof document.elementFromPoint!=`function`)return!1;let n=t.left+t.width/2,r=t.top+t.height/2;if(n<0||r<0||n>=window.innerWidth||r>=window.innerHeight)return!1;let i=document.elementFromPoint(n,r);return!i||i===e||e.contains(i)?!1:!Array.from(e.labels??[]).some(e=>e.contains(i))}var _e=8,ve=[24,32],ye=`button, a[href], input, select, textarea, [role=button], [tabindex]`;function be(e,t){if(typeof document.elementFromPoint!=`function`)return!1;let n=t.top+t.height/2;return ve.some(r=>{let i=t.right-_e-r/2;if(i<=t.left||i<0||n<0||i>=window.innerWidth||n>=window.innerHeight)return!1;let a=document.elementFromPoint(i,n)?.closest(ye);return!!a&&!a.contains(e)})}function xe(e){if(!e.isConnected||!P(e))return null;let t=e.getBoundingClientRect();return t.width<=0||t.height<=0||t.right<=0||t.bottom<=0||t.left>=window.innerWidth||t.top>=window.innerHeight||ge(e,t)?null:{x:$(t.left),y:$(t.top),width:$(t.width),height:$(t.height),...be(e,t)?{crowded:!0}:{}}}function Se(e,t={}){if(typeof window>`u`)return{track(){},focusField(){},teardown(){}};let n=t.frame??(e=>window.requestAnimationFrame(()=>e())),r=t.trusted??(e=>e.isTrusted),i=null,a=null,o=!1,c=!1,l=-1/0,u=-1/0,d=-1/0,f=!1,p=!1,m=null,h=null,g=null,_=()=>{if(c=!1,!i)return;let t=xe(i.field);a&&a.scrolling===o&&he(a.rect,t)||(a={rect:t,scrolling:o},e.onAnchor(t,o))},v=()=>{i&&!c&&(c=!0,n(_))},y=e=>{if(!i)return;let t=e.target;t instanceof Node&&!t.contains(i.field)||(o=!0,m&&clearTimeout(m),m=setTimeout(()=>{m=null,o=!1,v()},150),v())},b=()=>{let t=Date.now();t-l<250||(l=t,e.onInteraction())},x=/* @__PURE__ */ new Set,S=e=>e.pointerType===`touch`,C=e=>e.pointerId??0,w=()=>{e.onFieldFocus(),l=-1/0},T=e=>{if(!i||(e.button??0)!==0)return;let t=e.target;if(!(t instanceof Node))return;let n=i.field;(n.contains(t)||Array.from(n.labels??[]).some(e=>e.contains(t)))&&(u=Date.now(),document.activeElement===n&&w())},E=e=>{i&&r(e)&&(d=Date.now(),S(e)?x.add(C(e)):(b(),T(e)))},D=e=>{i&&r(e)&&(d=Date.now()),i&&r(e)&&S(e)&&x.delete(C(e))&&(b(),T(e))},O=e=>{if(!i)return;let t=f;f=!1,!(e.target!==i.field||t||p||!r(e))&&(Date.now()-u>1e3||(b(),w()))},k=e=>{i&&e.target===i.field&&r(e)&&e.relatedTarget instanceof Node&&b()},A=e=>{!r(e)||Date.now()-d<=me||(u=Date.now())},j=()=>{i&&document.activeElement===i.field&&(f=!0)},M=t=>{if(!i||!r(t))return;let{key:n,isComposing:a,shiftKey:o,altKey:c,ctrlKey:l,metaKey:d}=t;n===`Tab`&&(u=Date.now()),!(t.target!==i.field||a||o||c||l||d)&&s(n)&&e.onFieldKey(n)},N=e=>{x.delete(C(e))},P=e=>{if(!i||!r(e)||!(e.target instanceof Node))return;let t=e.target;(i.scope?i.scope.contains(t):i.inputs.some(e=>e===t))&&b()},F=()=>{document.visibilityState===`visible`&&v()},I=()=>{document.addEventListener(`scroll`,y,{capture:!0,passive:!0}),window.addEventListener(`resize`,v),window.visualViewport?.addEventListener(`resize`,v),window.visualViewport?.addEventListener(`scroll`,v),document.addEventListener(`pointerdown`,E,!0),document.addEventListener(`pointerup`,D,!0),document.addEventListener(`pointercancel`,N,!0),document.addEventListener(`input`,P,!0),document.addEventListener(`focusin`,O,!0),document.addEventListener(`focusout`,k,!0),document.addEventListener(`keydown`,M,!0),window.addEventListener(`focus`,A),window.addEventListener(`blur`,j),document.addEventListener(`visibilitychange`,F),h=setInterval(()=>{document.visibilityState===`visible`&&v()},250)},L=()=>{document.removeEventListener(`scroll`,y,{capture:!0}),window.removeEventListener(`resize`,v),window.visualViewport?.removeEventListener(`resize`,v),window.visualViewport?.removeEventListener(`scroll`,v),document.removeEventListener(`pointerdown`,E,!0),document.removeEventListener(`pointerup`,D,!0),document.removeEventListener(`pointercancel`,N,!0),document.removeEventListener(`input`,P,!0),document.removeEventListener(`focusin`,O,!0),document.removeEventListener(`focusout`,k,!0),document.removeEventListener(`keydown`,M,!0),window.removeEventListener(`focus`,A),window.removeEventListener(`blur`,j),x.clear(),f=!1,u=-1/0,d=-1/0,document.removeEventListener(`visibilitychange`,F),h&&clearInterval(h),m&&clearTimeout(m),h=null,m=null,g?.disconnect(),g=null,o=!1,c=!1},R=()=>{let t=i!==null;i=null,L(),a=null,t&&e.onAnchor(null,!1)};return{track(e){if(!e){R();return}let t=i?.field===e.field,n=i!==null;i=e,n||I(),t||(g?.disconnect(),g=typeof ResizeObserver>`u`?null:new ResizeObserver(()=>v()),g?.observe(e.field),a=null),v()},focusField(){if(i){p=!0;try{i.field.focus({preventScroll:!0})}finally{p=!1}}},teardown:R}}function Ce(e){let t=!1,n=!1,r=a(),i=Se({onAnchor:(t,n)=>e({type:`leesto:login-anchor`,rect:t,scrolling:n}),onInteraction:()=>e({type:`leesto:login-interaction`}),onFieldFocus:()=>e({type:`leesto:login-field-focus`}),onFieldKey:t=>e({type:`leesto:login-field-key`,key:t})}),o=pe({onDetected:()=>e({type:`leesto:login-form-detected`}),onFilled:t=>e({type:`leesto:login-filled`,step:t}),onError:t=>e({type:`leesto:login-error`,reason:t}),onNoForm:t=>e({type:`leesto:login-no-form`,signedIn:t}),onMatch:e=>{let a=t?Q(e):null;i.track(a),r.follow(n?a?.field??null:null)}});return{watch(e){t=e.anchor,n=t&&e.silenceAutofill,o.watch()},fill:e=>o.fill(e),cancel:()=>o.cancel(),focusField:()=>i.focusField(),teardown(){o.teardown(),i.teardown()}}}export{Ce as installLoginSession};
2
+ //# sourceMappingURL=login-session-BwFZO065.js.map