@prodact.ai/sdk 0.0.8 → 0.0.10
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/dist/cdn/sdk.global.js +2 -2
- package/dist/cdn/sdk.global.js.map +1 -1
- package/dist/index.js +36 -2
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +36 -2
- package/dist/index.mjs.map +1 -1
- package/dist/react.js +110 -2
- package/dist/react.js.map +1 -1
- package/dist/react.mjs +110 -2
- package/dist/react.mjs.map +1 -1
- package/package.json +1 -1
package/dist/cdn/sdk.global.js
CHANGED
|
@@ -51,7 +51,7 @@ https://www.w3ctech.com/topic/2226`));let a=t(...o);return a.postcssPlugin=e,a.p
|
|
|
51
51
|
https://evilmartians.com/chronicles/postcss-8-plugin-migration`),process.env.LANG&&process.env.LANG.startsWith("cn")&&console.warn(e+`: \u91CC\u9762 postcss.plugin \u88AB\u5F03\u7528. \u8FC1\u79FB\u6307\u5357:
|
|
52
52
|
https://www.w3ctech.com/topic/2226`));let a=t(...o);return a.postcssPlugin=e,a.postcssVersion=new Qs().version,a}let n;return Object.defineProperty(s,"postcss",{get(){return n||(n=s()),n}}),s.process=function(o,a,l){return _([s(l)]).process(o,a)},s};_.stringify=$f;_.parse=Bf;_.fromJSON=Lf;_.list=Wf;_.comment=i=>new nl(i);_.atRule=i=>new ol(i);_.decl=i=>new il(i);_.rule=i=>new al(i);_.root=i=>new ll(i);_.document=i=>new sl(i);_.CssSyntaxError=Of;_.Declaration=il;_.Container=Pf;_.Processor=Qs;_.Document=sl;_.Comment=nl;_.Warning=_f;_.AtRule=ol;_.Result=Ff;_.Input=Uf;_.Rule=al;_.Root=ll;_.Node=zf;Df.registerPostcss(_);Hf=_;_.default=_;K=ed(Hf);K.stringify;K.fromJSON;K.plugin;K.parse;K.list;K.document;K.comment;K.atRule;K.rule;K.decl;K.root;K.CssSyntaxError;K.Declaration;K.Container;K.Processor;K.Document;K.Comment;K.Warning;K.AtRule;K.Result;K.Input;K.Rule;K.Root;K.Node;N=(i=>(i[i.Document=0]="Document",i[i.DocumentType=1]="DocumentType",i[i.Element=2]="Element",i[i.Text=3]="Text",i[i.CDATA=4]="CDATA",i[i.Comment=5]="Comment",i))(N||{});Gf=/-([a-z])/g,Kf=/^--[a-zA-Z0-9-]+$/,ss=i=>Kf.test(i)?i:i.replace(Gf,(e,t)=>t?t.toUpperCase():""),jf=/\B([A-Z])/g,Yf=i=>i.replace(jf,"-$1").toLowerCase(),ce=class i{constructor(...e){C(this,"parentElement",null),C(this,"parentNode",null),C(this,"ownerDocument"),C(this,"firstChild",null),C(this,"lastChild",null),C(this,"previousSibling",null),C(this,"nextSibling",null),C(this,"ELEMENT_NODE",1),C(this,"TEXT_NODE",3),C(this,"nodeType"),C(this,"nodeName"),C(this,"RRNodeType")}get childNodes(){let e=[],t=this.firstChild;for(;t;)e.push(t),t=t.nextSibling;return e}contains(e){if(e instanceof i){if(e.ownerDocument!==this.ownerDocument)return!1;if(e===this)return!0}else return!1;for(;e.parentNode;){if(e.parentNode===this)return!0;e=e.parentNode}return!1}appendChild(e){throw new Error("RRDomException: Failed to execute 'appendChild' on 'RRNode': This RRNode type does not support this method.")}insertBefore(e,t){throw new Error("RRDomException: Failed to execute 'insertBefore' on 'RRNode': This RRNode type does not support this method.")}removeChild(e){throw new Error("RRDomException: Failed to execute 'removeChild' on 'RRNode': This RRNode type does not support this method.")}toString(){return"RRNode"}},ns=class i extends ce{constructor(...e){super(e),C(this,"nodeType",9),C(this,"nodeName","#document"),C(this,"compatMode","CSS1Compat"),C(this,"RRNodeType",N.Document),C(this,"textContent",null),this.ownerDocument=this}get documentElement(){return this.childNodes.find(e=>e.RRNodeType===N.Element&&e.tagName==="HTML")||null}get body(){var e;return((e=this.documentElement)==null?void 0:e.childNodes.find(t=>t.RRNodeType===N.Element&&t.tagName==="BODY"))||null}get head(){var e;return((e=this.documentElement)==null?void 0:e.childNodes.find(t=>t.RRNodeType===N.Element&&t.tagName==="HEAD"))||null}get implementation(){return this}get firstElementChild(){return this.documentElement}appendChild(e){let t=e.RRNodeType;if((t===N.Element||t===N.DocumentType)&&this.childNodes.some(s=>s.RRNodeType===t))throw new Error(`RRDomException: Failed to execute 'appendChild' on 'RRNode': Only one ${t===N.Element?"RRElement":"RRDoctype"} on RRDocument allowed.`);let r=en(this,e);return r.parentElement=null,r}insertBefore(e,t){let r=e.RRNodeType;if((r===N.Element||r===N.DocumentType)&&this.childNodes.some(n=>n.RRNodeType===r))throw new Error(`RRDomException: Failed to execute 'insertBefore' on 'RRNode': Only one ${r===N.Element?"RRElement":"RRDoctype"} on RRDocument allowed.`);let s=cl(this,e,t);return s.parentElement=null,s}removeChild(e){return ul(this,e)}open(){this.firstChild=null,this.lastChild=null}close(){}write(e){let t;if(e==='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">'?t="-//W3C//DTD XHTML 1.0 Transitional//EN":e==='<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "">'&&(t="-//W3C//DTD HTML 4.0 Transitional//EN"),t){let r=this.createDocumentType("html",t,"");this.open(),this.appendChild(r)}}createDocument(e,t,r){return new i}createDocumentType(e,t,r){let s=new Nr(e,t,r);return s.ownerDocument=this,s}createElement(e){let t=new it(e);return t.ownerDocument=this,t}createElementNS(e,t){return this.createElement(t)}createTextNode(e){let t=new Ar(e);return t.ownerDocument=this,t}createComment(e){let t=new Or(e);return t.ownerDocument=this,t}createCDATASection(e){let t=new Dr(e);return t.ownerDocument=this,t}toString(){return"RRDocument"}},Nr=class extends ce{constructor(e,t,r){super(),C(this,"nodeType",10),C(this,"RRNodeType",N.DocumentType),C(this,"name"),C(this,"publicId"),C(this,"systemId"),C(this,"textContent",null),this.name=e,this.publicId=t,this.systemId=r,this.nodeName=e}toString(){return"RRDocumentType"}},it=class extends ce{constructor(e){super(),C(this,"nodeType",1),C(this,"RRNodeType",N.Element),C(this,"tagName"),C(this,"attributes",{}),C(this,"shadowRoot",null),C(this,"scrollLeft"),C(this,"scrollTop"),this.tagName=e.toUpperCase(),this.nodeName=e.toUpperCase()}get textContent(){let e="";return this.childNodes.forEach(t=>e+=t.textContent),e}set textContent(e){this.firstChild=null,this.lastChild=null,this.appendChild(this.ownerDocument.createTextNode(e))}get classList(){return new ls(this.attributes.class,e=>{this.attributes.class=e})}get id(){return this.attributes.id||""}get className(){return this.attributes.class||""}get style(){let e=this.attributes.style?Vf(this.attributes.style):{},t=/\B([A-Z])/g;return e.setProperty=(r,s,n)=>{if(t.test(r))return;let o=ss(r);s?e[o]=s:delete e[o],n==="important"&&(e[o]+=" !important"),this.attributes.style=go(e)},e.removeProperty=r=>{if(t.test(r))return"";let s=ss(r),n=e[s]||"";return delete e[s],this.attributes.style=go(e),n},e}getAttribute(e){return this.attributes[e]===void 0?null:this.attributes[e]}setAttribute(e,t){this.attributes[e]=t}setAttributeNS(e,t,r){this.setAttribute(t,r)}removeAttribute(e){delete this.attributes[e]}appendChild(e){return en(this,e)}insertBefore(e,t){return cl(this,e,t)}removeChild(e){return ul(this,e)}attachShadow(e){let t=this.ownerDocument.createElement("SHADOWROOT");return this.shadowRoot=t,t}dispatchEvent(e){return!0}toString(){let e="";for(let t in this.attributes)e+=`${t}="${this.attributes[t]}" `;return`${this.tagName} ${e}`}},os=class extends it{constructor(){super(...arguments),C(this,"currentTime"),C(this,"volume"),C(this,"paused"),C(this,"muted"),C(this,"playbackRate"),C(this,"loop")}attachShadow(e){throw new Error("RRDomException: Failed to execute 'attachShadow' on 'RRElement': This RRElement does not support attachShadow")}play(){this.paused=!1}pause(){this.paused=!0}},as=class extends it{constructor(){super(...arguments),C(this,"tagName","DIALOG"),C(this,"nodeName","DIALOG")}get isModal(){return this.getAttribute("rr_open_mode")==="modal"}get open(){return this.getAttribute("open")!==null}close(){this.removeAttribute("open"),this.removeAttribute("rr_open_mode")}show(){this.setAttribute("open",""),this.setAttribute("rr_open_mode","non-modal")}showModal(){this.setAttribute("open",""),this.setAttribute("rr_open_mode","modal")}},Ar=class extends ce{constructor(e){super(),C(this,"nodeType",3),C(this,"nodeName","#text"),C(this,"RRNodeType",N.Text),C(this,"data"),this.data=e}get textContent(){return this.data}set textContent(e){this.data=e}toString(){return`RRText text=${JSON.stringify(this.data)}`}},Or=class extends ce{constructor(e){super(),C(this,"nodeType",8),C(this,"nodeName","#comment"),C(this,"RRNodeType",N.Comment),C(this,"data"),this.data=e}get textContent(){return this.data}set textContent(e){this.data=e}toString(){return`RRComment text=${JSON.stringify(this.data)}`}},Dr=class extends ce{constructor(e){super(),C(this,"nodeName","#cdata-section"),C(this,"nodeType",4),C(this,"RRNodeType",N.CDATA),C(this,"data"),this.data=e}get textContent(){return this.data}set textContent(e){this.data=e}toString(){return`RRCDATASection data=${JSON.stringify(this.data)}`}},ls=class{constructor(e,t){if(C(this,"onChange"),C(this,"classes",[]),C(this,"add",(...r)=>{for(let s of r){let n=String(s);this.classes.indexOf(n)>=0||this.classes.push(n)}this.onChange&&this.onChange(this.classes.join(" "))}),C(this,"remove",(...r)=>{this.classes=this.classes.filter(s=>r.indexOf(s)===-1),this.onChange&&this.onChange(this.classes.join(" "))}),e){let r=e.trim().split(/\s+/);this.classes.push(...r)}this.onChange=t}};ne=(i=>(i[i.PLACEHOLDER=0]="PLACEHOLDER",i[i.ELEMENT_NODE=1]="ELEMENT_NODE",i[i.ATTRIBUTE_NODE=2]="ATTRIBUTE_NODE",i[i.TEXT_NODE=3]="TEXT_NODE",i[i.CDATA_SECTION_NODE=4]="CDATA_SECTION_NODE",i[i.ENTITY_REFERENCE_NODE=5]="ENTITY_REFERENCE_NODE",i[i.ENTITY_NODE=6]="ENTITY_NODE",i[i.PROCESSING_INSTRUCTION_NODE=7]="PROCESSING_INSTRUCTION_NODE",i[i.COMMENT_NODE=8]="COMMENT_NODE",i[i.DOCUMENT_NODE=9]="DOCUMENT_NODE",i[i.DOCUMENT_TYPE_NODE=10]="DOCUMENT_TYPE_NODE",i[i.DOCUMENT_FRAGMENT_NODE=11]="DOCUMENT_FRAGMENT_NODE",i))(ne||{}),cs={svg:"http://www.w3.org/2000/svg","xlink:href":"http://www.w3.org/1999/xlink",xmlns:"http://www.w3.org/2000/xmlns/"},Xf={altglyph:"altGlyph",altglyphdef:"altGlyphDef",altglyphitem:"altGlyphItem",animatecolor:"animateColor",animatemotion:"animateMotion",animatetransform:"animateTransform",clippath:"clipPath",feblend:"feBlend",fecolormatrix:"feColorMatrix",fecomponenttransfer:"feComponentTransfer",fecomposite:"feComposite",feconvolvematrix:"feConvolveMatrix",fediffuselighting:"feDiffuseLighting",fedisplacementmap:"feDisplacementMap",fedistantlight:"feDistantLight",fedropshadow:"feDropShadow",feflood:"feFlood",fefunca:"feFuncA",fefuncb:"feFuncB",fefuncg:"feFuncG",fefuncr:"feFuncR",fegaussianblur:"feGaussianBlur",feimage:"feImage",femerge:"feMerge",femergenode:"feMergeNode",femorphology:"feMorphology",feoffset:"feOffset",fepointlight:"fePointLight",fespecularlighting:"feSpecularLighting",fespotlight:"feSpotLight",fetile:"feTile",feturbulence:"feTurbulence",foreignobject:"foreignObject",glyphref:"glyphRef",lineargradient:"linearGradient",radialgradient:"radialGradient"},me=null;st=class i extends ns{constructor(e){super(),C(this,"UNSERIALIZED_STARTING_ID",-2),C(this,"_unserializedId",this.UNSERIALIZED_STARTING_ID),C(this,"mirror",np()),C(this,"scrollData",null),e&&(this.mirror=e)}get unserializedId(){return this._unserializedId--}createDocument(e,t,r){return new i}createDocumentType(e,t,r){let s=new Qf(e,t,r);return s.ownerDocument=this,s}createElement(e){let t=e.toUpperCase(),r;switch(t){case"AUDIO":case"VIDEO":r=new us(t);break;case"IFRAME":r=new ps(t,this.mirror);break;case"CANVAS":r=new ds(t);break;case"STYLE":r=new fs(t);break;case"DIALOG":r=new hs(t);break;default:r=new nt(t);break}return r.ownerDocument=this,r}createComment(e){let t=new tp(e);return t.ownerDocument=this,t}createCDATASection(e){let t=new rp(e);return t.ownerDocument=this,t}createTextNode(e){let t=new ep(e);return t.ownerDocument=this,t}destroyTree(){this.firstChild=null,this.lastChild=null,this.mirror.reset()}open(){super.open(),this._unserializedId=this.UNSERIALIZED_STARTING_ID}},Qf=Nr,nt=class extends it{constructor(){super(...arguments),C(this,"inputData",null),C(this,"scrollData",null)}},us=class extends os{},hs=class extends as{},ds=class extends nt{constructor(){super(...arguments),C(this,"rr_dataURL",null),C(this,"canvasMutations",[])}getContext(){return null}},fs=class extends nt{constructor(){super(...arguments),C(this,"rules",[])}},ps=class extends nt{constructor(e,t){super(e),C(this,"contentDocument",new st),this.contentDocument.mirror=t}},ep=Ar,tp=Or,rp=Dr;ms=class{constructor(){C(this,"idNodeMap",new Map),C(this,"nodeMetaMap",new WeakMap)}getId(e){var t;if(!e)return-1;let r=(t=this.getMeta(e))==null?void 0:t.id;return r!=null?r:-1}getNode(e){return this.idNodeMap.get(e)||null}getIds(){return Array.from(this.idNodeMap.keys())}getMeta(e){return this.nodeMetaMap.get(e)||null}removeNodeFromMap(e){let t=this.getId(e);this.idNodeMap.delete(t),e.childNodes&&e.childNodes.forEach(r=>this.removeNodeFromMap(r))}has(e){return this.idNodeMap.has(e)}hasNode(e){return this.nodeMetaMap.has(e)}add(e,t){let r=t.id;this.idNodeMap.set(r,e),this.nodeMetaMap.set(e,t)}replace(e,t){let r=this.getNode(e);if(r){let s=this.nodeMetaMap.get(r);s&&this.nodeMetaMap.set(t,s)}this.idNodeMap.set(e,t)}reset(){this.idNodeMap=new Map,this.nodeMetaMap=new WeakMap}};yo={Node:["childNodes","parentNode","parentElement","textContent"],ShadowRoot:["host","styleSheets"],Element:["shadowRoot","querySelector","querySelectorAll"],MutationObserver:[]},wo={Node:["contains","getRootNode"],ShadowRoot:["getSelection"],Element:[],MutationObserver:["constructor"]},cr={},op=()=>!!globalThis.Zone;Ci={};Ei={};M={childNodes:ap,parentNode:lp,parentElement:cp,textContent:up,contains:hp,getRootNode:dp,host:fp,styleSheets:pp,shadowRoot:mp,querySelector:gp,querySelectorAll:yp,mutationObserver:ml};He=`Please stop import mirror directly. Instead of that,\r
|
|
53
53
|
now you can use replayer.getMirror() to access the mirror instance of a replayer,\r
|
|
54
|
-
or you can use record.mirror to access the mirror instance during recording.`,Lr={map:{},getId(){return console.error(He),-1},getNode(){return console.error(He),null},removeNodeFromMap(){console.error(He)},has(){return console.error(He),!1},reset(){console.error(He)}};typeof window!="undefined"&&window.Proxy&&window.Reflect&&(Lr=new Proxy(Lr,{get(i,e,t){return e==="map"&&console.error(He),Reflect.get(i,e,t)}}));Nt=Date.now;/[1-9][0-9]{12}/.test(Date.now().toString())||(Nt=()=>new Date().getTime());At=class{constructor(){v(this,"id",1),v(this,"styleIDMap",new WeakMap),v(this,"idStyleMap",new Map)}getId(e){var t;return(t=this.styleIDMap.get(e))!=null?t:-1}has(e){return this.styleIDMap.has(e)}add(e,t){if(this.has(e))return this.getId(e);let r;return t===void 0?r=this.id++:r=t,this.styleIDMap.set(e,r),this.idStyleMap.set(r,e),r}getStyle(e){return this.idStyleMap.get(e)||null}reset(){this.styleIDMap=new WeakMap,this.idStyleMap=new Map,this.id=1}generateId(){return this.id++}};wp=Object.freeze(Object.defineProperty({__proto__:null,StyleSheetMirror:At,get _mirror(){return Lr},closestElementOfNode:an,getBaseDimension:dn,getNestedRule:je,getPositionsAndIndex:gs,getRootShadowHost:vl,getShadowHost:fn,getWindowHeight:nn,getWindowScroll:sn,getWindowWidth:on,hasShadowRoot:xe,hookSetter:Lt,inDom:pn,isAncestorRemoved:ln,isBlocked:te,isIgnored:yr,isSerialized:gl,isSerializedIframe:Je,isSerializedStylesheet:hn,iterateResolveTree:un,legacy_isTouchEvent:_r,get nowTimestamp(){return Nt},on:ee,patch:Fe,polyfill:cn,queueToResolveTrees:yl,shadowHostInDom:bl,throttle:ot,uniqueTextMutations:wl},Symbol.toStringTag,{value:"Module"})),x=(i=>(i[i.DomContentLoaded=0]="DomContentLoaded",i[i.Load=1]="Load",i[i.FullSnapshot=2]="FullSnapshot",i[i.IncrementalSnapshot=3]="IncrementalSnapshot",i[i.Meta=4]="Meta",i[i.Custom=5]="Custom",i[i.Plugin=6]="Plugin",i))(x||{}),E=(i=>(i[i.Mutation=0]="Mutation",i[i.MouseMove=1]="MouseMove",i[i.MouseInteraction=2]="MouseInteraction",i[i.Scroll=3]="Scroll",i[i.ViewportResize=4]="ViewportResize",i[i.Input=5]="Input",i[i.TouchMove=6]="TouchMove",i[i.MediaInteraction=7]="MediaInteraction",i[i.StyleSheetRule=8]="StyleSheetRule",i[i.CanvasMutation=9]="CanvasMutation",i[i.Font=10]="Font",i[i.Log=11]="Log",i[i.Drag=12]="Drag",i[i.StyleDeclaration=13]="StyleDeclaration",i[i.Selection=14]="Selection",i[i.AdoptedStyleSheet=15]="AdoptedStyleSheet",i[i.CustomElement=16]="CustomElement",i))(E||{}),D=(i=>(i[i.MouseUp=0]="MouseUp",i[i.MouseDown=1]="MouseDown",i[i.Click=2]="Click",i[i.ContextMenu=3]="ContextMenu",i[i.DblClick=4]="DblClick",i[i.Focus=5]="Focus",i[i.Blur=6]="Blur",i[i.TouchStart=7]="TouchStart",i[i.TouchMove_Departed=8]="TouchMove_Departed",i[i.TouchEnd=9]="TouchEnd",i[i.TouchCancel=10]="TouchCancel",i))(D||{}),ge=(i=>(i[i.Mouse=0]="Mouse",i[i.Pen=1]="Pen",i[i.Touch=2]="Touch",i))(ge||{}),be=(i=>(i[i["2D"]=0]="2D",i[i.WebGL=1]="WebGL",i[i.WebGL2=2]="WebGL2",i))(be||{}),Ee=(i=>(i[i.Play=0]="Play",i[i.Pause=1]="Pause",i[i.Seeked=2]="Seeked",i[i.VolumeChange=3]="VolumeChange",i[i.RateChange=4]="RateChange",i))(Ee||{}),O=(i=>(i.Start="start",i.Pause="pause",i.Resume="resume",i.Resize="resize",i.Finish="finish",i.FullsnapshotRebuilded="fullsnapshot-rebuilded",i.LoadStylesheetStart="load-stylesheet-start",i.LoadStylesheetEnd="load-stylesheet-end",i.SkipStart="skip-start",i.SkipEnd="skip-end",i.MouseInteraction="mouse-interaction",i.EventCast="event-cast",i.CustomEvent="custom-event",i.Flush="flush",i.StateChange="state-change",i.PlayBack="play-back",i.Destroy="destroy",i))(O||{}),ye=(i=>(i[i.Document=0]="Document",i[i.DocumentType=1]="DocumentType",i[i.Element=2]="Element",i[i.Text=3]="Text",i[i.CDATA=4]="CDATA",i[i.Comment=5]="Comment",i))(ye||{});ys=class{constructor(){v(this,"length",0),v(this,"head",null),v(this,"tail",null)}get(e){if(e>=this.length)throw new Error("Position outside of list range");let t=this.head;for(let r=0;r<e;r++)t=(t==null?void 0:t.next)||null;return t}addNode(e){let t={value:e,previous:null,next:null};if(e.__ln=t,e.previousSibling&&vo(e.previousSibling)){let r=e.previousSibling.__ln.next;t.next=r,t.previous=e.previousSibling.__ln,e.previousSibling.__ln.next=t,r&&(r.previous=t)}else if(e.nextSibling&&vo(e.nextSibling)&&e.nextSibling.__ln.previous){let r=e.nextSibling.__ln.previous;t.previous=r,t.next=e.nextSibling.__ln,e.nextSibling.__ln.previous=t,r&&(r.next=t)}else this.head&&(this.head.previous=t),t.next=this.head,this.head=t;t.next===null&&(this.tail=t),this.length++}removeNode(e){let t=e.__ln;this.head&&(t.previous?(t.previous.next=t.next,t.next?t.next.previous=t.previous:this.tail=t.previous):(this.head=t.next,this.head?this.head.previous=null:this.tail=null),e.__ln&&delete e.__ln,this.length--)}},bo=(i,e)=>`${i}@${e}`,ws=class{constructor(){v(this,"frozen",!1),v(this,"locked",!1),v(this,"texts",[]),v(this,"attributes",[]),v(this,"attributeMap",new WeakMap),v(this,"removes",[]),v(this,"mapRemoves",[]),v(this,"movedMap",{}),v(this,"addedSet",new Set),v(this,"movedSet",new Set),v(this,"droppedSet",new Set),v(this,"removesSubTreeCache",new Set),v(this,"mutationCb"),v(this,"blockClass"),v(this,"blockSelector"),v(this,"maskTextClass"),v(this,"maskTextSelector"),v(this,"inlineStylesheet"),v(this,"maskInputOptions"),v(this,"maskTextFn"),v(this,"maskInputFn"),v(this,"keepIframeSrcFn"),v(this,"recordCanvas"),v(this,"inlineImages"),v(this,"slimDOMOptions"),v(this,"dataURLOptions"),v(this,"doc"),v(this,"mirror"),v(this,"iframeManager"),v(this,"stylesheetManager"),v(this,"shadowDomManager"),v(this,"canvasManager"),v(this,"processedNodeManager"),v(this,"unattachedDoc"),v(this,"processMutations",e=>{e.forEach(this.processMutation),this.emit()}),v(this,"emit",()=>{if(this.frozen||this.locked)return;let e=[],t=new Set,r=new ys,s=l=>{let c=l,u=St;for(;u===St;)c=c&&c.nextSibling,u=c&&this.mirror.getId(c);return u},n=l=>{let c=M.parentNode(l);if(!c||!pn(l))return;let u=!1;if(l.nodeType===Node.TEXT_NODE){let g=c.tagName;if(g==="TEXTAREA")return;g==="STYLE"&&this.addedSet.has(c)&&(u=!0)}let h=gt(c)?this.mirror.getId(fn(l)):this.mirror.getId(c),d=s(l);if(h===-1||d===-1)return r.addNode(l);let p=Ke(l,{doc:this.doc,mirror:this.mirror,blockClass:this.blockClass,blockSelector:this.blockSelector,maskTextClass:this.maskTextClass,maskTextSelector:this.maskTextSelector,skipChild:!0,newlyAddedElement:!0,inlineStylesheet:this.inlineStylesheet,maskInputOptions:this.maskInputOptions,maskTextFn:this.maskTextFn,maskInputFn:this.maskInputFn,slimDOMOptions:this.slimDOMOptions,dataURLOptions:this.dataURLOptions,recordCanvas:this.recordCanvas,inlineImages:this.inlineImages,onSerialize:g=>{Je(g,this.mirror)&&this.iframeManager.addIframe(g),hn(g,this.mirror)&&this.stylesheetManager.trackLinkElement(g),xe(l)&&this.shadowDomManager.addShadowRoot(M.shadowRoot(l),this.doc)},onIframeLoad:(g,m)=>{this.iframeManager.attachIframe(g,m),this.shadowDomManager.observeAttachShadow(g)},onStylesheetLoad:(g,m)=>{this.stylesheetManager.attachLinkElement(g,m)},cssCaptured:u});p&&(e.push({parentId:h,nextId:d,node:p}),t.add(p.id))};for(;this.mapRemoves.length;)this.mirror.removeNodeFromMap(this.mapRemoves.shift());for(let l of this.movedSet)So(this.removesSubTreeCache,l,this.mirror)&&!this.movedSet.has(M.parentNode(l))||n(l);for(let l of this.addedSet)!Co(this.droppedSet,l)&&!So(this.removesSubTreeCache,l,this.mirror)||Co(this.movedSet,l)?n(l):this.droppedSet.add(l);let o=null;for(;r.length;){let l=null;if(o){let c=this.mirror.getId(M.parentNode(o.value)),u=s(o.value);c!==-1&&u!==-1&&(l=o)}if(!l){let c=r.tail;for(;c;){let u=c;if(c=c.previous,u){let h=this.mirror.getId(M.parentNode(u.value));if(s(u.value)===-1)continue;if(h!==-1){l=u;break}else{let p=u.value,g=M.parentNode(p);if(g&&g.nodeType===Node.DOCUMENT_FRAGMENT_NODE){let m=M.host(g);if(this.mirror.getId(m)!==-1){l=u;break}}}}}}if(!l){for(;r.head;)r.removeNode(r.head.value);break}o=l.previous,r.removeNode(l.value),n(l.value)}let a={texts:this.texts.map(l=>{let c=l.node,u=M.parentNode(c);return u&&u.tagName==="TEXTAREA"&&this.genTextAreaValueMutation(u),{id:this.mirror.getId(c),value:l.value}}).filter(l=>!t.has(l.id)).filter(l=>this.mirror.has(l.id)),attributes:this.attributes.map(l=>{let{attributes:c}=l;if(typeof c.style=="string"){let u=JSON.stringify(l.styleDiff),h=JSON.stringify(l._unchangedStyles);u.length<c.style.length&&(u+h).split("var(").length===c.style.split("var(").length&&(c.style=l.styleDiff)}return{id:this.mirror.getId(l.node),attributes:c}}).filter(l=>!t.has(l.id)).filter(l=>this.mirror.has(l.id)),removes:this.removes,adds:e};!a.texts.length&&!a.attributes.length&&!a.removes.length&&!a.adds.length||(this.texts=[],this.attributes=[],this.attributeMap=new WeakMap,this.removes=[],this.addedSet=new Set,this.movedSet=new Set,this.droppedSet=new Set,this.removesSubTreeCache=new Set,this.movedMap={},this.mutationCb(a))}),v(this,"genTextAreaValueMutation",e=>{let t=this.attributeMap.get(e);t||(t={node:e,attributes:{},styleDiff:{},_unchangedStyles:{}},this.attributes.push(t),this.attributeMap.set(e,t)),t.attributes.value=Array.from(M.childNodes(e),r=>M.textContent(r)||"").join("")}),v(this,"processMutation",e=>{if(!yr(e.target,this.mirror,this.slimDOMOptions))switch(e.type){case"characterData":{let t=M.textContent(e.target);!te(e.target,this.blockClass,this.blockSelector,!1)&&t!==e.oldValue&&this.texts.push({value:Vo(e.target,this.maskTextClass,this.maskTextSelector,!0)&&t?this.maskTextFn?this.maskTextFn(t,an(e.target)):t.replace(/[\S]/g,"*"):t,node:e.target});break}case"attributes":{let t=e.target,r=e.attributeName,s=e.target.getAttribute(r);if(r==="value"){let o=Os(t);s=As({element:t,maskInputOptions:this.maskInputOptions,tagName:t.tagName,type:o,value:s,maskInputFn:this.maskInputFn})}if(te(e.target,this.blockClass,this.blockSelector,!1)||s===e.oldValue)return;let n=this.attributeMap.get(e.target);if(t.tagName==="IFRAME"&&r==="src"&&!this.keepIframeSrcFn(s))if(!t.contentDocument)r="rr_src";else return;if(n||(n={node:e.target,attributes:{},styleDiff:{},_unchangedStyles:{}},this.attributes.push(n),this.attributeMap.set(e.target,n)),r==="type"&&t.tagName==="INPUT"&&(e.oldValue||"").toLowerCase()==="password"&&t.setAttribute("data-rr-is-password","true"),!Ho(t.tagName,r))if(n.attributes[r]=zo(this.doc,Te(t.tagName),Te(r),s),r==="style"){if(!this.unattachedDoc)try{this.unattachedDoc=document.implementation.createHTMLDocument()}catch(a){this.unattachedDoc=this.doc}let o=this.unattachedDoc.createElement("span");e.oldValue&&o.setAttribute("style",e.oldValue);for(let a of Array.from(t.style)){let l=t.style.getPropertyValue(a),c=t.style.getPropertyPriority(a);l!==o.style.getPropertyValue(a)||c!==o.style.getPropertyPriority(a)?c===""?n.styleDiff[a]=l:n.styleDiff[a]=[l,c]:n._unchangedStyles[a]=[l,c]}for(let a of Array.from(o.style))t.style.getPropertyValue(a)===""&&(n.styleDiff[a]=!1)}else r==="open"&&t.tagName==="DIALOG"&&(t.matches("dialog:modal")?n.attributes.rr_open_mode="modal":n.attributes.rr_open_mode="non-modal");break}case"childList":{if(te(e.target,this.blockClass,this.blockSelector,!0))return;if(e.target.tagName==="TEXTAREA"){this.genTextAreaValueMutation(e.target);return}e.addedNodes.forEach(t=>this.genAdds(t,e.target)),e.removedNodes.forEach(t=>{let r=this.mirror.getId(t),s=gt(e.target)?this.mirror.getId(M.host(e.target)):this.mirror.getId(e.target);te(e.target,this.blockClass,this.blockSelector,!1)||yr(t,this.mirror,this.slimDOMOptions)||!gl(t,this.mirror)||(this.addedSet.has(t)?(vs(this.addedSet,t),this.droppedSet.add(t)):this.addedSet.has(e.target)&&r===-1||ln(e.target,this.mirror)||(this.movedSet.has(t)&&this.movedMap[bo(r,s)]?vs(this.movedSet,t):(this.removes.push({parentId:s,id:r,isShadow:gt(e.target)&&yt(e.target)?!0:void 0}),vp(t,this.removesSubTreeCache))),this.mapRemoves.push(t))});break}}}),v(this,"genAdds",(e,t)=>{if(!this.processedNodeManager.inOtherBuffer(e,this)&&!(this.addedSet.has(e)||this.movedSet.has(e))){if(this.mirror.hasNode(e)){if(yr(e,this.mirror,this.slimDOMOptions))return;this.movedSet.add(e);let r=null;t&&this.mirror.hasNode(t)&&(r=this.mirror.getId(t)),r&&r!==-1&&(this.movedMap[bo(this.mirror.getId(e),r)]=!0)}else this.addedSet.add(e),this.droppedSet.delete(e);te(e,this.blockClass,this.blockSelector,!1)||(M.childNodes(e).forEach(r=>this.genAdds(r)),xe(e)&&M.childNodes(M.shadowRoot(e)).forEach(r=>{this.processedNodeManager.add(r,this),this.genAdds(r,e)}))}})}init(e){["mutationCb","blockClass","blockSelector","maskTextClass","maskTextSelector","inlineStylesheet","maskInputOptions","maskTextFn","maskInputFn","keepIframeSrcFn","recordCanvas","inlineImages","slimDOMOptions","dataURLOptions","doc","mirror","iframeManager","stylesheetManager","shadowDomManager","canvasManager","processedNodeManager"].forEach(t=>{this[t]=e[t]})}freeze(){this.frozen=!0,this.canvasManager.freeze()}unfreeze(){this.frozen=!1,this.canvasManager.unfreeze(),this.emit()}isFrozen(){return this.frozen}lock(){this.locked=!0,this.canvasManager.lock()}unlock(){this.locked=!1,this.canvasManager.unlock(),this.emit()}reset(){this.shadowDomManager.reset(),this.canvasManager.reset()}};A=i=>vt?(...t)=>{try{return i(...t)}catch(r){if(vt&&vt(r)===!0)return;throw r}}:i,$e=[];Tp=["INPUT","TEXTAREA","SELECT"],Eo=new WeakMap;Ur=class{constructor(e){v(this,"iframeIdToRemoteIdMap",new WeakMap),v(this,"iframeRemoteIdToIdMap",new WeakMap),this.generateIdFn=e}getId(e,t,r,s){let n=r||this.getIdToRemoteIdMap(e),o=s||this.getRemoteIdToIdMap(e),a=n.get(t);return a||(a=this.generateIdFn(),n.set(t,a),o.set(a,t)),a}getIds(e,t){let r=this.getIdToRemoteIdMap(e),s=this.getRemoteIdToIdMap(e);return t.map(n=>this.getId(e,n,r,s))}getRemoteId(e,t,r){let s=r||this.getRemoteIdToIdMap(e);if(typeof t!="number")return t;let n=s.get(t);return n||-1}getRemoteIds(e,t){let r=this.getRemoteIdToIdMap(e);return t.map(s=>this.getRemoteId(e,s,r))}reset(e){if(!e){this.iframeIdToRemoteIdMap=new WeakMap,this.iframeRemoteIdToIdMap=new WeakMap;return}this.iframeIdToRemoteIdMap.delete(e),this.iframeRemoteIdToIdMap.delete(e)}getIdToRemoteIdMap(e){let t=this.iframeIdToRemoteIdMap.get(e);return t||(t=new Map,this.iframeIdToRemoteIdMap.set(e,t)),t}getRemoteIdToIdMap(e){let t=this.iframeRemoteIdToIdMap.get(e);return t||(t=new Map,this.iframeRemoteIdToIdMap.set(e,t)),t}},bs=class{constructor(e){v(this,"iframes",new WeakMap),v(this,"crossOriginIframeMap",new WeakMap),v(this,"crossOriginIframeMirror",new Ur(Wo)),v(this,"crossOriginIframeStyleMirror"),v(this,"crossOriginIframeRootIdMap",new WeakMap),v(this,"mirror"),v(this,"mutationCb"),v(this,"wrappedEmit"),v(this,"loadListener"),v(this,"stylesheetManager"),v(this,"recordCrossOriginIframes"),this.mutationCb=e.mutationCb,this.wrappedEmit=e.wrappedEmit,this.stylesheetManager=e.stylesheetManager,this.recordCrossOriginIframes=e.recordCrossOriginIframes,this.crossOriginIframeStyleMirror=new Ur(this.stylesheetManager.styleMirror.generateId.bind(this.stylesheetManager.styleMirror)),this.mirror=e.mirror,this.recordCrossOriginIframes&&window.addEventListener("message",this.handleMessage.bind(this))}addIframe(e){this.iframes.set(e,!0),e.contentWindow&&this.crossOriginIframeMap.set(e.contentWindow,e)}addLoadListener(e){this.loadListener=e}attachIframe(e,t){var r,s;this.mutationCb({adds:[{parentId:this.mirror.getId(e),nextId:null,node:t}],removes:[],texts:[],attributes:[],isAttachIframe:!0}),this.recordCrossOriginIframes&&((r=e.contentWindow)==null||r.addEventListener("message",this.handleMessage.bind(this))),(s=this.loadListener)==null||s.call(this,e),e.contentDocument&&e.contentDocument.adoptedStyleSheets&&e.contentDocument.adoptedStyleSheets.length>0&&this.stylesheetManager.adoptStyleSheets(e.contentDocument.adoptedStyleSheets,this.mirror.getId(e.contentDocument))}handleMessage(e){let t=e;if(t.data.type!=="rrweb"||t.origin!==t.data.origin||!e.source)return;let s=this.crossOriginIframeMap.get(e.source);if(!s)return;let n=this.transformCrossOriginEvent(s,t.data.event);n&&this.wrappedEmit(n,t.data.isCheckout)}transformCrossOriginEvent(e,t){var r;switch(t.type){case x.FullSnapshot:{this.crossOriginIframeMirror.reset(e),this.crossOriginIframeStyleMirror.reset(e),this.replaceIdOnNode(t.data.node,e);let s=t.data.node.id;return this.crossOriginIframeRootIdMap.set(e,s),this.patchRootIdOnNode(t.data.node,s),{timestamp:t.timestamp,type:x.IncrementalSnapshot,data:{source:E.Mutation,adds:[{parentId:this.mirror.getId(e),nextId:null,node:t.data.node}],removes:[],texts:[],attributes:[],isAttachIframe:!0}}}case x.Meta:case x.Load:case x.DomContentLoaded:return!1;case x.Plugin:return t;case x.Custom:return this.replaceIds(t.data.payload,e,["id","parentId","previousId","nextId"]),t;case x.IncrementalSnapshot:switch(t.data.source){case E.Mutation:return t.data.adds.forEach(s=>{this.replaceIds(s,e,["parentId","nextId","previousId"]),this.replaceIdOnNode(s.node,e);let n=this.crossOriginIframeRootIdMap.get(e);n&&this.patchRootIdOnNode(s.node,n)}),t.data.removes.forEach(s=>{this.replaceIds(s,e,["parentId","id"])}),t.data.attributes.forEach(s=>{this.replaceIds(s,e,["id"])}),t.data.texts.forEach(s=>{this.replaceIds(s,e,["id"])}),t;case E.Drag:case E.TouchMove:case E.MouseMove:return t.data.positions.forEach(s=>{this.replaceIds(s,e,["id"])}),t;case E.ViewportResize:return!1;case E.MediaInteraction:case E.MouseInteraction:case E.Scroll:case E.CanvasMutation:case E.Input:return this.replaceIds(t.data,e,["id"]),t;case E.StyleSheetRule:case E.StyleDeclaration:return this.replaceIds(t.data,e,["id"]),this.replaceStyleIds(t.data,e,["styleId"]),t;case E.Font:return t;case E.Selection:return t.data.ranges.forEach(s=>{this.replaceIds(s,e,["start","end"])}),t;case E.AdoptedStyleSheet:return this.replaceIds(t.data,e,["id"]),this.replaceStyleIds(t.data,e,["styleIds"]),(r=t.data.styles)==null||r.forEach(s=>{this.replaceStyleIds(s,e,["styleId"])}),t}}return!1}replace(e,t,r,s){for(let n of s)!Array.isArray(t[n])&&typeof t[n]!="number"||(Array.isArray(t[n])?t[n]=e.getIds(r,t[n]):t[n]=e.getId(r,t[n]));return t}replaceIds(e,t,r){return this.replace(this.crossOriginIframeMirror,e,t,r)}replaceStyleIds(e,t,r){return this.replace(this.crossOriginIframeStyleMirror,e,t,r)}replaceIdOnNode(e,t){this.replaceIds(e,t,["id","rootId"]),"childNodes"in e&&e.childNodes.forEach(r=>{this.replaceIdOnNode(r,t)})}patchRootIdOnNode(e,t){e.type!==ye.Document&&!e.rootId&&(e.rootId=t),"childNodes"in e&&e.childNodes.forEach(r=>{this.patchRootIdOnNode(r,t)})}},Ss=class{constructor(e){v(this,"shadowDoms",new WeakSet),v(this,"mutationCb"),v(this,"scrollCb"),v(this,"bypassOptions"),v(this,"mirror"),v(this,"restoreHandlers",[]),this.mutationCb=e.mutationCb,this.scrollCb=e.scrollCb,this.bypassOptions=e.bypassOptions,this.mirror=e.mirror,this.init()}init(){this.reset(),this.patchAttachShadow(Element,document)}addShadowRoot(e,t){if(!yt(e)||this.shadowDoms.has(e))return;this.shadowDoms.add(e);let r=Cl({...this.bypassOptions,doc:t,mutationCb:this.mutationCb,mirror:this.mirror,shadowDomManager:this},e);this.restoreHandlers.push(()=>r.disconnect()),this.restoreHandlers.push(El({...this.bypassOptions,scrollCb:this.scrollCb,doc:e,mirror:this.mirror})),setTimeout(()=>{e.adoptedStyleSheets&&e.adoptedStyleSheets.length>0&&this.bypassOptions.stylesheetManager.adoptStyleSheets(e.adoptedStyleSheets,this.mirror.getId(M.host(e))),this.restoreHandlers.push(xl({mirror:this.mirror,stylesheetManager:this.bypassOptions.stylesheetManager},e))},0)}observeAttachShadow(e){!e.contentWindow||!e.contentDocument||this.patchAttachShadow(e.contentWindow.Element,e.contentDocument)}patchAttachShadow(e,t){let r=this;this.restoreHandlers.push(Fe(e.prototype,"attachShadow",function(s){return function(n){let o=s.call(this,n),a=M.shadowRoot(this);return a&&pn(this)&&r.addShadowRoot(a,t),o}}))}reset(){this.restoreHandlers.forEach(e=>{try{e()}catch(t){}}),this.restoreHandlers=[],this.shadowDoms=new WeakSet}},Ye="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",mt=typeof Uint8Array=="undefined"?[]:new Uint8Array(256);for(pt=0;pt<Ye.length;pt++)mt[Ye.charCodeAt(pt)]=pt;Lp=function(i){var e=new Uint8Array(i),t,r=e.length,s="";for(t=0;t<r;t+=3)s+=Ye[e[t]>>2],s+=Ye[(e[t]&3)<<4|e[t+1]>>4],s+=Ye[(e[t+1]&15)<<2|e[t+2]>>6],s+=Ye[e[t+2]&63];return r%3===2?s=s.substring(0,s.length-1)+"=":r%3===1&&(s=s.substring(0,s.length-2)+"=="),s},_p=function(i){var e=i.length*.75,t=i.length,r,s=0,n,o,a,l;i[i.length-1]==="="&&(e--,i[i.length-2]==="="&&e--);var c=new ArrayBuffer(e),u=new Uint8Array(c);for(r=0;r<t;r+=4)n=mt[i.charCodeAt(r)],o=mt[i.charCodeAt(r+1)],a=mt[i.charCodeAt(r+2)],l=mt[i.charCodeAt(r+3)],u[s++]=n<<2|o>>4,u[s++]=(o&15)<<4|a>>2,u[s++]=(a&3)<<6|l&63;return c},xo=new Map;Il=(i,e,t)=>{if(!i||!(kl(i,e)||typeof i=="object"))return;let r=i.constructor.name,s=Fp(t,r),n=s.indexOf(i);return n===-1&&(n=s.length,s.push(i)),n};Tl=(i,e,t)=>i.map(r=>wr(r,e,t)),kl=(i,e)=>!!["WebGLActiveInfo","WebGLBuffer","WebGLFramebuffer","WebGLProgram","WebGLRenderbuffer","WebGLShader","WebGLShaderPrecisionFormat","WebGLTexture","WebGLUniformLocation","WebGLVertexArrayObject","WebGLVertexArrayObjectOES"].filter(s=>typeof e[s]=="function").find(s=>i instanceof e[s]);Ml="KGZ1bmN0aW9uKCkgewogICJ1c2Ugc3RyaWN0IjsKICB2YXIgY2hhcnMgPSAiQUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVphYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ejAxMjM0NTY3ODkrLyI7CiAgdmFyIGxvb2t1cCA9IHR5cGVvZiBVaW50OEFycmF5ID09PSAidW5kZWZpbmVkIiA/IFtdIDogbmV3IFVpbnQ4QXJyYXkoMjU2KTsKICBmb3IgKHZhciBpID0gMDsgaSA8IGNoYXJzLmxlbmd0aDsgaSsrKSB7CiAgICBsb29rdXBbY2hhcnMuY2hhckNvZGVBdChpKV0gPSBpOwogIH0KICB2YXIgZW5jb2RlID0gZnVuY3Rpb24oYXJyYXlidWZmZXIpIHsKICAgIHZhciBieXRlcyA9IG5ldyBVaW50OEFycmF5KGFycmF5YnVmZmVyKSwgaTIsIGxlbiA9IGJ5dGVzLmxlbmd0aCwgYmFzZTY0ID0gIiI7CiAgICBmb3IgKGkyID0gMDsgaTIgPCBsZW47IGkyICs9IDMpIHsKICAgICAgYmFzZTY0ICs9IGNoYXJzW2J5dGVzW2kyXSA+PiAyXTsKICAgICAgYmFzZTY0ICs9IGNoYXJzWyhieXRlc1tpMl0gJiAzKSA8PCA0IHwgYnl0ZXNbaTIgKyAxXSA+PiA0XTsKICAgICAgYmFzZTY0ICs9IGNoYXJzWyhieXRlc1tpMiArIDFdICYgMTUpIDw8IDIgfCBieXRlc1tpMiArIDJdID4+IDZdOwogICAgICBiYXNlNjQgKz0gY2hhcnNbYnl0ZXNbaTIgKyAyXSAmIDYzXTsKICAgIH0KICAgIGlmIChsZW4gJSAzID09PSAyKSB7CiAgICAgIGJhc2U2NCA9IGJhc2U2NC5zdWJzdHJpbmcoMCwgYmFzZTY0Lmxlbmd0aCAtIDEpICsgIj0iOwogICAgfSBlbHNlIGlmIChsZW4gJSAzID09PSAxKSB7CiAgICAgIGJhc2U2NCA9IGJhc2U2NC5zdWJzdHJpbmcoMCwgYmFzZTY0Lmxlbmd0aCAtIDIpICsgIj09IjsKICAgIH0KICAgIHJldHVybiBiYXNlNjQ7CiAgfTsKICBjb25zdCBsYXN0QmxvYk1hcCA9IC8qIEBfX1BVUkVfXyAqLyBuZXcgTWFwKCk7CiAgY29uc3QgdHJhbnNwYXJlbnRCbG9iTWFwID0gLyogQF9fUFVSRV9fICovIG5ldyBNYXAoKTsKICBhc3luYyBmdW5jdGlvbiBnZXRUcmFuc3BhcmVudEJsb2JGb3Iod2lkdGgsIGhlaWdodCwgZGF0YVVSTE9wdGlvbnMpIHsKICAgIGNvbnN0IGlkID0gYCR7d2lkdGh9LSR7aGVpZ2h0fWA7CiAgICBpZiAoIk9mZnNjcmVlbkNhbnZhcyIgaW4gZ2xvYmFsVGhpcykgewogICAgICBpZiAodHJhbnNwYXJlbnRCbG9iTWFwLmhhcyhpZCkpIHJldHVybiB0cmFuc3BhcmVudEJsb2JNYXAuZ2V0KGlkKTsKICAgICAgY29uc3Qgb2Zmc2NyZWVuID0gbmV3IE9mZnNjcmVlbkNhbnZhcyh3aWR0aCwgaGVpZ2h0KTsKICAgICAgb2Zmc2NyZWVuLmdldENvbnRleHQoIjJkIik7CiAgICAgIGNvbnN0IGJsb2IgPSBhd2FpdCBvZmZzY3JlZW4uY29udmVydFRvQmxvYihkYXRhVVJMT3B0aW9ucyk7CiAgICAgIGNvbnN0IGFycmF5QnVmZmVyID0gYXdhaXQgYmxvYi5hcnJheUJ1ZmZlcigpOwogICAgICBjb25zdCBiYXNlNjQgPSBlbmNvZGUoYXJyYXlCdWZmZXIpOwogICAgICB0cmFuc3BhcmVudEJsb2JNYXAuc2V0KGlkLCBiYXNlNjQpOwogICAgICByZXR1cm4gYmFzZTY0OwogICAgfSBlbHNlIHsKICAgICAgcmV0dXJuICIiOwogICAgfQogIH0KICBjb25zdCB3b3JrZXIgPSBzZWxmOwogIHdvcmtlci5vbm1lc3NhZ2UgPSBhc3luYyBmdW5jdGlvbihlKSB7CiAgICBpZiAoIk9mZnNjcmVlbkNhbnZhcyIgaW4gZ2xvYmFsVGhpcykgewogICAgICBjb25zdCB7IGlkLCBiaXRtYXAsIHdpZHRoLCBoZWlnaHQsIGRhdGFVUkxPcHRpb25zIH0gPSBlLmRhdGE7CiAgICAgIGNvbnN0IHRyYW5zcGFyZW50QmFzZTY0ID0gZ2V0VHJhbnNwYXJlbnRCbG9iRm9yKAogICAgICAgIHdpZHRoLAogICAgICAgIGhlaWdodCwKICAgICAgICBkYXRhVVJMT3B0aW9ucwogICAgICApOwogICAgICBjb25zdCBvZmZzY3JlZW4gPSBuZXcgT2Zmc2NyZWVuQ2FudmFzKHdpZHRoLCBoZWlnaHQpOwogICAgICBjb25zdCBjdHggPSBvZmZzY3JlZW4uZ2V0Q29udGV4dCgiMmQiKTsKICAgICAgY3R4LmRyYXdJbWFnZShiaXRtYXAsIDAsIDApOwogICAgICBiaXRtYXAuY2xvc2UoKTsKICAgICAgY29uc3QgYmxvYiA9IGF3YWl0IG9mZnNjcmVlbi5jb252ZXJ0VG9CbG9iKGRhdGFVUkxPcHRpb25zKTsKICAgICAgY29uc3QgdHlwZSA9IGJsb2IudHlwZTsKICAgICAgY29uc3QgYXJyYXlCdWZmZXIgPSBhd2FpdCBibG9iLmFycmF5QnVmZmVyKCk7CiAgICAgIGNvbnN0IGJhc2U2NCA9IGVuY29kZShhcnJheUJ1ZmZlcik7CiAgICAgIGlmICghbGFzdEJsb2JNYXAuaGFzKGlkKSAmJiBhd2FpdCB0cmFuc3BhcmVudEJhc2U2NCA9PT0gYmFzZTY0KSB7CiAgICAgICAgbGFzdEJsb2JNYXAuc2V0KGlkLCBiYXNlNjQpOwogICAgICAgIHJldHVybiB3b3JrZXIucG9zdE1lc3NhZ2UoeyBpZCB9KTsKICAgICAgfQogICAgICBpZiAobGFzdEJsb2JNYXAuZ2V0KGlkKSA9PT0gYmFzZTY0KSByZXR1cm4gd29ya2VyLnBvc3RNZXNzYWdlKHsgaWQgfSk7CiAgICAgIHdvcmtlci5wb3N0TWVzc2FnZSh7CiAgICAgICAgaWQsCiAgICAgICAgdHlwZSwKICAgICAgICBiYXNlNjQsCiAgICAgICAgd2lkdGgsCiAgICAgICAgaGVpZ2h0CiAgICAgIH0pOwogICAgICBsYXN0QmxvYk1hcC5zZXQoaWQsIGJhc2U2NCk7CiAgICB9IGVsc2UgewogICAgICByZXR1cm4gd29ya2VyLnBvc3RNZXNzYWdlKHsgaWQ6IGUuZGF0YS5pZCB9KTsKICAgIH0KICB9Owp9KSgpOwovLyMgc291cmNlTWFwcGluZ1VSTD1pbWFnZS1iaXRtYXAtZGF0YS11cmwtd29ya2VyLUlKcEM3Z19iLmpzLm1hcAo=",zp=i=>Uint8Array.from(atob(i),e=>e.charCodeAt(0)),ko=typeof window!="undefined"&&window.Blob&&new Blob([zp(Ml)],{type:"text/javascript;charset=utf-8"});Cs=class{constructor(e){v(this,"pendingCanvasMutations",new Map),v(this,"rafStamps",{latestId:0,invokeId:null}),v(this,"mirror"),v(this,"mutationCb"),v(this,"resetObservers"),v(this,"frozen",!1),v(this,"locked",!1),v(this,"processMutation",(l,c)=>{(this.rafStamps.invokeId&&this.rafStamps.latestId!==this.rafStamps.invokeId||!this.rafStamps.invokeId)&&(this.rafStamps.invokeId=this.rafStamps.latestId),this.pendingCanvasMutations.has(l)||this.pendingCanvasMutations.set(l,[]),this.pendingCanvasMutations.get(l).push(c)});let{sampling:t="all",win:r,blockClass:s,blockSelector:n,recordCanvas:o,dataURLOptions:a}=e;this.mutationCb=e.mutationCb,this.mirror=e.mirror,o&&t==="all"&&this.initCanvasMutationObserver(r,s,n),o&&typeof t=="number"&&this.initCanvasFPSObserver(t,r,s,n,{dataURLOptions:a})}reset(){this.pendingCanvasMutations.clear(),this.resetObservers&&this.resetObservers()}freeze(){this.frozen=!0}unfreeze(){this.frozen=!1}lock(){this.locked=!0}unlock(){this.locked=!1}initCanvasFPSObserver(e,t,r,s,n){let o=Io(t,r,s,!0),a=new Map,l=new Hp;l.onmessage=g=>{let{id:m}=g.data;if(a.set(m,!1),!("base64"in g.data))return;let{base64:f,type:y,width:b,height:w}=g.data;this.mutationCb({id:m,type:be["2D"],commands:[{property:"clearRect",args:[0,0,b,w]},{property:"drawImage",args:[{rr_type:"ImageBitmap",args:[{rr_type:"Blob",data:[{rr_type:"ArrayBuffer",base64:f}],type:y}]},0,0]}]})};let c=1e3/e,u=0,h,d=()=>{let g=[];return t.document.querySelectorAll("canvas").forEach(m=>{te(m,r,s,!0)||g.push(m)}),g},p=g=>{if(u&&g-u<c){h=requestAnimationFrame(p);return}u=g,d().forEach(async m=>{var f;let y=this.mirror.getId(m);if(a.get(y)||m.width===0||m.height===0)return;if(a.set(y,!0),["webgl","webgl2"].includes(m.__context)){let w=m.getContext(m.__context);((f=w==null?void 0:w.getContextAttributes())==null?void 0:f.preserveDrawingBuffer)===!1&&w.clear(w.COLOR_BUFFER_BIT)}let b=await createImageBitmap(m);l.postMessage({id:y,bitmap:b,width:m.width,height:m.height,dataURLOptions:n.dataURLOptions},[b])}),h=requestAnimationFrame(p)};h=requestAnimationFrame(p),this.resetObservers=()=>{o(),cancelAnimationFrame(h)}}initCanvasMutationObserver(e,t,r){this.startRAFTimestamping(),this.startPendingCanvasMutationFlusher();let s=Io(e,t,r,!1),n=Up(this.processMutation.bind(this),e,t,r),o=Wp(this.processMutation.bind(this),e,t,r);this.resetObservers=()=>{s(),n(),o()}}startPendingCanvasMutationFlusher(){requestAnimationFrame(()=>this.flushPendingCanvasMutations())}startRAFTimestamping(){let e=t=>{this.rafStamps.latestId=t,requestAnimationFrame(e)};requestAnimationFrame(e)}flushPendingCanvasMutations(){this.pendingCanvasMutations.forEach((e,t)=>{let r=this.mirror.getId(t);this.flushPendingCanvasMutationFor(t,r)}),requestAnimationFrame(()=>this.flushPendingCanvasMutations())}flushPendingCanvasMutationFor(e,t){if(this.frozen||this.locked)return;let r=this.pendingCanvasMutations.get(e);if(!r||t===-1)return;let s=r.map(o=>{let{type:a,...l}=o;return l}),{type:n}=r[0];this.mutationCb({id:t,type:n,commands:s}),this.pendingCanvasMutations.delete(e)}},Es=class{constructor(e){v(this,"trackedLinkElements",new WeakSet),v(this,"mutationCb"),v(this,"adoptedStyleSheetCb"),v(this,"styleMirror",new At),this.mutationCb=e.mutationCb,this.adoptedStyleSheetCb=e.adoptedStyleSheetCb}attachLinkElement(e,t){"_cssText"in t.attributes&&this.mutationCb({adds:[],removes:[],texts:[],attributes:[{id:t.id,attributes:t.attributes}]}),this.trackLinkElement(e)}trackLinkElement(e){this.trackedLinkElements.has(e)||(this.trackedLinkElements.add(e),this.trackStylesheetInLinkElement(e))}adoptStyleSheets(e,t){if(e.length===0)return;let r={id:t,styleIds:[]},s=[];for(let n of e){let o;this.styleMirror.has(n)?o=this.styleMirror.getId(n):(o=this.styleMirror.add(n),s.push({styleId:o,rules:Array.from(n.rules||CSSRule,(a,l)=>({rule:Fo(a,n.href),index:l}))})),r.styleIds.push(o)}s.length>0&&(r.styles=s),this.adoptedStyleSheetCb(r)}reset(){this.styleMirror.reset(),this.trackedLinkElements=new WeakSet}trackStylesheetInLinkElement(e){}},xs=class{constructor(){v(this,"nodeMap",new WeakMap),v(this,"active",!1)}inOtherBuffer(e,t){let r=this.nodeMap.get(e);return r&&Array.from(r).some(s=>s!==t)}add(e,t){this.active||(this.active=!0,requestAnimationFrame(()=>{this.nodeMap=new WeakMap,this.active=!1})),this.nodeMap.set(e,(this.nodeMap.get(e)||new Set).add(t))}destroy(){}},Br=!1;try{if(Array.from([1],i=>i*2)[0]!==2){let i=document.createElement("iframe");document.body.appendChild(i),Array.from=((Tn=i.contentWindow)==null?void 0:Tn.Array.from)||Array.from,document.body.removeChild(i)}}catch(i){console.debug("Unable to override Array.from",i)}le=Uo();Re.addCustomEvent=(i,e)=>{if(!Br)throw new Error("please add custom event after start recording");Z({type:x.Custom,data:{tag:i,payload:e}})};Re.freezePage=()=>{$e.forEach(i=>i.freeze())};Re.takeFullSnapshot=i=>{if(!Br)throw new Error("please take full snapshot after start recording");vr(i)};Re.mirror=le;Vp=Object.freeze(Object.defineProperty({__proto__:null,default:Rl},Symbol.toStringTag,{value:"Module"}));Is=class{constructor(e=[],t){v(this,"timeOffset",0),v(this,"speed"),v(this,"actions"),v(this,"raf",null),v(this,"lastTimestamp"),this.actions=e,this.speed=t.speed}addAction(e){let t=this.raf===!0;if(!this.actions.length||this.actions[this.actions.length-1].delay<=e.delay)this.actions.push(e);else{let r=this.findActionIndex(e);this.actions.splice(r,0,e)}t&&(this.raf=requestAnimationFrame(this.rafCheck.bind(this)))}start(){this.timeOffset=0,this.lastTimestamp=performance.now(),this.raf=requestAnimationFrame(this.rafCheck.bind(this))}rafCheck(){let e=performance.now();for(this.timeOffset+=(e-this.lastTimestamp)*this.speed,this.lastTimestamp=e;this.actions.length;){let t=this.actions[0];if(this.timeOffset>=t.delay)this.actions.shift(),t.doAction();else break}this.actions.length>0?this.raf=requestAnimationFrame(this.rafCheck.bind(this)):this.raf=!0}clear(){this.raf&&(this.raf!==!0&&cancelAnimationFrame(this.raf),this.raf=null),this.actions.length=0}setSpeed(e){this.speed=e}isActive(){return this.raf!==null}findActionIndex(e){let t=0,r=this.actions.length-1;for(;t<=r;){let s=Math.floor((t+r)/2);if(this.actions[s].delay<e.delay)t=s+1;else if(this.actions[s].delay>e.delay)r=s-1;else return s+1}return t}};(function(i){i[i.NotStarted=0]="NotStarted",i[i.Running=1]="Running",i[i.Stopped=2]="Stopped"})(Xe||(Xe={}));Nl={type:"xstate.init"};Do=function(i,e){return i.actions.forEach(function(t){var r=t.exec;return r&&r(i.context,e)})};Xp=i=>[`.${i} { background: currentColor }`,"noscript { display: none !important; }"],Po=new Map;Zp=["WebGLActiveInfo","WebGLBuffer","WebGLFramebuffer","WebGLProgram","WebGLRenderbuffer","WebGLShader","WebGLShaderPrecisionFormat","WebGLTexture","WebGLUniformLocation","WebGLVertexArrayObject"];ks=class{constructor(e){v(this,"mediaMap",new Map),v(this,"warn"),v(this,"service"),v(this,"speedService"),v(this,"emitter"),v(this,"getCurrentTime"),v(this,"metadataCallbackMap",new Map),this.warn=e.warn,this.service=e.service,this.speedService=e.speedService,this.emitter=e.emitter,this.getCurrentTime=e.getCurrentTime,this.emitter.on(O.Start,this.start.bind(this)),this.emitter.on(O.SkipStart,this.start.bind(this)),this.emitter.on(O.Pause,this.pause.bind(this)),this.emitter.on(O.Finish,this.pause.bind(this)),this.speedService.subscribe(()=>{this.syncAllMediaElements()})}syncAllMediaElements(e={pause:!1}){this.mediaMap.forEach((t,r)=>{this.syncTargetWithState(r),e.pause&&r.pause()})}start(){this.syncAllMediaElements()}pause(){this.syncAllMediaElements({pause:!0})}seekTo({time:e,target:t,mediaState:r}){if(r.isPlaying){let n=(e-r.lastInteractionTimeOffset)/1e3*r.playbackRate,o="duration"in t&&t.duration;if(Number.isNaN(o)){this.waitForMetadata(t);return}let a=r.currentTimeAtLastInteraction+n;t.loop&&o!==!1&&(a=a%o),t.currentTime=a}else t.pause(),t.currentTime=r.currentTimeAtLastInteraction}waitForMetadata(e){if(this.metadataCallbackMap.has(e)||!("addEventListener"in e))return;let t=()=>{this.metadataCallbackMap.delete(e);let r=this.mediaMap.get(e);r&&this.seekTo({time:this.getCurrentTime(),target:e,mediaState:r})};this.metadataCallbackMap.set(e,t),e.addEventListener("loadedmetadata",t,{once:!0})}getMediaStateFromMutation({target:e,timeOffset:t,mutation:r}){var p,g,m,f,y;let s=this.mediaMap.get(e),{type:n,playbackRate:o,currentTime:a,muted:l,volume:c,loop:u}=r;return{isPlaying:n===Ee.Play||n!==Ee.Pause&&((s==null?void 0:s.isPlaying)||e.getAttribute("autoplay")!==null),currentTimeAtLastInteraction:(p=a!=null?a:s==null?void 0:s.currentTimeAtLastInteraction)!=null?p:0,lastInteractionTimeOffset:t,playbackRate:(g=o!=null?o:s==null?void 0:s.playbackRate)!=null?g:1,volume:(m=c!=null?c:s==null?void 0:s.volume)!=null?m:1,muted:(f=l!=null?l:s==null?void 0:s.muted)!=null?f:e.getAttribute("muted")===null,loop:(y=u!=null?u:s==null?void 0:s.loop)!=null?y:e.getAttribute("loop")===null}}syncTargetWithState(e){let t=this.mediaMap.get(e);if(!t)return;let{muted:r,loop:s,volume:n,isPlaying:o}=t,a=this.service.state.matches("paused"),l=t.playbackRate*this.speedService.state.context.timer.speed;try{this.seekTo({time:this.getCurrentTime(),target:e,mediaState:t}),e.volume!==n&&(e.volume=n),e.muted=r,e.loop=s,e.playbackRate!==l&&(e.playbackRate=l),o&&!a?e.play():e.pause()}catch(c){this.warn(`Failed to replay media interactions: ${c.message||c}`)}}addMediaElements(e,t,r){if(!["AUDIO","VIDEO"].includes(e.nodeName))return;let s=e,n=r.getMeta(s);if(!n||!("attributes"in n))return;let o=this.service.state.matches("paused"),a=n.attributes,l=!1;a.rr_mediaState?l=a.rr_mediaState==="played":l=s.getAttribute("autoplay")!==null,l&&o&&s.pause();let c=1;typeof a.rr_mediaPlaybackRate=="number"&&(c=a.rr_mediaPlaybackRate);let u=!1;typeof a.rr_mediaMuted=="boolean"?u=a.rr_mediaMuted:u=s.getAttribute("muted")!==null;let h=!1;typeof a.rr_mediaLoop=="boolean"?h=a.rr_mediaLoop:h=s.getAttribute("loop")!==null;let d=1;typeof a.rr_mediaVolume=="number"&&(d=a.rr_mediaVolume);let p=0;typeof a.rr_mediaCurrentTime=="number"&&(p=a.rr_mediaCurrentTime),this.mediaMap.set(s,{isPlaying:l,currentTimeAtLastInteraction:p,lastInteractionTimeOffset:t,playbackRate:c,volume:d,muted:u,loop:h}),this.syncTargetWithState(s)}mediaMutation({target:e,timeOffset:t,mutation:r}){this.mediaMap.set(e,this.getMediaStateFromMutation({target:e,timeOffset:t,mutation:r})),this.syncTargetWithState(e)}isSupportedMediaElement(e){return["AUDIO","VIDEO"].includes(e.nodeName)}reset(){this.mediaMap.clear()}};rm=5*1e3,im=Rl||Vp,$o="[replayer]",Ti={duration:500,lineCap:"round",lineWidth:3,strokeStyle:"red"};Ms=class{constructor(e,t){if(v(this,"wrapper"),v(this,"iframe"),v(this,"service"),v(this,"speedService"),v(this,"config"),v(this,"usingVirtualDom",!1),v(this,"virtualDom",new st),v(this,"mouse"),v(this,"mouseTail",null),v(this,"tailPositions",[]),v(this,"emitter",im()),v(this,"nextUserInteractionEvent"),v(this,"legacy_missingNodeRetryMap",{}),v(this,"cache",Zn()),v(this,"imageMap",new Map),v(this,"canvasEventMap",new Map),v(this,"mirror",Uo()),v(this,"styleMirror",new At),v(this,"mediaManager"),v(this,"firstFullSnapshot",null),v(this,"newDocumentQueue",[]),v(this,"mousePos",null),v(this,"touchActive",null),v(this,"lastMouseDownEvent",null),v(this,"lastHoveredRootNode"),v(this,"lastSelectionData",null),v(this,"constructedStyleMutations",[]),v(this,"adoptedStyleSheets",[]),v(this,"handleResize",a=>{this.iframe.style.display="inherit";for(let l of[this.mouseTail,this.iframe])l&&(l.setAttribute("width",String(a.width)),l.setAttribute("height",String(a.height)))}),v(this,"applyEventsSynchronously",a=>{for(let l of a){switch(l.type){case x.DomContentLoaded:case x.Load:case x.Custom:continue;case x.FullSnapshot:case x.Meta:case x.Plugin:case x.IncrementalSnapshot:break}this.getCastFn(l,!0)()}}),v(this,"getCastFn",(a,l=!1)=>{let c;switch(a.type){case x.DomContentLoaded:case x.Load:break;case x.Custom:c=()=>{this.emitter.emit(O.CustomEvent,a)};break;case x.Meta:c=()=>this.emitter.emit(O.Resize,{width:a.data.width,height:a.data.height});break;case x.FullSnapshot:c=()=>{var h;if(this.firstFullSnapshot){if(this.firstFullSnapshot===a){this.firstFullSnapshot=!0;return}}else this.firstFullSnapshot=!0;this.mediaManager.reset(),this.styleMirror.reset(),this.rebuildFullSnapshot(a,l),(h=this.iframe.contentWindow)==null||h.scrollTo(a.data.initialOffset)};break;case x.IncrementalSnapshot:c=()=>{if(this.applyIncremental(a,l),!l&&(a===this.nextUserInteractionEvent&&(this.nextUserInteractionEvent=null,this.backToNormal()),this.config.skipInactive&&!this.nextUserInteractionEvent)){for(let h of this.service.state.context.events)if(!(h.timestamp<=a.timestamp)&&this.isUserInteraction(h)){h.delay-a.delay>this.config.inactivePeriodThreshold*this.speedService.state.context.timer.speed&&(this.nextUserInteractionEvent=h);break}if(this.nextUserInteractionEvent){let h=this.nextUserInteractionEvent.delay-a.delay,d={speed:Math.min(Math.round(h/rm),this.config.maxSpeed)};this.speedService.send({type:"FAST_FORWARD",payload:d}),this.emitter.emit(O.SkipStart,d)}}};break}return()=>{c&&c();for(let d of this.config.plugins||[])d.handler&&d.handler(a,l,{replayer:this});this.service.send({type:"CAST_EVENT",payload:{event:a}});let h=this.service.state.context.events.length-1;if(!this.config.liveMode&&a===this.service.state.context.events[h]){let d=()=>{h<this.service.state.context.events.length-1||(this.backToNormal(),this.service.send("END"),this.emitter.emit(O.Finish))},p=50;a.type===x.IncrementalSnapshot&&a.data.source===E.MouseMove&&a.data.positions.length&&(p+=Math.max(0,-a.data.positions[0].timeOffset)),setTimeout(d,p)}this.emitter.emit(O.EventCast,a)}}),!(t!=null&&t.liveMode)&&e.length<2)throw new Error("Replayer need at least 2 events.");let r={speed:1,maxSpeed:360,root:document.body,loadTimeout:0,skipInactive:!1,inactivePeriodThreshold:10*1e3,showWarning:!0,showDebug:!1,blockClass:"rr-block",liveMode:!1,insertStyleRules:[],triggerFocus:!0,UNSAFE_replayCanvas:!1,pauseAnimation:!0,mouseTail:Ti,useVirtualDom:!0,logger:console};this.config=Object.assign({},r,t),this.handleResize=this.handleResize.bind(this),this.getCastFn=this.getCastFn.bind(this),this.applyEventsSynchronously=this.applyEventsSynchronously.bind(this),this.emitter.on(O.Resize,this.handleResize),this.setupDom();for(let a of this.config.plugins||[])a.getMirror&&a.getMirror({nodeMirror:this.mirror});this.emitter.on(O.Flush,()=>{if(this.usingVirtualDom){let a={mirror:this.mirror,applyCanvas:(l,c,u)=>{Ts({event:l,mutation:c,target:u,imageMap:this.imageMap,canvasEventMap:this.canvasEventMap,errorHandler:this.warnCanvasMutationFailed.bind(this)})},applyInput:this.applyInput.bind(this),applyScroll:this.applyScroll.bind(this),applyStyleSheetMutation:(l,c)=>{l.source===E.StyleSheetRule?this.applyStyleSheetRule(l,c):l.source===E.StyleDeclaration&&this.applyStyleDeclaration(l,c)},afterAppend:(l,c)=>{for(let u of this.config.plugins||[])u.onBuild&&u.onBuild(l,{id:c,replayer:this})}};if(this.iframe.contentDocument)try{Pr(this.iframe.contentDocument,this.virtualDom,a,this.virtualDom.mirror)}catch(l){console.warn(l)}if(this.virtualDom.destroyTree(),this.usingVirtualDom=!1,Object.keys(this.legacy_missingNodeRetryMap).length)for(let l in this.legacy_missingNodeRetryMap)try{let c=this.legacy_missingNodeRetryMap[l],u=$r(c.node,this.mirror,this.virtualDom.mirror);Pr(u,c.node,a,this.virtualDom.mirror),c.node=u}catch(c){this.warn(c)}this.constructedStyleMutations.forEach(l=>{this.applyStyleSheetMutation(l)}),this.constructedStyleMutations=[],this.adoptedStyleSheets.forEach(l=>{this.applyAdoptedStyleSheet(l)}),this.adoptedStyleSheets=[]}if(this.mousePos&&(this.moveAndHover(this.mousePos.x,this.mousePos.y,this.mousePos.id,!0,this.mousePos.debugData),this.mousePos=null),this.touchActive===!0?this.mouse.classList.add("touch-active"):this.touchActive===!1&&this.mouse.classList.remove("touch-active"),this.touchActive=null,this.lastMouseDownEvent){let[a,l]=this.lastMouseDownEvent;a.dispatchEvent(l)}this.lastMouseDownEvent=null,this.lastSelectionData&&(this.applySelection(this.lastSelectionData),this.lastSelectionData=null)}),this.emitter.on(O.PlayBack,()=>{this.firstFullSnapshot=null,this.mirror.reset(),this.styleMirror.reset(),this.mediaManager.reset()});let s=new Is([],{speed:this.config.speed});this.service=jp({events:e.map(a=>t&&t.unpackFn?t.unpackFn(a):a).sort((a,l)=>a.timestamp-l.timestamp),timer:s,timeOffset:0,baselineTime:0,lastPlayedEvent:null},{getCastFn:this.getCastFn,applyEventsSynchronously:this.applyEventsSynchronously,emitter:this.emitter}),this.service.start(),this.service.subscribe(a=>{this.emitter.emit(O.StateChange,{player:a})}),this.speedService=Yp({normalSpeed:-1,timer:s}),this.speedService.start(),this.speedService.subscribe(a=>{this.emitter.emit(O.StateChange,{speed:a})}),this.mediaManager=new ks({warn:this.warn.bind(this),service:this.service,speedService:this.speedService,emitter:this.emitter,getCurrentTime:this.getCurrentTime.bind(this)});let n=this.service.state.context.events.find(a=>a.type===x.Meta),o=this.service.state.context.events.find(a=>a.type===x.FullSnapshot);if(n){let{width:a,height:l}=n.data;setTimeout(()=>{this.emitter.emit(O.Resize,{width:a,height:l})},0)}o&&setTimeout(()=>{var a;this.firstFullSnapshot||(this.firstFullSnapshot=o,this.rebuildFullSnapshot(o),(a=this.iframe.contentWindow)==null||a.scrollTo(o.data.initialOffset))},1),this.service.state.context.events.find(Lo)&&this.mouse.classList.add("touch-device")}get timer(){return this.service.state.context.timer}on(e,t){return this.emitter.on(e,t),this}off(e,t){return this.emitter.off(e,t),this}setConfig(e){Object.keys(e).forEach(t=>{e[t],this.config[t]=e[t]}),this.config.skipInactive||this.backToNormal(),typeof e.speed!="undefined"&&this.speedService.send({type:"SET_SPEED",payload:{speed:e.speed}}),typeof e.mouseTail!="undefined"&&(e.mouseTail===!1?this.mouseTail&&(this.mouseTail.style.display="none"):(this.mouseTail||(this.mouseTail=document.createElement("canvas"),this.mouseTail.width=Number.parseFloat(this.iframe.width),this.mouseTail.height=Number.parseFloat(this.iframe.height),this.mouseTail.classList.add("replayer-mouse-tail"),this.wrapper.insertBefore(this.mouseTail,this.iframe)),this.mouseTail.style.display="inherit"))}getMetaData(){let e=this.service.state.context.events[0],t=this.service.state.context.events[this.service.state.context.events.length-1];return{startTime:e.timestamp,endTime:t.timestamp,totalTime:t.timestamp-e.timestamp}}getCurrentTime(){return this.timer.timeOffset+this.getTimeOffset()}getTimeOffset(){let{baselineTime:e,events:t}=this.service.state.context;return e-t[0].timestamp}getMirror(){return this.mirror}play(e=0){var t,r;this.service.state.matches("paused")?this.service.send({type:"PLAY",payload:{timeOffset:e}}):(this.service.send({type:"PAUSE"}),this.service.send({type:"PLAY",payload:{timeOffset:e}})),(r=(t=this.iframe.contentDocument)==null?void 0:t.getElementsByTagName("html")[0])==null||r.classList.remove("rrweb-paused"),this.emitter.emit(O.Start)}pause(e){var t,r;e===void 0&&this.service.state.matches("playing")&&this.service.send({type:"PAUSE"}),typeof e=="number"&&(this.play(e),this.service.send({type:"PAUSE"})),(r=(t=this.iframe.contentDocument)==null?void 0:t.getElementsByTagName("html")[0])==null||r.classList.add("rrweb-paused"),this.emitter.emit(O.Pause)}resume(e=0){this.warn("The 'resume' was deprecated in 1.0. Please use 'play' method which has the same interface."),this.play(e),this.emitter.emit(O.Resume)}destroy(){this.pause(),this.mirror.reset(),this.styleMirror.reset(),this.mediaManager.reset(),this.config.root.removeChild(this.wrapper),this.emitter.emit(O.Destroy)}startLive(e){this.service.send({type:"TO_LIVE",payload:{baselineTime:e}})}addEvent(e){let t=this.config.unpackFn?this.config.unpackFn(e):e;Lo(t)&&this.mouse.classList.add("touch-device"),Promise.resolve().then(()=>this.service.send({type:"ADD_EVENT",payload:{event:t}}))}enableInteract(){this.iframe.setAttribute("scrolling","auto"),this.iframe.style.pointerEvents="auto"}disableInteract(){this.iframe.setAttribute("scrolling","no"),this.iframe.style.pointerEvents="none"}resetCache(){this.cache=Zn()}setupDom(){this.wrapper=document.createElement("div"),this.wrapper.classList.add("replayer-wrapper"),this.config.root.appendChild(this.wrapper),this.mouse=document.createElement("div"),this.mouse.classList.add("replayer-mouse"),this.wrapper.appendChild(this.mouse),this.config.mouseTail!==!1&&(this.mouseTail=document.createElement("canvas"),this.mouseTail.classList.add("replayer-mouse-tail"),this.mouseTail.style.display="inherit",this.wrapper.appendChild(this.mouseTail)),this.iframe=document.createElement("iframe");let e=["allow-same-origin"];this.config.UNSAFE_replayCanvas&&e.push("allow-scripts"),this.iframe.style.display="none",this.iframe.setAttribute("sandbox",e.join(" ")),this.disableInteract(),this.wrapper.appendChild(this.iframe),this.iframe.contentWindow&&this.iframe.contentDocument&&(Gp(this.iframe.contentWindow,this.iframe.contentDocument),cn(this.iframe.contentWindow))}rebuildFullSnapshot(e,t=!1){if(!this.iframe.contentDocument)return this.warn("Looks like your replayer has been destroyed.");Object.keys(this.legacy_missingNodeRetryMap).length&&this.warn("Found unresolved missing node map",this.legacy_missingNodeRetryMap),this.legacy_missingNodeRetryMap={};let r=[],s=new Set,n=(l,c)=>{if(l.nodeName==="DIALOG"&&s.add(l),this.collectIframeAndAttachDocument(r,l),this.mediaManager.isSupportedMediaElement(l)){let{events:u}=this.service.state.context;this.mediaManager.addMediaElements(l,e.timestamp-u[0].timestamp,this.mirror)}for(let u of this.config.plugins||[])u.onBuild&&u.onBuild(l,{id:c,replayer:this})};this.usingVirtualDom&&(this.virtualDom.destroyTree(),this.usingVirtualDom=!1),this.mirror.reset(),jh(e.data.node,{doc:this.iframe.contentDocument,afterAppend:n,cache:this.cache,mirror:this.mirror}),n(this.iframe.contentDocument,e.data.node.id);for(let{mutationInQueue:l,builtNode:c}of r)this.attachDocumentToIframe(l,c),this.newDocumentQueue=this.newDocumentQueue.filter(u=>u!==l);let{documentElement:o,head:a}=this.iframe.contentDocument;this.insertStyleRules(o,a),s.forEach(l=>dr(l)),this.service.state.matches("playing")||this.iframe.contentDocument.getElementsByTagName("html")[0].classList.add("rrweb-paused"),this.emitter.emit(O.FullsnapshotRebuilded,e),t||this.waitForStylesheetLoad(),this.config.UNSAFE_replayCanvas&&this.preloadAllImages()}insertStyleRules(e,t){var r;let s=Xp(this.config.blockClass).concat(this.config.insertStyleRules);if(this.config.pauseAnimation&&s.push("html.rrweb-paused *, html.rrweb-paused *:before, html.rrweb-paused *:after { animation-play-state: paused !important; }"),!!s.length)if(this.usingVirtualDom){let n=this.virtualDom.createElement("style");this.virtualDom.mirror.add(n,fl(n,this.virtualDom.unserializedId)),e.insertBefore(n,t),n.rules.push({source:E.StyleSheetRule,adds:s.map((o,a)=>({rule:o,index:a}))})}else{let n=document.createElement("style");e.insertBefore(n,t);for(let o=0;o<s.length;o++)(r=n.sheet)==null||r.insertRule(s[o],o)}}attachDocumentToIframe(e,t){let r=this.usingVirtualDom?this.virtualDom.mirror:this.mirror,s=[],n=new Set,o=(a,l)=>{a.nodeName==="DIALOG"&&n.add(a),this.collectIframeAndAttachDocument(s,a);let c=r.getMeta(a);if((c==null?void 0:c.type)===ye.Element&&(c==null?void 0:c.tagName.toUpperCase())==="HTML"){let{documentElement:u,head:h}=t.contentDocument;this.insertStyleRules(u,h)}if(!this.usingVirtualDom)for(let u of this.config.plugins||[])u.onBuild&&u.onBuild(a,{id:l,replayer:this})};wt(e.node,{doc:t.contentDocument,mirror:r,hackCss:!0,skipChild:!1,afterAppend:o,cache:this.cache}),o(t.contentDocument,e.node.id);for(let{mutationInQueue:a,builtNode:l}of s)this.attachDocumentToIframe(a,l),this.newDocumentQueue=this.newDocumentQueue.filter(c=>c!==a);n.forEach(a=>dr(a))}collectIframeAndAttachDocument(e,t){if(Je(t,this.mirror)){let r=this.newDocumentQueue.find(s=>s.parentId===this.mirror.getId(t));r&&e.push({mutationInQueue:r,builtNode:t})}}waitForStylesheetLoad(){var e;let t=(e=this.iframe.contentDocument)==null?void 0:e.head;if(t){let r=new Set,s,n=this.service.state,o=()=>{n=this.service.state};this.emitter.on(O.Start,o),this.emitter.on(O.Pause,o);let a=()=>{this.emitter.off(O.Start,o),this.emitter.off(O.Pause,o)};t.querySelectorAll('link[rel="stylesheet"]').forEach(l=>{l.sheet||(r.add(l),l.addEventListener("load",()=>{r.delete(l),r.size===0&&s!==-1&&(n.matches("playing")&&this.play(this.getCurrentTime()),this.emitter.emit(O.LoadStylesheetEnd),s&&clearTimeout(s),a())}))}),r.size>0&&(this.service.send({type:"PAUSE"}),this.emitter.emit(O.LoadStylesheetStart),s=setTimeout(()=>{n.matches("playing")&&this.play(this.getCurrentTime()),s=-1,a()},this.config.loadTimeout))}}async preloadAllImages(){let e=[];for(let t of this.service.state.context.events)t.type===x.IncrementalSnapshot&&t.data.source===E.CanvasMutation&&(e.push(this.deserializeAndPreloadCanvasEvents(t.data,t)),("commands"in t.data?t.data.commands:[t.data]).forEach(s=>{this.preloadImages(s,t)}));return Promise.all(e)}preloadImages(e,t){if(e.property==="drawImage"&&typeof e.args[0]=="string"&&!this.imageMap.has(t)){let r=document.createElement("canvas"),s=r.getContext("2d"),n=s==null?void 0:s.createImageData(r.width,r.height);s==null||s.putImageData(n,0,0)}}async deserializeAndPreloadCanvasEvents(e,t){if(!this.canvasEventMap.has(t)){let r={isUnchanged:!0};if("commands"in e){let s=await Promise.all(e.commands.map(async n=>{let o=await Promise.all(n.args.map(Ie(this.imageMap,null,r)));return{...n,args:o}}));r.isUnchanged===!1&&this.canvasEventMap.set(t,{...e,commands:s})}else{let s=await Promise.all(e.args.map(Ie(this.imageMap,null,r)));r.isUnchanged===!1&&this.canvasEventMap.set(t,{...e,args:s})}}}applyIncremental(e,t){var r,s,n;let{data:o}=e;switch(o.source){case E.Mutation:{try{this.applyMutation(o,t)}catch(a){this.warn(`Exception in mutation ${a.message||a}`,o)}break}case E.Drag:case E.TouchMove:case E.MouseMove:if(t){let a=o.positions[o.positions.length-1];this.mousePos={x:a.x,y:a.y,id:a.id,debugData:o}}else o.positions.forEach(a=>{let l={doAction:()=>{this.moveAndHover(a.x,a.y,a.id,t,o)},delay:a.timeOffset+e.timestamp-this.service.state.context.baselineTime};this.timer.addAction(l)}),this.timer.addAction({doAction(){},delay:e.delay-((r=o.positions[0])==null?void 0:r.timeOffset)});break;case E.MouseInteraction:{if(o.id===-1)break;let a=new Event(Te(D[o.type])),l=this.mirror.getNode(o.id);if(!l)return this.debugNodeNotFound(o,o.id);this.emitter.emit(O.MouseInteraction,{type:o.type,target:l});let{triggerFocus:c}=this.config;switch(o.type){case D.Blur:"blur"in l&&l.blur();break;case D.Focus:c&&l.focus&&l.focus({preventScroll:!0});break;case D.Click:case D.TouchStart:case D.TouchEnd:case D.MouseDown:case D.MouseUp:t?(o.type===D.TouchStart?this.touchActive=!0:o.type===D.TouchEnd&&(this.touchActive=!1),o.type===D.MouseDown?this.lastMouseDownEvent=[l,a]:o.type===D.MouseUp&&(this.lastMouseDownEvent=null),this.mousePos={x:o.x||0,y:o.y||0,id:o.id,debugData:o}):(o.type===D.TouchStart&&(this.tailPositions.length=0),this.moveAndHover(o.x||0,o.y||0,o.id,t,o),o.type===D.Click?(this.mouse.classList.remove("active"),this.mouse.offsetWidth,this.mouse.classList.add("active")):o.type===D.TouchStart?(this.mouse.offsetWidth,this.mouse.classList.add("touch-active")):o.type===D.TouchEnd?this.mouse.classList.remove("touch-active"):l.dispatchEvent(a));break;case D.TouchCancel:t?this.touchActive=!1:this.mouse.classList.remove("touch-active");break;default:l.dispatchEvent(a)}break}case E.Scroll:{if(o.id===-1)break;if(this.usingVirtualDom){let a=this.virtualDom.mirror.getNode(o.id);if(!a)return this.debugNodeNotFound(o,o.id);a.scrollData=o;break}this.applyScroll(o,t);break}case E.ViewportResize:this.emitter.emit(O.Resize,{width:o.width,height:o.height});break;case E.Input:{if(o.id===-1)break;if(this.usingVirtualDom){let a=this.virtualDom.mirror.getNode(o.id);if(!a)return this.debugNodeNotFound(o,o.id);a.inputData=o;break}this.applyInput(o);break}case E.MediaInteraction:{let a=this.usingVirtualDom?this.virtualDom.mirror.getNode(o.id):this.mirror.getNode(o.id);if(!a)return this.debugNodeNotFound(o,o.id);let l=a,{events:c}=this.service.state.context;this.mediaManager.mediaMutation({target:l,timeOffset:e.timestamp-c[0].timestamp,mutation:o});break}case E.StyleSheetRule:case E.StyleDeclaration:{this.usingVirtualDom?o.styleId?this.constructedStyleMutations.push(o):o.id&&((s=this.virtualDom.mirror.getNode(o.id))==null||s.rules.push(o)):this.applyStyleSheetMutation(o);break}case E.CanvasMutation:{if(!this.config.UNSAFE_replayCanvas)return;if(this.usingVirtualDom){let a=this.virtualDom.mirror.getNode(o.id);if(!a)return this.debugNodeNotFound(o,o.id);a.canvasMutations.push({event:e,mutation:o})}else{let a=this.mirror.getNode(o.id);if(!a)return this.debugNodeNotFound(o,o.id);Ts({event:e,mutation:o,target:a,imageMap:this.imageMap,canvasEventMap:this.canvasEventMap,errorHandler:this.warnCanvasMutationFailed.bind(this)})}break}case E.Font:{try{let a=new FontFace(o.family,o.buffer?new Uint8Array(JSON.parse(o.fontSource)):o.fontSource,o.descriptors);(n=this.iframe.contentDocument)==null||n.fonts.add(a)}catch(a){this.warn(a)}break}case E.Selection:{if(t){this.lastSelectionData=o;break}this.applySelection(o);break}case E.AdoptedStyleSheet:{this.usingVirtualDom?this.adoptedStyleSheets.push(o):this.applyAdoptedStyleSheet(o);break}}}applyMutation(e,t){if(this.config.useVirtualDom&&!this.usingVirtualDom&&t&&(this.usingVirtualDom=!0,sp(this.iframe.contentDocument,this.mirror,this.virtualDom),Object.keys(this.legacy_missingNodeRetryMap).length))for(let c in this.legacy_missingNodeRetryMap)try{let u=this.legacy_missingNodeRetryMap[c],h=dl(u.node,this.virtualDom,this.mirror);h&&(u.node=h)}catch(u){this.warn(u)}let r=this.usingVirtualDom?this.virtualDom.mirror:this.mirror;e.removes=e.removes.filter(c=>r.getNode(c.id)?!0:(this.warnNodeNotFound(e,c.id),!1)),e.removes.forEach(c=>{var u;let h=r.getNode(c.id);if(!h)return;let d=r.getNode(c.parentId);if(!d)return this.warnNodeNotFound(e,c.parentId);if(c.isShadow&&xe(d)&&(d=d.shadowRoot),r.removeNodeFromMap(h),d)try{d.removeChild(h),this.usingVirtualDom&&h.nodeName==="#text"&&d.nodeName==="STYLE"&&((u=d.rules)==null?void 0:u.length)>0&&(d.rules=[])}catch(p){if(p instanceof DOMException)this.warn("parent could not remove child in mutation",d,h,e);else throw p}});let s={...this.legacy_missingNodeRetryMap},n=[],o=c=>{let u=null;return c.nextId&&(u=r.getNode(c.nextId)),c.nextId!==null&&c.nextId!==void 0&&c.nextId!==-1&&!u},a=c=>{var u,h;if(!this.iframe.contentDocument)return this.warn("Looks like your replayer has been destroyed.");let d=r.getNode(c.parentId);if(!d)return c.node.type===ye.Document?this.newDocumentQueue.push(c):n.push(c);c.node.isShadow&&(xe(d)||d.attachShadow({mode:"open"}),d=d.shadowRoot);let p=null,g=null;if(c.previousId&&(p=r.getNode(c.previousId)),c.nextId&&(g=r.getNode(c.nextId)),o(c))return n.push(c);if(c.node.rootId&&!r.getNode(c.node.rootId))return;let m=c.node.rootId?r.getNode(c.node.rootId):this.usingVirtualDom?this.virtualDom:this.iframe.contentDocument;if(Je(d,r)){this.attachDocumentToIframe(c,d);return}let f=(w,S)=>{if(!this.usingVirtualDom){dr(w);for(let I of this.config.plugins||[])I.onBuild&&I.onBuild(w,{id:S,replayer:this})}},y=wt(c.node,{doc:m,mirror:r,skipChild:!0,hackCss:!0,cache:this.cache,afterAppend:f});if(c.previousId===-1||c.nextId===-1){s[c.node.id]={node:y,mutation:c};return}let b=r.getMeta(d);if(b&&b.type===ye.Element&&c.node.type===ye.Text){let w=Array.isArray(d.childNodes)?d.childNodes:Array.from(d.childNodes);if(b.tagName==="textarea")for(let S of w)S.nodeType===d.TEXT_NODE&&d.removeChild(S);else if(b.tagName==="style"&&w.length===1)for(let S of w)S.nodeType===d.TEXT_NODE&&!r.hasNode(S)&&(y.textContent=S.textContent,d.removeChild(S))}else if((b==null?void 0:b.type)===ye.Document){let w=d;c.node.type===ye.DocumentType&&((u=w.childNodes[0])==null?void 0:u.nodeType)===Node.DOCUMENT_TYPE_NODE&&w.removeChild(w.childNodes[0]),y.nodeName==="HTML"&&w.documentElement&&w.removeChild(w.documentElement)}if(p&&p.nextSibling&&p.nextSibling.parentNode?d.insertBefore(y,p.nextSibling):g&&g.parentNode?d.contains(g)?d.insertBefore(y,g):d.insertBefore(y,null):d.appendChild(y),f(y,c.node.id),this.usingVirtualDom&&y.nodeName==="#text"&&d.nodeName==="STYLE"&&((h=d.rules)==null?void 0:h.length)>0&&(d.rules=[]),Je(y,this.mirror)){let w=this.mirror.getId(y),S=this.newDocumentQueue.find(I=>I.parentId===w);S&&(this.attachDocumentToIframe(S,y),this.newDocumentQueue=this.newDocumentQueue.filter(I=>I!==S))}(c.previousId||c.nextId)&&this.legacy_resolveMissingNode(s,d,y,c)};e.adds.forEach(c=>{a(c)});let l=Date.now();for(;n.length;){let c=yl(n);if(n.length=0,Date.now()-l>500){this.warn("Timeout in the loop, please check the resolve tree data:",c);break}for(let u of c)r.getNode(u.value.parentId)?un(u,d=>{a(d)}):this.debug("Drop resolve tree since there is no parent for the root node.",u)}Object.keys(s).length&&Object.assign(this.legacy_missingNodeRetryMap,s),wl(e.texts).forEach(c=>{var u;let h=r.getNode(c.id);if(!h)return e.removes.find(p=>p.id===c.id)?void 0:this.warnNodeNotFound(e,c.id);let d=h.parentElement;if(c.value&&d&&d.tagName==="STYLE"?h.textContent=jr(c.value,this.cache):h.textContent=c.value,this.usingVirtualDom){let p=h.parentNode;((u=p==null?void 0:p.rules)==null?void 0:u.length)>0&&(p.rules=[])}}),e.attributes.forEach(c=>{var u;let h=r.getNode(c.id);if(!h)return e.removes.find(d=>d.id===c.id)?void 0:this.warnNodeNotFound(e,c.id);for(let d in c.attributes)if(typeof d=="string"){let p=c.attributes[d];if(p===null)h.removeAttribute(d),d==="open"&&tm(h,c);else if(typeof p=="string")try{if(d==="_cssText"&&(h.nodeName==="LINK"||h.nodeName==="STYLE"))try{let g=r.getMeta(h);Object.assign(g.attributes,c.attributes);let m=wt(g,{doc:h.ownerDocument,mirror:r,skipChild:!0,hackCss:!0,cache:this.cache}),f=h.nextSibling,y=h.parentNode;if(m&&y){y.removeChild(h),y.insertBefore(m,f),r.replace(c.id,m);break}}catch(g){}if(d==="value"&&h.nodeName==="TEXTAREA"){let g=h;g.childNodes.forEach(f=>g.removeChild(f));let m=(u=h.ownerDocument)==null?void 0:u.createTextNode(p);m&&g.appendChild(m)}else h.setAttribute(d,p);d==="rr_open_mode"&&h.nodeName==="DIALOG"&&dr(h,c)}catch(g){this.warn("An error occurred may due to the checkout feature.",g)}else if(d==="style"){let g=p,m=h;for(let f in g)if(g[f]===!1)m.style.removeProperty(f);else if(g[f]instanceof Array){let y=g[f];m.style.setProperty(f,y[0],y[1])}else{let y=g[f];m.style.setProperty(f,y)}}}})}applyScroll(e,t){var r,s;let n=this.mirror.getNode(e.id);if(!n)return this.debugNodeNotFound(e,e.id);let o=this.mirror.getMeta(n);if(n===this.iframe.contentDocument)(r=this.iframe.contentWindow)==null||r.scrollTo({top:e.y,left:e.x,behavior:t?"auto":"smooth"});else if((o==null?void 0:o.type)===ye.Document)(s=n.defaultView)==null||s.scrollTo({top:e.y,left:e.x,behavior:t?"auto":"smooth"});else try{n.scrollTo({top:e.y,left:e.x,behavior:t?"auto":"smooth"})}catch(a){}}applyInput(e){let t=this.mirror.getNode(e.id);if(!t)return this.debugNodeNotFound(e,e.id);try{t.checked=e.isChecked,t.value=e.text}catch(r){}}applySelection(e){try{let t=new Set,r=e.ranges.map(({start:s,startOffset:n,end:o,endOffset:a})=>{let l=this.mirror.getNode(s),c=this.mirror.getNode(o);if(!l||!c)return;let u=new Range;u.setStart(l,n),u.setEnd(c,a);let h=l.ownerDocument,d=h==null?void 0:h.getSelection();return d&&t.add(d),{range:u,selection:d}});t.forEach(s=>s.removeAllRanges()),r.forEach(s=>{var n;return s&&((n=s.selection)==null?void 0:n.addRange(s.range))})}catch(t){}}applyStyleSheetMutation(e){var t;let r=null;e.styleId?r=this.styleMirror.getStyle(e.styleId):e.id&&(r=((t=this.mirror.getNode(e.id))==null?void 0:t.sheet)||null),r&&(e.source===E.StyleSheetRule?this.applyStyleSheetRule(e,r):e.source===E.StyleDeclaration&&this.applyStyleDeclaration(e,r))}applyStyleSheetRule(e,t){var r,s,n,o;if((r=e.adds)==null||r.forEach(({rule:a,index:l})=>{try{if(Array.isArray(l)){let{positions:c,index:u}=gs(l);je(t.cssRules,c).insertRule(a,u)}else{let c=l===void 0?void 0:Math.min(l,t.cssRules.length);t==null||t.insertRule(a,c)}}catch(c){}}),(s=e.removes)==null||s.forEach(({index:a})=>{try{if(Array.isArray(a)){let{positions:l,index:c}=gs(a);je(t.cssRules,l).deleteRule(c||0)}else t==null||t.deleteRule(a)}catch(l){}}),e.replace)try{(n=t.replace)==null||n.call(t,e.replace)}catch(a){}if(e.replaceSync)try{(o=t.replaceSync)==null||o.call(t,e.replaceSync)}catch(a){}}applyStyleDeclaration(e,t){e.set&&je(t.rules,e.index).style.setProperty(e.set.property,e.set.value,e.set.priority),e.remove&&je(t.rules,e.index).style.removeProperty(e.remove.property)}applyAdoptedStyleSheet(e){var t;let r=this.mirror.getNode(e.id);if(!r)return;(t=e.styles)==null||t.forEach(a=>{var l;let c=null,u=null;if(xe(r)?u=((l=r.ownerDocument)==null?void 0:l.defaultView)||null:r.nodeName==="#document"&&(u=r.defaultView),!!u)try{c=new u.CSSStyleSheet,this.styleMirror.add(c,a.styleId),this.applyStyleSheetRule({source:E.StyleSheetRule,adds:a.rules},c)}catch(h){}});let s=10,n=0,o=(a,l)=>{let c=l.map(u=>this.styleMirror.getStyle(u)).filter(u=>u!==null);xe(a)?a.shadowRoot.adoptedStyleSheets=c:a.nodeName==="#document"&&(a.adoptedStyleSheets=c),c.length!==l.length&&n<s&&(setTimeout(()=>o(a,l),0+100*n),n++)};o(r,e.styleIds)}legacy_resolveMissingNode(e,t,r,s){let{previousId:n,nextId:o}=s,a=n&&e[n],l=o&&e[o];if(a){let{node:c,mutation:u}=a;t.insertBefore(c,r),delete e[u.node.id],delete this.legacy_missingNodeRetryMap[u.node.id],(u.previousId||u.nextId)&&this.legacy_resolveMissingNode(e,t,c,u)}if(l){let{node:c,mutation:u}=l;t.insertBefore(c,r.nextSibling),delete e[u.node.id],delete this.legacy_missingNodeRetryMap[u.node.id],(u.previousId||u.nextId)&&this.legacy_resolveMissingNode(e,t,c,u)}}moveAndHover(e,t,r,s,n){let o=this.mirror.getNode(r);if(!o)return this.debugNodeNotFound(n,r);let a=dn(o,this.iframe),l=e*a.absoluteScale+a.x,c=t*a.absoluteScale+a.y;this.mouse.style.left=`${l}px`,this.mouse.style.top=`${c}px`,s||this.drawMouseTail({x:l,y:c}),this.hoverElements(o)}drawMouseTail(e){if(!this.mouseTail)return;let{lineCap:t,lineWidth:r,strokeStyle:s,duration:n}=this.config.mouseTail===!0?Ti:Object.assign({},Ti,this.config.mouseTail),o=()=>{if(!this.mouseTail)return;let a=this.mouseTail.getContext("2d");!a||!this.tailPositions.length||(a.clearRect(0,0,this.mouseTail.width,this.mouseTail.height),a.beginPath(),a.lineWidth=r,a.lineCap=t,a.strokeStyle=s,a.moveTo(this.tailPositions[0].x,this.tailPositions[0].y),this.tailPositions.forEach(l=>a.lineTo(l.x,l.y)),a.stroke())};this.tailPositions.push(e),o(),setTimeout(()=>{this.tailPositions=this.tailPositions.filter(a=>a!==e),o()},n/this.speedService.state.context.timer.speed)}hoverElements(e){var t;(t=this.lastHoveredRootNode||this.iframe.contentDocument)==null||t.querySelectorAll(".\\:hover").forEach(s=>{s.classList.remove(":hover")}),this.lastHoveredRootNode=e.getRootNode();let r=e;for(;r;)r.classList&&r.classList.add(":hover"),r=r.parentElement}isUserInteraction(e){return e.type!==x.IncrementalSnapshot?!1:e.data.source>E.Mutation&&e.data.source<=E.Input}backToNormal(){this.nextUserInteractionEvent=null,!this.speedService.state.matches("normal")&&(this.speedService.send({type:"BACK_TO_NORMAL"}),this.emitter.emit(O.SkipEnd,{speed:this.speedService.state.context.normalSpeed}))}warnNodeNotFound(e,t){this.warn(`Node with id '${t}' not found. `,e)}warnCanvasMutationFailed(e,t){this.warn("Has error on canvas update",t,"canvas mutation:",e)}debugNodeNotFound(e,t){this.debug(`Node with id '${t}' not found. `,e)}warn(...e){this.config.showWarning&&this.config.logger.warn($o,...e)}debug(...e){this.config.showDebug&&this.config.logger.log($o,...e)}},{addCustomEvent:sm}=Re,{freezePage:nm}=Re,{takeFullSnapshot:om}=Re});var mm={};En(mm,{default:()=>pm});function oi(){let i=Date.now().toString(36),e=Math.random().toString(36).substring(2,15);return`rec_${i}_${e}`}function ai(){return typeof window=="undefined"?{userAgent:"unknown",screenWidth:0,screenHeight:0,viewportWidth:0,viewportHeight:0,devicePixelRatio:1,language:"en",platform:"unknown"}:{userAgent:navigator.userAgent,screenWidth:screen.width,screenHeight:screen.height,viewportWidth:window.innerWidth,viewportHeight:window.innerHeight,devicePixelRatio:window.devicePixelRatio||1,language:navigator.language,platform:navigator.platform}}var Ql={maskAllInputs:!0,maskAllText:!1,maskSelectors:[".sensitive","[data-sensitive]",".pii","[data-pii]"],blockSelectors:[".no-record","[data-no-record]"],maskInputTypes:["password","email","tel","credit-card"],maskCharacter:"*"},ec={batchEvents:!0,batchSize:50,batchTimeout:5e3,compress:!0,mouseMoveThrottle:50,maxDuration:1800*1e3},tc={console:!0,network:!1,performance:!1,errors:!0,customEvents:!0};function li(i){var e,t,r,s,n,o;return{enabled:(e=i==null?void 0:i.enabled)!=null?e:!0,samplingRate:(t=i==null?void 0:i.samplingRate)!=null?t:1,privacy:{...Ql,...i==null?void 0:i.privacy},performance:{...ec,...i==null?void 0:i.performance},capture:{...tc,...i==null?void 0:i.capture},endpoint:(r=i==null?void 0:i.endpoint)!=null?r:"",onStart:(s=i==null?void 0:i.onStart)!=null?s:(()=>{}),onStop:(n=i==null?void 0:i.onStop)!=null?n:(()=>{}),onError:(o=i==null?void 0:i.onError)!=null?o:(()=>{})}}function ci(i){return i>=1?!0:i<=0?!1:Math.random()<i}function ui(i){try{let e=JSON.stringify(i);return typeof btoa!="undefined"?btoa(encodeURIComponent(e)):e}catch(e){return console.warn("[Recording] Failed to compress events:",e),JSON.stringify(i)}}function Ht(){return typeof window!="undefined"&&typeof document!="undefined"}function In(){return Ht()?window.location.href:""}var at=class{constructor(e){this.state="idle";this.sessionId=null;this.sdkSessionToken=null;this.apiUrl="";this.sdkKey=null;this.stopRecording=null;this.events=[];this.eventCount=0;this.batchIndex=0;this.batchesSent=0;this.errorCount=0;this.startTime=null;this.batchTimeout=null;this.maxDurationTimeout=null;this.consoleCleanup=null;this.errorCleanup=null;this.config=li(e)}initialize(e,t,r){this.sdkSessionToken=e,this.apiUrl=t,this.sdkKey=r||null}updateConfig(e){this.config=li({...this.config,...e})}async start(){var e,t,r,s;if(!Ht())return console.warn("[Recording] Cannot record outside browser environment"),null;if(!this.config.enabled)return null;if(this.state==="recording")return console.warn("[Recording] Already recording"),this.sessionId;if(!ci(this.config.samplingRate))return console.log("[Recording] Session not sampled for recording"),null;try{let n=await Promise.resolve().then(()=>(Ll(),$l));this.sessionId=oi(),this.events=[],this.eventCount=0,this.batchIndex=0,this.batchesSent=0,this.errorCount=0,this.startTime=new Date,this.state="recording";let o={emit:a=>this.handleEvent(a),maskAllInputs:this.config.privacy.maskAllInputs,maskTextSelector:((e=this.config.privacy.maskSelectors)==null?void 0:e.join(","))||void 0,blockSelector:((t=this.config.privacy.blockSelectors)==null?void 0:t.join(","))||void 0,maskInputOptions:{password:!0,email:(r=this.config.privacy.maskInputTypes)==null?void 0:r.includes("email"),tel:(s=this.config.privacy.maskInputTypes)==null?void 0:s.includes("tel")},sampling:{mousemove:!0,mouseInteraction:!0,scroll:150,media:800,input:"last"}};return this.stopRecording=n.record(o),this.config.capture.console&&this.setupConsoleCapture(),this.config.capture.errors&&this.setupErrorCapture(),this.config.performance.maxDuration&&(this.maxDurationTimeout=setTimeout(()=>{console.log("[Recording] Max duration reached, stopping"),this.stop()},this.config.performance.maxDuration)),await this.sendSessionStart(),this.config.onStart(this.sessionId),console.log("[Recording] Started session:",this.sessionId),this.sessionId}catch(n){return console.error("[Recording] Failed to start:",n),this.state="idle",this.config.onError(n instanceof Error?n:new Error(String(n))),null}}async stop(){if(!(this.state!=="recording"&&this.state!=="paused"))try{this.stopRecording&&(this.stopRecording(),this.stopRecording=null),this.consoleCleanup&&(this.consoleCleanup(),this.consoleCleanup=null),this.errorCleanup&&(this.errorCleanup(),this.errorCleanup=null),this.batchTimeout&&(clearTimeout(this.batchTimeout),this.batchTimeout=null),this.maxDurationTimeout&&(clearTimeout(this.maxDurationTimeout),this.maxDurationTimeout=null),this.events.length>0&&await this.sendBatch(!0),await this.sendSessionEnd();let e=this.sessionId,t=this.eventCount;this.state="stopped",this.config.onStop(e||"",t),console.log("[Recording] Stopped session:",e,"Events:",t)}catch(e){console.error("[Recording] Error stopping:",e),this.config.onError(e instanceof Error?e:new Error(String(e)))}}pause(){this.state==="recording"&&(this.state="paused",console.log("[Recording] Paused"))}resume(){this.state==="paused"&&(this.state="recording",console.log("[Recording] Resumed"))}addCustomEvent(e){if(this.state!=="recording"||!this.config.capture.customEvents)return;let t={type:5,data:{tag:"custom",payload:e},timestamp:e.timestamp||Date.now()};this.handleEvent(t)}getStats(){let e=this.startTime?Date.now()-this.startTime.getTime():0;return{state:this.state,sessionId:this.sessionId,eventCount:this.eventCount,startTime:this.startTime,duration:e,batchesSent:this.batchesSent,errors:this.errorCount}}isRecording(){return this.state==="recording"}getSessionId(){return this.sessionId}handleEvent(e){this.state==="recording"&&(this.events.push(e),this.eventCount++,this.config.performance.batchEvents?this.events.length>=this.config.performance.batchSize?this.sendBatch():this.batchTimeout||(this.batchTimeout=setTimeout(()=>{this.batchTimeout=null,this.events.length>0&&this.sendBatch()},this.config.performance.batchTimeout)):this.sendBatch())}async sendBatch(e=!1){if(this.events.length===0)return;let t=[...this.events];this.events=[];let r={sessionId:this.sessionId,sdkSessionToken:this.sdkSessionToken,events:t,timestamp:new Date().toISOString(),batchIndex:this.batchIndex++,isFinal:e};try{let s=this.config.endpoint||`${this.apiUrl}/session-recordings/events`,n={"Content-Type":"application/json"};this.sdkKey&&(n["X-SDK-Key"]=this.sdkKey);let o=this.config.performance.compress?JSON.stringify({...r,events:void 0,compressedEvents:ui(t)}):JSON.stringify(r);await fetch(s,{method:"POST",headers:n,body:o}),this.batchesSent++}catch(s){console.error("[Recording] Failed to send batch:",s),this.errorCount++,this.events=[...t,...this.events]}}async sendSessionStart(){let e={id:this.sessionId,sdkSessionToken:this.sdkSessionToken,startUrl:In(),startTime:this.startTime,deviceInfo:ai()};try{let t=`${this.apiUrl}/session-recordings/start`,r={"Content-Type":"application/json"};this.sdkKey&&(r["X-SDK-Key"]=this.sdkKey),await fetch(t,{method:"POST",headers:r,body:JSON.stringify(e)})}catch(t){console.error("[Recording] Failed to send session start:",t)}}async sendSessionEnd(){try{let e=`${this.apiUrl}/session-recordings/end`,t={"Content-Type":"application/json"};this.sdkKey&&(t["X-SDK-Key"]=this.sdkKey),await fetch(e,{method:"POST",headers:t,body:JSON.stringify({sessionId:this.sessionId,endTime:new Date().toISOString(),eventCount:this.eventCount})})}catch(e){console.error("[Recording] Failed to send session end:",e)}}setupConsoleCapture(){let e={log:console.log,info:console.info,warn:console.warn,error:console.error,debug:console.debug},t=r=>(...s)=>{var o;if(e[r](...s),(o=s[0])!=null&&o.toString().includes("[Recording]"))return;let n={level:r,message:s.map(a=>typeof a=="object"?JSON.stringify(a):String(a)).join(" "),timestamp:Date.now()};this.addCustomEvent({type:"console",data:n})};console.log=t("log"),console.info=t("info"),console.warn=t("warn"),console.error=t("error"),console.debug=t("debug"),this.consoleCleanup=()=>{console.log=e.log,console.info=e.info,console.warn=e.warn,console.error=e.error,console.debug=e.debug}}setupErrorCapture(){let e=r=>{let s={type:"error",message:r.message,filename:r.filename,lineno:r.lineno,colno:r.colno,timestamp:Date.now()};this.addCustomEvent({type:"error",data:s})},t=r=>{var n,o;let s={type:"unhandledrejection",message:((n=r.reason)==null?void 0:n.message)||String(r.reason),stack:(o=r.reason)==null?void 0:o.stack,timestamp:Date.now()};this.addCustomEvent({type:"error",data:s})};window.addEventListener("error",e),window.addEventListener("unhandledrejection",t),this.errorCleanup=()=>{window.removeEventListener("error",e),window.removeEventListener("unhandledrejection",t)}}destroy(){this.stop(),this.sessionId=null,this.sdkSessionToken=null,this.events=[]}};var Qr=class{constructor(e,t){this.isTracking=!1;this.scrollDepth=0;this.pageLoadTime=0;this.clickCount=0;this.lastActivityTime=0;this.currentUrl="";this.previousUrl="";this.triggeredSet=new Set;this.lastTriggerTime=0;this.proactiveMessageCount=0;this.scrollHandler=null;this.clickHandler=null;this.mouseMoveHandler=null;this.mouseLeaveHandler=null;this.visibilityHandler=null;this.timeCheckInterval=null;this.idleCheckInterval=null;this.config=e,this.callbacks=t}start(){!this.config.enabled||this.isTracking||typeof window!="undefined"&&(this.config.respectUserPreference&&localStorage.getItem("produck_proactive_optout")==="true"||(this.isTracking=!0,this.pageLoadTime=Date.now(),this.lastActivityTime=Date.now(),this.currentUrl=window.location.href,this.setupScrollTracking(),this.setupClickTracking(),this.setupIdleTracking(),this.setupExitIntentTracking(),this.setupTimeTracking(),this.setupPageChangeTracking(),console.log("[Produck] Proactive behavior tracking started")))}stop(){this.isTracking&&(this.isTracking=!1,this.scrollHandler&&window.removeEventListener("scroll",this.scrollHandler),this.clickHandler&&document.removeEventListener("click",this.clickHandler),this.mouseMoveHandler&&document.removeEventListener("mousemove",this.mouseMoveHandler),this.mouseLeaveHandler&&document.removeEventListener("mouseleave",this.mouseLeaveHandler),this.visibilityHandler&&document.removeEventListener("visibilitychange",this.visibilityHandler),this.timeCheckInterval&&clearInterval(this.timeCheckInterval),this.idleCheckInterval&&clearInterval(this.idleCheckInterval),console.log("[Produck] Proactive behavior tracking stopped"))}reset(){this.scrollDepth=0,this.clickCount=0,this.pageLoadTime=Date.now(),this.lastActivityTime=Date.now()}getStats(){return{scrollDepth:this.scrollDepth,timeOnPage:Date.now()-this.pageLoadTime,clickCount:this.clickCount,idleTime:Date.now()-this.lastActivityTime,proactiveMessageCount:this.proactiveMessageCount}}shouldTrigger(e){if(this.config.maxProactiveMessages&&this.proactiveMessageCount>=this.config.maxProactiveMessages||this.config.globalCooldown&&Date.now()-this.lastTriggerTime<this.config.globalCooldown)return!1;let t=`${e.type}-${e.threshold||"default"}`;if(e.onlyOnce&&this.triggeredSet.has(t))return!1;let r=`${t}-lastTime`,s=parseInt(sessionStorage.getItem(r)||"0",10);return!(e.cooldown&&Date.now()-s<e.cooldown)}fireTrigger(e,t){if(!this.shouldTrigger(e))return;let r=`${e.type}-${e.threshold||"default"}`,s=`${r}-lastTime`;this.triggeredSet.add(r),this.lastTriggerTime=Date.now(),this.proactiveMessageCount++,sessionStorage.setItem(s,Date.now().toString());let n=e.message||this.getDefaultMessage(e.type,t);this.callbacks.onTrigger(t,n),this.callbacks.onMessage&&this.callbacks.onMessage(n),console.log("[Produck] Proactive trigger fired:",e.type,t)}getDefaultMessage(e,t){switch(e){case"scroll":return"I see you're exploring the page! Is there something specific you're looking for?";case"time":return"You've been here a while. Would you like some help finding what you need?";case"clicks":return"Looks like you're navigating around. Can I help you find something?";case"idle":return"Still there? Let me know if you have any questions!";case"exit":return"Wait! Before you go, is there anything I can help you with?";case"pageChange":return"I see you're exploring different pages. Need any guidance?";default:return"How can I help you today?"}}setupScrollTracking(){let e=this.config.triggers.filter(t=>t.type==="scroll"&&t.enabled);e.length!==0&&(this.scrollHandler=()=>{let t=document.documentElement.scrollHeight-window.innerHeight,r=t>0?window.scrollY/t*100:0;this.scrollDepth=Math.max(this.scrollDepth,r),this.lastActivityTime=Date.now(),e.forEach(s=>{s.threshold&&this.scrollDepth>=s.threshold&&this.fireTrigger(s,{triggerType:"scroll",scrollDepth:this.scrollDepth,currentUrl:window.location.href,pageTitle:document.title})})},window.addEventListener("scroll",this.scrollHandler,{passive:!0}))}setupClickTracking(){let e=this.config.triggers.filter(t=>t.type==="clicks"&&t.enabled);e.length!==0&&(this.clickHandler=()=>{this.clickCount++,this.lastActivityTime=Date.now(),e.forEach(t=>{t.threshold&&this.clickCount>=t.threshold&&this.fireTrigger(t,{triggerType:"clicks",clickCount:this.clickCount,currentUrl:window.location.href,pageTitle:document.title})})},document.addEventListener("click",this.clickHandler))}setupIdleTracking(){let e=this.config.triggers.filter(t=>t.type==="idle"&&t.enabled);e.length!==0&&(this.mouseMoveHandler=()=>{this.lastActivityTime=Date.now()},document.addEventListener("mousemove",this.mouseMoveHandler,{passive:!0}),this.idleCheckInterval=setInterval(()=>{let t=Date.now()-this.lastActivityTime;e.forEach(r=>{r.threshold&&t>=r.threshold&&this.fireTrigger(r,{triggerType:"idle",idleTime:t,currentUrl:window.location.href,pageTitle:document.title})})},1e3))}setupExitIntentTracking(){let e=this.config.triggers.filter(t=>t.type==="exit"&&t.enabled);e.length!==0&&(this.mouseLeaveHandler=t=>{t.clientY<=0&&e.forEach(r=>{this.fireTrigger(r,{triggerType:"exit",currentUrl:window.location.href,pageTitle:document.title})})},document.addEventListener("mouseleave",this.mouseLeaveHandler))}setupTimeTracking(){let e=this.config.triggers.filter(t=>t.type==="time"&&t.enabled);e.length!==0&&(this.timeCheckInterval=setInterval(()=>{let t=Date.now()-this.pageLoadTime;e.forEach(r=>{r.threshold&&t>=r.threshold&&this.fireTrigger(r,{triggerType:"time",timeOnPage:t,currentUrl:window.location.href,pageTitle:document.title})})},1e3))}setupPageChangeTracking(){let e=this.config.triggers.filter(t=>t.type==="pageChange"&&t.enabled);e.length!==0&&(this.visibilityHandler=()=>{if(document.visibilityState==="visible"){let t=window.location.href;t!==this.currentUrl&&(this.previousUrl=this.currentUrl,this.currentUrl=t,this.scrollDepth=0,this.clickCount=0,this.pageLoadTime=Date.now(),e.forEach(r=>{this.fireTrigger(r,{triggerType:"pageChange",currentUrl:this.currentUrl,previousUrl:this.previousUrl,pageTitle:document.title})}))}},document.addEventListener("visibilitychange",this.visibilityHandler),window.addEventListener("popstate",()=>{let t=window.location.href;t!==this.currentUrl&&(this.previousUrl=this.currentUrl,this.currentUrl=t,e.forEach(r=>{this.fireTrigger(r,{triggerType:"pageChange",currentUrl:this.currentUrl,previousUrl:this.previousUrl,pageTitle:document.title})}))}))}triggerManual(e,t){this.proactiveMessageCount++,this.lastTriggerTime=Date.now();let r={triggerType:"time",currentUrl:window.location.href,pageTitle:document.title,...t};this.callbacks.onTrigger(r,e),this.callbacks.onMessage&&this.callbacks.onMessage(e)}optOut(){typeof localStorage!="undefined"&&localStorage.setItem("produck_proactive_optout","true"),this.stop()}optIn(){typeof localStorage!="undefined"&&localStorage.removeItem("produck_proactive_optout"),this.start()}};function Se(){return typeof window!="undefined"&&typeof document!="undefined"}function mn(){return"ufs_"+Date.now().toString(36)+"_"+Math.random().toString(36).substring(2,11)}function Ne(){return Se()?window.location.href:""}function Ue(){return Se()?window.location.pathname:""}function Be(){return Se()&&document.title||""}function gn(i=1){return Math.random()<i}function yn(){if(!Se())return{deviceType:"desktop",browser:"unknown",os:"unknown",viewportWidth:0,viewportHeight:0,userAgent:""};let i=navigator.userAgent,e="desktop";/Mobi|Android/i.test(i)&&(e=/Tablet|iPad/i.test(i)?"tablet":"mobile");let t="unknown";i.includes("Firefox")?t="Firefox":i.includes("Edg")?t="Edge":i.includes("Chrome")?t="Chrome":i.includes("Safari")?t="Safari":(i.includes("Opera")||i.includes("OPR"))&&(t="Opera");let r="unknown";return i.includes("Windows")?r="Windows":i.includes("Mac OS")?r="macOS":i.includes("Linux")?r="Linux":i.includes("Android")?r="Android":(i.includes("iOS")||i.includes("iPhone")||i.includes("iPad"))&&(r="iOS"),{deviceType:e,browser:t,os:r,viewportWidth:window.innerWidth,viewportHeight:window.innerHeight,userAgent:i}}function _l(i,e=5){let t=[],r=i,s=0;for(;r&&r!==document.body&&s<e;){let n=r.tagName.toLowerCase();if(r.id){n+=`#${r.id}`,t.unshift(n);break}if(r.className&&typeof r.className=="string"){let a=r.className.trim().split(/\s+/);a.length>0&&a[0]&&(n+=`.${a[0]}`)}let o=r.parentElement;if(o){let a=Array.from(o.children).filter(l=>l.tagName===r.tagName);if(a.length>1){let l=a.indexOf(r)+1;n+=`:nth-child(${l})`}}t.unshift(n),r=r.parentElement,s++}return t.join(" > ")}function Fl(i){if(!i)return"";if(i.id)return`//*[@id="${i.id}"]`;let e=[],t=i;for(;t&&t.nodeType===Node.ELEMENT_NODE;){let r=0,s=t.previousElementSibling;for(;s;)s.tagName===t.tagName&&r++,s=s.previousElementSibling;let n=t.tagName.toLowerCase(),o=r>0?`${n}[${r+1}]`:n;e.unshift(o),t=t.parentElement}return"/"+e.join("/")}function ei(i,e={}){let t=(e==null?void 0:e.maxTextLength)||100,r=(e==null?void 0:e.maxHtmlLength)||500,s=(e==null?void 0:e.selectorDepth)||5,n="";i instanceof HTMLElement&&(n=i.innerText||i.textContent||"",n=n.trim().substring(0,t),n.length===t&&(n+="..."));let o;(e==null?void 0:e.captureHtml)!==!1&&(o=i.outerHTML.substring(0,r),o.length===r&&(o+="..."));let a=i.getBoundingClientRect(),l={tag:i.tagName.toLowerCase(),selector:_l(i,s)};return i.id&&(l.id=i.id),i.className&&typeof i.className=="string"&&(l.className=i.className),n&&(l.text=n),i instanceof HTMLAnchorElement&&i.href&&(l.href=i.href),l.xpath=Fl(i),l.rect={x:Math.round(a.x),y:Math.round(a.y),width:Math.round(a.width),height:Math.round(a.height)},o&&(l.html=o),l}function Ft(i,e){return!e||e.length===0?!1:e.some(t=>{try{return i.matches(t)||i.closest(t)!==null}catch(r){return!1}})}function Ul(i){try{if(typeof window=="undefined")return;let e=i,t=window.getComputedStyle(e);return{backgroundColor:t.backgroundColor,color:t.color,fontSize:t.fontSize,fontWeight:t.fontWeight,borderRadius:t.borderRadius,border:t.border,boxShadow:t.boxShadow,padding:t.padding}}catch(e){return}}async function Bl(i,e=200){try{if(typeof window=="undefined")return;let t=window.html2canvas;if(!t)try{return(await(await import("html2canvas")).default(i,{scale:.5,width:e,height:e,useCORS:!0,logging:!1})).toDataURL("image/jpeg",.7)}catch(s){console.debug("[UserFlow] html2canvas not available for screenshots");return}return(await t(i,{scale:.5,width:e,height:e,useCORS:!0,logging:!1})).toDataURL("image/jpeg",.7)}catch(t){console.debug("[UserFlow] Failed to capture screenshot:",t);return}}function wn(i){var t,r,s,n,o,a;let e={enabled:!0,samplingRate:1,events:{clicks:!0,navigation:!0,formSubmit:!0,inputs:!1,scroll:!1,ignoreSelectors:[],trackOnlySelectors:[]},element:{captureVisualStyles:!0,captureScreenshot:!1,screenshotMaxSize:200,captureHtml:!0,maxHtmlLength:500,maxTextLength:100,selectorDepth:5},performance:{batchEvents:!0,batchSize:10,batchTimeout:5e3,clickDebounce:500},session:{endOnHidden:!0,inactivityTimeout:3e5,endOnExternalNavigation:!0,autoRestart:!0},endpoint:"",onStart:()=>{},onStop:()=>{},onError:()=>{}};return i?{enabled:(t=i.enabled)!=null?t:e.enabled,samplingRate:(r=i.samplingRate)!=null?r:e.samplingRate,events:{...e.events,...i.events},element:{...e.element,...i.element},performance:{...e.performance,...i.performance},session:{...e.session,...i.session},endpoint:(s=i.endpoint)!=null?s:e.endpoint,onStart:(n=i.onStart)!=null?n:e.onStart,onStop:(o=i.onStop)!=null?o:e.onStop,onError:(a=i.onError)!=null?a:e.onError}:e}var lt=class{constructor(e){this.state="idle";this.sessionId=null;this.sdkSessionToken=null;this.apiUrl="";this.sdkKey=null;this.user=null;this.events=[];this.eventCount=0;this.batchIndex=0;this.batchesSent=0;this.pageCount=0;this.startTime=null;this.batchTimeout=null;this.inactivityTimeout=null;this.lastActivityTime=Date.now();this.lastClickTime=0;this.lastClickElement=null;this.currentPath="";this.visitedPaths=new Set;this.clickHandler=null;this.navigationHandler=null;this.formSubmitHandler=null;this.beforeUnloadHandler=null;this.visibilityHandler=null;this.linkedRecordingSessionId=null;this.config=wn(e)}initialize(e,t,r){this.sdkSessionToken=e,this.apiUrl=t,this.sdkKey=r||null}updateConfig(e){this.config=wn({...this.config,...e})}identify(e){this.user=e,this.state==="tracking"&&this.sessionId&&this.sendIdentificationUpdate().catch(t=>{console.error("[UserFlow] Failed to send identification update:",t)})}async start(e){if(!Se())return console.warn("[UserFlow] Cannot track outside browser environment"),null;if(!this.config.enabled)return null;if(this.state==="tracking")return console.warn("[UserFlow] Already tracking"),this.sessionId;if(!gn(this.config.samplingRate))return console.log("[UserFlow] Session not sampled for tracking"),null;try{return this.sessionId=mn(),this.linkedRecordingSessionId=e||null,this.events=[],this.eventCount=0,this.batchIndex=0,this.batchesSent=0,this.pageCount=1,this.startTime=new Date,this.currentPath=Ue(),this.visitedPaths=new Set([this.currentPath]),this.state="tracking",this.setupEventListeners(),await this.sendSessionStart(),this.addEvent({eventType:"navigation",eventOrder:0,timestamp:new Date().toISOString(),pageUrl:Ne(),pageTitle:Be(),pagePath:this.currentPath}),this.config.onStart(this.sessionId),console.log("[UserFlow] Started tracking session:",this.sessionId),this.sessionId}catch(t){return console.error("[UserFlow] Failed to start tracking:",t),this.state="idle",this.config.onError(t instanceof Error?t:new Error(String(t))),null}}async stop(){if(!(this.state!=="tracking"&&this.state!=="paused"))try{this.removeEventListeners(),this.batchTimeout&&(clearTimeout(this.batchTimeout),this.batchTimeout=null),this.inactivityTimeout&&(clearTimeout(this.inactivityTimeout),this.inactivityTimeout=null),this.events.length>0&&await this.sendEventBatch(!0),await this.sendSessionEnd(),this.state="stopped";let e=this.eventCount,t=this.sessionId;this.sessionId=null,this.events=[],this.eventCount=0,this.startTime=null,this.config.onStop(t,e),console.log("[UserFlow] Stopped tracking session:",t)}catch(e){console.error("[UserFlow] Error stopping tracking:",e),this.state="stopped",this.config.onError(e instanceof Error?e:new Error(String(e)))}}pause(){this.state==="tracking"&&(this.state="paused",console.log("[UserFlow] Tracking paused"))}resume(){this.state==="paused"&&(this.state="tracking",console.log("[UserFlow] Tracking resumed"))}getStats(){return{sessionId:this.sessionId,state:this.state,eventCount:this.eventCount,pageCount:this.pageCount,batchesSent:this.batchesSent,duration:this.startTime?Date.now()-this.startTime.getTime():0,startTime:this.startTime}}getState(){return this.state}isTracking(){return this.state==="tracking"}addCustomEvent(e){this.state==="tracking"&&this.addEvent({eventType:"custom",eventOrder:this.eventCount,timestamp:new Date().toISOString(),pageUrl:Ne(),pageTitle:Be(),pagePath:Ue(),metadata:e})}setupEventListeners(){if(Se()){if(this.config.events.clicks&&(this.clickHandler=e=>this.handleClick(e),document.addEventListener("click",this.clickHandler,{capture:!0,passive:!0})),this.config.events.navigation){this.navigationHandler=()=>this.handleNavigation(),window.addEventListener("popstate",this.navigationHandler);let e=history.pushState,t=history.replaceState;history.pushState=(...r)=>{e.apply(history,r),this.handleNavigation()},history.replaceState=(...r)=>{t.apply(history,r),this.handleNavigation()}}this.config.events.formSubmit&&(this.formSubmitHandler=e=>this.handleFormSubmit(e),document.addEventListener("submit",this.formSubmitHandler,{capture:!0})),this.beforeUnloadHandler=()=>{this.events.length>0&&this.sendEventBatchSync(!0),this.sendSessionEndSync()},window.addEventListener("beforeunload",this.beforeUnloadHandler),this.visibilityHandler=()=>{document.visibilityState==="hidden"?(this.events.length>0&&this.sendEventBatch(!0).catch(console.error),this.config.session.endOnHidden&&this.stop().catch(console.error)):document.visibilityState==="visible"&&this.config.session.autoRestart&&this.state==="stopped"&&this.start().catch(console.error)},document.addEventListener("visibilitychange",this.visibilityHandler),this.resetInactivityTimeout()}}removeEventListeners(){Se()&&(this.clickHandler&&(document.removeEventListener("click",this.clickHandler,{capture:!0}),this.clickHandler=null),this.navigationHandler&&(window.removeEventListener("popstate",this.navigationHandler),this.navigationHandler=null),this.formSubmitHandler&&(document.removeEventListener("submit",this.formSubmitHandler,{capture:!0}),this.formSubmitHandler=null),this.beforeUnloadHandler&&(window.removeEventListener("beforeunload",this.beforeUnloadHandler),this.beforeUnloadHandler=null),this.visibilityHandler&&(document.removeEventListener("visibilitychange",this.visibilityHandler),this.visibilityHandler=null))}async handleClick(e){if(this.state!=="tracking")return;let t=e.target;if(!t||!(t instanceof Element)||this.config.events.ignoreSelectors&&this.config.events.ignoreSelectors.length>0&&Ft(t,this.config.events.ignoreSelectors)||this.config.events.trackOnlySelectors&&this.config.events.trackOnlySelectors.length>0&&!Ft(t,this.config.events.trackOnlySelectors))return;let r=Date.now();if(this.lastClickElement===t&&r-this.lastClickTime<this.config.performance.clickDebounce)return;this.lastClickTime=r,this.lastClickElement=t;let s=ei(t,this.config.element);if(this.config.element.captureVisualStyles&&(s.visualStyles=Ul(t)),this.config.element.captureScreenshot)try{s.screenshot=await Bl(t,this.config.element.screenshotMaxSize)}catch(o){}let n={eventType:"click",eventOrder:this.eventCount,timestamp:new Date().toISOString(),pageUrl:Ne(),pageTitle:Be(),pagePath:Ue(),element:s,clickX:Math.round(e.pageX),clickY:Math.round(e.pageY),viewportX:Math.round(e.clientX),viewportY:Math.round(e.clientY)};this.addEvent(n)}handleNavigation(){if(this.state!=="tracking")return;let e=Ue();if(e===this.currentPath)return;this.currentPath=e,this.visitedPaths.has(e)||(this.visitedPaths.add(e),this.pageCount++);let t={eventType:"navigation",eventOrder:this.eventCount,timestamp:new Date().toISOString(),pageUrl:Ne(),pageTitle:Be(),pagePath:e};this.addEvent(t)}handleFormSubmit(e){if(this.state!=="tracking")return;let t=e.target;if(!t||!(t instanceof HTMLFormElement)||this.config.events.ignoreSelectors&&Ft(t,this.config.events.ignoreSelectors))return;let r=ei(t,this.config.element),s={eventType:"form_submit",eventOrder:this.eventCount,timestamp:new Date().toISOString(),pageUrl:Ne(),pageTitle:Be(),pagePath:Ue(),element:r,metadata:{action:t.action,method:t.method,name:t.name}};this.addEvent(s)}addEvent(e){this.events.push(e),this.eventCount++,this.resetInactivityTimeout(),this.config.performance.batchEvents&&this.events.length>=this.config.performance.batchSize?this.sendEventBatch(!1).catch(console.error):this.batchTimeout||(this.batchTimeout=setTimeout(()=>{this.batchTimeout=null,this.events.length>0&&this.sendEventBatch(!1).catch(console.error)},this.config.performance.batchTimeout))}async sendSessionStart(){var s;let e=this.config.endpoint||`${this.apiUrl}/user-flows/session/start`,t=yn(),r={sessionId:this.sessionId,sdkSessionToken:this.sdkSessionToken,startUrl:Ne(),startTime:(s=this.startTime)==null?void 0:s.toISOString(),user:this.user,device:t,linkedRecordingSessionId:this.linkedRecordingSessionId};try{let n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json",...this.sdkKey?{"X-SDK-Key":this.sdkKey}:{}},body:JSON.stringify(r)});if(!n.ok)throw console.error("[UserFlow] Failed to start session:",n.status,n.statusText),console.error("[UserFlow] Endpoint:",e),new Error(`Failed to start session: ${n.status}`);console.log("[UserFlow] Session started successfully:",this.sessionId)}catch(n){throw console.error("[UserFlow] Network error starting session:",n),console.error("[UserFlow] Attempted endpoint:",e),n}}async sendEventBatch(e){if(this.events.length===0)return;let t=[...this.events];this.events=[];let r=this.config.endpoint?`${this.config.endpoint}/events`:`${this.apiUrl}/user-flows/session/events`,s={sessionId:this.sessionId,events:t,batchIndex:this.batchIndex++,timestamp:new Date().toISOString(),isFinal:e};try{let n=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",...this.sdkKey?{"X-SDK-Key":this.sdkKey}:{}},body:JSON.stringify(s)});n.ok?(this.batchesSent++,console.log(`[UserFlow] Event batch ${this.batchIndex-1} sent (${t.length} events)`)):(console.error("[UserFlow] Failed to send event batch:",n.status,n.statusText),console.error("[UserFlow] Endpoint:",r),this.events=[...t,...this.events])}catch(n){console.error("[UserFlow] Network error sending event batch:",n),console.error("[UserFlow] Endpoint:",r),this.events=[...t,...this.events]}}sendEventBatchSync(e){if(this.events.length===0)return;let t=this.config.endpoint?`${this.config.endpoint}/events`:`${this.apiUrl}/user-flows/session/events`,r={sessionId:this.sessionId,events:this.events,batchIndex:this.batchIndex++,timestamp:new Date().toISOString(),isFinal:e};if(navigator.sendBeacon){let s=new Blob([JSON.stringify(r)],{type:"application/json"});navigator.sendBeacon(t,s),this.events=[]}}async sendSessionEnd(){let e=this.config.endpoint?`${this.config.endpoint}/end`:`${this.apiUrl}/user-flows/session/end`,t={sessionId:this.sessionId,endTime:new Date().toISOString(),eventCount:this.eventCount,status:"completed"};try{await fetch(e,{method:"POST",headers:{"Content-Type":"application/json",...this.sdkKey?{"X-SDK-Key":this.sdkKey}:{}},body:JSON.stringify(t)})}catch(r){console.error("[UserFlow] Failed to send session end:",r)}}sendSessionEndSync(){let e=this.config.endpoint?`${this.config.endpoint}/end`:`${this.apiUrl}/user-flows/session/end`,t={sessionId:this.sessionId,endTime:new Date().toISOString(),eventCount:this.eventCount,status:"completed"};if(navigator.sendBeacon){let r=new Blob([JSON.stringify(t)],{type:"application/json"});navigator.sendBeacon(e,r)}}resetInactivityTimeout(){this.inactivityTimeout&&(clearTimeout(this.inactivityTimeout),this.inactivityTimeout=null),this.lastActivityTime=Date.now();let e=this.config.session.inactivityTimeout;e&&e>0&&(this.inactivityTimeout=setTimeout(()=>{this.state==="tracking"&&(console.log("[UserFlow] Session ended due to inactivity"),this.stop().catch(console.error))},e))}async sendIdentificationUpdate(){if(!this.sessionId||!this.user)return;let e=this.config.endpoint?`${this.config.endpoint}/identify`:`${this.apiUrl}/user-flows/session/identify`,t={sessionId:this.sessionId,user:this.user};await fetch(e,{method:"PATCH",headers:{"Content-Type":"application/json",...this.sdkKey?{"X-SDK-Key":this.sdkKey}:{}},body:JSON.stringify(t)})}};var ti=class{constructor(e){this.actions=new Map;this.eventListeners=new Map;this.sessionToken=null;this.isReady=!1;this.recorder=null;this.proactiveTracker=null;this.userFlowTracker=null;let t=e.apiUrl,r=!1;t||(r=!0,typeof window!="undefined"?window.location.hostname==="localhost"||window.location.hostname==="127.0.0.1"?t="http://localhost:4001/api/v1":(t=`${window.location.protocol}//${window.location.host}/api/v1`,console.warn("%c\u26A0\uFE0F Produck SDK Warning: apiUrl not configured!","background: #fbbf24; color: #000; padding: 4px 8px; font-weight: bold;"),console.warn(`The SDK is auto-detecting apiUrl as: ${t}
|
|
54
|
+
or you can use record.mirror to access the mirror instance during recording.`,Lr={map:{},getId(){return console.error(He),-1},getNode(){return console.error(He),null},removeNodeFromMap(){console.error(He)},has(){return console.error(He),!1},reset(){console.error(He)}};typeof window!="undefined"&&window.Proxy&&window.Reflect&&(Lr=new Proxy(Lr,{get(i,e,t){return e==="map"&&console.error(He),Reflect.get(i,e,t)}}));Nt=Date.now;/[1-9][0-9]{12}/.test(Date.now().toString())||(Nt=()=>new Date().getTime());At=class{constructor(){v(this,"id",1),v(this,"styleIDMap",new WeakMap),v(this,"idStyleMap",new Map)}getId(e){var t;return(t=this.styleIDMap.get(e))!=null?t:-1}has(e){return this.styleIDMap.has(e)}add(e,t){if(this.has(e))return this.getId(e);let r;return t===void 0?r=this.id++:r=t,this.styleIDMap.set(e,r),this.idStyleMap.set(r,e),r}getStyle(e){return this.idStyleMap.get(e)||null}reset(){this.styleIDMap=new WeakMap,this.idStyleMap=new Map,this.id=1}generateId(){return this.id++}};wp=Object.freeze(Object.defineProperty({__proto__:null,StyleSheetMirror:At,get _mirror(){return Lr},closestElementOfNode:an,getBaseDimension:dn,getNestedRule:je,getPositionsAndIndex:gs,getRootShadowHost:vl,getShadowHost:fn,getWindowHeight:nn,getWindowScroll:sn,getWindowWidth:on,hasShadowRoot:xe,hookSetter:Lt,inDom:pn,isAncestorRemoved:ln,isBlocked:te,isIgnored:yr,isSerialized:gl,isSerializedIframe:Je,isSerializedStylesheet:hn,iterateResolveTree:un,legacy_isTouchEvent:_r,get nowTimestamp(){return Nt},on:ee,patch:Fe,polyfill:cn,queueToResolveTrees:yl,shadowHostInDom:bl,throttle:ot,uniqueTextMutations:wl},Symbol.toStringTag,{value:"Module"})),x=(i=>(i[i.DomContentLoaded=0]="DomContentLoaded",i[i.Load=1]="Load",i[i.FullSnapshot=2]="FullSnapshot",i[i.IncrementalSnapshot=3]="IncrementalSnapshot",i[i.Meta=4]="Meta",i[i.Custom=5]="Custom",i[i.Plugin=6]="Plugin",i))(x||{}),E=(i=>(i[i.Mutation=0]="Mutation",i[i.MouseMove=1]="MouseMove",i[i.MouseInteraction=2]="MouseInteraction",i[i.Scroll=3]="Scroll",i[i.ViewportResize=4]="ViewportResize",i[i.Input=5]="Input",i[i.TouchMove=6]="TouchMove",i[i.MediaInteraction=7]="MediaInteraction",i[i.StyleSheetRule=8]="StyleSheetRule",i[i.CanvasMutation=9]="CanvasMutation",i[i.Font=10]="Font",i[i.Log=11]="Log",i[i.Drag=12]="Drag",i[i.StyleDeclaration=13]="StyleDeclaration",i[i.Selection=14]="Selection",i[i.AdoptedStyleSheet=15]="AdoptedStyleSheet",i[i.CustomElement=16]="CustomElement",i))(E||{}),D=(i=>(i[i.MouseUp=0]="MouseUp",i[i.MouseDown=1]="MouseDown",i[i.Click=2]="Click",i[i.ContextMenu=3]="ContextMenu",i[i.DblClick=4]="DblClick",i[i.Focus=5]="Focus",i[i.Blur=6]="Blur",i[i.TouchStart=7]="TouchStart",i[i.TouchMove_Departed=8]="TouchMove_Departed",i[i.TouchEnd=9]="TouchEnd",i[i.TouchCancel=10]="TouchCancel",i))(D||{}),ge=(i=>(i[i.Mouse=0]="Mouse",i[i.Pen=1]="Pen",i[i.Touch=2]="Touch",i))(ge||{}),be=(i=>(i[i["2D"]=0]="2D",i[i.WebGL=1]="WebGL",i[i.WebGL2=2]="WebGL2",i))(be||{}),Ee=(i=>(i[i.Play=0]="Play",i[i.Pause=1]="Pause",i[i.Seeked=2]="Seeked",i[i.VolumeChange=3]="VolumeChange",i[i.RateChange=4]="RateChange",i))(Ee||{}),O=(i=>(i.Start="start",i.Pause="pause",i.Resume="resume",i.Resize="resize",i.Finish="finish",i.FullsnapshotRebuilded="fullsnapshot-rebuilded",i.LoadStylesheetStart="load-stylesheet-start",i.LoadStylesheetEnd="load-stylesheet-end",i.SkipStart="skip-start",i.SkipEnd="skip-end",i.MouseInteraction="mouse-interaction",i.EventCast="event-cast",i.CustomEvent="custom-event",i.Flush="flush",i.StateChange="state-change",i.PlayBack="play-back",i.Destroy="destroy",i))(O||{}),ye=(i=>(i[i.Document=0]="Document",i[i.DocumentType=1]="DocumentType",i[i.Element=2]="Element",i[i.Text=3]="Text",i[i.CDATA=4]="CDATA",i[i.Comment=5]="Comment",i))(ye||{});ys=class{constructor(){v(this,"length",0),v(this,"head",null),v(this,"tail",null)}get(e){if(e>=this.length)throw new Error("Position outside of list range");let t=this.head;for(let r=0;r<e;r++)t=(t==null?void 0:t.next)||null;return t}addNode(e){let t={value:e,previous:null,next:null};if(e.__ln=t,e.previousSibling&&vo(e.previousSibling)){let r=e.previousSibling.__ln.next;t.next=r,t.previous=e.previousSibling.__ln,e.previousSibling.__ln.next=t,r&&(r.previous=t)}else if(e.nextSibling&&vo(e.nextSibling)&&e.nextSibling.__ln.previous){let r=e.nextSibling.__ln.previous;t.previous=r,t.next=e.nextSibling.__ln,e.nextSibling.__ln.previous=t,r&&(r.next=t)}else this.head&&(this.head.previous=t),t.next=this.head,this.head=t;t.next===null&&(this.tail=t),this.length++}removeNode(e){let t=e.__ln;this.head&&(t.previous?(t.previous.next=t.next,t.next?t.next.previous=t.previous:this.tail=t.previous):(this.head=t.next,this.head?this.head.previous=null:this.tail=null),e.__ln&&delete e.__ln,this.length--)}},bo=(i,e)=>`${i}@${e}`,ws=class{constructor(){v(this,"frozen",!1),v(this,"locked",!1),v(this,"texts",[]),v(this,"attributes",[]),v(this,"attributeMap",new WeakMap),v(this,"removes",[]),v(this,"mapRemoves",[]),v(this,"movedMap",{}),v(this,"addedSet",new Set),v(this,"movedSet",new Set),v(this,"droppedSet",new Set),v(this,"removesSubTreeCache",new Set),v(this,"mutationCb"),v(this,"blockClass"),v(this,"blockSelector"),v(this,"maskTextClass"),v(this,"maskTextSelector"),v(this,"inlineStylesheet"),v(this,"maskInputOptions"),v(this,"maskTextFn"),v(this,"maskInputFn"),v(this,"keepIframeSrcFn"),v(this,"recordCanvas"),v(this,"inlineImages"),v(this,"slimDOMOptions"),v(this,"dataURLOptions"),v(this,"doc"),v(this,"mirror"),v(this,"iframeManager"),v(this,"stylesheetManager"),v(this,"shadowDomManager"),v(this,"canvasManager"),v(this,"processedNodeManager"),v(this,"unattachedDoc"),v(this,"processMutations",e=>{e.forEach(this.processMutation),this.emit()}),v(this,"emit",()=>{if(this.frozen||this.locked)return;let e=[],t=new Set,r=new ys,s=l=>{let c=l,u=St;for(;u===St;)c=c&&c.nextSibling,u=c&&this.mirror.getId(c);return u},n=l=>{let c=M.parentNode(l);if(!c||!pn(l))return;let u=!1;if(l.nodeType===Node.TEXT_NODE){let g=c.tagName;if(g==="TEXTAREA")return;g==="STYLE"&&this.addedSet.has(c)&&(u=!0)}let h=gt(c)?this.mirror.getId(fn(l)):this.mirror.getId(c),d=s(l);if(h===-1||d===-1)return r.addNode(l);let p=Ke(l,{doc:this.doc,mirror:this.mirror,blockClass:this.blockClass,blockSelector:this.blockSelector,maskTextClass:this.maskTextClass,maskTextSelector:this.maskTextSelector,skipChild:!0,newlyAddedElement:!0,inlineStylesheet:this.inlineStylesheet,maskInputOptions:this.maskInputOptions,maskTextFn:this.maskTextFn,maskInputFn:this.maskInputFn,slimDOMOptions:this.slimDOMOptions,dataURLOptions:this.dataURLOptions,recordCanvas:this.recordCanvas,inlineImages:this.inlineImages,onSerialize:g=>{Je(g,this.mirror)&&this.iframeManager.addIframe(g),hn(g,this.mirror)&&this.stylesheetManager.trackLinkElement(g),xe(l)&&this.shadowDomManager.addShadowRoot(M.shadowRoot(l),this.doc)},onIframeLoad:(g,m)=>{this.iframeManager.attachIframe(g,m),this.shadowDomManager.observeAttachShadow(g)},onStylesheetLoad:(g,m)=>{this.stylesheetManager.attachLinkElement(g,m)},cssCaptured:u});p&&(e.push({parentId:h,nextId:d,node:p}),t.add(p.id))};for(;this.mapRemoves.length;)this.mirror.removeNodeFromMap(this.mapRemoves.shift());for(let l of this.movedSet)So(this.removesSubTreeCache,l,this.mirror)&&!this.movedSet.has(M.parentNode(l))||n(l);for(let l of this.addedSet)!Co(this.droppedSet,l)&&!So(this.removesSubTreeCache,l,this.mirror)||Co(this.movedSet,l)?n(l):this.droppedSet.add(l);let o=null;for(;r.length;){let l=null;if(o){let c=this.mirror.getId(M.parentNode(o.value)),u=s(o.value);c!==-1&&u!==-1&&(l=o)}if(!l){let c=r.tail;for(;c;){let u=c;if(c=c.previous,u){let h=this.mirror.getId(M.parentNode(u.value));if(s(u.value)===-1)continue;if(h!==-1){l=u;break}else{let p=u.value,g=M.parentNode(p);if(g&&g.nodeType===Node.DOCUMENT_FRAGMENT_NODE){let m=M.host(g);if(this.mirror.getId(m)!==-1){l=u;break}}}}}}if(!l){for(;r.head;)r.removeNode(r.head.value);break}o=l.previous,r.removeNode(l.value),n(l.value)}let a={texts:this.texts.map(l=>{let c=l.node,u=M.parentNode(c);return u&&u.tagName==="TEXTAREA"&&this.genTextAreaValueMutation(u),{id:this.mirror.getId(c),value:l.value}}).filter(l=>!t.has(l.id)).filter(l=>this.mirror.has(l.id)),attributes:this.attributes.map(l=>{let{attributes:c}=l;if(typeof c.style=="string"){let u=JSON.stringify(l.styleDiff),h=JSON.stringify(l._unchangedStyles);u.length<c.style.length&&(u+h).split("var(").length===c.style.split("var(").length&&(c.style=l.styleDiff)}return{id:this.mirror.getId(l.node),attributes:c}}).filter(l=>!t.has(l.id)).filter(l=>this.mirror.has(l.id)),removes:this.removes,adds:e};!a.texts.length&&!a.attributes.length&&!a.removes.length&&!a.adds.length||(this.texts=[],this.attributes=[],this.attributeMap=new WeakMap,this.removes=[],this.addedSet=new Set,this.movedSet=new Set,this.droppedSet=new Set,this.removesSubTreeCache=new Set,this.movedMap={},this.mutationCb(a))}),v(this,"genTextAreaValueMutation",e=>{let t=this.attributeMap.get(e);t||(t={node:e,attributes:{},styleDiff:{},_unchangedStyles:{}},this.attributes.push(t),this.attributeMap.set(e,t)),t.attributes.value=Array.from(M.childNodes(e),r=>M.textContent(r)||"").join("")}),v(this,"processMutation",e=>{if(!yr(e.target,this.mirror,this.slimDOMOptions))switch(e.type){case"characterData":{let t=M.textContent(e.target);!te(e.target,this.blockClass,this.blockSelector,!1)&&t!==e.oldValue&&this.texts.push({value:Vo(e.target,this.maskTextClass,this.maskTextSelector,!0)&&t?this.maskTextFn?this.maskTextFn(t,an(e.target)):t.replace(/[\S]/g,"*"):t,node:e.target});break}case"attributes":{let t=e.target,r=e.attributeName,s=e.target.getAttribute(r);if(r==="value"){let o=Os(t);s=As({element:t,maskInputOptions:this.maskInputOptions,tagName:t.tagName,type:o,value:s,maskInputFn:this.maskInputFn})}if(te(e.target,this.blockClass,this.blockSelector,!1)||s===e.oldValue)return;let n=this.attributeMap.get(e.target);if(t.tagName==="IFRAME"&&r==="src"&&!this.keepIframeSrcFn(s))if(!t.contentDocument)r="rr_src";else return;if(n||(n={node:e.target,attributes:{},styleDiff:{},_unchangedStyles:{}},this.attributes.push(n),this.attributeMap.set(e.target,n)),r==="type"&&t.tagName==="INPUT"&&(e.oldValue||"").toLowerCase()==="password"&&t.setAttribute("data-rr-is-password","true"),!Ho(t.tagName,r))if(n.attributes[r]=zo(this.doc,Te(t.tagName),Te(r),s),r==="style"){if(!this.unattachedDoc)try{this.unattachedDoc=document.implementation.createHTMLDocument()}catch(a){this.unattachedDoc=this.doc}let o=this.unattachedDoc.createElement("span");e.oldValue&&o.setAttribute("style",e.oldValue);for(let a of Array.from(t.style)){let l=t.style.getPropertyValue(a),c=t.style.getPropertyPriority(a);l!==o.style.getPropertyValue(a)||c!==o.style.getPropertyPriority(a)?c===""?n.styleDiff[a]=l:n.styleDiff[a]=[l,c]:n._unchangedStyles[a]=[l,c]}for(let a of Array.from(o.style))t.style.getPropertyValue(a)===""&&(n.styleDiff[a]=!1)}else r==="open"&&t.tagName==="DIALOG"&&(t.matches("dialog:modal")?n.attributes.rr_open_mode="modal":n.attributes.rr_open_mode="non-modal");break}case"childList":{if(te(e.target,this.blockClass,this.blockSelector,!0))return;if(e.target.tagName==="TEXTAREA"){this.genTextAreaValueMutation(e.target);return}e.addedNodes.forEach(t=>this.genAdds(t,e.target)),e.removedNodes.forEach(t=>{let r=this.mirror.getId(t),s=gt(e.target)?this.mirror.getId(M.host(e.target)):this.mirror.getId(e.target);te(e.target,this.blockClass,this.blockSelector,!1)||yr(t,this.mirror,this.slimDOMOptions)||!gl(t,this.mirror)||(this.addedSet.has(t)?(vs(this.addedSet,t),this.droppedSet.add(t)):this.addedSet.has(e.target)&&r===-1||ln(e.target,this.mirror)||(this.movedSet.has(t)&&this.movedMap[bo(r,s)]?vs(this.movedSet,t):(this.removes.push({parentId:s,id:r,isShadow:gt(e.target)&&yt(e.target)?!0:void 0}),vp(t,this.removesSubTreeCache))),this.mapRemoves.push(t))});break}}}),v(this,"genAdds",(e,t)=>{if(!this.processedNodeManager.inOtherBuffer(e,this)&&!(this.addedSet.has(e)||this.movedSet.has(e))){if(this.mirror.hasNode(e)){if(yr(e,this.mirror,this.slimDOMOptions))return;this.movedSet.add(e);let r=null;t&&this.mirror.hasNode(t)&&(r=this.mirror.getId(t)),r&&r!==-1&&(this.movedMap[bo(this.mirror.getId(e),r)]=!0)}else this.addedSet.add(e),this.droppedSet.delete(e);te(e,this.blockClass,this.blockSelector,!1)||(M.childNodes(e).forEach(r=>this.genAdds(r)),xe(e)&&M.childNodes(M.shadowRoot(e)).forEach(r=>{this.processedNodeManager.add(r,this),this.genAdds(r,e)}))}})}init(e){["mutationCb","blockClass","blockSelector","maskTextClass","maskTextSelector","inlineStylesheet","maskInputOptions","maskTextFn","maskInputFn","keepIframeSrcFn","recordCanvas","inlineImages","slimDOMOptions","dataURLOptions","doc","mirror","iframeManager","stylesheetManager","shadowDomManager","canvasManager","processedNodeManager"].forEach(t=>{this[t]=e[t]})}freeze(){this.frozen=!0,this.canvasManager.freeze()}unfreeze(){this.frozen=!1,this.canvasManager.unfreeze(),this.emit()}isFrozen(){return this.frozen}lock(){this.locked=!0,this.canvasManager.lock()}unlock(){this.locked=!1,this.canvasManager.unlock(),this.emit()}reset(){this.shadowDomManager.reset(),this.canvasManager.reset()}};A=i=>vt?(...t)=>{try{return i(...t)}catch(r){if(vt&&vt(r)===!0)return;throw r}}:i,$e=[];Tp=["INPUT","TEXTAREA","SELECT"],Eo=new WeakMap;Ur=class{constructor(e){v(this,"iframeIdToRemoteIdMap",new WeakMap),v(this,"iframeRemoteIdToIdMap",new WeakMap),this.generateIdFn=e}getId(e,t,r,s){let n=r||this.getIdToRemoteIdMap(e),o=s||this.getRemoteIdToIdMap(e),a=n.get(t);return a||(a=this.generateIdFn(),n.set(t,a),o.set(a,t)),a}getIds(e,t){let r=this.getIdToRemoteIdMap(e),s=this.getRemoteIdToIdMap(e);return t.map(n=>this.getId(e,n,r,s))}getRemoteId(e,t,r){let s=r||this.getRemoteIdToIdMap(e);if(typeof t!="number")return t;let n=s.get(t);return n||-1}getRemoteIds(e,t){let r=this.getRemoteIdToIdMap(e);return t.map(s=>this.getRemoteId(e,s,r))}reset(e){if(!e){this.iframeIdToRemoteIdMap=new WeakMap,this.iframeRemoteIdToIdMap=new WeakMap;return}this.iframeIdToRemoteIdMap.delete(e),this.iframeRemoteIdToIdMap.delete(e)}getIdToRemoteIdMap(e){let t=this.iframeIdToRemoteIdMap.get(e);return t||(t=new Map,this.iframeIdToRemoteIdMap.set(e,t)),t}getRemoteIdToIdMap(e){let t=this.iframeRemoteIdToIdMap.get(e);return t||(t=new Map,this.iframeRemoteIdToIdMap.set(e,t)),t}},bs=class{constructor(e){v(this,"iframes",new WeakMap),v(this,"crossOriginIframeMap",new WeakMap),v(this,"crossOriginIframeMirror",new Ur(Wo)),v(this,"crossOriginIframeStyleMirror"),v(this,"crossOriginIframeRootIdMap",new WeakMap),v(this,"mirror"),v(this,"mutationCb"),v(this,"wrappedEmit"),v(this,"loadListener"),v(this,"stylesheetManager"),v(this,"recordCrossOriginIframes"),this.mutationCb=e.mutationCb,this.wrappedEmit=e.wrappedEmit,this.stylesheetManager=e.stylesheetManager,this.recordCrossOriginIframes=e.recordCrossOriginIframes,this.crossOriginIframeStyleMirror=new Ur(this.stylesheetManager.styleMirror.generateId.bind(this.stylesheetManager.styleMirror)),this.mirror=e.mirror,this.recordCrossOriginIframes&&window.addEventListener("message",this.handleMessage.bind(this))}addIframe(e){this.iframes.set(e,!0),e.contentWindow&&this.crossOriginIframeMap.set(e.contentWindow,e)}addLoadListener(e){this.loadListener=e}attachIframe(e,t){var r,s;this.mutationCb({adds:[{parentId:this.mirror.getId(e),nextId:null,node:t}],removes:[],texts:[],attributes:[],isAttachIframe:!0}),this.recordCrossOriginIframes&&((r=e.contentWindow)==null||r.addEventListener("message",this.handleMessage.bind(this))),(s=this.loadListener)==null||s.call(this,e),e.contentDocument&&e.contentDocument.adoptedStyleSheets&&e.contentDocument.adoptedStyleSheets.length>0&&this.stylesheetManager.adoptStyleSheets(e.contentDocument.adoptedStyleSheets,this.mirror.getId(e.contentDocument))}handleMessage(e){let t=e;if(t.data.type!=="rrweb"||t.origin!==t.data.origin||!e.source)return;let s=this.crossOriginIframeMap.get(e.source);if(!s)return;let n=this.transformCrossOriginEvent(s,t.data.event);n&&this.wrappedEmit(n,t.data.isCheckout)}transformCrossOriginEvent(e,t){var r;switch(t.type){case x.FullSnapshot:{this.crossOriginIframeMirror.reset(e),this.crossOriginIframeStyleMirror.reset(e),this.replaceIdOnNode(t.data.node,e);let s=t.data.node.id;return this.crossOriginIframeRootIdMap.set(e,s),this.patchRootIdOnNode(t.data.node,s),{timestamp:t.timestamp,type:x.IncrementalSnapshot,data:{source:E.Mutation,adds:[{parentId:this.mirror.getId(e),nextId:null,node:t.data.node}],removes:[],texts:[],attributes:[],isAttachIframe:!0}}}case x.Meta:case x.Load:case x.DomContentLoaded:return!1;case x.Plugin:return t;case x.Custom:return this.replaceIds(t.data.payload,e,["id","parentId","previousId","nextId"]),t;case x.IncrementalSnapshot:switch(t.data.source){case E.Mutation:return t.data.adds.forEach(s=>{this.replaceIds(s,e,["parentId","nextId","previousId"]),this.replaceIdOnNode(s.node,e);let n=this.crossOriginIframeRootIdMap.get(e);n&&this.patchRootIdOnNode(s.node,n)}),t.data.removes.forEach(s=>{this.replaceIds(s,e,["parentId","id"])}),t.data.attributes.forEach(s=>{this.replaceIds(s,e,["id"])}),t.data.texts.forEach(s=>{this.replaceIds(s,e,["id"])}),t;case E.Drag:case E.TouchMove:case E.MouseMove:return t.data.positions.forEach(s=>{this.replaceIds(s,e,["id"])}),t;case E.ViewportResize:return!1;case E.MediaInteraction:case E.MouseInteraction:case E.Scroll:case E.CanvasMutation:case E.Input:return this.replaceIds(t.data,e,["id"]),t;case E.StyleSheetRule:case E.StyleDeclaration:return this.replaceIds(t.data,e,["id"]),this.replaceStyleIds(t.data,e,["styleId"]),t;case E.Font:return t;case E.Selection:return t.data.ranges.forEach(s=>{this.replaceIds(s,e,["start","end"])}),t;case E.AdoptedStyleSheet:return this.replaceIds(t.data,e,["id"]),this.replaceStyleIds(t.data,e,["styleIds"]),(r=t.data.styles)==null||r.forEach(s=>{this.replaceStyleIds(s,e,["styleId"])}),t}}return!1}replace(e,t,r,s){for(let n of s)!Array.isArray(t[n])&&typeof t[n]!="number"||(Array.isArray(t[n])?t[n]=e.getIds(r,t[n]):t[n]=e.getId(r,t[n]));return t}replaceIds(e,t,r){return this.replace(this.crossOriginIframeMirror,e,t,r)}replaceStyleIds(e,t,r){return this.replace(this.crossOriginIframeStyleMirror,e,t,r)}replaceIdOnNode(e,t){this.replaceIds(e,t,["id","rootId"]),"childNodes"in e&&e.childNodes.forEach(r=>{this.replaceIdOnNode(r,t)})}patchRootIdOnNode(e,t){e.type!==ye.Document&&!e.rootId&&(e.rootId=t),"childNodes"in e&&e.childNodes.forEach(r=>{this.patchRootIdOnNode(r,t)})}},Ss=class{constructor(e){v(this,"shadowDoms",new WeakSet),v(this,"mutationCb"),v(this,"scrollCb"),v(this,"bypassOptions"),v(this,"mirror"),v(this,"restoreHandlers",[]),this.mutationCb=e.mutationCb,this.scrollCb=e.scrollCb,this.bypassOptions=e.bypassOptions,this.mirror=e.mirror,this.init()}init(){this.reset(),this.patchAttachShadow(Element,document)}addShadowRoot(e,t){if(!yt(e)||this.shadowDoms.has(e))return;this.shadowDoms.add(e);let r=Cl({...this.bypassOptions,doc:t,mutationCb:this.mutationCb,mirror:this.mirror,shadowDomManager:this},e);this.restoreHandlers.push(()=>r.disconnect()),this.restoreHandlers.push(El({...this.bypassOptions,scrollCb:this.scrollCb,doc:e,mirror:this.mirror})),setTimeout(()=>{e.adoptedStyleSheets&&e.adoptedStyleSheets.length>0&&this.bypassOptions.stylesheetManager.adoptStyleSheets(e.adoptedStyleSheets,this.mirror.getId(M.host(e))),this.restoreHandlers.push(xl({mirror:this.mirror,stylesheetManager:this.bypassOptions.stylesheetManager},e))},0)}observeAttachShadow(e){!e.contentWindow||!e.contentDocument||this.patchAttachShadow(e.contentWindow.Element,e.contentDocument)}patchAttachShadow(e,t){let r=this;this.restoreHandlers.push(Fe(e.prototype,"attachShadow",function(s){return function(n){let o=s.call(this,n),a=M.shadowRoot(this);return a&&pn(this)&&r.addShadowRoot(a,t),o}}))}reset(){this.restoreHandlers.forEach(e=>{try{e()}catch(t){}}),this.restoreHandlers=[],this.shadowDoms=new WeakSet}},Ye="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",mt=typeof Uint8Array=="undefined"?[]:new Uint8Array(256);for(pt=0;pt<Ye.length;pt++)mt[Ye.charCodeAt(pt)]=pt;Lp=function(i){var e=new Uint8Array(i),t,r=e.length,s="";for(t=0;t<r;t+=3)s+=Ye[e[t]>>2],s+=Ye[(e[t]&3)<<4|e[t+1]>>4],s+=Ye[(e[t+1]&15)<<2|e[t+2]>>6],s+=Ye[e[t+2]&63];return r%3===2?s=s.substring(0,s.length-1)+"=":r%3===1&&(s=s.substring(0,s.length-2)+"=="),s},_p=function(i){var e=i.length*.75,t=i.length,r,s=0,n,o,a,l;i[i.length-1]==="="&&(e--,i[i.length-2]==="="&&e--);var c=new ArrayBuffer(e),u=new Uint8Array(c);for(r=0;r<t;r+=4)n=mt[i.charCodeAt(r)],o=mt[i.charCodeAt(r+1)],a=mt[i.charCodeAt(r+2)],l=mt[i.charCodeAt(r+3)],u[s++]=n<<2|o>>4,u[s++]=(o&15)<<4|a>>2,u[s++]=(a&3)<<6|l&63;return c},xo=new Map;Il=(i,e,t)=>{if(!i||!(kl(i,e)||typeof i=="object"))return;let r=i.constructor.name,s=Fp(t,r),n=s.indexOf(i);return n===-1&&(n=s.length,s.push(i)),n};Tl=(i,e,t)=>i.map(r=>wr(r,e,t)),kl=(i,e)=>!!["WebGLActiveInfo","WebGLBuffer","WebGLFramebuffer","WebGLProgram","WebGLRenderbuffer","WebGLShader","WebGLShaderPrecisionFormat","WebGLTexture","WebGLUniformLocation","WebGLVertexArrayObject","WebGLVertexArrayObjectOES"].filter(s=>typeof e[s]=="function").find(s=>i instanceof e[s]);Ml="KGZ1bmN0aW9uKCkgewogICJ1c2Ugc3RyaWN0IjsKICB2YXIgY2hhcnMgPSAiQUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVphYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ejAxMjM0NTY3ODkrLyI7CiAgdmFyIGxvb2t1cCA9IHR5cGVvZiBVaW50OEFycmF5ID09PSAidW5kZWZpbmVkIiA/IFtdIDogbmV3IFVpbnQ4QXJyYXkoMjU2KTsKICBmb3IgKHZhciBpID0gMDsgaSA8IGNoYXJzLmxlbmd0aDsgaSsrKSB7CiAgICBsb29rdXBbY2hhcnMuY2hhckNvZGVBdChpKV0gPSBpOwogIH0KICB2YXIgZW5jb2RlID0gZnVuY3Rpb24oYXJyYXlidWZmZXIpIHsKICAgIHZhciBieXRlcyA9IG5ldyBVaW50OEFycmF5KGFycmF5YnVmZmVyKSwgaTIsIGxlbiA9IGJ5dGVzLmxlbmd0aCwgYmFzZTY0ID0gIiI7CiAgICBmb3IgKGkyID0gMDsgaTIgPCBsZW47IGkyICs9IDMpIHsKICAgICAgYmFzZTY0ICs9IGNoYXJzW2J5dGVzW2kyXSA+PiAyXTsKICAgICAgYmFzZTY0ICs9IGNoYXJzWyhieXRlc1tpMl0gJiAzKSA8PCA0IHwgYnl0ZXNbaTIgKyAxXSA+PiA0XTsKICAgICAgYmFzZTY0ICs9IGNoYXJzWyhieXRlc1tpMiArIDFdICYgMTUpIDw8IDIgfCBieXRlc1tpMiArIDJdID4+IDZdOwogICAgICBiYXNlNjQgKz0gY2hhcnNbYnl0ZXNbaTIgKyAyXSAmIDYzXTsKICAgIH0KICAgIGlmIChsZW4gJSAzID09PSAyKSB7CiAgICAgIGJhc2U2NCA9IGJhc2U2NC5zdWJzdHJpbmcoMCwgYmFzZTY0Lmxlbmd0aCAtIDEpICsgIj0iOwogICAgfSBlbHNlIGlmIChsZW4gJSAzID09PSAxKSB7CiAgICAgIGJhc2U2NCA9IGJhc2U2NC5zdWJzdHJpbmcoMCwgYmFzZTY0Lmxlbmd0aCAtIDIpICsgIj09IjsKICAgIH0KICAgIHJldHVybiBiYXNlNjQ7CiAgfTsKICBjb25zdCBsYXN0QmxvYk1hcCA9IC8qIEBfX1BVUkVfXyAqLyBuZXcgTWFwKCk7CiAgY29uc3QgdHJhbnNwYXJlbnRCbG9iTWFwID0gLyogQF9fUFVSRV9fICovIG5ldyBNYXAoKTsKICBhc3luYyBmdW5jdGlvbiBnZXRUcmFuc3BhcmVudEJsb2JGb3Iod2lkdGgsIGhlaWdodCwgZGF0YVVSTE9wdGlvbnMpIHsKICAgIGNvbnN0IGlkID0gYCR7d2lkdGh9LSR7aGVpZ2h0fWA7CiAgICBpZiAoIk9mZnNjcmVlbkNhbnZhcyIgaW4gZ2xvYmFsVGhpcykgewogICAgICBpZiAodHJhbnNwYXJlbnRCbG9iTWFwLmhhcyhpZCkpIHJldHVybiB0cmFuc3BhcmVudEJsb2JNYXAuZ2V0KGlkKTsKICAgICAgY29uc3Qgb2Zmc2NyZWVuID0gbmV3IE9mZnNjcmVlbkNhbnZhcyh3aWR0aCwgaGVpZ2h0KTsKICAgICAgb2Zmc2NyZWVuLmdldENvbnRleHQoIjJkIik7CiAgICAgIGNvbnN0IGJsb2IgPSBhd2FpdCBvZmZzY3JlZW4uY29udmVydFRvQmxvYihkYXRhVVJMT3B0aW9ucyk7CiAgICAgIGNvbnN0IGFycmF5QnVmZmVyID0gYXdhaXQgYmxvYi5hcnJheUJ1ZmZlcigpOwogICAgICBjb25zdCBiYXNlNjQgPSBlbmNvZGUoYXJyYXlCdWZmZXIpOwogICAgICB0cmFuc3BhcmVudEJsb2JNYXAuc2V0KGlkLCBiYXNlNjQpOwogICAgICByZXR1cm4gYmFzZTY0OwogICAgfSBlbHNlIHsKICAgICAgcmV0dXJuICIiOwogICAgfQogIH0KICBjb25zdCB3b3JrZXIgPSBzZWxmOwogIHdvcmtlci5vbm1lc3NhZ2UgPSBhc3luYyBmdW5jdGlvbihlKSB7CiAgICBpZiAoIk9mZnNjcmVlbkNhbnZhcyIgaW4gZ2xvYmFsVGhpcykgewogICAgICBjb25zdCB7IGlkLCBiaXRtYXAsIHdpZHRoLCBoZWlnaHQsIGRhdGFVUkxPcHRpb25zIH0gPSBlLmRhdGE7CiAgICAgIGNvbnN0IHRyYW5zcGFyZW50QmFzZTY0ID0gZ2V0VHJhbnNwYXJlbnRCbG9iRm9yKAogICAgICAgIHdpZHRoLAogICAgICAgIGhlaWdodCwKICAgICAgICBkYXRhVVJMT3B0aW9ucwogICAgICApOwogICAgICBjb25zdCBvZmZzY3JlZW4gPSBuZXcgT2Zmc2NyZWVuQ2FudmFzKHdpZHRoLCBoZWlnaHQpOwogICAgICBjb25zdCBjdHggPSBvZmZzY3JlZW4uZ2V0Q29udGV4dCgiMmQiKTsKICAgICAgY3R4LmRyYXdJbWFnZShiaXRtYXAsIDAsIDApOwogICAgICBiaXRtYXAuY2xvc2UoKTsKICAgICAgY29uc3QgYmxvYiA9IGF3YWl0IG9mZnNjcmVlbi5jb252ZXJ0VG9CbG9iKGRhdGFVUkxPcHRpb25zKTsKICAgICAgY29uc3QgdHlwZSA9IGJsb2IudHlwZTsKICAgICAgY29uc3QgYXJyYXlCdWZmZXIgPSBhd2FpdCBibG9iLmFycmF5QnVmZmVyKCk7CiAgICAgIGNvbnN0IGJhc2U2NCA9IGVuY29kZShhcnJheUJ1ZmZlcik7CiAgICAgIGlmICghbGFzdEJsb2JNYXAuaGFzKGlkKSAmJiBhd2FpdCB0cmFuc3BhcmVudEJhc2U2NCA9PT0gYmFzZTY0KSB7CiAgICAgICAgbGFzdEJsb2JNYXAuc2V0KGlkLCBiYXNlNjQpOwogICAgICAgIHJldHVybiB3b3JrZXIucG9zdE1lc3NhZ2UoeyBpZCB9KTsKICAgICAgfQogICAgICBpZiAobGFzdEJsb2JNYXAuZ2V0KGlkKSA9PT0gYmFzZTY0KSByZXR1cm4gd29ya2VyLnBvc3RNZXNzYWdlKHsgaWQgfSk7CiAgICAgIHdvcmtlci5wb3N0TWVzc2FnZSh7CiAgICAgICAgaWQsCiAgICAgICAgdHlwZSwKICAgICAgICBiYXNlNjQsCiAgICAgICAgd2lkdGgsCiAgICAgICAgaGVpZ2h0CiAgICAgIH0pOwogICAgICBsYXN0QmxvYk1hcC5zZXQoaWQsIGJhc2U2NCk7CiAgICB9IGVsc2UgewogICAgICByZXR1cm4gd29ya2VyLnBvc3RNZXNzYWdlKHsgaWQ6IGUuZGF0YS5pZCB9KTsKICAgIH0KICB9Owp9KSgpOwovLyMgc291cmNlTWFwcGluZ1VSTD1pbWFnZS1iaXRtYXAtZGF0YS11cmwtd29ya2VyLUlKcEM3Z19iLmpzLm1hcAo=",zp=i=>Uint8Array.from(atob(i),e=>e.charCodeAt(0)),ko=typeof window!="undefined"&&window.Blob&&new Blob([zp(Ml)],{type:"text/javascript;charset=utf-8"});Cs=class{constructor(e){v(this,"pendingCanvasMutations",new Map),v(this,"rafStamps",{latestId:0,invokeId:null}),v(this,"mirror"),v(this,"mutationCb"),v(this,"resetObservers"),v(this,"frozen",!1),v(this,"locked",!1),v(this,"processMutation",(l,c)=>{(this.rafStamps.invokeId&&this.rafStamps.latestId!==this.rafStamps.invokeId||!this.rafStamps.invokeId)&&(this.rafStamps.invokeId=this.rafStamps.latestId),this.pendingCanvasMutations.has(l)||this.pendingCanvasMutations.set(l,[]),this.pendingCanvasMutations.get(l).push(c)});let{sampling:t="all",win:r,blockClass:s,blockSelector:n,recordCanvas:o,dataURLOptions:a}=e;this.mutationCb=e.mutationCb,this.mirror=e.mirror,o&&t==="all"&&this.initCanvasMutationObserver(r,s,n),o&&typeof t=="number"&&this.initCanvasFPSObserver(t,r,s,n,{dataURLOptions:a})}reset(){this.pendingCanvasMutations.clear(),this.resetObservers&&this.resetObservers()}freeze(){this.frozen=!0}unfreeze(){this.frozen=!1}lock(){this.locked=!0}unlock(){this.locked=!1}initCanvasFPSObserver(e,t,r,s,n){let o=Io(t,r,s,!0),a=new Map,l=new Hp;l.onmessage=g=>{let{id:m}=g.data;if(a.set(m,!1),!("base64"in g.data))return;let{base64:f,type:y,width:b,height:w}=g.data;this.mutationCb({id:m,type:be["2D"],commands:[{property:"clearRect",args:[0,0,b,w]},{property:"drawImage",args:[{rr_type:"ImageBitmap",args:[{rr_type:"Blob",data:[{rr_type:"ArrayBuffer",base64:f}],type:y}]},0,0]}]})};let c=1e3/e,u=0,h,d=()=>{let g=[];return t.document.querySelectorAll("canvas").forEach(m=>{te(m,r,s,!0)||g.push(m)}),g},p=g=>{if(u&&g-u<c){h=requestAnimationFrame(p);return}u=g,d().forEach(async m=>{var f;let y=this.mirror.getId(m);if(a.get(y)||m.width===0||m.height===0)return;if(a.set(y,!0),["webgl","webgl2"].includes(m.__context)){let w=m.getContext(m.__context);((f=w==null?void 0:w.getContextAttributes())==null?void 0:f.preserveDrawingBuffer)===!1&&w.clear(w.COLOR_BUFFER_BIT)}let b=await createImageBitmap(m);l.postMessage({id:y,bitmap:b,width:m.width,height:m.height,dataURLOptions:n.dataURLOptions},[b])}),h=requestAnimationFrame(p)};h=requestAnimationFrame(p),this.resetObservers=()=>{o(),cancelAnimationFrame(h)}}initCanvasMutationObserver(e,t,r){this.startRAFTimestamping(),this.startPendingCanvasMutationFlusher();let s=Io(e,t,r,!1),n=Up(this.processMutation.bind(this),e,t,r),o=Wp(this.processMutation.bind(this),e,t,r);this.resetObservers=()=>{s(),n(),o()}}startPendingCanvasMutationFlusher(){requestAnimationFrame(()=>this.flushPendingCanvasMutations())}startRAFTimestamping(){let e=t=>{this.rafStamps.latestId=t,requestAnimationFrame(e)};requestAnimationFrame(e)}flushPendingCanvasMutations(){this.pendingCanvasMutations.forEach((e,t)=>{let r=this.mirror.getId(t);this.flushPendingCanvasMutationFor(t,r)}),requestAnimationFrame(()=>this.flushPendingCanvasMutations())}flushPendingCanvasMutationFor(e,t){if(this.frozen||this.locked)return;let r=this.pendingCanvasMutations.get(e);if(!r||t===-1)return;let s=r.map(o=>{let{type:a,...l}=o;return l}),{type:n}=r[0];this.mutationCb({id:t,type:n,commands:s}),this.pendingCanvasMutations.delete(e)}},Es=class{constructor(e){v(this,"trackedLinkElements",new WeakSet),v(this,"mutationCb"),v(this,"adoptedStyleSheetCb"),v(this,"styleMirror",new At),this.mutationCb=e.mutationCb,this.adoptedStyleSheetCb=e.adoptedStyleSheetCb}attachLinkElement(e,t){"_cssText"in t.attributes&&this.mutationCb({adds:[],removes:[],texts:[],attributes:[{id:t.id,attributes:t.attributes}]}),this.trackLinkElement(e)}trackLinkElement(e){this.trackedLinkElements.has(e)||(this.trackedLinkElements.add(e),this.trackStylesheetInLinkElement(e))}adoptStyleSheets(e,t){if(e.length===0)return;let r={id:t,styleIds:[]},s=[];for(let n of e){let o;this.styleMirror.has(n)?o=this.styleMirror.getId(n):(o=this.styleMirror.add(n),s.push({styleId:o,rules:Array.from(n.rules||CSSRule,(a,l)=>({rule:Fo(a,n.href),index:l}))})),r.styleIds.push(o)}s.length>0&&(r.styles=s),this.adoptedStyleSheetCb(r)}reset(){this.styleMirror.reset(),this.trackedLinkElements=new WeakSet}trackStylesheetInLinkElement(e){}},xs=class{constructor(){v(this,"nodeMap",new WeakMap),v(this,"active",!1)}inOtherBuffer(e,t){let r=this.nodeMap.get(e);return r&&Array.from(r).some(s=>s!==t)}add(e,t){this.active||(this.active=!0,requestAnimationFrame(()=>{this.nodeMap=new WeakMap,this.active=!1})),this.nodeMap.set(e,(this.nodeMap.get(e)||new Set).add(t))}destroy(){}},Br=!1;try{if(Array.from([1],i=>i*2)[0]!==2){let i=document.createElement("iframe");document.body.appendChild(i),Array.from=((Tn=i.contentWindow)==null?void 0:Tn.Array.from)||Array.from,document.body.removeChild(i)}}catch(i){console.debug("Unable to override Array.from",i)}le=Uo();Re.addCustomEvent=(i,e)=>{if(!Br)throw new Error("please add custom event after start recording");Z({type:x.Custom,data:{tag:i,payload:e}})};Re.freezePage=()=>{$e.forEach(i=>i.freeze())};Re.takeFullSnapshot=i=>{if(!Br)throw new Error("please take full snapshot after start recording");vr(i)};Re.mirror=le;Vp=Object.freeze(Object.defineProperty({__proto__:null,default:Rl},Symbol.toStringTag,{value:"Module"}));Is=class{constructor(e=[],t){v(this,"timeOffset",0),v(this,"speed"),v(this,"actions"),v(this,"raf",null),v(this,"lastTimestamp"),this.actions=e,this.speed=t.speed}addAction(e){let t=this.raf===!0;if(!this.actions.length||this.actions[this.actions.length-1].delay<=e.delay)this.actions.push(e);else{let r=this.findActionIndex(e);this.actions.splice(r,0,e)}t&&(this.raf=requestAnimationFrame(this.rafCheck.bind(this)))}start(){this.timeOffset=0,this.lastTimestamp=performance.now(),this.raf=requestAnimationFrame(this.rafCheck.bind(this))}rafCheck(){let e=performance.now();for(this.timeOffset+=(e-this.lastTimestamp)*this.speed,this.lastTimestamp=e;this.actions.length;){let t=this.actions[0];if(this.timeOffset>=t.delay)this.actions.shift(),t.doAction();else break}this.actions.length>0?this.raf=requestAnimationFrame(this.rafCheck.bind(this)):this.raf=!0}clear(){this.raf&&(this.raf!==!0&&cancelAnimationFrame(this.raf),this.raf=null),this.actions.length=0}setSpeed(e){this.speed=e}isActive(){return this.raf!==null}findActionIndex(e){let t=0,r=this.actions.length-1;for(;t<=r;){let s=Math.floor((t+r)/2);if(this.actions[s].delay<e.delay)t=s+1;else if(this.actions[s].delay>e.delay)r=s-1;else return s+1}return t}};(function(i){i[i.NotStarted=0]="NotStarted",i[i.Running=1]="Running",i[i.Stopped=2]="Stopped"})(Xe||(Xe={}));Nl={type:"xstate.init"};Do=function(i,e){return i.actions.forEach(function(t){var r=t.exec;return r&&r(i.context,e)})};Xp=i=>[`.${i} { background: currentColor }`,"noscript { display: none !important; }"],Po=new Map;Zp=["WebGLActiveInfo","WebGLBuffer","WebGLFramebuffer","WebGLProgram","WebGLRenderbuffer","WebGLShader","WebGLShaderPrecisionFormat","WebGLTexture","WebGLUniformLocation","WebGLVertexArrayObject"];ks=class{constructor(e){v(this,"mediaMap",new Map),v(this,"warn"),v(this,"service"),v(this,"speedService"),v(this,"emitter"),v(this,"getCurrentTime"),v(this,"metadataCallbackMap",new Map),this.warn=e.warn,this.service=e.service,this.speedService=e.speedService,this.emitter=e.emitter,this.getCurrentTime=e.getCurrentTime,this.emitter.on(O.Start,this.start.bind(this)),this.emitter.on(O.SkipStart,this.start.bind(this)),this.emitter.on(O.Pause,this.pause.bind(this)),this.emitter.on(O.Finish,this.pause.bind(this)),this.speedService.subscribe(()=>{this.syncAllMediaElements()})}syncAllMediaElements(e={pause:!1}){this.mediaMap.forEach((t,r)=>{this.syncTargetWithState(r),e.pause&&r.pause()})}start(){this.syncAllMediaElements()}pause(){this.syncAllMediaElements({pause:!0})}seekTo({time:e,target:t,mediaState:r}){if(r.isPlaying){let n=(e-r.lastInteractionTimeOffset)/1e3*r.playbackRate,o="duration"in t&&t.duration;if(Number.isNaN(o)){this.waitForMetadata(t);return}let a=r.currentTimeAtLastInteraction+n;t.loop&&o!==!1&&(a=a%o),t.currentTime=a}else t.pause(),t.currentTime=r.currentTimeAtLastInteraction}waitForMetadata(e){if(this.metadataCallbackMap.has(e)||!("addEventListener"in e))return;let t=()=>{this.metadataCallbackMap.delete(e);let r=this.mediaMap.get(e);r&&this.seekTo({time:this.getCurrentTime(),target:e,mediaState:r})};this.metadataCallbackMap.set(e,t),e.addEventListener("loadedmetadata",t,{once:!0})}getMediaStateFromMutation({target:e,timeOffset:t,mutation:r}){var p,g,m,f,y;let s=this.mediaMap.get(e),{type:n,playbackRate:o,currentTime:a,muted:l,volume:c,loop:u}=r;return{isPlaying:n===Ee.Play||n!==Ee.Pause&&((s==null?void 0:s.isPlaying)||e.getAttribute("autoplay")!==null),currentTimeAtLastInteraction:(p=a!=null?a:s==null?void 0:s.currentTimeAtLastInteraction)!=null?p:0,lastInteractionTimeOffset:t,playbackRate:(g=o!=null?o:s==null?void 0:s.playbackRate)!=null?g:1,volume:(m=c!=null?c:s==null?void 0:s.volume)!=null?m:1,muted:(f=l!=null?l:s==null?void 0:s.muted)!=null?f:e.getAttribute("muted")===null,loop:(y=u!=null?u:s==null?void 0:s.loop)!=null?y:e.getAttribute("loop")===null}}syncTargetWithState(e){let t=this.mediaMap.get(e);if(!t)return;let{muted:r,loop:s,volume:n,isPlaying:o}=t,a=this.service.state.matches("paused"),l=t.playbackRate*this.speedService.state.context.timer.speed;try{this.seekTo({time:this.getCurrentTime(),target:e,mediaState:t}),e.volume!==n&&(e.volume=n),e.muted=r,e.loop=s,e.playbackRate!==l&&(e.playbackRate=l),o&&!a?e.play():e.pause()}catch(c){this.warn(`Failed to replay media interactions: ${c.message||c}`)}}addMediaElements(e,t,r){if(!["AUDIO","VIDEO"].includes(e.nodeName))return;let s=e,n=r.getMeta(s);if(!n||!("attributes"in n))return;let o=this.service.state.matches("paused"),a=n.attributes,l=!1;a.rr_mediaState?l=a.rr_mediaState==="played":l=s.getAttribute("autoplay")!==null,l&&o&&s.pause();let c=1;typeof a.rr_mediaPlaybackRate=="number"&&(c=a.rr_mediaPlaybackRate);let u=!1;typeof a.rr_mediaMuted=="boolean"?u=a.rr_mediaMuted:u=s.getAttribute("muted")!==null;let h=!1;typeof a.rr_mediaLoop=="boolean"?h=a.rr_mediaLoop:h=s.getAttribute("loop")!==null;let d=1;typeof a.rr_mediaVolume=="number"&&(d=a.rr_mediaVolume);let p=0;typeof a.rr_mediaCurrentTime=="number"&&(p=a.rr_mediaCurrentTime),this.mediaMap.set(s,{isPlaying:l,currentTimeAtLastInteraction:p,lastInteractionTimeOffset:t,playbackRate:c,volume:d,muted:u,loop:h}),this.syncTargetWithState(s)}mediaMutation({target:e,timeOffset:t,mutation:r}){this.mediaMap.set(e,this.getMediaStateFromMutation({target:e,timeOffset:t,mutation:r})),this.syncTargetWithState(e)}isSupportedMediaElement(e){return["AUDIO","VIDEO"].includes(e.nodeName)}reset(){this.mediaMap.clear()}};rm=5*1e3,im=Rl||Vp,$o="[replayer]",Ti={duration:500,lineCap:"round",lineWidth:3,strokeStyle:"red"};Ms=class{constructor(e,t){if(v(this,"wrapper"),v(this,"iframe"),v(this,"service"),v(this,"speedService"),v(this,"config"),v(this,"usingVirtualDom",!1),v(this,"virtualDom",new st),v(this,"mouse"),v(this,"mouseTail",null),v(this,"tailPositions",[]),v(this,"emitter",im()),v(this,"nextUserInteractionEvent"),v(this,"legacy_missingNodeRetryMap",{}),v(this,"cache",Zn()),v(this,"imageMap",new Map),v(this,"canvasEventMap",new Map),v(this,"mirror",Uo()),v(this,"styleMirror",new At),v(this,"mediaManager"),v(this,"firstFullSnapshot",null),v(this,"newDocumentQueue",[]),v(this,"mousePos",null),v(this,"touchActive",null),v(this,"lastMouseDownEvent",null),v(this,"lastHoveredRootNode"),v(this,"lastSelectionData",null),v(this,"constructedStyleMutations",[]),v(this,"adoptedStyleSheets",[]),v(this,"handleResize",a=>{this.iframe.style.display="inherit";for(let l of[this.mouseTail,this.iframe])l&&(l.setAttribute("width",String(a.width)),l.setAttribute("height",String(a.height)))}),v(this,"applyEventsSynchronously",a=>{for(let l of a){switch(l.type){case x.DomContentLoaded:case x.Load:case x.Custom:continue;case x.FullSnapshot:case x.Meta:case x.Plugin:case x.IncrementalSnapshot:break}this.getCastFn(l,!0)()}}),v(this,"getCastFn",(a,l=!1)=>{let c;switch(a.type){case x.DomContentLoaded:case x.Load:break;case x.Custom:c=()=>{this.emitter.emit(O.CustomEvent,a)};break;case x.Meta:c=()=>this.emitter.emit(O.Resize,{width:a.data.width,height:a.data.height});break;case x.FullSnapshot:c=()=>{var h;if(this.firstFullSnapshot){if(this.firstFullSnapshot===a){this.firstFullSnapshot=!0;return}}else this.firstFullSnapshot=!0;this.mediaManager.reset(),this.styleMirror.reset(),this.rebuildFullSnapshot(a,l),(h=this.iframe.contentWindow)==null||h.scrollTo(a.data.initialOffset)};break;case x.IncrementalSnapshot:c=()=>{if(this.applyIncremental(a,l),!l&&(a===this.nextUserInteractionEvent&&(this.nextUserInteractionEvent=null,this.backToNormal()),this.config.skipInactive&&!this.nextUserInteractionEvent)){for(let h of this.service.state.context.events)if(!(h.timestamp<=a.timestamp)&&this.isUserInteraction(h)){h.delay-a.delay>this.config.inactivePeriodThreshold*this.speedService.state.context.timer.speed&&(this.nextUserInteractionEvent=h);break}if(this.nextUserInteractionEvent){let h=this.nextUserInteractionEvent.delay-a.delay,d={speed:Math.min(Math.round(h/rm),this.config.maxSpeed)};this.speedService.send({type:"FAST_FORWARD",payload:d}),this.emitter.emit(O.SkipStart,d)}}};break}return()=>{c&&c();for(let d of this.config.plugins||[])d.handler&&d.handler(a,l,{replayer:this});this.service.send({type:"CAST_EVENT",payload:{event:a}});let h=this.service.state.context.events.length-1;if(!this.config.liveMode&&a===this.service.state.context.events[h]){let d=()=>{h<this.service.state.context.events.length-1||(this.backToNormal(),this.service.send("END"),this.emitter.emit(O.Finish))},p=50;a.type===x.IncrementalSnapshot&&a.data.source===E.MouseMove&&a.data.positions.length&&(p+=Math.max(0,-a.data.positions[0].timeOffset)),setTimeout(d,p)}this.emitter.emit(O.EventCast,a)}}),!(t!=null&&t.liveMode)&&e.length<2)throw new Error("Replayer need at least 2 events.");let r={speed:1,maxSpeed:360,root:document.body,loadTimeout:0,skipInactive:!1,inactivePeriodThreshold:10*1e3,showWarning:!0,showDebug:!1,blockClass:"rr-block",liveMode:!1,insertStyleRules:[],triggerFocus:!0,UNSAFE_replayCanvas:!1,pauseAnimation:!0,mouseTail:Ti,useVirtualDom:!0,logger:console};this.config=Object.assign({},r,t),this.handleResize=this.handleResize.bind(this),this.getCastFn=this.getCastFn.bind(this),this.applyEventsSynchronously=this.applyEventsSynchronously.bind(this),this.emitter.on(O.Resize,this.handleResize),this.setupDom();for(let a of this.config.plugins||[])a.getMirror&&a.getMirror({nodeMirror:this.mirror});this.emitter.on(O.Flush,()=>{if(this.usingVirtualDom){let a={mirror:this.mirror,applyCanvas:(l,c,u)=>{Ts({event:l,mutation:c,target:u,imageMap:this.imageMap,canvasEventMap:this.canvasEventMap,errorHandler:this.warnCanvasMutationFailed.bind(this)})},applyInput:this.applyInput.bind(this),applyScroll:this.applyScroll.bind(this),applyStyleSheetMutation:(l,c)=>{l.source===E.StyleSheetRule?this.applyStyleSheetRule(l,c):l.source===E.StyleDeclaration&&this.applyStyleDeclaration(l,c)},afterAppend:(l,c)=>{for(let u of this.config.plugins||[])u.onBuild&&u.onBuild(l,{id:c,replayer:this})}};if(this.iframe.contentDocument)try{Pr(this.iframe.contentDocument,this.virtualDom,a,this.virtualDom.mirror)}catch(l){console.warn(l)}if(this.virtualDom.destroyTree(),this.usingVirtualDom=!1,Object.keys(this.legacy_missingNodeRetryMap).length)for(let l in this.legacy_missingNodeRetryMap)try{let c=this.legacy_missingNodeRetryMap[l],u=$r(c.node,this.mirror,this.virtualDom.mirror);Pr(u,c.node,a,this.virtualDom.mirror),c.node=u}catch(c){this.warn(c)}this.constructedStyleMutations.forEach(l=>{this.applyStyleSheetMutation(l)}),this.constructedStyleMutations=[],this.adoptedStyleSheets.forEach(l=>{this.applyAdoptedStyleSheet(l)}),this.adoptedStyleSheets=[]}if(this.mousePos&&(this.moveAndHover(this.mousePos.x,this.mousePos.y,this.mousePos.id,!0,this.mousePos.debugData),this.mousePos=null),this.touchActive===!0?this.mouse.classList.add("touch-active"):this.touchActive===!1&&this.mouse.classList.remove("touch-active"),this.touchActive=null,this.lastMouseDownEvent){let[a,l]=this.lastMouseDownEvent;a.dispatchEvent(l)}this.lastMouseDownEvent=null,this.lastSelectionData&&(this.applySelection(this.lastSelectionData),this.lastSelectionData=null)}),this.emitter.on(O.PlayBack,()=>{this.firstFullSnapshot=null,this.mirror.reset(),this.styleMirror.reset(),this.mediaManager.reset()});let s=new Is([],{speed:this.config.speed});this.service=jp({events:e.map(a=>t&&t.unpackFn?t.unpackFn(a):a).sort((a,l)=>a.timestamp-l.timestamp),timer:s,timeOffset:0,baselineTime:0,lastPlayedEvent:null},{getCastFn:this.getCastFn,applyEventsSynchronously:this.applyEventsSynchronously,emitter:this.emitter}),this.service.start(),this.service.subscribe(a=>{this.emitter.emit(O.StateChange,{player:a})}),this.speedService=Yp({normalSpeed:-1,timer:s}),this.speedService.start(),this.speedService.subscribe(a=>{this.emitter.emit(O.StateChange,{speed:a})}),this.mediaManager=new ks({warn:this.warn.bind(this),service:this.service,speedService:this.speedService,emitter:this.emitter,getCurrentTime:this.getCurrentTime.bind(this)});let n=this.service.state.context.events.find(a=>a.type===x.Meta),o=this.service.state.context.events.find(a=>a.type===x.FullSnapshot);if(n){let{width:a,height:l}=n.data;setTimeout(()=>{this.emitter.emit(O.Resize,{width:a,height:l})},0)}o&&setTimeout(()=>{var a;this.firstFullSnapshot||(this.firstFullSnapshot=o,this.rebuildFullSnapshot(o),(a=this.iframe.contentWindow)==null||a.scrollTo(o.data.initialOffset))},1),this.service.state.context.events.find(Lo)&&this.mouse.classList.add("touch-device")}get timer(){return this.service.state.context.timer}on(e,t){return this.emitter.on(e,t),this}off(e,t){return this.emitter.off(e,t),this}setConfig(e){Object.keys(e).forEach(t=>{e[t],this.config[t]=e[t]}),this.config.skipInactive||this.backToNormal(),typeof e.speed!="undefined"&&this.speedService.send({type:"SET_SPEED",payload:{speed:e.speed}}),typeof e.mouseTail!="undefined"&&(e.mouseTail===!1?this.mouseTail&&(this.mouseTail.style.display="none"):(this.mouseTail||(this.mouseTail=document.createElement("canvas"),this.mouseTail.width=Number.parseFloat(this.iframe.width),this.mouseTail.height=Number.parseFloat(this.iframe.height),this.mouseTail.classList.add("replayer-mouse-tail"),this.wrapper.insertBefore(this.mouseTail,this.iframe)),this.mouseTail.style.display="inherit"))}getMetaData(){let e=this.service.state.context.events[0],t=this.service.state.context.events[this.service.state.context.events.length-1];return{startTime:e.timestamp,endTime:t.timestamp,totalTime:t.timestamp-e.timestamp}}getCurrentTime(){return this.timer.timeOffset+this.getTimeOffset()}getTimeOffset(){let{baselineTime:e,events:t}=this.service.state.context;return e-t[0].timestamp}getMirror(){return this.mirror}play(e=0){var t,r;this.service.state.matches("paused")?this.service.send({type:"PLAY",payload:{timeOffset:e}}):(this.service.send({type:"PAUSE"}),this.service.send({type:"PLAY",payload:{timeOffset:e}})),(r=(t=this.iframe.contentDocument)==null?void 0:t.getElementsByTagName("html")[0])==null||r.classList.remove("rrweb-paused"),this.emitter.emit(O.Start)}pause(e){var t,r;e===void 0&&this.service.state.matches("playing")&&this.service.send({type:"PAUSE"}),typeof e=="number"&&(this.play(e),this.service.send({type:"PAUSE"})),(r=(t=this.iframe.contentDocument)==null?void 0:t.getElementsByTagName("html")[0])==null||r.classList.add("rrweb-paused"),this.emitter.emit(O.Pause)}resume(e=0){this.warn("The 'resume' was deprecated in 1.0. Please use 'play' method which has the same interface."),this.play(e),this.emitter.emit(O.Resume)}destroy(){this.pause(),this.mirror.reset(),this.styleMirror.reset(),this.mediaManager.reset(),this.config.root.removeChild(this.wrapper),this.emitter.emit(O.Destroy)}startLive(e){this.service.send({type:"TO_LIVE",payload:{baselineTime:e}})}addEvent(e){let t=this.config.unpackFn?this.config.unpackFn(e):e;Lo(t)&&this.mouse.classList.add("touch-device"),Promise.resolve().then(()=>this.service.send({type:"ADD_EVENT",payload:{event:t}}))}enableInteract(){this.iframe.setAttribute("scrolling","auto"),this.iframe.style.pointerEvents="auto"}disableInteract(){this.iframe.setAttribute("scrolling","no"),this.iframe.style.pointerEvents="none"}resetCache(){this.cache=Zn()}setupDom(){this.wrapper=document.createElement("div"),this.wrapper.classList.add("replayer-wrapper"),this.config.root.appendChild(this.wrapper),this.mouse=document.createElement("div"),this.mouse.classList.add("replayer-mouse"),this.wrapper.appendChild(this.mouse),this.config.mouseTail!==!1&&(this.mouseTail=document.createElement("canvas"),this.mouseTail.classList.add("replayer-mouse-tail"),this.mouseTail.style.display="inherit",this.wrapper.appendChild(this.mouseTail)),this.iframe=document.createElement("iframe");let e=["allow-same-origin"];this.config.UNSAFE_replayCanvas&&e.push("allow-scripts"),this.iframe.style.display="none",this.iframe.setAttribute("sandbox",e.join(" ")),this.disableInteract(),this.wrapper.appendChild(this.iframe),this.iframe.contentWindow&&this.iframe.contentDocument&&(Gp(this.iframe.contentWindow,this.iframe.contentDocument),cn(this.iframe.contentWindow))}rebuildFullSnapshot(e,t=!1){if(!this.iframe.contentDocument)return this.warn("Looks like your replayer has been destroyed.");Object.keys(this.legacy_missingNodeRetryMap).length&&this.warn("Found unresolved missing node map",this.legacy_missingNodeRetryMap),this.legacy_missingNodeRetryMap={};let r=[],s=new Set,n=(l,c)=>{if(l.nodeName==="DIALOG"&&s.add(l),this.collectIframeAndAttachDocument(r,l),this.mediaManager.isSupportedMediaElement(l)){let{events:u}=this.service.state.context;this.mediaManager.addMediaElements(l,e.timestamp-u[0].timestamp,this.mirror)}for(let u of this.config.plugins||[])u.onBuild&&u.onBuild(l,{id:c,replayer:this})};this.usingVirtualDom&&(this.virtualDom.destroyTree(),this.usingVirtualDom=!1),this.mirror.reset(),jh(e.data.node,{doc:this.iframe.contentDocument,afterAppend:n,cache:this.cache,mirror:this.mirror}),n(this.iframe.contentDocument,e.data.node.id);for(let{mutationInQueue:l,builtNode:c}of r)this.attachDocumentToIframe(l,c),this.newDocumentQueue=this.newDocumentQueue.filter(u=>u!==l);let{documentElement:o,head:a}=this.iframe.contentDocument;this.insertStyleRules(o,a),s.forEach(l=>dr(l)),this.service.state.matches("playing")||this.iframe.contentDocument.getElementsByTagName("html")[0].classList.add("rrweb-paused"),this.emitter.emit(O.FullsnapshotRebuilded,e),t||this.waitForStylesheetLoad(),this.config.UNSAFE_replayCanvas&&this.preloadAllImages()}insertStyleRules(e,t){var r;let s=Xp(this.config.blockClass).concat(this.config.insertStyleRules);if(this.config.pauseAnimation&&s.push("html.rrweb-paused *, html.rrweb-paused *:before, html.rrweb-paused *:after { animation-play-state: paused !important; }"),!!s.length)if(this.usingVirtualDom){let n=this.virtualDom.createElement("style");this.virtualDom.mirror.add(n,fl(n,this.virtualDom.unserializedId)),e.insertBefore(n,t),n.rules.push({source:E.StyleSheetRule,adds:s.map((o,a)=>({rule:o,index:a}))})}else{let n=document.createElement("style");e.insertBefore(n,t);for(let o=0;o<s.length;o++)(r=n.sheet)==null||r.insertRule(s[o],o)}}attachDocumentToIframe(e,t){let r=this.usingVirtualDom?this.virtualDom.mirror:this.mirror,s=[],n=new Set,o=(a,l)=>{a.nodeName==="DIALOG"&&n.add(a),this.collectIframeAndAttachDocument(s,a);let c=r.getMeta(a);if((c==null?void 0:c.type)===ye.Element&&(c==null?void 0:c.tagName.toUpperCase())==="HTML"){let{documentElement:u,head:h}=t.contentDocument;this.insertStyleRules(u,h)}if(!this.usingVirtualDom)for(let u of this.config.plugins||[])u.onBuild&&u.onBuild(a,{id:l,replayer:this})};wt(e.node,{doc:t.contentDocument,mirror:r,hackCss:!0,skipChild:!1,afterAppend:o,cache:this.cache}),o(t.contentDocument,e.node.id);for(let{mutationInQueue:a,builtNode:l}of s)this.attachDocumentToIframe(a,l),this.newDocumentQueue=this.newDocumentQueue.filter(c=>c!==a);n.forEach(a=>dr(a))}collectIframeAndAttachDocument(e,t){if(Je(t,this.mirror)){let r=this.newDocumentQueue.find(s=>s.parentId===this.mirror.getId(t));r&&e.push({mutationInQueue:r,builtNode:t})}}waitForStylesheetLoad(){var e;let t=(e=this.iframe.contentDocument)==null?void 0:e.head;if(t){let r=new Set,s,n=this.service.state,o=()=>{n=this.service.state};this.emitter.on(O.Start,o),this.emitter.on(O.Pause,o);let a=()=>{this.emitter.off(O.Start,o),this.emitter.off(O.Pause,o)};t.querySelectorAll('link[rel="stylesheet"]').forEach(l=>{l.sheet||(r.add(l),l.addEventListener("load",()=>{r.delete(l),r.size===0&&s!==-1&&(n.matches("playing")&&this.play(this.getCurrentTime()),this.emitter.emit(O.LoadStylesheetEnd),s&&clearTimeout(s),a())}))}),r.size>0&&(this.service.send({type:"PAUSE"}),this.emitter.emit(O.LoadStylesheetStart),s=setTimeout(()=>{n.matches("playing")&&this.play(this.getCurrentTime()),s=-1,a()},this.config.loadTimeout))}}async preloadAllImages(){let e=[];for(let t of this.service.state.context.events)t.type===x.IncrementalSnapshot&&t.data.source===E.CanvasMutation&&(e.push(this.deserializeAndPreloadCanvasEvents(t.data,t)),("commands"in t.data?t.data.commands:[t.data]).forEach(s=>{this.preloadImages(s,t)}));return Promise.all(e)}preloadImages(e,t){if(e.property==="drawImage"&&typeof e.args[0]=="string"&&!this.imageMap.has(t)){let r=document.createElement("canvas"),s=r.getContext("2d"),n=s==null?void 0:s.createImageData(r.width,r.height);s==null||s.putImageData(n,0,0)}}async deserializeAndPreloadCanvasEvents(e,t){if(!this.canvasEventMap.has(t)){let r={isUnchanged:!0};if("commands"in e){let s=await Promise.all(e.commands.map(async n=>{let o=await Promise.all(n.args.map(Ie(this.imageMap,null,r)));return{...n,args:o}}));r.isUnchanged===!1&&this.canvasEventMap.set(t,{...e,commands:s})}else{let s=await Promise.all(e.args.map(Ie(this.imageMap,null,r)));r.isUnchanged===!1&&this.canvasEventMap.set(t,{...e,args:s})}}}applyIncremental(e,t){var r,s,n;let{data:o}=e;switch(o.source){case E.Mutation:{try{this.applyMutation(o,t)}catch(a){this.warn(`Exception in mutation ${a.message||a}`,o)}break}case E.Drag:case E.TouchMove:case E.MouseMove:if(t){let a=o.positions[o.positions.length-1];this.mousePos={x:a.x,y:a.y,id:a.id,debugData:o}}else o.positions.forEach(a=>{let l={doAction:()=>{this.moveAndHover(a.x,a.y,a.id,t,o)},delay:a.timeOffset+e.timestamp-this.service.state.context.baselineTime};this.timer.addAction(l)}),this.timer.addAction({doAction(){},delay:e.delay-((r=o.positions[0])==null?void 0:r.timeOffset)});break;case E.MouseInteraction:{if(o.id===-1)break;let a=new Event(Te(D[o.type])),l=this.mirror.getNode(o.id);if(!l)return this.debugNodeNotFound(o,o.id);this.emitter.emit(O.MouseInteraction,{type:o.type,target:l});let{triggerFocus:c}=this.config;switch(o.type){case D.Blur:"blur"in l&&l.blur();break;case D.Focus:c&&l.focus&&l.focus({preventScroll:!0});break;case D.Click:case D.TouchStart:case D.TouchEnd:case D.MouseDown:case D.MouseUp:t?(o.type===D.TouchStart?this.touchActive=!0:o.type===D.TouchEnd&&(this.touchActive=!1),o.type===D.MouseDown?this.lastMouseDownEvent=[l,a]:o.type===D.MouseUp&&(this.lastMouseDownEvent=null),this.mousePos={x:o.x||0,y:o.y||0,id:o.id,debugData:o}):(o.type===D.TouchStart&&(this.tailPositions.length=0),this.moveAndHover(o.x||0,o.y||0,o.id,t,o),o.type===D.Click?(this.mouse.classList.remove("active"),this.mouse.offsetWidth,this.mouse.classList.add("active")):o.type===D.TouchStart?(this.mouse.offsetWidth,this.mouse.classList.add("touch-active")):o.type===D.TouchEnd?this.mouse.classList.remove("touch-active"):l.dispatchEvent(a));break;case D.TouchCancel:t?this.touchActive=!1:this.mouse.classList.remove("touch-active");break;default:l.dispatchEvent(a)}break}case E.Scroll:{if(o.id===-1)break;if(this.usingVirtualDom){let a=this.virtualDom.mirror.getNode(o.id);if(!a)return this.debugNodeNotFound(o,o.id);a.scrollData=o;break}this.applyScroll(o,t);break}case E.ViewportResize:this.emitter.emit(O.Resize,{width:o.width,height:o.height});break;case E.Input:{if(o.id===-1)break;if(this.usingVirtualDom){let a=this.virtualDom.mirror.getNode(o.id);if(!a)return this.debugNodeNotFound(o,o.id);a.inputData=o;break}this.applyInput(o);break}case E.MediaInteraction:{let a=this.usingVirtualDom?this.virtualDom.mirror.getNode(o.id):this.mirror.getNode(o.id);if(!a)return this.debugNodeNotFound(o,o.id);let l=a,{events:c}=this.service.state.context;this.mediaManager.mediaMutation({target:l,timeOffset:e.timestamp-c[0].timestamp,mutation:o});break}case E.StyleSheetRule:case E.StyleDeclaration:{this.usingVirtualDom?o.styleId?this.constructedStyleMutations.push(o):o.id&&((s=this.virtualDom.mirror.getNode(o.id))==null||s.rules.push(o)):this.applyStyleSheetMutation(o);break}case E.CanvasMutation:{if(!this.config.UNSAFE_replayCanvas)return;if(this.usingVirtualDom){let a=this.virtualDom.mirror.getNode(o.id);if(!a)return this.debugNodeNotFound(o,o.id);a.canvasMutations.push({event:e,mutation:o})}else{let a=this.mirror.getNode(o.id);if(!a)return this.debugNodeNotFound(o,o.id);Ts({event:e,mutation:o,target:a,imageMap:this.imageMap,canvasEventMap:this.canvasEventMap,errorHandler:this.warnCanvasMutationFailed.bind(this)})}break}case E.Font:{try{let a=new FontFace(o.family,o.buffer?new Uint8Array(JSON.parse(o.fontSource)):o.fontSource,o.descriptors);(n=this.iframe.contentDocument)==null||n.fonts.add(a)}catch(a){this.warn(a)}break}case E.Selection:{if(t){this.lastSelectionData=o;break}this.applySelection(o);break}case E.AdoptedStyleSheet:{this.usingVirtualDom?this.adoptedStyleSheets.push(o):this.applyAdoptedStyleSheet(o);break}}}applyMutation(e,t){if(this.config.useVirtualDom&&!this.usingVirtualDom&&t&&(this.usingVirtualDom=!0,sp(this.iframe.contentDocument,this.mirror,this.virtualDom),Object.keys(this.legacy_missingNodeRetryMap).length))for(let c in this.legacy_missingNodeRetryMap)try{let u=this.legacy_missingNodeRetryMap[c],h=dl(u.node,this.virtualDom,this.mirror);h&&(u.node=h)}catch(u){this.warn(u)}let r=this.usingVirtualDom?this.virtualDom.mirror:this.mirror;e.removes=e.removes.filter(c=>r.getNode(c.id)?!0:(this.warnNodeNotFound(e,c.id),!1)),e.removes.forEach(c=>{var u;let h=r.getNode(c.id);if(!h)return;let d=r.getNode(c.parentId);if(!d)return this.warnNodeNotFound(e,c.parentId);if(c.isShadow&&xe(d)&&(d=d.shadowRoot),r.removeNodeFromMap(h),d)try{d.removeChild(h),this.usingVirtualDom&&h.nodeName==="#text"&&d.nodeName==="STYLE"&&((u=d.rules)==null?void 0:u.length)>0&&(d.rules=[])}catch(p){if(p instanceof DOMException)this.warn("parent could not remove child in mutation",d,h,e);else throw p}});let s={...this.legacy_missingNodeRetryMap},n=[],o=c=>{let u=null;return c.nextId&&(u=r.getNode(c.nextId)),c.nextId!==null&&c.nextId!==void 0&&c.nextId!==-1&&!u},a=c=>{var u,h;if(!this.iframe.contentDocument)return this.warn("Looks like your replayer has been destroyed.");let d=r.getNode(c.parentId);if(!d)return c.node.type===ye.Document?this.newDocumentQueue.push(c):n.push(c);c.node.isShadow&&(xe(d)||d.attachShadow({mode:"open"}),d=d.shadowRoot);let p=null,g=null;if(c.previousId&&(p=r.getNode(c.previousId)),c.nextId&&(g=r.getNode(c.nextId)),o(c))return n.push(c);if(c.node.rootId&&!r.getNode(c.node.rootId))return;let m=c.node.rootId?r.getNode(c.node.rootId):this.usingVirtualDom?this.virtualDom:this.iframe.contentDocument;if(Je(d,r)){this.attachDocumentToIframe(c,d);return}let f=(w,S)=>{if(!this.usingVirtualDom){dr(w);for(let I of this.config.plugins||[])I.onBuild&&I.onBuild(w,{id:S,replayer:this})}},y=wt(c.node,{doc:m,mirror:r,skipChild:!0,hackCss:!0,cache:this.cache,afterAppend:f});if(c.previousId===-1||c.nextId===-1){s[c.node.id]={node:y,mutation:c};return}let b=r.getMeta(d);if(b&&b.type===ye.Element&&c.node.type===ye.Text){let w=Array.isArray(d.childNodes)?d.childNodes:Array.from(d.childNodes);if(b.tagName==="textarea")for(let S of w)S.nodeType===d.TEXT_NODE&&d.removeChild(S);else if(b.tagName==="style"&&w.length===1)for(let S of w)S.nodeType===d.TEXT_NODE&&!r.hasNode(S)&&(y.textContent=S.textContent,d.removeChild(S))}else if((b==null?void 0:b.type)===ye.Document){let w=d;c.node.type===ye.DocumentType&&((u=w.childNodes[0])==null?void 0:u.nodeType)===Node.DOCUMENT_TYPE_NODE&&w.removeChild(w.childNodes[0]),y.nodeName==="HTML"&&w.documentElement&&w.removeChild(w.documentElement)}if(p&&p.nextSibling&&p.nextSibling.parentNode?d.insertBefore(y,p.nextSibling):g&&g.parentNode?d.contains(g)?d.insertBefore(y,g):d.insertBefore(y,null):d.appendChild(y),f(y,c.node.id),this.usingVirtualDom&&y.nodeName==="#text"&&d.nodeName==="STYLE"&&((h=d.rules)==null?void 0:h.length)>0&&(d.rules=[]),Je(y,this.mirror)){let w=this.mirror.getId(y),S=this.newDocumentQueue.find(I=>I.parentId===w);S&&(this.attachDocumentToIframe(S,y),this.newDocumentQueue=this.newDocumentQueue.filter(I=>I!==S))}(c.previousId||c.nextId)&&this.legacy_resolveMissingNode(s,d,y,c)};e.adds.forEach(c=>{a(c)});let l=Date.now();for(;n.length;){let c=yl(n);if(n.length=0,Date.now()-l>500){this.warn("Timeout in the loop, please check the resolve tree data:",c);break}for(let u of c)r.getNode(u.value.parentId)?un(u,d=>{a(d)}):this.debug("Drop resolve tree since there is no parent for the root node.",u)}Object.keys(s).length&&Object.assign(this.legacy_missingNodeRetryMap,s),wl(e.texts).forEach(c=>{var u;let h=r.getNode(c.id);if(!h)return e.removes.find(p=>p.id===c.id)?void 0:this.warnNodeNotFound(e,c.id);let d=h.parentElement;if(c.value&&d&&d.tagName==="STYLE"?h.textContent=jr(c.value,this.cache):h.textContent=c.value,this.usingVirtualDom){let p=h.parentNode;((u=p==null?void 0:p.rules)==null?void 0:u.length)>0&&(p.rules=[])}}),e.attributes.forEach(c=>{var u;let h=r.getNode(c.id);if(!h)return e.removes.find(d=>d.id===c.id)?void 0:this.warnNodeNotFound(e,c.id);for(let d in c.attributes)if(typeof d=="string"){let p=c.attributes[d];if(p===null)h.removeAttribute(d),d==="open"&&tm(h,c);else if(typeof p=="string")try{if(d==="_cssText"&&(h.nodeName==="LINK"||h.nodeName==="STYLE"))try{let g=r.getMeta(h);Object.assign(g.attributes,c.attributes);let m=wt(g,{doc:h.ownerDocument,mirror:r,skipChild:!0,hackCss:!0,cache:this.cache}),f=h.nextSibling,y=h.parentNode;if(m&&y){y.removeChild(h),y.insertBefore(m,f),r.replace(c.id,m);break}}catch(g){}if(d==="value"&&h.nodeName==="TEXTAREA"){let g=h;g.childNodes.forEach(f=>g.removeChild(f));let m=(u=h.ownerDocument)==null?void 0:u.createTextNode(p);m&&g.appendChild(m)}else h.setAttribute(d,p);d==="rr_open_mode"&&h.nodeName==="DIALOG"&&dr(h,c)}catch(g){this.warn("An error occurred may due to the checkout feature.",g)}else if(d==="style"){let g=p,m=h;for(let f in g)if(g[f]===!1)m.style.removeProperty(f);else if(g[f]instanceof Array){let y=g[f];m.style.setProperty(f,y[0],y[1])}else{let y=g[f];m.style.setProperty(f,y)}}}})}applyScroll(e,t){var r,s;let n=this.mirror.getNode(e.id);if(!n)return this.debugNodeNotFound(e,e.id);let o=this.mirror.getMeta(n);if(n===this.iframe.contentDocument)(r=this.iframe.contentWindow)==null||r.scrollTo({top:e.y,left:e.x,behavior:t?"auto":"smooth"});else if((o==null?void 0:o.type)===ye.Document)(s=n.defaultView)==null||s.scrollTo({top:e.y,left:e.x,behavior:t?"auto":"smooth"});else try{n.scrollTo({top:e.y,left:e.x,behavior:t?"auto":"smooth"})}catch(a){}}applyInput(e){let t=this.mirror.getNode(e.id);if(!t)return this.debugNodeNotFound(e,e.id);try{t.checked=e.isChecked,t.value=e.text}catch(r){}}applySelection(e){try{let t=new Set,r=e.ranges.map(({start:s,startOffset:n,end:o,endOffset:a})=>{let l=this.mirror.getNode(s),c=this.mirror.getNode(o);if(!l||!c)return;let u=new Range;u.setStart(l,n),u.setEnd(c,a);let h=l.ownerDocument,d=h==null?void 0:h.getSelection();return d&&t.add(d),{range:u,selection:d}});t.forEach(s=>s.removeAllRanges()),r.forEach(s=>{var n;return s&&((n=s.selection)==null?void 0:n.addRange(s.range))})}catch(t){}}applyStyleSheetMutation(e){var t;let r=null;e.styleId?r=this.styleMirror.getStyle(e.styleId):e.id&&(r=((t=this.mirror.getNode(e.id))==null?void 0:t.sheet)||null),r&&(e.source===E.StyleSheetRule?this.applyStyleSheetRule(e,r):e.source===E.StyleDeclaration&&this.applyStyleDeclaration(e,r))}applyStyleSheetRule(e,t){var r,s,n,o;if((r=e.adds)==null||r.forEach(({rule:a,index:l})=>{try{if(Array.isArray(l)){let{positions:c,index:u}=gs(l);je(t.cssRules,c).insertRule(a,u)}else{let c=l===void 0?void 0:Math.min(l,t.cssRules.length);t==null||t.insertRule(a,c)}}catch(c){}}),(s=e.removes)==null||s.forEach(({index:a})=>{try{if(Array.isArray(a)){let{positions:l,index:c}=gs(a);je(t.cssRules,l).deleteRule(c||0)}else t==null||t.deleteRule(a)}catch(l){}}),e.replace)try{(n=t.replace)==null||n.call(t,e.replace)}catch(a){}if(e.replaceSync)try{(o=t.replaceSync)==null||o.call(t,e.replaceSync)}catch(a){}}applyStyleDeclaration(e,t){e.set&&je(t.rules,e.index).style.setProperty(e.set.property,e.set.value,e.set.priority),e.remove&&je(t.rules,e.index).style.removeProperty(e.remove.property)}applyAdoptedStyleSheet(e){var t;let r=this.mirror.getNode(e.id);if(!r)return;(t=e.styles)==null||t.forEach(a=>{var l;let c=null,u=null;if(xe(r)?u=((l=r.ownerDocument)==null?void 0:l.defaultView)||null:r.nodeName==="#document"&&(u=r.defaultView),!!u)try{c=new u.CSSStyleSheet,this.styleMirror.add(c,a.styleId),this.applyStyleSheetRule({source:E.StyleSheetRule,adds:a.rules},c)}catch(h){}});let s=10,n=0,o=(a,l)=>{let c=l.map(u=>this.styleMirror.getStyle(u)).filter(u=>u!==null);xe(a)?a.shadowRoot.adoptedStyleSheets=c:a.nodeName==="#document"&&(a.adoptedStyleSheets=c),c.length!==l.length&&n<s&&(setTimeout(()=>o(a,l),0+100*n),n++)};o(r,e.styleIds)}legacy_resolveMissingNode(e,t,r,s){let{previousId:n,nextId:o}=s,a=n&&e[n],l=o&&e[o];if(a){let{node:c,mutation:u}=a;t.insertBefore(c,r),delete e[u.node.id],delete this.legacy_missingNodeRetryMap[u.node.id],(u.previousId||u.nextId)&&this.legacy_resolveMissingNode(e,t,c,u)}if(l){let{node:c,mutation:u}=l;t.insertBefore(c,r.nextSibling),delete e[u.node.id],delete this.legacy_missingNodeRetryMap[u.node.id],(u.previousId||u.nextId)&&this.legacy_resolveMissingNode(e,t,c,u)}}moveAndHover(e,t,r,s,n){let o=this.mirror.getNode(r);if(!o)return this.debugNodeNotFound(n,r);let a=dn(o,this.iframe),l=e*a.absoluteScale+a.x,c=t*a.absoluteScale+a.y;this.mouse.style.left=`${l}px`,this.mouse.style.top=`${c}px`,s||this.drawMouseTail({x:l,y:c}),this.hoverElements(o)}drawMouseTail(e){if(!this.mouseTail)return;let{lineCap:t,lineWidth:r,strokeStyle:s,duration:n}=this.config.mouseTail===!0?Ti:Object.assign({},Ti,this.config.mouseTail),o=()=>{if(!this.mouseTail)return;let a=this.mouseTail.getContext("2d");!a||!this.tailPositions.length||(a.clearRect(0,0,this.mouseTail.width,this.mouseTail.height),a.beginPath(),a.lineWidth=r,a.lineCap=t,a.strokeStyle=s,a.moveTo(this.tailPositions[0].x,this.tailPositions[0].y),this.tailPositions.forEach(l=>a.lineTo(l.x,l.y)),a.stroke())};this.tailPositions.push(e),o(),setTimeout(()=>{this.tailPositions=this.tailPositions.filter(a=>a!==e),o()},n/this.speedService.state.context.timer.speed)}hoverElements(e){var t;(t=this.lastHoveredRootNode||this.iframe.contentDocument)==null||t.querySelectorAll(".\\:hover").forEach(s=>{s.classList.remove(":hover")}),this.lastHoveredRootNode=e.getRootNode();let r=e;for(;r;)r.classList&&r.classList.add(":hover"),r=r.parentElement}isUserInteraction(e){return e.type!==x.IncrementalSnapshot?!1:e.data.source>E.Mutation&&e.data.source<=E.Input}backToNormal(){this.nextUserInteractionEvent=null,!this.speedService.state.matches("normal")&&(this.speedService.send({type:"BACK_TO_NORMAL"}),this.emitter.emit(O.SkipEnd,{speed:this.speedService.state.context.normalSpeed}))}warnNodeNotFound(e,t){this.warn(`Node with id '${t}' not found. `,e)}warnCanvasMutationFailed(e,t){this.warn("Has error on canvas update",t,"canvas mutation:",e)}debugNodeNotFound(e,t){this.debug(`Node with id '${t}' not found. `,e)}warn(...e){this.config.showWarning&&this.config.logger.warn($o,...e)}debug(...e){this.config.showDebug&&this.config.logger.log($o,...e)}},{addCustomEvent:sm}=Re,{freezePage:nm}=Re,{takeFullSnapshot:om}=Re});var mm={};En(mm,{default:()=>pm});function oi(){let i=Date.now().toString(36),e=Math.random().toString(36).substring(2,15);return`rec_${i}_${e}`}function ai(){return typeof window=="undefined"?{userAgent:"unknown",screenWidth:0,screenHeight:0,viewportWidth:0,viewportHeight:0,devicePixelRatio:1,language:"en",platform:"unknown"}:{userAgent:navigator.userAgent,screenWidth:screen.width,screenHeight:screen.height,viewportWidth:window.innerWidth,viewportHeight:window.innerHeight,devicePixelRatio:window.devicePixelRatio||1,language:navigator.language,platform:navigator.platform}}var Ql={maskAllInputs:!0,maskAllText:!1,maskSelectors:[".sensitive","[data-sensitive]",".pii","[data-pii]"],blockSelectors:[".no-record","[data-no-record]"],maskInputTypes:["password","email","tel","credit-card"],maskCharacter:"*"},ec={batchEvents:!0,batchSize:50,batchTimeout:5e3,compress:!0,mouseMoveThrottle:50,maxDuration:1800*1e3},tc={console:!0,network:!1,performance:!1,errors:!0,customEvents:!0};function li(i){var e,t,r,s,n,o;return{enabled:(e=i==null?void 0:i.enabled)!=null?e:!0,samplingRate:(t=i==null?void 0:i.samplingRate)!=null?t:1,privacy:{...Ql,...i==null?void 0:i.privacy},performance:{...ec,...i==null?void 0:i.performance},capture:{...tc,...i==null?void 0:i.capture},endpoint:(r=i==null?void 0:i.endpoint)!=null?r:"",onStart:(s=i==null?void 0:i.onStart)!=null?s:(()=>{}),onStop:(n=i==null?void 0:i.onStop)!=null?n:(()=>{}),onError:(o=i==null?void 0:i.onError)!=null?o:(()=>{})}}function ci(i){return i>=1?!0:i<=0?!1:Math.random()<i}function ui(i){try{let e=JSON.stringify(i);return typeof btoa!="undefined"?btoa(encodeURIComponent(e)):e}catch(e){return console.warn("[Recording] Failed to compress events:",e),JSON.stringify(i)}}function Ht(){return typeof window!="undefined"&&typeof document!="undefined"}function In(){return Ht()?window.location.href:""}var at=class{constructor(e){this.state="idle";this.sessionId=null;this.sdkSessionToken=null;this.apiUrl="";this.sdkKey=null;this.stopRecording=null;this.events=[];this.eventCount=0;this.batchIndex=0;this.batchesSent=0;this.errorCount=0;this.startTime=null;this.batchTimeout=null;this.maxDurationTimeout=null;this.consoleCleanup=null;this.errorCleanup=null;this.config=li(e)}initialize(e,t,r){this.sdkSessionToken=e,this.apiUrl=t,this.sdkKey=r||null}updateConfig(e){this.config=li({...this.config,...e})}async start(){var e,t,r,s;if(!Ht())return console.warn("[Recording] Cannot record outside browser environment"),null;if(!this.config.enabled)return null;if(this.state==="recording")return console.warn("[Recording] Already recording"),this.sessionId;if(!ci(this.config.samplingRate))return console.log("[Recording] Session not sampled for recording"),null;try{let n=await Promise.resolve().then(()=>(Ll(),$l));this.sessionId=oi(),this.events=[],this.eventCount=0,this.batchIndex=0,this.batchesSent=0,this.errorCount=0,this.startTime=new Date,this.state="recording";let o={emit:a=>this.handleEvent(a),maskAllInputs:this.config.privacy.maskAllInputs,maskTextSelector:((e=this.config.privacy.maskSelectors)==null?void 0:e.join(","))||void 0,blockSelector:((t=this.config.privacy.blockSelectors)==null?void 0:t.join(","))||void 0,maskInputOptions:{password:!0,email:(r=this.config.privacy.maskInputTypes)==null?void 0:r.includes("email"),tel:(s=this.config.privacy.maskInputTypes)==null?void 0:s.includes("tel")},sampling:{mousemove:!0,mouseInteraction:!0,scroll:150,media:800,input:"last"}};return this.stopRecording=n.record(o),this.config.capture.console&&this.setupConsoleCapture(),this.config.capture.errors&&this.setupErrorCapture(),this.config.performance.maxDuration&&(this.maxDurationTimeout=setTimeout(()=>{console.log("[Recording] Max duration reached, stopping"),this.stop()},this.config.performance.maxDuration)),await this.sendSessionStart(),this.config.onStart(this.sessionId),console.log("[Recording] Started session:",this.sessionId),this.sessionId}catch(n){return console.error("[Recording] Failed to start:",n),this.state="idle",this.config.onError(n instanceof Error?n:new Error(String(n))),null}}async stop(){if(!(this.state!=="recording"&&this.state!=="paused"))try{this.stopRecording&&(this.stopRecording(),this.stopRecording=null),this.consoleCleanup&&(this.consoleCleanup(),this.consoleCleanup=null),this.errorCleanup&&(this.errorCleanup(),this.errorCleanup=null),this.batchTimeout&&(clearTimeout(this.batchTimeout),this.batchTimeout=null),this.maxDurationTimeout&&(clearTimeout(this.maxDurationTimeout),this.maxDurationTimeout=null),this.events.length>0&&await this.sendBatch(!0),await this.sendSessionEnd();let e=this.sessionId,t=this.eventCount;this.state="stopped",this.config.onStop(e||"",t),console.log("[Recording] Stopped session:",e,"Events:",t)}catch(e){console.error("[Recording] Error stopping:",e),this.config.onError(e instanceof Error?e:new Error(String(e)))}}pause(){this.state==="recording"&&(this.state="paused",console.log("[Recording] Paused"))}resume(){this.state==="paused"&&(this.state="recording",console.log("[Recording] Resumed"))}addCustomEvent(e){if(this.state!=="recording"||!this.config.capture.customEvents)return;let t={type:5,data:{tag:"custom",payload:e},timestamp:e.timestamp||Date.now()};this.handleEvent(t)}getStats(){let e=this.startTime?Date.now()-this.startTime.getTime():0;return{state:this.state,sessionId:this.sessionId,eventCount:this.eventCount,startTime:this.startTime,duration:e,batchesSent:this.batchesSent,errors:this.errorCount}}isRecording(){return this.state==="recording"}getSessionId(){return this.sessionId}handleEvent(e){this.state==="recording"&&(this.events.push(e),this.eventCount++,this.config.performance.batchEvents?this.events.length>=this.config.performance.batchSize?this.sendBatch():this.batchTimeout||(this.batchTimeout=setTimeout(()=>{this.batchTimeout=null,this.events.length>0&&this.sendBatch()},this.config.performance.batchTimeout)):this.sendBatch())}async sendBatch(e=!1){if(this.events.length===0)return;let t=[...this.events];this.events=[];let r={sessionId:this.sessionId,sdkSessionToken:this.sdkSessionToken,events:t,timestamp:new Date().toISOString(),batchIndex:this.batchIndex++,isFinal:e};try{let s=this.config.endpoint||`${this.apiUrl}/session-recordings/events`,n={"Content-Type":"application/json"};this.sdkKey&&(n["X-SDK-Key"]=this.sdkKey);let o=this.config.performance.compress?JSON.stringify({...r,events:void 0,compressedEvents:ui(t)}):JSON.stringify(r);await fetch(s,{method:"POST",headers:n,body:o}),this.batchesSent++}catch(s){console.error("[Recording] Failed to send batch:",s),this.errorCount++,this.events=[...t,...this.events]}}async sendSessionStart(){let e={id:this.sessionId,sdkSessionToken:this.sdkSessionToken,startUrl:In(),startTime:this.startTime,deviceInfo:ai()};try{let t=`${this.apiUrl}/session-recordings/start`,r={"Content-Type":"application/json"};this.sdkKey&&(r["X-SDK-Key"]=this.sdkKey),await fetch(t,{method:"POST",headers:r,body:JSON.stringify(e)})}catch(t){console.error("[Recording] Failed to send session start:",t)}}async sendSessionEnd(){try{let e=`${this.apiUrl}/session-recordings/end`,t={"Content-Type":"application/json"};this.sdkKey&&(t["X-SDK-Key"]=this.sdkKey),await fetch(e,{method:"POST",headers:t,body:JSON.stringify({sessionId:this.sessionId,endTime:new Date().toISOString(),eventCount:this.eventCount})})}catch(e){console.error("[Recording] Failed to send session end:",e)}}setupConsoleCapture(){let e={log:console.log,info:console.info,warn:console.warn,error:console.error,debug:console.debug},t=r=>(...s)=>{var o;if(e[r](...s),(o=s[0])!=null&&o.toString().includes("[Recording]"))return;let n={level:r,message:s.map(a=>typeof a=="object"?JSON.stringify(a):String(a)).join(" "),timestamp:Date.now()};this.addCustomEvent({type:"console",data:n})};console.log=t("log"),console.info=t("info"),console.warn=t("warn"),console.error=t("error"),console.debug=t("debug"),this.consoleCleanup=()=>{console.log=e.log,console.info=e.info,console.warn=e.warn,console.error=e.error,console.debug=e.debug}}setupErrorCapture(){let e=r=>{let s={type:"error",message:r.message,filename:r.filename,lineno:r.lineno,colno:r.colno,timestamp:Date.now()};this.addCustomEvent({type:"error",data:s})},t=r=>{var n,o;let s={type:"unhandledrejection",message:((n=r.reason)==null?void 0:n.message)||String(r.reason),stack:(o=r.reason)==null?void 0:o.stack,timestamp:Date.now()};this.addCustomEvent({type:"error",data:s})};window.addEventListener("error",e),window.addEventListener("unhandledrejection",t),this.errorCleanup=()=>{window.removeEventListener("error",e),window.removeEventListener("unhandledrejection",t)}}destroy(){this.stop(),this.sessionId=null,this.sdkSessionToken=null,this.events=[]}};var Qr=class{constructor(e,t){this.isTracking=!1;this.scrollDepth=0;this.pageLoadTime=0;this.clickCount=0;this.lastActivityTime=0;this.currentUrl="";this.previousUrl="";this.triggeredSet=new Set;this.lastTriggerTime=0;this.proactiveMessageCount=0;this.scrollHandler=null;this.clickHandler=null;this.mouseMoveHandler=null;this.mouseLeaveHandler=null;this.visibilityHandler=null;this.timeCheckInterval=null;this.idleCheckInterval=null;this.config=e,this.callbacks=t}start(){!this.config.enabled||this.isTracking||typeof window!="undefined"&&(this.config.respectUserPreference&&localStorage.getItem("produck_proactive_optout")==="true"||(this.isTracking=!0,this.pageLoadTime=Date.now(),this.lastActivityTime=Date.now(),this.currentUrl=window.location.href,this.setupScrollTracking(),this.setupClickTracking(),this.setupIdleTracking(),this.setupExitIntentTracking(),this.setupTimeTracking(),this.setupPageChangeTracking(),console.log("[Produck] Proactive behavior tracking started")))}stop(){this.isTracking&&(this.isTracking=!1,this.scrollHandler&&window.removeEventListener("scroll",this.scrollHandler),this.clickHandler&&document.removeEventListener("click",this.clickHandler),this.mouseMoveHandler&&document.removeEventListener("mousemove",this.mouseMoveHandler),this.mouseLeaveHandler&&document.removeEventListener("mouseleave",this.mouseLeaveHandler),this.visibilityHandler&&document.removeEventListener("visibilitychange",this.visibilityHandler),this.timeCheckInterval&&clearInterval(this.timeCheckInterval),this.idleCheckInterval&&clearInterval(this.idleCheckInterval),console.log("[Produck] Proactive behavior tracking stopped"))}reset(){this.scrollDepth=0,this.clickCount=0,this.pageLoadTime=Date.now(),this.lastActivityTime=Date.now()}getStats(){return{scrollDepth:this.scrollDepth,timeOnPage:Date.now()-this.pageLoadTime,clickCount:this.clickCount,idleTime:Date.now()-this.lastActivityTime,proactiveMessageCount:this.proactiveMessageCount}}shouldTrigger(e){if(this.config.maxProactiveMessages&&this.proactiveMessageCount>=this.config.maxProactiveMessages||this.config.globalCooldown&&Date.now()-this.lastTriggerTime<this.config.globalCooldown)return!1;let t=`${e.type}-${e.threshold||"default"}`;if(e.onlyOnce&&this.triggeredSet.has(t))return!1;let r=`${t}-lastTime`,s=parseInt(sessionStorage.getItem(r)||"0",10);return!(e.cooldown&&Date.now()-s<e.cooldown)}fireTrigger(e,t){if(!this.shouldTrigger(e))return;let r=`${e.type}-${e.threshold||"default"}`,s=`${r}-lastTime`;this.triggeredSet.add(r),this.lastTriggerTime=Date.now(),this.proactiveMessageCount++,sessionStorage.setItem(s,Date.now().toString());let n=e.message||this.getDefaultMessage(e.type,t);this.callbacks.onTrigger(t,n),this.callbacks.onMessage&&this.callbacks.onMessage(n),console.log("[Produck] Proactive trigger fired:",e.type,t)}getDefaultMessage(e,t){switch(e){case"scroll":return"I see you're exploring the page! Is there something specific you're looking for?";case"time":return"You've been here a while. Would you like some help finding what you need?";case"clicks":return"Looks like you're navigating around. Can I help you find something?";case"idle":return"Still there? Let me know if you have any questions!";case"exit":return"Wait! Before you go, is there anything I can help you with?";case"pageChange":return"I see you're exploring different pages. Need any guidance?";default:return"How can I help you today?"}}setupScrollTracking(){let e=this.config.triggers.filter(t=>t.type==="scroll"&&t.enabled);e.length!==0&&(this.scrollHandler=()=>{let t=document.documentElement.scrollHeight-window.innerHeight,r=t>0?window.scrollY/t*100:0;this.scrollDepth=Math.max(this.scrollDepth,r),this.lastActivityTime=Date.now(),e.forEach(s=>{s.threshold&&this.scrollDepth>=s.threshold&&this.fireTrigger(s,{triggerType:"scroll",scrollDepth:this.scrollDepth,currentUrl:window.location.href,pageTitle:document.title})})},window.addEventListener("scroll",this.scrollHandler,{passive:!0}))}setupClickTracking(){let e=this.config.triggers.filter(t=>t.type==="clicks"&&t.enabled);e.length!==0&&(this.clickHandler=()=>{this.clickCount++,this.lastActivityTime=Date.now(),e.forEach(t=>{t.threshold&&this.clickCount>=t.threshold&&this.fireTrigger(t,{triggerType:"clicks",clickCount:this.clickCount,currentUrl:window.location.href,pageTitle:document.title})})},document.addEventListener("click",this.clickHandler))}setupIdleTracking(){let e=this.config.triggers.filter(t=>t.type==="idle"&&t.enabled);e.length!==0&&(this.mouseMoveHandler=()=>{this.lastActivityTime=Date.now()},document.addEventListener("mousemove",this.mouseMoveHandler,{passive:!0}),this.idleCheckInterval=setInterval(()=>{let t=Date.now()-this.lastActivityTime;e.forEach(r=>{r.threshold&&t>=r.threshold&&this.fireTrigger(r,{triggerType:"idle",idleTime:t,currentUrl:window.location.href,pageTitle:document.title})})},1e3))}setupExitIntentTracking(){let e=this.config.triggers.filter(t=>t.type==="exit"&&t.enabled);e.length!==0&&(this.mouseLeaveHandler=t=>{t.clientY<=0&&e.forEach(r=>{this.fireTrigger(r,{triggerType:"exit",currentUrl:window.location.href,pageTitle:document.title})})},document.addEventListener("mouseleave",this.mouseLeaveHandler))}setupTimeTracking(){let e=this.config.triggers.filter(t=>t.type==="time"&&t.enabled);e.length!==0&&(this.timeCheckInterval=setInterval(()=>{let t=Date.now()-this.pageLoadTime;e.forEach(r=>{r.threshold&&t>=r.threshold&&this.fireTrigger(r,{triggerType:"time",timeOnPage:t,currentUrl:window.location.href,pageTitle:document.title})})},1e3))}setupPageChangeTracking(){let e=this.config.triggers.filter(t=>t.type==="pageChange"&&t.enabled);e.length!==0&&(this.visibilityHandler=()=>{if(document.visibilityState==="visible"){let t=window.location.href;t!==this.currentUrl&&(this.previousUrl=this.currentUrl,this.currentUrl=t,this.scrollDepth=0,this.clickCount=0,this.pageLoadTime=Date.now(),e.forEach(r=>{this.fireTrigger(r,{triggerType:"pageChange",currentUrl:this.currentUrl,previousUrl:this.previousUrl,pageTitle:document.title})}))}},document.addEventListener("visibilitychange",this.visibilityHandler),window.addEventListener("popstate",()=>{let t=window.location.href;t!==this.currentUrl&&(this.previousUrl=this.currentUrl,this.currentUrl=t,e.forEach(r=>{this.fireTrigger(r,{triggerType:"pageChange",currentUrl:this.currentUrl,previousUrl:this.previousUrl,pageTitle:document.title})}))}))}triggerManual(e,t){this.proactiveMessageCount++,this.lastTriggerTime=Date.now();let r={triggerType:"time",currentUrl:window.location.href,pageTitle:document.title,...t};this.callbacks.onTrigger(r,e),this.callbacks.onMessage&&this.callbacks.onMessage(e)}optOut(){typeof localStorage!="undefined"&&localStorage.setItem("produck_proactive_optout","true"),this.stop()}optIn(){typeof localStorage!="undefined"&&localStorage.removeItem("produck_proactive_optout"),this.start()}};function Se(){return typeof window!="undefined"&&typeof document!="undefined"}function mn(){return"ufs_"+Date.now().toString(36)+"_"+Math.random().toString(36).substring(2,11)}function Ne(){return Se()?window.location.href:""}function Ue(){return Se()?window.location.pathname:""}function Be(){return Se()&&document.title||""}function gn(i=1){return Math.random()<i}function yn(){if(!Se())return{deviceType:"desktop",browser:"unknown",os:"unknown",viewportWidth:0,viewportHeight:0,userAgent:""};let i=navigator.userAgent,e="desktop";/Mobi|Android/i.test(i)&&(e=/Tablet|iPad/i.test(i)?"tablet":"mobile");let t="unknown";i.includes("Firefox")?t="Firefox":i.includes("Edg")?t="Edge":i.includes("Chrome")?t="Chrome":i.includes("Safari")?t="Safari":(i.includes("Opera")||i.includes("OPR"))&&(t="Opera");let r="unknown";return i.includes("Windows")?r="Windows":i.includes("Mac OS")?r="macOS":i.includes("Linux")?r="Linux":i.includes("Android")?r="Android":(i.includes("iOS")||i.includes("iPhone")||i.includes("iPad"))&&(r="iOS"),{deviceType:e,browser:t,os:r,viewportWidth:window.innerWidth,viewportHeight:window.innerHeight,userAgent:i}}function _l(i,e=5){let t=[],r=i,s=0;for(;r&&r!==document.body&&s<e;){let n=r.tagName.toLowerCase();if(r.id){n+=`#${r.id}`,t.unshift(n);break}if(r.className&&typeof r.className=="string"){let a=r.className.trim().split(/\s+/);a.length>0&&a[0]&&(n+=`.${a[0]}`)}let o=r.parentElement;if(o){let a=Array.from(o.children).filter(l=>l.tagName===r.tagName);if(a.length>1){let l=a.indexOf(r)+1;n+=`:nth-child(${l})`}}t.unshift(n),r=r.parentElement,s++}return t.join(" > ")}function Fl(i){if(!i)return"";if(i.id)return`//*[@id="${i.id}"]`;let e=[],t=i;for(;t&&t.nodeType===Node.ELEMENT_NODE;){let r=0,s=t.previousElementSibling;for(;s;)s.tagName===t.tagName&&r++,s=s.previousElementSibling;let n=t.tagName.toLowerCase(),o=r>0?`${n}[${r+1}]`:n;e.unshift(o),t=t.parentElement}return"/"+e.join("/")}function ei(i,e={}){let t=(e==null?void 0:e.maxTextLength)||100,r=(e==null?void 0:e.maxHtmlLength)||500,s=(e==null?void 0:e.selectorDepth)||5,n="";i instanceof HTMLElement&&(n=i.innerText||i.textContent||"",n=n.trim().substring(0,t),n.length===t&&(n+="..."));let o;(e==null?void 0:e.captureHtml)!==!1&&(o=i.outerHTML.substring(0,r),o.length===r&&(o+="..."));let a=i.getBoundingClientRect(),l={tag:i.tagName.toLowerCase(),selector:_l(i,s)};return i.id&&(l.id=i.id),i.className&&typeof i.className=="string"&&(l.className=i.className),n&&(l.text=n),i instanceof HTMLAnchorElement&&i.href&&(l.href=i.href),l.xpath=Fl(i),l.rect={x:Math.round(a.x),y:Math.round(a.y),width:Math.round(a.width),height:Math.round(a.height)},o&&(l.html=o),l}function Ft(i,e){return!e||e.length===0?!1:e.some(t=>{try{return i.matches(t)||i.closest(t)!==null}catch(r){return!1}})}function Ul(i){try{if(typeof window=="undefined")return;let e=i,t=window.getComputedStyle(e);return{backgroundColor:t.backgroundColor,color:t.color,fontSize:t.fontSize,fontWeight:t.fontWeight,borderRadius:t.borderRadius,border:t.border,boxShadow:t.boxShadow,padding:t.padding}}catch(e){return}}async function Bl(i,e=200){try{if(typeof window=="undefined")return;let t=window.html2canvas;if(!t)try{return(await(await import("html2canvas")).default(i,{scale:.5,width:e,height:e,useCORS:!0,logging:!1})).toDataURL("image/jpeg",.7)}catch(s){console.debug("[UserFlow] html2canvas not available for screenshots");return}return(await t(i,{scale:.5,width:e,height:e,useCORS:!0,logging:!1})).toDataURL("image/jpeg",.7)}catch(t){console.debug("[UserFlow] Failed to capture screenshot:",t);return}}function wn(i){var t,r,s,n,o,a;let e={enabled:!0,samplingRate:1,events:{clicks:!0,navigation:!0,formSubmit:!0,inputs:!1,scroll:!1,ignoreSelectors:[],trackOnlySelectors:[]},element:{captureVisualStyles:!0,captureScreenshot:!1,screenshotMaxSize:200,captureHtml:!0,maxHtmlLength:500,maxTextLength:100,selectorDepth:5},performance:{batchEvents:!0,batchSize:10,batchTimeout:5e3,clickDebounce:500},session:{endOnHidden:!0,inactivityTimeout:3e5,endOnExternalNavigation:!0,autoRestart:!0},endpoint:"",onStart:()=>{},onStop:()=>{},onError:()=>{}};return i?{enabled:(t=i.enabled)!=null?t:e.enabled,samplingRate:(r=i.samplingRate)!=null?r:e.samplingRate,events:{...e.events,...i.events},element:{...e.element,...i.element},performance:{...e.performance,...i.performance},session:{...e.session,...i.session},endpoint:(s=i.endpoint)!=null?s:e.endpoint,onStart:(n=i.onStart)!=null?n:e.onStart,onStop:(o=i.onStop)!=null?o:e.onStop,onError:(a=i.onError)!=null?a:e.onError}:e}var lt=class{constructor(e){this.state="idle";this.sessionId=null;this.sdkSessionToken=null;this.apiUrl="";this.sdkKey=null;this.user=null;this.events=[];this.eventCount=0;this.batchIndex=0;this.batchesSent=0;this.pageCount=0;this.startTime=null;this.batchTimeout=null;this.inactivityTimeout=null;this.lastActivityTime=Date.now();this.lastClickTime=0;this.lastClickElement=null;this.currentPath="";this.visitedPaths=new Set;this.clickHandler=null;this.navigationHandler=null;this.formSubmitHandler=null;this.beforeUnloadHandler=null;this.visibilityHandler=null;this.linkedRecordingSessionId=null;this.config=wn(e)}initialize(e,t,r){this.sdkSessionToken=e,this.apiUrl=t,this.sdkKey=r||null}updateConfig(e){this.config=wn({...this.config,...e})}identify(e){this.user=e,this.state==="tracking"&&this.sessionId&&this.sendIdentificationUpdate().catch(t=>{console.error("[UserFlow] Failed to send identification update:",t)})}async start(e){if(!Se())return console.warn("[UserFlow] Cannot track outside browser environment"),null;if(console.log("[UserFlow] start() called",{enabled:this.config.enabled,samplingRate:this.config.samplingRate,currentState:this.state,apiUrl:this.apiUrl,hasSessionToken:!!this.sessionToken}),!this.config.enabled)return console.warn("[UserFlow] Tracking disabled by config"),null;if(this.state==="tracking")return console.warn("[UserFlow] Already tracking"),this.sessionId;if(!gn(this.config.samplingRate))return console.log("[UserFlow] Session not sampled for tracking"),null;try{return this.sessionId=mn(),this.linkedRecordingSessionId=e||null,this.events=[],this.eventCount=0,this.batchIndex=0,this.batchesSent=0,this.pageCount=1,this.startTime=new Date,this.currentPath=Ue(),this.visitedPaths=new Set([this.currentPath]),this.state="tracking",this.setupEventListeners(),await this.sendSessionStart(),this.addEvent({eventType:"navigation",eventOrder:0,timestamp:new Date().toISOString(),pageUrl:Ne(),pageTitle:Be(),pagePath:this.currentPath}),this.config.onStart(this.sessionId),console.log("[UserFlow] Started tracking session:",this.sessionId),this.sessionId}catch(t){return console.error("[UserFlow] Failed to start tracking:",t),this.state="idle",this.config.onError(t instanceof Error?t:new Error(String(t))),null}}async stop(){if(!(this.state!=="tracking"&&this.state!=="paused"))try{this.removeEventListeners(),this.batchTimeout&&(clearTimeout(this.batchTimeout),this.batchTimeout=null),this.inactivityTimeout&&(clearTimeout(this.inactivityTimeout),this.inactivityTimeout=null),this.events.length>0&&await this.sendEventBatch(!0),await this.sendSessionEnd(),this.state="stopped";let e=this.eventCount,t=this.sessionId;this.sessionId=null,this.events=[],this.eventCount=0,this.startTime=null,this.config.onStop(t,e),console.log("[UserFlow] Stopped tracking session:",t)}catch(e){console.error("[UserFlow] Error stopping tracking:",e),this.state="stopped",this.config.onError(e instanceof Error?e:new Error(String(e)))}}pause(){this.state==="tracking"&&(this.state="paused",console.log("[UserFlow] Tracking paused"))}resume(){this.state==="paused"&&(this.state="tracking",console.log("[UserFlow] Tracking resumed"))}getStats(){return{sessionId:this.sessionId,state:this.state,eventCount:this.eventCount,pageCount:this.pageCount,batchesSent:this.batchesSent,duration:this.startTime?Date.now()-this.startTime.getTime():0,startTime:this.startTime}}getState(){return this.state}isTracking(){return this.state==="tracking"}addCustomEvent(e){this.state==="tracking"&&this.addEvent({eventType:"custom",eventOrder:this.eventCount,timestamp:new Date().toISOString(),pageUrl:Ne(),pageTitle:Be(),pagePath:Ue(),metadata:e})}setupEventListeners(){if(Se()){if(this.config.events.clicks&&(this.clickHandler=e=>this.handleClick(e),document.addEventListener("click",this.clickHandler,{capture:!0,passive:!0})),this.config.events.navigation){this.navigationHandler=()=>this.handleNavigation(),window.addEventListener("popstate",this.navigationHandler);let e=history.pushState,t=history.replaceState;history.pushState=(...r)=>{e.apply(history,r),this.handleNavigation()},history.replaceState=(...r)=>{t.apply(history,r),this.handleNavigation()}}this.config.events.formSubmit&&(this.formSubmitHandler=e=>this.handleFormSubmit(e),document.addEventListener("submit",this.formSubmitHandler,{capture:!0})),this.beforeUnloadHandler=()=>{this.events.length>0&&this.sendEventBatchSync(!0),this.sendSessionEndSync()},window.addEventListener("beforeunload",this.beforeUnloadHandler),this.visibilityHandler=()=>{document.visibilityState==="hidden"?(this.events.length>0&&this.sendEventBatch(!0).catch(console.error),this.config.session.endOnHidden&&this.stop().catch(console.error)):document.visibilityState==="visible"&&this.config.session.autoRestart&&this.state==="stopped"&&this.start().catch(console.error)},document.addEventListener("visibilitychange",this.visibilityHandler),this.resetInactivityTimeout()}}removeEventListeners(){Se()&&(this.clickHandler&&(document.removeEventListener("click",this.clickHandler,{capture:!0}),this.clickHandler=null),this.navigationHandler&&(window.removeEventListener("popstate",this.navigationHandler),this.navigationHandler=null),this.formSubmitHandler&&(document.removeEventListener("submit",this.formSubmitHandler,{capture:!0}),this.formSubmitHandler=null),this.beforeUnloadHandler&&(window.removeEventListener("beforeunload",this.beforeUnloadHandler),this.beforeUnloadHandler=null),this.visibilityHandler&&(document.removeEventListener("visibilitychange",this.visibilityHandler),this.visibilityHandler=null))}async handleClick(e){if(this.state!=="tracking")return;let t=e.target;if(!t||!(t instanceof Element)||this.config.events.ignoreSelectors&&this.config.events.ignoreSelectors.length>0&&Ft(t,this.config.events.ignoreSelectors)||this.config.events.trackOnlySelectors&&this.config.events.trackOnlySelectors.length>0&&!Ft(t,this.config.events.trackOnlySelectors))return;let r=Date.now();if(this.lastClickElement===t&&r-this.lastClickTime<this.config.performance.clickDebounce)return;this.lastClickTime=r,this.lastClickElement=t;let s=ei(t,this.config.element);if(this.config.element.captureVisualStyles&&(s.visualStyles=Ul(t)),this.config.element.captureScreenshot)try{s.screenshot=await Bl(t,this.config.element.screenshotMaxSize)}catch(o){}let n={eventType:"click",eventOrder:this.eventCount,timestamp:new Date().toISOString(),pageUrl:Ne(),pageTitle:Be(),pagePath:Ue(),element:s,clickX:Math.round(e.pageX),clickY:Math.round(e.pageY),viewportX:Math.round(e.clientX),viewportY:Math.round(e.clientY)};this.addEvent(n)}handleNavigation(){if(this.state!=="tracking")return;let e=Ue();if(e===this.currentPath)return;this.currentPath=e,this.visitedPaths.has(e)||(this.visitedPaths.add(e),this.pageCount++);let t={eventType:"navigation",eventOrder:this.eventCount,timestamp:new Date().toISOString(),pageUrl:Ne(),pageTitle:Be(),pagePath:e};this.addEvent(t)}handleFormSubmit(e){if(this.state!=="tracking")return;let t=e.target;if(!t||!(t instanceof HTMLFormElement)||this.config.events.ignoreSelectors&&Ft(t,this.config.events.ignoreSelectors))return;let r=ei(t,this.config.element),s={eventType:"form_submit",eventOrder:this.eventCount,timestamp:new Date().toISOString(),pageUrl:Ne(),pageTitle:Be(),pagePath:Ue(),element:r,metadata:{action:t.action,method:t.method,name:t.name}};this.addEvent(s)}addEvent(e){this.events.push(e),this.eventCount++,this.resetInactivityTimeout(),this.config.performance.batchEvents&&this.events.length>=this.config.performance.batchSize?this.sendEventBatch(!1).catch(console.error):this.batchTimeout||(this.batchTimeout=setTimeout(()=>{this.batchTimeout=null,this.events.length>0&&this.sendEventBatch(!1).catch(console.error)},this.config.performance.batchTimeout))}async sendSessionStart(){var s;let e=this.config.endpoint||`${this.apiUrl}/user-flows/session/start`,t=yn(),r={sessionId:this.sessionId,sdkSessionToken:this.sdkSessionToken,startUrl:Ne(),startTime:(s=this.startTime)==null?void 0:s.toISOString(),user:this.user,device:t,linkedRecordingSessionId:this.linkedRecordingSessionId};try{let n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json",...this.sdkKey?{"X-SDK-Key":this.sdkKey}:{}},body:JSON.stringify(r)});if(!n.ok)throw console.error("[UserFlow] Failed to start session:",n.status,n.statusText),console.error("[UserFlow] Endpoint:",e),new Error(`Failed to start session: ${n.status}`);console.log("[UserFlow] Session started successfully:",this.sessionId)}catch(n){throw console.error("[UserFlow] Network error starting session:",n),console.error("[UserFlow] Attempted endpoint:",e),n}}async sendEventBatch(e){if(this.events.length===0)return;let t=[...this.events];this.events=[];let r=this.config.endpoint?`${this.config.endpoint}/events`:`${this.apiUrl}/user-flows/session/events`,s={sessionId:this.sessionId,events:t,batchIndex:this.batchIndex++,timestamp:new Date().toISOString(),isFinal:e};try{let n=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",...this.sdkKey?{"X-SDK-Key":this.sdkKey}:{}},body:JSON.stringify(s)});n.ok?(this.batchesSent++,console.log(`[UserFlow] Event batch ${this.batchIndex-1} sent (${t.length} events)`)):(console.error("[UserFlow] Failed to send event batch:",n.status,n.statusText),console.error("[UserFlow] Endpoint:",r),this.events=[...t,...this.events])}catch(n){console.error("[UserFlow] Network error sending event batch:",n),console.error("[UserFlow] Endpoint:",r),this.events=[...t,...this.events]}}sendEventBatchSync(e){if(this.events.length===0)return;let t=this.config.endpoint?`${this.config.endpoint}/events`:`${this.apiUrl}/user-flows/session/events`,r={sessionId:this.sessionId,events:this.events,batchIndex:this.batchIndex++,timestamp:new Date().toISOString(),isFinal:e};if(navigator.sendBeacon){let s=new Blob([JSON.stringify(r)],{type:"application/json"});navigator.sendBeacon(t,s),this.events=[]}}async sendSessionEnd(){let e=this.config.endpoint?`${this.config.endpoint}/end`:`${this.apiUrl}/user-flows/session/end`,t={sessionId:this.sessionId,endTime:new Date().toISOString(),eventCount:this.eventCount,status:"completed"};try{await fetch(e,{method:"POST",headers:{"Content-Type":"application/json",...this.sdkKey?{"X-SDK-Key":this.sdkKey}:{}},body:JSON.stringify(t)})}catch(r){console.error("[UserFlow] Failed to send session end:",r)}}sendSessionEndSync(){let e=this.config.endpoint?`${this.config.endpoint}/end`:`${this.apiUrl}/user-flows/session/end`,t={sessionId:this.sessionId,endTime:new Date().toISOString(),eventCount:this.eventCount,status:"completed"};if(navigator.sendBeacon){let r=new Blob([JSON.stringify(t)],{type:"application/json"});navigator.sendBeacon(e,r)}}resetInactivityTimeout(){this.inactivityTimeout&&(clearTimeout(this.inactivityTimeout),this.inactivityTimeout=null),this.lastActivityTime=Date.now();let e=this.config.session.inactivityTimeout;e&&e>0&&(this.inactivityTimeout=setTimeout(()=>{this.state==="tracking"&&(console.log("[UserFlow] Session ended due to inactivity"),this.stop().catch(console.error))},e))}async sendIdentificationUpdate(){if(!this.sessionId||!this.user)return;let e=this.config.endpoint?`${this.config.endpoint}/identify`:`${this.apiUrl}/user-flows/session/identify`,t={sessionId:this.sessionId,user:this.user};await fetch(e,{method:"PATCH",headers:{"Content-Type":"application/json",...this.sdkKey?{"X-SDK-Key":this.sdkKey}:{}},body:JSON.stringify(t)})}};var ti=class{constructor(e){this.actions=new Map;this.eventListeners=new Map;this.sessionToken=null;this.isReady=!1;this.recorder=null;this.proactiveTracker=null;this.userFlowTracker=null;let t=e.apiUrl,r=!1;t||(r=!0,typeof window!="undefined"?window.location.hostname==="localhost"||window.location.hostname==="127.0.0.1"?t="http://localhost:4001/api/v1":(t=`${window.location.protocol}//${window.location.host}/api/v1`,console.warn("%c\u26A0\uFE0F Produck SDK Warning: apiUrl not configured!","background: #fbbf24; color: #000; padding: 4px 8px; font-weight: bold;"),console.warn(`The SDK is auto-detecting apiUrl as: ${t}
|
|
55
55
|
This is likely WRONG for production. Your backend is probably at a different URL.
|
|
56
56
|
|
|
57
57
|
To fix this, provide apiUrl in your SDK config:
|
|
@@ -70,7 +70,7 @@ Make sure your backend is running and the URL is correct.`),await this.log("erro
|
|
|
70
70
|
3. The backend server is unreachable
|
|
71
71
|
|
|
72
72
|
Current apiUrl: ${this.config.apiUrl}
|
|
73
|
-
Check the Network tab in DevTools for more details.`),await this.log("error","SDK initialization failed",{error:n}),this.emit("error",s),s}}register(e,t){this.actions.set(e,t),this.log("info","Action handler registered",{actionKey:e,totalActions:this.actions.size})}unregister(e){this.actions.delete(e),this.log("info","Action handler unregistered",{actionKey:e,remainingActions:this.actions.size})}async sendMessage(e){var r,s;if(!this.isReady||!this.sessionToken)throw new Error("SDK not initialized. Call init() first.");let t=Date.now();await this.log("info","sendMessage called",{message:e});try{let n,o={"Content-Type":"application/json"};this.config.sdkKey?(n=`${this.config.apiUrl}/sdk/match-intent`,o["X-SDK-Key"]=this.config.sdkKey):n=`${this.config.apiUrl}/sdk/public/${this.config.guiderId}/match-intent`;let a=await fetch(n,{method:"POST",headers:o,body:JSON.stringify({userMessage:e})});if(await this.log("info","Match-intent response received",{status:a.status}),a.ok){let h=await a.json();if(h.matched&&h.type==="flow"&&h.flow){await this.log("info","Flow matched",{flowId:h.flow.flowId,name:h.flow.name,stepCount:(r=h.flow.steps)==null?void 0:r.length}),await this.sendLogToBackend({userMessage:e,matched:!0,actionKey:`flow:${h.flow.flowId}`,responseMessage:h.responseMessage,executionTimeMs:Date.now()-t});let d=await this.executeFlow(h.flow),p={role:"assistant",content:h.responseMessage||`I've completed the "${h.flow.name}" flow for you.`,flow:h.flow,flowResult:d};return this.emit("message",p),p}if(h.matched&&(h.type==="operation"||h.action)){let d=h.action;await this.log("info","Action matched",{actionKey:d.actionKey,actionType:d.actionType,responseMessage:d.responseMessage}),await this.sendLogToBackend({userMessage:e,matched:!0,actionKey:d.actionKey,responseMessage:d.responseMessage,executionTimeMs:Date.now()-t}),await this.executeAction(d);let p={role:"assistant",content:d.responseMessage||`I've triggered the "${d.name}" action for you.`,action:d};return this.emit("message",p),p}else await this.sendLogToBackend({userMessage:e,matched:!1,executionTimeMs:Date.now()-t})}let l=await fetch(`${this.config.apiUrl}/chat/sessions/${this.sessionToken}/message`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({message:e})});if(!l.ok)throw new Error(`Failed to send message: ${l.status}`);let c=await l.json(),u={role:"assistant",content:((s=c.message)==null?void 0:s.content)||c.response||"",visualFlows:c.flows||[],images:c.images||[]};return await this.log("info","Chat response received",{hasFlows:(c.flows||[]).length>0,hasImages:(c.images||[]).length>0}),this.emit("message",u),u}catch(n){throw await this.log("error","Error in sendMessage",{error:n instanceof Error?n.message:String(n)}),this.emit("error",n),n}}async executeFlow(e){await this.log("info","executeFlow started",{flowId:e.flowId,name:e.name,stepCount:e.steps.length}),this.emit("flowStart",e),this.config.onFlowStart&&this.config.onFlowStart(e);let t=[],r={},s=[...e.steps].sort((o,a)=>o.order-a.order);for(let o of s){await this.log("info","Executing flow step",{flowId:e.flowId,operationId:o.operationId,order:o.order});let a={operationId:o.operationId,order:o.order,success:!1};try{let l=this.actions.get(o.operationId);if(l){let c={actionKey:o.operationId,name:o.operationId,actionType:"callback",actionConfig:{flowContext:r,inputMapping:o.inputMapping}},u=await l(c);a.success=!0,a.data=u,r={...r,[`step_${o.order}`]:u,previousResult:u},await this.log("info","Flow step completed successfully",{flowId:e.flowId,operationId:o.operationId,order:o.order})}else await this.log("warn","No handler registered for flow step",{flowId:e.flowId,operationId:o.operationId}),a.success=!0,a.data={skipped:!0,reason:"No handler registered"}}catch(l){a.success=!1,a.error=l instanceof Error?l.message:String(l),await this.log("error","Flow step failed",{flowId:e.flowId,operationId:o.operationId,error:a.error})}t.push(a),this.emit("flowStepComplete",{step:a,flow:e}),this.config.onFlowStepComplete&&this.config.onFlowStepComplete(a,e)}let n={flowId:e.flowId,name:e.name,steps:t,completed:!0,totalSteps:e.steps.length,successfulSteps:t.filter(o=>o.success).length};return await this.log("info","Flow execution completed",{flowId:e.flowId,totalSteps:n.totalSteps,successfulSteps:n.successfulSteps}),this.emit("flowComplete",n),this.config.onFlowComplete&&this.config.onFlowComplete(n),n}async sendLogToBackend(e){try{let t={"Content-Type":"application/json"};this.config.sdkKey&&(t["X-SDK-Key"]=this.config.sdkKey);let r=`${this.config.apiUrl}/sdk-logs/client`;await fetch(r,{method:"POST",headers:t,body:JSON.stringify({...e,timestamp:new Date().toISOString(),sessionToken:this.sessionToken})})}catch(t){}}async log(e,t,r){try{let s={"Content-Type":"application/json"};this.config.sdkKey&&(s["X-SDK-Key"]=this.config.sdkKey);let n=`${this.config.apiUrl}/sdk-logs/client`;await fetch(n,{method:"POST",headers:s,body:JSON.stringify({level:e,message:t,data:r,timestamp:new Date().toISOString(),sessionToken:this.sessionToken})})}catch(s){}}async executeAction(e){var s,n;let t=Array.from(this.actions.keys());typeof window!="undefined"&&console.log("%c\u{1F3AF} SDK executeAction","background: #ff0; color: #000; font-size: 20px; padding: 10px;",{actionKey:e.actionKey,totalRegistered:this.actions.size,registeredKeys:t}),await this.log("info","executeAction called",{actionKey:e.actionKey,actionType:typeof e.actionKey,totalRegistered:this.actions.size,registeredKeys:t,keyComparisons:t.map(o=>({key:o,matches:o===e.actionKey,keyLength:o.length,actionKeyLength:e.actionKey.length}))});let r=this.actions.get(e.actionKey);if(typeof window!="undefined"&&console.log("%c\u{1F50D} SDK Handler Lookup","background: #0ff; color: #000; font-size: 16px; padding: 5px;",{actionKey:e.actionKey,found:!!r,hasConfigOnAction:!!this.config.onAction,registeredKeys:Array.from(this.actions.keys())}),r)try{let o=Date.now();await r(e);let a=Date.now()-o;await this.log("info","Handler executed successfully",{actionKey:e.actionKey,executionTime:a}),await this.sendLogToBackend({userMessage:`Action executed: ${e.actionKey}`,matched:!0,actionKey:e.actionKey,responseMessage:e.responseMessage||`Executed ${e.name}`,executionTimeMs:a}),this.emit("action",e),(n=(s=this.config).onAction)==null||n.call(s,e.actionKey,e)}catch(o){await this.log("error","Handler execution failed",{actionKey:e.actionKey,error:o instanceof Error?o.message:String(o),stack:o instanceof Error?o.stack:void 0}),await this.sendLogToBackend({userMessage:`Action execution failed: ${e.actionKey}`,matched:!0,actionKey:e.actionKey,error:o instanceof Error?o.message:String(o)}),this.emit("error",o)}else{if(this.config.onAction){await this.log("info","No internal handler, trying config.onAction callback",{actionKey:e.actionKey});try{this.config.onAction(e.actionKey,e),this.emit("action",e),await this.log("info","Action dispatched via config.onAction",{actionKey:e.actionKey}),await this.sendLogToBackend({userMessage:`Action dispatched: ${e.actionKey}`,matched:!0,actionKey:e.actionKey,responseMessage:e.responseMessage||`Dispatched ${e.name}`});return}catch(o){await this.log("error","config.onAction callback failed",{actionKey:e.actionKey,error:o instanceof Error?o.message:String(o)})}}await this.log("warn","No handler registered for action",{actionKey:e.actionKey,registeredActions:Array.from(this.actions.keys())}),await this.sendLogToBackend({userMessage:`No handler for action: ${e.actionKey}`,matched:!1,actionKey:e.actionKey,error:`Handler not registered. Available: ${Array.from(this.actions.keys()).join(", ")}`})}}on(e,t){this.eventListeners.has(e)||this.eventListeners.set(e,new Set),this.eventListeners.get(e).add(t)}off(e,t){var r;(r=this.eventListeners.get(e))==null||r.delete(t)}emit(e,t){var r;(r=this.eventListeners.get(e))==null||r.forEach(s=>s(t))}getSessionToken(){return this.sessionToken}getIsReady(){return this.isReady}getRegisteredActions(){return Array.from(this.actions.keys())}getGuiderId(){return this.config.guiderId}async getVisualFlow(e){let t=this.config.guiderId;if(!t)return await this.log("warn","Cannot fetch visual flow without guiderId"),null;try{let r=await fetch(`${this.config.apiUrl}/visual-flows/chat/${t}/${e}`);if(!r.ok)return await this.log("warn","Visual flow not found",{flowId:e,status:r.status}),null;let s=await r.json();return!s.found||!s.flow?null:s.flow}catch(r){return await this.log("error","Error fetching visual flow",{flowId:e,error:r}),null}}async initRecording(){try{this.recorder=new at(this.config.recording),this.recorder.initialize(this.sessionToken,this.config.apiUrl,this.config.sdkKey);let e=await this.recorder.start();e&&await this.log("info","Session recording started",{recordingSessionId:e})}catch(e){await this.log("warn","Failed to initialize session recording",{error:e instanceof Error?e.message:String(e)})}}async startRecording(){return this.isReady?(this.recorder||(this.recorder=new at(this.config.recording),this.recorder.initialize(this.sessionToken,this.config.apiUrl,this.config.sdkKey)),this.recorder.start()):(console.warn("[SDK] Cannot start recording before SDK is initialized"),null)}async stopRecording(){this.recorder&&await this.recorder.stop()}pauseRecording(){var e;(e=this.recorder)==null||e.pause()}resumeRecording(){var e;(e=this.recorder)==null||e.resume()}addRecordingEvent(e){var t;(t=this.recorder)==null||t.addCustomEvent(e)}getRecordingStats(){var e,t;return(t=(e=this.recorder)==null?void 0:e.getStats())!=null?t:null}isRecordingActive(){var e,t;return(t=(e=this.recorder)==null?void 0:e.isRecording())!=null?t:!1}getRecordingSessionId(){var e,t;return(t=(e=this.recorder)==null?void 0:e.getSessionId())!=null?t:null}initProactive(){this.config.proactive&&(this.proactiveTracker=new Qr(this.config.proactive,{onTrigger:async(e,t)=>{this.emit("proactive",{context:e,message:t}),this.config.onProactiveMessage&&this.config.onProactiveMessage(t,e);try{await this.getProactiveAIMessage(e,t)}catch(r){await this.log("warn","Failed to get AI proactive message",{error:r})}}}),this.proactiveTracker.start(),this.log("info","Proactive behavior tracking initialized"))}async getProactiveAIMessage(e,t){try{let r={"Content-Type":"application/json"};this.config.sdkKey&&(r["X-SDK-Key"]=this.config.sdkKey);let s=await fetch(`${this.config.apiUrl}/sdk/proactive-message`,{method:"POST",headers:r,body:JSON.stringify({context:e,fallbackMessage:t,sessionToken:this.sessionToken})});if(!s.ok)return t;let o=(await s.json()).message||t,a={role:"assistant",content:o};return this.emit("message",a),o}catch(r){return t}}async sendInitialMessage(){let e=this.config.initialMessage;if(e)if(this.config.streamInitialMessage)await this.streamMessage(e);else{let t={role:"assistant",content:e};this.emit("message",t),this.config.onMessage&&this.config.onMessage(t)}}async streamMessage(e,t=30){let r="";for(let s=0;s<e.length;s++){r+=e[s];let n={role:"assistant",content:r};this.emit("message",n),await new Promise(o=>setTimeout(o,t))}}startProactiveTracking(){this.proactiveTracker&&this.proactiveTracker.start()}stopProactiveTracking(){this.proactiveTracker&&this.proactiveTracker.stop()}getProactiveStats(){var e,t;return(t=(e=this.proactiveTracker)==null?void 0:e.getStats())!=null?t:null}triggerProactiveMessage(e,t){if(this.proactiveTracker)this.proactiveTracker.triggerManual(e,t);else{let r={role:"assistant",content:e};this.emit("message",r),this.config.onMessage&&this.config.onMessage(r)}}optOutProactive(){var e;(e=this.proactiveTracker)==null||e.optOut()}optInProactive(){var e;(e=this.proactiveTracker)==null||e.optIn()}async initUserFlowTracking(){var e,t;try{this.userFlowTracker=new lt(this.config.userFlows),this.userFlowTracker.initialize(this.sessionToken,this.config.apiUrl,this.config.sdkKey);let r=((t=(e=this.recorder)==null?void 0:e.getSessionId)==null?void 0:t.call(e))||null,s=await this.userFlowTracker.start(r);s&&await this.log("info","User flow tracking started",{flowSessionId:s,linkedRecordingSession:r})}catch(r){await this.log("warn","Failed to initialize user flow tracking",{error:r instanceof Error?r.message:String(r)})}}identify(e){this.userFlowTracker&&this.userFlowTracker.identify(e),this.log("info","User identified",{hasEmail:!!e.email,hasName:!!e.name,hasTags:!!e.tags&&Object.keys(e.tags).length>0})}async startUserFlowTracking(){return this.isReady?(this.userFlowTracker||(this.userFlowTracker=new lt(this.config.userFlows),this.userFlowTracker.initialize(this.sessionToken,this.config.apiUrl,this.config.sdkKey)),this.userFlowTracker.start()):(console.warn("[SDK] Cannot start flow tracking before SDK is initialized"),null)}async stopUserFlowTracking(){this.userFlowTracker&&await this.userFlowTracker.stop()}pauseUserFlowTracking(){var e;(e=this.userFlowTracker)==null||e.pause()}resumeUserFlowTracking(){var e;(e=this.userFlowTracker)==null||e.resume()}trackEvent(e){var t;(t=this.userFlowTracker)==null||t.addCustomEvent(e)}getUserFlowStats(){var e,t;return(t=(e=this.userFlowTracker)==null?void 0:e.getStats())!=null?t:null}isUserFlowTrackingActive(){var e,t;return(t=(e=this.userFlowTracker)==null?void 0:e.isTracking())!=null?t:!1}destroy(){this.recorder&&(this.recorder.destroy(),this.recorder=null),this.proactiveTracker&&(this.proactiveTracker.stop(),this.proactiveTracker=null),this.userFlowTracker&&(this.userFlowTracker.stop(),this.userFlowTracker=null),this.actions.clear(),this.eventListeners.clear(),this.sessionToken=null,this.isReady=!1}};var F={instance:null,container:null,config:null,isOpen:!1};function am(i){var n,o,a,l,c,u,h,d;let e=document.createElement("div");e.id="produck-chat-widget";let r=(i.position||"bottom-right")==="bottom-right",s=document.createElement("style");return s.textContent=`
|
|
73
|
+
Check the Network tab in DevTools for more details.`),await this.log("error","SDK initialization failed",{error:n}),this.emit("error",s),s}}register(e,t){this.actions.set(e,t),this.log("info","Action handler registered",{actionKey:e,totalActions:this.actions.size})}unregister(e){this.actions.delete(e),this.log("info","Action handler unregistered",{actionKey:e,remainingActions:this.actions.size})}async sendMessage(e){var r,s;if(!this.isReady||!this.sessionToken)throw new Error("SDK not initialized. Call init() first.");let t=Date.now();await this.log("info","sendMessage called",{message:e});try{let n,o={"Content-Type":"application/json"};this.config.sdkKey?(n=`${this.config.apiUrl}/sdk/match-intent`,o["X-SDK-Key"]=this.config.sdkKey):n=`${this.config.apiUrl}/sdk/public/${this.config.guiderId}/match-intent`;let a=await fetch(n,{method:"POST",headers:o,body:JSON.stringify({userMessage:e})});if(await this.log("info","Match-intent response received",{status:a.status}),a.ok){let h=await a.json();if(h.matched&&h.type==="flow"&&h.flow){await this.log("info","Flow matched",{flowId:h.flow.flowId,name:h.flow.name,stepCount:(r=h.flow.steps)==null?void 0:r.length}),await this.sendLogToBackend({userMessage:e,matched:!0,actionKey:`flow:${h.flow.flowId}`,responseMessage:h.responseMessage,executionTimeMs:Date.now()-t});let d=await this.executeFlow(h.flow),p={role:"assistant",content:h.responseMessage||`I've completed the "${h.flow.name}" flow for you.`,flow:h.flow,flowResult:d};return this.emit("message",p),p}if(h.matched&&(h.type==="operation"||h.action)){let d=h.action;await this.log("info","Action matched",{actionKey:d.actionKey,actionType:d.actionType,responseMessage:d.responseMessage}),await this.sendLogToBackend({userMessage:e,matched:!0,actionKey:d.actionKey,responseMessage:d.responseMessage,executionTimeMs:Date.now()-t}),await this.executeAction(d);let p={role:"assistant",content:d.responseMessage||`I've triggered the "${d.name}" action for you.`,action:d};return this.emit("message",p),p}else await this.sendLogToBackend({userMessage:e,matched:!1,executionTimeMs:Date.now()-t})}let l=await fetch(`${this.config.apiUrl}/chat/sessions/${this.sessionToken}/message`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({message:e})});if(!l.ok)throw new Error(`Failed to send message: ${l.status}`);let c=await l.json(),u={role:"assistant",content:((s=c.message)==null?void 0:s.content)||c.response||"",visualFlows:c.flows||[],images:c.images||[],userFlows:c.userFlows||[]};return await this.log("info","Chat response received",{hasFlows:(c.flows||[]).length>0,hasImages:(c.images||[]).length>0,hasUserFlows:(c.userFlows||[]).length>0}),this.emit("message",u),u}catch(n){throw await this.log("error","Error in sendMessage",{error:n instanceof Error?n.message:String(n)}),this.emit("error",n),n}}async executeFlow(e){await this.log("info","executeFlow started",{flowId:e.flowId,name:e.name,stepCount:e.steps.length}),this.emit("flowStart",e),this.config.onFlowStart&&this.config.onFlowStart(e);let t=[],r={},s=[...e.steps].sort((o,a)=>o.order-a.order);for(let o of s){await this.log("info","Executing flow step",{flowId:e.flowId,operationId:o.operationId,order:o.order});let a={operationId:o.operationId,order:o.order,success:!1};try{let l=this.actions.get(o.operationId);if(l){let c={actionKey:o.operationId,name:o.operationId,actionType:"callback",actionConfig:{flowContext:r,inputMapping:o.inputMapping}},u=await l(c);a.success=!0,a.data=u,r={...r,[`step_${o.order}`]:u,previousResult:u},await this.log("info","Flow step completed successfully",{flowId:e.flowId,operationId:o.operationId,order:o.order})}else await this.log("warn","No handler registered for flow step",{flowId:e.flowId,operationId:o.operationId}),a.success=!0,a.data={skipped:!0,reason:"No handler registered"}}catch(l){a.success=!1,a.error=l instanceof Error?l.message:String(l),await this.log("error","Flow step failed",{flowId:e.flowId,operationId:o.operationId,error:a.error})}t.push(a),this.emit("flowStepComplete",{step:a,flow:e}),this.config.onFlowStepComplete&&this.config.onFlowStepComplete(a,e)}let n={flowId:e.flowId,name:e.name,steps:t,completed:!0,totalSteps:e.steps.length,successfulSteps:t.filter(o=>o.success).length};return await this.log("info","Flow execution completed",{flowId:e.flowId,totalSteps:n.totalSteps,successfulSteps:n.successfulSteps}),this.emit("flowComplete",n),this.config.onFlowComplete&&this.config.onFlowComplete(n),n}async sendLogToBackend(e){try{let t={"Content-Type":"application/json"};this.config.sdkKey&&(t["X-SDK-Key"]=this.config.sdkKey);let r=`${this.config.apiUrl}/sdk-logs/client`;await fetch(r,{method:"POST",headers:t,body:JSON.stringify({...e,timestamp:new Date().toISOString(),sessionToken:this.sessionToken})})}catch(t){}}async log(e,t,r){try{let s={"Content-Type":"application/json"};this.config.sdkKey&&(s["X-SDK-Key"]=this.config.sdkKey);let n=`${this.config.apiUrl}/sdk-logs/client`;await fetch(n,{method:"POST",headers:s,body:JSON.stringify({level:e,message:t,data:r,timestamp:new Date().toISOString(),sessionToken:this.sessionToken})})}catch(s){}}async executeAction(e){var s,n;let t=Array.from(this.actions.keys());typeof window!="undefined"&&console.log("%c\u{1F3AF} SDK executeAction","background: #ff0; color: #000; font-size: 20px; padding: 10px;",{actionKey:e.actionKey,totalRegistered:this.actions.size,registeredKeys:t}),await this.log("info","executeAction called",{actionKey:e.actionKey,actionType:typeof e.actionKey,totalRegistered:this.actions.size,registeredKeys:t,keyComparisons:t.map(o=>({key:o,matches:o===e.actionKey,keyLength:o.length,actionKeyLength:e.actionKey.length}))});let r=this.actions.get(e.actionKey);if(typeof window!="undefined"&&console.log("%c\u{1F50D} SDK Handler Lookup","background: #0ff; color: #000; font-size: 16px; padding: 5px;",{actionKey:e.actionKey,found:!!r,hasConfigOnAction:!!this.config.onAction,registeredKeys:Array.from(this.actions.keys())}),r)try{let o=Date.now();await r(e);let a=Date.now()-o;await this.log("info","Handler executed successfully",{actionKey:e.actionKey,executionTime:a}),await this.sendLogToBackend({userMessage:`Action executed: ${e.actionKey}`,matched:!0,actionKey:e.actionKey,responseMessage:e.responseMessage||`Executed ${e.name}`,executionTimeMs:a}),this.emit("action",e),(n=(s=this.config).onAction)==null||n.call(s,e.actionKey,e)}catch(o){await this.log("error","Handler execution failed",{actionKey:e.actionKey,error:o instanceof Error?o.message:String(o),stack:o instanceof Error?o.stack:void 0}),await this.sendLogToBackend({userMessage:`Action execution failed: ${e.actionKey}`,matched:!0,actionKey:e.actionKey,error:o instanceof Error?o.message:String(o)}),this.emit("error",o)}else{if(this.config.onAction){await this.log("info","No internal handler, trying config.onAction callback",{actionKey:e.actionKey});try{this.config.onAction(e.actionKey,e),this.emit("action",e),await this.log("info","Action dispatched via config.onAction",{actionKey:e.actionKey}),await this.sendLogToBackend({userMessage:`Action dispatched: ${e.actionKey}`,matched:!0,actionKey:e.actionKey,responseMessage:e.responseMessage||`Dispatched ${e.name}`});return}catch(o){await this.log("error","config.onAction callback failed",{actionKey:e.actionKey,error:o instanceof Error?o.message:String(o)})}}await this.log("warn","No handler registered for action",{actionKey:e.actionKey,registeredActions:Array.from(this.actions.keys())}),await this.sendLogToBackend({userMessage:`No handler for action: ${e.actionKey}`,matched:!1,actionKey:e.actionKey,error:`Handler not registered. Available: ${Array.from(this.actions.keys()).join(", ")}`})}}on(e,t){this.eventListeners.has(e)||this.eventListeners.set(e,new Set),this.eventListeners.get(e).add(t)}off(e,t){var r;(r=this.eventListeners.get(e))==null||r.delete(t)}emit(e,t){var r;(r=this.eventListeners.get(e))==null||r.forEach(s=>s(t))}getSessionToken(){return this.sessionToken}getIsReady(){return this.isReady}getRegisteredActions(){return Array.from(this.actions.keys())}getGuiderId(){return this.config.guiderId}async getVisualFlow(e){let t=this.config.guiderId;if(!t)return await this.log("warn","Cannot fetch visual flow without guiderId"),null;try{let r=await fetch(`${this.config.apiUrl}/visual-flows/chat/${t}/${e}`);if(!r.ok)return await this.log("warn","Visual flow not found",{flowId:e,status:r.status}),null;let s=await r.json();return!s.found||!s.flow?null:s.flow}catch(r){return await this.log("error","Error fetching visual flow",{flowId:e,error:r}),null}}async initRecording(){try{this.recorder=new at(this.config.recording),this.recorder.initialize(this.sessionToken,this.config.apiUrl,this.config.sdkKey);let e=await this.recorder.start();e&&await this.log("info","Session recording started",{recordingSessionId:e})}catch(e){await this.log("warn","Failed to initialize session recording",{error:e instanceof Error?e.message:String(e)})}}async startRecording(){return this.isReady?(this.recorder||(this.recorder=new at(this.config.recording),this.recorder.initialize(this.sessionToken,this.config.apiUrl,this.config.sdkKey)),this.recorder.start()):(console.warn("[SDK] Cannot start recording before SDK is initialized"),null)}async stopRecording(){this.recorder&&await this.recorder.stop()}pauseRecording(){var e;(e=this.recorder)==null||e.pause()}resumeRecording(){var e;(e=this.recorder)==null||e.resume()}addRecordingEvent(e){var t;(t=this.recorder)==null||t.addCustomEvent(e)}getRecordingStats(){var e,t;return(t=(e=this.recorder)==null?void 0:e.getStats())!=null?t:null}isRecordingActive(){var e,t;return(t=(e=this.recorder)==null?void 0:e.isRecording())!=null?t:!1}getRecordingSessionId(){var e,t;return(t=(e=this.recorder)==null?void 0:e.getSessionId())!=null?t:null}initProactive(){this.config.proactive&&(this.proactiveTracker=new Qr(this.config.proactive,{onTrigger:async(e,t)=>{this.emit("proactive",{context:e,message:t}),this.config.onProactiveMessage&&this.config.onProactiveMessage(t,e);try{await this.getProactiveAIMessage(e,t)}catch(r){await this.log("warn","Failed to get AI proactive message",{error:r})}}}),this.proactiveTracker.start(),this.log("info","Proactive behavior tracking initialized"))}async getProactiveAIMessage(e,t){try{let r={"Content-Type":"application/json"};this.config.sdkKey&&(r["X-SDK-Key"]=this.config.sdkKey);let s=await fetch(`${this.config.apiUrl}/sdk/proactive-message`,{method:"POST",headers:r,body:JSON.stringify({context:e,fallbackMessage:t,sessionToken:this.sessionToken})});if(!s.ok)return t;let o=(await s.json()).message||t,a={role:"assistant",content:o};return this.emit("message",a),o}catch(r){return t}}async sendInitialMessage(){let e=this.config.initialMessage;if(e)if(this.config.streamInitialMessage)await this.streamMessage(e);else{let t={role:"assistant",content:e};this.emit("message",t),this.config.onMessage&&this.config.onMessage(t)}}async streamMessage(e,t=30){let r="";for(let s=0;s<e.length;s++){r+=e[s];let n={role:"assistant",content:r};this.emit("message",n),await new Promise(o=>setTimeout(o,t))}}startProactiveTracking(){this.proactiveTracker&&this.proactiveTracker.start()}stopProactiveTracking(){this.proactiveTracker&&this.proactiveTracker.stop()}getProactiveStats(){var e,t;return(t=(e=this.proactiveTracker)==null?void 0:e.getStats())!=null?t:null}triggerProactiveMessage(e,t){if(this.proactiveTracker)this.proactiveTracker.triggerManual(e,t);else{let r={role:"assistant",content:e};this.emit("message",r),this.config.onMessage&&this.config.onMessage(r)}}optOutProactive(){var e;(e=this.proactiveTracker)==null||e.optOut()}optInProactive(){var e;(e=this.proactiveTracker)==null||e.optIn()}async initUserFlowTracking(){var e,t;try{console.log("%c\u{1F4CA} Initializing User Flow Tracking","background: #8b5cf6; color: #fff; padding: 2px 6px; border-radius: 3px;",{config:this.config.userFlows,apiUrl:this.config.apiUrl,sdkKey:this.config.sdkKey?"present":"missing"}),this.userFlowTracker=new lt(this.config.userFlows),this.userFlowTracker.initialize(this.sessionToken,this.config.apiUrl,this.config.sdkKey);let r=((t=(e=this.recorder)==null?void 0:e.getSessionId)==null?void 0:t.call(e))||null,s=await this.userFlowTracker.start(r);s?(console.log("%c\u2705 User Flow Tracking Started","background: #10b981; color: #fff; padding: 2px 6px; border-radius: 3px;",{flowSessionId:s,linkedRecordingSession:r}),await this.log("info","User flow tracking started",{flowSessionId:s,linkedRecordingSession:r})):console.warn("%c\u26A0\uFE0F User Flow Tracking: No session ID returned","background: #f59e0b; color: #000; padding: 2px 6px; border-radius: 3px;")}catch(r){console.error("%c\u274C User Flow Tracking Failed","background: #ef4444; color: #fff; padding: 2px 6px; border-radius: 3px;",r),await this.log("warn","Failed to initialize user flow tracking",{error:r instanceof Error?r.message:String(r)})}}identify(e){this.userFlowTracker&&this.userFlowTracker.identify(e),this.log("info","User identified",{hasEmail:!!e.email,hasName:!!e.name,hasTags:!!e.tags&&Object.keys(e.tags).length>0})}async startUserFlowTracking(){return this.isReady?(this.userFlowTracker||(this.userFlowTracker=new lt(this.config.userFlows),this.userFlowTracker.initialize(this.sessionToken,this.config.apiUrl,this.config.sdkKey)),this.userFlowTracker.start()):(console.warn("[SDK] Cannot start flow tracking before SDK is initialized"),null)}async stopUserFlowTracking(){this.userFlowTracker&&await this.userFlowTracker.stop()}pauseUserFlowTracking(){var e;(e=this.userFlowTracker)==null||e.pause()}resumeUserFlowTracking(){var e;(e=this.userFlowTracker)==null||e.resume()}trackEvent(e){var t;(t=this.userFlowTracker)==null||t.addCustomEvent(e)}getUserFlowStats(){var e,t;return(t=(e=this.userFlowTracker)==null?void 0:e.getStats())!=null?t:null}isUserFlowTrackingActive(){var e,t;return(t=(e=this.userFlowTracker)==null?void 0:e.isTracking())!=null?t:!1}destroy(){this.recorder&&(this.recorder.destroy(),this.recorder=null),this.proactiveTracker&&(this.proactiveTracker.stop(),this.proactiveTracker=null),this.userFlowTracker&&(this.userFlowTracker.stop(),this.userFlowTracker=null),this.actions.clear(),this.eventListeners.clear(),this.sessionToken=null,this.isReady=!1}};var F={instance:null,container:null,config:null,isOpen:!1};function am(i){var n,o,a,l,c,u,h,d;let e=document.createElement("div");e.id="produck-chat-widget";let r=(i.position||"bottom-right")==="bottom-right",s=document.createElement("style");return s.textContent=`
|
|
74
74
|
#produck-chat-widget {
|
|
75
75
|
position: fixed;
|
|
76
76
|
bottom: 20px;
|