/**
 * Minified by jsDelivr using Terser v5.39.0.
 * Original file: /npm/@twick/timeline@0.15.29/dist/index.js
 *
 * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files
 */
"use strict";var __defProp=Object.defineProperty,__defNormalProp=(e,t,i)=>t in e?__defProp(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,__publicField=(e,t,i)=>__defNormalProp(e,"symbol"!=typeof t?t+"":t,i);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const jsxRuntime=require("react/jsx-runtime"),React=require("react"),COLOR_FILTERS={SATURATED:"saturated",BRIGHT:"bright",VIBRANT:"vibrant",RETRO:"retro",BLACK_WHITE:"blackWhite",SEPIA:"sepia",COOL:"cool",WARM:"warm",CINEMATIC:"cinematic",SOFT_GLOW:"softGlow",MOODY:"moody",DREAMY:"dreamy",INVERTED:"inverted",VINTAGE:"vintage",DRAMATIC:"dramatic",FADED:"faded"},imageDimensionsCache={},videoMetaCache={},audioDurationCache={},getAudioDuration=e=>audioDurationCache[e]?Promise.resolve(audioDurationCache[e]):new Promise(((t,i)=>{const r=document.createElement("audio");r.preload="metadata";if(!/^(https?:|blob:|data:audio\/)/i.test(e))throw new Error("Unsafe audio source URL");r.src=e,r.onloadedmetadata=()=>{const i=r.duration;audioDurationCache[e]=i,t(i)},r.onerror=()=>{i(new Error("Failed to load audio metadata"))}})),concurrencyLimit=5;let activeCount=0;const queue=[];function runNext(){if(0===queue.length||activeCount>=5)return;const e=queue.shift();e&&(activeCount++,e())}function limit(e){return new Promise(((t,i)=>{const r=()=>{e().then(t).catch(i).finally((()=>{activeCount--,runNext()}))};activeCount<5?(activeCount++,r()):queue.push(r)}))}const loadImageDimensions=e=>new Promise(((t,i)=>{if("undefined"==typeof document)return void i(new Error("getImageDimensions() is only available in the browser."));const r=new Image;r.onload=()=>{t({width:r.naturalWidth,height:r.naturalHeight})},r.onerror=i,r.src=e})),getImageDimensions=e=>imageDimensionsCache[e]?Promise.resolve(imageDimensionsCache[e]):limit((()=>loadImageDimensions(e))).then((t=>(imageDimensionsCache[e]=t,t))),getVideoMeta=e=>videoMetaCache[e]?Promise.resolve(videoMetaCache[e]):new Promise(((t,i)=>{if(!/^(https?:|blob:|data:video\/)/i.test(e))return void i(new Error("Unsafe video source URL"));const r=n=>{const s=document.createElement("video");s.preload="metadata",s.crossOrigin=n?"anonymous":null,s.src=e,s.onloadedmetadata=()=>{const i={width:s.videoWidth,height:s.videoHeight,duration:s.duration};videoMetaCache[e]=i,t(i)},s.onerror=()=>{n?(s.src="",r(!1)):i(new Error("Failed to load video metadata. This may be due to CORS restrictions or an invalid video URL."))}};r(!0)})),extractAudio=async({src:e,playbackRate:t=1,start:i=0,end:r})=>{if(!e)throw new Error("src is required");if(t<=0)throw new Error("playbackRate must be > 0");if(!/^(https?:|blob:|data:)/i.test(e))throw new Error("Unsafe media source URL");const n=await fetchAndDecodeAudio(e);if(0===n.duration||0===n.length)throw new Error("No audio track found in the media source");if(isAudioSilent(n))throw new Error("Audio track is silent (no audio content detected)");const s=Math.max(0,i||0),o=n.duration,a=Math.min("number"==typeof r?r:o,o);if(a<=s)throw new Error("Invalid range: end must be greater than start");const l=await renderAudioSegment(n,s,a,t),c=await audioBufferToMp3(l);return URL.createObjectURL(c)},stitchAudio=async(e,t)=>{if(!e||0===e.length)throw new Error("At least one audio segment is required");const i=t||Math.max(...e.map((e=>e.e))),r=await createAudioTimeline(e,i),n=await audioBufferToMp3(r);return URL.createObjectURL(n)},fetchAndDecodeAudio=async e=>{const t=await fetch(e);if(!t.ok)throw new Error(`Failed to fetch source: ${t.status}`);const i=await t.arrayBuffer();return decodeAudioData(i)},decodeAudioData=async e=>{const t=window.AudioContext||window.webkitAudioContext;if(!t)throw new Error("Web Audio API not supported");const i=new t;try{return await new Promise(((t,r)=>{i.decodeAudioData(e.slice(0),(e=>t(e)),(e=>r(e||new Error("Failed to decode audio: no audio track found or unsupported format"))))}))}finally{i.close()}},isAudioSilent=(e,t=.001)=>{for(let i=0;i<e.numberOfChannels;i++){const r=e.getChannelData(i);for(let e=0;e<r.length;e+=100)if(Math.abs(r[e])>t)return!1}return!0},renderAudioSegment=async(e,t,i,r)=>{const n=window.OfflineAudioContext||window.webkitOfflineAudioContext;if(!n)throw new Error("OfflineAudioContext not supported");const s=e.sampleRate,o=i-t,a=new n(e.numberOfChannels,Math.max(1,Math.ceil(o/r*s)),s),l=a.createBufferSource();return l.buffer=e,l.playbackRate.value=r,l.connect(a.destination),l.start(0,t,o),await a.startRendering()},createAudioTimeline=async(e,t)=>{const i=window.OfflineAudioContext||window.webkitOfflineAudioContext;if(!i)throw new Error("OfflineAudioContext not supported");const r=new i(2,Math.ceil(44100*t),44100);for(const t of e){if(t.s>=t.e)continue;const e=t.volume??1;if(!(e<=0))try{const i=await fetchAndDecodeAudio(t.src),n=t.e-t.s,s=Math.min(n,i.duration),o=r.createBufferSource();if(o.buffer=i,1!==e){const t=r.createGain();t.gain.value=e,o.connect(t),t.connect(r.destination)}else o.connect(r.destination);o.start(t.s,0,s)}catch{}}return await r.startRendering()},audioBufferToMp3=async e=>{try{const t=audioBufferToWavArrayBuffer(e),i=await decodeAudioData(t);return await encodePcmToMp3(i)}catch(t){return audioBufferToWavBlob(e)}},audioBufferToWavArrayBuffer=e=>{const t=e.numberOfChannels,i=e.sampleRate,r=e.length,n=interleave(e,t,r),s=2*t,o=i*s,a=2*n.length,l=new ArrayBuffer(44+a),c=new DataView(l);return writeString(c,0,"RIFF"),c.setUint32(4,36+a,!0),writeString(c,8,"WAVE"),writeString(c,12,"fmt "),c.setUint32(16,16,!0),c.setUint16(20,1,!0),c.setUint16(22,t,!0),c.setUint32(24,i,!0),c.setUint32(28,o,!0),c.setUint16(32,s,!0),c.setUint16(34,16,!0),writeString(c,36,"data"),c.setUint32(40,a,!0),floatTo16BitPCM(c,44,n),l},encodePcmToMp3=async e=>{const t=await Promise.resolve().then((()=>require("./index-CXhwwSX--32kJEN73.js"))).then((e=>e.i)),i=e.numberOfChannels>=2?2:1,r=downsampleAudioBuffer(e,22050),n=new t.default.Mp3Encoder(i,22050,48),s=1152,o=r.getChannelData(0),a=floatTo16(o);let l;if(2===i){const e=r.getChannelData(1);l=floatTo16(e)}const c=[];for(let e=0;e<a.length;e+=s){const t=a.subarray(e,Math.min(e+s,a.length));let r;if(2===i&&l){const i=l.subarray(e,Math.min(e+s,l.length));r=n.encodeBuffer(t,i)}else r=n.encodeBuffer(t);r.length>0&&c.push(r)}const u=n.flush();return u.length>0&&c.push(u),new Blob(c,{type:"audio/mpeg"})},audioBufferToWavBlob=e=>{const t=audioBufferToWavArrayBuffer(e);return new Blob([t],{type:"audio/wav"})},downsampleAudioBuffer=(e,t)=>{if(e.sampleRate===t)return e;const i=e.sampleRate/t,r=Math.round(e.length/i),n=(new AudioContext).createBuffer(e.numberOfChannels,r,t);for(let t=0;t<e.numberOfChannels;t++){const s=e.getChannelData(t),o=n.getChannelData(t);for(let e=0;e<r;e++){const t=Math.floor(e*i);o[e]=s[t]}}return n},interleave=(e,t,i)=>{if(1===t)return e.getChannelData(0).slice(0,i);const r=new Float32Array(i*t),n=[];for(let i=0;i<t;i++)n[i]=e.getChannelData(i);let s=0;for(let e=0;e<i;e++)for(let i=0;i<t;i++)r[s++]=n[i][e];return r},floatTo16BitPCM=(e,t,i)=>{let r=t;for(let t=0;t<i.length;t++,r+=2){let n=Math.max(-1,Math.min(1,i[t]));e.setInt16(r,n<0?32768*n:32767*n,!0)}},floatTo16=e=>{const t=new Int16Array(e.length);for(let i=0;i<e.length;i++){const r=Math.max(-1,Math.min(1,e[i]));t[i]=r<0?32768*r:32767*r}return t},writeString=(e,t,i)=>{for(let r=0;r<i.length;r++)e.setUint8(t+r,i.charCodeAt(r))},getObjectFitSize=(e,t,i)=>{const r=t.width/t.height,n=i.width/i.height;switch(e){case"contain":return r>n?{width:i.width,height:i.width/r}:{width:i.height*r,height:i.height};case"cover":return r>n?{width:i.height*r,height:i.height}:{width:i.width,height:i.width/r};case"fill":return{width:i.width,height:i.height};default:return{width:t.width,height:t.height}}},TRACK_TYPES={VIDEO:"video",AUDIO:"audio",CAPTION:"caption",SCENE:"scene",ELEMENT:"element"},INITIAL_TIMELINE_DATA={tracks:[{type:TRACK_TYPES.ELEMENT,id:"t-sample",name:"sample",elements:[{id:"e-sample",trackId:"t-sample",name:"sample",type:"text",s:0,e:5,props:{text:"Twick SDK",fill:"#FFFFFF"}}]}],version:1},PLAYER_STATE={REFRESH:"Refresh",PLAYING:"Playing",PAUSED:"Paused"},CAPTION_STYLE={WORD_BG_HIGHLIGHT:"highlight_bg",WORD_BY_WORD:"word_by_word",WORD_BY_WORD_WITH_BG:"word_by_word_with_bg",OUTLINE_ONLY:"outline_only",SOFT_BOX:"soft_box",LOWER_THIRD:"lower_third",TYPEWRITER:"typewriter",KARAOKE:"karaoke",KARAOKE_WORD:"karaoke-word",POP_SCALE:"pop_scale"},CAPTION_STYLE_OPTIONS={[CAPTION_STYLE.WORD_BG_HIGHLIGHT]:{label:"Highlight Background",value:CAPTION_STYLE.WORD_BG_HIGHLIGHT},[CAPTION_STYLE.WORD_BY_WORD]:{label:"Word by Word",value:CAPTION_STYLE.WORD_BY_WORD},[CAPTION_STYLE.WORD_BY_WORD_WITH_BG]:{label:"Word with Background",value:CAPTION_STYLE.WORD_BY_WORD_WITH_BG},[CAPTION_STYLE.OUTLINE_ONLY]:{label:"Classic Outline",value:CAPTION_STYLE.OUTLINE_ONLY},[CAPTION_STYLE.SOFT_BOX]:{label:"Soft Box",value:CAPTION_STYLE.SOFT_BOX},[CAPTION_STYLE.LOWER_THIRD]:{label:"Lower Third",value:CAPTION_STYLE.LOWER_THIRD},[CAPTION_STYLE.TYPEWRITER]:{label:"Typewriter",value:CAPTION_STYLE.TYPEWRITER},[CAPTION_STYLE.KARAOKE]:{label:"Karaoke",value:CAPTION_STYLE.KARAOKE},[CAPTION_STYLE.KARAOKE_WORD]:{label:"Karaoke (Word Fade)",value:CAPTION_STYLE.KARAOKE_WORD},[CAPTION_STYLE.POP_SCALE]:{label:"Pop / Scale",value:CAPTION_STYLE.POP_SCALE}},CAPTION_FONT={size:40},CAPTION_COLOR={text:"#ffffff",highlight:"#ff4081",bgColor:"#8C52FF"},WORDS_PER_PHRASE=4,TIMELINE_ACTION={NONE:"none",SET_PLAYER_STATE:"setPlayerState",UPDATE_PLAYER_DATA:"updatePlayerData",ON_PLAYER_UPDATED:"onPlayerUpdated"},TIMELINE_ELEMENT_TYPE={VIDEO:"video",CAPTION:"caption",IMAGE:"image",AUDIO:"audio",TEXT:"text",RECT:"rect",CIRCLE:"circle",ICON:"icon",EMOJI:"emoji",PLACEHOLDER:"placeholder",LINE:"line",ARROW:"arrow",EFFECT:"effect"},PROCESS_STATE={IDLE:"Idle",PROCESSING:"Processing",COMPLETED:"Completed",FAILED:"Failed"};class TrackElement{constructor(e,t){__publicField(this,"id"),__publicField(this,"type"),__publicField(this,"s"),__publicField(this,"e"),__publicField(this,"trackId"),__publicField(this,"name"),__publicField(this,"animation"),__publicField(this,"props"),__publicField(this,"metadata"),this.id=t??`e-${generateShortUuid()}`,this.type=e,this.props={x:0,y:0,opacity:1,rotation:0}}getId(){return this.id}getType(){return this.type}getStart(){return this.s}getEnd(){return this.e}getDuration(){return this.e-this.s}getTrackId(){return this.trackId}getProps(){return this.props}getMetadata(){return this.metadata}getName(){return this.name}getAnimation(){return this.animation}getPosition(){var e,t;return{x:(null==(e=this.props)?void 0:e.x)??0,y:(null==(t=this.props)?void 0:t.y)??0}}getRotation(){return this.props.rotation??0}getOpacity(){return this.props.opacity??1}setId(e){return this.id=e,this}setType(e){return this.type=e,this}setStart(e){return this.s=Math.max(0,e),this}setEnd(e){return this.e=Math.max(this.s??0,e),this}setTrackId(e){return this.trackId=e,this}setName(e){return this.name=e,this}setAnimation(e){return this.animation=e,this}setPosition(e){return this.props.x=e.x,this.props.y=e.y,this}setRotation(e){return this.props.rotation=e,this}setOpacity(e){return this.props.opacity=e,this}setProps(e){return this.props=structuredClone(e),this}setMetadata(e){return this.metadata=e?structuredClone(e):void 0,this}getTransition(){var e;return null==(e=this.props)?void 0:e.transition}setTransition(e){return this.props||(this.props={}),this.props.transition=e,this}}class VideoElement extends TrackElement{constructor(e,t){super(TIMELINE_ELEMENT_TYPE.VIDEO),__publicField(this,"baseSize"),__publicField(this,"mediaDuration"),__publicField(this,"parentSize"),__publicField(this,"backgroundColor"),__publicField(this,"objectFit"),__publicField(this,"frameEffects"),__publicField(this,"frame"),this.objectFit="cover",this.frameEffects=[],this.parentSize=t,this.props={src:e,playbackRate:1,time:0,mediaFilter:"none",volume:1}}getParentSize(){return this.parentSize}getFrame(){return this.frame}getFrameEffects(){return this.frameEffects}getBackgroundColor(){return this.backgroundColor}getObjectFit(){return this.objectFit}getMediaDuration(){return this.mediaDuration}getStartAt(){return this.props.time||0}getEndAt(){return this.getDuration()*this.getPlaybackRate()}getSrc(){return this.props.src}getPlaybackRate(){return this.props.playbackRate??1}getVolume(){return this.props.volume??1}getRotation(){var e;return(null==(e=this.frame)?void 0:e.rotation)??0}setRotation(e){return this.frame.rotation=e,this}getPosition(){return{x:this.frame.x??0,y:this.frame.y??0}}async updateVideoMeta(e=!0){const t=await getVideoMeta(this.props.src);if(e){const e=getObjectFitSize("contain",{width:t.width,height:t.height},this.parentSize);this.frame={...this.frame,size:[e.width,e.height]}}this.mediaDuration=t.duration}setPosition(e){return this.frame.x=e.x,this.frame.y=e.y,this}async setSrc(e){return this.props.src=e,await this.updateVideoMeta(),this}setMediaDuration(e){return this.mediaDuration=e,this}setParentSize(e){return this.parentSize=structuredClone(e),this}setObjectFit(e){return this.objectFit=e,this}setFrame(e){return this.frame=structuredClone(e),this}setPlaybackRate(e){return this.props.playbackRate=e,this}setStartAt(e){return this.props.time=Math.max(0,e),this}setMediaFilter(e){return this.props.mediaFilter=e,this}setVolume(e){return this.props.volume=e,this}setBackgroundColor(e){return this.backgroundColor=e,this}setProps(e){return this.props={...structuredClone(e),src:this.props.src},this}setFrameEffects(e){return this.frameEffects=e,this}addFrameEffect(e){var t;return null==(t=this.frameEffects)||t.push(e),this}accept(e){return e.visitVideoElement(this)}}const getDecimalNumber=(e,t=3)=>Number(e.toFixed(t)),getTotalDuration=e=>(e||[]).reduce(((e,t)=>Math.max(e,((null==t?void 0:t.elements)||[]).reduce(((e,t)=>Math.max(e,t.e)),0))),0),generateShortUuid=()=>"xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})),getCurrentElements=(e,t)=>{const i=[];if(null==t?void 0:t.length)for(let r=0;r<t.length;r++)if(t[r]){const n=t[r].getElements();for(let t=0;t<n.length;t++){const r=n[t];r.getStart()<=e&&r.getEnd()>=e&&i.push(r)}}return i},SPLIT_EDGE_BUFFER_SEC=.1,canSplitElement=(e,t)=>t>e.getStart()+.1&&t<e.getEnd()-.1,isElementId=e=>e.startsWith("e-"),isTrackId=e=>e.startsWith("t-"),extractVideoAudio=async(e,t)=>{const i=[];e.forEach((e=>e.getElements().forEach((e=>{e instanceof VideoElement&&i.push({src:e.getSrc(),startAt:e.getStartAt(),endAt:e.getEndAt(),s:e.getStart(),e:e.getEnd(),volume:e.getVolume(),playbackRate:e.getPlaybackRate()})}))));const r=i.map((e=>extractAudio({src:e.src,startAt:e.startAt,endAt:e.endAt,volume:e.volume,playbackRate:e.playbackRate}))),n=await Promise.all(r);return await stitchAudio(n.map(((e,t)=>({src:e,s:i[t].s,e:i[t].e,volume:i[t].volume}))),t)},CURRENT_PROJECT_VERSION=2,migrateToV1=e=>({...e,version:1,tracks:e.tracks||[]}),migrateToV2=e=>({...e,version:2,metadata:e.metadata??{},tracks:(e.tracks||[]).map((e=>({...e,elements:(e.elements||[]).map((e=>({...e,metadata:e.metadata??void 0})))})))}),MIGRATIONS={1:migrateToV1,2:migrateToV2};function migrateProject(e,t=2){const i={tracks:(null==e?void 0:e.tracks)||[],version:Math.max(0,(null==e?void 0:e.version)||0),...void 0!==(null==e?void 0:e.watermark)&&{watermark:e.watermark},...void 0!==(null==e?void 0:e.backgroundColor)&&{backgroundColor:e.backgroundColor},...void 0!==(null==e?void 0:e.metadata)&&{metadata:e.metadata}};let r=i.version,n=i;for(;r<t;){const e=r+1,t=MIGRATIONS[e];if(!t)break;n=t(n),r=e}return{...n,version:Math.max(r,n.version)}}class AudioElement extends TrackElement{constructor(e){super(TIMELINE_ELEMENT_TYPE.AUDIO),__publicField(this,"mediaDuration"),this.props={src:e,time:0,playbackRate:1,volume:1,loop:!1}}getMediaDuration(){return this.mediaDuration}getStartAt(){return this.props.time||0}getEndAt(){return this.getDuration()*this.getPlaybackRate()}getSrc(){return this.props.src}getPlaybackRate(){return this.props.playbackRate??1}getVolume(){return this.props.volume??1}async updateAudioMeta(){this.mediaDuration=await getAudioDuration(this.props.src)}async setSrc(e){return this.props.src=e,await this.updateAudioMeta(),this}setMediaDuration(e){return this.mediaDuration=e,this}setVolume(e){return this.props.volume=e,this}setLoop(e){return this.props.loop=e,this}setStartAt(e){return this.props.time=Math.max(0,e),this}setPlaybackRate(e){return this.props.playbackRate=e,this}setProps(e){return this.props={...structuredClone(e),src:this.props.src},this}accept(e){return e.visitAudioElement(this)}}class ImageElement extends TrackElement{constructor(e,t){super(TIMELINE_ELEMENT_TYPE.IMAGE),__publicField(this,"backgroundColor"),__publicField(this,"parentSize"),__publicField(this,"objectFit"),__publicField(this,"frameEffects"),__publicField(this,"frame"),this.parentSize=t,this.objectFit="cover",this.frameEffects=[],this.props={src:e,mediaFilter:"none"},this.frame={x:0,y:0}}getParentSize(){return this.parentSize}getFrame(){return this.frame}getFrameEffects(){return this.frameEffects}getBackgroundColor(){return this.backgroundColor}getObjectFit(){return this.objectFit}getSrc(){return this.props.src}getRotation(){var e;return(null==(e=this.frame)?void 0:e.rotation)??0}setRotation(e){return this.frame.rotation=e,this}getPosition(){return{x:this.frame.x??0,y:this.frame.y??0}}async updateImageMeta(e=!0){const t=await getImageDimensions(this.props.src);if(e){const e=getObjectFitSize("contain",{width:t.width,height:t.height},this.parentSize);this.frame={size:[e.width,e.height],...this.frame}}}setPosition(e){return this.frame.x=e.x,this.frame.y=e.y,this}async setSrc(e){return this.props.src=e,await this.updateImageMeta(),this}setObjectFit(e){return this.objectFit=e,this}setFrame(e){return this.frame=structuredClone(e),this}setParentSize(e){return this.parentSize=structuredClone(e),this}setMediaFilter(e){return this.props.mediaFilter=e,this}setBackgroundColor(e){return this.backgroundColor=e,this}setProps(e){return this.props={...structuredClone(e),src:this.props.src},this}setFrameEffects(e){return this.frameEffects=e,this}addFrameEffect(e){var t;return null==(t=this.frameEffects)||t.push(e),this}accept(e){return e.visitImageElement(this)}}class TextElement extends TrackElement{constructor(e,t){super(TIMELINE_ELEMENT_TYPE.TEXT),__publicField(this,"textEffect"),this.props={text:e,fill:"#888888",...t||{}}}getTextEffect(){return this.textEffect}getText(){return this.props.text}getStrokeColor(){return this.props.stroke}getLineWidth(){return this.props.lineWidth}getProps(){return this.props}setText(e){return this.props.text=e,this}setFill(e){return this.props.fill=e,this}setRotation(e){return this.props.rotation=e,this}setFontSize(e){return this.props.fontSize=e,this}setFontFamily(e){return this.props.fontFamily=e,this}setFontWeight(e){return this.props.fontWeight=e,this}setFontStyle(e){return this.props.fontStyle=e,this}setTextEffect(e){return this.textEffect=e,this}setTextAlign(e){return this.props.textAlign=e,this}setStrokeColor(e){return this.props.stroke=e,this}setLineWidth(e){return this.props.lineWidth=e,this}setProps(e){return this.props=structuredClone(e),this}accept(e){return e.visitTextElement(this)}}class CaptionElement extends TrackElement{constructor(e,t,i){super(TIMELINE_ELEMENT_TYPE.CAPTION),__publicField(this,"t"),this.t=e,this.s=t,this.e=i,this.props={}}getText(){return this.t}setText(e){return this.t=e,this}accept(e){return e.visitCaptionElement(this)}}class IconElement extends TrackElement{constructor(e,t,i="#866bbf"){super(TIMELINE_ELEMENT_TYPE.ICON),this.props={src:e,fill:i,size:t}}getSrc(){return this.props.src}getFill(){return this.props.fill}getSize(){return this.props.size}setSrc(e){return this.props.src=e,this}setFill(e){return this.props.fill=e,this}setSize(e){return this.props.size=e,this}accept(e){return e.visitIconElement(this)}}const DEFAULT_EMOJI_SIZE=150;class EmojiElement extends ImageElement{constructor(e,t,i){super(t,i),this.setType(TIMELINE_ELEMENT_TYPE.EMOJI),this.setObjectFit("contain"),this.setFrame({x:0,y:0,size:[150,150]}),this.props={...this.props,emoji:e}}getEmoji(){return this.props.emoji??""}setEmoji(e){return this.props.emoji=e,this}accept(e){return e.visitEmojiElement(this)}}class CircleElement extends TrackElement{constructor(e,t){super(TIMELINE_ELEMENT_TYPE.CIRCLE),this.props={radius:t,height:2*t,width:2*t,fill:e,strokeColor:e,lineWidth:1}}getFill(){return this.props.fill}getRadius(){return this.props.radius}getStrokeColor(){return this.props.strokeColor||this.props.fill}getLineWidth(){return this.props.lineWidth??0}setFill(e){return this.props.fill=e,this}setRadius(e){return this.props.radius=e,this.props.width=2*e,this.props.height=2*e,this}setStrokeColor(e){return this.props.strokeColor=e,this}setLineWidth(e){return this.props.lineWidth=e,this}accept(e){return e.visitCircleElement(this)}}class RectElement extends TrackElement{constructor(e,t){super(TIMELINE_ELEMENT_TYPE.RECT),this.props={width:t.width,height:t.height,fill:e,radius:0,strokeColor:e,lineWidth:1}}getFill(){return this.props.fill}setFill(e){return this.props.fill=e,this}getSize(){return{width:this.props.width,height:this.props.height}}getCornerRadius(){return this.props.radius}getStrokeColor(){return this.props.strokeColor||this.props.fill}getLineWidth(){return this.props.lineWidth??0}setSize(e){return this.props.width=e.width,this.props.height=e.height,this}setCornerRadius(e){return this.props.radius=e,this}setStrokeColor(e){return this.props.strokeColor=e,this}setLineWidth(e){return this.props.lineWidth=e,this}accept(e){return e.visitRectElement(this)}}class PlaceholderElement extends TrackElement{constructor(e,t,i){super(TIMELINE_ELEMENT_TYPE.PLACEHOLDER),__publicField(this,"parentSize"),this.parentSize=t,this.props={src:e,...null!=i&&{expectedDuration:i}}}getSrc(){var e;return(null==(e=this.props)?void 0:e.src)??""}getExpectedDuration(){var e;return null==(e=this.props)?void 0:e.expectedDuration}getParentSize(){return this.parentSize}accept(e){return e.visitPlaceholderElement(this)}}class ElementAnimation{constructor(e){__publicField(this,"name"),__publicField(this,"interval"),__publicField(this,"duration"),__publicField(this,"intensity"),__publicField(this,"animate"),__publicField(this,"mode"),__publicField(this,"direction"),this.name=e}getName(){return this.name}getInterval(){return this.interval}getDuration(){return this.duration}getIntensity(){return this.intensity}getAnimate(){return this.animate}getMode(){return this.mode}getDirection(){return this.direction}setInterval(e){return this.interval=e,this}setDuration(e){return this.duration=e,this}setIntensity(e){return this.intensity=e,this}setAnimate(e){return this.animate=e,this}setMode(e){return this.mode=e,this}setDirection(e){return this.direction=e,this}toJSON(){return{name:this.name,interval:this.interval,duration:this.duration,intensity:this.intensity,animate:this.animate,mode:this.mode,direction:this.direction}}static fromJSON(e){const t=new ElementAnimation(e.name);return t.setInterval(e.interval),t.setDuration(e.duration),t.setIntensity(e.intensity),t.setAnimate(e.animate),t.setMode(e.mode),t.setDirection(e.direction),t}}class ElementFrameEffect{constructor(e,t){__publicField(this,"s"),__publicField(this,"e"),__publicField(this,"props"),this.s=e,this.e=t}setProps(e){return this.props=e,this}getProps(){return this.props}getStart(){return this.s}getEnd(){return this.e}setStart(e){return this.s=e,this}setEnd(e){return this.e=e,this}toJSON(){return{s:this.s,e:this.e,props:this.props}}static fromJSON(e){const t=new ElementFrameEffect(e.s,e.e);return t.setProps(e.props),t}}class ElementTextEffect{constructor(e){__publicField(this,"name"),__publicField(this,"duration"),__publicField(this,"delay"),__publicField(this,"bufferTime"),this.name=e}getName(){return this.name}getDuration(){return this.duration}getDelay(){return this.delay}getBufferTime(){return this.bufferTime}setDuration(e){return this.duration=e,this}setDelay(e){return this.delay=e,this}setBufferTime(e){return this.bufferTime=e,this}toJSON(){return{name:this.name,delay:this.delay,duration:this.duration??1,bufferTime:this.bufferTime}}static fromJSON(e){const t=new ElementTextEffect(e.name);return t.setDelay(e.delay),t.setDuration(e.duration),t.setBufferTime(e.bufferTime),t}}class ArrowElement extends TrackElement{constructor(e,t){super(TIMELINE_ELEMENT_TYPE.ARROW),this.props={fill:e,width:t.width,height:t.height,lineWidth:4}}accept(e){return e.visitArrowElement(this)}}class LineElement extends TrackElement{constructor(e,t){super(TIMELINE_ELEMENT_TYPE.LINE),this.props={fill:e,width:t.width,height:t.height,radius:4,lineWidth:t.height}}accept(e){return e.visitLineElement(this)}}class EffectElement extends TrackElement{constructor(e,t){super(TIMELINE_ELEMENT_TYPE.EFFECT),this.props={effectKey:e,intensity:1,...t||{}}}getEffectKey(){return this.props.effectKey}getIntensity(){return this.props.intensity??1}getProps(){return this.props}setEffectKey(e){return this.props.effectKey=e,this}setIntensity(e){return this.props.intensity=e,this}setProps(e){return this.props=structuredClone(e),this}accept(e){return e.visitEffectElement(this)}}const _ElementDeserializer=class e{static registerCustomType(e,t){if(!(null==e?void 0:e.trim()))throw new Error("Element type is required for custom deserializer registration");this.customDeserializers[e]=t}static unregisterCustomType(e){delete this.customDeserializers[e]}static deserializeBaseElement(e,t){t.id&&e.setId(t.id),t.trackId&&e.setTrackId(t.trackId),t.name&&e.setName(t.name),void 0!==t.s&&e.setStart(t.s),void 0!==t.e&&e.setEnd(t.e);const i={...t.props||{}};void 0!==t.zIndex&&(i.zIndex=t.zIndex),Object.keys(i).length&&e.setProps(i),t.metadata&&e.setMetadata(t.metadata),t.transition&&e.setTransition(t.transition),t.animation&&e.setAnimation(ElementAnimation.fromJSON(t.animation))}static deserializeVideoElement(t){var i;const r=t.frame&&t.frame.size?{width:t.frame.size[0],height:t.frame.size[1]}:{width:0,height:0},n=new VideoElement((null==(i=t.props)?void 0:i.src)||"",r);return e.deserializeBaseElement(n,t),void 0!==t.mediaDuration&&n.setMediaDuration(t.mediaDuration),t.objectFit&&n.setObjectFit(t.objectFit),t.frame&&n.setFrame(t.frame),t.frameEffects&&n.setFrameEffects(t.frameEffects.map((e=>ElementFrameEffect.fromJSON(e)))),t.backgroundColor&&n.setBackgroundColor(t.backgroundColor),n}static deserializeAudioElement(t){var i;const r=new AudioElement((null==(i=t.props)?void 0:i.src)||"");return e.deserializeBaseElement(r,t),void 0!==t.mediaDuration&&r.setMediaDuration(t.mediaDuration),r}static deserializeImageElement(t){var i;const r=t.frame&&t.frame.size?{width:t.frame.size[0],height:t.frame.size[1]}:{width:0,height:0},n=new ImageElement((null==(i=t.props)?void 0:i.src)||"",r);return e.deserializeBaseElement(n,t),t.objectFit&&n.setObjectFit(t.objectFit),t.frame&&n.setFrame(t.frame),t.frameEffects&&n.setFrameEffects(t.frameEffects.map((e=>ElementFrameEffect.fromJSON(e)))),t.backgroundColor&&n.setBackgroundColor(t.backgroundColor),n}static deserializeTextElement(t){var i;const r=new TextElement((null==(i=t.props)?void 0:i.text)||"");return e.deserializeBaseElement(r,t),t.textEffect&&r.setTextEffect(ElementTextEffect.fromJSON(t.textEffect)),r}static deserializeCaptionElement(t){const i=new CaptionElement(t.t||"",t.s||0,t.e||0);return e.deserializeBaseElement(i,t),i}static deserializeIconElement(t){var i,r,n;const s=(null==(i=t.props)?void 0:i.size)??{width:100,height:100},o=new IconElement((null==(r=t.props)?void 0:r.src)||"",s,null==(n=t.props)?void 0:n.fill);return e.deserializeBaseElement(o,t),o}static deserializeEmojiElement(t){var i,r;const n=t.frame&&t.frame.size?{width:t.frame.size[0],height:t.frame.size[1]}:{width:0,height:0},s=new EmojiElement((null==(i=t.props)?void 0:i.emoji)||"",(null==(r=t.props)?void 0:r.src)||"",n);return e.deserializeBaseElement(s,t),t.objectFit&&s.setObjectFit(t.objectFit),t.frame?s.setFrame(t.frame):s.setFrame({x:0,y:0,size:[150,150]}),t.frameEffects&&s.setFrameEffects(t.frameEffects.map((e=>ElementFrameEffect.fromJSON(e)))),t.backgroundColor&&s.setBackgroundColor(t.backgroundColor),s}static deserializeCircleElement(t){var i,r;const n=new CircleElement((null==(i=t.props)?void 0:i.fill)||"",(null==(r=t.props)?void 0:r.radius)||0);return e.deserializeBaseElement(n,t),n}static deserializeRectElement(t){var i,r,n;const s=new RectElement((null==(i=t.props)?void 0:i.fill)||"",{width:(null==(r=t.props)?void 0:r.width)||0,height:(null==(n=t.props)?void 0:n.height)||0});return e.deserializeBaseElement(s,t),s}static deserializePlaceholderElement(t){var i,r,n,s;const o=(null==(i=t.props)?void 0:i.parentSize)??((null==(r=t.frame)?void 0:r.size)?{width:t.frame.size[0],height:t.frame.size[1]}:{width:0,height:0}),a=new PlaceholderElement((null==(n=t.props)?void 0:n.src)??"",o,null==(s=t.props)?void 0:s.expectedDuration);return e.deserializeBaseElement(a,t),a}static deserializeArrowElement(t){var i,r,n;const s=new ArrowElement((null==(i=t.props)?void 0:i.fill)||"#ffcc00",{width:(null==(r=t.props)?void 0:r.width)||180,height:(null==(n=t.props)?void 0:n.height)||30});return e.deserializeBaseElement(s,t),s}static deserializeLineElement(t){var i,r,n;const s=new LineElement((null==(i=t.props)?void 0:i.fill)||"#f97316",{width:(null==(r=t.props)?void 0:r.width)||200,height:(null==(n=t.props)?void 0:n.height)||4});return e.deserializeBaseElement(s,t),s}static deserializeEffectElement(t){var i;const r=(null==(i=t.props)?void 0:i.effectKey)??"",n=new EffectElement(r,t.props);return e.deserializeBaseElement(n,t),n}static fromJSON(t){var i,r;try{const n=e.customDeserializers[t.type];if(n)return n(t);switch(t.type){case"video":return e.deserializeVideoElement(t);case"audio":return e.deserializeAudioElement(t);case"image":return e.deserializeImageElement(t);case"text":return e.deserializeTextElement(t);case"caption":return e.deserializeCaptionElement(t);case"icon":return e.deserializeIconElement(t);case"emoji":return e.deserializeEmojiElement(t);case"circle":return e.deserializeCircleElement(t);case"rect":return e.deserializeRectElement(t);case"placeholder":return e.deserializePlaceholderElement(t);case"line":return e.deserializeLineElement(t);case"arrow":return e.deserializeArrowElement(t);case"effect":return e.deserializeEffectElement(t);default:return e.deserializePlaceholderElement({...t,type:"placeholder",props:{...t.props||{},src:(null==(i=t.props)?void 0:i.src)??"",parentSize:null==(r=t.props)?void 0:r.parentSize,expectedDuration:t.e-t.s}})}}catch(e){return console.error("Error deserializing element:",e),null}}};__publicField(_ElementDeserializer,"customDeserializers",{});let ElementDeserializer=_ElementDeserializer;class ElementSerializer{serializeElement(e){var t,i,r;const n=structuredClone(e.getProps()),s=null==n?void 0:n.zIndex,o=null==(t=e.getTransition)?void 0:t.call(e);return{id:e.getId(),trackId:e.getTrackId(),type:e.getType(),name:e.getName(),s:e.getStart(),e:e.getEnd(),props:n,metadata:null==(i=e.getMetadata)?void 0:i.call(e),...void 0!==s&&{zIndex:s},...void 0!==o&&{transition:o},animation:null==(r=e.getAnimation())?void 0:r.toJSON()}}visitVideoElement(e){var t;return{...this.serializeElement(e),frame:structuredClone(e.getFrame()),frameEffects:null==(t=e.getFrameEffects())?void 0:t.map((e=>e.toJSON())),backgroundColor:e.getBackgroundColor(),objectFit:e.getObjectFit(),mediaDuration:e.getMediaDuration()}}visitAudioElement(e){return{...this.serializeElement(e),mediaDuration:e.getMediaDuration()}}visitImageElement(e){var t;return{...this.serializeElement(e),frame:structuredClone(e.getFrame()),frameEffects:null==(t=e.getFrameEffects())?void 0:t.map((e=>e.toJSON())),backgroundColor:e.getBackgroundColor(),objectFit:e.getObjectFit()}}visitTextElement(e){var t;return{...this.serializeElement(e),textEffect:null==(t=e.getTextEffect())?void 0:t.toJSON()}}visitCaptionElement(e){return{...this.serializeElement(e),t:structuredClone(e.getText())}}visitIconElement(e){return{...this.serializeElement(e)}}visitEmojiElement(e){var t;return{...this.serializeElement(e),frame:structuredClone(e.getFrame()),frameEffects:null==(t=e.getFrameEffects())?void 0:t.map((e=>e.toJSON())),backgroundColor:e.getBackgroundColor(),objectFit:e.getObjectFit()}}visitCircleElement(e){return{...this.serializeElement(e)}}visitRectElement(e){return{...this.serializeElement(e)}}visitPlaceholderElement(e){return this.serializeElement(e)}visitLineElement(e){return this.serializeElement(e)}visitArrowElement(e){return this.serializeElement(e)}visitEffectElement(e){return this.serializeElement(e)}}const VALIDATION_ERROR_CODE={ELEMENT_NOT_FOUND:"ELEMENT_NOT_FOUND",ELEMENT_NOT_ADDED:"ELEMENT_NOT_ADDED",ELEMENT_NOT_UPDATED:"ELEMENT_NOT_UPDATED",ELEMENT_NOT_REMOVED:"ELEMENT_NOT_REMOVED",COLLISION_ERROR:"COLLISION_ERROR",INVALID_TIMING:"INVALID_TIMING"};class ValidationError extends Error{constructor(e,t,i=[]){super(e),this.errors=t,this.warnings=i,this.name="ValidationError"}}class ElementValidator{validateBasicProperties(e){const t=[],i=[];return e.getId()||t.push("Element must have an ID"),e.getType()||t.push("Element must have a type"),void 0!==e.getStart()&&null!==e.getStart()||t.push("Element must have a start time (s)"),void 0!==e.getEnd()&&null!==e.getEnd()||t.push("Element must have an end time (e)"),void 0!==e.getStart()&&void 0!==e.getEnd()&&(e.getStart()<0&&t.push("Start time cannot be negative"),e.getEnd()<=e.getStart()&&t.push("End time must be greater than start time")),e.getName()||i.push("Element should have a name for better identification"),e.getTrackId()||i.push("Element should have a track Id"),{errors:t,warnings:i}}validateTextElement(e){const t=this.validateBasicProperties(e),i=[...t.errors],r=[...t.warnings],n=e.getProps();return(null==n?void 0:n.text)||i.push("Text element must have text content"),void 0!==(null==n?void 0:n.fontSize)&&n.fontSize<=0&&i.push("Font size must be greater than 0"),void 0!==(null==n?void 0:n.fontWeight)&&n.fontWeight<0&&i.push("Font weight cannot be negative"),{errors:i,warnings:r}}validateVideoElement(e){const t=this.validateBasicProperties(e),i=[...t.errors],r=[...t.warnings],n=e.getProps();return(null==n?void 0:n.src)||i.push("Video element must have a source URL"),void 0!==(null==n?void 0:n.volume)&&(n.volume<0||n.volume>3)&&i.push("Volume must be between 0 and 3 (linear; ~+6 dB max)"),void 0!==(null==n?void 0:n.playbackRate)&&n.playbackRate<=0&&i.push("Playback rate must be greater than 0"),{errors:i,warnings:r}}validateAudioElement(e){const t=this.validateBasicProperties(e),i=[...t.errors],r=[...t.warnings],n=e.getProps();return(null==n?void 0:n.src)||i.push("Audio element must have a source URL"),void 0!==(null==n?void 0:n.volume)&&(n.volume<0||n.volume>3)&&i.push("Volume must be between 0 and 3 (linear; ~+6 dB max)"),void 0!==(null==n?void 0:n.playbackRate)&&n.playbackRate<=0&&i.push("Playback rate must be greater than 0"),{errors:i,warnings:r}}validateImageElement(e){const t=this.validateBasicProperties(e),i=[...t.errors],r=[...t.warnings],n=e.getProps();return(null==n?void 0:n.src)||i.push("Image element must have a source URL"),{errors:i,warnings:r}}validateCaptionElement(e){const t=this.validateBasicProperties(e),i=[...t.errors],r=[...t.warnings],n=e.getText();return n&&""!==n.trim()||i.push("Caption element must have text content"),{errors:i,warnings:r}}validateIconElement(e){const t=this.validateBasicProperties(e);return{errors:[...t.errors],warnings:[...t.warnings]}}validateEmojiElement(e){const t=this.validateBasicProperties(e),i=[...t.errors],r=[...t.warnings],n=e.getProps();return(null==n?void 0:n.src)||i.push("Emoji element must have an image source URL"),(null==n?void 0:n.emoji)||r.push("Emoji element should include the source emoji character"),{errors:i,warnings:r}}validateCircleElement(e){const t=this.validateBasicProperties(e),i=[...t.errors],r=[...t.warnings],n=e.getProps();return void 0!==(null==n?void 0:n.radius)&&n.radius<=0&&i.push("Circle radius must be greater than 0"),{errors:i,warnings:r}}validateRectElement(e){const t=this.validateBasicProperties(e),i=[...t.errors],r=[...t.warnings],n=e.getProps();return void 0!==(null==n?void 0:n.width)&&n.width<=0&&i.push("Rectangle width must be greater than 0"),void 0!==(null==n?void 0:n.height)&&n.height<=0&&i.push("Rectangle height must be greater than 0"),{errors:i,warnings:r}}validateEffectElement(e){const t=this.validateBasicProperties(e),i=[...t.errors],r=[...t.warnings],n=e.getProps();return(null==n?void 0:n.effectKey)&&"string"==typeof n.effectKey||i.push("Effect element must have a valid effectKey"),void 0!==(null==n?void 0:n.intensity)&&(n.intensity<0||n.intensity>1)&&i.push("Effect intensity must be between 0 and 1"),{errors:i,warnings:r}}visitVideoElement(e){const t=this.validateVideoElement(e);if(t.errors.length>0)throw new ValidationError(`Video element validation failed: ${t.errors.join(", ")}`,t.errors,t.warnings);return!0}visitAudioElement(e){const t=this.validateAudioElement(e);if(t.errors.length>0)throw new ValidationError(`Audio element validation failed: ${t.errors.join(", ")}`,t.errors,t.warnings);return!0}visitImageElement(e){const t=this.validateImageElement(e);if(t.errors.length>0)throw new ValidationError(`Image element validation failed: ${t.errors.join(", ")}`,t.errors,t.warnings);return!0}visitTextElement(e){const t=this.validateTextElement(e);if(t.errors.length>0)throw new ValidationError(`Text element validation failed: ${t.errors.join(", ")}`,t.errors,t.warnings);return!0}visitCaptionElement(e){const t=this.validateCaptionElement(e);if(t.errors.length>0)throw new ValidationError(`Caption element validation failed: ${t.errors.join(", ")}`,t.errors,t.warnings);return!0}visitIconElement(e){const t=this.validateIconElement(e);if(t.errors.length>0)throw new ValidationError(`Icon element validation failed: ${t.errors.join(", ")}`,t.errors,t.warnings);return!0}visitEmojiElement(e){const t=this.validateEmojiElement(e);if(t.errors.length>0)throw new ValidationError(`Emoji element validation failed: ${t.errors.join(", ")}`,t.errors,t.warnings);return!0}visitCircleElement(e){const t=this.validateCircleElement(e);if(t.errors.length>0)throw new ValidationError(`Circle element validation failed: ${t.errors.join(", ")}`,t.errors,t.warnings);return!0}visitRectElement(e){const t=this.validateRectElement(e);if(t.errors.length>0)throw new ValidationError(`Rectangle element validation failed: ${t.errors.join(", ")}`,t.errors,t.warnings);return!0}visitPlaceholderElement(e){const t=this.validateBasicProperties(e);if(t.errors.length>0)throw new ValidationError(`Placeholder element validation failed: ${t.errors.join(", ")}`,t.errors,t.warnings);return!0}visitArrowElement(e){const t=this.validateBasicProperties(e);if(t.errors.length>0)throw new ValidationError(`Arrow element validation failed: ${t.errors.join(", ")}`,t.errors,t.warnings);return!0}visitLineElement(e){const t=this.validateBasicProperties(e);if(t.errors.length>0)throw new ValidationError(`Line element validation failed: ${t.errors.join(", ")}`,t.errors,t.warnings);return!0}visitEffectElement(e){const t=this.validateEffectElement(e);if(t.errors.length>0)throw new ValidationError(`Effect element validation failed: ${t.errors.join(", ")}`,t.errors,t.warnings);return!0}}class TrackFriend{constructor(e){this.track=e}addElement(e,t=!1){return this.track.addElementViaFriend(e,t)}removeElement(e){this.track.removeElementViaFriend(e)}updateElement(e){return this.track.updateElementViaFriend(e)}getTrack(){return this.track}}class Track{constructor(e,t=TRACK_TYPES.ELEMENT,i){__publicField(this,"id"),__publicField(this,"name"),__publicField(this,"type"),__publicField(this,"language"),__publicField(this,"props"),__publicField(this,"elements"),__publicField(this,"validator"),this.name=e,this.id=i??`t-${generateShortUuid()}`,this.type=t,this.props={},this.elements=[],this.validator=new ElementValidator}createFriend(){return new TrackFriend(this)}addElementViaFriend(e,t=!1){return this.addElement(e,t)}removeElementViaFriend(e){this.removeElement(e)}updateElementViaFriend(e){return this.updateElement(e)}getId(){return this.id}getName(){return this.name}setName(e){return this.name=e,this}getType(){return this.type}setType(e){return this.type=e,this}getLanguage(){return this.language}setLanguage(e){return this.language=e,this}getElements(){return[...this.elements]}getProps(){return this.props}setProps(e){return this.props=structuredClone(e),this}validateElement(e){return e.accept(this.validator)}getTrackDuration(){var e;return(null==(e=this.elements)?void 0:e.length)?this.elements[this.elements.length-1].getEnd():0}addElement(e,t=!1){if(e.setTrackId(this.id),t)return this.elements.push(e),!0;try{if(this.validateElement(e)){if(this.isElementColliding(e))throw new ValidationError("Element is colliding with another element",["COLLISION_ERROR"]);return this.elements.push(e),!0}}catch(e){throw e}return!1}isElementColliding(e){return this.elements.some((t=>t.getStart()<e.getEnd()&&t.getEnd()>e.getStart()))}removeElement(e){const t=this.elements.findIndex((t=>t.getId()===e.getId()));-1!==t&&this.elements.splice(t,1)}updateElement(e){try{if(this.validateElement(e)){const t=this.elements.findIndex((t=>t.getId()===e.getId()));if(-1!==t)return this.elements[t]=e,!0}}catch(e){if(e instanceof ValidationError)throw e;throw e}return!1}getElementById(e){const t=this.elements.find((t=>t.getId()===e));if(t)return t}validateAllElements(){let e=!0;const t=this.elements.map((t=>{try{const i=this.validateElement(t);return i||(e=!1),{element:t,isValid:i}}catch(i){return i instanceof ValidationError?(e=!1,{element:t,isValid:!1,errors:i.errors,warnings:i.warnings}):{element:t,isValid:!1,errors:[i instanceof Error?i.message:"Unknown error"]}}}));return{isValid:e,results:t}}serialize(){const e=new ElementSerializer;return{id:this.id,name:this.name,type:this.type,language:this.language,props:this.props,elements:this.elements.map((t=>t.accept(e)))}}static fromJSON(e){if(!e||"object"!=typeof e)throw new Error("Invalid JSON data for Track deserialization");const t=new Track(e.name||"",e.type??TRACK_TYPES.ELEMENT,e.id);return t.type=e.type,t.language=e.language,t.props=e.props||{},t.elements=(e.elements||[]).map(ElementDeserializer.fromJSON).filter((e=>null!==e)),t}}const _TimelineContextStore=class e{constructor(){__publicField(this,"storeMap"),this.storeMap=new Map}static getInstance(){return e.instance||(e.instance=new e),e.instance}initializeContext(e){this.storeMap.has(e)||this.storeMap.set(e,{tracks:[],version:0,elementMap:{},trackMap:{},captionProps:{}})}getTimelineData(e){const t=this.storeMap.get(e);return t?{tracks:t.tracks,version:t.version,backgroundColor:t.backgroundColor,metadata:t.metadata}:null}setTimelineData(e,t){this.ensureContext(e);const i=this.storeMap.get(e);return i.tracks=t.tracks,i.version=t.version,void 0!==t.backgroundColor&&(i.backgroundColor=t.backgroundColor),void 0!==t.metadata&&(i.metadata=t.metadata),t}getElementMap(e){return this.ensureContext(e),this.storeMap.get(e).elementMap}setElementMap(e,t){this.ensureContext(e),this.storeMap.get(e).elementMap=t}getTrackMap(e){return this.ensureContext(e),this.storeMap.get(e).trackMap}setTrackMap(e,t){this.ensureContext(e),this.storeMap.get(e).trackMap=t}getCaptionProps(e){return this.ensureContext(e),this.storeMap.get(e).captionProps}setCaptionProps(e,t){this.ensureContext(e),this.storeMap.get(e).captionProps=t}clearContext(e){this.storeMap.delete(e)}ensureContext(e){this.storeMap.has(e)||this.initializeContext(e)}};__publicField(_TimelineContextStore,"instance");let TimelineContextStore=_TimelineContextStore;const timelineContextStore=TimelineContextStore.getInstance();class ElementAdder{constructor(e){__publicField(this,"track"),__publicField(this,"trackFriend"),this.track=e,this.trackFriend=e.createFriend()}async visitVideoElement(e){await e.updateVideoMeta();const t=this.track.getElements(),i=(null==t?void 0:t.length)?t[t.length-1].getEnd():0;return isNaN(e.getStart())&&e.setStart(i),isNaN(e.getEnd())&&e.setEnd(e.getStart()+e.getMediaDuration()),this.trackFriend.addElement(e)}async visitAudioElement(e){await e.updateAudioMeta();const t=this.track.getElements(),i=(null==t?void 0:t.length)?t[t.length-1].getEnd():0;return isNaN(e.getStart())&&e.setStart(i),isNaN(e.getEnd())&&e.setEnd(e.getStart()+e.getMediaDuration()),this.trackFriend.addElement(e)}async visitImageElement(e){await e.updateImageMeta();const t=this.track.getElements(),i=(null==t?void 0:t.length)?t[t.length-1].getEnd():0;return isNaN(e.getStart())&&e.setStart(i),isNaN(e.getEnd())&&e.setEnd(e.getStart()+1),this.trackFriend.addElement(e)}async visitTextElement(e){const t=this.track.getElements(),i=(null==t?void 0:t.length)?t[t.length-1].getEnd():0;return isNaN(e.getStart())&&e.setStart(i),isNaN(e.getEnd())&&e.setEnd(e.getStart()+1),this.trackFriend.addElement(e)}async visitCaptionElement(e){const t=this.track.getElements(),i=(null==t?void 0:t.length)?t[t.length-1].getEnd():0;return isNaN(e.getStart())&&e.setStart(i),isNaN(e.getEnd())&&e.setEnd(e.getStart()+1),this.trackFriend.addElement(e)}async visitIconElement(e){const t=this.track.getElements(),i=(null==t?void 0:t.length)?t[t.length-1].getEnd():0;return isNaN(e.getStart())&&e.setStart(i),isNaN(e.getEnd())&&e.setEnd(e.getStart()+1),this.trackFriend.addElement(e)}async visitEmojiElement(e){await e.updateImageMeta();const t=this.track.getElements(),i=(null==t?void 0:t.length)?t[t.length-1].getEnd():0;return isNaN(e.getStart())&&e.setStart(i),isNaN(e.getEnd())&&e.setEnd(e.getStart()+1),this.trackFriend.addElement(e)}async visitCircleElement(e){const t=this.track.getElements(),i=(null==t?void 0:t.length)?t[t.length-1].getEnd():0;return isNaN(e.getStart())&&e.setStart(i),isNaN(e.getEnd())&&e.setEnd(e.getStart()+1),this.trackFriend.addElement(e)}async visitRectElement(e){const t=this.track.getElements(),i=(null==t?void 0:t.length)?t[t.length-1].getEnd():0;return isNaN(e.getStart())&&e.setStart(i),isNaN(e.getEnd())&&e.setEnd(e.getStart()+1),this.trackFriend.addElement(e)}async visitPlaceholderElement(e){const t=this.track.getElements(),i=(null==t?void 0:t.length)?t[t.length-1].getEnd():0;if(isNaN(e.getStart())&&e.setStart(i),isNaN(e.getEnd())){const t=e.getExpectedDuration();e.setEnd(e.getStart()+(t??1))}return this.trackFriend.addElement(e)}async visitLineElement(e){const t=this.track.getElements(),i=(null==t?void 0:t.length)?t[t.length-1].getEnd():0;return isNaN(e.getStart())&&e.setStart(i),isNaN(e.getEnd())&&e.setEnd(e.getStart()+1),this.trackFriend.addElement(e)}async visitArrowElement(e){const t=this.track.getElements(),i=(null==t?void 0:t.length)?t[t.length-1].getEnd():0;return isNaN(e.getStart())&&e.setStart(i),isNaN(e.getEnd())&&e.setEnd(e.getStart()+1),this.trackFriend.addElement(e)}async visitEffectElement(e){const t=this.track.getElements(),i=(null==t?void 0:t.length)?t[t.length-1].getEnd():0;return isNaN(e.getStart())&&e.setStart(i),isNaN(e.getEnd())&&e.setEnd(e.getStart()+1),this.trackFriend.addElement(e)}}class ElementRemover{constructor(e){__publicField(this,"trackFriend"),this.trackFriend=e.createFriend()}visitVideoElement(e){return this.trackFriend.removeElement(e),!0}visitAudioElement(e){return this.trackFriend.removeElement(e),!0}visitImageElement(e){return this.trackFriend.removeElement(e),!0}visitTextElement(e){return this.trackFriend.removeElement(e),!0}visitCaptionElement(e){return this.trackFriend.removeElement(e),!0}visitIconElement(e){return this.trackFriend.removeElement(e),!0}visitEmojiElement(e){return this.trackFriend.removeElement(e),!0}visitCircleElement(e){return this.trackFriend.removeElement(e),!0}visitRectElement(e){return this.trackFriend.removeElement(e),!0}visitPlaceholderElement(e){return this.trackFriend.removeElement(e),!0}visitArrowElement(e){return this.trackFriend.removeElement(e),!0}visitLineElement(e){return this.trackFriend.removeElement(e),!0}visitEffectElement(e){return this.trackFriend.removeElement(e),!0}}class ElementUpdater{constructor(e){__publicField(this,"trackFriend"),this.trackFriend=e.createFriend()}visitVideoElement(e){return this.trackFriend.updateElement(e)}visitAudioElement(e){return this.trackFriend.updateElement(e)}visitImageElement(e){return this.trackFriend.updateElement(e)}visitTextElement(e){return this.trackFriend.updateElement(e)}visitCaptionElement(e){return this.trackFriend.updateElement(e)}visitIconElement(e){return this.trackFriend.updateElement(e)}visitEmojiElement(e){return this.trackFriend.updateElement(e)}visitCircleElement(e){return this.trackFriend.updateElement(e)}visitRectElement(e){return this.trackFriend.updateElement(e)}visitPlaceholderElement(e){return this.trackFriend.updateElement(e)}visitArrowElement(e){return this.trackFriend.updateElement(e)}visitLineElement(e){return this.trackFriend.updateElement(e)}visitEffectElement(e){return this.trackFriend.updateElement(e)}}class ElementCloner{cloneElementProperties(e,t){var i;return t.setName(e.getName()).setType(e.getType()).setStart(e.getStart()).setEnd(e.getEnd()).setProps(e.getProps()).setMetadata(null==(i=e.getMetadata)?void 0:i.call(e)).setAnimation(e.getAnimation())}visitVideoElement(e){const t=e.getProps(),i=new VideoElement(t.src,e.getParentSize());return this.cloneElementProperties(e,i),i.setParentSize(e.getParentSize()).setMediaDuration(e.getMediaDuration()).setFrame(e.getFrame()).setFrameEffects(e.getFrameEffects()??[]).setBackgroundColor(e.getBackgroundColor()).setObjectFit(e.getObjectFit()),i}visitAudioElement(e){const t=new AudioElement(e.getProps().src);return this.cloneElementProperties(e,t),t.setMediaDuration(e.getMediaDuration()),t}visitImageElement(e){const t=new ImageElement(e.getProps().src,e.getParentSize());return this.cloneElementProperties(e,t),t.setParentSize(e.getParentSize()).setFrame(e.getFrame()).setFrameEffects(e.getFrameEffects()).setBackgroundColor(e.getBackgroundColor()).setObjectFit(e.getObjectFit()),t}visitTextElement(e){const t=new TextElement(e.getProps().text);return this.cloneElementProperties(e,t),t.setTextEffect(e.getTextEffect()),t}visitCaptionElement(e){const t=new CaptionElement(e.getProps().text,e.getStart(),e.getEnd());return this.cloneElementProperties(e,t),t}visitRectElement(e){const t=new RectElement(e.getProps().fill,e.getProps().size);return this.cloneElementProperties(e,t),t}visitCircleElement(e){const t=new CircleElement(e.getProps().fill,e.getProps().radius);return this.cloneElementProperties(e,t),t}visitIconElement(e){const t=new IconElement(e.getProps().src,e.getProps().size,e.getProps().fill);return this.cloneElementProperties(e,t),t}visitEmojiElement(e){const t=new EmojiElement(e.getEmoji(),e.getProps().src,e.getParentSize());return this.cloneElementProperties(e,t),t.setParentSize(e.getParentSize()).setFrame(e.getFrame()).setFrameEffects(e.getFrameEffects()).setBackgroundColor(e.getBackgroundColor()).setObjectFit(e.getObjectFit()),t}visitPlaceholderElement(e){const t=new PlaceholderElement(e.getSrc(),e.getParentSize(),e.getExpectedDuration());return this.cloneElementProperties(e,t),t}visitArrowElement(e){const t=new ArrowElement(e.getProps().fill,{width:e.getProps().width,height:e.getProps().height});return this.cloneElementProperties(e,t),t}visitLineElement(e){const t=new LineElement(e.getProps().fill,{width:e.getProps().width,height:e.getProps().height});return this.cloneElementProperties(e,t),t}visitEffectElement(e){const t=new EffectElement(e.getEffectKey(),e.getProps());return this.cloneElementProperties(e,t),t}}class ElementSplitter{constructor(e){__publicField(this,"splitTime"),__publicField(this,"elementCloner"),this.splitTime=e,this.elementCloner=new ElementCloner}splitTextToNonEmptyParts(e,t){const i=e.split(/\s+/).map((e=>e.trim())).filter(Boolean);if(i.length<2)return null;const r=Math.floor(i.length*t),n=Math.min(i.length-1,Math.max(1,r));return{first:i.slice(0,n).join(" "),second:i.slice(n).join(" ")}}visitVideoElement(e){if(!canSplitElement(e,this.splitTime))return{firstElement:null,secondElement:null,success:!1};const t=this.elementCloner.visitVideoElement(e),i=this.elementCloner.visitVideoElement(e),r=e.getProps(),n=(r.time??0)+(this.splitTime-e.getStart())*(r.playbackRate??1);return t.setEnd(this.splitTime),i.setStart(this.splitTime).setStartAt(n),{firstElement:t,secondElement:i,success:!0}}visitAudioElement(e){if(!canSplitElement(e,this.splitTime))return{firstElement:null,secondElement:null,success:!1};const t=this.elementCloner.visitAudioElement(e),i=this.elementCloner.visitAudioElement(e),r=e.getProps(),n=(r.time??0)+(this.splitTime-e.getStart())*(r.playbackRate??1);return t.setEnd(this.splitTime),i.setStart(this.splitTime).setStartAt(n),{firstElement:t,secondElement:i,success:!0}}visitImageElement(e){if(!canSplitElement(e,this.splitTime))return{firstElement:null,secondElement:null,success:!1};const t=this.elementCloner.visitImageElement(e),i=this.elementCloner.visitImageElement(e);return t.setEnd(this.splitTime),i.setStart(this.splitTime),{firstElement:t,secondElement:i,success:!0}}visitTextElement(e){if(!canSplitElement(e,this.splitTime))return{firstElement:null,secondElement:null,success:!1};const t=e.getText()||"",i=(this.splitTime-e.getStart())/e.getDuration(),r=this.splitTextToNonEmptyParts(t,i);if(!r)return{firstElement:null,secondElement:null,success:!1};const n=this.elementCloner.visitTextElement(e);n.setText(r.first),n.setEnd(this.splitTime);const s=this.elementCloner.visitTextElement(e);return s.setText(r.second),s.setStart(this.splitTime),{firstElement:n,secondElement:s,success:!0}}visitCaptionElement(e){if(!canSplitElement(e,this.splitTime))return{firstElement:null,secondElement:null,success:!1};const t=e.getText()||"",i=(this.splitTime-e.getStart())/e.getDuration(),r=this.splitTextToNonEmptyParts(t,i);if(!r)return{firstElement:null,secondElement:null,success:!1};const n=this.elementCloner.visitCaptionElement(e);n.setText(r.first),n.setEnd(this.splitTime);const s=this.elementCloner.visitCaptionElement(e);return s.setText(r.second),s.setStart(this.splitTime),{firstElement:n,secondElement:s,success:!0}}visitRectElement(e){if(!canSplitElement(e,this.splitTime))return{firstElement:null,secondElement:null,success:!1};const t=this.elementCloner.visitRectElement(e),i=this.elementCloner.visitRectElement(e);return t.setEnd(this.splitTime),i.setStart(this.splitTime),{firstElement:t,secondElement:i,success:!0}}visitCircleElement(e){if(!canSplitElement(e,this.splitTime))return{firstElement:null,secondElement:null,success:!1};const t=this.elementCloner.visitCircleElement(e),i=this.elementCloner.visitCircleElement(e);return t.setEnd(this.splitTime),i.setStart(this.splitTime),{firstElement:t,secondElement:i,success:!0}}visitIconElement(e){if(!canSplitElement(e,this.splitTime))return{firstElement:null,secondElement:null,success:!1};const t=this.elementCloner.visitIconElement(e),i=this.elementCloner.visitIconElement(e);return t.setEnd(this.splitTime),i.setStart(this.splitTime),{firstElement:t,secondElement:i,success:!0}}visitEmojiElement(e){if(!canSplitElement(e,this.splitTime))return{firstElement:null,secondElement:null,success:!1};const t=this.elementCloner.visitEmojiElement(e),i=this.elementCloner.visitEmojiElement(e);return t.setEnd(this.splitTime),i.setStart(this.splitTime),{firstElement:t,secondElement:i,success:!0}}visitPlaceholderElement(e){if(!canSplitElement(e,this.splitTime))return{firstElement:null,secondElement:null,success:!1};const t=this.elementCloner.visitPlaceholderElement(e),i=this.elementCloner.visitPlaceholderElement(e);return t.setEnd(this.splitTime),i.setStart(this.splitTime),{firstElement:t,secondElement:i,success:!0}}visitArrowElement(e){if(!canSplitElement(e,this.splitTime))return{firstElement:null,secondElement:null,success:!1};const t=this.elementCloner.visitArrowElement(e),i=this.elementCloner.visitArrowElement(e);return t.setEnd(this.splitTime),i.setStart(this.splitTime),{firstElement:t,secondElement:i,success:!0}}visitLineElement(e){if(!canSplitElement(e,this.splitTime))return{firstElement:null,secondElement:null,success:!1};const t=this.elementCloner.visitLineElement(e),i=this.elementCloner.visitLineElement(e);return t.setEnd(this.splitTime),i.setStart(this.splitTime),{firstElement:t,secondElement:i,success:!0}}visitEffectElement(e){if(!canSplitElement(e,this.splitTime))return{firstElement:null,secondElement:null,success:!1};const t=this.elementCloner.visitEffectElement(e),i=this.elementCloner.visitEffectElement(e);return t.setEnd(this.splitTime),i.setStart(this.splitTime),{firstElement:t,secondElement:i,success:!0}}}class TimelineEditor{constructor(e){__publicField(this,"context"),__publicField(this,"totalDuration",0),__publicField(this,"eventListeners",new Map),this.context=e,timelineContextStore.initializeContext(this.context.contextId)}registerElementType(e,t){ElementDeserializer.registerCustomType(e,t)}unregisterElementType(e){ElementDeserializer.unregisterCustomType(e)}on(e,t){let i=this.eventListeners.get(e);i||(i=new Set,this.eventListeners.set(e,i)),i.add(t)}off(e,t){var i;null==(i=this.eventListeners.get(e))||i.delete(t)}emit(e,t){var i;null==(i=this.eventListeners.get(e))||i.forEach((e=>e(t)))}getContext(){return this.context}pauseVideo(){var e;(null==(e=this.context)?void 0:e.setTimelineAction)&&this.context.setTimelineAction(TIMELINE_ACTION.SET_PLAYER_STATE,PLAYER_STATE.PAUSED)}getTimelineData(){const e=this.context.contextId;return timelineContextStore.getTimelineData(e)}getLatestVersion(){const e=this.context.contextId,t=timelineContextStore.getTimelineData(e);return(null==t?void 0:t.version)||0}setTimelineData({tracks:e,version:t,watermark:i,backgroundColor:r,metadata:n,updatePlayerData:s}){var o,a,l;const c=this.getTimelineData(),u=t??((null==c?void 0:c.version)||0)+1,d=void 0!==r?r:null==c?void 0:c.backgroundColor,h=void 0!==n?n:null==c?void 0:c.metadata,p={tracks:e,version:u,watermark:i,backgroundColor:d,metadata:h};if(timelineContextStore.setTimelineData(this.context.contextId,p),this.updateHistory(p),this.context.updateChangeLog(),s){const t=e.map((e=>e.serialize()));null==(l=null==(o=this.context)?void 0:o.setTimelineAction)||l.call(o,TIMELINE_ACTION.UPDATE_PLAYER_DATA,{tracks:t,version:u,watermark:null!=i?null==(a=i.toJSON)?void 0:a.call(i):void 0,backgroundColor:d,metadata:h})}return p}addTrack(e,t=TRACK_TYPES.ELEMENT){const i=this.getTimelineData(),r=`t-${generateShortUuid()}`,n=new Track(e,t,r),s=[...(null==i?void 0:i.tracks)||[],n];return this.setTimelineData({tracks:s,updatePlayerData:!0}),this.emit("track:added",{track:n.serialize(),index:s.length-1}),n}getTrackById(e){const t=this.getTimelineData();return null==t?void 0:t.tracks.find((t=>t.getId()===e))}getTrackByName(e){const t=this.getTimelineData();return null==t?void 0:t.tracks.find((t=>t.getName()===e))}getCaptionsTrack(){const e=this.getTimelineData();return null==e?void 0:e.tracks.find((e=>e.getType()===TRACK_TYPES.CAPTION))}getTracksByType(e){const t=this.getTimelineData();return(null==t?void 0:t.tracks.filter((t=>t.getType()===e)))??[]}getTracksByPredicate(e){const t=this.getTimelineData();return(null==t?void 0:t.tracks.filter(((t,i)=>e(t,i))))??[]}updateTrackProps(e,t){const i=this.getTrackById(e);if(!i)return null;const r=i.getProps()??{};return i.setProps({...r,...t}),this.refresh(),i}replaceTrackProps(e,t){const i=this.getTrackById(e);return i?(i.setProps(t),this.refresh(),i):null}upsertTrack(e){if(e.id){const t=this.getTrackById(e.id);if(t)return e.name&&t.setName(e.name),e.type&&t.setType(e.type),void 0!==e.language&&t.setLanguage(e.language),void 0!==e.props&&t.setProps(e.props),this.refresh(),t}const t=this.addTrack(e.name,e.type??TRACK_TYPES.ELEMENT);return void 0!==e.language&&t.setLanguage(e.language),void 0!==e.props&&t.setProps(e.props),this.refresh(),t}validateTrackOverlaps(e){const t=this.getTrackById(e);if(!t)return{valid:!0,issues:[]};const i=[...t.getElements()].sort(((e,t)=>e.getStart()-t.getStart())),r=[];for(let t=0;t<i.length-1;t+=1){const n=i[t],s=i[t+1];n.getEnd()>s.getStart()&&r.push({elementId:n.getId(),overlapsWithElementId:s.getId(),trackId:e})}return{valid:0===r.length,issues:r}}removeTrackById(e){var t;const i=((null==(t=this.getTimelineData())?void 0:t.tracks)||[]).filter((t=>t.getId()!==e));this.setTimelineData({tracks:i,updatePlayerData:!0}),this.emit("track:removed",{trackId:e})}removeTrack(e){var t;const i=((null==(t=this.getTimelineData())?void 0:t.tracks)||[]).filter((t=>t.getId()!==e.getId()));this.setTimelineData({tracks:i,updatePlayerData:!0}),this.emit("track:removed",{trackId:e.getId()})}refresh(){const e=this.getTimelineData();e&&this.setTimelineData({tracks:e.tracks,updatePlayerData:!0})}async addElementToTrack(e,t){var i;if(!e)throw new Error("TRACK_NOT_FOUND");try{const i=new ElementAdder(e);if(await t.accept(i)){const i=this.getTimelineData();return i&&this.setTimelineData({tracks:i.tracks,updatePlayerData:!0}),this.emit("element:added",{element:t,trackId:e.getId()}),!0}return!1}catch(e){throw e instanceof ValidationError&&(null==(i=e.errors)?void 0:i.length)>0?e:new Error("ELEMENT_NOT_ADDED")}}removeElement(e){const t=this.getTrackById(e.getTrackId());if(!t)return!1;try{const i=new ElementRemover(t),r=e.accept(i);if(r){const t=this.getTimelineData();t&&this.setTimelineData({tracks:t.tracks,updatePlayerData:!0}),this.emit("element:removed",{elementId:e.getId(),trackId:e.getTrackId()})}return r}catch(e){return!1}}updateElement(e){const t=this.getTrackById(e.getTrackId());if(!t)return e;try{const i=new ElementUpdater(t);if(e.accept(i)){const t=this.getTimelineData();t&&this.setTimelineData({tracks:t.tracks,updatePlayerData:!0}),this.emit("element:updated",{element:e})}return e}catch(t){return e}}async splitElement(e,t){const i=this.getTrackById(e.getTrackId());if(!i)return{firstElement:e,secondElement:null,success:!1};if(!canSplitElement(e,t))return{firstElement:e,secondElement:null,success:!1};try{const r=new ElementSplitter(t),n=e.accept(r);if(n.success&&n.firstElement&&n.secondElement){const t=new ElementRemover(i),r=new ElementAdder(i);let s=!1,o=!1;try{if(e.accept(t),s=await n.firstElement.accept(r),!s)throw new Error("Failed to add first split element");if(o=await n.secondElement.accept(r),!o)throw new Error("Failed to add second split element")}catch(i){o&&n.secondElement.accept(t),s&&n.firstElement.accept(t);try{await e.accept(r)}catch(e){}return{firstElement:e,secondElement:null,success:!1}}const a=this.getTimelineData();a&&this.setTimelineData({tracks:a.tracks,updatePlayerData:!0})}return n}catch(t){return{firstElement:e,secondElement:null,success:!1}}}cloneElement(e){try{const t=new ElementCloner;return e.accept(t)}catch(e){return null}}reorderTracks(e){this.setTimelineData({tracks:e,updatePlayerData:!0}),this.emit("track:reordered",{tracks:e.map((e=>e.serialize()))})}async moveElementToNewTrackAt(e,t,i){if(!this.removeElement(e))return!1;const r=this.getTimelineData(),n=(null==r?void 0:r.tracks)??[],s=e.getType().toLowerCase();let o=TRACK_TYPES.ELEMENT;"video"===s||"image"===s?o=TRACK_TYPES.VIDEO:"audio"===s?o=TRACK_TYPES.AUDIO:"caption"!==s&&"text"!==s||(o=TRACK_TYPES.ELEMENT);const a=new Track(`${o.charAt(0).toUpperCase()+o.slice(1)} Track`,o),l=e.getStart(),c=e.getEnd(),u=c-l;e.setStart(i),e.setEnd(i+u),this.adjustCaptionWordsForTimeChange(e,l,c);const d=new ElementAdder(a);await e.accept(d);const h=Math.max(0,Math.min(t,n.length)),p=[...n.slice(0,h),a,...n.slice(h)];return this.setTimelineData({tracks:p,updatePlayerData:!0}),this.emit("element:added",{element:e,trackId:a.getId()}),this.emit("element:updated",{element:e}),!0}updateHistory(e){const t=e.tracks.map((e=>e.serialize()));this.totalDuration=getTotalDuration(t),this.context.setTotalDuration(this.totalDuration);const i=e.version;this.context.setPresent({tracks:t,version:i,...void 0!==e.backgroundColor&&{backgroundColor:e.backgroundColor},...void 0!==e.metadata&&{metadata:e.metadata}})}undo(){var e;const t=this.context.handleUndo();if(t&&t.tracks){const i=t.tracks.map((e=>Track.fromJSON(e)));timelineContextStore.setTimelineData(this.context.contextId,{tracks:i,version:t.version,...void 0!==t.backgroundColor&&{backgroundColor:t.backgroundColor},...void 0!==t.metadata&&{metadata:t.metadata}}),this.totalDuration=getTotalDuration(t.tracks),this.context.setTotalDuration(this.totalDuration),this.context.updateChangeLog(),(null==(e=this.context)?void 0:e.setTimelineAction)&&this.context.setTimelineAction(TIMELINE_ACTION.UPDATE_PLAYER_DATA,{tracks:t.tracks,version:t.version,...void 0!==t.backgroundColor&&{backgroundColor:t.backgroundColor},...void 0!==t.metadata&&{metadata:t.metadata}})}}redo(){var e;const t=this.context.handleRedo();if(t&&t.tracks){const i=t.tracks.map((e=>Track.fromJSON(e)));timelineContextStore.setTimelineData(this.context.contextId,{tracks:i,version:t.version,...void 0!==t.backgroundColor&&{backgroundColor:t.backgroundColor},...void 0!==t.metadata&&{metadata:t.metadata}}),this.totalDuration=getTotalDuration(t.tracks),this.context.setTotalDuration(this.totalDuration),this.context.updateChangeLog(),(null==(e=this.context)?void 0:e.setTimelineAction)&&this.context.setTimelineAction(TIMELINE_ACTION.UPDATE_PLAYER_DATA,{tracks:t.tracks,version:t.version,...void 0!==t.backgroundColor&&{backgroundColor:t.backgroundColor},...void 0!==t.metadata&&{metadata:t.metadata}})}}resetHistory(){var e;this.context.handleResetHistory(),timelineContextStore.setTimelineData(this.context.contextId,{tracks:[],version:0,metadata:void 0}),this.context.setTotalDuration(0),this.context.updateChangeLog(),(null==(e=this.context)?void 0:e.setTimelineAction)&&this.context.setTimelineAction(TIMELINE_ACTION.UPDATE_PLAYER_DATA,{tracks:[],version:0,metadata:void 0})}loadProject({tracks:e,version:t,backgroundColor:i,metadata:r}){var n;const s=migrateProject({tracks:e,version:t,backgroundColor:i,metadata:r},2);this.pauseVideo(),this.context.handleResetHistory();const o=s.tracks.map((e=>Track.fromJSON(e)));this.setTimelineData({tracks:o,version:s.version,backgroundColor:s.backgroundColor,metadata:s.metadata,updatePlayerData:!0}),(null==(n=this.context)?void 0:n.setTimelineAction)&&this.context.setTimelineAction(TIMELINE_ACTION.UPDATE_PLAYER_DATA,{tracks:s.tracks,version:s.version,backgroundColor:s.backgroundColor,metadata:s.metadata,forceUpdate:!0}),this.emit("project:loaded",{tracks:s.tracks,version:s.version})}loadProjectSnapshot({tracks:e,version:t,backgroundColor:i,metadata:r}){const n=migrateProject({tracks:e,version:t,backgroundColor:i,metadata:r},2),s=n.tracks.map((e=>Track.fromJSON(e)));this.setTimelineData({tracks:s,version:n.version,backgroundColor:n.backgroundColor,metadata:n.metadata,updatePlayerData:!0}),this.emit("project:loaded",{tracks:n.tracks,version:n.version})}getWatermark(){const e=this.getTimelineData();return(null==e?void 0:e.watermark)||null}setWatermark(e){const t=this.getTimelineData();t&&this.setTimelineData({tracks:t.tracks,updatePlayerData:!0,watermark:e})}removeWatermark(){const e=this.getTimelineData();e&&this.setTimelineData({tracks:e.tracks,updatePlayerData:!0})}async getVideoAudio(){var e;const t=(null==(e=this.getTimelineData())?void 0:e.tracks)||[];return await extractVideoAudio(t,this.totalDuration)}addTransition(e,t,i,r){const n=this.findElementById(e);if(!n)return!1;const s={toElementId:t,duration:r,kind:i};return n.setTransition(s),this.updateElement(n),!0}removeTransition(e){const t=this.findElementById(e);return!!t&&(t.setTransition(void 0),this.updateElement(t),!0)}findElementById(e){var t;const i=(null==(t=this.getTimelineData())?void 0:t.tracks)??[];for(const t of i){const i=t.getElementById(e);if(i)return i}return null}getProject(){var e,t;const i=this.getTimelineData();return i?{tracks:i.tracks.map((e=>e.serialize())),version:i.version,watermark:null!=i.watermark?null==(t=(e=i.watermark).toJSON)?void 0:t.call(e):void 0,...void 0!==i.backgroundColor&&{backgroundColor:i.backgroundColor},...void 0!==i.metadata&&{metadata:i.metadata}}:{tracks:[],version:0}}getBackgroundColor(){var e;return null==(e=this.getTimelineData())?void 0:e.backgroundColor}setBackgroundColor(e){const t=this.getTimelineData();t&&this.setTimelineData({tracks:t.tracks,backgroundColor:e,metadata:t.metadata,updatePlayerData:!0})}getMetadata(){var e;return null==(e=this.getTimelineData())?void 0:e.metadata}setMetadata(e){const t=this.getTimelineData();t&&this.setTimelineData({tracks:t.tracks,backgroundColor:t.backgroundColor,metadata:e,updatePlayerData:!0})}async rippleDelete(e,t){var i;if(e>=t)return;const r=t-e,n=(null==(i=this.getTimelineData())?void 0:i.tracks)??[],s=[];for(const i of n){const n=Track.fromJSON(i.serialize()),o=n.createFriend(),a=n.getElements();for(const i of a){const n=i.getStart(),s=i.getEnd();if(!(s<=e))if(n>=t)i.setStart(n-r),i.setEnd(s-r);else if(n>=e&&s<=t)o.removeElement(i);else if(n<e&&s>t){const r=new ElementSplitter(e),n=i.accept(r);o.removeElement(i),n.success&&n.firstElement&&n.secondElement&&(n.secondElement.setEnd(e+(s-t)),o.addElement(n.firstElement,!0),o.addElement(n.secondElement,!0))}else n<e&&s<=t?i.setEnd(e):n>=e&&s>t&&(i.setStart(e),i.setEnd(e+(s-t)))}s.push(n)}this.setTimelineData({tracks:s,updatePlayerData:!0})}trimElement(e,t,i){if(t>=i)return!1;const r=e.getStart(),n=e.getEnd();return!(t<r||i>n)&&(e.setStart(t),e.setEnd(i),this.updateElement(e),!0)}updateElements(e){var t,i,r;const n=this.getTimelineData();if(!n)return;const s=n.tracks;let o=!1;for(const{elementId:n,updates:a}of e)for(const e of s){const s=e.getElementById(n);if(!s)continue;const l=s.getStart(),c=s.getEnd(),u=structuredClone(s.getProps()),d=null==(t=s.getText)?void 0:t.call(s),h=structuredClone(s.getPosition()),p=s.getRotation(),g=s.getOpacity(),v={},m=s;for(const e of Object.keys(a))["id","type","s","e","t","position","rotation","opacity","props"].includes(e)||(v[e]=m[e]);try{void 0!==a.s&&s.setStart(a.s),void 0!==a.e&&s.setEnd(a.e),null!=a.props&&s.setProps(a.props),null!=a.t&&(null==(i=s.setText)||i.call(s,a.t)),null!=a.position&&s.setPosition(a.position),null!=a.rotation&&s.setRotation(a.rotation),null!=a.opacity&&s.setOpacity(a.opacity),this.adjustCaptionWordsForTimeChange(s,l,c),Object.keys(a).forEach((e=>{["id","type","s","e","t","position","rotation","opacity","props"].includes(e)||void 0===a[e]||(s[e]=a[e])}));const t=new ElementUpdater(e);if(!s.accept(t))throw new Error("ELEMENT_NOT_UPDATED");o=!0}catch(e){s.setStart(l),s.setEnd(c),s.setProps(u),void 0!==d&&(null==(r=s.setText)||r.call(s,d)),s.setPosition(h),s.setRotation(p),s.setOpacity(g),Object.keys(v).forEach((e=>{m[e]=v[e]}))}break}o&&this.setTimelineData({tracks:s,updatePlayerData:!0})}adjustCaptionWordsForTimeChange(e,t,i){var r;if("caption"!==e.getType().toLowerCase())return;const n=e.getProps()??{},s=e.getMetadata()??{},o=n.wordsMs,a=s.wordsMs,l=Array.isArray(o),c=Array.isArray(a),u=(null==(r=e.getText)?void 0:r.call(e))??"",d=String(u).split(" ").map((e=>e.trim())).filter((e=>e.length>0));if(!d.length||!l&&!c)return;const h=l?o.length:c?a.length:0,p=e.getStart(),g=e.getEnd();if(!(g>p))return;const v=i-t,m=g-p;if(h===d.length&&v>0&&m>0){const i=e=>{if(!Array.isArray(e)||0===e.length)return null;const i=1e3*v,r=1e3*m,n=1e3*t,s=1e3*p;if(Math.abs(v-m)<1e-6){const t=s-n;return e.map((e=>e+t))}return e.map((e=>{const t=i?(e-n)/i:0,o=Math.max(0,Math.min(1,t));return s+o*r}))},r=i(o),l=i(a);return r&&(n.wordsMs=r,e.setProps(n)),void(l&&(s.wordsMs=l,e.setMetadata(s)))}const f=1e3*(g-p),_=1e3*p,E=d.map((e=>e.replace(/\s+/g,"").length||1)),y=E.reduce(((e,t)=>e+t),0);if(y<=0)return;let b=0;const w=E.map((e=>{const t=_+b/y*f;return b+=e,t}));l&&(n.wordsMs=w,e.setProps(n)),c&&(s.wordsMs=w,e.setMetadata(s))}removeElements(e){const t=this.getTimelineData();if(!t)return;const i=t.tracks,r=new Set(e);let n=!1;for(const e of i){const t=e.getElements();for(const i of t)if(r.has(i.getId())){const t=new ElementRemover(e);i.accept(t),n=!0}}n&&(this.setTimelineData({tracks:i,updatePlayerData:!0}),this.emit("elements:removed",{elementIds:e}))}replaceElementsBySource(e,t){var i,r;const n=this.getTimelineData();if(!n)return 0;const s=n.tracks;let o=0;for(const n of s){const s=n.getElements();for(const a of s){if(((null==(i=a.getProps())?void 0:i.src)??(null==(r=a.getSrc)?void 0:r.call(a)))!==e)continue;const s=ElementDeserializer.fromJSON(t);if(!s)continue;s.setId(a.getId()),s.setStart(a.getStart()),s.setEnd(a.getEnd()),s.setTrackId(n.getId());const l=n.createFriend();l.removeElement(a),l.addElement(s,!0),o++}}return o>0&&this.setTimelineData({tracks:s,updatePlayerData:!0}),o}centerElementInScene(e,t,i){var r,n,s,o,a,l;const c=this.findElementById(e);if(!c)return!1;const u=c.getProps()??{},d=t/2-(u.width??(null==(s=null==(n=null==(r=c.getFrame)?void 0:r.call(c))?void 0:n.size)?void 0:s[0])??0)/2,h=i/2-(u.height??(null==(l=null==(a=null==(o=c.getFrame)?void 0:o.call(c))?void 0:a.size)?void 0:l[1])??0)/2;return c.setPosition({x:d,y:h}),this.updateElement(c),!0}scaleElementToFit(e,t,i){var r,n,s,o;const a=this.findElementById(e);if(!a)return!1;const l=a.getProps()??{},c=null==(r=a.getFrame)?void 0:r.call(a),u=l.width??(null==(n=null==c?void 0:c.size)?void 0:n[0])??t,d=l.height??(null==(s=null==c?void 0:c.size)?void 0:s[1])??i;if(u<=0||d<=0)return!1;const h=Math.min(t/u,i/d),p=u*h,g=d*h;c&&Array.isArray(c.size)?null==(o=a.setFrame)||o.call(a,{...c,size:[p,g]}):a.setProps({...l,width:p,height:g});const v=t/2-p/2,m=i/2-g/2;return a.setPosition({x:v,y:m}),this.updateElement(a),!0}async duplicateElements(e){const t=this.getTimelineData();if(!t)return[];const i=t.tracks,r=[],n=new ElementCloner;for(const t of e)for(const e of i){const i=e.getElementById(t);if(!i)continue;const s=i.accept(n);if(s){s.setId(`e-${generateShortUuid()}`);const t=new ElementAdder(e);await s.accept(t)&&r.push(s)}break}return r.length>0&&this.setTimelineData({tracks:i,updatePlayerData:!0}),r}}const MAX_HISTORY=20,deepClone=e=>JSON.parse(JSON.stringify(e)),UndoRedoContext=React.createContext(void 0),STORAGE_KEY_PREFIX="twick_undo_redo_",isBrowser="undefined"!=typeof window&&void 0!==window.localStorage,saveToStorage=(e,t)=>{if(isBrowser)try{window.localStorage.setItem(e,JSON.stringify(t))}catch(e){console.warn("Failed to save undo-redo state to localStorage:",e)}},loadFromStorage=e=>{if(!isBrowser)return null;try{const t=window.localStorage.getItem(e);return t?JSON.parse(t):null}catch(e){return console.warn("Failed to load undo-redo state from localStorage:",e),null}},UndoRedoProvider=({children:e,persistenceKey:t,maxHistorySize:i=20})=>{const[r,n]=React.useState((()=>{if(t){const e=loadFromStorage("twick_undo_redo_"+t);if(e)return{past:e.past,present:e.present,future:e.future}}return{past:[],present:null,future:[]}})),s=e=>{t&&saveToStorage("twick_undo_redo_"+t,e)},o={canUndo:r.past.length>0,canRedo:r.future.length>0,present:r.present,setPresent:e=>{n((t=>{let r=[...t.past];t.present&&r.push(deepClone(t.present));const n={past:r,present:deepClone(e),future:[]};return n.past.length>i&&n.past.shift(),s(n),n}))},undo:()=>{let e=null;return n((t=>{if(0===t.past.length)return t;const i=t.past[t.past.length-1],r={past:t.past.slice(0,-1),present:i,future:t.present?[deepClone(t.present),...t.future]:t.future};return e=i,s(r),r})),e},redo:()=>{let e=null;return n((t=>{if(0===t.future.length)return t;const r=t.future[0],n={past:t.present?[...t.past,deepClone(t.present)]:t.past,present:r,future:t.future.slice(1)};return n.past.length>i&&n.past.shift(),e=r,s(n),n})),e},resetHistory:()=>{n({past:[],present:null,future:[]}),t&&isBrowser&&window.localStorage.removeItem("twick_undo_redo_"+t)},getLastPersistedState:()=>{if(t){const e=loadFromStorage("twick_undo_redo_"+t);return(null==e?void 0:e.present)||null}return null},disablePersistence:()=>{t&&isBrowser&&window.localStorage.removeItem("twick_undo_redo_"+t)}};return jsxRuntime.jsx(UndoRedoContext.Provider,{value:o,children:e})},useUndoRedo=()=>{const e=React.useContext(UndoRedoContext);if(void 0===e)throw new Error("useUndoRedo must be used within an UndoRedoProvider");return e};function resolveId(e,t){if(isTrackId(e))return t.find((t=>t.getId()===e))??null;for(const i of t){const t=i.getElementById(e);if(t)return t}return null}function resolveIds(e,t){const i=[];for(const r of e){const e=resolveId(r,t);e&&i.push(e)}return i}function getElementIdsInRange(e,t,i){const r=e.getElements(),n=r.findIndex((e=>e.getId()===t)),s=r.findIndex((e=>e.getId()===i));if(-1===n||-1===s)return[];const[o,a]=n<=s?[n,s]:[s,n];return r.slice(o,a+1).map((e=>e.getId()))}const editorRegistry=new Map;"undefined"!=typeof window&&(window.twickTimelineEditors=editorRegistry);var t="undefined"!=typeof window?window:void 0,i="undefined"!=typeof globalThis?globalThis:t;"undefined"==typeof self&&(i.self=i),"undefined"==typeof File&&(i.File=function(){});var e=Array.prototype,r=e.forEach,s=e.indexOf,n=null==i?void 0:i.navigator,o=null==i?void 0:i.document,a=null==i?void 0:i.location,l=null==i?void 0:i.fetch,u=null!=i&&i.XMLHttpRequest&&"withCredentials"in new i.XMLHttpRequest?i.XMLHttpRequest:void 0,h=null==i?void 0:i.AbortController,d=null==n?void 0:n.userAgent,v=null!=t?t:{},c={DEBUG:!1,LIB_VERSION:"1.335.5"};function f(e,t,i,r,n,s,o){try{var a=e[s](o),l=a.value}catch(e){return void i(e)}a.done?t(l):Promise.resolve(l).then(r,n)}function p(e){return function(){var t=this,i=arguments;return new Promise((function(r,n){var s=e.apply(t,i);function o(e){f(s,r,n,o,a,"next",e)}function a(e){f(s,r,n,o,a,"throw",e)}o(void 0)}))}}function g(){return g=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var i=arguments[t];for(var r in i)({}).hasOwnProperty.call(i,r)&&(e[r]=i[r])}return e},g.apply(null,arguments)}function _(e,t){if(null==e)return{};var i={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(-1!==t.indexOf(r))continue;i[r]=e[r]}return i}var m=["amazonbot","amazonproductbot","app.hypefactors.com","applebot","archive.org_bot","awariobot","backlinksextendedbot","baiduspider","bingbot","bingpreview","chrome-lighthouse","dataforseobot","deepscan","duckduckbot","facebookexternal","facebookcatalog","http://yandex.com/bots","hubspot","ia_archiver","leikibot","linkedinbot","meta-externalagent","mj12bot","msnbot","nessus","petalbot","pinterest","prerender","rogerbot","screaming frog","sebot-wa","sitebulb","slackbot","slurp","trendictionbot","turnitin","twitterbot","vercel-screenshot","vercelbot","yahoo! slurp","yandexbot","zoombot","bot.htm","bot.php","(bot;","bot/","crawler","ahrefsbot","ahrefssiteaudit","semrushbot","siteauditbot","splitsignalbot","gptbot","oai-searchbot","chatgpt-user","perplexitybot","better uptime bot","sentryuptimebot","uptimerobot","headlesschrome","cypress","google-hoteladsverifier","adsbot-google","apis-google","duplexweb-google","feedfetcher-google","google favicon","google web preview","google-read-aloud","googlebot","googleother","google-cloudvertexbot","googleweblight","mediapartners-google","storebot-google","google-inspectiontool","bytespider"],y=function(e,t){if(void 0===t&&(t=[]),!e)return!1;var i=e.toLowerCase();return m.concat(t).some((e=>{var t=e.toLowerCase();return-1!==i.indexOf(t)}))},b=["$snapshot","$pageview","$pageleave","$set","survey dismissed","survey sent","survey shown","$identify","$groupidentify","$create_alias","$$client_ingestion_warning","$web_experiment_applied","$feature_enrollment_update","$feature_flag_called"];function w(e,t){return-1!==e.indexOf(t)}var x=function(e){return e.trim()},E=function(e){return e.replace(/^\$/,"")},S=Array.isArray,k=Object.prototype,P=k.hasOwnProperty,T=k.toString,I=S||function(e){return"[object Array]"===T.call(e)},C=e=>"function"==typeof e,R=e=>e===Object(e)&&!I(e),F=e=>{if(R(e)){for(var t in e)if(P.call(e,t))return!1;return!0}return!1},M=e=>void 0===e,O=e=>"[object String]"==T.call(e),A=e=>O(e)&&0===e.trim().length,D=e=>null===e,j=e=>M(e)||D(e),L=e=>"[object Number]"==T.call(e)&&e==e,N=e=>L(e)&&e>0,U=e=>"[object Boolean]"===T.call(e),z=e=>e instanceof FormData,H=e=>w(b,e);function B(e){return null===e||"object"!=typeof e}function q(e,t){return Object.prototype.toString.call(e)==="[object "+t+"]"}function W(e){return!M(Event)&&function(e,t){try{return e instanceof t}catch(e){return!1}}(e,Event)}var G=[!0,"true",1,"1","yes"],V=e=>w(G,e),J=[!1,"false",0,"0","no"];function K(e,t,i,r,n){return t>i&&(r.warn("min cannot be greater than max."),t=i),L(e)?e>i?(r.warn(" cannot be  greater than max: "+i+". Using max value instead."),i):e<t?(r.warn(" cannot be less than min: "+t+". Using min value instead."),t):e:(r.warn(" must be a number. using max or fallback. max: "+i+", fallback: "+n),K(n||i,t,i,r))}class Y{constructor(e){this.t={},this.i=e.i,this.o=K(e.bucketSize,0,100,e.h),this.m=K(e.refillRate,0,this.o,e.h),this.$=K(e.refillInterval,0,864e5,e.h)}S(e,t){var i=t-e.lastAccess,r=Math.floor(i/this.$);if(r>0){var n=r*this.m;e.tokens=Math.min(e.tokens+n,this.o),e.lastAccess=e.lastAccess+r*this.$}}consumeRateLimit(e){var t,i=Date.now(),r=String(e),n=this.t[r];return n?this.S(n,i):(n={tokens:this.o,lastAccess:i},this.t[r]=n),0===n.tokens||(n.tokens--,0===n.tokens&&(null==(t=this.i)||t.call(this,e)),0===n.tokens)}stop(){this.t={}}}var zt,Ht,Bt,X="Mobile",Q="iOS",Z="Android",tt="Tablet",it=Z+" "+tt,et="iPad",rt="Apple",st=rt+" Watch",nt="Safari",ot="BlackBerry",at="Samsung",lt=at+"Browser",ut=at+" Internet",ht="Chrome",dt=ht+" OS",vt=ht+" "+Q,ct="Internet Explorer",ft=ct+" "+X,pt="Opera",gt=pt+" Mini",_t="Edge",mt="Microsoft "+_t,yt="Firefox",bt=yt+" "+Q,wt="Nintendo",xt="PlayStation",Et="Xbox",$t=Z+" "+X,St=X+" "+nt,kt="Windows",Pt=kt+" Phone",Tt="Nokia",It="Ouya",Ct="Generic",Rt=Ct+" "+X.toLowerCase(),Ft=Ct+" "+tt.toLowerCase(),Mt="Konqueror",Ot="(\\d+(\\.\\d+)?)",At=new RegExp("Version/"+Ot),Dt=new RegExp(Et,"i"),jt=new RegExp(xt+" \\w+","i"),Lt=new RegExp(wt+" \\w+","i"),Nt=new RegExp(ot+"|PlayBook|BB10","i"),Ut={"NT3.51":"NT 3.11","NT4.0":"NT 4.0","5.0":"2000",5.1:"XP",5.2:"XP","6.0":"Vista",6.1:"7",6.2:"8",6.3:"8.1",6.4:"10","10.0":"10"},qt=(e,t)=>{return t&&w(t,rt)||w(i=e,nt)&&!w(i,ht)&&!w(i,Z);var i},Wt=function(e,t){return t=t||"",w(e," OPR/")&&w(e,"Mini")?gt:w(e," OPR/")?pt:Nt.test(e)?ot:w(e,"IE"+X)||w(e,"WPDesktop")?ft:w(e,lt)?ut:w(e,_t)||w(e,"Edg/")?mt:w(e,"FBIOS")?"Facebook "+X:w(e,"UCWEB")||w(e,"UCBrowser")?"UC Browser":w(e,"CriOS")?vt:w(e,"CrMo")||w(e,ht)?ht:w(e,Z)&&w(e,nt)?$t:w(e,"FxiOS")?bt:w(e.toLowerCase(),Mt.toLowerCase())?Mt:qt(e,t)?w(e,X)?St:nt:w(e,yt)?yt:w(e,"MSIE")||w(e,"Trident/")?ct:w(e,"Gecko")?yt:""},Gt={[ft]:[new RegExp("rv:"+Ot)],[mt]:[new RegExp(_t+"?\\/"+Ot)],[ht]:[new RegExp("("+ht+"|CrMo)\\/"+Ot)],[vt]:[new RegExp("CriOS\\/"+Ot)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+Ot)],[nt]:[At],[St]:[At],[pt]:[new RegExp("(Opera|OPR)\\/"+Ot)],[yt]:[new RegExp(yt+"\\/"+Ot)],[bt]:[new RegExp("FxiOS\\/"+Ot)],[Mt]:[new RegExp("Konqueror[:/]?"+Ot,"i")],[ot]:[new RegExp(ot+" "+Ot),At],[$t]:[new RegExp("android\\s"+Ot,"i")],[ut]:[new RegExp(lt+"\\/"+Ot)],[ct]:[new RegExp("(rv:|MSIE )"+Ot)],Mozilla:[new RegExp("rv:"+Ot)]},Vt=function(e,t){var i=Wt(e,t),r=Gt[i];if(M(r))return null;for(var n=0;n<r.length;n++){var s=r[n],o=e.match(s);if(o)return parseFloat(o[o.length-2])}return null},Jt=[[new RegExp(Et+"; "+Et+" (.*?)[);]","i"),e=>[Et,e&&e[1]||""]],[new RegExp(wt,"i"),[wt,""]],[new RegExp(xt,"i"),[xt,""]],[Nt,[ot,""]],[new RegExp(kt,"i"),(e,t)=>{if(/Phone/.test(t)||/WPDesktop/.test(t))return[Pt,""];if(new RegExp(X).test(t)&&!/IEMobile\b/.test(t))return[kt+" "+X,""];var i=/Windows NT ([0-9.]+)/i.exec(t);if(i&&i[1]){var r=i[1],n=Ut[r]||"";return/arm/i.test(t)&&(n="RT"),[kt,n]}return[kt,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,e=>{if(e&&e[3]){var t=[e[3],e[4],e[5]||"0"];return[Q,t.join(".")]}return[Q,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,e=>{var t="";return e&&e.length>=3&&(t=M(e[2])?e[3]:e[2]),["watchOS",t]}],[new RegExp("("+Z+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+Z+")","i"),e=>{if(e&&e[2]){var t=[e[2],e[3],e[4]||"0"];return[Z,t.join(".")]}return[Z,""]}],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,e=>{var t=["Mac OS X",""];if(e&&e[1]){var i=[e[1],e[2],e[3]||"0"];t[1]=i.join(".")}return t}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[dt,""]],[/Linux|debian/i,["Linux",""]]],Kt=function(e){return Lt.test(e)?wt:jt.test(e)?xt:Dt.test(e)?Et:new RegExp(It,"i").test(e)?It:new RegExp("("+Pt+"|WPDesktop)","i").test(e)?Pt:/iPad/.test(e)?et:/iPod/.test(e)?"iPod Touch":/iPhone/.test(e)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(e)?st:Nt.test(e)?ot:/(kobo)\s(ereader|touch)/i.test(e)?"Kobo":new RegExp(Tt,"i").test(e)?Tt:/(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i.test(e)||/(kf[a-z]+)( bui|\)).+silk\//i.test(e)?"Kindle Fire":/(Android|ZTE)/i.test(e)?new RegExp(X).test(e)&&!/(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(e)||/pixel[\daxl ]{1,6}/i.test(e)&&!/pixel c/i.test(e)||/(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(e)||/lmy47v/i.test(e)&&!/QTAQZ3/i.test(e)?Z:it:new RegExp("(pda|"+X+")","i").test(e)?Rt:new RegExp(tt,"i").test(e)&&!new RegExp(tt+" pc","i").test(e)?Ft:""},Yt=e=>e instanceof Error;function Xt(e){var t=globalThis._posthogChunkIds;if(t){var i=Object.keys(t);return Bt&&i.length===Ht||(Ht=i.length,Bt=i.reduce(((i,r)=>{zt||(zt={});var n=zt[r];if(n)i[n[0]]=n[1];else for(var s=e(r),o=s.length-1;o>=0;o--){var a=s[o],l=null==a?void 0:a.filename,c=t[r];if(l&&c){i[l]=c,zt[r]=[l,c];break}}return i}),{})),Bt}}class Qt{constructor(e,t,i){void 0===i&&(i=[]),this.coercers=e,this.stackParser=t,this.modifiers=i}buildFromUnknown(e,t){void 0===t&&(t={});var i=t&&t.mechanism||{handled:!0,type:"generic"},r=this.buildCoercingContext(i,t,0).apply(e),n=this.buildParsingContext(),s=this.parseStacktrace(r,n);return{$exception_list:this.convertToExceptionList(s,i),$exception_level:"error"}}modifyFrames(e){var t=this;return p((function*(){for(var i of e)i.stacktrace&&i.stacktrace.frames&&I(i.stacktrace.frames)&&(i.stacktrace.frames=yield t.applyModifiers(i.stacktrace.frames));return e}))()}coerceFallback(e){var t;return{type:"Error",value:"Unknown error",stack:null==(t=e.syntheticException)?void 0:t.stack,synthetic:!0}}parseStacktrace(e,t){var i,r;return null!=e.cause&&(i=this.parseStacktrace(e.cause,t)),""!=e.stack&&null!=e.stack&&(r=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?1:0),t.chunkIdMap)),g({},e,{cause:i,stack:r})}applyChunkIds(e,t){return e.map((e=>(e.filename&&t&&(e.chunk_id=t[e.filename]),e)))}applyCoercers(e,t){for(var i of this.coercers)if(i.match(e))return i.coerce(e,t);return this.coerceFallback(t)}applyModifiers(e){var t=this;return p((function*(){var i=e;for(var r of t.modifiers)i=yield r(i);return i}))()}convertToExceptionList(e,t){var i,r,n,s={type:e.type,value:e.value,mechanism:{type:null!==(i=t.type)&&void 0!==i?i:"generic",handled:null===(r=t.handled)||void 0===r||r,synthetic:null!==(n=e.synthetic)&&void 0!==n&&n}};e.stack&&(s.stacktrace={type:"raw",frames:e.stack});var o=[s];return null!=e.cause&&o.push(...this.convertToExceptionList(e.cause,g({},t,{handled:!0}))),o}buildParsingContext(){return{chunkIdMap:Xt(this.stackParser)}}buildCoercingContext(e,t,i){void 0===i&&(i=0);var r=(i,r)=>{if(r<=4){var n=this.buildCoercingContext(e,t,r);return this.applyCoercers(i,n)}};return g({},t,{syntheticException:0==i?t.syntheticException:void 0,mechanism:e,apply:e=>r(e,i),next:e=>r(e,i+1)})}}var Zt="?";function ti(e,t,i,r,n){var s={platform:e,filename:t,function:"<anonymous>"===i?Zt:i,in_app:!0};return M(r)||(s.lineno=r),M(n)||(s.colno=n),s}var ii=(e,t)=>{var i=-1!==e.indexOf("safari-extension"),r=-1!==e.indexOf("safari-web-extension");return i||r?[-1!==e.indexOf("@")?e.split("@")[0]:Zt,i?"safari-extension:"+t:"safari-web-extension:"+t]:[e,t]},ei=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,ri=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,si=/\((\S*)(?::(\d+))(?::(\d+))\)/,ni=(e,t)=>{var i=ei.exec(e);if(i){var[,r,n,s]=i;return ti(t,r,Zt,+n,+s)}var o=ri.exec(e);if(o){if(o[2]&&0===o[2].indexOf("eval")){var a=si.exec(o[2]);a&&(o[2]=a[1],o[3]=a[2],o[4]=a[3])}var[l,c]=ii(o[1]||Zt,o[2]);return ti(t,c,l,o[3]?+o[3]:void 0,o[4]?+o[4]:void 0)}},oi=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,ai=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,li=(e,t)=>{var i=oi.exec(e);if(i){if(i[3]&&i[3].indexOf(" > eval")>-1){var r=ai.exec(i[3]);r&&(i[1]=i[1]||"eval",i[3]=r[1],i[4]=r[2],i[5]="")}var n=i[3],s=i[1]||Zt;return[s,n]=ii(s,n),ti(t,n,s,i[4]?+i[4]:void 0,i[5]?+i[5]:void 0)}},ui=/\(error: (.*)\)/,hi=50;function di(){return function(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];return function(t,r){void 0===r&&(r=0);for(var n=[],s=t.split("\n"),o=r;o<s.length;o++){var a=s[o];if(!(a.length>1024)){var l=ui.test(a)?a.replace(ui,"$1"):a;if(!l.match(/\S*Error: /)){for(var c of i){var u=c(l,e);if(u){n.push(u);break}}if(n.length>=hi)break}}}return function(e){if(!e.length)return[];var t=Array.from(e);return t.reverse(),t.slice(0,hi).map((e=>{return g({},e,{filename:e.filename||(i=t,i[i.length-1]||{}).filename,function:e.function||Zt});var i}))}(n)}}("web:javascript",ni,li)}class vi{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,t){var i=O(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:i?e.stack:void 0,cause:e.cause?t.next(e.cause):void 0,synthetic:!1}}getType(e){return this.isDOMError(e)?"DOMError":"DOMException"}getValue(e){var t=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?t+": "+e.message:t}isDOMException(e){return q(e,"DOMException")}isDOMError(e){return q(e,"DOMError")}}class ci{match(e){return e instanceof Error}coerce(e,t){return{type:this.getType(e),value:this.getMessage(e,t),stack:this.getStack(e),cause:e.cause?t.next(e.cause):void 0,synthetic:!1}}getType(e){return e.name||e.constructor.name}getMessage(e,t){var i=e.message;return i.error&&"string"==typeof i.error.message?String(i.error.message):String(i)}getStack(e){return e.stacktrace||e.stack||void 0}}class fi{constructor(){}match(e){return q(e,"ErrorEvent")&&null!=e.error}coerce(e,t){var i;return t.apply(e.error)||{type:"ErrorEvent",value:e.message,stack:null==(i=t.syntheticException)?void 0:i.stack,synthetic:!0}}}var pi=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class gi{match(e){return"string"==typeof e}coerce(e,t){var i,[r,n]=this.getInfos(e);return{type:null!=r?r:"Error",value:null!=n?n:e,stack:null==(i=t.syntheticException)?void 0:i.stack,synthetic:!0}}getInfos(e){var t="Error",i=e,r=e.match(pi);return r&&(t=r[1],i=r[2]),[t,i]}}var _i=["fatal","error","warning","log","info","debug"];function mi(e,t){void 0===t&&(t=40);var i=Object.keys(e);if(i.sort(),!i.length)return"[object has no keys]";for(var r=i.length;r>0;r--){var n=i.slice(0,r).join(", ");if(!(n.length>t))return r===i.length||n.length<=t?n:n.slice(0,t)+"..."}return""}class yi{match(e){return"object"==typeof e&&null!==e}coerce(e,t){var i,r=this.getErrorPropertyFromObject(e);return r?t.apply(r):{type:this.getType(e),value:this.getValue(e),stack:null==(i=t.syntheticException)?void 0:i.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){return W(e)?e.constructor.name:"Error"}getValue(e){if("name"in e&&"string"==typeof e.name){var t="'"+e.name+"' captured as exception";return"message"in e&&"string"==typeof e.message&&(t+=" with message: '"+e.message+"'"),t}if("message"in e&&"string"==typeof e.message)return e.message;var i=this.getObjectClassName(e);return(i&&"Object"!==i?"'"+i+"'":"Object")+" captured as exception with keys: "+mi(e)}isSeverityLevel(e){return O(e)&&!A(e)&&_i.indexOf(e)>=0}getErrorPropertyFromObject(e){for(var t in e)if(Object.prototype.hasOwnProperty.call(e,t)){var i=e[t];if(Yt(i))return i}}getObjectClassName(e){try{var t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch(e){return}}}class bi{match(e){return W(e)}coerce(e,t){var i,r=e.constructor.name;return{type:r,value:r+" captured as exception with keys: "+mi(e),stack:null==(i=t.syntheticException)?void 0:i.stack,synthetic:!0}}}class wi{match(e){return B(e)}coerce(e,t){var i;return{type:"Error",value:"Primitive value captured as exception: "+String(e),stack:null==(i=t.syntheticException)?void 0:i.stack,synthetic:!0}}}class xi{match(e){return q(e,"PromiseRejectionEvent")}coerce(e,t){var i,r=this.getUnhandledRejectionReason(e);return B(r)?{type:"UnhandledRejection",value:"Non-Error promise rejection captured with value: "+String(r),stack:null==(i=t.syntheticException)?void 0:i.stack,synthetic:!0}:t.apply(r)}getUnhandledRejectionReason(e){if(B(e))return e;try{if("reason"in e)return e.reason;if("detail"in e&&"reason"in e.detail)return e.detail.reason}catch(e){}return e}}var Ei=function(e,i){var{debugEnabled:r}=void 0===i?{}:i,n={k:function(i){if(t&&(c.DEBUG||v.POSTHOG_DEBUG||r)&&!M(t.console)&&t.console){for(var n=("__rrweb_original__"in t.console[i]?t.console[i].__rrweb_original__:t.console[i]),s=arguments.length,o=new Array(s>1?s-1:0),a=1;a<s;a++)o[a-1]=arguments[a];n(e,...o)}},info:function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];n.k("log",...t)},warn:function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];n.k("warn",...t)},error:function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];n.k("error",...t)},critical:function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];console.error(e,...i)},uninitializedWarning:e=>{n.error("You must initialize PostHog before calling "+e)},createLogger:(t,i)=>Ei(e+" "+t,i)};return n},$i=Ei("[PostHog.js]"),Si=$i.createLogger,ki=Si("[ExternalScriptsLoader]"),Pi=(e,t,i)=>{if(e.config.disable_external_dependency_loading)return ki.warn(t+" was requested but loading of external scripts is disabled."),i("Loading of external scripts is disabled");var r=null==o?void 0:o.querySelectorAll("script");if(r)for(var n,s=function(){if(r[a].src===t){var e=r[a];return e.__posthog_loading_callback_fired?{v:i()}:(e.addEventListener("load",(t=>{e.__posthog_loading_callback_fired=!0,i(void 0,t)})),e.onerror=e=>i(e),{v:void 0})}},a=0;a<r.length;a++)if(n=s())return n.v;var l=()=>{if(!o)return i("document not found");var r=o.createElement("script");if(r.type="text/javascript",r.crossOrigin="anonymous",r.src=t,r.onload=e=>{r.__posthog_loading_callback_fired=!0,i(void 0,e)},r.onerror=e=>i(e),e.config.prepare_external_dependency_script&&(r=e.config.prepare_external_dependency_script(r)),!r)return i("prepare_external_dependency_script returned null");if("head"===e.config.external_scripts_inject_target)o.head.appendChild(r);else{var n,s=o.querySelectorAll("body > script");s.length>0?null==(n=s[0].parentNode)||n.insertBefore(r,s[0]):o.body.appendChild(r)}};null!=o&&o.body?l():null==o||o.addEventListener("DOMContentLoaded",l)};v.__PosthogExtensions__=v.__PosthogExtensions__||{},v.__PosthogExtensions__.loadExternalDependency=(e,t,i)=>{var r="/static/"+t+".js?v="+e.version;if("remote-config"===t&&(r="/array/"+e.config.token+"/config.js"),"toolbar"===t){var n=3e5;r=r+"&t="+Math.floor(Date.now()/n)*n}var s=e.requestRouter.endpointFor("assets",r);Pi(e,s,i)},v.__PosthogExtensions__.loadSiteApp=(e,t,i)=>{var r=e.requestRouter.endpointFor("api",t);Pi(e,r,i)};var Ti={};function Ii(e,t,i){if(I(e))if(r&&e.forEach===r)e.forEach(t,i);else if("length"in e&&e.length===+e.length)for(var n=0,s=e.length;n<s;n++)if(n in e&&t.call(i,e[n],n)===Ti)return}function Ci(e,t,i){if(!j(e)){if(I(e))return Ii(e,t,i);if(z(e)){for(var r of e.entries())if(t.call(i,r[1],r[0])===Ti)return}else for(var n in e)if(P.call(e,n)&&t.call(i,e[n],n)===Ti)return}}var Ri=function(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];return Ii(i,(function(t){for(var i in t)void 0!==t[i]&&(e[i]=t[i])})),e},Fi=function(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];return Ii(i,(function(t){Ii(t,(function(t){e.push(t)}))})),e};function Mi(e){for(var t=Object.keys(e),i=t.length,r=new Array(i);i--;)r[i]=[t[i],e[t[i]]];return r}var Oi=function(e){try{return e()}catch(e){return}},Ai=function(e){return function(){try{for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];return e.apply(this,i)}catch(e){$i.critical("Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A."),$i.critical(e)}}},Di=function(e){var t={};return Ci(e,(function(e,i){(O(e)&&e.length>0||L(e))&&(t[i]=e)})),t};function ji(e,t){return i=e,r=e=>O(e)&&!D(t)?e.slice(0,t):e,n=new Set,function e(t,i){return t!==Object(t)?r?r(t):t:n.has(t)?void 0:(n.add(t),I(t)?(s=[],Ii(t,(t=>{s.push(e(t))}))):(s={},Ci(t,((t,i)=>{n.has(t)||(s[i]=e(t,i))}))),s);var s}(i);var i,r,n}var Li=["herokuapp.com","vercel.app","netlify.app"];function Ni(e){var t=null==e?void 0:e.hostname;if(!O(t))return!1;var i=t.split(".").slice(-2).join(".");for(var r of Li)if(i===r)return!1;return!0}function Ui(e,t){for(var i=0;i<e.length;i++)if(t(e[i]))return e[i]}function zi(e,t,i,r){var{capture:n=!1,passive:s=!0}=null!=r?r:{};null==e||e.addEventListener(t,i,{capture:n,passive:s})}var Hi="$people_distinct_id",Bi="__alias",qi="__timers",Wi="$autocapture_disabled_server_side",Gi="$heatmaps_enabled_server_side",Vi="$exception_capture_enabled_server_side",Ji="$error_tracking_suppression_rules",Ki="$error_tracking_capture_extension_exceptions",Yi="$web_vitals_enabled_server_side",Xi="$dead_clicks_enabled_server_side",Qi="$product_tours_enabled_server_side",Zi="$web_vitals_allowed_metrics",te="$session_recording_remote_config",ie="$sesid",ee="$session_is_sampled",re="$enabled_feature_flags",se="$early_access_features",ne="$feature_flag_details",oe="$stored_person_properties",ae="$stored_group_properties",le="$surveys",ue="$flag_call_reported",he="$user_state",de="$client_session_props",ve="$capture_rate_limit",ce="$initial_campaign_params",fe="$initial_referrer_info",pe="$initial_person_info",ge="$epp",_e="__POSTHOG_TOOLBAR__",me="$posthog_cookieless",ye=[Hi,Bi,"__cmpns",qi,"$session_recording_enabled_server_side",Gi,ie,re,Ji,he,se,ne,ae,oe,le,ue,de,ve,ce,fe,ge,pe,"$conversations_widget_session_id","$conversations_ticket_id","$conversations_widget_state","$conversations_user_traits"];function be(e){return e instanceof Element&&(e.id===_e||!(null==e.closest||!e.closest(".toolbar-global-fade-container")))}function we(e){return!!e&&1===e.nodeType}function xe(e,t){return!!e&&!!e.tagName&&e.tagName.toLowerCase()===t.toLowerCase()}function Ee(e){return!!e&&3===e.nodeType}function $e(e){return!!e&&11===e.nodeType}function Se(e){return e?x(e).split(/\s+/):[]}function ke(e){var i=null==t?void 0:t.location.href;return!!(i&&e&&e.some((e=>i.match(e))))}function Pe(e){var t="";switch(typeof e.className){case"string":t=e.className;break;case"object":t=(e.className&&"baseVal"in e.className?e.className.baseVal:null)||e.getAttribute("class")||"";break;default:t=""}return Se(t)}function Te(e){return j(e)?null:x(e).split(/(\s+)/).filter((e=>Ke(e))).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function Ie(e){var t="";return ze(e)&&!He(e)&&e.childNodes&&e.childNodes.length&&Ci(e.childNodes,(function(e){var i;Ee(e)&&e.textContent&&(t+=null!==(i=Te(e.textContent))&&void 0!==i?i:"")})),x(t)}function Ce(e){return M(e.target)?e.srcElement||null:null!=(t=e.target)&&t.shadowRoot?e.composedPath()[0]||null:e.target||null;var t}var Re=["a","button","form","input","select","textarea","label"];function Fe(e,t){if(M(t))return!0;var i,r=function(e){if(t.some((t=>e.matches(t))))return{v:!0}};for(var n of e)if(i=r(n))return i.v;return!1}function Me(e){var t=e.parentNode;return!(!t||!we(t))&&t}var Oe=["next","previous","prev",">","<"],Ae=10,De=[".ph-no-rageclick",".ph-no-capture"];function je(e,i){if(!t||Le(e))return!1;var r,n,s;if(U(i)?(r=!!i&&De,n=void 0):(r=null!==(s=null==i?void 0:i.css_selector_ignorelist)&&void 0!==s?s:De,n=null==i?void 0:i.content_ignorelist),!1===r)return!1;var{targetElementList:o}=Ne(e,!1);return!function(e,t){if(!1===e||M(e))return!1;var i;if(!0===e)i=Oe;else{if(!I(e))return!1;if(e.length>Ae)return $i.error("[PostHog] content_ignorelist array cannot exceed "+Ae+" items. Use css_selector_ignorelist for more complex matching."),!1;i=e.map((e=>e.toLowerCase()))}return t.some((e=>{var{safeText:t,ariaLabel:r}=e;return i.some((e=>t.includes(e)||r.includes(e)))}))}(n,o.map((e=>{var t;return{safeText:Ie(e).toLowerCase(),ariaLabel:(null==(t=e.getAttribute("aria-label"))?void 0:t.toLowerCase().trim())||""}})))&&!Fe(o,r)}var Le=e=>!e||xe(e,"html")||!we(e),Ne=(e,i)=>{if(!t||Le(e))return{parentIsUsefulElement:!1,targetElementList:[]};for(var r=!1,n=[e],s=e;s.parentNode&&!xe(s,"body");)if($e(s.parentNode))n.push(s.parentNode.host),s=s.parentNode.host;else{var o=Me(s);if(!o)break;if(i||Re.indexOf(o.tagName.toLowerCase())>-1)r=!0;else{var a=t.getComputedStyle(o);a&&"pointer"===a.getPropertyValue("cursor")&&(r=!0)}n.push(o),s=o}return{parentIsUsefulElement:r,targetElementList:n}};function Ue(e,i,r,n,s){var o,a,l,c;if(void 0===r&&(r=void 0),!t||Le(e))return!1;if(null!=(o=r)&&o.url_allowlist&&!ke(r.url_allowlist))return!1;if(null!=(a=r)&&a.url_ignorelist&&ke(r.url_ignorelist))return!1;if(null!=(l=r)&&l.dom_event_allowlist){var u=r.dom_event_allowlist;if(u&&!u.some((e=>i.type===e)))return!1}var{parentIsUsefulElement:d,targetElementList:h}=Ne(e,n);if(!function(e,t){var i=null==t?void 0:t.element_allowlist;if(M(i))return!0;var r,n=function(e){if(i.some((t=>e.tagName.toLowerCase()===t)))return{v:!0}};for(var s of e)if(r=n(s))return r.v;return!1}(h,r))return!1;if(!Fe(h,null==(c=r)?void 0:c.css_selector_allowlist))return!1;var p=t.getComputedStyle(e);if(p&&"pointer"===p.getPropertyValue("cursor")&&"click"===i.type)return!0;var g=e.tagName.toLowerCase();switch(g){case"html":return!1;case"form":return(s||["submit"]).indexOf(i.type)>=0;case"input":case"select":case"textarea":return(s||["change","click"]).indexOf(i.type)>=0;default:return d?(s||["click"]).indexOf(i.type)>=0:(s||["click"]).indexOf(i.type)>=0&&(Re.indexOf(g)>-1||"true"===e.getAttribute("contenteditable"))}}function ze(e){for(var t=e;t.parentNode&&!xe(t,"body");t=t.parentNode){var i=Pe(t);if(w(i,"ph-sensitive")||w(i,"ph-no-capture"))return!1}if(w(Pe(e),"ph-include"))return!0;var r=e.type||"";if(O(r))switch(r.toLowerCase()){case"hidden":case"password":return!1}var n=e.name||e.id||"";return!O(n)||!/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(n.replace(/[^a-zA-Z0-9]/g,""))}function He(e){return!!(xe(e,"input")&&!["button","checkbox","submit","reset"].includes(e.type)||xe(e,"select")||xe(e,"textarea")||"true"===e.getAttribute("contenteditable"))}var Be="(4[0-9]{12}(?:[0-9]{3})?)|(5[1-5][0-9]{14})|(6(?:011|5[0-9]{2})[0-9]{12})|(3[47][0-9]{13})|(3(?:0[0-5]|[68][0-9])[0-9]{11})|((?:2131|1800|35[0-9]{3})[0-9]{11})",qe=new RegExp("^(?:"+Be+")$"),We=new RegExp(Be),Ge="\\d{3}-?\\d{2}-?\\d{4}",Ve=new RegExp("^("+Ge+")$"),Je=new RegExp("("+Ge+")");function Ke(e,t){if(void 0===t&&(t=!0),j(e))return!1;if(O(e)){if(e=x(e),(t?qe:We).test((e||"").replace(/[- ]/g,"")))return!1;if((t?Ve:Je).test(e))return!1}return!0}function Ye(e){var t=Ie(e);return Ke(t=(t+" "+Xe(e)).trim())?t:""}function Xe(e){var t="";return e&&e.childNodes&&e.childNodes.length&&Ci(e.childNodes,(function(e){var i;if(e&&"span"===(null==(i=e.tagName)?void 0:i.toLowerCase()))try{var r=Ie(e);t=(t+" "+r).trim(),e.childNodes&&e.childNodes.length&&(t=(t+" "+Xe(e)).trim())}catch(e){$i.error("[AutoCapture]",e)}})),t}function Qe(e){return function(e){return e.map((e=>{var t,i,r="";if(e.tag_name&&(r+=e.tag_name),e.attr_class)for(var n of(e.attr_class.sort(),e.attr_class))r+="."+n.replace(/"/g,"");var s=g({},e.text?{text:e.text}:{},{"nth-child":null!==(t=e.nth_child)&&void 0!==t?t:0,"nth-of-type":null!==(i=e.nth_of_type)&&void 0!==i?i:0},e.href?{href:e.href}:{},e.attr_id?{attr_id:e.attr_id}:{},e.attributes),o={};return Mi(s).sort(((e,t)=>{var[i]=e,[r]=t;return i.localeCompare(r)})).forEach((e=>{var[t,i]=e;return o[Ze(t.toString())]=Ze(i.toString())})),(r+=":")+Mi(o).map((e=>{var[t,i]=e;return t+'="'+i+'"'})).join("")})).join(";")}(e.map((e=>{var t,i,r={text:null==(t=e.$el_text)?void 0:t.slice(0,400),tag_name:e.tag_name,href:null==(i=e.attr__href)?void 0:i.slice(0,2048),attr_class:tr(e),attr_id:e.attr__id,nth_child:e.nth_child,nth_of_type:e.nth_of_type,attributes:{}};return Mi(e).filter((e=>{var[t]=e;return 0===t.indexOf("attr__")})).forEach((e=>{var[t,i]=e;return r.attributes[t]=i})),r})))}function Ze(e){return e.replace(/"|\\"/g,'\\"')}function tr(e){var t=e.attr__class;return t?I(t)?t:Se(t):void 0}class ir{constructor(e){this.disabled=!1===e;var t=R(e)?e:{};this.thresholdPx=t.threshold_px||30,this.timeoutMs=t.timeout_ms||1e3,this.clickCount=t.click_count||3,this.clicks=[]}isRageClick(e,t,i){if(this.disabled)return!1;var r=this.clicks[this.clicks.length-1];if(r&&Math.abs(e-r.x)+Math.abs(t-r.y)<this.thresholdPx&&i-r.timestamp<this.timeoutMs){if(this.clicks.push({x:e,y:t,timestamp:i}),this.clicks.length===this.clickCount)return!0}else this.clicks=[{x:e,y:t,timestamp:i}];return!1}}var er=e=>{var t=null==o?void 0:o.createElement("a");return M(t)?null:(t.href=e,t)},rr=function(e,t){var i,r;void 0===t&&(t="&");var n=[];return Ci(e,(function(e,t){M(e)||M(t)||"undefined"===t||(i=encodeURIComponent(e instanceof File?e.name:e.toString()),r=encodeURIComponent(t),n[n.length]=r+"="+i)})),n.join(t)},sr=function(e,t){for(var i,r=((e.split("#")[0]||"").split(/\?(.*)/)[1]||"").replace(/^\?+/g,"").split("&"),n=0;n<r.length;n++){var s=r[n].split("=");if(s[0]===t){i=s;break}}if(!I(i)||i.length<2)return"";var o=i[1];try{o=decodeURIComponent(o)}catch(e){$i.error("Skipping decoding for malformed query param: "+o)}return o.replace(/\+/g," ")},nr=function(e,t,i){if(!e||!t||!t.length)return e;for(var r=e.split("#"),n=r[0]||"",s=r[1],o=n.split("?"),a=o[1],l=o[0],c=(a||"").split("&"),u=[],d=0;d<c.length;d++){var h=c[d].split("=");I(h)&&(t.includes(h[0])?u.push(h[0]+"="+i):u.push(c[d]))}var p=l;return null!=a&&(p+="?"+u.join("&")),null!=s&&(p+="#"+s),p},or=function(e,t){var i=e.match(new RegExp(t+"=([^&]*)"));return i?i[1]:null},ar="$copy_autocapture",lr=Si("[AutoCapture]");function ur(e,t){return t.length>e?t.slice(0,e)+"...":t}function hr(e){if(e.previousElementSibling)return e.previousElementSibling;var t=e;do{t=t.previousSibling}while(t&&!we(t));return t}function dr(e,t,i,r){var n=e.tagName.toLowerCase(),s={tag_name:n};Re.indexOf(n)>-1&&!i&&("a"===n.toLowerCase()||"button"===n.toLowerCase()?s.$el_text=ur(1024,Ye(e)):s.$el_text=ur(1024,Ie(e)));var o=Pe(e);o.length>0&&(s.classes=o.filter((function(e){return""!==e}))),Ci(e.attributes,(function(i){var n;if((!He(e)||-1!==["name","id","class","aria-label"].indexOf(i.name))&&(null==r||!r.includes(i.name))&&!t&&Ke(i.value)&&(n=i.name,!O(n)||"_ngcontent"!==n.substring(0,10)&&"_nghost"!==n.substring(0,7))){var o=i.value;"class"===i.name&&(o=Se(o).join(" ")),s["attr__"+i.name]=ur(1024,o)}}));for(var a=1,l=1,c=e;c=hr(c);)a++,c.tagName===e.tagName&&l++;return s.nth_child=a,s.nth_of_type=l,s}function vr(e,i){for(var r,n,{e:s,maskAllElementAttributes:o,maskAllText:a,elementAttributeIgnoreList:l,elementsChainAsString:c}=i,u=[e],d=e;d.parentNode&&!xe(d,"body");)$e(d.parentNode)?(u.push(d.parentNode.host),d=d.parentNode.host):(u.push(d.parentNode),d=d.parentNode);var h,p=[],g={},v=!1,m=!1;if(Ci(u,(e=>{var t=ze(e);"a"===e.tagName.toLowerCase()&&(v=e.getAttribute("href"),v=t&&v&&Ke(v)&&v),w(Pe(e),"ph-no-capture")&&(m=!0),p.push(dr(e,o,a,l));var i=function(e){if(!ze(e))return{};var t={};return Ci(e.attributes,(function(e){if(e.name&&0===e.name.indexOf("data-ph-capture-attribute")){var i=e.name.replace("data-ph-capture-attribute-",""),r=e.value;i&&r&&Ke(r)&&(t[i]=r)}})),t}(e);Ri(g,i)})),m)return{props:{},explicitNoCapture:m};if(a||("a"===e.tagName.toLowerCase()||"button"===e.tagName.toLowerCase()?p[0].$el_text=Ye(e):p[0].$el_text=Ie(e)),v){var f,_;p[0].attr__href=v;var E=null==(f=er(v))?void 0:f.host,y=null==t||null==(_=t.location)?void 0:_.host;E&&y&&E!==y&&(h=v)}return{props:Ri({$event_type:s.type,$ce_version:1},c?{}:{$elements:p},{$elements_chain:Qe(p)},null!=(r=p[0])&&r.$el_text?{$el_text:null==(n=p[0])?void 0:n.$el_text}:{},h&&"click"===s.type?{$external_click_url:h}:{},g)}}class cr{constructor(e){this.P=!1,this.T=null,this.I=!1,this.instance=e,this.rageclicks=new ir(e.config.rageclick),this.C=null}get R(){var e,t,i=R(this.instance.config.autocapture)?this.instance.config.autocapture:{};return i.url_allowlist=null==(e=i.url_allowlist)?void 0:e.map((e=>new RegExp(e))),i.url_ignorelist=null==(t=i.url_ignorelist)?void 0:t.map((e=>new RegExp(e))),i}F(){if(this.isBrowserSupported()){if(t&&o){var e=e=>{e=e||(null==t?void 0:t.event);try{this.M(e)}catch(e){lr.error("Failed to capture event",e)}};if(zi(o,"submit",e,{capture:!0}),zi(o,"change",e,{capture:!0}),zi(o,"click",e,{capture:!0}),this.R.capture_copied_text){var i=e=>{e=e||(null==t?void 0:t.event),this.M(e,ar)};zi(o,"copy",i,{capture:!0}),zi(o,"cut",i,{capture:!0})}}}else lr.info("Disabling Automatic Event Collection because this browser is not supported")}startIfEnabled(){this.isEnabled&&!this.P&&(this.F(),this.P=!0)}onRemoteConfig(e){e.elementsChainAsString&&(this.I=e.elementsChainAsString),this.instance.persistence&&this.instance.persistence.register({[Wi]:!!e.autocapture_opt_out}),this.T=!!e.autocapture_opt_out,this.startIfEnabled()}setElementSelectors(e){this.C=e}getElementSelectors(e){var t,i=[];return null==(t=this.C)||t.forEach((t=>{var r=null==o?void 0:o.querySelectorAll(t);null==r||r.forEach((r=>{e===r&&i.push(t)}))})),i}get isEnabled(){var e,t,i=null==(e=this.instance.persistence)?void 0:e.props[Wi],r=this.T;if(D(r)&&!U(i)&&!this.instance.O())return!1;var n=null!==(t=this.T)&&void 0!==t?t:!!i;return!!this.instance.config.autocapture&&!n}M(e,i){if(void 0===i&&(i="$autocapture"),this.isEnabled){var r,n=Ce(e);Ee(n)&&(n=n.parentNode||null),"$autocapture"===i&&"click"===e.type&&e instanceof MouseEvent&&this.instance.config.rageclick&&null!=(r=this.rageclicks)&&r.isRageClick(e.clientX,e.clientY,e.timeStamp||(new Date).getTime())&&je(n,this.instance.config.rageclick)&&this.M(e,"$rageclick");var s=i===ar;if(n&&Ue(n,e,this.R,s,s?["copy","cut"]:void 0)){var{props:o,explicitNoCapture:a}=vr(n,{e:e,maskAllElementAttributes:this.instance.config.mask_all_element_attributes,maskAllText:this.instance.config.mask_all_text,elementAttributeIgnoreList:this.R.element_attribute_ignorelist,elementsChainAsString:this.I});if(a)return!1;var l=this.getElementSelectors(n);if(l&&l.length>0&&(o.$element_selectors=l),i===ar){var c,u=Te(null==t||null==(c=t.getSelection())?void 0:c.toString()),d=e.type||"clipboard";if(!u)return!1;o.$selected_content=u,o.$copy_type=d}return this.instance.capture(i,o),!0}}}isBrowserSupported(){return C(null==o?void 0:o.querySelectorAll)}}Math.trunc||(Math.trunc=function(e){return e<0?Math.ceil(e):Math.floor(e)}),Number.isInteger||(Number.isInteger=function(e){return L(e)&&isFinite(e)&&Math.floor(e)===e});var fr="0123456789abcdef";class pr{constructor(e){if(this.bytes=e,16!==e.length)throw new TypeError("not 128-bit length")}static fromFieldsV7(e,t,i,r){if(!Number.isInteger(e)||!Number.isInteger(t)||!Number.isInteger(i)||!Number.isInteger(r)||e<0||t<0||i<0||r<0||e>0xffffffffffff||t>4095||i>1073741823||r>4294967295)throw new RangeError("invalid field value");var n=new Uint8Array(16);return n[0]=e/Math.pow(2,40),n[1]=e/Math.pow(2,32),n[2]=e/Math.pow(2,24),n[3]=e/Math.pow(2,16),n[4]=e/Math.pow(2,8),n[5]=e,n[6]=112|t>>>8,n[7]=t,n[8]=128|i>>>24,n[9]=i>>>16,n[10]=i>>>8,n[11]=i,n[12]=r>>>24,n[13]=r>>>16,n[14]=r>>>8,n[15]=r,new pr(n)}toString(){for(var e="",t=0;t<this.bytes.length;t++)e=e+fr.charAt(this.bytes[t]>>>4)+fr.charAt(15&this.bytes[t]),3!==t&&5!==t&&7!==t&&9!==t||(e+="-");if(36!==e.length)throw new Error("Invalid UUIDv7 was generated");return e}clone(){return new pr(this.bytes.slice(0))}equals(e){return 0===this.compareTo(e)}compareTo(e){for(var t=0;t<16;t++){var i=this.bytes[t]-e.bytes[t];if(0!==i)return Math.sign(i)}return 0}}class gr{constructor(){this.A=0,this.D=0,this.j=new yr}generate(){var e=this.generateOrAbort();if(M(e)){this.A=0;var t=this.generateOrAbort();if(M(t))throw new Error("Could not generate UUID after timestamp reset");return t}return e}generateOrAbort(){var e=Date.now();if(e>this.A)this.A=e,this.L();else{if(!(e+1e4>this.A))return;this.D++,this.D>4398046511103&&(this.A++,this.L())}return pr.fromFieldsV7(this.A,Math.trunc(this.D/Math.pow(2,30)),this.D&Math.pow(2,30)-1,this.j.nextUint32())}L(){this.D=1024*this.j.nextUint32()+(1023&this.j.nextUint32())}}var _r,mr=e=>{if("undefined"!=typeof UUIDV7_DENY_WEAK_RNG&&UUIDV7_DENY_WEAK_RNG)throw new Error("no cryptographically strong RNG available");for(var t=0;t<e.length;t++)e[t]=65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random());return e};t&&!M(t.crypto)&&crypto.getRandomValues&&(mr=e=>crypto.getRandomValues(e));class yr{constructor(){this.N=new Uint32Array(8),this.U=1/0}nextUint32(){return this.U>=this.N.length&&(mr(this.N),this.U=0),this.N[this.U++]}}var br=()=>wr().toString(),wr=()=>(_r||(_r=new gr)).generate(),xr="",Er=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i;function $r(e,t){if(t){var i=function(e,t){if(void 0===t&&(t=o),xr)return xr;if(!t)return"";if(["localhost","127.0.0.1"].includes(e))return"";for(var i=e.split("."),r=Math.min(i.length,8),n="dmn_chk_"+br();!xr&&r--;){var s=i.slice(r).join("."),a=n+"=1;domain=."+s+";path=/";t.cookie=a+";max-age=3",t.cookie.includes(n)&&(t.cookie=a+";max-age=0",xr=s)}return xr}(e);if(!i){var r=(n=e.match(Er))?n[0]:"";r!==i&&$i.info("Warning: cookie subdomain discovery mismatch",r,i),i=r}return i?"; domain=."+i:""}var n;return""}var Sr={H:()=>!!o,B:function(e){$i.error("cookieStore error: "+e)},q:function(e){if(o){try{for(var t=e+"=",i=o.cookie.split(";").filter((e=>e.length)),r=0;r<i.length;r++){for(var n=i[r];" "==n.charAt(0);)n=n.substring(1,n.length);if(0===n.indexOf(t))return decodeURIComponent(n.substring(t.length,n.length))}}catch(e){}return null}},W:function(e){var t;try{t=JSON.parse(Sr.q(e))||{}}catch(e){}return t},G:function(e,t,i,r,n){if(o)try{var s="",a="",l=$r(o.location.hostname,r);if(i){var c=new Date;c.setTime(c.getTime()+24*i*60*60*1e3),s="; expires="+c.toUTCString()}n&&(a="; secure");var u=e+"="+encodeURIComponent(JSON.stringify(t))+s+"; SameSite=Lax; path=/"+l+a;return u.length>3686.4&&$i.warn("cookieStore warning: large cookie, len="+u.length),o.cookie=u,u}catch(e){return}},V:function(e,t){if(null!=o&&o.cookie)try{Sr.G(e,"",-1,t)}catch(e){return}}},kr=null,Pr={H:function(){if(!D(kr))return kr;var e=!0;if(M(t))e=!1;else try{var i="__mplssupport__";Pr.G(i,"xyz"),'"xyz"'!==Pr.q(i)&&(e=!1),Pr.V(i)}catch(t){e=!1}return e||$i.error("localStorage unsupported; falling back to cookie store"),kr=e,e},B:function(e){$i.error("localStorage error: "+e)},q:function(e){try{return null==t?void 0:t.localStorage.getItem(e)}catch(e){Pr.B(e)}return null},W:function(e){try{return JSON.parse(Pr.q(e))||{}}catch(e){}return null},G:function(e,i){try{null==t||t.localStorage.setItem(e,JSON.stringify(i))}catch(e){Pr.B(e)}},V:function(e){try{null==t||t.localStorage.removeItem(e)}catch(e){Pr.B(e)}}},Tr=["$device_id","distinct_id",ie,ee,ge,pe],Ir={},Cr={H:function(){return!0},B:function(e){$i.error("memoryStorage error: "+e)},q:function(e){return Ir[e]||null},W:function(e){return Ir[e]||null},G:function(e,t){Ir[e]=t},V:function(e){delete Ir[e]}},Rr=null,Fr={H:function(){if(!D(Rr))return Rr;if(Rr=!0,M(t))Rr=!1;else try{var e="__support__";Fr.G(e,"xyz"),'"xyz"'!==Fr.q(e)&&(Rr=!1),Fr.V(e)}catch(e){Rr=!1}return Rr},B:function(e){$i.error("sessionStorage error: ",e)},q:function(e){try{return null==t?void 0:t.sessionStorage.getItem(e)}catch(e){Fr.B(e)}return null},W:function(e){try{return JSON.parse(Fr.q(e))||null}catch(e){}return null},G:function(e,i){try{null==t||t.sessionStorage.setItem(e,JSON.stringify(i))}catch(e){Fr.B(e)}},V:function(e){try{null==t||t.sessionStorage.removeItem(e)}catch(e){Fr.B(e)}}},Mr=function(e){return e[e.PENDING=-1]="PENDING",e[e.DENIED=0]="DENIED",e[e.GRANTED=1]="GRANTED",e}({});class Or{constructor(e){this._instance=e}get R(){return this._instance.config}get consent(){return this.J()?Mr.DENIED:this.K}isOptedOut(){return"always"===this.R.cookieless_mode||this.consent===Mr.DENIED||this.consent===Mr.PENDING&&(this.R.opt_out_capturing_by_default||"on_reject"===this.R.cookieless_mode)}isOptedIn(){return!this.isOptedOut()}isExplicitlyOptedOut(){return this.consent===Mr.DENIED}optInOut(e){this.Y.G(this.X,e?1:0,this.R.cookie_expiration,this.R.cross_subdomain_cookie,this.R.secure_cookie)}reset(){this.Y.V(this.X,this.R.cross_subdomain_cookie)}get X(){var{token:e,opt_out_capturing_cookie_prefix:t,consent_persistence_name:i}=this._instance.config;return i||(t?t+e:"__ph_opt_in_out_"+e)}get K(){var e=this.Y.q(this.X);return V(e)?Mr.GRANTED:w(J,e)?Mr.DENIED:Mr.PENDING}get Y(){if(!this.Z){var e=this.R.opt_out_capturing_persistence_type;this.Z="localStorage"===e?Pr:Sr;var t="localStorage"===e?Sr:Pr;t.q(this.X)&&(this.Z.q(this.X)||this.optInOut(V(t.q(this.X))),t.V(this.X,this.R.cross_subdomain_cookie))}return this.Z}J(){return!!this.R.respect_dnt&&!!Ui([null==n?void 0:n.doNotTrack,null==n?void 0:n.msDoNotTrack,v.doNotTrack],(e=>V(e)))}}var Ar=Si("[Dead Clicks]"),Dr=()=>!0,jr=e=>{var t,i=!(null==(t=e.instance.persistence)||!t.get_property(Xi)),r=e.instance.config.capture_dead_clicks;return U(r)?r:!!R(r)||i};class Lr{get lazyLoadedDeadClicksAutocapture(){return this.tt}constructor(e,t,i){this.instance=e,this.isEnabled=t,this.onCapture=i,this.startIfEnabled()}onRemoteConfig(e){this.instance.persistence&&this.instance.persistence.register({[Xi]:null==e?void 0:e.captureDeadClicks}),this.startIfEnabled()}startIfEnabled(){this.isEnabled(this)&&this.it((()=>{this.et()}))}it(e){var t,i;null!=(t=v.__PosthogExtensions__)&&t.initDeadClicksAutocapture&&e(),null==(i=v.__PosthogExtensions__)||null==i.loadExternalDependency||i.loadExternalDependency(this.instance,"dead-clicks-autocapture",(t=>{t?Ar.error("failed to load script",t):e()}))}et(){var e;if(o){if(!this.tt&&null!=(e=v.__PosthogExtensions__)&&e.initDeadClicksAutocapture){var t=R(this.instance.config.capture_dead_clicks)?this.instance.config.capture_dead_clicks:{};t.__onCapture=this.onCapture,this.tt=v.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,t),this.tt.start(o),Ar.info("starting...")}}else Ar.error("`document` not found. Cannot start.")}stop(){this.tt&&(this.tt.stop(),this.tt=void 0,Ar.info("stopping..."))}}var Nr=Si("[ExceptionAutocapture]");class Ur{constructor(e){var i,r,n;this.rt=()=>{var e;if(t&&this.isEnabled&&null!=(e=v.__PosthogExtensions__)&&e.errorWrappingFunctions){var i=v.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,r=v.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,n=v.__PosthogExtensions__.errorWrappingFunctions.wrapConsoleError;try{!this.st&&this.R.capture_unhandled_errors&&(this.st=i(this.captureException.bind(this))),!this.nt&&this.R.capture_unhandled_rejections&&(this.nt=r(this.captureException.bind(this))),!this.ot&&this.R.capture_console_errors&&(this.ot=n(this.captureException.bind(this)))}catch(e){Nr.error("failed to start",e),this.ut()}}},this._instance=e,this.ht=!(null==(i=this._instance.persistence)||!i.props[Vi]),this.dt=new Y({refillRate:null!==(r=this._instance.config.error_tracking.__exceptionRateLimiterRefillRate)&&void 0!==r?r:1,bucketSize:null!==(n=this._instance.config.error_tracking.__exceptionRateLimiterBucketSize)&&void 0!==n?n:10,refillInterval:1e4,h:Nr}),this.R=this.vt(),this.startIfEnabledOrStop()}vt(){var e=this._instance.config.capture_exceptions,t={capture_unhandled_errors:!1,capture_unhandled_rejections:!1,capture_console_errors:!1};return R(e)?t=g({},t,e):(M(e)?this.ht:e)&&(t=g({},t,{capture_unhandled_errors:!0,capture_unhandled_rejections:!0})),t}get isEnabled(){return this.R.capture_console_errors||this.R.capture_unhandled_errors||this.R.capture_unhandled_rejections}startIfEnabledOrStop(){this.isEnabled?(Nr.info("enabled"),this.ut(),this.it(this.rt)):this.ut()}it(e){var t,i;null!=(t=v.__PosthogExtensions__)&&t.errorWrappingFunctions&&e(),null==(i=v.__PosthogExtensions__)||null==i.loadExternalDependency||i.loadExternalDependency(this._instance,"exception-autocapture",(t=>{if(t)return Nr.error("failed to load script",t);e()}))}ut(){var e,t,i;null==(e=this.st)||e.call(this),this.st=void 0,null==(t=this.nt)||t.call(this),this.nt=void 0,null==(i=this.ot)||i.call(this),this.ot=void 0}onRemoteConfig(e){var t=e.autocaptureExceptions;this.ht=!!t||!1,this._instance.persistence&&this._instance.persistence.register({[Vi]:this.ht}),this.R=this.vt(),this.startIfEnabledOrStop()}onConfigChange(){this.R=this.vt()}captureException(e){var t,i,r=null!==(t=null==e||null==(i=e.$exception_list)||null==(i=i[0])?void 0:i.type)&&void 0!==t?t:"Exception";this.dt.consumeRateLimit(r)?Nr.info("Skipping exception capture because of client rate limiting.",{exception:r}):this._instance.exceptions.sendExceptionEvent(e)}}function zr(e,t,i){try{if(!(t in e))return()=>{};var r=e[t],n=i(r);return C(n)&&(n.prototype=n.prototype||{},Object.defineProperties(n,{__posthog_wrapped__:{enumerable:!1,value:!0}})),e[t]=n,()=>{e[t]=r}}catch(e){return()=>{}}}class Hr{constructor(e){var i;this._instance=e,this.ct=(null==t||null==(i=t.location)?void 0:i.pathname)||""}get isEnabled(){return"history_change"===this._instance.config.capture_pageview}startIfEnabled(){this.isEnabled&&($i.info("History API monitoring enabled, starting..."),this.monitorHistoryChanges())}stop(){this.ft&&this.ft(),this.ft=void 0,$i.info("History API monitoring stopped")}monitorHistoryChanges(){var e,i;if(t&&t.history){var r=this;null!=(e=t.history.pushState)&&e.__posthog_wrapped__||zr(t.history,"pushState",(e=>function(t,i,n){e.call(this,t,i,n),r._t("pushState")})),null!=(i=t.history.replaceState)&&i.__posthog_wrapped__||zr(t.history,"replaceState",(e=>function(t,i,n){e.call(this,t,i,n),r._t("replaceState")})),this.yt()}}_t(e){try{var i,r=null==t||null==(i=t.location)?void 0:i.pathname;if(!r)return;r!==this.ct&&this.isEnabled&&this._instance.capture("$pageview",{navigation_type:e}),this.ct=r}catch(t){$i.error("Error capturing "+e+" pageview",t)}}yt(){if(!this.ft){var e=()=>{this._t("popstate")};zi(t,"popstate",e),this.ft=()=>{t&&t.removeEventListener("popstate",e)}}}}var Br=Si("[SegmentIntegration]");function qr(e,t){var i=e.config.segment;if(!i)return t();!function(e,t){var i=e.config.segment;if(!i)return t();var r=i=>{var r=()=>i.anonymousId()||br();e.config.get_device_id=r,i.id()&&(e.register({distinct_id:i.id(),$device_id:r()}),e.persistence.set_property(he,"identified")),t()},n=i.user();"then"in n&&C(n.then)?n.then(r):r(n)}(e,(()=>{i.register((e=>{Promise&&Promise.resolve||Br.warn("This browser does not have Promise support, and can not use the segment integration");var t=(t,i)=>{if(!i)return t;t.event.userId||t.event.anonymousId===e.get_distinct_id()||(Br.info("No userId set, resetting PostHog"),e.reset()),t.event.userId&&t.event.userId!==e.get_distinct_id()&&(Br.info("UserId set, identifying with PostHog"),e.identify(t.event.userId));var r=e.calculateEventProperties(i,t.event.properties);return t.event.properties=Object.assign({},r,t.event.properties),t};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded:()=>!0,load:()=>Promise.resolve(),track:e=>t(e,e.event.event),page:e=>t(e,"$pageview"),identify:e=>t(e,"$identify"),screen:e=>t(e,"$screen")}})(e)).then((()=>{t()}))}))}var Wr="posthog-js";function Gr(e,t){var{organization:i,projectId:r,prefix:n,severityAllowList:s=["error"],sendExceptionsToPostHog:o=!0}=void 0===t?{}:t;return t=>{var a,l,c,u,d;if("*"!==s&&!s.includes(t.level)||!e.__loaded)return t;t.tags||(t.tags={});var h=e.requestRouter.endpointFor("ui","/project/"+e.config.token+"/person/"+e.get_distinct_id());t.tags["PostHog Person URL"]=h,e.sessionRecordingStarted()&&(t.tags["PostHog Recording URL"]=e.get_session_replay_url({withTimestamp:!0}));var p=(null==(a=t.exception)?void 0:a.values)||[],v=p.map((e=>g({},e,{stacktrace:e.stacktrace?g({},e.stacktrace,{type:"raw",frames:(e.stacktrace.frames||[]).map((e=>g({},e,{platform:"web:javascript"})))}):void 0}))),m={$exception_message:(null==(l=p[0])?void 0:l.value)||t.message,$exception_type:null==(c=p[0])?void 0:c.type,$exception_level:t.level,$exception_list:v,$sentry_event_id:t.event_id,$sentry_exception:t.exception,$sentry_exception_message:(null==(u=p[0])?void 0:u.value)||t.message,$sentry_exception_type:null==(d=p[0])?void 0:d.type,$sentry_tags:t.tags};return i&&r&&(m.$sentry_url=(n||"https://sentry.io/organizations/")+i+"/issues/?project="+r+"&query="+t.event_id),o&&e.exceptions.sendExceptionEvent(m),t}}class Vr{constructor(e,t,i,r,n,s){this.name=Wr,this.setupOnce=function(o){o(Gr(e,{organization:t,projectId:i,prefix:r,severityAllowList:n,sendExceptionsToPostHog:null==s||s}))}}}var Jr=null!=t&&t.location?or(t.location.hash,"__posthog")||or(location.hash,"state"):null,Kr="_postHogToolbarParams",Yr=Si("[Toolbar]"),Xr=function(e){return e[e.UNINITIALIZED=0]="UNINITIALIZED",e[e.LOADING=1]="LOADING",e[e.LOADED=2]="LOADED",e}(Xr||{});class Qr{constructor(e){this.instance=e}bt(e){v.ph_toolbar_state=e}wt(){var e;return null!==(e=v.ph_toolbar_state)&&void 0!==e?e:Xr.UNINITIALIZED}maybeLoadToolbar(e,i,r){if(void 0===e&&(e=void 0),void 0===i&&(i=void 0),void 0===r&&(r=void 0),!t||!o)return!1;e=null!=e?e:t.location,r=null!=r?r:t.history;try{if(!i){try{t.localStorage.setItem("test","test"),t.localStorage.removeItem("test")}catch(e){return!1}i=null==t?void 0:t.localStorage}var n,s=Jr||or(e.hash,"__posthog")||or(e.hash,"state"),a=s?Oi((()=>JSON.parse(atob(decodeURIComponent(s)))))||Oi((()=>JSON.parse(decodeURIComponent(s)))):null;return a&&"ph_authorize"===a.action?((n=a).source="url",n&&Object.keys(n).length>0&&(a.desiredHash?e.hash=a.desiredHash:r?r.replaceState(r.state,"",e.pathname+e.search):e.hash="")):((n=JSON.parse(i.getItem(Kr)||"{}")).source="localstorage",delete n.userIntent),!(!n.token||this.instance.config.token!==n.token||(this.loadToolbar(n),0))}catch(e){return!1}}xt(e){var t=v.ph_load_toolbar||v.ph_load_editor;!j(t)&&C(t)?t(e,this.instance):Yr.warn("No toolbar load function found")}loadToolbar(e){var i=!(null==o||!o.getElementById(_e));if(!t||i)return!1;var r="custom"===this.instance.requestRouter.region&&this.instance.config.advanced_disable_toolbar_metrics,n=g({token:this.instance.config.token},e,{apiURL:this.instance.requestRouter.endpointFor("ui")},r?{instrument:!1}:{});if(t.localStorage.setItem(Kr,JSON.stringify(g({},n,{source:void 0}))),this.wt()===Xr.LOADED)this.xt(n);else if(this.wt()===Xr.UNINITIALIZED){var s;this.bt(Xr.LOADING),null==(s=v.__PosthogExtensions__)||null==s.loadExternalDependency||s.loadExternalDependency(this.instance,"toolbar",(e=>{if(e)return Yr.error("[Toolbar] Failed to load",e),void this.bt(Xr.UNINITIALIZED);this.bt(Xr.LOADED),this.xt(n)})),zi(t,"turbolinks:load",(()=>{this.bt(Xr.UNINITIALIZED),this.loadToolbar(n)}))}return!0}Et(e){return this.loadToolbar(e)}maybeLoadEditor(e,t,i){return void 0===e&&(e=void 0),void 0===t&&(t=void 0),void 0===i&&(i=void 0),this.maybeLoadToolbar(e,t,i)}}var Zr=Si("[TracingHeaders]");class ts{constructor(e){this.$t=void 0,this.St=void 0,this.rt=()=>{var e,t;M(this.$t)&&(null==(e=v.__PosthogExtensions__)||null==(e=e.tracingHeadersPatchFns)||e._patchXHR(this._instance.config.__add_tracing_headers||[],this._instance.get_distinct_id(),this._instance.sessionManager)),M(this.St)&&(null==(t=v.__PosthogExtensions__)||null==(t=t.tracingHeadersPatchFns)||t._patchFetch(this._instance.config.__add_tracing_headers||[],this._instance.get_distinct_id(),this._instance.sessionManager))},this._instance=e}it(e){var t,i;null!=(t=v.__PosthogExtensions__)&&t.tracingHeadersPatchFns&&e(),null==(i=v.__PosthogExtensions__)||null==i.loadExternalDependency||i.loadExternalDependency(this._instance,"tracing-headers",(t=>{if(t)return Zr.error("failed to load script",t);e()}))}startIfEnabledOrStop(){var e,t;this._instance.config.__add_tracing_headers?this.it(this.rt):(null==(e=this.$t)||e.call(this),null==(t=this.St)||t.call(this),this.$t=void 0,this.St=void 0)}}var is="https?://(.*)",es=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],rs=Fi(["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid"],es),ss="<masked>",ns=["li_fat_id"];function os(e,t,i){if(!o)return{};var r,n=t?Fi([],es,i||[]):[],s=as(nr(o.URL,n,ss),e),a=(r={},Ci(ns,(function(e){var t=Sr.q(e);r[e]=t||null})),r);return Ri(a,s)}function as(e,t){var i=rs.concat(t||[]),r={};return Ci(i,(function(t){var i=sr(e,t);r[t]=i||null})),r}function ls(e){var t,i=(t=e)?0===t.search(is+"google.([^/?]*)")?"google":0===t.search(is+"bing.com")?"bing":0===t.search(is+"yahoo.com")?"yahoo":0===t.search(is+"duckduckgo.com")?"duckduckgo":null:null,r="yahoo"!=i?"q":"p",n={};if(!D(i)){n.$search_engine=i;var s=o?sr(o.referrer,r):"";s.length&&(n.ph_keyword=s)}return n}function us(){return navigator.language||navigator.userLanguage}function hs(){return(null==o?void 0:o.referrer)||"$direct"}function ds(e,t){var i=e?Fi([],es,t||[]):[],r=null==a?void 0:a.href.substring(0,1e3);return{r:hs().substring(0,1e3),u:r?nr(r,i,ss):void 0}}function vs(e){var t,{r:i,u:r}=e,n={$referrer:i,$referring_domain:null==i?void 0:"$direct"==i?"$direct":null==(t=er(i))?void 0:t.host};if(r){n.$current_url=r;var s=er(r);n.$host=null==s?void 0:s.host,n.$pathname=null==s?void 0:s.pathname;var o=as(r);Ri(n,o)}if(i){var a=ls(i);Ri(n,a)}return n}function cs(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch(e){return}}function fs(){try{return(new Date).getTimezoneOffset()}catch(e){return}}function ps(e,i){if(!d)return{};var r,n,s,o=e?Fi([],es,i||[]):[],[l,u]=function(e){for(var t=0;t<Jt.length;t++){var[i,r]=Jt[t],n=i.exec(e),s=n&&(C(r)?r(n,e):r);if(s)return s}return["",""]}(d);return Ri(Di({$os:l,$os_version:u,$browser:Wt(d,navigator.vendor),$device:Kt(d),$device_type:(n=d,s=Kt(n),s===et||s===it||"Kobo"===s||"Kindle Fire"===s||s===Ft?tt:s===wt||s===Et||s===xt||s===It?"Console":s===st?"Wearable":s?X:"Desktop"),$timezone:cs(),$timezone_offset:fs()}),{$current_url:nr(null==a?void 0:a.href,o,ss),$host:null==a?void 0:a.host,$pathname:null==a?void 0:a.pathname,$raw_user_agent:d.length>1e3?d.substring(0,997)+"...":d,$browser_version:Vt(d,navigator.vendor),$browser_language:us(),$browser_language_prefix:(r=us(),"string"==typeof r?r.split("-")[0]:void 0),$screen_height:null==t?void 0:t.screen.height,$screen_width:null==t?void 0:t.screen.width,$viewport_height:null==t?void 0:t.innerHeight,$viewport_width:null==t?void 0:t.innerWidth,$lib:"web",$lib_version:c.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3})}var gs=Si("[Web Vitals]"),_s=9e5;class ms{constructor(e){var t;this.kt=!1,this.P=!1,this.N={url:void 0,metrics:[],firstMetricTimestamp:void 0},this.Pt=()=>{clearTimeout(this.Tt),0!==this.N.metrics.length&&(this._instance.capture("$web_vitals",this.N.metrics.reduce(((e,t)=>g({},e,{["$web_vitals_"+t.name+"_event"]:g({},t),["$web_vitals_"+t.name+"_value"]:t.value})),{})),this.N={url:void 0,metrics:[],firstMetricTimestamp:void 0})},this.It=e=>{var t,i=null==(t=this._instance.sessionManager)?void 0:t.checkAndGetSessionAndWindowId(!0);if(M(i))gs.error("Could not read session ID. Dropping metrics!");else{this.N=this.N||{url:void 0,metrics:[],firstMetricTimestamp:void 0};var r=this.Ct();M(r)||(j(null==e?void 0:e.name)||j(null==e?void 0:e.value)?gs.error("Invalid metric received",e):this.Rt&&e.value>=this.Rt?gs.error("Ignoring metric with value >= "+this.Rt,e):(this.N.url!==r&&(this.Pt(),this.Tt=setTimeout(this.Pt,this.flushToCaptureTimeoutMs)),M(this.N.url)&&(this.N.url=r),this.N.firstMetricTimestamp=M(this.N.firstMetricTimestamp)?Date.now():this.N.firstMetricTimestamp,e.attribution&&e.attribution.interactionTargetElement&&(e.attribution.interactionTargetElement=void 0),this.N.metrics.push(g({},e,{$current_url:r,$session_id:i.sessionId,$window_id:i.windowId,timestamp:Date.now()})),this.N.metrics.length===this.allowedMetrics.length&&this.Pt()))}},this.rt=()=>{if(!this.P){var e,t,i,r,n=v.__PosthogExtensions__;M(n)||M(n.postHogWebVitalsCallbacks)||({onLCP:e,onCLS:t,onFCP:i,onINP:r}=n.postHogWebVitalsCallbacks),e&&t&&i&&r?(this.allowedMetrics.indexOf("LCP")>-1&&e(this.It.bind(this)),this.allowedMetrics.indexOf("CLS")>-1&&t(this.It.bind(this)),this.allowedMetrics.indexOf("FCP")>-1&&i(this.It.bind(this)),this.allowedMetrics.indexOf("INP")>-1&&r(this.It.bind(this)),this.P=!0):gs.error("web vitals callbacks not loaded - not starting")}},this._instance=e,this.kt=!(null==(t=this._instance.persistence)||!t.props[Yi]),this.startIfEnabled()}get allowedMetrics(){var e,t,i=R(this._instance.config.capture_performance)?null==(e=this._instance.config.capture_performance)?void 0:e.web_vitals_allowed_metrics:void 0;return M(i)?(null==(t=this._instance.persistence)?void 0:t.props[Zi])||["CLS","FCP","INP","LCP"]:i}get flushToCaptureTimeoutMs(){return(R(this._instance.config.capture_performance)?this._instance.config.capture_performance.web_vitals_delayed_flush_ms:void 0)||5e3}get useAttribution(){var e=R(this._instance.config.capture_performance)?this._instance.config.capture_performance.web_vitals_attribution:void 0;return null==e||e}get Rt(){var e=R(this._instance.config.capture_performance)&&L(this._instance.config.capture_performance.__web_vitals_max_value)?this._instance.config.capture_performance.__web_vitals_max_value:_s;return 0<e&&e<=6e4?_s:e}get isEnabled(){var e=null==a?void 0:a.protocol;if("http:"!==e&&"https:"!==e)return gs.info("Web Vitals are disabled on non-http/https protocols"),!1;var t=R(this._instance.config.capture_performance)?this._instance.config.capture_performance.web_vitals:U(this._instance.config.capture_performance)?this._instance.config.capture_performance:void 0;return U(t)?t:this.kt}startIfEnabled(){this.isEnabled&&!this.P&&(gs.info("enabled, starting..."),this.it(this.rt))}onRemoteConfig(e){var t=R(e.capturePerformance)&&!!e.capturePerformance.web_vitals,i=R(e.capturePerformance)?e.capturePerformance.web_vitals_allowed_metrics:void 0;this._instance.persistence&&(this._instance.persistence.register({[Yi]:t}),this._instance.persistence.register({[Zi]:i})),this.kt=t,this.startIfEnabled()}it(e){var t,i;null!=(t=v.__PosthogExtensions__)&&t.postHogWebVitalsCallbacks?e():null==(i=v.__PosthogExtensions__)||null==i.loadExternalDependency||i.loadExternalDependency(this._instance,"web-vitals",(t=>{var i;if(t)gs.error("failed to load script",t);else{var r=null==(i=v.__PosthogExtensions__)?void 0:i.loadWebVitalsCallbacks;r?(r(this.useAttribution),e()):e()}}))}Ct(){var e=t?t.location.href:void 0;if(e){var i=this._instance.config.mask_personal_data_properties,r=this._instance.config.custom_personal_data_properties,n=i?Fi([],es,r||[]):[];return nr(e,n,ss)}gs.error("Could not determine current URL")}}var ys=Si("[Heatmaps]");function bs(e){return R(e)&&"clientX"in e&&"clientY"in e&&L(e.clientX)&&L(e.clientY)}class ws{constructor(e){var t;this.kt=!1,this.P=!1,this.Ft=null,this.instance=e,this.kt=!(null==(t=this.instance.persistence)||!t.props[Gi]),this.rageclicks=new ir(e.config.rageclick)}get flushIntervalMilliseconds(){var e=5e3;return R(this.instance.config.capture_heatmaps)&&this.instance.config.capture_heatmaps.flush_interval_milliseconds&&(e=this.instance.config.capture_heatmaps.flush_interval_milliseconds),e}get isEnabled(){return M(this.instance.config.capture_heatmaps)?M(this.instance.config.enable_heatmaps)?this.kt:this.instance.config.enable_heatmaps:!1!==this.instance.config.capture_heatmaps}startIfEnabled(){if(this.isEnabled){if(this.P)return;ys.info("starting..."),this.Mt(),this.Ot()}else{var e;clearInterval(null!==(e=this.Ft)&&void 0!==e?e:void 0),this.At(),this.getAndClearBuffer()}}onRemoteConfig(e){var t=!!e.heatmaps;this.instance.persistence&&this.instance.persistence.register({[Gi]:t}),this.kt=t,this.startIfEnabled()}getAndClearBuffer(){var e=this.N;return this.N=void 0,e}Dt(e){this.jt(e.originalEvent,"deadclick")}Ot(){this.Ft&&clearInterval(this.Ft),this.Ft="visible"===(null==o?void 0:o.visibilityState)?setInterval(this.Lt.bind(this),this.flushIntervalMilliseconds):null}Mt(){t&&o&&(this.Nt=this.Lt.bind(this),zi(t,"beforeunload",this.Nt),this.Ut=e=>this.jt(e||(null==t?void 0:t.event)),zi(o,"click",this.Ut,{capture:!0}),this.zt=e=>this.Ht(e||(null==t?void 0:t.event)),zi(o,"mousemove",this.zt,{capture:!0}),this.Bt=new Lr(this.instance,Dr,this.Dt.bind(this)),this.Bt.startIfEnabled(),this.qt=this.Ot.bind(this),zi(o,"visibilitychange",this.qt),this.P=!0)}At(){var e;t&&o&&(this.Nt&&t.removeEventListener("beforeunload",this.Nt),this.Ut&&o.removeEventListener("click",this.Ut,{capture:!0}),this.zt&&o.removeEventListener("mousemove",this.zt,{capture:!0}),this.qt&&o.removeEventListener("visibilitychange",this.qt),clearTimeout(this.Wt),null==(e=this.Bt)||e.stop(),this.P=!1)}Gt(e,i){var r=this.instance.scrollManager.scrollY(),n=this.instance.scrollManager.scrollX(),s=this.instance.scrollManager.scrollElement(),o=function(e,i,r){for(var n=e;n&&we(n)&&!xe(n,"body");){if(n===r)return!1;if(w(i,null==t?void 0:t.getComputedStyle(n).position))return!0;n=Me(n)}return!1}(Ce(e),["fixed","sticky"],s);return{x:e.clientX+(o?0:n),y:e.clientY+(o?0:r),target_fixed:o,type:i}}jt(e,t){var i;if(void 0===t&&(t="click"),!be(e.target)&&bs(e)){var r=this.Gt(e,t);null!=(i=this.rageclicks)&&i.isRageClick(e.clientX,e.clientY,(new Date).getTime())&&this.Vt(g({},r,{type:"rageclick"})),this.Vt(r)}}Ht(e){!be(e.target)&&bs(e)&&(clearTimeout(this.Wt),this.Wt=setTimeout((()=>{this.Vt(this.Gt(e,"mousemove"))}),500))}Vt(e){if(t){var i=t.location.href,r=this.instance.config.mask_personal_data_properties,n=this.instance.config.custom_personal_data_properties,s=r?Fi([],es,n||[]):[],o=nr(i,s,ss);this.N=this.N||{},this.N[o]||(this.N[o]=[]),this.N[o].push(e)}}Lt(){this.N&&!F(this.N)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}}class xs{constructor(e){this.Jt=(e,t,i)=>{i&&(i.noSessionId||i.activityTimeout||i.sessionPastMaximumLength)&&($i.info("[PageViewManager] Session rotated, clearing pageview state",{sessionId:e,changeReason:i}),this.Kt=void 0,this._instance.scrollManager.resetContext())},this._instance=e,this.Yt()}Yt(){var e;this.Xt=null==(e=this._instance.sessionManager)?void 0:e.onSessionId(this.Jt)}destroy(){var e;null==(e=this.Xt)||e.call(this),this.Xt=void 0}doPageView(e,i){var r,n=this.Qt(e,i);return this.Kt={pathname:null!==(r=null==t?void 0:t.location.pathname)&&void 0!==r?r:"",pageViewId:i,timestamp:e},this._instance.scrollManager.resetContext(),n}doPageLeave(e){var t;return this.Qt(e,null==(t=this.Kt)?void 0:t.pageViewId)}doEvent(){var e;return{$pageview_id:null==(e=this.Kt)?void 0:e.pageViewId}}Qt(e,t){var i=this.Kt;if(!i)return{$pageview_id:t};var r={$pageview_id:t,$prev_pageview_id:i.pageViewId},n=this._instance.scrollManager.getContext();if(n&&!this._instance.config.disable_scroll_properties){var{maxScrollHeight:s,lastScrollY:o,maxScrollY:a,maxContentHeight:l,lastContentY:c,maxContentY:u}=n;if(!(M(s)||M(o)||M(a)||M(l)||M(c)||M(u))){s=Math.ceil(s),o=Math.ceil(o),a=Math.ceil(a),l=Math.ceil(l),c=Math.ceil(c),u=Math.ceil(u);var d=s<=1?1:K(o/s,0,1,$i),h=s<=1?1:K(a/s,0,1,$i),p=l<=1?1:K(c/l,0,1,$i),g=l<=1?1:K(u/l,0,1,$i);r=Ri(r,{$prev_pageview_last_scroll:o,$prev_pageview_last_scroll_percentage:d,$prev_pageview_max_scroll:a,$prev_pageview_max_scroll_percentage:h,$prev_pageview_last_content:c,$prev_pageview_last_content_percentage:p,$prev_pageview_max_content:u,$prev_pageview_max_content_percentage:g})}}return i.pathname&&(r.$prev_pageview_pathname=i.pathname),i.timestamp&&(r.$prev_pageview_duration=(e.getTime()-i.timestamp.getTime())/1e3),r}}var $s=function(e){return e.GZipJS="gzip-js",e.Base64="base64",e}({}),Ss=Uint8Array,ks=Uint16Array,Ps=Uint32Array,Ts=new Ss([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Is=new Ss([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),Cs=new Ss([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Rs=function(e,t){for(var i=new ks(31),r=0;r<31;++r)i[r]=t+=1<<e[r-1];var n=new Ps(i[30]);for(r=1;r<30;++r)for(var s=i[r];s<i[r+1];++s)n[s]=s-i[r]<<5|r;return[i,n]},Fs=Rs(Ts,2),Ms=Fs[0],Os=Fs[1];Ms[28]=258,Os[258]=28;for(var As=Rs(Is,0)[1],Ds=new ks(32768),js=0;js<32768;++js){var Ls=(43690&js)>>>1|(21845&js)<<1;Ls=(61680&(Ls=(52428&Ls)>>>2|(13107&Ls)<<2))>>>4|(3855&Ls)<<4,Ds[js]=((65280&Ls)>>>8|(255&Ls)<<8)>>>1}var Ns=function(e,t,i){for(var r=e.length,n=0,s=new ks(t);n<r;++n)++s[e[n]-1];var o,a=new ks(t);for(n=0;n<t;++n)a[n]=a[n-1]+s[n-1]<<1;for(o=new ks(r),n=0;n<r;++n)o[n]=Ds[a[e[n]-1]++]>>>15-e[n];return o},Us=new Ss(288);for(js=0;js<144;++js)Us[js]=8;for(js=144;js<256;++js)Us[js]=9;for(js=256;js<280;++js)Us[js]=7;for(js=280;js<288;++js)Us[js]=8;var zs=new Ss(32);for(js=0;js<32;++js)zs[js]=5;var Hs=Ns(Us,9),Bs=Ns(zs,5),qs=function(e){return(e/8|0)+(7&e&&1)},Ws=function(e,t,i){(null==i||i>e.length)&&(i=e.length);var r=new(e instanceof ks?ks:e instanceof Ps?Ps:Ss)(i-t);return r.set(e.subarray(t,i)),r},Gs=function(e,t,i){i<<=7&t;var r=t/8|0;e[r]|=i,e[r+1]|=i>>>8},Vs=function(e,t,i){i<<=7&t;var r=t/8|0;e[r]|=i,e[r+1]|=i>>>8,e[r+2]|=i>>>16},Js=function(e,t){for(var i=[],r=0;r<e.length;++r)e[r]&&i.push({s:r,f:e[r]});var n=i.length,s=i.slice();if(!n)return[new Ss(0),0];if(1==n){var o=new Ss(i[0].s+1);return o[i[0].s]=1,[o,1]}i.sort((function(e,t){return e.f-t.f})),i.push({s:-1,f:25001});var a=i[0],l=i[1],c=0,u=1,d=2;for(i[0]={s:-1,f:a.f+l.f,l:a,r:l};u!=n-1;)a=i[i[c].f<i[d].f?c++:d++],l=i[c!=u&&i[c].f<i[d].f?c++:d++],i[u++]={s:-1,f:a.f+l.f,l:a,r:l};var h=s[0].s;for(r=1;r<n;++r)s[r].s>h&&(h=s[r].s);var p=new ks(h+1),g=Ks(i[u-1],p,0);if(g>t){r=0;var v=0,m=g-t,f=1<<m;for(s.sort((function(e,t){return p[t.s]-p[e.s]||e.f-t.f}));r<n;++r){var _=s[r].s;if(!(p[_]>t))break;v+=f-(1<<g-p[_]),p[_]=t}for(v>>>=m;v>0;){var E=s[r].s;p[E]<t?v-=1<<t-p[E]++-1:++r}for(;r>=0&&v;--r){var y=s[r].s;p[y]==t&&(--p[y],++v)}g=t}return[new Ss(p),g]},Ks=function(e,t,i){return-1==e.s?Math.max(Ks(e.l,t,i+1),Ks(e.r,t,i+1)):t[e.s]=i},Ys=function(e){for(var t=e.length;t&&!e[--t];);for(var i=new ks(++t),r=0,n=e[0],s=1,o=function(e){i[r++]=e},a=1;a<=t;++a)if(e[a]==n&&a!=t)++s;else{if(!n&&s>2){for(;s>138;s-=138)o(32754);s>2&&(o(s>10?s-11<<5|28690:s-3<<5|12305),s=0)}else if(s>3){for(o(n),--s;s>6;s-=6)o(8304);s>2&&(o(s-3<<5|8208),s=0)}for(;s--;)o(n);s=1,n=e[a]}return[i.subarray(0,r),t]},Xs=function(e,t){for(var i=0,r=0;r<t.length;++r)i+=e[r]*t[r];return i},Qs=function(e,t,i){var r=i.length,n=qs(t+2);e[n]=255&r,e[n+1]=r>>>8,e[n+2]=255^e[n],e[n+3]=255^e[n+1];for(var s=0;s<r;++s)e[n+s+4]=i[s];return 8*(n+4+r)},Zs=function(e,t,i,r,n,s,o,a,l,c,u){Gs(t,u++,i),++n[256];for(var d=Js(n,15),h=d[0],p=d[1],g=Js(s,15),v=g[0],m=g[1],f=Ys(h),_=f[0],E=f[1],y=Ys(v),b=y[0],w=y[1],T=new ks(19),k=0;k<_.length;++k)T[31&_[k]]++;for(k=0;k<b.length;++k)T[31&b[k]]++;for(var x=Js(T,7),S=x[0],P=x[1],I=19;I>4&&!S[Cs[I-1]];--I);var C,R,A,F,O=c+5<<3,M=Xs(n,Us)+Xs(s,zs)+o,D=Xs(n,h)+Xs(s,v)+o+14+3*I+Xs(T,S)+(2*T[16]+3*T[17]+7*T[18]);if(O<=M&&O<=D)return Qs(t,u,e.subarray(l,l+c));if(Gs(t,u,1+(D<M)),u+=2,D<M){C=Ns(h,p),R=h,A=Ns(v,m),F=v;var N=Ns(S,P);for(Gs(t,u,E-257),Gs(t,u+5,w-1),Gs(t,u+10,I-4),u+=14,k=0;k<I;++k)Gs(t,u+3*k,S[Cs[k]]);u+=3*I;for(var L=[_,b],$=0;$<2;++$){var j=L[$];for(k=0;k<j.length;++k){var z=31&j[k];Gs(t,u,N[z]),u+=S[z],z>15&&(Gs(t,u,j[k]>>>5&127),u+=j[k]>>>12)}}}else C=Hs,R=Us,A=Bs,F=zs;for(k=0;k<a;++k)if(r[k]>255){z=r[k]>>>18&31,Vs(t,u,C[z+257]),u+=R[z+257],z>7&&(Gs(t,u,r[k]>>>23&31),u+=Ts[z]);var B=31&r[k];Vs(t,u,A[B]),u+=F[B],B>3&&(Vs(t,u,r[k]>>>5&8191),u+=Is[B])}else Vs(t,u,C[r[k]]),u+=R[r[k]];return Vs(t,u,C[256]),u+R[256]},tn=new Ps([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),en=function(){for(var e=new Ps(256),t=0;t<256;++t){for(var i=t,r=9;--r;)i=(1&i&&3988292384)^i>>>1;e[t]=i}return e}(),rn=function(e,t,i,r,n){return function(e,t,i,r,n){var s=e.length,o=new Ss(r+s+5*(1+Math.floor(s/7e3))+n),a=o.subarray(r,o.length-n),l=0;if(!t||s<8)for(var c=0;c<=s;c+=65535){var u=c+65535;u<s?l=Qs(a,l,e.subarray(c,u)):(a[c]=true,l=Qs(a,l,e.subarray(c,s)))}else{for(var d=tn[t-1],h=d>>>13,p=8191&d,g=(1<<i)-1,v=new ks(32768),m=new ks(g+1),f=Math.ceil(i/3),_=2*f,E=function(t){return(e[t]^e[t+1]<<f^e[t+2]<<_)&g},y=new Ps(25e3),b=new ks(288),w=new ks(32),T=0,k=0,x=(c=0,0),S=0,P=0;c<s;++c){var I=E(c),C=32767&c,R=m[I];if(v[C]=R,m[I]=C,S<=c){var A=s-c;if((T>7e3||x>24576)&&A>423){l=Zs(e,a,0,y,b,w,k,x,P,c-P,l),x=T=k=0,P=c;for(var F=0;F<286;++F)b[F]=0;for(F=0;F<30;++F)w[F]=0}var O=2,M=0,D=p,N=C-R&32767;if(A>2&&I==E(c-N))for(var L=Math.min(h,A)-1,$=Math.min(32767,c),j=Math.min(258,A);N<=$&&--D&&C!=R;){if(e[c+O]==e[c+O-N]){for(var z=0;z<j&&e[c+z]==e[c+z-N];++z);if(z>O){if(O=z,M=N,z>L)break;var B=Math.min(N,z-2),V=0;for(F=0;F<B;++F){var U=c-N+F+32768&32767,H=U-v[U]+32768&32767;H>V&&(V=H,R=U)}}}N+=(C=R)-(R=v[C])+32768&32767}if(M){y[x++]=268435456|Os[O]<<18|As[M];var W=31&Os[O],Y=31&As[M];k+=Ts[W]+Is[Y],++b[257+W],++w[Y],S=c+O,++T}else y[x++]=e[c],++b[e[c]]}}l=Zs(e,a,true,y,b,w,k,x,P,c-P,l)}return Ws(o,0,r+qs(l)+n)}(e,null==t.level?6:t.level,null==t.mem?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(e.length)))):12+t.mem,i,r)},sn=function(e,t,i){for(;i;++t)e[t]=i,i>>>=8};function nn(e,t){void 0===t&&(t={});var i=function(){var e=4294967295;return{p:function(t){for(var i=e,r=0;r<t.length;++r)i=en[255&i^t[r]]^i>>>8;e=i},d:function(){return 4294967295^e}}}(),r=e.length;i.p(e);var n,s=rn(e,t,10+((n=t).filename&&n.filename.length+1||0),8),o=s.length;return function(e,t){var i=t.filename;if(e[0]=31,e[1]=139,e[2]=8,e[8]=t.level<2?4:9==t.level?2:0,e[9]=3,0!=t.mtime&&sn(e,4,Math.floor(new Date(t.mtime||Date.now())/1e3)),i){e[3]=8;for(var r=0;r<=i.length;++r)e[r+10]=i.charCodeAt(r)}}(s,t),sn(s,o-8,i.d()),sn(s,o-4,r),s}var on=function(e){var t,i,r,n,s="";for(t=i=0,r=(e=(e+"").replace(/\r\n/g,"\n").replace(/\r/g,"\n")).length,n=0;n<r;n++){var o=e.charCodeAt(n),a=null;o<128?i++:a=o>127&&o<2048?String.fromCharCode(o>>6|192,63&o|128):String.fromCharCode(o>>12|224,o>>6&63|128,63&o|128),D(a)||(i>t&&(s+=e.substring(t,i)),s+=a,t=i=n+1)}return i>t&&(s+=e.substring(t,e.length)),s},an=!!u||!!l,ln="text/plain",un=function(e,t,i){var r;void 0===i&&(i=!0);var[n,s]=e.split("?"),o=g({},t),a=null!==(r=null==s?void 0:s.split("&").map((e=>{var t,[r,n]=e.split("="),s=i&&null!==(t=o[r])&&void 0!==t?t:n;return delete o[r],r+"="+s})))&&void 0!==r?r:[],l=rr(o);return l&&a.push(l),n+"?"+a.join("&")},hn=(e,t)=>JSON.stringify(e,((e,t)=>"bigint"==typeof t?t.toString():t),t),dn=e=>{var t,{data:i,compression:r}=e;if(i){if(r===$s.GZipJS){var n=nn(function(e){var t=e.length;if("undefined"!=typeof TextEncoder)return(new TextEncoder).encode(e);for(var i=new Ss(e.length+(e.length>>>1)),r=0,n=function(e){i[r++]=e},s=0;s<t;++s){if(r+5>i.length){var o=new Ss(r+8+(t-s<<1));o.set(i),i=o}var a=e.charCodeAt(s);a<128?n(a):a<2048?(n(192|a>>>6),n(128|63&a)):a>55295&&a<57344?(n(240|(a=65536+(1047552&a)|1023&e.charCodeAt(++s))>>>18),n(128|a>>>12&63),n(128|a>>>6&63),n(128|63&a)):(n(224|a>>>12),n(128|a>>>6&63),n(128|63&a))}return Ws(i,0,r)}(hn(i)),{mtime:0}),s=new Blob([n],{type:ln});return{contentType:ln,body:s,estimatedSize:s.size}}if(r===$s.Base64){var o=function(e){var t,i,r,n,s,o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",a=0,l=0,c="",u=[];if(!e)return e;e=on(e);do{t=(s=e.charCodeAt(a++)<<16|e.charCodeAt(a++)<<8|e.charCodeAt(a++))>>18&63,i=s>>12&63,r=s>>6&63,n=63&s,u[l++]=o.charAt(t)+o.charAt(i)+o.charAt(r)+o.charAt(n)}while(a<e.length);switch(c=u.join(""),e.length%3){case 1:c=c.slice(0,-2)+"==";break;case 2:c=c.slice(0,-1)+"="}return c}(hn(i)),a=(t=o,"data="+encodeURIComponent("string"==typeof t?t:hn(t)));return{contentType:"application/x-www-form-urlencoded",body:a,estimatedSize:new Blob([a]).size}}var l=hn(i);return{contentType:"application/json",body:l,estimatedSize:new Blob([l]).size}}},vn=[];l&&vn.push({transport:"fetch",method:e=>{var t,i,{contentType:r,body:n,estimatedSize:s}=null!==(t=dn(e))&&void 0!==t?t:{},o=new Headers;Ci(e.headers,(function(e,t){o.append(t,e)})),r&&o.append("Content-Type",r);var a=e.url,c=null;if(h){var u=new h;c={signal:u.signal,timeout:setTimeout((()=>u.abort()),e.timeout)}}l(a,g({method:(null==e?void 0:e.method)||"GET",headers:o,keepalive:"POST"===e.method&&(s||0)<52428.8,body:n,signal:null==(i=c)?void 0:i.signal},e.fetchOptions)).then((t=>t.text().then((i=>{var r={statusCode:t.status,text:i};if(200===t.status)try{r.json=JSON.parse(i)}catch(e){$i.error(e)}null==e.callback||e.callback(r)})))).catch((t=>{$i.error(t),null==e.callback||e.callback({statusCode:0,text:t})})).finally((()=>c?clearTimeout(c.timeout):null))}}),u&&vn.push({transport:"XHR",method:e=>{var t,i=new u;i.open(e.method||"GET",e.url,!0);var{contentType:r,body:n}=null!==(t=dn(e))&&void 0!==t?t:{};Ci(e.headers,(function(e,t){i.setRequestHeader(t,e)})),r&&i.setRequestHeader("Content-Type",r),e.timeout&&(i.timeout=e.timeout),e.disableXHRCredentials||(i.withCredentials=!0),i.onreadystatechange=()=>{if(4===i.readyState){var t={statusCode:i.status,text:i.responseText};if(200===i.status)try{t.json=JSON.parse(i.responseText)}catch(e){}null==e.callback||e.callback(t)}},i.send(n)}}),null!=n&&n.sendBeacon&&vn.push({transport:"sendBeacon",method:e=>{var t=un(e.url,{beacon:"1"});try{var i,{contentType:r,body:s}=null!==(i=dn(e))&&void 0!==i?i:{},o="string"==typeof s?new Blob([s],{type:r}):s;n.sendBeacon(t,o)}catch(e){}}});var cn=function(e,t){if(!function(e){try{new RegExp(e)}catch(e){return!1}return!0}(t))return!1;try{return new RegExp(t).test(e)}catch(e){return!1}};function fn(e,t,i){return hn({distinct_id:e,userPropertiesToSet:t,userPropertiesToSetOnce:i})}var pn={exact:(e,t)=>t.some((t=>e.some((e=>t===e)))),is_not:(e,t)=>t.every((t=>e.every((e=>t!==e)))),regex:(e,t)=>t.some((t=>e.some((e=>cn(t,e))))),not_regex:(e,t)=>t.every((t=>e.every((e=>!cn(t,e))))),icontains:(e,t)=>t.map(gn).some((t=>e.map(gn).some((e=>t.includes(e))))),not_icontains:(e,t)=>t.map(gn).every((t=>e.map(gn).every((e=>!t.includes(e))))),gt:(e,t)=>t.some((t=>{var i=parseFloat(t);return!isNaN(i)&&e.some((e=>i>parseFloat(e)))})),lt:(e,t)=>t.some((t=>{var i=parseFloat(t);return!isNaN(i)&&e.some((e=>i<parseFloat(e)))}))},gn=e=>e.toLowerCase();function _n(e,t){return!e||Object.entries(e).every((e=>{var[i,r]=e,n=null==t?void 0:t[i];if(M(n)||D(n))return!1;var s=[String(n)],o=pn[r.operator];return!!o&&o(r.values,s)}))}var mn=Si("[Error tracking]");class yn{constructor(e){var t,i;this.Zt=[],this.ti=new Qt([new vi,new xi,new fi,new ci,new bi,new yi,new gi,new wi],di()),this._instance=e,this.Zt=null!==(t=null==(i=this._instance.persistence)?void 0:i.get_property(Ji))&&void 0!==t?t:[]}onRemoteConfig(e){var t,i,r,n=null!==(t=null==(i=e.errorTracking)?void 0:i.suppressionRules)&&void 0!==t?t:[],s=null==(r=e.errorTracking)?void 0:r.captureExtensionExceptions;this.Zt=n,this._instance.persistence&&this._instance.persistence.register({[Ji]:this.Zt,[Ki]:s})}get ii(){var e,t=!!this._instance.get_property(Ki),i=this._instance.config.error_tracking.captureExtensionExceptions;return null!==(e=null!=i?i:t)&&void 0!==e&&e}buildProperties(e,t){return this.ti.buildFromUnknown(e,{syntheticException:null==t?void 0:t.syntheticException,mechanism:{handled:null==t?void 0:t.handled}})}sendExceptionEvent(e){var t=e.$exception_list;if(this.ei(t)){if(this.ri(t))return void mn.info("Skipping exception capture because a suppression rule matched");if(!this.ii&&this.si(t))return void mn.info("Skipping exception capture because it was thrown by an extension");if(!this._instance.config.error_tracking.__capturePostHogExceptions&&this.ni(t))return void mn.info("Skipping exception capture because it was thrown by the PostHog SDK")}return this._instance.capture("$exception",e,{_noTruncate:!0,_batchKey:"exceptionEvent"})}ri(e){if(0===e.length)return!1;var t=e.reduce(((e,t)=>{var{type:i,value:r}=t;return O(i)&&i.length>0&&e.$exception_types.push(i),O(r)&&r.length>0&&e.$exception_values.push(r),e}),{$exception_types:[],$exception_values:[]});return this.Zt.some((e=>{var i=e.values.map((e=>{var i,r=pn[e.operator],n=I(e.value)?e.value:[e.value],s=null!==(i=t[e.key])&&void 0!==i?i:[];return n.length>0&&r(n,s)}));return"OR"===e.type?i.some(Boolean):i.every(Boolean)}))}si(e){return e.flatMap((e=>{var t,i;return null!==(t=null==(i=e.stacktrace)?void 0:i.frames)&&void 0!==t?t:[]})).some((e=>e.filename&&e.filename.startsWith("chrome-extension://")))}ni(e){if(e.length>0){var t,i,r,n,s=null!==(t=null==(i=e[0].stacktrace)?void 0:i.frames)&&void 0!==t?t:[],o=s[s.length-1];return null!==(r=null==o||null==(n=o.filename)?void 0:n.includes("posthog.com/static"))&&void 0!==r&&r}return!1}ei(e){return!j(e)&&I(e)}}var bn=Si("[FeatureFlags]"),wn=Si("[FeatureFlags]",{debugEnabled:!0}),xn="$active_feature_flags",En="$override_feature_flags",$n="$feature_flag_payloads",Sn="$override_feature_flag_payloads",kn="$feature_flag_request_id",Pn="$feature_flag_evaluated_at",Tn=e=>{var t={};for(var[i,r]of Mi(e||{}))r&&(t[i]=r);return t},In=e=>{var t=e.flags;return t?(e.featureFlags=Object.fromEntries(Object.keys(t).map((e=>{var i;return[e,null!==(i=t[e].variant)&&void 0!==i?i:t[e].enabled]}))),e.featureFlagPayloads=Object.fromEntries(Object.keys(t).filter((e=>t[e].enabled)).filter((e=>{var i;return null==(i=t[e].metadata)?void 0:i.payload})).map((e=>{var i;return[e,null==(i=t[e].metadata)?void 0:i.payload]})))):bn.warn("Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version"),e},Cn=function(e){return e.FeatureFlags="feature_flags",e.Recordings="recordings",e}({});class Rn{constructor(e){this.oi=!1,this.ai=!1,this.li=!1,this.ui=!1,this.hi=!1,this.di=!1,this.vi=!1,this.ci=!1,this._instance=e,this.featureFlagEventHandlers=[]}fi(){var e,t=null!==(e=this._instance.config.evaluation_contexts)&&void 0!==e?e:this._instance.config.evaluation_environments;return!this._instance.config.evaluation_environments||this._instance.config.evaluation_contexts||this.ci||(bn.warn("evaluation_environments is deprecated. Use evaluation_contexts instead. evaluation_environments will be removed in a future version."),this.ci=!0),null!=t&&t.length?t.filter((e=>{var t=e&&"string"==typeof e&&e.trim().length>0;return t||bn.error("Invalid evaluation context found:",e,"Expected non-empty string"),t})):[]}pi(){return this.fi().length>0}flags(){if(this._instance.config.__preview_remote_config)this.di=!0;else{var e=!this.gi&&(this._instance.config.advanced_disable_feature_flags||this._instance.config.advanced_disable_feature_flags_on_first_load);this.mi({disableFlags:e})}}get hasLoadedFlags(){return this.ai}getFlags(){return Object.keys(this.getFlagVariants())}getFlagsWithDetails(){var e=this._instance.get_property(ne),t=this._instance.get_property(En),i=this._instance.get_property(Sn);if(!i&&!t)return e||{};var r=Ri({},e||{}),n=[...new Set([...Object.keys(i||{}),...Object.keys(t||{})])];for(var s of n){var o,a,l=r[s],c=null==t?void 0:t[s],u=M(c)?null!==(o=null==l?void 0:l.enabled)&&void 0!==o&&o:!!c,d=M(c)?l.variant:"string"==typeof c?c:void 0,h=null==i?void 0:i[s],p=g({},l,{enabled:u,variant:u?null!=d?d:null==l?void 0:l.variant:void 0});u!==(null==l?void 0:l.enabled)&&(p.original_enabled=null==l?void 0:l.enabled),d!==(null==l?void 0:l.variant)&&(p.original_variant=null==l?void 0:l.variant),h&&(p.metadata=g({},null==l?void 0:l.metadata,{payload:h,original_payload:null==l||null==(a=l.metadata)?void 0:a.payload})),r[s]=p}return this.oi||(bn.warn(" Overriding feature flag details!",{flagDetails:e,overriddenPayloads:i,finalDetails:r}),this.oi=!0),r}getFlagVariants(){var e=this._instance.get_property(re),t=this._instance.get_property(En);if(!t)return e||{};for(var i=Ri({},e),r=Object.keys(t),n=0;n<r.length;n++)i[r[n]]=t[r[n]];return this.oi||(bn.warn(" Overriding feature flags!",{enabledFlags:e,overriddenFlags:t,finalFlags:i}),this.oi=!0),i}getFlagPayloads(){var e=this._instance.get_property($n),t=this._instance.get_property(Sn);if(!t)return e||{};for(var i=Ri({},e||{}),r=Object.keys(t),n=0;n<r.length;n++)i[r[n]]=t[r[n]];return this.oi||(bn.warn(" Overriding feature flag payloads!",{flagPayloads:e,overriddenPayloads:t,finalPayloads:i}),this.oi=!0),i}reloadFeatureFlags(){this.ui||this._instance.config.advanced_disable_feature_flags||this.gi||(this.gi=setTimeout((()=>{this.mi()}),5))}yi(){clearTimeout(this.gi),this.gi=void 0}ensureFlagsLoaded(){this.ai||this.li||this.gi||this.reloadFeatureFlags()}setAnonymousDistinctId(e){this.$anon_distinct_id=e}setReloadingPaused(e){this.ui=e}mi(e){var t;if(this.yi(),!this._instance.O())if(this.li)this.hi=!0;else{var i=this._instance.config.token,r=this._instance.get_property("$device_id"),n={token:i,distinct_id:this._instance.get_distinct_id(),groups:this._instance.getGroups(),$anon_distinct_id:this.$anon_distinct_id,person_properties:g({},(null==(t=this._instance.persistence)?void 0:t.get_initial_props())||{},this._instance.get_property(oe)||{}),group_properties:this._instance.get_property(ae)};D(r)||M(r)||(n.$device_id=r),(null!=e&&e.disableFlags||this._instance.config.advanced_disable_feature_flags)&&(n.disable_flags=!0),this.pi()&&(n.evaluation_contexts=this.fi());var s=this._instance.config.__preview_remote_config,o=s?"/flags/?v=2":"/flags/?v=2&config=true",a=this._instance.config.advanced_only_evaluate_survey_feature_flags?"&only_evaluate_survey_feature_flags=true":"",l=this._instance.requestRouter.endpointFor("flags",o+a);s&&(n.timezone=cs()),this.li=!0,this._instance._send_request({method:"POST",url:l,data:n,compression:this._instance.config.disable_compression?void 0:$s.Base64,timeout:this._instance.config.feature_flag_request_timeout_ms,callback:e=>{var t,i,r=!0;if(200===e.statusCode&&(this.hi||(this.$anon_distinct_id=void 0),r=!1),this.li=!1,this.di||(this.di=!0,this._instance.bi(null!==(i=e.json)&&void 0!==i?i:{})),!n.disable_flags||this.hi)if(this.vi=!r,e.json&&null!=(t=e.json.quotaLimited)&&t.includes(Cn.FeatureFlags))bn.warn("You have hit your feature flags quota limit, and will not be able to load feature flags until the quota is reset.  Please visit https://posthog.com/docs/billing/limits-alerts to learn more.");else{var s;n.disable_flags||this.receivedFeatureFlags(null!==(s=e.json)&&void 0!==s?s:{},r),this.hi&&(this.hi=!1,this.mi())}}})}}getFeatureFlag(e,t){if(void 0===t&&(t={}),this.ai||this.getFlags()&&this.getFlags().length>0){var i=this.getFlagVariants()[e],r=""+i,n=this._instance.get_property(kn)||void 0,s=this._instance.get_property(Pn)||void 0,o=this._instance.get_property(ue)||{};if((t.send_event||!("send_event"in t))&&(!(e in o)||!o[e].includes(r))){var a,l,c,u,d,h,p,g,v;I(o[e])?o[e].push(r):o[e]=[r],null==(a=this._instance.persistence)||a.register({[ue]:o});var m=this.getFeatureFlagDetails(e),f={$feature_flag:e,$feature_flag_response:i,$feature_flag_payload:this.getFeatureFlagPayload(e)||null,$feature_flag_request_id:n,$feature_flag_evaluated_at:s,$feature_flag_bootstrapped_response:(null==(l=this._instance.config.bootstrap)||null==(l=l.featureFlags)?void 0:l[e])||null,$feature_flag_bootstrapped_payload:(null==(c=this._instance.config.bootstrap)||null==(c=c.featureFlagPayloads)?void 0:c[e])||null,$used_bootstrap_value:!this.vi};M(null==m||null==(u=m.metadata)?void 0:u.version)||(f.$feature_flag_version=m.metadata.version);var _,E=null!==(d=null==m||null==(h=m.reason)?void 0:h.description)&&void 0!==d?d:null==m||null==(p=m.reason)?void 0:p.code;E&&(f.$feature_flag_reason=E),null!=m&&null!=(g=m.metadata)&&g.id&&(f.$feature_flag_id=m.metadata.id),M(null==m?void 0:m.original_variant)&&M(null==m?void 0:m.original_enabled)||(f.$feature_flag_original_response=M(m.original_variant)?m.original_enabled:m.original_variant),null!=m&&null!=(v=m.metadata)&&v.original_payload&&(f.$feature_flag_original_payload=null==m||null==(_=m.metadata)?void 0:_.original_payload),this._instance.capture("$feature_flag_called",f)}return i}bn.warn('getFeatureFlag for key "'+e+"\" failed. Feature flags didn't load in time.")}getFeatureFlagDetails(e){return this.getFlagsWithDetails()[e]}getFeatureFlagPayload(e){return this.getFlagPayloads()[e]}getRemoteConfigPayload(e,t){var i=this._instance.config.token,r={distinct_id:this._instance.get_distinct_id(),token:i};this.pi()&&(r.evaluation_contexts=this.fi()),this._instance._send_request({method:"POST",url:this._instance.requestRouter.endpointFor("flags","/flags/?v=2&config=true"),data:r,compression:this._instance.config.disable_compression?void 0:$s.Base64,timeout:this._instance.config.feature_flag_request_timeout_ms,callback:i=>{var r,n=null==(r=i.json)?void 0:r.featureFlagPayloads;t((null==n?void 0:n[e])||void 0)}})}isFeatureEnabled(e,t){if(void 0===t&&(t={}),this.ai||this.getFlags()&&this.getFlags().length>0){var i=this.getFeatureFlag(e,t);return M(i)?void 0:!!i}bn.warn('isFeatureEnabled for key "'+e+"\" failed. Feature flags didn't load in time.")}addFeatureFlagsHandler(e){this.featureFlagEventHandlers.push(e)}removeFeatureFlagsHandler(e){this.featureFlagEventHandlers=this.featureFlagEventHandlers.filter((t=>t!==e))}receivedFeatureFlags(e,t){if(this._instance.persistence){this.ai=!0;var i=this.getFlagVariants(),r=this.getFlagPayloads(),n=this.getFlagsWithDetails();!function(e,t,i,r,n){void 0===i&&(i={}),void 0===r&&(r={}),void 0===n&&(n={});var s=In(e),o=s.flags,a=s.featureFlags,l=s.featureFlagPayloads;if(a){var c=e.requestId,u=e.evaluatedAt;if(I(a)){bn.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");var d={};if(a)for(var h=0;h<a.length;h++)d[a[h]]=!0;t&&t.register({[xn]:a,[re]:d})}else{var p=a,v=l,m=o;e.errorsWhileComputingFlags&&(p=g({},i,p),v=g({},r,v),m=g({},n,m)),t&&t.register(g({[xn]:Object.keys(Tn(p)),[re]:p||{},[$n]:v||{},[ne]:m||{}},c?{[kn]:c}:{},u?{[Pn]:u}:{}))}}}(e,this._instance.persistence,i,r,n),this.wi(t)}}override(e,t){void 0===t&&(t=!1),bn.warn("override is deprecated. Please use overrideFeatureFlags instead."),this.overrideFeatureFlags({flags:e,suppressWarning:t})}overrideFeatureFlags(e){if(!this._instance.__loaded||!this._instance.persistence)return bn.uninitializedWarning("posthog.featureFlags.overrideFeatureFlags");if(!1===e)return this._instance.persistence.unregister(En),this._instance.persistence.unregister(Sn),this.wi(),wn.info("All overrides cleared");if(e&&"object"==typeof e&&("flags"in e||"payloads"in e)){var t,i=e;if(this.oi=Boolean(null!==(t=i.suppressWarning)&&void 0!==t&&t),"flags"in i)if(!1===i.flags)this._instance.persistence.unregister(En),wn.info("Flag overrides cleared");else if(i.flags){if(I(i.flags)){for(var r={},n=0;n<i.flags.length;n++)r[i.flags[n]]=!0;this._instance.persistence.register({[En]:r})}else this._instance.persistence.register({[En]:i.flags});wn.info("Flag overrides set",{flags:i.flags})}return"payloads"in i&&(!1===i.payloads?(this._instance.persistence.unregister(Sn),wn.info("Payload overrides cleared")):i.payloads&&(this._instance.persistence.register({[Sn]:i.payloads}),wn.info("Payload overrides set",{payloads:i.payloads}))),void this.wi()}this.wi()}onFeatureFlags(e){if(this.addFeatureFlagsHandler(e),this.ai){var{flags:t,flagVariants:i}=this.xi();e(t,i)}return()=>this.removeFeatureFlagsHandler(e)}updateEarlyAccessFeatureEnrollment(e,t,i){var r,n=(this._instance.get_property(se)||[]).find((t=>t.flagKey===e)),s={["$feature_enrollment/"+e]:t},o={$feature_flag:e,$feature_enrollment:t,$set:s};n&&(o.$early_access_feature_name=n.name),i&&(o.$feature_enrollment_stage=i),this._instance.capture("$feature_enrollment_update",o),this.setPersonPropertiesForFlags(s,!1);var a=g({},this.getFlagVariants(),{[e]:t});null==(r=this._instance.persistence)||r.register({[xn]:Object.keys(Tn(a)),[re]:a}),this.wi()}getEarlyAccessFeatures(e,t,i){void 0===t&&(t=!1);var r=this._instance.get_property(se),n=i?"&"+i.map((e=>"stage="+e)).join("&"):"";if(r&&!t)return e(r);this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/early_access_features/?token="+this._instance.config.token+n),method:"GET",callback:t=>{var i,r;if(t.json){var n=t.json.earlyAccessFeatures;return null==(i=this._instance.persistence)||i.unregister(se),null==(r=this._instance.persistence)||r.register({[se]:n}),e(n)}}})}xi(){var e=this.getFlags(),t=this.getFlagVariants();return{flags:e.filter((e=>t[e])),flagVariants:Object.keys(t).filter((e=>t[e])).reduce(((e,i)=>(e[i]=t[i],e)),{})}}wi(e){var{flags:t,flagVariants:i}=this.xi();this.featureFlagEventHandlers.forEach((r=>r(t,i,{errorsLoading:e})))}setPersonPropertiesForFlags(e,t){void 0===t&&(t=!0);var i=this._instance.get_property(oe)||{};this._instance.register({[oe]:g({},i,e)}),t&&this._instance.reloadFeatureFlags()}resetPersonPropertiesForFlags(){this._instance.unregister(oe)}setGroupPropertiesForFlags(e,t){void 0===t&&(t=!0);var i=this._instance.get_property(ae)||{};0!==Object.keys(i).length&&Object.keys(i).forEach((t=>{i[t]=g({},i[t],e[t]),delete e[t]})),this._instance.register({[ae]:g({},i,e)}),t&&this._instance.reloadFeatureFlags()}resetGroupPropertiesForFlags(e){if(e){var t=this._instance.get_property(ae)||{};this._instance.register({[ae]:g({},t,{[e]:{}})})}else this._instance.unregister(ae)}reset(){this.ai=!1,this.li=!1,this.ui=!1,this.hi=!1,this.di=!1,this.vi=!1,this.$anon_distinct_id=void 0,this.yi(),this.oi=!1}}var Fn=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"];class Mn{constructor(e,t){var i,r;this.R=e,this.props={},this.Ei=!1,this.$i=(r="",(i=e).token&&(r=i.token.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ")),i.persistence_name?"ph_"+i.persistence_name:"ph_"+r+"_posthog"),this.Y=this.Si(e),this.load(),e.debug&&$i.info("Persistence loaded",e.persistence,g({},this.props)),this.update_config(e,e,t),this.save()}isDisabled(){return!!this.ki}Si(e){-1===Fn.indexOf(e.persistence.toLowerCase())&&($i.critical("Unknown persistence type "+e.persistence+"; falling back to localStorage+cookie"),e.persistence="localStorage+cookie");var i=function(e){void 0===e&&(e=[]);var i=[...Tr,...e];return g({},Pr,{W:function(e){try{var t={};try{t=Sr.W(e)||{}}catch(e){}var i=Ri(t,JSON.parse(Pr.q(e)||"{}"));return Pr.G(e,i),i}catch(e){}return null},G:function(e,t,r,n,s,o){try{Pr.G(e,t,void 0,void 0,o);var a={};i.forEach((e=>{t[e]&&(a[e]=t[e])})),Object.keys(a).length&&Sr.G(e,a,r,n,s,o)}catch(e){Pr.B(e)}},V:function(e,i){try{null==t||t.localStorage.removeItem(e),Sr.V(e,i)}catch(e){Pr.B(e)}}})}(e.cookie_persisted_properties||[]),r=e.persistence.toLowerCase();return"localstorage"===r&&Pr.H()?Pr:"localstorage+cookie"===r&&i.H()?i:"sessionstorage"===r&&Fr.H()?Fr:"memory"===r?Cr:"cookie"===r?Sr:i.H()?i:Sr}properties(){var e={};return Ci(this.props,(function(t,i){if(i===re&&R(t))for(var r=Object.keys(t),n=0;n<r.length;n++)e["$feature/"+r[n]]=t[r[n]];else a=i,l=!1,(D(o=ye)?l:s&&o.indexOf===s?-1!=o.indexOf(a):(Ci(o,(function(e){if(l||(l=e===a))return Ti})),l))||(e[i]=t);var o,a,l})),e}load(){if(!this.ki){var e=this.Y.W(this.$i);e&&(this.props=Ri({},e))}}save(){this.ki||this.Y.G(this.$i,this.props,this.Pi,this.Ti,this.Ii,this.R.debug)}remove(){this.Y.V(this.$i,!1),this.Y.V(this.$i,!0)}clear(){this.remove(),this.props={}}register_once(e,t,i){if(R(e)){M(t)&&(t="None"),this.Pi=M(i)?this.Ci:i;var r=!1;if(Ci(e,((e,i)=>{this.props.hasOwnProperty(i)&&this.props[i]!==t||(this.props[i]=e,r=!0)})),r)return this.save(),!0}return!1}register(e,t){if(R(e)){this.Pi=M(t)?this.Ci:t;var i=!1;if(Ci(e,((t,r)=>{e.hasOwnProperty(r)&&this.props[r]!==t&&(this.props[r]=t,i=!0)})),i)return this.save(),!0}return!1}unregister(e){e in this.props&&(delete this.props[e],this.save())}update_campaign_params(){if(!this.Ei){var e=os(this.R.custom_campaign_params,this.R.mask_personal_data_properties,this.R.custom_personal_data_properties);F(Di(e))||this.register(e),this.Ei=!0}}update_search_keyword(){var e;this.register((e=null==o?void 0:o.referrer)?ls(e):{})}update_referrer_info(){var e;this.register_once({$referrer:hs(),$referring_domain:null!=o&&o.referrer&&(null==(e=er(o.referrer))?void 0:e.host)||"$direct"},void 0)}set_initial_person_info(){this.props[ce]||this.props[fe]||this.register_once({[pe]:ds(this.R.mask_personal_data_properties,this.R.custom_personal_data_properties)},void 0)}get_initial_props(){var e={};Ci([fe,ce],(t=>{var i=this.props[t];i&&Ci(i,(function(t,i){e["$initial_"+E(i)]=t}))}));var t,i,r=this.props[pe];if(r){var n=(t=vs(r),i={},Ci(t,(function(e,t){i["$initial_"+E(t)]=e})),i);Ri(e,n)}return e}safe_merge(e){return Ci(this.props,(function(t,i){i in e||(e[i]=t)})),e}update_config(e,t,i){if(this.Ci=this.Pi=e.cookie_expiration,this.set_disabled(e.disable_persistence||!!i),this.set_cross_subdomain(e.cross_subdomain_cookie),this.set_secure(e.secure_cookie),e.persistence!==t.persistence||!((e,t)=>{if(e.length!==t.length)return!1;var i=[...e].sort(),r=[...t].sort();return i.every(((e,t)=>e===r[t]))})(e.cookie_persisted_properties||[],t.cookie_persisted_properties||[])){var r=this.Si(e),n=this.props;this.clear(),this.Y=r,this.props=n,this.save()}}set_disabled(e){this.ki=e,this.ki?this.remove():this.save()}set_cross_subdomain(e){e!==this.Ti&&(this.Ti=e,this.remove(),this.save())}set_secure(e){e!==this.Ii&&(this.Ii=e,this.remove(),this.save())}set_event_timer(e,t){var i=this.props[qi]||{};i[e]=t,this.props[qi]=i,this.save()}remove_event_timer(e){var t=(this.props[qi]||{})[e];return M(t)||(delete this.props[qi][e],this.save()),t}get_property(e){return this.props[e]}set_property(e,t){this.props[e]=t,this.save()}}var On=Si("[Product Tours]"),An="ph_product_tours";class Dn{constructor(e){this.Ri=null,this.Fi=null,this._instance=e}onRemoteConfig(e){this._instance.persistence&&this._instance.persistence.register({[Qi]:!(null==e||!e.productTours)}),this.loadIfEnabled()}loadIfEnabled(){var e,t;this.Ri||(e=this._instance).config.disable_product_tours||null==(t=e.persistence)||!t.get_property(Qi)||this.it((()=>this.Mi()))}it(e){var t,i;null!=(t=v.__PosthogExtensions__)&&t.generateProductTours?e():null==(i=v.__PosthogExtensions__)||null==i.loadExternalDependency||i.loadExternalDependency(this._instance,"product-tours",(t=>{t?On.error("Could not load product tours script",t):e()}))}Mi(){var e;!this.Ri&&null!=(e=v.__PosthogExtensions__)&&e.generateProductTours&&(this.Ri=v.__PosthogExtensions__.generateProductTours(this._instance,!0))}getProductTours(e,t){if(void 0===t&&(t=!1),!I(this.Fi)||t){var i=this._instance.persistence;if(i){var r=i.props[An];if(I(r)&&!t)return this.Fi=r,void e(r,{isLoaded:!0})}this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/product_tours/?token="+this._instance.config.token),method:"GET",callback:t=>{var r=t.statusCode;if(200!==r||!t.json){var n="Product Tours API could not be loaded, status: "+r;return On.error(n),void e([],{isLoaded:!1,error:n})}var s=I(t.json.product_tours)?t.json.product_tours:[];this.Fi=s,i&&i.register({[An]:s}),e(s,{isLoaded:!0})}})}else e(this.Fi,{isLoaded:!0})}getActiveProductTours(e){j(this.Ri)?e([],{isLoaded:!1,error:"Product tours not loaded"}):this.Ri.getActiveProductTours(e)}showProductTour(e){var t;null==(t=this.Ri)||t.showTourById(e)}previewTour(e){this.Ri?this.Ri.previewTour(e):this.it((()=>{var t;this.Mi(),null==(t=this.Ri)||t.previewTour(e)}))}dismissProductTour(){var e;null==(e=this.Ri)||e.dismissTour("user_clicked_skip")}nextStep(){var e;null==(e=this.Ri)||e.nextStep()}previousStep(){var e;null==(e=this.Ri)||e.previousStep()}clearCache(){var e;this.Fi=null,null==(e=this._instance.persistence)||e.unregister(An)}resetTour(e){var t;null==(t=this.Ri)||t.resetTour(e)}resetAllTours(){var e;null==(e=this.Ri)||e.resetAllTours()}cancelPendingTour(e){var t;null==(t=this.Ri)||t.cancelPendingTour(e)}}var jn=function(e){return e.Activation="events",e.Cancellation="cancelEvents",e}({});!function(e){e.Button="button",e.Tab="tab",e.Selector="selector"}({}),function(e){e.TopLeft="top_left",e.TopRight="top_right",e.TopCenter="top_center",e.MiddleLeft="middle_left",e.MiddleRight="middle_right",e.MiddleCenter="middle_center",e.Left="left",e.Center="center",e.Right="right",e.NextToTrigger="next_to_trigger"}({}),function(e){e.Top="top",e.Left="left",e.Right="right",e.Bottom="bottom"}({});var zn=function(e){return e.Popover="popover",e.API="api",e.Widget="widget",e.ExternalSurvey="external_survey",e}({});!function(e){e.Open="open",e.MultipleChoice="multiple_choice",e.SingleChoice="single_choice",e.Rating="rating",e.Link="link"}({}),function(e){e.NextQuestion="next_question",e.End="end",e.ResponseBased="response_based",e.SpecificQuestion="specific_question"}({}),function(e){e.Once="once",e.Recurring="recurring",e.Always="always"}({});var Wn=function(e){return e.SHOWN="survey shown",e.DISMISSED="survey dismissed",e.SENT="survey sent",e.ABANDONED="survey abandoned",e}({}),Gn=function(e){return e.SURVEY_ID="$survey_id",e.SURVEY_NAME="$survey_name",e.SURVEY_RESPONSE="$survey_response",e.SURVEY_ITERATION="$survey_iteration",e.SURVEY_ITERATION_START_DATE="$survey_iteration_start_date",e.SURVEY_PARTIALLY_COMPLETED="$survey_partially_completed",e.SURVEY_SUBMISSION_ID="$survey_submission_id",e.SURVEY_QUESTIONS="$survey_questions",e.SURVEY_COMPLETED="$survey_completed",e.PRODUCT_TOUR_ID="$product_tour_id",e.SURVEY_LAST_SEEN_DATE="$survey_last_seen_date",e}({}),Vn=function(e){return e.Popover="popover",e.Inline="inline",e}({}),Jn=Si("[Surveys]"),Kn="seenSurvey_",Yn=(e,t)=>{var i="$survey_"+t+"/"+e.id;return e.current_iteration&&e.current_iteration>0&&(i="$survey_"+t+"/"+e.id+"/"+e.current_iteration),i},Xn=e=>{return r=""+(t=Kn)+(i=e).id,i.current_iteration&&i.current_iteration>0&&(r=""+t+i.id+"_"+i.current_iteration),r;var t,i,r},Qn=[zn.Popover,zn.Widget,zn.API],Zn={ignoreConditions:!1,ignoreDelay:!1,displayType:Vn.Popover};class to{constructor(){this.Oi={},this.Oi={}}on(e,t){return this.Oi[e]||(this.Oi[e]=[]),this.Oi[e].push(t),()=>{this.Oi[e]=this.Oi[e].filter((e=>e!==t))}}emit(e,t){for(var i of this.Oi[e]||[])i(t);for(var r of this.Oi["*"]||[])r(e,t)}}function io(e,t,i){if(j(e))return!1;switch(i){case"exact":return e===t;case"contains":var r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/_/g,".").replace(/%/g,".*");return new RegExp(r,"i").test(e);case"regex":try{return new RegExp(t).test(e)}catch(e){return!1}default:return!1}}class eo{constructor(e){this.Ai=new to,this.Di=(e,t)=>this.ji(e,t)&&this.Li(e,t)&&this.Ni(e,t)&&this.Ui(e,t),this.ji=(e,t)=>null==t||!t.event||(null==e?void 0:e.event)===(null==t?void 0:t.event),this._instance=e,this.zi=new Set,this.Hi=new Set}init(){var e,t;M(null==(e=this._instance)?void 0:e._addCaptureHook)||(null==(t=this._instance)||t._addCaptureHook(((e,t)=>{this.on(e,t)})))}register(e){var t,i;if(!M(null==(t=this._instance)?void 0:t._addCaptureHook)&&(e.forEach((e=>{var t,i;null==(t=this.Hi)||t.add(e),null==(i=e.steps)||i.forEach((e=>{var t;null==(t=this.zi)||t.add((null==e?void 0:e.event)||"")}))})),null!=(i=this._instance)&&i.autocapture)){var r,n=new Set;e.forEach((e=>{var t;null==(t=e.steps)||t.forEach((e=>{null!=e&&e.selector&&n.add(null==e?void 0:e.selector)}))})),null==(r=this._instance)||r.autocapture.setElementSelectors(n)}}on(e,t){var i;null!=t&&0!=e.length&&(this.zi.has(e)||this.zi.has(null==t?void 0:t.event))&&this.Hi&&(null==(i=this.Hi)?void 0:i.size)>0&&this.Hi.forEach((e=>{this.Bi(t,e)&&this.Ai.emit("actionCaptured",e.name)}))}qi(e){this.onAction("actionCaptured",(t=>e(t)))}Bi(e,t){if(null==(null==t?void 0:t.steps))return!1;for(var i of t.steps)if(this.Di(e,i))return!0;return!1}onAction(e,t){return this.Ai.on(e,t)}Li(e,t){if(null!=t&&t.url){var i,r=null==e||null==(i=e.properties)?void 0:i.$current_url;if(!r||"string"!=typeof r)return!1;if(!io(r,t.url,t.url_matching||"contains"))return!1}return!0}Ni(e,t){return!!this.Wi(e,t)&&!!this.Gi(e,t)&&!!this.Vi(e,t)}Wi(e,t){var i;if(null==t||!t.href)return!0;var r=this.Ji(e);if(r.length>0)return r.some((e=>io(e.href,t.href,t.href_matching||"exact")));var n,s=(null==e||null==(i=e.properties)?void 0:i.$elements_chain)||"";return!!s&&io((n=s.match(/(?::|")href="(.*?)"/))?n[1]:"",t.href,t.href_matching||"exact")}Gi(e,t){var i;if(null==t||!t.text)return!0;var r=this.Ji(e);if(r.length>0)return r.some((e=>io(e.text,t.text,t.text_matching||"exact")||io(e.$el_text,t.text,t.text_matching||"exact")));var n,s,o,a=(null==e||null==(i=e.properties)?void 0:i.$elements_chain)||"";return!!a&&(n=function(e){for(var t,i=[],r=/(?::|")text="(.*?)"/g;!j(t=r.exec(e));)i.includes(t[1])||i.push(t[1]);return i}(a),s=t.text,o=t.text_matching||"exact",n.some((e=>io(e,s,o))))}Vi(e,t){var i,r;if(null==t||!t.selector)return!0;var n=null==e||null==(i=e.properties)?void 0:i.$element_selectors;if(null!=n&&n.includes(t.selector))return!0;var s=(null==e||null==(r=e.properties)?void 0:r.$elements_chain)||"";if(t.selector_regex&&s)try{return new RegExp(t.selector_regex).test(s)}catch(e){return!1}return!1}Ji(e){var t;return null==(null==e||null==(t=e.properties)?void 0:t.$elements)?[]:null==e?void 0:e.properties.$elements}Ui(e,t){return null==t||!t.properties||0===t.properties.length||_n(t.properties.reduce(((e,t)=>{var i=I(t.value)?t.value.map(String):null!=t.value?[String(t.value)]:[];return e[t.key]={values:i,operator:t.operator||"exact"},e}),{}),null==e?void 0:e.properties)}}class ro{constructor(e){this._instance=e,this.Ki=new Map,this.Yi=new Map,this.Xi=new Map}Qi(e,t){return!!e&&_n(e.propertyFilters,null==t?void 0:t.properties)}Zi(e,t){var i=new Map;return e.forEach((e=>{var r;null==(r=e.conditions)||null==(r=r[t])||null==(r=r.values)||r.forEach((t=>{if(null!=t&&t.name){var r=i.get(t.name)||[];r.push(e.id),i.set(t.name,r)}}))})),i}te(e,t,i){var r=(i===jn.Activation?this.Ki:this.Yi).get(e),n=[];return this.ie((e=>{n=e.filter((e=>null==r?void 0:r.includes(e.id)))})),n.filter((r=>{var n,s=null==(n=r.conditions)||null==(n=n[i])||null==(n=n.values)?void 0:n.find((t=>t.name===e));return this.Qi(s,t)}))}register(e){var t;M(null==(t=this._instance)?void 0:t._addCaptureHook)||(this.ee(e),this.re(e))}re(e){var t=e.filter((e=>{var t,i;return(null==(t=e.conditions)?void 0:t.actions)&&(null==(i=e.conditions)||null==(i=i.actions)||null==(i=i.values)?void 0:i.length)>0}));0!==t.length&&(null==this.se&&(this.se=new eo(this._instance),this.se.init(),this.se.qi((e=>{this.onAction(e)}))),t.forEach((e=>{var t,i,r,n,s;e.conditions&&null!=(t=e.conditions)&&t.actions&&null!=(i=e.conditions)&&null!=(i=i.actions)&&i.values&&(null==(r=e.conditions)||null==(r=r.actions)||null==(r=r.values)?void 0:r.length)>0&&(null==(n=this.se)||n.register(e.conditions.actions.values),null==(s=e.conditions)||null==(s=s.actions)||null==(s=s.values)||s.forEach((t=>{if(t&&t.name){var i=this.Xi.get(t.name);i&&i.push(e.id),this.Xi.set(t.name,i||[e.id])}})))})))}ee(e){var t,i=e.filter((e=>{var t,i;return(null==(t=e.conditions)?void 0:t.events)&&(null==(i=e.conditions)||null==(i=i.events)||null==(i=i.values)?void 0:i.length)>0})),r=e.filter((e=>{var t,i;return(null==(t=e.conditions)?void 0:t.cancelEvents)&&(null==(i=e.conditions)||null==(i=i.cancelEvents)||null==(i=i.values)?void 0:i.length)>0}));0===i.length&&0===r.length||(null==(t=this._instance)||t._addCaptureHook(((e,t)=>{this.onEvent(e,t)})),this.Ki=this.Zi(e,jn.Activation),this.Yi=this.Zi(e,jn.Cancellation))}onEvent(e,t){var i,r=this.ne(),n=this.oe(),s=this.ae(),o=(null==(i=this._instance)||null==(i=i.persistence)?void 0:i.props[n])||[];if(s===e&&t&&o.length>0){var a,l;r.info("event matched, removing item from activated items",{event:e,eventPayload:t,existingActivatedItems:o});var c=(null==t||null==(a=t.properties)?void 0:a.$survey_id)||(null==t||null==(l=t.properties)?void 0:l.$product_tour_id);if(c){var u=o.indexOf(c);u>=0&&(o.splice(u,1),this.le(o))}}else{if(this.Yi.has(e)){var d=this.te(e,t,jn.Cancellation);d.length>0&&(r.info("cancel event matched, cancelling items",{event:e,itemsToCancel:d.map((e=>e.id))}),d.forEach((e=>{var t=o.indexOf(e.id);t>=0&&o.splice(t,1),this.ue(e.id)})),this.le(o))}if(this.Ki.has(e)){r.info("event name matched",{event:e,eventPayload:t,items:this.Ki.get(e)});var h=this.te(e,t,jn.Activation);this.le(o.concat(h.map((e=>e.id))||[]))}}}onAction(e){var t,i=this.oe(),r=(null==(t=this._instance)||null==(t=t.persistence)?void 0:t.props[i])||[];this.Xi.has(e)&&this.le(r.concat(this.Xi.get(e)||[]))}le(e){var t,i=this.ne(),r=this.oe(),n=[...new Set(e)].filter((e=>!this.he(e)));i.info("updating activated items",{activatedItems:n}),null==(t=this._instance)||null==(t=t.persistence)||t.register({[r]:n})}getActivatedIds(){var e,t=this.oe();return(null==(e=this._instance)||null==(e=e.persistence)?void 0:e.props[t])||[]}getEventToItemsMap(){return this.Ki}de(){return this.se}}class so extends ro{constructor(e){super(e)}oe(){return"$surveys_activated"}ae(){return Wn.SHOWN}ie(e){var t;null==(t=this._instance)||t.getSurveys(e)}ue(e){var t;null==(t=this._instance)||t.cancelPendingSurvey(e)}ne(){return Jn}he(){return!1}getSurveys(){return this.getActivatedIds()}getEventToSurveys(){return this.getEventToItemsMap()}}class no{constructor(e){this.ve=void 0,this._surveyManager=null,this.ce=!1,this.fe=[],this.pe=null,this._instance=e,this._surveyEventReceiver=null}onRemoteConfig(e){if(!this._instance.config.disable_surveys){var t=e.surveys;if(j(t))return Jn.warn("Flags not loaded yet. Not loading surveys.");var i=I(t);this.ve=i?t.length>0:t,Jn.info("flags response received, isSurveysEnabled: "+this.ve),this.loadIfEnabled()}}reset(){localStorage.removeItem("lastSeenSurveyDate");for(var e=[],t=0;t<localStorage.length;t++){var i=localStorage.key(t);(null!=i&&i.startsWith(Kn)||null!=i&&i.startsWith("inProgressSurvey_"))&&e.push(i)}e.forEach((e=>localStorage.removeItem(e)))}loadIfEnabled(){if(!this._surveyManager)if(this.ce)Jn.info("Already initializing surveys, skipping...");else if(this._instance.config.disable_surveys)Jn.info("Disabled. Not loading surveys.");else if(this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())Jn.info("Not loading surveys in cookieless mode without consent.");else{var e=null==v?void 0:v.__PosthogExtensions__;if(e){if(!M(this.ve)||this._instance.config.advanced_enable_surveys){var t=this.ve||this._instance.config.advanced_enable_surveys;this.ce=!0;try{var i=e.generateSurveys;if(i)return void this.ge(i,t);var r=e.loadExternalDependency;if(!r)return void this._e("PostHog loadExternalDependency extension not found.");r(this._instance,"surveys",(i=>{i||!e.generateSurveys?this._e("Could not load surveys script",i):this.ge(e.generateSurveys,t)}))}catch(e){throw this._e("Error initializing surveys",e),e}finally{this.ce=!1}}}else Jn.error("PostHog Extensions not found.")}}ge(e,t){this._surveyManager=e(this._instance,t),this._surveyEventReceiver=new so(this._instance),Jn.info("Surveys loaded successfully"),this.me({isLoaded:!0})}_e(e,t){Jn.error(e,t),this.me({isLoaded:!1,error:e})}onSurveysLoaded(e){return this.fe.push(e),this._surveyManager&&this.me({isLoaded:!0}),()=>{this.fe=this.fe.filter((t=>t!==e))}}getSurveys(e,t){if(void 0===t&&(t=!1),this._instance.config.disable_surveys)return Jn.info("Disabled. Not loading surveys."),e([]);var i,r=this._instance.get_property(le);if(r&&!t)return e(r,{isLoaded:!0});"undefined"!=typeof Promise&&this.pe?this.pe.then((t=>{var{surveys:i,context:r}=t;return e(i,r)})):("undefined"!=typeof Promise&&(this.pe=new Promise((e=>{i=e}))),this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/surveys/?token="+this._instance.config.token),method:"GET",timeout:this._instance.config.surveys_request_timeout_ms,callback:t=>{var r;this.pe=null;var n=t.statusCode;if(200!==n||!t.json){var s="Surveys API could not be loaded, status: "+n;Jn.error(s);var o={isLoaded:!1,error:s};return e([],o),void(null==i||i({surveys:[],context:o}))}var a,l=t.json.surveys||[],c=l.filter((e=>{return!(!(t=e).start_date||t.end_date)&&(function(e){var t;return!(null==(t=e.conditions)||null==(t=t.events)||null==(t=t.values)||!t.length)}(e)||function(e){var t;return!(null==(t=e.conditions)||null==(t=t.actions)||null==(t=t.values)||!t.length)}(e));var t}));c.length>0&&(null==(a=this._surveyEventReceiver)||a.register(c)),null==(r=this._instance.persistence)||r.register({[le]:l});var u={isLoaded:!0};e(l,u),null==i||i({surveys:l,context:u})}}))}me(e){for(var t of this.fe)try{if(!e.isLoaded)return t([],e);this.getSurveys(t)}catch(e){Jn.error("Error in survey callback",e)}}getActiveMatchingSurveys(e,t){if(void 0===t&&(t=!1),!j(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(e,t);Jn.warn("init was not called")}ye(e){var t=null;return this.getSurveys((i=>{var r;t=null!==(r=i.find((t=>t.id===e)))&&void 0!==r?r:null})),t}be(e){if(j(this._surveyManager))return{eligible:!1,reason:"SDK is not enabled or survey functionality is not yet loaded"};var t="string"==typeof e?this.ye(e):e;return t?this._surveyManager.checkSurveyEligibility(t):{eligible:!1,reason:"Survey not found"}}canRenderSurvey(e){if(j(this._surveyManager))return Jn.warn("init was not called"),{visible:!1,disabledReason:"SDK is not enabled or survey functionality is not yet loaded"};var t=this.be(e);return{visible:t.eligible,disabledReason:t.reason}}canRenderSurveyAsync(e,t){return j(this._surveyManager)?(Jn.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:"SDK is not enabled or survey functionality is not yet loaded"})):new Promise((i=>{this.getSurveys((t=>{var r,n=null!==(r=t.find((t=>t.id===e)))&&void 0!==r?r:null;if(n){var s=this.be(n);i({visible:s.eligible,disabledReason:s.reason})}else i({visible:!1,disabledReason:"Survey not found"})}),t)}))}renderSurvey(e,t,i){var r;if(j(this._surveyManager))Jn.warn("init was not called");else{var n="string"==typeof e?this.ye(e):e;if(null!=n&&n.id)if(Qn.includes(n.type)){var s=null==o?void 0:o.querySelector(t);if(s)return null!=(r=n.appearance)&&r.surveyPopupDelaySeconds?(Jn.info("Rendering survey "+n.id+" with delay of "+n.appearance.surveyPopupDelaySeconds+" seconds"),void setTimeout((()=>{var e,t;Jn.info("Rendering survey "+n.id+" with delay of "+(null==(e=n.appearance)?void 0:e.surveyPopupDelaySeconds)+" seconds"),null==(t=this._surveyManager)||t.renderSurvey(n,s,i),Jn.info("Survey "+n.id+" rendered")}),1e3*n.appearance.surveyPopupDelaySeconds)):void this._surveyManager.renderSurvey(n,s,i);Jn.warn("Survey element not found")}else Jn.warn("Surveys of type "+n.type+" cannot be rendered in the app");else Jn.warn("Survey not found")}}displaySurvey(e,t){var i;if(j(this._surveyManager))Jn.warn("init was not called");else{var r=this.ye(e);if(r){var n=r;if(null!=(i=r.appearance)&&i.surveyPopupDelaySeconds&&t.ignoreDelay&&(n=g({},r,{appearance:g({},r.appearance,{surveyPopupDelaySeconds:0})})),t.displayType!==Vn.Popover&&t.initialResponses&&Jn.warn("initialResponses is only supported for popover surveys. prefill will not be applied."),!1===t.ignoreConditions){var s=this.canRenderSurvey(r);if(!s.visible)return void Jn.warn("Survey is not eligible to be displayed: ",s.disabledReason)}t.displayType!==Vn.Inline?this._surveyManager.handlePopoverSurvey(n,t):this.renderSurvey(n,t.selector,t.properties)}else Jn.warn("Survey not found")}}cancelPendingSurvey(e){j(this._surveyManager)?Jn.warn("init was not called"):this._surveyManager.cancelSurvey(e)}handlePageUnload(){var e;null==(e=this._surveyManager)||e.handlePageUnload()}}var oo=Si("[Conversations]");class ao{constructor(e){this.we=void 0,this._conversationsManager=null,this.xe=!1,this.Ee=null,this._instance=e}onRemoteConfig(e){if(!this._instance.config.disable_conversations){var t=e.conversations;j(t)||(U(t)?this.we=t:(this.we=t.enabled,this.Ee=t),this.loadIfEnabled())}}reset(){var e;null==(e=this._conversationsManager)||e.reset(),this._conversationsManager=null,this.we=void 0,this.Ee=null}loadIfEnabled(){if(!this._conversationsManager&&!this.xe&&!(this._instance.config.disable_conversations||this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())){var e=null==v?void 0:v.__PosthogExtensions__;if(e&&!M(this.we)&&this.we)if(this.Ee&&this.Ee.token){this.xe=!0;try{var t=e.initConversations;if(t)return this.$e(t),void(this.xe=!1);var i=e.loadExternalDependency;if(!i)return void this.Se("PostHog loadExternalDependency extension not found.");i(this._instance,"conversations",(t=>{t||!e.initConversations?this.Se("Could not load conversations script",t):this.$e(e.initConversations),this.xe=!1}))}catch(e){this.Se("Error initializing conversations",e),this.xe=!1}}else oo.error("Conversations enabled but missing token in remote config.")}}$e(e){if(this.Ee)try{this._conversationsManager=e(this.Ee,this._instance),oo.info("Conversations loaded successfully")}catch(e){this.Se("Error completing conversations initialization",e)}else oo.error("Cannot complete initialization: remote config is null")}Se(e,t){oo.error(e,t),this._conversationsManager=null,this.xe=!1}show(){this._conversationsManager?this._conversationsManager.show():oo.warn("Conversations not loaded yet.")}hide(){this._conversationsManager&&this._conversationsManager.hide()}isAvailable(){return!0===this.we&&!D(this._conversationsManager)}isVisible(){var e,t;return null!==(e=null==(t=this._conversationsManager)?void 0:t.isVisible())&&void 0!==e&&e}sendMessage(e,t,i){var r=this;return p((function*(){return r._conversationsManager?r._conversationsManager.sendMessage(e,t,i):(oo.warn("Conversations not available yet."),null)}))()}getMessages(e,t){var i=this;return p((function*(){return i._conversationsManager?i._conversationsManager.getMessages(e,t):(oo.warn("Conversations not available yet."),null)}))()}markAsRead(e){var t=this;return p((function*(){return t._conversationsManager?t._conversationsManager.markAsRead(e):(oo.warn("Conversations not available yet."),null)}))()}getTickets(e){var t=this;return p((function*(){return t._conversationsManager?t._conversationsManager.getTickets(e):(oo.warn("Conversations not available yet."),null)}))()}getCurrentTicketId(){var e,t;return null!==(e=null==(t=this._conversationsManager)?void 0:t.getCurrentTicketId())&&void 0!==e?e:null}getWidgetSessionId(){var e,t;return null!==(e=null==(t=this._conversationsManager)?void 0:t.getWidgetSessionId())&&void 0!==e?e:null}}class lo{constructor(e){var t;this.ke=!1,this.Pe=!1,this._instance=e,this._instance&&null!=(t=this._instance.config.logs)&&t.captureConsoleLogs&&(this.ke=!0)}onRemoteConfig(e){var t,i=null==(t=e.logs)?void 0:t.captureConsoleLogs;!j(i)&&i&&(this.ke=!0,this.loadIfEnabled())}reset(){}loadIfEnabled(){if(this.ke&&!this.Pe){var e=Si("[logs]"),t=null==v?void 0:v.__PosthogExtensions__;if(t){var i=t.loadExternalDependency;i?i(this._instance,"logs",(i=>{var r;i||null==(r=t.logs)||!r.initializeLogs?e.error("Could not load logs script",i):(t.logs.initializeLogs(this._instance),this.Pe=!0)})):e.error("PostHog loadExternalDependency extension not found.")}else e.error("PostHog Extensions not found.")}}}var uo=Si("[RateLimiter]");class ho{constructor(e){this.serverLimits={},this.lastEventRateLimited=!1,this.checkForLimiting=e=>{var t=e.text;if(t&&t.length)try{(JSON.parse(t).quota_limited||[]).forEach((e=>{uo.info((e||"events")+" is quota limited."),this.serverLimits[e]=(new Date).getTime()+6e4}))}catch(e){return void uo.warn('could not rate limit - continuing. Error: "'+(null==e?void 0:e.message)+'"',{text:t})}},this.instance=e,this.lastEventRateLimited=this.clientRateLimitContext(!0).isRateLimited}get captureEventsPerSecond(){var e;return(null==(e=this.instance.config.rate_limiting)?void 0:e.events_per_second)||10}get captureEventsBurstLimit(){var e;return Math.max((null==(e=this.instance.config.rate_limiting)?void 0:e.events_burst_limit)||10*this.captureEventsPerSecond,this.captureEventsPerSecond)}clientRateLimitContext(e){var t,i,r;void 0===e&&(e=!1);var{captureEventsBurstLimit:n,captureEventsPerSecond:s}=this,o=(new Date).getTime(),a=null!==(t=null==(i=this.instance.persistence)?void 0:i.get_property(ve))&&void 0!==t?t:{tokens:n,last:o};a.tokens+=(o-a.last)/1e3*s,a.last=o,a.tokens>n&&(a.tokens=n);var l=a.tokens<1;return l||e||(a.tokens=Math.max(0,a.tokens-1)),!l||this.lastEventRateLimited||e||this.instance.capture("$$client_ingestion_warning",{$$client_ingestion_warning_message:"posthog-js client rate limited. Config is set to "+s+" events per second and "+n+" events burst limit."},{skip_client_rate_limiting:!0}),this.lastEventRateLimited=l,null==(r=this.instance.persistence)||r.set_property(ve,a),{isRateLimited:l,remainingTokens:a.tokens}}isServerRateLimited(e){var t=this.serverLimits[e||"events"]||!1;return!1!==t&&(new Date).getTime()<t}}var vo=Si("[RemoteConfig]");class co{constructor(e){this._instance=e}get remoteConfig(){var e;return null==(e=v._POSTHOG_REMOTE_CONFIG)||null==(e=e[this._instance.config.token])?void 0:e.config}Te(e){var t,i;null!=(t=v.__PosthogExtensions__)&&t.loadExternalDependency?null==(i=v.__PosthogExtensions__)||null==i.loadExternalDependency||i.loadExternalDependency(this._instance,"remote-config",(()=>e(this.remoteConfig))):(vo.error("PostHog Extensions not found. Cannot load remote config."),e())}Ie(e){this._instance._send_request({method:"GET",url:this._instance.requestRouter.endpointFor("assets","/array/"+this._instance.config.token+"/config"),callback:t=>{e(t.json)}})}load(){try{if(this.remoteConfig)return vo.info("Using preloaded remote config",this.remoteConfig),void this.bi(this.remoteConfig);if(this._instance.O())return void vo.warn("Remote config is disabled. Falling back to local config.");this.Te((e=>{if(!e)return vo.info("No config found after loading remote JS config. Falling back to JSON."),void this.Ie((e=>{this.bi(e)}));this.bi(e)}))}catch(e){vo.error("Error loading remote config",e)}}bi(e){e?this._instance.config.__preview_remote_config?(this._instance.bi(e),!1!==e.hasFeatureFlags&&this._instance.featureFlags.ensureFlagsLoaded()):vo.info("__preview_remote_config is disabled. Logging config instead",e):vo.error("Failed to fetch remote config from PostHog.")}}var fo=3e3;class po{constructor(e,t){this.Ce=!0,this.Re=[],this.Fe=K((null==t?void 0:t.flush_interval_ms)||fo,250,5e3,$i.createLogger("flush interval"),fo),this.Me=e}enqueue(e){this.Re.push(e),this.Oe||this.Ae()}unload(){this.De();var e=this.Re.length>0?this.je():{},t=Object.values(e);[...t.filter((e=>0===e.url.indexOf("/e"))),...t.filter((e=>0!==e.url.indexOf("/e")))].map((e=>{this.Me(g({},e,{transport:"sendBeacon"}))}))}enable(){this.Ce=!1,this.Ae()}Ae(){var e=this;this.Ce||(this.Oe=setTimeout((()=>{if(this.De(),this.Re.length>0){var t=this.je(),i=function(){var i=t[r],n=(new Date).getTime();i.data&&I(i.data)&&Ci(i.data,(e=>{e.offset=Math.abs(e.timestamp-n),delete e.timestamp})),e.Me(i)};for(var r in t)i()}}),this.Fe))}De(){clearTimeout(this.Oe),this.Oe=void 0}je(){var e={};return Ci(this.Re,(t=>{var i,r=t,n=(r?r.batchKey:null)||r.url;M(e[n])&&(e[n]=g({},r,{data:[]})),null==(i=e[n].data)||i.push(r.data)})),this.Re=[],e}}var go=["retriesPerformedSoFar"];class _o{constructor(e){this.Le=!1,this.Ne=3e3,this.Re=[],this._instance=e,this.Re=[],this.Ue=!0,!M(t)&&"onLine"in t.navigator&&(this.Ue=t.navigator.onLine,this.ze=()=>{this.Ue=!0,this.Lt()},this.He=()=>{this.Ue=!1},zi(t,"online",this.ze),zi(t,"offline",this.He))}get length(){return this.Re.length}retriableRequest(e){var{retriesPerformedSoFar:t}=e,i=_(e,go);N(t)&&(i.url=un(i.url,{retry_count:t})),this._instance._send_request(g({},i,{callback:e=>{200!==e.statusCode&&(e.statusCode<400||e.statusCode>=500)&&(null!=t?t:0)<10?this.Be(g({retriesPerformedSoFar:t},i)):null==i.callback||i.callback(e)}}))}Be(e){var t=e.retriesPerformedSoFar||0;e.retriesPerformedSoFar=t+1;var i,r,n,s,o,a=(i=t,r=3e3*Math.pow(2,i),n=r/2,s=Math.min(18e5,r),o=(Math.random()-.5)*(s-n),Math.ceil(s+o)),l=Date.now()+a;this.Re.push({retryAt:l,requestOptions:e});var c="Enqueued failed request for retry in "+a;navigator.onLine||(c+=" (Browser is offline)"),$i.warn(c),this.Le||(this.Le=!0,this.qe())}qe(){if(this.We&&clearTimeout(this.We),0===this.Re.length)return this.Le=!1,void(this.We=void 0);this.We=setTimeout((()=>{this.Ue&&this.Re.length>0&&this.Lt(),this.qe()}),this.Ne)}Lt(){var e=Date.now(),t=[],i=this.Re.filter((i=>i.retryAt<e||(t.push(i),!1)));if(this.Re=t,i.length>0)for(var{requestOptions:r}of i)this.retriableRequest(r)}unload(){for(var{requestOptions:e}of(this.We&&(clearTimeout(this.We),this.We=void 0),this.Le=!1,M(t)||(this.ze&&(t.removeEventListener("online",this.ze),this.ze=void 0),this.He&&(t.removeEventListener("offline",this.He),this.He=void 0)),this.Re))try{this._instance._send_request(g({},e,{transport:"sendBeacon"}))}catch(e){$i.error(e)}this.Re=[]}}class mo{constructor(e){this.Ge=()=>{var e,t,i,r;this.Ve||(this.Ve={});var n=this.scrollElement(),s=this.scrollY(),o=n?Math.max(0,n.scrollHeight-n.clientHeight):0,a=s+((null==n?void 0:n.clientHeight)||0),l=(null==n?void 0:n.scrollHeight)||0;this.Ve.lastScrollY=Math.ceil(s),this.Ve.maxScrollY=Math.max(s,null!==(e=this.Ve.maxScrollY)&&void 0!==e?e:0),this.Ve.maxScrollHeight=Math.max(o,null!==(t=this.Ve.maxScrollHeight)&&void 0!==t?t:0),this.Ve.lastContentY=a,this.Ve.maxContentY=Math.max(a,null!==(i=this.Ve.maxContentY)&&void 0!==i?i:0),this.Ve.maxContentHeight=Math.max(l,null!==(r=this.Ve.maxContentHeight)&&void 0!==r?r:0)},this._instance=e}getContext(){return this.Ve}resetContext(){var e=this.Ve;return setTimeout(this.Ge,0),e}startMeasuringScrollPosition(){zi(t,"scroll",this.Ge,{capture:!0}),zi(t,"scrollend",this.Ge,{capture:!0}),zi(t,"resize",this.Ge)}scrollElement(){if(!this._instance.config.scroll_root_selector)return null==t?void 0:t.document.documentElement;var e=I(this._instance.config.scroll_root_selector)?this._instance.config.scroll_root_selector:[this._instance.config.scroll_root_selector];for(var i of e){var r=null==t?void 0:t.document.querySelector(i);if(r)return r}}scrollY(){if(this._instance.config.scroll_root_selector){var e=this.scrollElement();return e&&e.scrollTop||0}return t&&(t.scrollY||t.pageYOffset||t.document.documentElement.scrollTop)||0}scrollX(){if(this._instance.config.scroll_root_selector){var e=this.scrollElement();return e&&e.scrollLeft||0}return t&&(t.scrollX||t.pageXOffset||t.document.documentElement.scrollLeft)||0}}var yo=e=>ds(null==e?void 0:e.config.mask_personal_data_properties,null==e?void 0:e.config.custom_personal_data_properties);class bo{constructor(e,t,i,r){this.Je=e=>{var t=this.Ke();if(!t||t.sessionId!==e){var i={sessionId:e,props:this.Ye(this._instance)};this.Xe.register({[de]:i})}},this._instance=e,this.Qe=t,this.Xe=i,this.Ye=r||yo,this.Qe.onSessionId(this.Je)}Ke(){return this.Xe.props[de]}getSetOnceProps(){var e,t=null==(e=this.Ke())?void 0:e.props;return t?"r"in t?vs(t):{$referring_domain:t.referringDomain,$pathname:t.initialPathName,utm_source:t.utm_source,utm_campaign:t.utm_campaign,utm_medium:t.utm_medium,utm_content:t.utm_content,utm_term:t.utm_term}:{}}getSessionProps(){var e={};return Ci(Di(this.getSetOnceProps()),((t,i)=>{"$current_url"===i&&(i="url"),e["$session_entry_"+E(i)]=t})),e}}var wo=Si("[SessionId]");class xo{on(e,t){return this.Ze.on(e,t)}constructor(e,t,i){var r;if(this.tr=[],this.ir=void 0,this.Ze=new to,this.er=(e,t)=>!(!N(e)||!N(t))&&Math.abs(e-t)>this.sessionTimeoutMs,!e.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if("always"===e.config.cookieless_mode)throw new Error('SessionIdManager cannot be used with cookieless_mode="always"');this.R=e.config,this.Xe=e.persistence,this.rr=void 0,this.sr=void 0,this._sessionStartTimestamp=null,this._sessionActivityTimestamp=null,this.nr=t||br,this.ar=i||br;var n=this.R.persistence_name||this.R.token,s=this.R.session_idle_timeout_seconds||1800;if(this._sessionTimeoutMs=1e3*K(s,60,36e3,wo.createLogger("session_idle_timeout_seconds"),1800),e.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this.lr(),this.ur="ph_"+n+"_window_id",this.hr="ph_"+n+"_primary_window_exists",this.dr()){var o=Fr.W(this.ur),a=Fr.W(this.hr);o&&!a?this.rr=o:Fr.V(this.ur),Fr.G(this.hr,!0)}if(null!=(r=this.R.bootstrap)&&r.sessionID)try{var l=(()=>{var e=this.R.bootstrap.sessionID.replace(/-/g,"");if(32!==e.length)throw new Error("Not a valid UUID");if("7"!==e[12])throw new Error("Not a UUIDv7");return parseInt(e.substring(0,12),16)})();this.vr(this.R.bootstrap.sessionID,(new Date).getTime(),l)}catch(e){wo.error("Invalid sessionID in bootstrap",e)}this.cr()}get sessionTimeoutMs(){return this._sessionTimeoutMs}onSessionId(e){return M(this.tr)&&(this.tr=[]),this.tr.push(e),this.sr&&e(this.sr,this.rr),()=>{this.tr=this.tr.filter((t=>t!==e))}}dr(){return"memory"!==this.R.persistence&&!this.Xe.ki&&Fr.H()}pr(e){e!==this.rr&&(this.rr=e,this.dr()&&Fr.G(this.ur,e))}gr(){return this.rr?this.rr:this.dr()?Fr.W(this.ur):null}vr(e,t,i){e===this.sr&&t===this._sessionActivityTimestamp&&i===this._sessionStartTimestamp||(this._sessionStartTimestamp=i,this._sessionActivityTimestamp=t,this.sr=e,this.Xe.register({[ie]:[t,e,i]}))}_r(){var e=this.Xe.props[ie];return I(e)&&2===e.length&&e.push(e[0]),e||[0,null,0]}resetSessionId(){this.vr(null,null,null)}destroy(){clearTimeout(this.mr),this.mr=void 0,this.ir&&t&&(t.removeEventListener("beforeunload",this.ir,{capture:!1}),this.ir=void 0),this.tr=[]}cr(){this.ir=()=>{this.dr()&&Fr.V(this.hr)},zi(t,"beforeunload",this.ir,{capture:!1})}checkAndGetSessionAndWindowId(e,t){if(void 0===e&&(e=!1),void 0===t&&(t=null),"always"===this.R.cookieless_mode)throw new Error('checkAndGetSessionAndWindowId should not be called with cookieless_mode="always"');var i=t||(new Date).getTime(),[r,n,s]=this._r(),o=this.gr(),a=N(s)&&Math.abs(i-s)>864e5,l=!1,c=!n,u=!c&&!e&&this.er(i,r);c||u||a?(n=this.nr(),o=this.ar(),wo.info("new session ID generated",{sessionId:n,windowId:o,changeReason:{noSessionId:c,activityTimeout:u,sessionPastMaximumLength:a}}),s=i,l=!0):o||(o=this.ar(),l=!0);var d=N(r)&&e&&!a?r:i,h=N(s)?s:(new Date).getTime();return this.pr(o),this.vr(n,d,h),e||this.lr(),l&&this.tr.forEach((e=>e(n,o,l?{noSessionId:c,activityTimeout:u,sessionPastMaximumLength:a}:void 0))),{sessionId:n,windowId:o,sessionStartTimestamp:h,changeReason:l?{noSessionId:c,activityTimeout:u,sessionPastMaximumLength:a}:void 0,lastActivityTimestamp:r}}lr(){clearTimeout(this.mr),this.mr=setTimeout((()=>{var[e]=this._r();if(this.er((new Date).getTime(),e)){var t=this.sr;this.resetSessionId(),this.Ze.emit("forcedIdleReset",{idleSessionId:t})}}),1.1*this.sessionTimeoutMs)}}var Eo=["$set_once","$set"],$o=Si("[SiteApps]");class So{constructor(e){this._instance=e,this.yr=[],this.apps={}}get isEnabled(){return!!this._instance.config.opt_in_site_apps}br(e,t){if(t){var i=this.globalsForEvent(t);this.yr.push(i),this.yr.length>1e3&&(this.yr=this.yr.slice(10))}}get siteAppLoaders(){var e;return null==(e=v._POSTHOG_REMOTE_CONFIG)||null==(e=e[this._instance.config.token])?void 0:e.siteApps}init(){if(this.isEnabled){var e=this._instance._addCaptureHook(this.br.bind(this));this.wr=()=>{e(),this.yr=[],this.wr=void 0}}}globalsForEvent(e){var t,i,r,n,s,o,a;if(!e)throw new Error("Event payload is required");var l={},c=this._instance.get_property("$groups")||[],u=this._instance.get_property("$stored_group_properties")||{};for(var[d,h]of Object.entries(u))l[d]={id:c[d],type:d,properties:h};var{$set_once:p,$set:v}=e;return{event:g({},_(e,Eo),{properties:g({},e.properties,v?{$set:g({},null!==(t=null==(i=e.properties)?void 0:i.$set)&&void 0!==t?t:{},v)}:{},p?{$set_once:g({},null!==(r=null==(n=e.properties)?void 0:n.$set_once)&&void 0!==r?r:{},p)}:{}),elements_chain:null!==(s=null==(o=e.properties)?void 0:o.$elements_chain)&&void 0!==s?s:"",distinct_id:null==(a=e.properties)?void 0:a.distinct_id}),person:{properties:this._instance.get_property("$stored_person_properties")},groups:l}}setupSiteApp(e){var t=this.apps[e.id],i=()=>{var i;!t.errored&&this.yr.length&&($o.info("Processing "+this.yr.length+" events for site app with id "+e.id),this.yr.forEach((e=>null==t.processEvent?void 0:t.processEvent(e))),t.processedBuffer=!0),Object.values(this.apps).every((e=>e.processedBuffer||e.errored))&&(null==(i=this.wr)||i.call(this))},r=!1,n=n=>{t.errored=!n,t.loaded=!0,$o.info("Site app with id "+e.id+" "+(n?"loaded":"errored")),r&&i()};try{var{processEvent:s}=e.init({posthog:this._instance,callback:e=>{n(e)}});s&&(t.processEvent=s),r=!0}catch(t){$o.error("Error while initializing PostHog app with config id "+e.id,t),n(!1)}if(r&&t.loaded)try{i()}catch(i){$o.error("Error while processing buffered events PostHog app with config id "+e.id,i),t.errored=!0}}Er(){var e=this.siteAppLoaders||[];for(var t of e)this.apps[t.id]={id:t.id,loaded:!1,errored:!1,processedBuffer:!1};for(var i of e)this.setupSiteApp(i)}$r(e){if(0!==Object.keys(this.apps).length){var t=this.globalsForEvent(e);for(var i of Object.values(this.apps))try{null==i.processEvent||i.processEvent(t)}catch(t){$o.error("Error while processing event "+e.event+" for site app "+i.id,t)}}}onRemoteConfig(e){var t,i,r,n=this;if(null!=(t=this.siteAppLoaders)&&t.length)return this.isEnabled?(this.Er(),void this._instance.on("eventCaptured",(e=>this.$r(e)))):void $o.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.');if(null==(i=this.wr)||i.call(this),null!=(r=e.siteApps)&&r.length)if(this.isEnabled){var s=function(e){var t;v["__$$ph_site_app_"+e]=n._instance,null==(t=v.__PosthogExtensions__)||null==t.loadSiteApp||t.loadSiteApp(n._instance,a,(t=>{if(t)return $o.error("Error while initializing PostHog app with config id "+e,t)}))};for(var{id:o,url:a}of e.siteApps)s(o)}else $o.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}}var ko=function(e,t){if(!e)return!1;var i=e.userAgent;if(i&&y(i,t))return!0;try{var r=null==e?void 0:e.userAgentData;if(null!=r&&r.brands&&r.brands.some((e=>y(null==e?void 0:e.brand,t))))return!0}catch(e){}return!!e.webdriver},Po=function(e){return e.US="us",e.EU="eu",e.CUSTOM="custom",e}({}),To="i.posthog.com";class Io{constructor(e){this.Sr={},this.instance=e}get apiHost(){var e=this.instance.config.api_host.trim().replace(/\/$/,"");return"https://app.posthog.com"===e?"https://us.i.posthog.com":e}get flagsApiHost(){var e=this.instance.config.flags_api_host;return e?e.trim().replace(/\/$/,""):this.apiHost}get uiHost(){var e,t=null==(e=this.instance.config.ui_host)?void 0:e.replace(/\/$/,"");return t||(t=this.apiHost.replace("."+To,".posthog.com")),"https://app.posthog.com"===t?"https://us.posthog.com":t}get region(){return this.Sr[this.apiHost]||(/https:\/\/(app|us|us-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?this.Sr[this.apiHost]=Po.US:/https:\/\/(eu|eu-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?this.Sr[this.apiHost]=Po.EU:this.Sr[this.apiHost]=Po.CUSTOM),this.Sr[this.apiHost]}endpointFor(e,t){if(void 0===t&&(t=""),t&&(t="/"===t[0]?t:"/"+t),"ui"===e)return this.uiHost+t;if("flags"===e)return this.flagsApiHost+t;if(this.region===Po.CUSTOM)return this.apiHost+t;var i=To+t;switch(e){case"assets":return"https://"+this.region+"-assets."+i;case"api":return"https://"+this.region+"."+i}}}var Co={icontains:(e,i)=>!!t&&i.href.toLowerCase().indexOf(e.toLowerCase())>-1,not_icontains:(e,i)=>!!t&&-1===i.href.toLowerCase().indexOf(e.toLowerCase()),regex:(e,i)=>!!t&&cn(i.href,e),not_regex:(e,i)=>!!t&&!cn(i.href,e),exact:(e,t)=>t.href===e,is_not:(e,t)=>t.href!==e};class Ro{constructor(e){var t=this;this.getWebExperimentsAndEvaluateDisplayLogic=function(e){void 0===e&&(e=!1),t.getWebExperiments((e=>{Ro.kr("retrieved web experiments from the server"),t.Pr=new Map,e.forEach((e=>{if(e.feature_flag_key){var i;t.Pr&&(Ro.kr("setting flag key ",e.feature_flag_key," to web experiment ",e),null==(i=t.Pr)||i.set(e.feature_flag_key,e));var r=t._instance.getFeatureFlag(e.feature_flag_key);O(r)&&e.variants[r]&&t.Tr(e.name,r,e.variants[r].transforms)}else if(e.variants)for(var n in e.variants){var s=e.variants[n];Ro.Ir(s)&&t.Tr(e.name,n,s.transforms)}}))}),e)},this._instance=e,this._instance.onFeatureFlags((e=>{this.onFeatureFlags(e)}))}onFeatureFlags(e){if(this._is_bot())Ro.kr("Refusing to render web experiment since the viewer is a likely bot");else if(!this._instance.config.disable_web_experiments){if(j(this.Pr))return this.Pr=new Map,this.loadIfEnabled(),void this.previewWebExperiment();Ro.kr("applying feature flags",e),e.forEach((e=>{var t;if(this.Pr&&null!=(t=this.Pr)&&t.has(e)){var i,r=this._instance.getFeatureFlag(e),n=null==(i=this.Pr)?void 0:i.get(e);r&&null!=n&&n.variants[r]&&this.Tr(n.name,r,n.variants[r].transforms)}}))}}previewWebExperiment(){var e=Ro.getWindowLocation();if(null!=e&&e.search){var t=sr(null==e?void 0:e.search,"__experiment_id"),i=sr(null==e?void 0:e.search,"__experiment_variant");t&&i&&(Ro.kr("previewing web experiments "+t+" && "+i),this.getWebExperiments((e=>{this.Cr(parseInt(t),i,e)}),!1,!0))}}loadIfEnabled(){this._instance.config.disable_web_experiments||this.getWebExperimentsAndEvaluateDisplayLogic()}getWebExperiments(e,t,i){if(this._instance.config.disable_web_experiments&&!i)return e([]);var r=this._instance.get_property("$web_experiments");if(r&&!t)return e(r);this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/web_experiments/?token="+this._instance.config.token),method:"GET",callback:t=>{if(200!==t.statusCode||!t.json)return e([]);var i=t.json.experiments||[];return e(i)}})}Cr(e,t,i){var r=i.filter((t=>t.id===e));r&&r.length>0&&(Ro.kr("Previewing web experiment ["+r[0].name+"] with variant ["+t+"]"),this.Tr(r[0].name,t,r[0].variants[t].transforms))}static Ir(e){return!j(e.conditions)&&Ro.Rr(e)&&Ro.Fr(e)}static Rr(e){var t;if(j(e.conditions)||j(null==(t=e.conditions)?void 0:t.url))return!0;var i,r,n,s=Ro.getWindowLocation();return!!s&&(null==(i=e.conditions)||!i.url||Co[null!==(r=null==(n=e.conditions)?void 0:n.urlMatchType)&&void 0!==r?r:"icontains"](e.conditions.url,s))}static getWindowLocation(){return null==t?void 0:t.location}static Fr(e){var t;if(j(e.conditions)||j(null==(t=e.conditions)?void 0:t.utm))return!0;var i=os();if(i.utm_source){var r,n,s,o,a,l,c,u,d=null==(r=e.conditions)||null==(r=r.utm)||!r.utm_campaign||(null==(n=e.conditions)||null==(n=n.utm)?void 0:n.utm_campaign)==i.utm_campaign,h=null==(s=e.conditions)||null==(s=s.utm)||!s.utm_source||(null==(o=e.conditions)||null==(o=o.utm)?void 0:o.utm_source)==i.utm_source,p=null==(a=e.conditions)||null==(a=a.utm)||!a.utm_medium||(null==(l=e.conditions)||null==(l=l.utm)?void 0:l.utm_medium)==i.utm_medium,g=null==(c=e.conditions)||null==(c=c.utm)||!c.utm_term||(null==(u=e.conditions)||null==(u=u.utm)?void 0:u.utm_term)==i.utm_term;return d&&p&&g&&h}return!1}static kr(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];$i.info("[WebExperiments] "+e,i)}Tr(e,t,i){this._is_bot()?Ro.kr("Refusing to render web experiment since the viewer is a likely bot"):"control"!==t?i.forEach((i=>{if(i.selector){var r;Ro.kr("applying transform of variant "+t+" for experiment "+e+" ",i);var n=null==(r=document)?void 0:r.querySelectorAll(i.selector);null==n||n.forEach((e=>{var t=e;i.html&&(t.innerHTML=i.html),i.css&&t.setAttribute("style",i.css)}))}})):Ro.kr("Control variants leave the page unmodified.")}_is_bot(){return n&&this._instance?ko(n,this._instance.config.custom_blocked_useragents):void 0}}var Fo=Si("[PostHog ExternalIntegrations]"),Mo={intercom:"intercom-integration",crispChat:"crisp-chat-integration"};class Oo{constructor(e){this._instance=e}it(e,t){var i;null==(i=v.__PosthogExtensions__)||null==i.loadExternalDependency||i.loadExternalDependency(this._instance,e,(e=>{if(e)return Fo.error("failed to load script",e);t()}))}startIfEnabledOrStop(){var e=this,t=function(t){var i,n,s;!r||null!=(i=v.__PosthogExtensions__)&&null!=(i=i.integrations)&&i[t]||e.it(Mo[t],(()=>{var i;null==(i=v.__PosthogExtensions__)||null==(i=i.integrations)||null==(i=i[t])||i.start(e._instance)})),!r&&null!=(n=v.__PosthogExtensions__)&&null!=(n=n.integrations)&&n[t]&&(null==(s=v.__PosthogExtensions__)||null==(s=s.integrations)||null==(s=s[t])||s.stop())};for(var[i,r]of Object.entries(null!==(n=this._instance.config.integrations)&&void 0!==n?n:{})){var n;t(i)}}}var Ao="[SessionRecording]",Do=Si(Ao);class jo{get started(){var e;return!(null==(e=this.Mr)||!e.isStarted)}get status(){return this.Mr?this.Mr.status:this.Or&&!this.Ar?"disabled":"lazy_loading"}constructor(e){if(this._forceAllowLocalhostNetworkCapture=!1,this.Or=!1,this.Dr=void 0,this._instance=e,!this._instance.sessionManager)throw Do.error("started without valid sessionManager"),new Error(Ao+" started without valid sessionManager. This is a bug.");if("always"===this._instance.config.cookieless_mode)throw new Error(Ao+' cannot be used with cookieless_mode="always"')}get Ar(){var e,i=!(null==(e=this._instance.get_property(te))||!e.enabled),r=!this._instance.config.disable_session_recording,n=this._instance.config.disable_session_recording||this._instance.consent.isOptedOut();return t&&i&&r&&!n}startIfEnabledOrStop(e){var t;if(!this.Ar||null==(t=this.Mr)||!t.isStarted){var i=!M(Object.assign)&&!M(Array.from);this.Ar&&i?(this.jr(e),Do.info("starting")):this.stopRecording()}}jr(e){var t,i,r;this.Ar&&(null!=v&&null!=(t=v.__PosthogExtensions__)&&null!=(t=t.rrweb)&&t.record&&null!=(i=v.__PosthogExtensions__)&&i.initSessionRecording?this.Lr(e):null==(r=v.__PosthogExtensions__)||null==r.loadExternalDependency||r.loadExternalDependency(this._instance,this.Nr,(t=>{if(t)return Do.error("could not load recorder",t);this.Lr(e)})))}stopRecording(){var e,t;null==(e=this.Dr)||e.call(this),this.Dr=void 0,null==(t=this.Mr)||t.stop()}Ur(){var e;null==(e=this._instance.persistence)||e.unregister(ee)}zr(e){if(this._instance.persistence){var t,i,r=this._instance.persistence,n=()=>{var t=!1===e.sessionRecording?void 0:e.sessionRecording,i=null==t?void 0:t.sampleRate,n=j(i)?null:parseFloat(i);j(n)&&this.Ur();var s=null==t?void 0:t.minimumDurationMilliseconds;r.register({[te]:g({enabled:!!t},t,{networkPayloadCapture:g({capturePerformance:e.capturePerformance},null==t?void 0:t.networkPayloadCapture),canvasRecording:{enabled:null==t?void 0:t.recordCanvas,fps:null==t?void 0:t.canvasFps,quality:null==t?void 0:t.canvasQuality},sampleRate:n,minimumDurationMilliseconds:M(s)?null:s,endpoint:null==t?void 0:t.endpoint,triggerMatchType:null==t?void 0:t.triggerMatchType,masking:null==t?void 0:t.masking,urlTriggers:null==t?void 0:t.urlTriggers})})};n(),null==(t=this.Dr)||t.call(this),this.Dr=null==(i=this._instance.sessionManager)?void 0:i.onSessionId(n)}}onRemoteConfig(e){"sessionRecording"in e?!1!==e.sessionRecording?(this.zr(e),this.Or=!0,this.startIfEnabledOrStop()):this.Or=!0:Do.info("skipping remote config with no sessionRecording",e)}log(e,t){var i;void 0===t&&(t="log"),null!=(i=this.Mr)&&i.log?this.Mr.log(e,t):Do.warn("log called before recorder was ready")}get Nr(){var e,t,i=null==(e=this._instance)||null==(e=e.persistence)?void 0:e.get_property(te);return(null==i||null==(t=i.scriptConfig)?void 0:t.script)||"lazy-recorder"}Lr(e){var t,i;if(null==(t=v.__PosthogExtensions__)||!t.initSessionRecording)throw Error("Called on script loaded before session recording is available");this.Mr||(this.Mr=null==(i=v.__PosthogExtensions__)?void 0:i.initSessionRecording(this._instance),this.Mr._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),this.Mr.start(e)}onRRwebEmit(e){var t;null==(t=this.Mr)||null==t.onRRwebEmit||t.onRRwebEmit(e)}overrideLinkedFlag(){var e,t;this.Mr||null==(t=this._instance.persistence)||t.register({$replay_override_linked_flag:!0}),null==(e=this.Mr)||e.overrideLinkedFlag()}overrideSampling(){var e,t;this.Mr||null==(t=this._instance.persistence)||t.register({$replay_override_sampling:!0}),null==(e=this.Mr)||e.overrideSampling()}overrideTrigger(e){var t,i;this.Mr||null==(i=this._instance.persistence)||i.register({["url"===e?"$replay_override_url_trigger":"$replay_override_event_trigger"]:!0}),null==(t=this.Mr)||t.overrideTrigger(e)}get sdkDebugProperties(){var e;return(null==(e=this.Mr)?void 0:e.sdkDebugProperties)||{$recording_status:this.status}}tryAddCustomEvent(e,t){var i;return!(null==(i=this.Mr)||!i.tryAddCustomEvent(e,t))}}var Lo={},No=()=>{},Uo="posthog",zo=!an&&-1===(null==d?void 0:d.indexOf("MSIE"))&&-1===(null==d?void 0:d.indexOf("Mozilla")),Ho=e=>{var i,r;return g({api_host:"https://us.i.posthog.com",flags_api_host:null,ui_host:null,token:"",autocapture:!0,cross_subdomain_cookie:Ni(null==o?void 0:o.location),persistence:"localStorage+cookie",persistence_name:"",cookie_persisted_properties:[],loaded:No,save_campaign_params:!0,custom_campaign_params:[],custom_blocked_useragents:[],save_referrer:!0,capture_pageleave:"if_capture_pageview",defaults:null!=e?e:"unset",__preview_deferred_init_extensions:!1,debug:a&&O(null==a?void 0:a.search)&&-1!==a.search.indexOf("__posthog_debug=true")||!1,cookie_expiration:365,upgrade:!1,disable_session_recording:!1,disable_persistence:!1,disable_web_experiments:!0,disable_surveys:!1,disable_surveys_automatic_display:!1,disable_conversations:!1,disable_product_tours:!0,disable_external_dependency_loading:!1,enable_recording_console_log:void 0,secure_cookie:"https:"===(null==t||null==(i=t.location)?void 0:i.protocol),ip:!1,opt_out_capturing_by_default:!1,opt_out_persistence_by_default:!1,opt_out_useragent_filter:!1,opt_out_capturing_persistence_type:"localStorage",consent_persistence_name:null,opt_out_capturing_cookie_prefix:null,opt_in_site_apps:!1,property_denylist:[],respect_dnt:!1,sanitize_properties:null,request_headers:{},request_batching:!0,properties_string_max_length:65535,mask_all_element_attributes:!1,mask_all_text:!1,mask_personal_data_properties:!1,custom_personal_data_properties:[],advanced_disable_flags:!1,advanced_disable_decide:!1,advanced_disable_feature_flags:!1,advanced_disable_feature_flags_on_first_load:!1,advanced_only_evaluate_survey_feature_flags:!1,advanced_enable_surveys:!1,advanced_disable_toolbar_metrics:!1,feature_flag_request_timeout_ms:3e3,surveys_request_timeout_ms:1e4,on_request_error:e=>{var t="Bad HTTP status: "+e.statusCode+" "+e.text;$i.error(t)},get_device_id:e=>e,capture_performance:void 0,name:"posthog",bootstrap:{},disable_compression:!1,session_idle_timeout_seconds:1800,person_profiles:"identified_only",before_send:void 0,request_queue_config:{flush_interval_ms:fo},error_tracking:{},_onCapture:No,__preview_eager_load_replay:!1},{rageclick:!((r=e)&&r>="2025-11-30")||{content_ignorelist:!0},capture_pageview:!(r&&r>="2025-05-24")||"history_change",session_recording:r&&r>="2025-11-30"?{strictMinimumDuration:!0}:{},external_scripts_inject_target:r&&r>="2026-01-30"?"head":"body"})},Bo=e=>{var t={};M(e.process_person)||(t.person_profiles=e.process_person),M(e.xhr_headers)||(t.request_headers=e.xhr_headers),M(e.cookie_name)||(t.persistence_name=e.cookie_name),M(e.disable_cookie)||(t.disable_persistence=e.disable_cookie),M(e.store_google)||(t.save_campaign_params=e.store_google),M(e.verbose)||(t.debug=e.verbose);var i=Ri({},t,e);return I(e.property_blacklist)&&(M(e.property_denylist)?i.property_denylist=e.property_blacklist:I(e.property_denylist)?i.property_denylist=[...e.property_blacklist,...e.property_denylist]:$i.error("Invalid value for property_denylist config: "+e.property_denylist)),i};class qo{constructor(){this.__forceAllowLocalhost=!1}get Hr(){return this.__forceAllowLocalhost}set Hr(e){$i.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=e}}class Wo{get decideEndpointWasHit(){var e,t;return null!==(e=null==(t=this.featureFlags)?void 0:t.hasLoadedFlags)&&void 0!==e&&e}get flagsEndpointWasHit(){var e,t;return null!==(e=null==(t=this.featureFlags)?void 0:t.hasLoadedFlags)&&void 0!==e&&e}constructor(){this.webPerformance=new qo,this.Br=!1,this.version=c.LIB_VERSION,this.qr=new to,this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=Ho(),this.SentryIntegration=Vr,this.sentryIntegration=e=>{return t=Gr(this,e),{name:Wr,processEvent:e=>t(e)};var t},this.__request_queue=[],this.__loaded=!1,this.analyticsDefaultEndpoint="/e/",this.Wr=!1,this.Gr=null,this.Vr=null,this.Jr=null,this.featureFlags=new Rn(this),this.toolbar=new Qr(this),this.scrollManager=new mo(this),this.pageViewManager=new xs(this),this.surveys=new no(this),this.conversations=new ao(this),this.logs=new lo(this),this.experiments=new Ro(this),this.exceptions=new yn(this),this.rateLimiter=new ho(this),this.requestRouter=new Io(this),this.consent=new Or(this),this.externalIntegrations=new Oo(this),this.people={set:(e,t,i)=>{var r=O(e)?{[e]:t}:e;this.setPersonProperties(r),null==i||i({})},set_once:(e,t,i)=>{var r=O(e)?{[e]:t}:e;this.setPersonProperties(void 0,r),null==i||i({})}},this.on("eventCaptured",(e=>$i.info('send "'+(null==e?void 0:e.event)+'"',e)))}init(e,t,i){if(i&&i!==Uo){var r,n=null!==(r=Lo[i])&&void 0!==r?r:new Wo;return n._init(e,t,i),Lo[i]=n,Lo[Uo][i]=n,n}return this._init(e,t,i)}_init(e,i,r){var n;if(void 0===i&&(i={}),M(e)||A(e))return $i.critical("PostHog was initialized without a token. This likely indicates a misconfiguration. Please check the first argument passed to posthog.init()"),this;if(this.__loaded)return console.warn("[PostHog.js]","You have already initialized PostHog! Re-initializing is a no-op"),this;this.__loaded=!0,this.config={},i.debug=this.Kr(i.debug),this.Yr=i,this.Xr=[],i.person_profiles&&(this.Vr=i.person_profiles),this.set_config(Ri({},Ho(i.defaults),Bo(i),{name:r,token:e})),this.config.on_xhr_error&&$i.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=i.disable_compression?void 0:$s.GZipJS;var s=this.Qr();this.persistence=new Mn(this.config,s),this.sessionPersistence="sessionStorage"===this.config.persistence||"memory"===this.config.persistence?this.persistence:new Mn(g({},this.config,{persistence:"sessionStorage"}),s);var o=g({},this.persistence.props),a=g({},this.sessionPersistence.props);this.register({$initialization_time:(new Date).toISOString()}),this.Zr=new po((e=>this.ts(e)),this.config.request_queue_config),this.es=new _o(this),this.__request_queue=[];var l="always"===this.config.cookieless_mode||"on_reject"===this.config.cookieless_mode&&this.consent.isExplicitlyOptedOut();if(l||(this.sessionManager=new xo(this),this.sessionPropsManager=new bo(this,this.sessionManager,this.persistence)),this.config.__preview_deferred_init_extensions?($i.info("Deferring extension initialization to improve startup performance"),setTimeout((()=>{this.rs(l)}),0)):($i.info("Initializing extensions synchronously"),this.rs(l)),c.DEBUG=c.DEBUG||this.config.debug,c.DEBUG&&$i.info("Starting in debug mode",{this:this,config:i,thisC:g({},this.config),p:o,s:a}),void 0!==(null==(n=i.bootstrap)?void 0:n.distinctID)){var u,d,h=this.config.get_device_id(br()),p=null!=(u=i.bootstrap)&&u.isIdentifiedID?h:i.bootstrap.distinctID;this.persistence.set_property(he,null!=(d=i.bootstrap)&&d.isIdentifiedID?"identified":"anonymous"),this.register({distinct_id:i.bootstrap.distinctID,$device_id:p})}if(this.ss()){var v,m,f=Object.keys((null==(v=i.bootstrap)?void 0:v.featureFlags)||{}).filter((e=>{var t;return!(null==(t=i.bootstrap)||null==(t=t.featureFlags)||!t[e])})).reduce(((e,t)=>{var r;return e[t]=(null==(r=i.bootstrap)||null==(r=r.featureFlags)?void 0:r[t])||!1,e}),{}),_=Object.keys((null==(m=i.bootstrap)?void 0:m.featureFlagPayloads)||{}).filter((e=>f[e])).reduce(((e,t)=>{var r,n;return null!=(r=i.bootstrap)&&null!=(r=r.featureFlagPayloads)&&r[t]&&(e[t]=null==(n=i.bootstrap)||null==(n=n.featureFlagPayloads)?void 0:n[t]),e}),{});this.featureFlags.receivedFeatureFlags({featureFlags:f,featureFlagPayloads:_})}if(l)this.register_once({distinct_id:me,$device_id:null},"");else if(!this.get_distinct_id()){var E=this.config.get_device_id(br());this.register_once({distinct_id:E,$device_id:E},""),this.persistence.set_property(he,"anonymous")}return zi(t,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),this.toolbar.maybeLoadToolbar(),i.segment?qr(this,(()=>this.ns())):this.ns(),C(this.config._onCapture)&&this.config._onCapture!==No&&($i.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",(e=>this.config._onCapture(e.event,e)))),this.config.ip&&$i.warn('The `ip` config option has NO EFFECT AT ALL and has been deprecated. Use a custom transformation or "Discard IP data" project setting instead. See https://posthog.com/tutorials/web-redact-properties#hiding-customer-ip-address for more information.'),this}rs(e){var t=performance.now();this.historyAutocapture=new Hr(this),this.historyAutocapture.startIfEnabled();var i=[];i.push((()=>{new ts(this).startIfEnabledOrStop()})),i.push((()=>{var e;this.siteApps=new So(this),null==(e=this.siteApps)||e.init()})),e||i.push((()=>{this.sessionRecording=new jo(this),this.sessionRecording.startIfEnabledOrStop()})),this.config.disable_scroll_properties||i.push((()=>{this.scrollManager.startMeasuringScrollPosition()})),i.push((()=>{this.autocapture=new cr(this),this.autocapture.startIfEnabled()})),i.push((()=>{this.surveys.loadIfEnabled()})),i.push((()=>{this.logs.loadIfEnabled()})),i.push((()=>{this.conversations.loadIfEnabled()})),i.push((()=>{this.productTours=new Dn(this),this.productTours.loadIfEnabled()})),i.push((()=>{this.heatmaps=new ws(this),this.heatmaps.startIfEnabled()})),i.push((()=>{this.webVitalsAutocapture=new ms(this)})),i.push((()=>{this.exceptionObserver=new Ur(this),this.exceptionObserver.startIfEnabledOrStop()})),i.push((()=>{this.deadClicksAutocapture=new Lr(this,jr),this.deadClicksAutocapture.startIfEnabled()})),i.push((()=>{if(this.os){var e=this.os;this.os=void 0,this.bi(e)}})),this.ls(i,t)}ls(e,t){for(;e.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-t>=30&&e.length>0)return void setTimeout((()=>{this.ls(e,t)}),0);var i=e.shift();if(i)try{i()}catch(e){$i.error("Error initializing extension:",e)}}var r=Math.round(performance.now()-t);this.register_for_session({$sdk_debug_extensions_init_method:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",$sdk_debug_extensions_init_time_ms:r}),this.config.__preview_deferred_init_extensions&&$i.info("PostHog extensions initialized ("+r+"ms)")}bi(e){var t,i,r,n,s,a,l,c,u;if(!o||!o.body)return $i.info("document not ready yet, trying again in 500 milliseconds..."),void setTimeout((()=>{this.bi(e)}),500);this.config.__preview_deferred_init_extensions&&(this.os=e),this.compression=void 0,e.supportedCompression&&!this.config.disable_compression&&(this.compression=w(e.supportedCompression,$s.GZipJS)?$s.GZipJS:w(e.supportedCompression,$s.Base64)?$s.Base64:void 0),null!=(t=e.analytics)&&t.endpoint&&(this.analyticsDefaultEndpoint=e.analytics.endpoint),this.set_config({person_profiles:this.Vr?this.Vr:"identified_only"}),null==(i=this.siteApps)||i.onRemoteConfig(e),null==(r=this.sessionRecording)||r.onRemoteConfig(e),null==(n=this.autocapture)||n.onRemoteConfig(e),null==(s=this.heatmaps)||s.onRemoteConfig(e),this.surveys.onRemoteConfig(e),this.logs.onRemoteConfig(e),this.conversations.onRemoteConfig(e),null==(a=this.productTours)||a.onRemoteConfig(e),null==(l=this.webVitalsAutocapture)||l.onRemoteConfig(e),null==(c=this.exceptionObserver)||c.onRemoteConfig(e),this.exceptions.onRemoteConfig(e),null==(u=this.deadClicksAutocapture)||u.onRemoteConfig(e)}ns(){try{this.config.loaded(this)}catch(e){$i.critical("`loaded` function failed",e)}this.us(),this.config.capture_pageview&&setTimeout((()=>{(this.consent.isOptedIn()||"always"===this.config.cookieless_mode)&&this.hs()}),1),new co(this).load(),this.featureFlags.flags()}us(){var e;this.is_capturing()&&this.config.request_batching&&(null==(e=this.Zr)||e.enable())}_dom_loaded(){this.is_capturing()&&Ii(this.__request_queue,(e=>this.ts(e))),this.__request_queue=[],this.us()}_handle_unload(){var e,t;this.surveys.handlePageUnload(),this.config.request_batching?(this.ds()&&this.capture("$pageleave"),null==(e=this.Zr)||e.unload(),null==(t=this.es)||t.unload()):this.ds()&&this.capture("$pageleave",null,{transport:"sendBeacon"})}_send_request(e){this.__loaded&&(zo?this.__request_queue.push(e):this.rateLimiter.isServerRateLimited(e.batchKey)||(e.transport=e.transport||this.config.api_transport,e.url=un(e.url,{ip:this.config.ip?1:0}),e.headers=g({},this.config.request_headers,e.headers),e.compression="best-available"===e.compression?this.compression:e.compression,e.disableXHRCredentials=this.config.__preview_disable_xhr_credentials,this.config.__preview_disable_beacon&&(e.disableTransport=["sendBeacon"]),e.fetchOptions=e.fetchOptions||this.config.fetch_options,(e=>{var t,i,r,n=g({},e);n.timeout=n.timeout||6e4,n.url=un(n.url,{_:(new Date).getTime().toString(),ver:c.LIB_VERSION,compression:n.compression});var s=null!==(t=n.transport)&&void 0!==t?t:"fetch",o=vn.filter((e=>!n.disableTransport||!e.transport||!n.disableTransport.includes(e.transport))),a=null!==(i=null==(r=Ui(o,(e=>e.transport===s)))?void 0:r.method)&&void 0!==i?i:o[0].method;if(!a)throw new Error("No available transport method");a(n)})(g({},e,{callback:t=>{var i,r;this.rateLimiter.checkForLimiting(t),t.statusCode>=400&&(null==(i=(r=this.config).on_request_error)||i.call(r,t)),null==e.callback||e.callback(t)}}))))}ts(e){this.es?this.es.retriableRequest(e):this._send_request(e)}_execute_array(e){var t,i=[],r=[],n=[];Ii(e,(e=>{e&&(t=e[0],I(t)?n.push(e):C(e)?e.call(this):I(e)&&"alias"===t?i.push(e):I(e)&&-1!==t.indexOf("capture")&&C(this[t])?n.push(e):r.push(e))}));var s=function(e,t){Ii(e,(function(e){if(I(e[0])){var i=t;Ci(e,(function(e){i=i[e[0]].apply(i,e.slice(1))}))}else this[e[0]].apply(this,e.slice(1))}),t)};s(i,this),s(r,this),s(n,this)}ss(){var e,t;return(null==(e=this.config.bootstrap)?void 0:e.featureFlags)&&Object.keys(null==(t=this.config.bootstrap)?void 0:t.featureFlags).length>0||!1}push(e){this._execute_array([e])}capture(e,t,i){var r;if(this.__loaded&&this.persistence&&this.sessionPersistence&&this.Zr){if(this.is_capturing())if(!M(e)&&O(e)){var n=!this.config.opt_out_useragent_filter&&this._is_bot();if(!n||this.config.__preview_capture_bot_pageviews){var s=null!=i&&i.skip_client_rate_limiting?void 0:this.rateLimiter.clientRateLimitContext();if(null==s||!s.isRateLimited){null!=t&&t.$current_url&&!O(null==t?void 0:t.$current_url)&&($i.error("Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value."),null==t||delete t.$current_url),this.sessionPersistence.update_search_keyword(),this.config.save_campaign_params&&this.sessionPersistence.update_campaign_params(),this.config.save_referrer&&this.sessionPersistence.update_referrer_info(),(this.config.save_campaign_params||this.config.save_referrer)&&this.persistence.set_initial_person_info();var o=new Date,a=(null==i?void 0:i.timestamp)||o,l=br(),c={uuid:l,event:e,properties:this.calculateEventProperties(e,t||{},a,l)};"$pageview"===e&&this.config.__preview_capture_bot_pageviews&&n&&(c.event="$bot_pageview",c.properties.$browser_type="bot"),s&&(c.properties.$lib_rate_limit_remaining_tokens=s.remainingTokens),(null==i?void 0:i.$set)&&(c.$set=null==i?void 0:i.$set);var u,d="$groupidentify"!==e,h=this.vs(null==i?void 0:i.$set_once,d);if(h&&(c.$set_once=h),(c=ji(c,null!=i&&i._noTruncate?null:this.config.properties_string_max_length)).timestamp=a,M(null==i?void 0:i.timestamp)||(c.properties.$event_time_override_provided=!0,c.properties.$event_time_override_system_time=o),e===Wn.DISMISSED||e===Wn.SENT){var p=null==t?void 0:t[Gn.SURVEY_ID],v=null==t?void 0:t[Gn.SURVEY_ITERATION];u={id:p,current_iteration:v},localStorage.getItem(Xn(u))||localStorage.setItem(Xn(u),"true"),c.$set=g({},c.$set,{[Yn({id:p,current_iteration:v},e===Wn.SENT?"responded":"dismissed")]:!0})}else e===Wn.SHOWN&&(c.$set=g({},c.$set,{[Gn.SURVEY_LAST_SEEN_DATE]:(new Date).toISOString()}));var m=g({},c.properties.$set,c.$set);if(F(m)||this.setPersonPropertiesForFlags(m),!j(this.config.before_send)){var f=this.cs(c);if(!f)return;c=f}this.qr.emit("eventCaptured",c);var _={method:"POST",url:null!==(r=null==i?void 0:i._url)&&void 0!==r?r:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),data:c,compression:"best-available",batchKey:null==i?void 0:i._batchKey};return!this.config.request_batching||i&&(null==i||!i._batchKey)||null!=i&&i.send_instantly?this.ts(_):this.Zr.enqueue(_),c}$i.critical("This capture call is ignored due to client rate limiting.")}}else $i.error("No event name provided to posthog.capture")}else $i.uninitializedWarning("posthog.capture")}_addCaptureHook(e){return this.on("eventCaptured",(t=>e(t.event,t)))}calculateEventProperties(e,t,i,r,n){if(i=i||new Date,!this.persistence||!this.sessionPersistence)return t;var s=n?void 0:this.persistence.remove_event_timer(e),a=g({},t);if(a.token=this.config.token,a.$config_defaults=this.config.defaults,("always"==this.config.cookieless_mode||"on_reject"==this.config.cookieless_mode&&this.consent.isExplicitlyOptedOut())&&(a.$cookieless_mode=!0),"$snapshot"===e){var l=g({},this.persistence.properties(),this.sessionPersistence.properties());return a.distinct_id=l.distinct_id,(!O(a.distinct_id)&&!L(a.distinct_id)||A(a.distinct_id))&&$i.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),a}var c,u=ps(this.config.mask_personal_data_properties,this.config.custom_personal_data_properties);if(this.sessionManager){var{sessionId:h,windowId:p}=this.sessionManager.checkAndGetSessionAndWindowId(n,i.getTime());a.$session_id=h,a.$window_id=p}this.sessionPropsManager&&Ri(a,this.sessionPropsManager.getSessionProps());try{var v;this.sessionRecording&&Ri(a,this.sessionRecording.sdkDebugProperties),a.$sdk_debug_retry_queue_size=null==(v=this.es)?void 0:v.length}catch(e){a.$sdk_debug_error_capturing_properties=String(e)}if(this.requestRouter.region===Po.CUSTOM&&(a.$lib_custom_api_host=this.config.api_host),c="$pageview"!==e||n?"$pageleave"!==e||n?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(i):this.pageViewManager.doPageView(i,r),a=Ri(a,c),"$pageview"===e&&o&&(a.title=o.title),!M(s)){var m=i.getTime()-s;a.$duration=parseFloat((m/1e3).toFixed(3))}d&&this.config.opt_out_useragent_filter&&(a.$browser_type=this._is_bot()?"bot":"browser"),(a=Ri({},u,this.persistence.properties(),this.sessionPersistence.properties(),a)).$is_identified=this._isIdentified(),I(this.config.property_denylist)?Ci(this.config.property_denylist,(function(e){delete a[e]})):$i.error("Invalid value for property_denylist config: "+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var f=this.config.sanitize_properties;f&&($i.error("sanitize_properties is deprecated. Use before_send instead"),a=f(a,e));var _=this.fs();return a.$process_person_profile=_,_&&!n&&this.ps("_calculate_event_properties"),a}vs(e,t){var i;if(void 0===t&&(t=!0),!this.persistence||!this.fs())return e;if(this.Br)return e;var r=this.persistence.get_initial_props(),n=null==(i=this.sessionPropsManager)?void 0:i.getSetOnceProps(),s=Ri({},r,n||{},e||{}),o=this.config.sanitize_properties;return o&&($i.error("sanitize_properties is deprecated. Use before_send instead"),s=o(s,"$set_once")),t&&(this.Br=!0),F(s)?void 0:s}register(e,t){var i;null==(i=this.persistence)||i.register(e,t)}register_once(e,t,i){var r;null==(r=this.persistence)||r.register_once(e,t,i)}register_for_session(e){var t;null==(t=this.sessionPersistence)||t.register(e)}unregister(e){var t;null==(t=this.persistence)||t.unregister(e)}unregister_for_session(e){var t;null==(t=this.sessionPersistence)||t.unregister(e)}gs(e,t){this.register({[e]:t})}getFeatureFlag(e,t){return this.featureFlags.getFeatureFlag(e,t)}getFeatureFlagPayload(e){var t=this.featureFlags.getFeatureFlagPayload(e);try{return JSON.parse(t)}catch(e){return t}}isFeatureEnabled(e,t){return this.featureFlags.isFeatureEnabled(e,t)}reloadFeatureFlags(){this.featureFlags.reloadFeatureFlags()}updateFlags(e,t,i){var r=null!=i&&i.merge?this.featureFlags.getFlagVariants():{},n=null!=i&&i.merge?this.featureFlags.getFlagPayloads():{},s=g({},r,e),o=g({},n,t),a={};for(var[l,c]of Object.entries(s)){var u="string"==typeof c;a[l]={key:l,enabled:!!u||Boolean(c),variant:u?c:void 0,reason:void 0,metadata:M(null==o?void 0:o[l])?void 0:{id:0,version:void 0,description:void 0,payload:o[l]}}}this.featureFlags.receivedFeatureFlags({flags:a})}updateEarlyAccessFeatureEnrollment(e,t,i){this.featureFlags.updateEarlyAccessFeatureEnrollment(e,t,i)}getEarlyAccessFeatures(e,t,i){return void 0===t&&(t=!1),this.featureFlags.getEarlyAccessFeatures(e,t,i)}on(e,t){return this.qr.on(e,t)}onFeatureFlags(e){return this.featureFlags.onFeatureFlags(e)}onSurveysLoaded(e){return this.surveys.onSurveysLoaded(e)}onSessionId(e){var t,i;return null!==(t=null==(i=this.sessionManager)?void 0:i.onSessionId(e))&&void 0!==t?t:()=>{}}getSurveys(e,t){void 0===t&&(t=!1),this.surveys.getSurveys(e,t)}getActiveMatchingSurveys(e,t){void 0===t&&(t=!1),this.surveys.getActiveMatchingSurveys(e,t)}renderSurvey(e,t){this.surveys.renderSurvey(e,t)}displaySurvey(e,t){void 0===t&&(t=Zn),this.surveys.displaySurvey(e,t)}cancelPendingSurvey(e){this.surveys.cancelPendingSurvey(e)}canRenderSurvey(e){return this.surveys.canRenderSurvey(e)}canRenderSurveyAsync(e,t){return void 0===t&&(t=!1),this.surveys.canRenderSurveyAsync(e,t)}identify(e,t,i){if(!this.__loaded||!this.persistence)return $i.uninitializedWarning("posthog.identify");if(L(e)&&(e=e.toString(),$i.warn("The first argument to posthog.identify was a number, but it should be a string. It has been converted to a string.")),e)if(["distinct_id","distinctid"].includes(e.toLowerCase()))$i.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID should be unique to the user and not a hardcoded string.');else if(e!==me){if(this.ps("posthog.identify")){var r=this.get_distinct_id();if(this.register({$user_id:e}),!this.get_property("$device_id")){var n=r;this.register_once({$had_persisted_distinct_id:!0,$device_id:n},"")}e!==r&&e!==this.get_property(Bi)&&(this.unregister(Bi),this.register({distinct_id:e}));var s="anonymous"===(this.persistence.get_property(he)||"anonymous");e!==r&&s?(this.persistence.set_property(he,"identified"),this.setPersonPropertiesForFlags(g({},i||{},t||{}),!1),this.capture("$identify",{distinct_id:e,$anon_distinct_id:r},{$set:t||{},$set_once:i||{}}),this.Jr=fn(e,t,i),this.featureFlags.setAnonymousDistinctId(r)):(t||i)&&this.setPersonProperties(t,i),e!==r&&(this.reloadFeatureFlags(),this.unregister(ue))}}else $i.critical('The string "'+me+'" was set in posthog.identify which indicates an error. This ID is only used as a sentinel value.');else $i.error("Unique user id has not been set in posthog.identify")}setPersonProperties(e,t){if((e||t)&&this.ps("posthog.setPersonProperties")){var i=fn(this.get_distinct_id(),e,t);this.Jr!==i?(this.setPersonPropertiesForFlags(g({},t||{},e||{})),this.capture("$set",{$set:e||{},$set_once:t||{}}),this.Jr=i):$i.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")}}group(e,t,i){if(e&&t){var r=this.getGroups();r[e]!==t&&this.resetGroupPropertiesForFlags(e),this.register({$groups:g({},r,{[e]:t})}),i&&(this.capture("$groupidentify",{$group_type:e,$group_key:t,$group_set:i}),this.setGroupPropertiesForFlags({[e]:i})),r[e]===t||i||this.reloadFeatureFlags()}else $i.error("posthog.group requires a group type and group key")}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(e,t){void 0===t&&(t=!0),this.featureFlags.setPersonPropertiesForFlags(e,t)}resetPersonPropertiesForFlags(){this.featureFlags.resetPersonPropertiesForFlags()}setGroupPropertiesForFlags(e,t){void 0===t&&(t=!0),this.ps("posthog.setGroupPropertiesForFlags")&&this.featureFlags.setGroupPropertiesForFlags(e,t)}resetGroupPropertiesForFlags(e){this.featureFlags.resetGroupPropertiesForFlags(e)}reset(e){var t,i,r,n;if($i.info("reset"),!this.__loaded)return $i.uninitializedWarning("posthog.reset");var s=this.get_property("$device_id");if(this.consent.reset(),null==(t=this.persistence)||t.clear(),null==(i=this.sessionPersistence)||i.clear(),this.surveys.reset(),this.featureFlags.reset(),null==(r=this.persistence)||r.set_property(he,"anonymous"),null==(n=this.sessionManager)||n.resetSessionId(),this.Jr=null,"always"===this.config.cookieless_mode)this.register_once({distinct_id:me,$device_id:null},"");else{var o=this.config.get_device_id(br());this.register_once({distinct_id:o,$device_id:e?o:s},"")}this.register({$last_posthog_reset:(new Date).toISOString()},1)}get_distinct_id(){return this.get_property("distinct_id")}getGroups(){return this.get_property("$groups")||{}}get_session_id(){var e,t;return null!==(e=null==(t=this.sessionManager)?void 0:t.checkAndGetSessionAndWindowId(!0).sessionId)&&void 0!==e?e:""}get_session_replay_url(e){if(!this.sessionManager)return"";var{sessionId:t,sessionStartTimestamp:i}=this.sessionManager.checkAndGetSessionAndWindowId(!0),r=this.requestRouter.endpointFor("ui","/project/"+this.config.token+"/replay/"+t);if(null!=e&&e.withTimestamp&&i){var n,s=null!==(n=e.timestampLookBack)&&void 0!==n?n:10;if(!i)return r;r+="?t="+Math.max(Math.floor(((new Date).getTime()-i)/1e3)-s,0)}return r}alias(e,t){return e===this.get_property(Hi)?($i.critical("Attempting to create alias for existing People user - aborting."),-2):this.ps("posthog.alias")?(M(t)&&(t=this.get_distinct_id()),e!==t?(this.gs(Bi,e),this.capture("$create_alias",{alias:e,distinct_id:t})):($i.warn("alias matches current distinct_id - skipping api call."),this.identify(e),-1)):void 0}set_config(e){var t=g({},this.config);if(R(e)){var i,r,n,s,o,a,l;Ri(this.config,Bo(e));var u=this.Qr();null==(i=this.persistence)||i.update_config(this.config,t,u),this.sessionPersistence="sessionStorage"===this.config.persistence||"memory"===this.config.persistence?this.persistence:new Mn(g({},this.config,{persistence:"sessionStorage"}),u);var d=this.Kr(this.config.debug);U(d)&&(this.config.debug=d),U(this.config.debug)&&(this.config.debug?(c.DEBUG=!0,Pr.H()&&Pr.G("ph_debug","true"),$i.info("set_config",{config:e,oldConfig:t,newConfig:g({},this.config)})):(c.DEBUG=!1,Pr.H()&&Pr.V("ph_debug"))),null==(r=this.exceptionObserver)||r.onConfigChange(),null==(n=this.sessionRecording)||n.startIfEnabledOrStop(),null==(s=this.autocapture)||s.startIfEnabled(),null==(o=this.heatmaps)||o.startIfEnabled(),null==(a=this.exceptionObserver)||a.startIfEnabledOrStop(),this.surveys.loadIfEnabled(),this._s(),null==(l=this.externalIntegrations)||l.startIfEnabledOrStop()}}startSessionRecording(e){var t,i,r,n,s,o=!0===e,a={sampling:o||!(null==e||!e.sampling),linked_flag:o||!(null==e||!e.linked_flag),url_trigger:o||!(null==e||!e.url_trigger),event_trigger:o||!(null==e||!e.event_trigger)};Object.values(a).some(Boolean)&&(null==(t=this.sessionManager)||t.checkAndGetSessionAndWindowId(),a.sampling&&(null==(i=this.sessionRecording)||i.overrideSampling()),a.linked_flag&&(null==(r=this.sessionRecording)||r.overrideLinkedFlag()),a.url_trigger&&(null==(n=this.sessionRecording)||n.overrideTrigger("url")),a.event_trigger&&(null==(s=this.sessionRecording)||s.overrideTrigger("event")));this.set_config({disable_session_recording:!1})}stopSessionRecording(){this.set_config({disable_session_recording:!0})}sessionRecordingStarted(){var e;return!(null==(e=this.sessionRecording)||!e.started)}captureException(e,t){var i=new Error("PostHog syntheticException"),r=this.exceptions.buildProperties(e,{handled:!0,syntheticException:i});return this.exceptions.sendExceptionEvent(g({},r,t))}startExceptionAutocapture(e){this.set_config({capture_exceptions:null==e||e})}stopExceptionAutocapture(){this.set_config({capture_exceptions:!1})}loadToolbar(e){return this.toolbar.loadToolbar(e)}get_property(e){var t;return null==(t=this.persistence)?void 0:t.props[e]}getSessionProperty(e){var t;return null==(t=this.sessionPersistence)?void 0:t.props[e]}toString(){var e,t=null!==(e=this.config.name)&&void 0!==e?e:Uo;return t!==Uo&&(t=Uo+"."+t),t}_isIdentified(){var e,t;return"identified"===(null==(e=this.persistence)?void 0:e.get_property(he))||"identified"===(null==(t=this.sessionPersistence)?void 0:t.get_property(he))}fs(){var e,t;return!("never"===this.config.person_profiles||"identified_only"===this.config.person_profiles&&!this._isIdentified()&&F(this.getGroups())&&(null==(e=this.persistence)||null==(e=e.props)||!e[Bi])&&(null==(t=this.persistence)||null==(t=t.props)||!t[ge]))}ds(){return!0===this.config.capture_pageleave||"if_capture_pageview"===this.config.capture_pageleave&&(!0===this.config.capture_pageview||"history_change"===this.config.capture_pageview)}createPersonProfile(){this.fs()||this.ps("posthog.createPersonProfile")&&this.setPersonProperties({},{})}ps(e){return"never"===this.config.person_profiles?($i.error(e+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this.gs(ge,!0),!0)}Qr(){if("always"===this.config.cookieless_mode)return!0;var e=this.consent.isOptedOut(),t=this.config.opt_out_persistence_by_default||"on_reject"===this.config.cookieless_mode;return this.config.disable_persistence||e&&!!t}_s(){var e,t,i,r,n=this.Qr();return(null==(e=this.persistence)?void 0:e.ki)!==n&&(null==(i=this.persistence)||i.set_disabled(n)),(null==(t=this.sessionPersistence)?void 0:t.ki)!==n&&(null==(r=this.sessionPersistence)||r.set_disabled(n)),n}opt_in_capturing(e){var t,i,r,n;"always"!==this.config.cookieless_mode?("on_reject"===this.config.cookieless_mode&&this.consent.isExplicitlyOptedOut()&&(this.reset(!0),null==(i=this.sessionManager)||i.destroy(),null==(r=this.pageViewManager)||r.destroy(),this.sessionManager=new xo(this),this.pageViewManager=new xs(this),this.persistence&&(this.sessionPropsManager=new bo(this,this.sessionManager,this.persistence)),this.sessionRecording=new jo(this),this.sessionRecording.startIfEnabledOrStop()),this.consent.optInOut(!0),this._s(),this.us(),null==(t=this.sessionRecording)||t.startIfEnabledOrStop(),"on_reject"==this.config.cookieless_mode&&this.surveys.loadIfEnabled(),(M(null==e?void 0:e.captureEventName)||null!=e&&e.captureEventName)&&this.capture(null!==(n=null==e?void 0:e.captureEventName)&&void 0!==n?n:"$opt_in",null==e?void 0:e.captureProperties,{send_instantly:!0}),this.config.capture_pageview&&this.hs()):$i.warn('Consent opt in/out is not valid with cookieless_mode="always" and will be ignored')}opt_out_capturing(){var e,t,i;"always"!==this.config.cookieless_mode?("on_reject"===this.config.cookieless_mode&&this.consent.isOptedIn()&&this.reset(!0),this.consent.optInOut(!1),this._s(),"on_reject"===this.config.cookieless_mode&&(this.register({distinct_id:me,$device_id:null}),null==(e=this.sessionManager)||e.destroy(),null==(t=this.pageViewManager)||t.destroy(),this.sessionManager=void 0,this.sessionPropsManager=void 0,null==(i=this.sessionRecording)||i.stopRecording(),this.sessionRecording=void 0,this.hs())):$i.warn('Consent opt in/out is not valid with cookieless_mode="always" and will be ignored')}has_opted_in_capturing(){return this.consent.isOptedIn()}has_opted_out_capturing(){return this.consent.isOptedOut()}get_explicit_consent_status(){var e=this.consent.consent;return e===Mr.GRANTED?"granted":e===Mr.DENIED?"denied":"pending"}is_capturing(){return"always"===this.config.cookieless_mode||("on_reject"===this.config.cookieless_mode?this.consent.isExplicitlyOptedOut()||this.consent.isOptedIn():!this.has_opted_out_capturing())}clear_opt_in_out_capturing(){this.consent.reset(),this._s()}_is_bot(){return n?ko(n,this.config.custom_blocked_useragents):void 0}hs(){o&&("visible"===o.visibilityState?this.Wr||(this.Wr=!0,this.capture("$pageview",{title:o.title},{send_instantly:!0}),this.Gr&&(o.removeEventListener("visibilitychange",this.Gr),this.Gr=null)):this.Gr||(this.Gr=this.hs.bind(this),zi(o,"visibilitychange",this.Gr)))}debug(e){!1===e?(null==t||t.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(null==t||t.console.log("You're now in debug mode. All calls to PostHog will be logged in your console.\nYou can disable this with `posthog.debug(false)`."),this.set_config({debug:!0}))}O(){var e,t,i,r,n,s,o=this.Yr||{};return"advanced_disable_flags"in o?!!o.advanced_disable_flags:!1!==this.config.advanced_disable_flags?!!this.config.advanced_disable_flags:!0===this.config.advanced_disable_decide?($i.warn("Config field 'advanced_disable_decide' is deprecated. Please use 'advanced_disable_flags' instead. The old field will be removed in a future major version."),!0):(i="advanced_disable_decide",r=$i,n=(t="advanced_disable_flags")in(e=o)&&!M(e[t]),s=i in e&&!M(e[i]),n?e[t]:!!s&&(r&&r.warn("Config field '"+i+"' is deprecated. Please use '"+t+"' instead. The old field will be removed in a future major version."),e[i]))}cs(e){if(j(this.config.before_send))return e;var t=I(this.config.before_send)?this.config.before_send:[this.config.before_send],i=e;for(var r of t){if(i=r(i),j(i)){var n="Event '"+e.event+"' was rejected in beforeSend function";return H(e.event)?$i.warn(n+". This can cause unexpected behavior."):$i.info(n),null}i.properties&&!F(i.properties)||$i.warn("Event '"+e.event+"' has no properties after beforeSend function, this is likely an error.")}return i}getPageViewId(){var e;return null==(e=this.pageViewManager.Kt)?void 0:e.pageViewId}captureTraceFeedback(e,t){this.capture("$ai_feedback",{$ai_trace_id:String(e),$ai_feedback_text:t})}captureTraceMetric(e,t,i){this.capture("$ai_metric",{$ai_trace_id:String(e),$ai_metric_name:t,$ai_metric_value:String(i)})}Kr(e){var t=U(e)&&!e,i=Pr.H()&&"true"===Pr.q("ph_debug");return!t&&(!!i||e)}}!function(e,t){for(var i=0;i<t.length;i++)e.prototype[t[i]]=Ai(e.prototype[t[i]])}(Wo,["identify"]);var Go,Jo=(Go=Lo[Uo]=new Wo,function(){function e(){e.done||(e.done=!0,zo=!1,Ci(Lo,(function(e){e._dom_loaded()})))}null!=o&&o.addEventListener?"complete"===o.readyState?e():zi(o,"DOMContentLoaded",e,{capture:!1}):t&&$i.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")}(),Go),PostHogContext=React.createContext({client:Jo,bootstrap:void 0});function isDeepEqual(e,t,i){if(void 0===i&&(i=new WeakMap),e===t)return!0;if("object"!=typeof e||null===e||"object"!=typeof t||null===t)return!1;if(i.has(e)&&i.get(e)===t)return!0;i.set(e,t);var r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(var s=0,o=r;s<o.length;s++){var a=o[s];if(!n.includes(a))return!1;if(!isDeepEqual(e[a],t[a],i))return!1}return!0}function PostHogProvider(e){var t,i,r=e.children,n=e.client,s=e.apiKey,o=e.options,a=React.useRef(null),l=React.useMemo((function(){return n?(s&&console.warn("[PostHog.js] You have provided both `client` and `apiKey` to `PostHogProvider`. `apiKey` will be ignored in favour of `client`."),o&&console.warn("[PostHog.js] You have provided both `client` and `options` to `PostHogProvider`. `options` will be ignored in favour of `client`."),n):(s||console.warn("[PostHog.js] No `apiKey` or `client` were provided to `PostHogProvider`. Using default global `window.posthog` instance. You must initialize it manually. This is not recommended behavior."),Jo)}),[n,s,JSON.stringify(o)]);return React.useEffect((function(){if(!n){var e=a.current;e?(s!==e.apiKey&&console.warn("[PostHog.js] You have provided a different `apiKey` to `PostHogProvider` than the one that was already initialized. This is not supported by our provider and we'll keep using the previous key. If you need to toggle between API Keys you need to control the `client` yourself and pass it in as a prop rather than an `apiKey` prop."),o&&!isDeepEqual(o,e.options)&&Jo.set_config(o),a.current={apiKey:s,options:null!=o?o:{}}):(Jo.__loaded&&console.warn("[PostHog.js] `posthog` was already loaded elsewhere. This may cause issues."),Jo.init(s,o),a.current={apiKey:s,options:null!=o?o:{}})}}),[n,s,JSON.stringify(o)]),React.createElement(PostHogContext.Provider,{value:{client:l,bootstrap:null!==(t=null==o?void 0:o.bootstrap)&&void 0!==t?t:null===(i=null==n?void 0:n.config)||void 0===i?void 0:i.bootstrap}},r)}var isFunction=function(e){return"function"==typeof e},extendStatics=function(e,t){return(extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i])})(e,t)};function __extends(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function i(){this.constructor=e}extendStatics(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)}"function"==typeof SuppressedError&&SuppressedError;var INITIAL_STATE={componentStack:null,exceptionEvent:null,error:null},__POSTHOG_ERROR_MESSAGES={INVALID_FALLBACK:"[PostHog.js][PostHogErrorBoundary] Invalid fallback prop, provide a valid React element or a function that returns a valid React element."};!function(e){function t(t){var i=e.call(this,t)||this;return i.state=INITIAL_STATE,i}__extends(t,e),t.prototype.componentDidCatch=function(e,t){var i,r=this.props.additionalProperties;isFunction(r)?i=r(e):"object"==typeof r&&(i=r);var n=this.context.client.captureException(e,i),s=t.componentStack;this.setState({error:e,componentStack:null!=s?s:null,exceptionEvent:n})},t.prototype.render=function(){var e=this.props,t=e.children,i=e.fallback,r=this.state;if(null==r.componentStack)return isFunction(t)?t():t;var n=isFunction(i)?React.createElement(i,{error:r.error,componentStack:r.componentStack,exceptionEvent:r.exceptionEvent}):i;return React.isValidElement(n)?n:(console.warn(__POSTHOG_ERROR_MESSAGES.INVALID_FALLBACK),React.createElement(React.Fragment,null))},t.contextType=PostHogContext}(React.Component);const name="@twick/timeline",version="0.15.29",packageJson={name:name,version:version};function getPackageVersion(){return packageJson.version}function getPackageName(){return packageJson.name}const __vite_import_meta_env__={};function isAnalyticsEnabled(e){var t,i;if("undefined"!=typeof window){if(!0===window.__TWICK_ANALYTICS_DISABLED__||"false"===(null==__vite_import_meta_env__?void 0:__vite_import_meta_env__.VITE_TWICK_ANALYTICS_ENABLED)||"undefined"!=typeof process&&"false"===(null==(t=process.env)?void 0:t.TWICK_ANALYTICS_ENABLED))return!1}if(!1===(null==e?void 0:e.enabled))return!1;if(!0===(null==e?void 0:e.enabled))return!0;return"undefined"!=typeof window&&"true"===(null==__vite_import_meta_env__?void 0:__vite_import_meta_env__.VITE_TWICK_ANALYTICS_ENABLED)||"undefined"!=typeof process&&"true"===(null==(i=process.env)?void 0:i.TWICK_ANALYTICS_ENABLED)}function getPostHogApiKey(e){var t;return(null==e?void 0:e.apiKey)||"undefined"!=typeof window&&(null==__vite_import_meta_env__?void 0:__vite_import_meta_env__.VITE_POSTHOG_API_KEY)||"undefined"!=typeof process&&(null==(t=process.env)?void 0:t.POSTHOG_API_KEY)}function getPostHogApiHost(e){return(null==e?void 0:e.apiHost)||"https://us.i.posthog.com"}function trackEvent(e,t,i,r){if(isAnalyticsEnabled(r))try{const r=getPackageVersion(),n=getPackageName();e.capture(t,{...i,packageName:n,packageVersion:r,timestamp:(new Date).toISOString()})}catch(e){}}function getPostHogOptions(e,t){return{api_host:getPostHogApiHost(e),disable_session_recording:(null==e?void 0:e.disableSessionRecording)??!0,loaded:t}}const TimelineContext=React.createContext(void 0),TimelineProviderInner=({contextId:e,children:t,resolution:i,initialData:r})=>{const[n,s]=React.useState({type:TIMELINE_ACTION.NONE,payload:null}),[o,a]=React.useState(new Set),[l,c]=React.useState(!0),u=React.useCallback((e=>{a(e?new Set([e.getId()]):new Set)}),[]),d=React.useCallback((e=>{a(e)}),[]),[h,p]=React.useState(i??{width:720,height:1280}),[g,v]=React.useState(0),[m,f]=React.useState(0),_=useUndoRedo(),E=React.useRef(!1),y=()=>{f((e=>e+1))},b=React.useMemo((()=>{editorRegistry.has(e)&&editorRegistry.delete(e);const t=new TimelineEditor({contextId:e,setTotalDuration:v,setPresent:_.setPresent,handleUndo:_.undo,handleRedo:_.redo,handleResetHistory:_.resetHistory,updateChangeLog:y,setTimelineAction:(e,t)=>{s({type:e,payload:t})}});return editorRegistry.set(e,t),t}),[e]),w=React.useMemo((()=>{var e;if(0===o.size)return null;const t=(null==(e=b.getTimelineData())?void 0:e.tracks)??[];return resolveId([...o][0],t)}),[o,m,b]);React.useEffect((()=>{var e;const t=(null==(e=b.getTimelineData())?void 0:e.tracks)??[],i=new Set;for(const e of t){i.add(e.getId());for(const t of e.getElements())i.add(t.getId())}a((e=>{const t=new Set([...e].filter((e=>i.has(e))));return t.size===e.size?e:t}))}),[m,b]);React.useEffect((()=>{r&&!E.current&&((e=>{const t=_.getLastPersistedState();t?b.loadProject(t):b.loadProject(e)})(r),E.current=!0)}),[r]);const T={contextId:e,selectedItem:w,selectedIds:o,setSelection:d,timelineAction:n,totalDuration:g,changeLog:m,videoResolution:h,present:_.present,canUndo:_.canUndo,canRedo:_.canRedo,setVideoResolution:p,setSelectedItem:u,setTimelineAction:(e,t)=>{s({type:e,payload:t})},editor:b,followPlayheadEnabled:l,setFollowPlayheadEnabled:c};return jsxRuntime.jsx(TimelineContext.Provider,{value:T,children:t})},TimelineProvider=({contextId:e,children:t,resolution:i={width:720,height:1280},initialData:r,undoRedoPersistenceKey:n,maxHistorySize:s,analytics:o})=>{const a=isAnalyticsEnabled(o),l=getPostHogApiKey(o),c=getPostHogOptions(o,(t=>{trackEvent(t,"timeline_editor_created",{contextId:e,url:"undefined"!=typeof window?window.location.href:void 0,timestamp:(new Date).toISOString()})}));return a&&l?jsxRuntime.jsx(PostHogProvider,{apiKey:l,options:c,children:jsxRuntime.jsx(UndoRedoProvider,{persistenceKey:n,maxHistorySize:s,children:jsxRuntime.jsx(TimelineProviderInner,{resolution:i,initialData:r,contextId:e,undoRedoPersistenceKey:n,maxHistorySize:s,analytics:o,children:t})})}):jsxRuntime.jsx(UndoRedoProvider,{persistenceKey:n,maxHistorySize:s,children:jsxRuntime.jsx(TimelineProviderInner,{resolution:i,initialData:r,contextId:e,undoRedoPersistenceKey:n,maxHistorySize:s,analytics:o,children:t})})},useTimelineContext=()=>{const e=React.useContext(TimelineContext);if(void 0===e)throw new Error("useTimelineContext must be used within a TimelineProvider");return e};class Watermark{constructor(e){__publicField(this,"id"),__publicField(this,"type"),__publicField(this,"position"),__publicField(this,"rotation"),__publicField(this,"opacity"),__publicField(this,"props"),this.type=e,this.id="e-watermark"}getId(){return this.id}getType(){return this.type}getPosition(){return this.position}getRotation(){return this.rotation}getOpacity(){return this.opacity}getProps(){return"text"===this.type||"image"===this.type?this.props:void 0}setProps(e){return("text"===this.type||"image"===this.type)&&(this.props=e),this}setPosition(e){return this.position=e,this}setRotation(e){return this.rotation=e,this}setOpacity(e){return this.opacity=e,this}toJSON(){return{id:"e-watermark",type:this.type,position:this.position,rotation:this.rotation,opacity:this.opacity,props:this.props}}static fromJSON(e){const t=new Watermark(e.type);return t.setPosition(e.position??{x:0,y:0}),t.setRotation(e.rotation??0),t.setOpacity(e.opacity??1),t.setProps(e.props),t}}function formatTimeWithFrames(e,t=30){const i=Math.max(0,e),r=Math.floor(i/60),n=Math.floor(i%60),s=Math.floor(i%1*t);return`${r.toString().padStart(2,"0")}:${n.toString().padStart(2,"0")}.${s.toString().padStart(2,"0")}`}function formatTimeSimple(e){const t=Math.max(0,e),i=Math.floor(t/60),r=Math.floor(t%60);return`${i.toString().padStart(2,"0")}:${r.toString().padStart(2,"0")}`}const pad=(e,t=2)=>String(e).padStart(t,"0"),toSrtTime=e=>{const t=Math.max(0,Math.floor(1e3*e)),i=t%1e3,r=Math.floor(t/1e3),n=r%60,s=Math.floor(r/60),o=s%60,a=Math.floor(s/60);return`${pad(a)}:${pad(o)}:${pad(n)},${pad(i,3)}`},toVttTime=e=>{const t=Math.max(0,Math.floor(1e3*e)),i=t%1e3,r=Math.floor(t/1e3),n=r%60,s=Math.floor(r/60),o=s%60,a=Math.floor(s/60);return`${pad(a)}:${pad(o)}:${pad(n)}.${pad(i,3)}`},getCaptionText=e=>{var t;const i="string"==typeof e.t?e.t:"",r="string"==typeof(null==(t=e.props)?void 0:t.text)?e.props.text:"";return(i||r).trim()},getCaptionElements=(e,t)=>(e.tracks||[]).filter((e=>"caption"===e.type&&(!t||(e.language||"default")===t))).flatMap((e=>e.elements||[])).filter((e=>"caption"===e.type)).map((e=>({s:e.s,e:e.e,text:getCaptionText(e)}))).filter((e=>e.text&&e.e>e.s)).sort(((e,t)=>e.s-t.s)),getCaptionLanguages=e=>{const t=(e.tracks||[]).filter((e=>"caption"===e.type)).map((e=>e.language||"default"));return[...new Set(t)]},exportCaptionsAsSRT=(e,t)=>getCaptionElements(e,t).map(((e,t)=>`${t+1}\n${toSrtTime(e.s)} --\x3e ${toSrtTime(e.e)}\n${e.text}\n`)).join("\n"),exportCaptionsAsVTT=(e,t)=>`WEBVTT\n\n${getCaptionElements(e,t).map((e=>`${toVttTime(e.s)} --\x3e ${toVttTime(e.e)}\n${e.text}\n`)).join("\n")}`.trimEnd(),formatSeconds=e=>{const t=Math.max(0,Math.floor(e)),i=Math.floor(t/3600),r=Math.floor(t%3600/60),n=t%60;return i>0?`${i}:${String(r).padStart(2,"0")}:${String(n).padStart(2,"0")}`:`${r}:${String(n).padStart(2,"0")}`},getChapterMarkers=e=>{var t;return[...(null==(t=e.metadata)?void 0:t.chapters)??[]].sort(((e,t)=>e.time-t.time))},exportChaptersAsYouTube=e=>getChapterMarkers(e).map((e=>`${formatSeconds(e.time)} ${e.title}`)).join("\n"),exportChaptersAsJSON=e=>JSON.stringify(getChapterMarkers(e),null,2);function snapTime(e,t,i=.1){if(0===t.length||i<=0)return{time:e,didSnap:!1};let r,n=i;for(const i of t){const t=Math.abs(e-i);t<n&&(n=t,r=i)}return void 0!==r?{time:r,didSnap:!0,snapTarget:r}:{time:e,didSnap:!1}}function pxToSecThreshold(e,t){return t<=0?1/0:e/t}function computeCaptionGeometry(e,t){const i=e??8;return{lineWidth:t===CAPTION_STYLE.WORD_BG_HIGHLIGHT?.1:parseFloat((.05*i).toFixed(3)),rectProps:{gap:t===CAPTION_STYLE.WORD_BG_HIGHLIGHT?0:Math.round(.2*i)}}}"undefined"!=typeof window&&(window.Twick={Track:Track,TrackElement:TrackElement,ElementDeserializer:ElementDeserializer,ElementSerializer:ElementSerializer,ElementValidator:ElementValidator,ElementAdder:ElementAdder,ElementRemover:ElementRemover,ElementUpdater:ElementUpdater,ElementSplitter:ElementSplitter,ElementCloner:ElementCloner,TimelineEditor:TimelineEditor,TimelineProvider:TimelineProvider,TIMELINE_ELEMENT_TYPE:TIMELINE_ELEMENT_TYPE,CaptionElement:CaptionElement,RectElement:RectElement,TextElement:TextElement,ImageElement:ImageElement,AudioElement:AudioElement,CircleElement:CircleElement,IconElement:IconElement,EmojiElement:EmojiElement,VideoElement:VideoElement,PlaceholderElement:PlaceholderElement,ArrowElement:ArrowElement,LineElement:LineElement,ElementAnimation:ElementAnimation,ElementFrameEffect:ElementFrameEffect,ElementTextEffect:ElementTextEffect,generateShortUuid:generateShortUuid,getTotalDuration:getTotalDuration,getCurrentElements:getCurrentElements,isTrackId:isTrackId,isElementId:isElementId}),exports.ArrowElement=ArrowElement,exports.AudioElement=AudioElement,exports.CAPTION_COLOR=CAPTION_COLOR,exports.CAPTION_FONT=CAPTION_FONT,exports.CAPTION_STYLE=CAPTION_STYLE,exports.CAPTION_STYLE_OPTIONS=CAPTION_STYLE_OPTIONS,exports.COLOR_FILTERS=COLOR_FILTERS,exports.CURRENT_PROJECT_VERSION=2,exports.CaptionElement=CaptionElement,exports.CircleElement=CircleElement,exports.EffectElement=EffectElement,exports.ElementAdder=ElementAdder,exports.ElementAnimation=ElementAnimation,exports.ElementCloner=ElementCloner,exports.ElementDeserializer=ElementDeserializer,exports.ElementFrameEffect=ElementFrameEffect,exports.ElementRemover=ElementRemover,exports.ElementSerializer=ElementSerializer,exports.ElementSplitter=ElementSplitter,exports.ElementTextEffect=ElementTextEffect,exports.ElementUpdater=ElementUpdater,exports.ElementValidator=ElementValidator,exports.EmojiElement=EmojiElement,exports.INITIAL_TIMELINE_DATA=INITIAL_TIMELINE_DATA,exports.IconElement=IconElement,exports.ImageElement=ImageElement,exports.LineElement=LineElement,exports.PLAYER_STATE=PLAYER_STATE,exports.PROCESS_STATE=PROCESS_STATE,exports.PlaceholderElement=PlaceholderElement,exports.RectElement=RectElement,exports.SPLIT_EDGE_BUFFER_SEC=.1,exports.TIMELINE_ACTION=TIMELINE_ACTION,exports.TIMELINE_ELEMENT_TYPE=TIMELINE_ELEMENT_TYPE,exports.TRACK_TYPES=TRACK_TYPES,exports.TextElement=TextElement,exports.TimelineEditor=TimelineEditor,exports.TimelineProvider=TimelineProvider,exports.Track=Track,exports.TrackElement=TrackElement,exports.VALIDATION_ERROR_CODE=VALIDATION_ERROR_CODE,exports.ValidationError=ValidationError,exports.VideoElement=VideoElement,exports.WORDS_PER_PHRASE=4,exports.Watermark=Watermark,exports.canSplitElement=canSplitElement,exports.computeCaptionGeometry=computeCaptionGeometry,exports.exportCaptionsAsSRT=exportCaptionsAsSRT,exports.exportCaptionsAsVTT=exportCaptionsAsVTT,exports.exportChaptersAsJSON=exportChaptersAsJSON,exports.exportChaptersAsYouTube=exportChaptersAsYouTube,exports.extractVideoAudio=extractVideoAudio,exports.formatTimeSimple=formatTimeSimple,exports.formatTimeWithFrames=formatTimeWithFrames,exports.generateShortUuid=generateShortUuid,exports.getCaptionElements=getCaptionElements,exports.getCaptionLanguages=getCaptionLanguages,exports.getChapterMarkers=getChapterMarkers,exports.getCurrentElements=getCurrentElements,exports.getDecimalNumber=getDecimalNumber,exports.getElementIdsInRange=getElementIdsInRange,exports.getTotalDuration=getTotalDuration,exports.isElementId=isElementId,exports.isTrackId=isTrackId,exports.migrateProject=migrateProject,exports.pxToSecThreshold=pxToSecThreshold,exports.resolveId=resolveId,exports.resolveIds=resolveIds,exports.snapTime=snapTime,exports.useTimelineContext=useTimelineContext;
//# sourceMappingURL=/sm/4b1341d5db696079bf0c66fc3ef4c62389668a7675aaf52efc132808b007f1f0.map