@mevdragon/vidfarm-devcli 0.18.1 → 0.19.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.agents/skills/editor-capabilities/SKILL.md +166 -0
- package/.agents/skills/editor-capabilities/references/re-theme-walkthrough.md +58 -0
- package/.agents/skills/vidfarm-media/SKILL.md +2 -0
- package/SKILL.director.md +174 -16
- package/SKILL.platform.md +7 -3
- package/demo/dist/app.css +1 -1
- package/demo/dist/app.js +77 -75
- package/dist/src/app.js +1513 -145
- package/dist/src/cli.js +1365 -105
- package/dist/src/config.js +7 -0
- package/dist/src/devcli/clips.js +3 -0
- package/dist/src/devcli/composition-edit.js +396 -8
- package/dist/src/devcli/local-backend.js +123 -0
- package/dist/src/devcli/migrate-local.js +140 -0
- package/dist/src/devcli/sync.js +311 -0
- package/dist/src/devcli/timeline-edit.js +208 -1
- package/dist/src/editor-chat.js +33 -17
- package/dist/src/frontend/file-directory.js +271 -20
- package/dist/src/frontend/homepage-view.js +3 -3
- package/dist/src/frontend/template-editor-chat.js +6 -3
- package/dist/src/page-shell.js +1 -1
- package/dist/src/primitive-registry.js +409 -4
- package/dist/src/reskin/chat-page.js +103 -15
- package/dist/src/reskin/discover-page.js +247 -10
- package/dist/src/reskin/document.js +147 -10
- package/dist/src/reskin/inpaint-clipper-page.js +649 -0
- package/dist/src/reskin/inpaint-page.js +2459 -452
- package/dist/src/reskin/inpaint-video-page.js +1339 -0
- package/dist/src/reskin/library-page.js +324 -82
- package/dist/src/reskin/theme.js +36 -11
- package/dist/src/services/billing.js +4 -0
- package/dist/src/services/clip-curation/hunt.js +2 -0
- package/dist/src/services/clip-records.js +28 -0
- package/dist/src/services/file-directory.js +6 -3
- package/dist/src/services/hyperframes.js +283 -3
- package/dist/src/services/serverless-records.js +43 -0
- package/dist/src/services/storage.js +24 -2
- package/package.json +1 -1
- package/public/assets/file-directory-app.js +2 -2
- package/public/assets/homepage-client-app.js +1 -1
- package/public/assets/page-runtime-client-app.js +2 -2
- package/public/assets/placeholders/scene-placeholder.png +0 -0
|
@@ -30,7 +30,7 @@ now you can use replayer.getMirror() to access the mirror instance of a replayer
|
|
|
30
30
|
or you can use record.mirror to access the mirror instance during recording.`,KE={map:{},getId(){return console.error(Rs),-1},getNode(){return console.error(Rs),null},removeNodeFromMap(){console.error(Rs)},has(){return console.error(Rs),!1},reset(){console.error(Rs)}};typeof window<"u"&&window.Proxy&&window.Reflect&&(KE=new Proxy(KE,{get(e,t,n){return t==="map"&&console.error(Rs),Reflect.get(e,t,n)}}));function vl(e,t,n={}){let r=null,o=0;return function(...i){let s=Date.now();!o&&n.leading===!1&&(o=s);let a=t-(s-o),l=this;a<=0||a>t?(r&&(IM(r),r=null),o=s,e.apply(l,i)):!r&&n.trailing!==!1&&(r=od(()=>{o=n.leading===!1?0:Date.now(),r=null,e.apply(l,i)},a))}}function ET(e,t,n,r,o=window){let i=o.Object.getOwnPropertyDescriptor(e,t);return o.Object.defineProperty(e,t,r?n:{set(s){od(()=>{n.set.call(this,s)},0),i&&i.set&&i.set.call(this,s)}}),()=>ET(e,t,i||{},!0)}function Sh(e,t,n){try{if(!(t in e))return()=>{};let r=e[t],o=n(r);return typeof o=="function"&&(o.prototype=o.prototype||{},Object.defineProperties(o,{__rrweb_original__:{enumerable:!1,value:r}})),e[t]=o,()=>{e[t]=r}}catch{return()=>{}}}var Gu=Date.now;/[1-9][0-9]{12}/.test(Date.now().toString())||(Gu=()=>new Date().getTime());function TT(e){let t=e.document;return{left:t.scrollingElement?t.scrollingElement.scrollLeft:e.pageXOffset!==void 0?e.pageXOffset:t?.documentElement.scrollLeft||t?.body?.parentElement?.scrollLeft||t?.body?.scrollLeft||0,top:t.scrollingElement?t.scrollingElement.scrollTop:e.pageYOffset!==void 0?e.pageYOffset:t?.documentElement.scrollTop||t?.body?.parentElement?.scrollTop||t?.body?.scrollTop||0}}function IT(){return window.innerHeight||document.documentElement&&document.documentElement.clientHeight||document.body&&document.body.clientHeight}function wT(){return window.innerWidth||document.documentElement&&document.documentElement.clientWidth||document.body&&document.body.clientWidth}function CT(e){if(!e)return null;try{return e.nodeType===e.ELEMENT_NODE?e:e.parentElement}catch{return null}}function Nn(e,t,n,r,o){if(!e)return!1;let i=CT(e);if(!i)return!1;let s=ks(t,n);if(!o){let c=r&&i.matches(r);return s(i)&&!c}let a=wi(i,s),l=-1;return a<0?!1:(r&&(l=wi(i,ks(null,r))),a>-1&&l<0?!0:a<l)}function SM(e,t){return t.getId(e)!==-1}function Fm(e,t){return t.getId(e)===_l}function RT(e,t){if(hl(e))return!1;let n=t.getId(e);return t.has(n)?e.parentNode&&e.parentNode.nodeType===e.DOCUMENT_NODE?!1:e.parentNode?RT(e.parentNode,t):!0:!0}function Gm(e){return!!e.changedTouches}function _M(e=window){"NodeList"in e&&!e.NodeList.prototype.forEach&&(e.NodeList.prototype.forEach=Array.prototype.forEach),"DOMTokenList"in e&&!e.DOMTokenList.prototype.forEach&&(e.DOMTokenList.prototype.forEach=Array.prototype.forEach),Node.prototype.contains||(Node.prototype.contains=(...t)=>{let n=t[0];if(!(0 in t))throw new TypeError("1 argument is required");do if(this===n)return!0;while(n=n&&n.parentNode);return!1})}function xT(e,t){return!!(e.nodeName==="IFRAME"&&t.getMeta(e))}function bT(e,t){return!!(e.nodeName==="LINK"&&e.nodeType===e.ELEMENT_NODE&&e.getAttribute&&e.getAttribute("rel")==="stylesheet"&&t.getMeta(e))}function Vm(e){return!!e?.shadowRoot}var qm=class{constructor(){this.id=1,this.styleIDMap=new WeakMap,this.idStyleMap=new Map}getId(t){return this.styleIDMap.get(t)??-1}has(t){return this.styleIDMap.has(t)}add(t,n){if(this.has(t))return this.getId(t);let r;return n===void 0?r=this.id++:r=n,this.styleIDMap.set(t,r),this.idStyleMap.set(r,t),r}getStyle(t){return this.idStyleMap.get(t)||null}reset(){this.styleIDMap=new WeakMap,this.idStyleMap=new Map,this.id=1}generateId(){return this.id++}};function kT(e){let t=null;return e.getRootNode?.()?.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&e.getRootNode().host&&(t=e.getRootNode().host),t}function vM(e){let t=e,n;for(;n=kT(t);)t=n;return t}function EM(e){let t=e.ownerDocument;if(!t)return!1;let n=vM(e);return t.contains(n)}function NT(e){let t=e.ownerDocument;return t?t.contains(e)||EM(e):!1}var JE={};function _h(e){let t=JE[e];if(t)return t;let n=window.document,r=window[e];if(n&&typeof n.createElement=="function")try{let o=n.createElement("iframe");o.hidden=!0,n.head.appendChild(o);let i=o.contentWindow;i&&i[e]&&(r=i[e]),n.head.removeChild(o)}catch{}return JE[e]=r.bind(window)}function TM(...e){return _h("requestAnimationFrame")(...e)}function od(...e){return _h("setTimeout")(...e)}function IM(...e){return _h("clearTimeout")(...e)}var me=(e=>(e[e.DomContentLoaded=0]="DomContentLoaded",e[e.Load=1]="Load",e[e.FullSnapshot=2]="FullSnapshot",e[e.IncrementalSnapshot=3]="IncrementalSnapshot",e[e.Meta=4]="Meta",e[e.Custom=5]="Custom",e[e.Plugin=6]="Plugin",e))(me||{}),se=(e=>(e[e.Mutation=0]="Mutation",e[e.MouseMove=1]="MouseMove",e[e.MouseInteraction=2]="MouseInteraction",e[e.Scroll=3]="Scroll",e[e.ViewportResize=4]="ViewportResize",e[e.Input=5]="Input",e[e.TouchMove=6]="TouchMove",e[e.MediaInteraction=7]="MediaInteraction",e[e.StyleSheetRule=8]="StyleSheetRule",e[e.CanvasMutation=9]="CanvasMutation",e[e.Font=10]="Font",e[e.Log=11]="Log",e[e.Drag=12]="Drag",e[e.StyleDeclaration=13]="StyleDeclaration",e[e.Selection=14]="Selection",e[e.AdoptedStyleSheet=15]="AdoptedStyleSheet",e[e.CustomElement=16]="CustomElement",e))(se||{}),nn=(e=>(e[e.MouseUp=0]="MouseUp",e[e.MouseDown=1]="MouseDown",e[e.Click=2]="Click",e[e.ContextMenu=3]="ContextMenu",e[e.DblClick=4]="DblClick",e[e.Focus=5]="Focus",e[e.Blur=6]="Blur",e[e.TouchStart=7]="TouchStart",e[e.TouchMove_Departed=8]="TouchMove_Departed",e[e.TouchEnd=9]="TouchEnd",e[e.TouchCancel=10]="TouchCancel",e))(nn||{}),Zr=(e=>(e[e.Mouse=0]="Mouse",e[e.Pen=1]="Pen",e[e.Touch=2]="Touch",e))(Zr||{}),xs=(e=>(e[e.Play=0]="Play",e[e.Pause=1]="Pause",e[e.Seeked=2]="Seeked",e[e.VolumeChange=3]="VolumeChange",e[e.RateChange=4]="RateChange",e))(xs||{}),yl;function wM(e){yl=e}function CM(){yl=void 0}var Ce=e=>yl?((...n)=>{try{return e(...n)}catch(r){if(yl&&yl(r)===!0)return()=>{};throw r}}):e,XE="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",RM=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(pl=0;pl<XE.length;pl++)RM[XE.charCodeAt(pl)]=pl;var pl,Vu=class{reset(){}freeze(){}unfreeze(){}lock(){}unlock(){}snapshot(){}addWindow(){}addShadowRoot(){}resetShadowRoots(){}};function vh(e){try{return e.contentDocument}catch{}}function El(e){try{return e.contentWindow}catch{}}var Ym=class{constructor(t){this.doc=t,this.unattachedDoc=null}parse(t){return this.parseWithConstructableStylesheet(t)||this.parseWithDetachedElement(t)}parseWithConstructableStylesheet(t){if(typeof CSSStyleSheet>"u"||typeof CSSStyleSheet.prototype.replaceSync!="function")return null;try{let n=new CSSStyleSheet;n.replaceSync(`x { ${t} }`);let r=n.cssRules[0];return!r||r.type!==CSSRule.STYLE_RULE?null:r.style}catch{return null}}parseWithDetachedElement(t){let n=this.getUnattachedDoc().createElement("span");return n.setAttribute("style",t),n.style}getUnattachedDoc(){if(!this.unattachedDoc)try{this.unattachedDoc=document.implementation.createHTMLDocument()}catch{this.unattachedDoc=this.doc}return this.unattachedDoc}};function QE(e){return"__ln"in e}var Km=class{constructor(){this.length=0,this.head=null,this.tail=null}get(t){if(t>=this.length)throw new Error("Position outside of list range");let n=this.head;for(let r=0;r<t;r++)n=n?.next||null;return n}addNode(t){let n={value:t,previous:null,next:null};if(t.__ln=n,t.previousSibling&&QE(t.previousSibling)){let r=t.previousSibling.__ln.next;n.next=r,n.previous=t.previousSibling.__ln,t.previousSibling.__ln.next=n,r&&(r.previous=n)}else if(t.nextSibling&&QE(t.nextSibling)&&t.nextSibling.__ln.previous){let r=t.nextSibling.__ln.previous;n.previous=r,n.next=t.nextSibling.__ln,t.nextSibling.__ln.previous=n,r&&(r.next=n)}else this.head&&(this.head.previous=n),n.next=this.head,this.head=n;n.next===null&&(this.tail=n),this.length++}removeNode(t){let n=t.__ln;this.head&&(n.previous?(n.previous.next=n.next,n.next?n.next.previous=n.previous:this.tail=n.previous):(this.head=n.next,this.head?this.head.previous=null:this.tail=null),t.__ln&&delete t.__ln,this.length--)}},ZE=(e,t)=>`${e}@${t}`,Jm=class{constructor(){this.frozen=!1,this.locked=!1,this.texts=[],this.attributes=[],this.attributeMap=new WeakMap,this.removes=[],this.mapRemoves=[],this.movedMap={},this.addedSet=new Set,this.movedSet=new Set,this.droppedSet=new Set,this.processMutations=t=>{t.forEach(this.processMutation),this.emit()},this.emit=()=>{if(this.frozen||this.locked)return;let t=[],n=new Set,r=new Km,o=l=>{let c=l,u=_l;for(;u===_l;)c=c&&c.nextSibling,u=c&&this.mirror.getId(c);return u},i=l=>{if(!l.parentNode||!NT(l))return;let c=hl(l.parentNode)?this.mirror.getId(kT(l)):this.mirror.getId(l.parentNode),u=o(l);if(c===-1||u===-1)return r.addNode(l);let f=Ns(l,{doc:this.doc,mirror:this.mirror,blockClass:this.blockClass,blockSelector:this.blockSelector,maskAllText:this.maskAllText,unblockSelector:this.unblockSelector,maskTextClass:this.maskTextClass,unmaskTextClass:this.unmaskTextClass,maskTextSelector:this.maskTextSelector,unmaskTextSelector:this.unmaskTextSelector,skipChild:!0,newlyAddedElement:!0,inlineStylesheet:this.inlineStylesheet,maskInputOptions:this.maskInputOptions,maskAttributeFn:this.maskAttributeFn,maskTextFn:this.maskTextFn,maskInputFn:this.maskInputFn,slimDOMOptions:this.slimDOMOptions,dataURLOptions:this.dataURLOptions,recordCanvas:this.recordCanvas,inlineImages:this.inlineImages,onSerialize:p=>{xT(p,this.mirror)&&!Nn(p,this.blockClass,this.blockSelector,this.unblockSelector,!1)&&this.iframeManager.addIframe(p),bT(p,this.mirror)&&this.stylesheetManager.trackLinkElement(p),Vm(l)&&this.shadowDomManager.addShadowRoot(l.shadowRoot,this.doc)},onIframeLoad:(p,h)=>{if(Nn(p,this.blockClass,this.blockSelector,this.unblockSelector,!1))return;this.iframeManager.attachIframe(p,h);let y=El(p);y&&this.canvasManager.addWindow(y),this.shadowDomManager.observeAttachShadow(p)},onStylesheetLoad:(p,h)=>{this.stylesheetManager.attachLinkElement(p,h)},onBlockedImageLoad:(p,h,{width:y,height:_})=>{this.mutationCb({adds:[],removes:[],texts:[],attributes:[{id:h.id,attributes:{style:{width:`${y}px`,height:`${_}px`}}}]})},ignoreCSSAttributes:this.ignoreCSSAttributes});f&&(t.push({parentId:c,nextId:u,node:f}),n.add(f.id))};for(;this.mapRemoves.length;)this.mirror.removeNodeFromMap(this.mapRemoves.shift());for(let l of this.movedSet)eT(this.removes,l,this.mirror)&&!this.movedSet.has(l.parentNode)||i(l);for(let l of this.addedSet)!tT(this.droppedSet,l)&&!eT(this.removes,l,this.mirror)||tT(this.movedSet,l)?i(l):this.droppedSet.add(l);let s=null;for(;r.length;){let l=null;if(s){let c=this.mirror.getId(s.value.parentNode),u=o(s.value);c!==-1&&u!==-1&&(l=s)}if(!l){let c=r.tail;for(;c;){let u=c;if(c=c.previous,u){let f=this.mirror.getId(u.value.parentNode);if(o(u.value)===-1)continue;if(f!==-1){l=u;break}else{let h=u.value;if(h.parentNode&&h.parentNode.nodeType===Node.DOCUMENT_FRAGMENT_NODE){let y=h.parentNode.host;if(this.mirror.getId(y)!==-1){l=u;break}}}}}}if(!l){for(;r.head;)r.removeNode(r.head.value);break}s=l.previous,r.removeNode(l.value),i(l.value)}let a={texts:this.texts.map(l=>({id:this.mirror.getId(l.node),value:l.value})).filter(l=>!n.has(l.id)).filter(l=>this.mirror.has(l.id)),attributes:this.attributes.map(l=>{let{attributes:c}=l;if(typeof c.style=="string"){let u=JSON.stringify(l.styleDiff),f=JSON.stringify(l._unchangedStyles);u.length<c.style.length&&(u+f).split("var(").length===c.style.split("var(").length&&(c.style=l.styleDiff)}return{id:this.mirror.getId(l.node),attributes:c}}).filter(l=>!n.has(l.id)).filter(l=>this.mirror.has(l.id)),removes:this.removes,adds:t};!a.texts.length&&!a.attributes.length&&!a.removes.length&&!a.adds.length||(this.texts=[],this.attributes=[],this.attributeMap=new WeakMap,this.removes=[],this.addedSet=new Set,this.movedSet=new Set,this.droppedSet=new Set,this.movedMap={},this.mutationCb(a))},this.processMutation=t=>{if(!Fm(t.target,this.mirror))switch(t.type){case"characterData":{let n=t.target.textContent;!Nn(t.target,this.blockClass,this.blockSelector,this.unblockSelector,!1)&&n!==t.oldValue&&this.texts.push({value:Ps(t.target,this.maskTextClass,this.maskTextSelector,this.unmaskTextClass,this.unmaskTextSelector,this.maskAllText)&&n?this.maskTextFn?this.maskTextFn(n,CT(t.target)):n.replace(/[\S]/g,"*"):n,node:t.target});break}case"attributes":{let n=t.target,r=t.attributeName,o=t.target.getAttribute(r);if(r==="value"){let s=gh(n),a=n.tagName;o=ju(n,a,s);let l=nd({maskInputOptions:this.maskInputOptions,tagName:a,type:s}),c=Ps(t.target,this.maskTextClass,this.maskTextSelector,this.unmaskTextClass,this.unmaskTextSelector,l);o=Sl({isMasked:c,element:n,value:o,maskInputFn:this.maskInputFn})}if(Nn(t.target,this.blockClass,this.blockSelector,this.unblockSelector,!1)||o===t.oldValue)return;let i=this.attributeMap.get(t.target);if(n.tagName==="IFRAME"&&r==="src"&&!this.keepIframeSrcFn(o))if(!vh(n))r="rr_src";else return;if(i||(i={node:t.target,attributes:{},styleDiff:{},_unchangedStyles:{}},this.attributes.push(i),this.attributeMap.set(t.target,i)),r==="type"&&n.tagName==="INPUT"&&(t.oldValue||"").toLowerCase()==="password"&&n.setAttribute("data-rr-is-password","true"),!vT(n.tagName,r)&&(i.attributes[r]=_T(this.doc,Ms(n.tagName),Ms(r),o,n,this.maskAttributeFn),r==="style")){let s=t.oldValue?this.styleDeclarationParser.parse(t.oldValue):null;for(let a of Array.from(n.style)){let l=n.style.getPropertyValue(a),c=n.style.getPropertyPriority(a);l!==(s?.getPropertyValue(a)||"")||c!==(s?.getPropertyPriority(a)||"")?c===""?i.styleDiff[a]=l:i.styleDiff[a]=[l,c]:i._unchangedStyles[a]=[l,c]}if(s)for(let a of Array.from(s))n.style.getPropertyValue(a)===""&&(i.styleDiff[a]=!1)}break}case"childList":{if(Nn(t.target,this.blockClass,this.blockSelector,this.unblockSelector,!0))return;t.addedNodes.forEach(n=>this.genAdds(n,t.target)),t.removedNodes.forEach(n=>{let r=this.mirror.getId(n),o=hl(t.target)?this.mirror.getId(t.target.host):this.mirror.getId(t.target);Nn(t.target,this.blockClass,this.blockSelector,this.unblockSelector,!1)||Fm(n,this.mirror)||!SM(n,this.mirror)||(this.addedSet.has(n)?(Xm(this.addedSet,n),this.droppedSet.add(n)):this.addedSet.has(t.target)&&r===-1||RT(t.target,this.mirror)||(this.movedSet.has(n)&&this.movedMap[ZE(r,o)]?Xm(this.movedSet,n):this.removes.push({parentId:o,id:r,isShadow:hl(t.target)&&gl(t.target)?!0:void 0})),this.mapRemoves.push(n))});break}}},this.genAdds=(t,n)=>{if(!this.processedNodeManager.inOtherBuffer(t,this)&&!(this.addedSet.has(t)||this.movedSet.has(t))){if(this.mirror.hasNode(t)){if(Fm(t,this.mirror))return;this.movedSet.add(t);let r=null;n&&this.mirror.hasNode(n)&&(r=this.mirror.getId(n)),r&&r!==-1&&(this.movedMap[ZE(this.mirror.getId(t),r)]=!0)}else this.addedSet.add(t),this.droppedSet.delete(t);Nn(t,this.blockClass,this.blockSelector,this.unblockSelector,!1)||(t.childNodes&&t.childNodes.forEach(r=>this.genAdds(r)),Vm(t)&&t.shadowRoot.childNodes.forEach(r=>{this.processedNodeManager.add(r,this),this.genAdds(r,t)}))}}}init(t){["mutationCb","blockClass","blockSelector","unblockSelector","maskAllText","maskTextClass","unmaskTextClass","maskTextSelector","unmaskTextSelector","inlineStylesheet","maskInputOptions","maskAttributeFn","maskTextFn","maskInputFn","keepIframeSrcFn","recordCanvas","inlineImages","slimDOMOptions","dataURLOptions","doc","mirror","iframeManager","stylesheetManager","shadowDomManager","canvasManager","processedNodeManager","ignoreCSSAttributes"].forEach(n=>{this[n]=t[n]}),this.styleDeclarationParser=new Ym(this.doc)}freeze(){this.frozen=!0,this.canvasManager.freeze()}unfreeze(){this.frozen=!1,this.canvasManager.unfreeze(),this.emit()}isFrozen(){return this.frozen}lock(){this.locked=!0,this.canvasManager.lock()}unlock(){this.locked=!1,this.canvasManager.unlock(),this.emit()}reset(){this.shadowDomManager.reset(),this.canvasManager.reset()}};function Xm(e,t){e.delete(t),t.childNodes?.forEach(n=>Xm(e,n))}function eT(e,t,n){return e.length===0?!1:xM(e,t,n)}function xM(e,t,n){let r=t.parentNode;for(;r;){let o=n.getId(r);if(e.some(i=>i.id===o))return!0;r=r.parentNode}return!1}function tT(e,t){return e.size===0?!1:AT(e,t)}function AT(e,t){let{parentNode:n}=t;return n?e.has(n)?!0:AT(e,n):!1}var As=[];function Rl(e){try{if("composedPath"in e){let t=e.composedPath();if(t.length)return t[0]}else if("path"in e&&e.path.length)return e.path[0]}catch{}return e&&e.target}function MT(e,t){let n=new Jm;As.push(n),n.init(e);let r=window.MutationObserver||window.__rrMutationObserver,o=window?.Zone?.__symbol__?.("MutationObserver");o&&window[o]&&(r=window[o]);let i=new r(Ce(s=>{e.onMutation&&e.onMutation(s)===!1||n.processMutations.bind(n)(s)}));return i.observe(t,{attributes:!0,attributeOldValue:!0,characterData:!0,characterDataOldValue:!0,childList:!0,subtree:!0}),i}function bM({mousemoveCb:e,sampling:t,doc:n,mirror:r}){if(t.mousemove===!1)return()=>{};let o=typeof t.mousemove=="number"?t.mousemove:50,i=typeof t.mousemoveCallback=="number"?t.mousemoveCallback:500,s=[],a,l=vl(Ce(f=>{let p=Date.now()-a;e(s.map(h=>(h.timeOffset-=p,h)),f),s=[],a=null}),i),c=Ce(vl(Ce(f=>{let p=Rl(f),{clientX:h,clientY:y}=Gm(f)?f.changedTouches[0]:f;a||(a=Gu()),s.push({x:h,y,id:r.getId(p),timeOffset:Gu()-a}),l(typeof DragEvent<"u"&&f instanceof DragEvent?se.Drag:f instanceof MouseEvent?se.MouseMove:se.TouchMove)}),o,{trailing:!1})),u=[rn("mousemove",c,n),rn("touchmove",c,n),rn("drag",c,n)];return Ce(()=>{u.forEach(f=>f())})}function kM({mouseInteractionCb:e,doc:t,mirror:n,blockClass:r,blockSelector:o,unblockSelector:i,sampling:s}){if(s.mouseInteraction===!1)return()=>{};let a=s.mouseInteraction===!0||s.mouseInteraction===void 0?{}:s.mouseInteraction,l=[],c=null,u=f=>p=>{let h=Rl(p);if(Nn(h,r,o,i,!0))return;let y=null,_=f;if("pointerType"in p){switch(p.pointerType){case"mouse":y=Zr.Mouse;break;case"touch":y=Zr.Touch;break;case"pen":y=Zr.Pen;break}y===Zr.Touch?nn[f]===nn.MouseDown?_="TouchStart":nn[f]===nn.MouseUp&&(_="TouchEnd"):Zr.Pen}else Gm(p)&&(y=Zr.Touch);y!==null?(c=y,(_.startsWith("Touch")&&y===Zr.Touch||_.startsWith("Mouse")&&y===Zr.Mouse)&&(y=null)):nn[f]===nn.Click&&(y=c,c=null);let T=Gm(p)?p.changedTouches[0]:p;if(!T)return;let g=n.getId(h),{clientX:S,clientY:E}=T;Ce(e)({type:nn[_],id:g,x:S,y:E,...y!==null&&{pointerType:y}})};return Object.keys(nn).filter(f=>Number.isNaN(Number(f))&&!f.endsWith("_Departed")&&a[f]!==!1).forEach(f=>{let p=Ms(f),h=u(f);if(window.PointerEvent)switch(nn[f]){case nn.MouseDown:case nn.MouseUp:p=p.replace("mouse","pointer");break;case nn.TouchStart:case nn.TouchEnd:return}l.push(rn(p,h,t))}),Ce(()=>{l.forEach(f=>f())})}function PT({scrollCb:e,doc:t,mirror:n,blockClass:r,blockSelector:o,unblockSelector:i,sampling:s}){let a=Ce(vl(Ce(l=>{let c=Rl(l);if(!c||Nn(c,r,o,i,!0))return;let u=n.getId(c);if(c===t&&t.defaultView){let f=TT(t.defaultView);e({id:u,x:f.left,y:f.top})}else e({id:u,x:c.scrollLeft,y:c.scrollTop})}),s.scroll||100));return rn("scroll",a,t)}function NM({viewportResizeCb:e},{win:t}){let n=-1,r=-1,o=Ce(vl(Ce(()=>{let i=IT(),s=wT();(n!==i||r!==s)&&(e({width:Number(s),height:Number(i)}),n=i,r=s)}),200));return rn("resize",o,t)}var AM=["INPUT","TEXTAREA","SELECT"],nT=new WeakMap;function MM({inputCb:e,doc:t,mirror:n,blockClass:r,blockSelector:o,unblockSelector:i,ignoreClass:s,ignoreSelector:a,maskInputOptions:l,maskInputFn:c,sampling:u,userTriggeredOnInput:f,maskTextClass:p,unmaskTextClass:h,maskTextSelector:y,unmaskTextSelector:_}){function T(I){let N=Rl(I),U=I.isTrusted,x=N&&jm(N.tagName);if(x==="OPTION"&&(N=N.parentElement),!N||!x||AM.indexOf(x)<0||Nn(N,r,o,i,!0))return;let H=N;if(H.classList.contains(s)||a&&H.matches(a))return;let j=gh(N),he=ju(H,x,j),X=!1,Ze=nd({maskInputOptions:l,tagName:x,type:j}),fe=Ps(N,p,y,h,_,Ze);(j==="radio"||j==="checkbox")&&(X=N.checked),he=Sl({isMasked:fe,element:N,value:he,maskInputFn:c}),g(N,f?{text:he,isChecked:X,userTriggered:U}:{text:he,isChecked:X});let de=N.name;j==="radio"&&de&&X&&t.querySelectorAll(`input[type="radio"][name="${de}"]`).forEach(D=>{if(D!==N){let ge=Sl({isMasked:fe,element:D,value:ju(D,x,j),maskInputFn:c});g(D,f?{text:ge,isChecked:!X,userTriggered:!1}:{text:ge,isChecked:!X})}})}function g(I,N){let U=nT.get(I);if(!U||U.text!==N.text||U.isChecked!==N.isChecked){nT.set(I,N);let x=n.getId(I);Ce(e)({...N,id:x})}}let E=(u.input==="last"?["change"]:["input","change"]).map(I=>rn(I,Ce(T),t)),R=t.defaultView;if(!R)return()=>{E.forEach(I=>I())};let M=R.Object.getOwnPropertyDescriptor(R.HTMLInputElement.prototype,"value"),A=[[R.HTMLInputElement.prototype,"value"],[R.HTMLInputElement.prototype,"checked"],[R.HTMLSelectElement.prototype,"value"],[R.HTMLTextAreaElement.prototype,"value"],[R.HTMLSelectElement.prototype,"selectedIndex"],[R.HTMLOptionElement.prototype,"selected"]];return M&&M.set&&E.push(...A.map(I=>ET(I[0],I[1],{set(){Ce(T)({target:this,isTrusted:!1})}},!1,R))),Ce(()=>{E.forEach(I=>I())})}function qu(e){let t=[];function n(r,o){if(Uu("CSSGroupingRule")&&r.parentRule instanceof CSSGroupingRule||Uu("CSSMediaRule")&&r.parentRule instanceof CSSMediaRule||Uu("CSSSupportsRule")&&r.parentRule instanceof CSSSupportsRule||Uu("CSSConditionRule")&&r.parentRule instanceof CSSConditionRule){let s=Array.from(r.parentRule.cssRules).indexOf(r);o.unshift(s)}else if(r.parentStyleSheet){let s=Array.from(r.parentStyleSheet.cssRules).indexOf(r);o.unshift(s)}return o}return n(e,t)}function bo(e,t,n){let r,o;return e?(e.ownerNode?r=t.getId(e.ownerNode):o=n.getId(e),{styleId:o,id:r}):{}}function PM({styleSheetRuleCb:e,mirror:t,stylesheetManager:n},{win:r}){if(!r.CSSStyleSheet||!r.CSSStyleSheet.prototype)return()=>{};let o=r.CSSStyleSheet.prototype.insertRule;r.CSSStyleSheet.prototype.insertRule=new Proxy(o,{apply:Ce((u,f,p)=>{let[h,y]=p,{id:_,styleId:T}=bo(f,t,n.styleMirror);return(_&&_!==-1||T&&T!==-1)&&e({id:_,styleId:T,adds:[{rule:h,index:y}]}),u.apply(f,p)})});let i=r.CSSStyleSheet.prototype.deleteRule;r.CSSStyleSheet.prototype.deleteRule=new Proxy(i,{apply:Ce((u,f,p)=>{let[h]=p,{id:y,styleId:_}=bo(f,t,n.styleMirror);return(y&&y!==-1||_&&_!==-1)&&e({id:y,styleId:_,removes:[{index:h}]}),u.apply(f,p)})});let s;r.CSSStyleSheet.prototype.replace&&(s=r.CSSStyleSheet.prototype.replace,r.CSSStyleSheet.prototype.replace=new Proxy(s,{apply:Ce((u,f,p)=>{let[h]=p,{id:y,styleId:_}=bo(f,t,n.styleMirror);return(y&&y!==-1||_&&_!==-1)&&e({id:y,styleId:_,replace:h}),u.apply(f,p)})}));let a;r.CSSStyleSheet.prototype.replaceSync&&(a=r.CSSStyleSheet.prototype.replaceSync,r.CSSStyleSheet.prototype.replaceSync=new Proxy(a,{apply:Ce((u,f,p)=>{let[h]=p,{id:y,styleId:_}=bo(f,t,n.styleMirror);return(y&&y!==-1||_&&_!==-1)&&e({id:y,styleId:_,replaceSync:h}),u.apply(f,p)})}));let l={};Fu("CSSGroupingRule")?l.CSSGroupingRule=r.CSSGroupingRule:(Fu("CSSMediaRule")&&(l.CSSMediaRule=r.CSSMediaRule),Fu("CSSConditionRule")&&(l.CSSConditionRule=r.CSSConditionRule),Fu("CSSSupportsRule")&&(l.CSSSupportsRule=r.CSSSupportsRule));let c={};return Object.entries(l).forEach(([u,f])=>{c[u]={insertRule:f.prototype.insertRule,deleteRule:f.prototype.deleteRule},f.prototype.insertRule=new Proxy(c[u].insertRule,{apply:Ce((p,h,y)=>{let[_,T]=y,{id:g,styleId:S}=bo(h.parentStyleSheet,t,n.styleMirror);return(g&&g!==-1||S&&S!==-1)&&e({id:g,styleId:S,adds:[{rule:_,index:[...qu(h),T||0]}]}),p.apply(h,y)})}),f.prototype.deleteRule=new Proxy(c[u].deleteRule,{apply:Ce((p,h,y)=>{let[_]=y,{id:T,styleId:g}=bo(h.parentStyleSheet,t,n.styleMirror);return(T&&T!==-1||g&&g!==-1)&&e({id:T,styleId:g,removes:[{index:[...qu(h),_]}]}),p.apply(h,y)})})}),Ce(()=>{r.CSSStyleSheet.prototype.insertRule=o,r.CSSStyleSheet.prototype.deleteRule=i,s&&(r.CSSStyleSheet.prototype.replace=s),a&&(r.CSSStyleSheet.prototype.replaceSync=a),Object.entries(l).forEach(([u,f])=>{f.prototype.insertRule=c[u].insertRule,f.prototype.deleteRule=c[u].deleteRule})})}function LT({mirror:e,stylesheetManager:t},n){let r=null;n.nodeName==="#document"?r=e.getId(n):r=e.getId(n.host);let o=n.nodeName==="#document"?n.defaultView?.Document:n.ownerDocument?.defaultView?.ShadowRoot,i=o?.prototype?Object.getOwnPropertyDescriptor(o?.prototype,"adoptedStyleSheets"):void 0;return r===null||r===-1||!o||!i?()=>{}:(Object.defineProperty(n,"adoptedStyleSheets",{configurable:i.configurable,enumerable:i.enumerable,get(){return i.get?.call(this)},set(s){let a=i.set?.call(this,s);if(r!==null&&r!==-1)try{t.adoptStyleSheets(s,r)}catch{}return a}}),Ce(()=>{Object.defineProperty(n,"adoptedStyleSheets",{configurable:i.configurable,enumerable:i.enumerable,get:i.get,set:i.set})}))}function LM({styleDeclarationCb:e,mirror:t,ignoreCSSAttributes:n,stylesheetManager:r},{win:o}){let i=o.CSSStyleDeclaration.prototype.setProperty;o.CSSStyleDeclaration.prototype.setProperty=new Proxy(i,{apply:Ce((a,l,c)=>{let[u,f,p]=c;if(n.has(u))return i.apply(l,[u,f,p]);let{id:h,styleId:y}=bo(l.parentRule?.parentStyleSheet,t,r.styleMirror);return(h&&h!==-1||y&&y!==-1)&&e({id:h,styleId:y,set:{property:u,value:f,priority:p},index:qu(l.parentRule)}),a.apply(l,c)})});let s=o.CSSStyleDeclaration.prototype.removeProperty;return o.CSSStyleDeclaration.prototype.removeProperty=new Proxy(s,{apply:Ce((a,l,c)=>{let[u]=c;if(n.has(u))return s.apply(l,[u]);let{id:f,styleId:p}=bo(l.parentRule?.parentStyleSheet,t,r.styleMirror);return(f&&f!==-1||p&&p!==-1)&&e({id:f,styleId:p,remove:{property:u},index:qu(l.parentRule)}),a.apply(l,c)})}),Ce(()=>{o.CSSStyleDeclaration.prototype.setProperty=i,o.CSSStyleDeclaration.prototype.removeProperty=s})}function OM({mediaInteractionCb:e,blockClass:t,blockSelector:n,unblockSelector:r,mirror:o,sampling:i,doc:s}){let a=Ce(c=>vl(Ce(u=>{let f=Rl(u);if(!f||Nn(f,t,n,r,!0))return;let{currentTime:p,volume:h,muted:y,playbackRate:_}=f;e({type:c,id:o.getId(f),currentTime:p,volume:h,muted:y,playbackRate:_})}),i.media||500)),l=[rn("play",a(xs.Play),s),rn("pause",a(xs.Pause),s),rn("seeked",a(xs.Seeked),s),rn("volumechange",a(xs.VolumeChange),s),rn("ratechange",a(xs.RateChange),s)];return Ce(()=>{l.forEach(c=>c())})}function DM({fontCb:e,doc:t}){let n=t.defaultView;if(!n)return()=>{};let r=[],o=new WeakMap,i=n.FontFace;n.FontFace=function(l,c,u){let f=new i(l,c,u);return o.set(f,{family:l,buffer:typeof c!="string",descriptors:u,fontSource:typeof c=="string"?c:JSON.stringify(Array.from(new Uint8Array(c)))}),f};let s=Sh(t.fonts,"add",function(a){return function(l){return od(Ce(()=>{let c=o.get(l);c&&(e(c),o.delete(l))}),0),a.apply(this,[l])}});return r.push(()=>{n.FontFace=i}),r.push(s),Ce(()=>{r.forEach(a=>a())})}function UM(e){let{doc:t,mirror:n,blockClass:r,blockSelector:o,unblockSelector:i,selectionCb:s}=e,a=!0,l=Ce(()=>{let c=t.getSelection();if(!c||a&&c?.isCollapsed)return;a=c.isCollapsed||!1;let u=[],f=c.rangeCount||0;for(let p=0;p<f;p++){let h=c.getRangeAt(p),{startContainer:y,startOffset:_,endContainer:T,endOffset:g}=h;Nn(y,r,o,i,!0)||Nn(T,r,o,i,!0)||u.push({start:n.getId(y),startOffset:_,end:n.getId(T),endOffset:g})}s({ranges:u})});return l(),rn("selectionchange",l)}function FM({doc:e,customElementCb:t}){let n=e.defaultView;return!n||!n.customElements?()=>{}:Sh(n.customElements,"define",function(o){return function(i,s,a){try{t({define:{name:i}})}catch{}return o.apply(this,[i,s,a])}})}function BM(e,t={}){let n=e.doc.defaultView;if(!n)return()=>{};let r;e.recordDOM&&(r=MT(e,e.doc));let o=bM(e),i=kM(e),s=PT(e),a=NM(e,{win:n}),l=MM(e),c=OM(e),u=()=>{},f=()=>{},p=()=>{},h=()=>{};e.recordDOM&&(u=PM(e,{win:n}),f=LT(e,e.doc),p=LM(e,{win:n}),e.collectFonts&&(h=DM(e)));let y=UM(e),_=FM(e),T=[];for(let g of e.plugins)T.push(g.observer(g.callback,n,g.options));return Ce(()=>{As.forEach(g=>g.reset()),r?.disconnect(),o(),i(),s(),a(),l(),c(),u(),f(),p(),h(),y(),_(),T.forEach(g=>g())})}function Uu(e){return typeof window[e]<"u"}function Fu(e){return!!(typeof window[e]<"u"&&window[e].prototype&&"insertRule"in window[e].prototype&&"deleteRule"in window[e].prototype)}var Tl=class{constructor(t){this.generateIdFn=t,this.iframeIdToRemoteIdMap=new WeakMap,this.iframeRemoteIdToIdMap=new WeakMap}getId(t,n,r,o){let i=r||this.getIdToRemoteIdMap(t),s=o||this.getRemoteIdToIdMap(t),a=i.get(n);return a||(a=this.generateIdFn(),i.set(n,a),s.set(a,n)),a}getIds(t,n){let r=this.getIdToRemoteIdMap(t),o=this.getRemoteIdToIdMap(t);return n.map(i=>this.getId(t,i,r,o))}getRemoteId(t,n,r){let o=r||this.getRemoteIdToIdMap(t);if(typeof n!="number")return n;let i=o.get(n);return i||-1}getRemoteIds(t,n){let r=this.getRemoteIdToIdMap(t);return n.map(o=>this.getRemoteId(t,o,r))}reset(t){if(!t){this.iframeIdToRemoteIdMap=new WeakMap,this.iframeRemoteIdToIdMap=new WeakMap;return}this.iframeIdToRemoteIdMap.delete(t),this.iframeRemoteIdToIdMap.delete(t)}getIdToRemoteIdMap(t){let n=this.iframeIdToRemoteIdMap.get(t);return n||(n=new Map,this.iframeIdToRemoteIdMap.set(t,n)),n}getRemoteIdToIdMap(t){let n=this.iframeRemoteIdToIdMap.get(t);return n||(n=new Map,this.iframeRemoteIdToIdMap.set(t,n)),n}},Qm=class{constructor(){this.crossOriginIframeMirror=new Tl(yh),this.crossOriginIframeRootIdMap=new WeakMap}addIframe(){}addLoadListener(){}attachIframe(){}},Zm=class{constructor(t){this.iframes=new WeakMap,this.crossOriginIframeMap=new WeakMap,this.crossOriginIframeMirror=new Tl(yh),this.crossOriginIframeRootIdMap=new WeakMap,this.mutationCb=t.mutationCb,this.wrappedEmit=t.wrappedEmit,this.stylesheetManager=t.stylesheetManager,this.recordCrossOriginIframes=t.recordCrossOriginIframes,this.crossOriginIframeStyleMirror=new Tl(this.stylesheetManager.styleMirror.generateId.bind(this.stylesheetManager.styleMirror)),this.mirror=t.mirror,this.recordCrossOriginIframes&&window.addEventListener("message",this.handleMessage.bind(this))}addIframe(t){this.iframes.set(t,!0);let n=El(t);n&&this.crossOriginIframeMap.set(n,t)}addLoadListener(t){this.loadListener=t}attachIframe(t,n){this.mutationCb({adds:[{parentId:this.mirror.getId(t),nextId:null,node:n}],removes:[],texts:[],attributes:[],isAttachIframe:!0}),this.recordCrossOriginIframes&&El(t)?.addEventListener("message",this.handleMessage.bind(this)),this.loadListener?.(t);let r=vh(t);r&&r.adoptedStyleSheets&&r.adoptedStyleSheets.length>0&&this.stylesheetManager.adoptStyleSheets(r.adoptedStyleSheets,this.mirror.getId(r))}handleMessage(t){let n=t;if(n.data.type!=="rrweb"||n.origin!==n.data.origin||!t.source)return;let o=this.crossOriginIframeMap.get(t.source);if(!o)return;let i=this.transformCrossOriginEvent(o,n.data.event);i&&this.wrappedEmit(i,n.data.isCheckout)}transformCrossOriginEvent(t,n){switch(n.type){case me.FullSnapshot:{this.crossOriginIframeMirror.reset(t),this.crossOriginIframeStyleMirror.reset(t),this.replaceIdOnNode(n.data.node,t);let r=n.data.node.id;return this.crossOriginIframeRootIdMap.set(t,r),this.patchRootIdOnNode(n.data.node,r),{timestamp:n.timestamp,type:me.IncrementalSnapshot,data:{source:se.Mutation,adds:[{parentId:this.mirror.getId(t),nextId:null,node:n.data.node}],removes:[],texts:[],attributes:[],isAttachIframe:!0}}}case me.Meta:case me.Load:case me.DomContentLoaded:return!1;case me.Plugin:return n;case me.Custom:return this.replaceIds(n.data.payload,t,["id","parentId","previousId","nextId"]),n;case me.IncrementalSnapshot:switch(n.data.source){case se.Mutation:return n.data.adds.forEach(r=>{this.replaceIds(r,t,["parentId","nextId","previousId"]),this.replaceIdOnNode(r.node,t);let o=this.crossOriginIframeRootIdMap.get(t);o&&this.patchRootIdOnNode(r.node,o)}),n.data.removes.forEach(r=>{this.replaceIds(r,t,["parentId","id"])}),n.data.attributes.forEach(r=>{this.replaceIds(r,t,["id"])}),n.data.texts.forEach(r=>{this.replaceIds(r,t,["id"])}),n;case se.Drag:case se.TouchMove:case se.MouseMove:return n.data.positions.forEach(r=>{this.replaceIds(r,t,["id"])}),n;case se.ViewportResize:return!1;case se.MediaInteraction:case se.MouseInteraction:case se.Scroll:case se.CanvasMutation:case se.Input:return this.replaceIds(n.data,t,["id"]),n;case se.StyleSheetRule:case se.StyleDeclaration:return this.replaceIds(n.data,t,["id"]),this.replaceStyleIds(n.data,t,["styleId"]),n;case se.Font:return n;case se.Selection:return n.data.ranges.forEach(r=>{this.replaceIds(r,t,["start","end"])}),n;case se.AdoptedStyleSheet:return this.replaceIds(n.data,t,["id"]),this.replaceStyleIds(n.data,t,["styleIds"]),n.data.styles?.forEach(r=>{this.replaceStyleIds(r,t,["styleId"])}),n}}return!1}replace(t,n,r,o){for(let i of o)!Array.isArray(n[i])&&typeof n[i]!="number"||(Array.isArray(n[i])?n[i]=t.getIds(r,n[i]):n[i]=t.getId(r,n[i]));return n}replaceIds(t,n,r){return this.replace(this.crossOriginIframeMirror,t,n,r)}replaceStyleIds(t,n,r){return this.replace(this.crossOriginIframeStyleMirror,t,n,r)}replaceIdOnNode(t,n){this.replaceIds(t,n,["id","rootId"]),"childNodes"in t&&t.childNodes.forEach(r=>{this.replaceIdOnNode(r,n)})}patchRootIdOnNode(t,n){t.type!==gt.Document&&!t.rootId&&(t.rootId=n),"childNodes"in t&&t.childNodes.forEach(r=>{this.patchRootIdOnNode(r,n)})}},eh=class{init(){}addShadowRoot(){}observeAttachShadow(){}reset(){}},th=class{constructor(t){this.shadowDoms=new WeakSet,this.restoreHandlers=[],this.mutationCb=t.mutationCb,this.scrollCb=t.scrollCb,this.bypassOptions=t.bypassOptions,this.mirror=t.mirror,this.init()}init(){this.reset(),this.patchAttachShadow(Element,document)}addShadowRoot(t,n){if(!gl(t)||this.shadowDoms.has(t))return;this.shadowDoms.add(t),this.bypassOptions.canvasManager.addShadowRoot(t);let r=MT({...this.bypassOptions,doc:n,mutationCb:this.mutationCb,mirror:this.mirror,shadowDomManager:this},t);this.restoreHandlers.push(()=>r.disconnect()),this.restoreHandlers.push(PT({...this.bypassOptions,scrollCb:this.scrollCb,doc:t,mirror:this.mirror})),od(()=>{t.adoptedStyleSheets&&t.adoptedStyleSheets.length>0&&this.bypassOptions.stylesheetManager.adoptStyleSheets(t.adoptedStyleSheets,this.mirror.getId(t.host)),this.restoreHandlers.push(LT({mirror:this.mirror,stylesheetManager:this.bypassOptions.stylesheetManager},t))},0)}observeAttachShadow(t){let n=vh(t),r=El(t);!n||!r||this.patchAttachShadow(r.Element,n)}patchAttachShadow(t,n){let r=this;this.restoreHandlers.push(Sh(t.prototype,"attachShadow",function(o){return function(i){let s=o.call(this,i);return this.shadowRoot&&NT(this)&&r.addShadowRoot(this.shadowRoot,n),s}}))}reset(){this.restoreHandlers.forEach(t=>{try{t()}catch{}}),this.restoreHandlers=[],this.shadowDoms=new WeakSet,this.bypassOptions.canvasManager.resetShadowRoots()}},nh=class{constructor(t){this.trackedLinkElements=new WeakSet,this.styleMirror=new qm,this.mutationCb=t.mutationCb,this.adoptedStyleSheetCb=t.adoptedStyleSheetCb}attachLinkElement(t,n){"_cssText"in n.attributes&&this.mutationCb({adds:[],removes:[],texts:[],attributes:[{id:n.id,attributes:n.attributes}]}),this.trackLinkElement(t)}trackLinkElement(t){this.trackedLinkElements.has(t)||(this.trackedLinkElements.add(t),this.trackStylesheetInLinkElement(t))}adoptStyleSheets(t,n){if(t.length===0)return;let r={id:n,styleIds:[]},o=[];for(let i of t){let s;this.styleMirror.has(i)?s=this.styleMirror.getId(i):(s=this.styleMirror.add(i),o.push({styleId:s,rules:Array.from(i.rules||CSSRule,(a,l)=>({rule:mT(a),index:l}))})),r.styleIds.push(s)}o.length>0&&(r.styles=o),this.adoptedStyleSheetCb(r)}reset(){this.styleMirror.reset(),this.trackedLinkElements=new WeakSet}trackStylesheetInLinkElement(t){}},rh=class{constructor(){this.nodeMap=new WeakMap,this.active=!1}inOtherBuffer(t,n){let r=this.nodeMap.get(t);return r&&Array.from(r).some(o=>o!==n)}add(t,n){this.active||(this.active=!0,TM(()=>{this.nodeMap=new WeakMap,this.active=!1})),this.nodeMap.set(t,(this.nodeMap.get(t)||new Set).add(n))}destroy(){}},lt,Yu;try{if(Array.from([1],e=>e*2)[0]!==2){let e=document.createElement("iframe");document.body.appendChild(e),Array.from=e.contentWindow?.Array.from||Array.from,document.body.removeChild(e)}}catch(e){console.debug("Unable to override Array.from",e)}var dr=V1();function fr(e={}){let{emit:t,checkoutEveryNms:n,checkoutEveryNth:r,blockClass:o="rr-block",blockSelector:i=null,unblockSelector:s=null,ignoreClass:a="rr-ignore",ignoreSelector:l=null,maskAllText:c=!1,maskTextClass:u="rr-mask",unmaskTextClass:f=null,maskTextSelector:p=null,unmaskTextSelector:h=null,inlineStylesheet:y=!0,maskAllInputs:_,maskInputOptions:T,slimDOMOptions:g,maskAttributeFn:S,maskInputFn:E,maskTextFn:R,maxCanvasSize:M=null,packFn:A,sampling:I={},dataURLOptions:N={},mousemoveWait:U,recordDOM:x=!0,recordCanvas:H=!1,recordCrossOriginIframes:j=!1,recordAfter:he=e.recordAfter==="DOMContentLoaded"?e.recordAfter:"load",userTriggeredOnInput:X=!1,collectFonts:Ze=!1,inlineImages:fe=!1,plugins:de,keepIframeSrcFn:D=()=>!1,ignoreCSSAttributes:ge=new Set([]),errorHandler:Q,onMutation:ae,getCanvasManager:Re}=e;wM(Q);let Te=j?window.parent===window:!0,St=!1;if(!Te)try{window.parent.document&&(St=!1)}catch{St=!0}if(Te&&!t)throw new Error("emit function is required");if(!Te&&!St)return()=>{};U!==void 0&&I.mousemove===void 0&&(I.mousemove=U),dr.reset();let ot=_===!0?{color:!0,date:!0,"datetime-local":!0,email:!0,month:!0,number:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0,textarea:!0,select:!0,radio:!0,checkbox:!0}:T!==void 0?T:{},bt=g===!0||g==="all"?{script:!0,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaVerification:!0,headMetaAuthorship:g==="all",headMetaDescKeywords:g==="all"}:g||{};_M();let it,In=0,Dt=J=>{for(let $e of de||[])$e.eventProcessor&&(J=$e.eventProcessor(J));return A&&!St&&(J=A(J)),J};lt=(J,$e)=>{let ye=J;if(ye.timestamp=Gu(),As[0]?.isFrozen()&&ye.type!==me.FullSnapshot&&!(ye.type===me.IncrementalSnapshot&&ye.data.source===se.Mutation)&&As.forEach(Je=>Je.unfreeze()),Te)t?.(Dt(ye),$e);else if(St){let Je={type:"rrweb",event:Dt(ye),origin:window.location.origin,isCheckout:$e};window.parent.postMessage(Je,"*")}if(ye.type===me.FullSnapshot)it=ye,In=0;else if(ye.type===me.IncrementalSnapshot){if(ye.data.source===se.Mutation&&ye.data.isAttachIframe)return;In++;let Je=r&&In>=r,Se=n&&it&&ye.timestamp-it.timestamp>n;(Je||Se)&&dt(!0)}};let wn=J=>{lt({type:me.IncrementalSnapshot,data:{source:se.Mutation,...J}})},nr=J=>lt({type:me.IncrementalSnapshot,data:{source:se.Scroll,...J}}),Vi=J=>lt({type:me.IncrementalSnapshot,data:{source:se.CanvasMutation,...J}}),Zo=J=>lt({type:me.IncrementalSnapshot,data:{source:se.AdoptedStyleSheet,...J}}),P=new nh({mutationCb:wn,adoptedStyleSheetCb:Zo}),V=typeof __RRWEB_EXCLUDE_IFRAME__=="boolean"&&__RRWEB_EXCLUDE_IFRAME__?new Qm:new Zm({mirror:dr,mutationCb:wn,stylesheetManager:P,recordCrossOriginIframes:j,wrappedEmit:lt});for(let J of de||[])J.getMirror&&J.getMirror({nodeMirror:dr,crossOriginIframeMirror:V.crossOriginIframeMirror,crossOriginIframeStyleMirror:V.crossOriginIframeStyleMirror});let ie=new rh,Y=$M(Re,{mirror:dr,win:window,mutationCb:J=>lt({type:me.IncrementalSnapshot,data:{source:se.CanvasMutation,...J}}),recordCanvas:H,blockClass:o,blockSelector:i,unblockSelector:s,maxCanvasSize:M,sampling:I.canvas,dataURLOptions:N,errorHandler:Q}),Ie=typeof __RRWEB_EXCLUDE_SHADOW_DOM__=="boolean"&&__RRWEB_EXCLUDE_SHADOW_DOM__?new eh:new th({mutationCb:wn,scrollCb:nr,bypassOptions:{onMutation:ae,blockClass:o,blockSelector:i,unblockSelector:s,maskAllText:c,maskTextClass:u,unmaskTextClass:f,maskTextSelector:p,unmaskTextSelector:h,inlineStylesheet:y,maskInputOptions:ot,dataURLOptions:N,maskAttributeFn:S,maskTextFn:R,maskInputFn:E,recordCanvas:H,inlineImages:fe,sampling:I,slimDOMOptions:bt,iframeManager:V,stylesheetManager:P,canvasManager:Y,keepIframeSrcFn:D,processedNodeManager:ie,ignoreCSSAttributes:ge},mirror:dr}),dt=(J=!1)=>{if(!x)return;lt({type:me.Meta,data:{href:window.location.href,width:wT(),height:IT()}},J),P.reset(),Ie.init(),As.forEach(ye=>ye.lock());let $e=yM(document,{mirror:dr,blockClass:o,blockSelector:i,unblockSelector:s,maskAllText:c,maskTextClass:u,unmaskTextClass:f,maskTextSelector:p,unmaskTextSelector:h,inlineStylesheet:y,maskAllInputs:ot,maskAttributeFn:S,maskInputFn:E,maskTextFn:R,slimDOM:bt,dataURLOptions:N,recordCanvas:H,inlineImages:fe,onSerialize:ye=>{xT(ye,dr)&&V.addIframe(ye),bT(ye,dr)&&P.trackLinkElement(ye),Vm(ye)&&Ie.addShadowRoot(ye.shadowRoot,document)},onIframeLoad:(ye,Je)=>{V.attachIframe(ye,Je);let Se=El(ye);Se&&Y.addWindow(Se),Ie.observeAttachShadow(ye)},onStylesheetLoad:(ye,Je)=>{P.attachLinkElement(ye,Je)},onBlockedImageLoad:(ye,Je,{width:Se,height:Ur})=>{wn({adds:[],removes:[],texts:[],attributes:[{id:Je.id,attributes:{style:{width:`${Se}px`,height:`${Ur}px`}}}]})},keepIframeSrcFn:D,ignoreCSSAttributes:ge});if(!$e)return console.warn("Failed to snapshot the document");lt({type:me.FullSnapshot,data:{node:$e,initialOffset:TT(window)}}),As.forEach(ye=>ye.unlock()),document.adoptedStyleSheets&&document.adoptedStyleSheets.length>0&&P.adoptStyleSheets(document.adoptedStyleSheets,dr.getId(document))};Yu=dt;try{let J=[],$e=Je=>Ce(BM)({onMutation:ae,mutationCb:wn,mousemoveCb:(Se,Ur)=>lt({type:me.IncrementalSnapshot,data:{source:Ur,positions:Se}}),mouseInteractionCb:Se=>lt({type:me.IncrementalSnapshot,data:{source:se.MouseInteraction,...Se}}),scrollCb:nr,viewportResizeCb:Se=>lt({type:me.IncrementalSnapshot,data:{source:se.ViewportResize,...Se}}),inputCb:Se=>lt({type:me.IncrementalSnapshot,data:{source:se.Input,...Se}}),mediaInteractionCb:Se=>lt({type:me.IncrementalSnapshot,data:{source:se.MediaInteraction,...Se}}),styleSheetRuleCb:Se=>lt({type:me.IncrementalSnapshot,data:{source:se.StyleSheetRule,...Se}}),styleDeclarationCb:Se=>lt({type:me.IncrementalSnapshot,data:{source:se.StyleDeclaration,...Se}}),canvasMutationCb:Vi,fontCb:Se=>lt({type:me.IncrementalSnapshot,data:{source:se.Font,...Se}}),selectionCb:Se=>{lt({type:me.IncrementalSnapshot,data:{source:se.Selection,...Se}})},customElementCb:Se=>{lt({type:me.IncrementalSnapshot,data:{source:se.CustomElement,...Se}})},blockClass:o,ignoreClass:a,ignoreSelector:l,maskAllText:c,maskTextClass:u,unmaskTextClass:f,maskTextSelector:p,unmaskTextSelector:h,maskInputOptions:ot,inlineStylesheet:y,sampling:I,recordDOM:x,recordCanvas:H,inlineImages:fe,userTriggeredOnInput:X,collectFonts:Ze,doc:Je,maskAttributeFn:S,maskInputFn:E,maskTextFn:R,keepIframeSrcFn:D,blockSelector:i,unblockSelector:s,slimDOMOptions:bt,dataURLOptions:N,mirror:dr,iframeManager:V,stylesheetManager:P,shadowDomManager:Ie,processedNodeManager:ie,canvasManager:Y,ignoreCSSAttributes:ge,plugins:de?.filter(Se=>Se.observer)?.map(Se=>({observer:Se.observer,options:Se.options,callback:Ur=>lt({type:me.Plugin,data:{plugin:Se.name,payload:Ur}})}))||[]},{});V.addLoadListener(Je=>{try{J.push($e(Je.contentDocument))}catch(Se){console.warn(Se)}});let ye=()=>{dt(),J.push($e(document))};return document.readyState==="interactive"||document.readyState==="complete"?ye():(J.push(rn("DOMContentLoaded",()=>{lt({type:me.DomContentLoaded,data:{}}),he==="DOMContentLoaded"&&ye()})),J.push(rn("load",()=>{lt({type:me.Load,data:{}}),he==="load"&&ye()},window))),()=>{J.forEach(Je=>Je()),ie.destroy(),Yu=void 0,CM()}}catch(J){console.warn(J)}}function HM(e){if(!Yu)throw new Error("please take full snapshot after start recording");Yu(e)}fr.mirror=dr;fr.takeFullSnapshot=HM;function $M(e,t){try{return e?e(t):new Vu}catch{return console.warn("Unable to initialize CanvasManager"),new Vu}}var rT;(function(e){e[e.NotStarted=0]="NotStarted",e[e.Running=1]="Running",e[e.Stopped=2]="Stopped"})(rT||(rT={}));var zM=3,jM=5;function Eh(e){return e>9999999999?e:e*1e3}function Bm(e){return e>9999999999?e/1e3:e}function xl(e,t){t.category!=="sentry.transaction"&&(["ui.click","ui.input"].includes(t.category)?e.triggerUserActivity():e.checkAndHandleExpiredSession(),e.addUpdate(()=>(e.throttledAddEvent({type:me.Custom,timestamp:(t.timestamp||0)*1e3,data:{tag:"breadcrumb",payload:$t(t,10,1e3)}}),t.category==="console")))}var WM="button,a";function OT(e){return e.closest(WM)||e}function DT(e){let t=UT(e);return!t||!(t instanceof Element)?t:OT(t)}function UT(e){return GM(e)?e.target:e}function GM(e){return typeof e=="object"&&!!e&&"target"in e}var ko;function VM(e){return ko||(ko=[],qM()),ko.push(e),()=>{let t=ko?ko.indexOf(e):-1;t>-1&&ko.splice(t,1)}}function qM(){st(je,"open",function(e){return function(...t){if(ko)try{ko.forEach(n=>n())}catch{}return e.apply(je,t)}})}var YM=new Set([se.Mutation,se.StyleSheetRule,se.StyleDeclaration,se.AdoptedStyleSheet,se.CanvasMutation,se.Selection,se.MediaInteraction]);function KM(e,t,n){e.handleClick(t,n)}var oh=class{constructor(t,n,r=xl){this._lastMutation=0,this._lastScroll=0,this._clicks=[],this._timeout=n.timeout/1e3,this._threshold=n.threshold/1e3,this._scrollTimeout=n.scrollTimeout/1e3,this._replay=t,this._ignoreSelector=n.ignoreSelector,this._addBreadcrumbEvent=r}addListeners(){let t=VM(()=>{this._lastMutation=oT()});this._teardown=()=>{t(),this._clicks=[],this._lastMutation=0,this._lastScroll=0}}removeListeners(){this._teardown&&this._teardown(),this._checkClickTimeout&&clearTimeout(this._checkClickTimeout)}handleClick(t,n){if(XM(n,this._ignoreSelector)||!QM(t))return;let r={timestamp:Bm(t.timestamp),clickBreadcrumb:t,clickCount:0,node:n};this._clicks.some(o=>o.node===r.node&&Math.abs(o.timestamp-r.timestamp)<1)||(this._clicks.push(r),this._clicks.length===1&&this._scheduleCheckClicks())}registerMutation(t=Date.now()){this._lastMutation=Bm(t)}registerScroll(t=Date.now()){this._lastScroll=Bm(t)}registerClick(t){let n=OT(t);this._handleMultiClick(n)}_handleMultiClick(t){this._getClicks(t).forEach(n=>{n.clickCount++})}_getClicks(t){return this._clicks.filter(n=>n.node===t)}_checkClicks(){let t=[],n=oT();this._clicks.forEach(r=>{!r.mutationAfter&&this._lastMutation&&(r.mutationAfter=r.timestamp<=this._lastMutation?this._lastMutation-r.timestamp:void 0),!r.scrollAfter&&this._lastScroll&&(r.scrollAfter=r.timestamp<=this._lastScroll?this._lastScroll-r.timestamp:void 0),r.timestamp+this._timeout<=n&&t.push(r)});for(let r of t){let o=this._clicks.indexOf(r);o>-1&&(this._generateBreadcrumbs(r),this._clicks.splice(o,1))}this._clicks.length&&this._scheduleCheckClicks()}_generateBreadcrumbs(t){let n=this._replay,r=t.scrollAfter&&t.scrollAfter<=this._scrollTimeout,o=t.mutationAfter&&t.mutationAfter<=this._threshold,i=!r&&!o,{clickCount:s,clickBreadcrumb:a}=t;if(i){let l=Math.min(t.mutationAfter||this._timeout,this._timeout)*1e3,c=l<this._timeout*1e3?"mutation":"timeout",u={type:"default",message:a.message,timestamp:a.timestamp,category:"ui.slowClickDetected",data:{...a.data,url:je.location.href,route:n.getCurrentRoute(),timeAfterClickMs:l,endReason:c,clickCount:s||1}};this._addBreadcrumbEvent(n,u);return}if(s>1){let l={type:"default",message:a.message,timestamp:a.timestamp,category:"ui.multiClick",data:{...a.data,url:je.location.href,route:n.getCurrentRoute(),clickCount:s,metric:!0}};this._addBreadcrumbEvent(n,l)}}_scheduleCheckClicks(){this._checkClickTimeout&&clearTimeout(this._checkClickTimeout),this._checkClickTimeout=Ii(()=>this._checkClicks(),1e3)}},JM=["A","BUTTON","INPUT"];function XM(e,t){return!!(!JM.includes(e.tagName)||e.tagName==="INPUT"&&!["submit","button"].includes(e.getAttribute("type")||"")||e.tagName==="A"&&(e.hasAttribute("download")||e.hasAttribute("target")&&e.getAttribute("target")!=="_self")||t&&e.matches(t))}function QM(e){return!!(e.data&&typeof e.data.nodeId=="number"&&e.timestamp)}function oT(){return Date.now()/1e3}function ZM(e,t){try{if(!eP(t))return;let{source:n}=t.data;if(YM.has(n)&&e.registerMutation(t.timestamp),n===se.Scroll&&e.registerScroll(t.timestamp),tP(t)){let{type:r,id:o}=t.data,i=fr.mirror.getNode(o);i instanceof HTMLElement&&r===nn.Click&&e.registerClick(i)}}catch{}}function eP(e){return e.type===zM}function tP(e){return e.data.source===se.MouseInteraction}function br(e){return{timestamp:Date.now()/1e3,type:"default",...e}}var id=(e=>(e[e.Document=0]="Document",e[e.DocumentType=1]="DocumentType",e[e.Element=2]="Element",e[e.Text=3]="Text",e[e.CDATA=4]="CDATA",e[e.Comment=5]="Comment",e))(id||{}),nP=new Set(["id","class","aria-label","role","name","alt","title","data-test-id","data-testid","disabled","aria-disabled","data-sentry-component"]);function rP(e){let t={};!e["data-sentry-component"]&&e["data-sentry-element"]&&(e["data-sentry-component"]=e["data-sentry-element"]);for(let n in e)if(nP.has(n)){let r=n;(n==="data-testid"||n==="data-test-id")&&(r="testId"),t[r]=e[n]}return t}var oP=e=>t=>{if(!e.isEnabled())return;let n=iP(t);if(!n)return;let r=t.name==="click",o=r?t.event:void 0;r&&e.clickDetector&&o?.target&&!o.altKey&&!o.metaKey&&!o.ctrlKey&&!o.shiftKey&&KM(e.clickDetector,n,DT(t.event)),xl(e,n)};function FT(e,t){let n=fr.mirror.getId(e),r=n&&fr.mirror.getNode(n),o=r&&fr.mirror.getMeta(r),i=o&&aP(o)?o:null;return{message:t,data:i?{nodeId:n,node:{id:n,tagName:i.tagName,textContent:Array.from(i.childNodes).map(s=>s.type===id.Text&&s.textContent).filter(Boolean).map(s=>s.trim()).join(""),attributes:rP(i.attributes)}}:{}}}function iP(e){let{target:t,message:n}=sP(e);return br({category:`ui.${e.name}`,...FT(t,n)})}function sP(e){let t=e.name==="click",n,r=null;try{r=t?DT(e.event):UT(e.event),n=Ue(r,{maxStringLength:200})||"<unknown>"}catch{n="<unknown>"}return{target:r,message:n}}function aP(e){return e.type===id.Element}function lP(e,t){if(!e.isEnabled())return;e.updateUserActivity();let n=cP(t);n&&xl(e,n)}function cP(e){let{metaKey:t,shiftKey:n,ctrlKey:r,altKey:o,key:i,target:s}=e;if(!s||uP(s)||!i)return null;let a=t||r||o,l=i.length===1;if(!a&&l)return null;let c=Ue(s,{maxStringLength:200})||"<unknown>",u=FT(s,c);return br({category:"ui.keyDown",message:c,data:{...u.data,metaKey:t,shiftKey:n,ctrlKey:r,altKey:o,key:i}})}function uP(e){return e.tagName==="INPUT"||e.tagName==="TEXTAREA"||e.isContentEditable}var dP={resource:gP,paint:mP,navigation:hP};function Hm(e,t){return({metric:n})=>{t.replayPerformanceEntries.push(e(n))}}function fP(e){return e.map(pP).filter(Boolean)}function pP(e){let t=dP[e.entryType];return t?t(e):null}function Ls(e){return((He()||je.performance.timeOrigin)+e)/1e3}function mP(e){let{duration:t,entryType:n,name:r,startTime:o}=e,i=Ls(o);return{type:n,name:r,start:i,end:i+t,data:void 0}}function hP(e){let{entryType:t,name:n,decodedBodySize:r,duration:o,domComplete:i,encodedBodySize:s,domContentLoadedEventStart:a,domContentLoadedEventEnd:l,domInteractive:c,loadEventStart:u,loadEventEnd:f,redirectCount:p,startTime:h,transferSize:y,type:_}=e;return o===0?null:{type:`${t}.${_}`,start:Ls(h),end:Ls(i),name:n,data:{size:y,decodedBodySize:r,encodedBodySize:s,duration:o,domInteractive:c,domContentLoadedEventStart:a,domContentLoadedEventEnd:l,loadEventStart:u,loadEventEnd:f,domComplete:i,redirectCount:p}}}function gP(e){let{entryType:t,initiatorType:n,name:r,responseEnd:o,startTime:i,decodedBodySize:s,encodedBodySize:a,responseStatus:l,transferSize:c}=e;return["fetch","xmlhttprequest"].includes(n)?null:{type:`${t}.${n}`,start:Ls(i),end:Ls(o),name:r,data:{size:c,statusCode:l,decodedBodySize:s,encodedBodySize:a}}}function yP(e){let t=e.entries[e.entries.length-1],n=t?.element?[t.element]:void 0;return Th(e,"largest-contentful-paint",n)}function SP(e){return e.sources!==void 0}function _P(e){let t=[],n=[];for(let r of e.entries)if(SP(r)){let o=[];for(let i of r.sources)if(i.node){n.push(i.node);let s=fr.mirror.getId(i.node);s&&o.push(s)}t.push({value:r.value,nodeIds:o.length?o:void 0})}return Th(e,"cumulative-layout-shift",n,t)}function vP(e){let t=e.entries[e.entries.length-1],n=t?.target?[t.target]:void 0;return Th(e,"interaction-to-next-paint",n)}function Th(e,t,n,r){let o=e.value,i=e.rating,s=Ls(o);return{type:"web-vital",name:t,start:s,end:s,data:{value:o,size:o,rating:i,nodeIds:n?n.map(a=>fr.mirror.getId(a)):void 0,attributions:r}}}function EP(e){function t(o){e.performanceEntries.includes(o)||e.performanceEntries.push(o)}function n({entries:o}){o.forEach(t)}let r=[];return["navigation","paint","resource"].forEach(o=>{r.push(cr(o,n))}),r.push(Kr(Hm(yP,e)),Yr(Hm(_P,e)),_i(Hm(vP,e))),()=>{r.forEach(o=>o())}}var re=typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__,TP='var t=Uint8Array,n=Uint16Array,r=Int32Array,e=new t([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),i=new t([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]),s=new t([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),a=function(t,e){for(var i=new n(31),s=0;s<31;++s)i[s]=e+=1<<t[s-1];var a=new r(i[30]);for(s=1;s<30;++s)for(var o=i[s];o<i[s+1];++o)a[o]=o-i[s]<<5|s;return{b:i,r:a}},o=a(e,2),h=o.b,f=o.r;h[28]=258,f[258]=28;for(var l=a(i,0).r,u=new n(32768),c=0;c<32768;++c){var v=(43690&c)>>1|(21845&c)<<1;v=(61680&(v=(52428&v)>>2|(13107&v)<<2))>>4|(3855&v)<<4,u[c]=((65280&v)>>8|(255&v)<<8)>>1}var d=function(t,r,e){for(var i=t.length,s=0,a=new n(r);s<i;++s)t[s]&&++a[t[s]-1];var o,h=new n(r);for(s=1;s<r;++s)h[s]=h[s-1]+a[s-1]<<1;if(e){o=new n(1<<r);var f=15-r;for(s=0;s<i;++s)if(t[s])for(var l=s<<4|t[s],c=r-t[s],v=h[t[s]-1]++<<c,d=v|(1<<c)-1;v<=d;++v)o[u[v]>>f]=l}else for(o=new n(i),s=0;s<i;++s)t[s]&&(o[s]=u[h[t[s]-1]++]>>15-t[s]);return o},p=new t(288);for(c=0;c<144;++c)p[c]=8;for(c=144;c<256;++c)p[c]=9;for(c=256;c<280;++c)p[c]=7;for(c=280;c<288;++c)p[c]=8;var g=new t(32);for(c=0;c<32;++c)g[c]=5;var w=d(p,9,0),y=d(g,5,0),m=function(t){return(t+7)/8|0},b=function(n,r,e){return(null==e||e>n.length)&&(e=n.length),new t(n.subarray(r,e))},M=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],E=function(t,n,r){var e=new Error(n||M[t]);if(e.code=t,Error.captureStackTrace&&Error.captureStackTrace(e,E),!r)throw e;return e},z=function(t,n,r){r<<=7&n;var e=n/8|0;t[e]|=r,t[e+1]|=r>>8},_=function(t,n,r){r<<=7&n;var e=n/8|0;t[e]|=r,t[e+1]|=r>>8,t[e+2]|=r>>16},x=function(r,e){for(var i=[],s=0;s<r.length;++s)r[s]&&i.push({s:s,f:r[s]});var a=i.length,o=i.slice();if(!a)return{t:F,l:0};if(1==a){var h=new t(i[0].s+1);return h[i[0].s]=1,{t:h,l:1}}i.sort(function(t,n){return t.f-n.f}),i.push({s:-1,f:25001});var f=i[0],l=i[1],u=0,c=1,v=2;for(i[0]={s:-1,f:f.f+l.f,l:f,r:l};c!=a-1;)f=i[i[u].f<i[v].f?u++:v++],l=i[u!=c&&i[u].f<i[v].f?u++:v++],i[c++]={s:-1,f:f.f+l.f,l:f,r:l};var d=o[0].s;for(s=1;s<a;++s)o[s].s>d&&(d=o[s].s);var p=new n(d+1),g=A(i[c-1],p,0);if(g>e){s=0;var w=0,y=g-e,m=1<<y;for(o.sort(function(t,n){return p[n.s]-p[t.s]||t.f-n.f});s<a;++s){var b=o[s].s;if(!(p[b]>e))break;w+=m-(1<<g-p[b]),p[b]=e}for(w>>=y;w>0;){var M=o[s].s;p[M]<e?w-=1<<e-p[M]++-1:++s}for(;s>=0&&w;--s){var E=o[s].s;p[E]==e&&(--p[E],++w)}g=e}return{t:new t(p),l:g}},A=function(t,n,r){return-1==t.s?Math.max(A(t.l,n,r+1),A(t.r,n,r+1)):n[t.s]=r},D=function(t){for(var r=t.length;r&&!t[--r];);for(var e=new n(++r),i=0,s=t[0],a=1,o=function(t){e[i++]=t},h=1;h<=r;++h)if(t[h]==s&&h!=r)++a;else{if(!s&&a>2){for(;a>138;a-=138)o(32754);a>2&&(o(a>10?a-11<<5|28690:a-3<<5|12305),a=0)}else if(a>3){for(o(s),--a;a>6;a-=6)o(8304);a>2&&(o(a-3<<5|8208),a=0)}for(;a--;)o(s);a=1,s=t[h]}return{c:e.subarray(0,i),n:r}},T=function(t,n){for(var r=0,e=0;e<n.length;++e)r+=t[e]*n[e];return r},k=function(t,n,r){var e=r.length,i=m(n+2);t[i]=255&e,t[i+1]=e>>8,t[i+2]=255^t[i],t[i+3]=255^t[i+1];for(var s=0;s<e;++s)t[i+s+4]=r[s];return 8*(i+4+e)},U=function(t,r,a,o,h,f,l,u,c,v,m){z(r,m++,a),++h[256];for(var b=x(h,15),M=b.t,E=b.l,A=x(f,15),U=A.t,C=A.l,F=D(M),I=F.c,S=F.n,L=D(U),O=L.c,j=L.n,q=new n(19),B=0;B<I.length;++B)++q[31&I[B]];for(B=0;B<O.length;++B)++q[31&O[B]];for(var G=x(q,7),H=G.t,J=G.l,K=19;K>4&&!H[s[K-1]];--K);var N,P,Q,R,V=v+5<<3,W=T(h,p)+T(f,g)+l,X=T(h,M)+T(f,U)+l+14+3*K+T(q,H)+2*q[16]+3*q[17]+7*q[18];if(c>=0&&V<=W&&V<=X)return k(r,m,t.subarray(c,c+v));if(z(r,m,1+(X<W)),m+=2,X<W){N=d(M,E,0),P=M,Q=d(U,C,0),R=U;var Y=d(H,J,0);z(r,m,S-257),z(r,m+5,j-1),z(r,m+10,K-4),m+=14;for(B=0;B<K;++B)z(r,m+3*B,H[s[B]]);m+=3*K;for(var Z=[I,O],$=0;$<2;++$){var tt=Z[$];for(B=0;B<tt.length;++B){var nt=31&tt[B];z(r,m,Y[nt]),m+=H[nt],nt>15&&(z(r,m,tt[B]>>5&127),m+=tt[B]>>12)}}}else N=w,P=p,Q=y,R=g;for(B=0;B<u;++B){var rt=o[B];if(rt>255){_(r,m,N[(nt=rt>>18&31)+257]),m+=P[nt+257],nt>7&&(z(r,m,rt>>23&31),m+=e[nt]);var et=31&rt;_(r,m,Q[et]),m+=R[et],et>3&&(_(r,m,rt>>5&8191),m+=i[et])}else _(r,m,N[rt]),m+=P[rt]}return _(r,m,N[256]),m+P[256]},C=new r([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),F=new t(0),I=function(){for(var t=new Int32Array(256),n=0;n<256;++n){for(var r=n,e=9;--e;)r=(1&r&&-306674912)^r>>>1;t[n]=r}return t}(),S=function(){var t=1,n=0;return{p:function(r){for(var e=t,i=n,s=0|r.length,a=0;a!=s;){for(var o=Math.min(a+2655,s);a<o;++a)i+=e+=r[a];e=(65535&e)+15*(e>>16),i=(65535&i)+15*(i>>16)}t=e,n=i},d:function(){return(255&(t%=65521))<<24|(65280&t)<<8|(255&(n%=65521))<<8|n>>8}}},L=function(s,a,o,h,u){if(!u&&(u={l:1},a.dictionary)){var c=a.dictionary.subarray(-32768),v=new t(c.length+s.length);v.set(c),v.set(s,c.length),s=v,u.w=c.length}return function(s,a,o,h,u,c){var v=c.z||s.length,d=new t(h+v+5*(1+Math.ceil(v/7e3))+u),p=d.subarray(h,d.length-u),g=c.l,w=7&(c.r||0);if(a){w&&(p[0]=c.r>>3);for(var y=C[a-1],M=y>>13,E=8191&y,z=(1<<o)-1,_=c.p||new n(32768),x=c.h||new n(z+1),A=Math.ceil(o/3),D=2*A,T=function(t){return(s[t]^s[t+1]<<A^s[t+2]<<D)&z},F=new r(25e3),I=new n(288),S=new n(32),L=0,O=0,j=c.i||0,q=0,B=c.w||0,G=0;j+2<v;++j){var H=T(j),J=32767&j,K=x[H];if(_[J]=K,x[H]=J,B<=j){var N=v-j;if((L>7e3||q>24576)&&(N>423||!g)){w=U(s,p,0,F,I,S,O,q,G,j-G,w),q=L=O=0,G=j;for(var P=0;P<286;++P)I[P]=0;for(P=0;P<30;++P)S[P]=0}var Q=2,R=0,V=E,W=J-K&32767;if(N>2&&H==T(j-W))for(var X=Math.min(M,N)-1,Y=Math.min(32767,j),Z=Math.min(258,N);W<=Y&&--V&&J!=K;){if(s[j+Q]==s[j+Q-W]){for(var $=0;$<Z&&s[j+$]==s[j+$-W];++$);if($>Q){if(Q=$,R=W,$>X)break;var tt=Math.min(W,$-2),nt=0;for(P=0;P<tt;++P){var rt=j-W+P&32767,et=rt-_[rt]&32767;et>nt&&(nt=et,K=rt)}}}W+=(J=K)-(K=_[J])&32767}if(R){F[q++]=268435456|f[Q]<<18|l[R];var it=31&f[Q],st=31&l[R];O+=e[it]+i[st],++I[257+it],++S[st],B=j+Q,++L}else F[q++]=s[j],++I[s[j]]}}for(j=Math.max(j,B);j<v;++j)F[q++]=s[j],++I[s[j]];w=U(s,p,g,F,I,S,O,q,G,j-G,w),g||(c.r=7&w|p[w/8|0]<<3,w-=7,c.h=x,c.p=_,c.i=j,c.w=B)}else{for(j=c.w||0;j<v+g;j+=65535){var at=j+65535;at>=v&&(p[w/8|0]=g,at=v),w=k(p,w+1,s.subarray(j,at))}c.i=v}return b(d,0,h+m(w)+u)}(s,null==a.level?6:a.level,null==a.mem?u.l?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(s.length)))):20:12+a.mem,o,h,u)},O=function(t,n,r){for(;r;++n)t[n]=r,r>>>=8},j=function(){function n(n,r){if("function"==typeof n&&(r=n,n={}),this.ondata=r,this.o=n||{},this.s={l:0,i:32768,w:32768,z:32768},this.b=new t(98304),this.o.dictionary){var e=this.o.dictionary.subarray(-32768);this.b.set(e,32768-e.length),this.s.i=32768-e.length}}return n.prototype.p=function(t,n){this.ondata(L(t,this.o,0,0,this.s),n)},n.prototype.push=function(n,r){this.ondata||E(5),this.s.l&&E(4);var e=n.length+this.s.z;if(e>this.b.length){if(e>2*this.b.length-32768){var i=new t(-32768&e);i.set(this.b.subarray(0,this.s.z)),this.b=i}var s=this.b.length-this.s.z;this.b.set(n.subarray(0,s),this.s.z),this.s.z=this.b.length,this.p(this.b,!1),this.b.set(this.b.subarray(-32768)),this.b.set(n.subarray(s),32768),this.s.z=n.length-s+32768,this.s.i=32766,this.s.w=32768}else this.b.set(n,this.s.z),this.s.z+=n.length;this.s.l=1&r,(this.s.z>this.s.w+8191||r)&&(this.p(this.b,r||!1),this.s.w=this.s.i,this.s.i-=2)},n.prototype.flush=function(){this.ondata||E(5),this.s.l&&E(4),this.p(this.b,!1),this.s.w=this.s.i,this.s.i-=2},n}();function q(t,n){n||(n={});var r=function(){var t=-1;return{p:function(n){for(var r=t,e=0;e<n.length;++e)r=I[255&r^n[e]]^r>>>8;t=r},d:function(){return~t}}}(),e=t.length;r.p(t);var i,s=L(t,n,10+((i=n).filename?i.filename.length+1:0),8),a=s.length;return function(t,n){var r=n.filename;if(t[0]=31,t[1]=139,t[2]=8,t[8]=n.level<2?4:9==n.level?2:0,t[9]=3,0!=n.mtime&&O(t,4,Math.floor(new Date(n.mtime||Date.now())/1e3)),r){t[3]=8;for(var e=0;e<=r.length;++e)t[e+10]=r.charCodeAt(e)}}(s,n),O(s,a-8,r.d()),O(s,a-4,e),s}var B=function(){function t(t,n){this.c=S(),this.v=1,j.call(this,t,n)}return t.prototype.push=function(t,n){this.c.p(t),j.prototype.push.call(this,t,n)},t.prototype.p=function(t,n){var r=L(t,this.o,this.v&&(this.o.dictionary?6:2),n&&4,this.s);this.v&&(function(t,n){var r=n.level,e=0==r?0:r<6?1:9==r?3:2;if(t[0]=120,t[1]=e<<6|(n.dictionary&&32),t[1]|=31-(t[0]<<8|t[1])%31,n.dictionary){var i=S();i.p(n.dictionary),O(t,2,i.d())}}(r,this.o),this.v=0),n&&O(r,r.length-4,this.c.d()),this.ondata(r,n)},t.prototype.flush=function(){j.prototype.flush.call(this)},t}(),G="undefined"!=typeof TextEncoder&&new TextEncoder,H="undefined"!=typeof TextDecoder&&new TextDecoder;try{H.decode(F,{stream:!0})}catch(t){}var J=function(){function t(t){this.ondata=t}return t.prototype.push=function(t,n){this.ondata||E(5),this.d&&E(4),this.ondata(K(t),this.d=n||!1)},t}();function K(n,r){if(G)return G.encode(n);for(var e=n.length,i=new t(n.length+(n.length>>1)),s=0,a=function(t){i[s++]=t},o=0;o<e;++o){if(s+5>i.length){var h=new t(s+8+(e-o<<1));h.set(i),i=h}var f=n.charCodeAt(o);f<128||r?a(f):f<2048?(a(192|f>>6),a(128|63&f)):f>55295&&f<57344?(a(240|(f=65536+(1047552&f)|1023&n.charCodeAt(++o))>>18),a(128|f>>12&63),a(128|f>>6&63),a(128|63&f)):(a(224|f>>12),a(128|f>>6&63),a(128|63&f))}return b(i,0,s)}const N=new class{constructor(){this._init()}clear(){this._init()}addEvent(t){if(!t)throw new Error("Adding invalid event");const n=this._hasEvents?",":"";this.stream.push(n+t),this._hasEvents=!0}finish(){this.stream.push("]",!0);const t=function(t){let n=0;for(const r of t)n+=r.length;const r=new Uint8Array(n);for(let n=0,e=0,i=t.length;n<i;n++){const i=t[n];r.set(i,e),e+=i.length}return r}(this._deflatedData);return this._init(),t}_init(){this._hasEvents=!1,this._deflatedData=[],this.deflate=new B,this.deflate.ondata=(t,n)=>{this._deflatedData.push(t)},this.stream=new J((t,n)=>{this.deflate.push(t,n)}),this.stream.push("[")}},P={clear:()=>{N.clear()},addEvent:t=>N.addEvent(t),finish:()=>N.finish(),compress:t=>function(t){return q(K(t))}(t)};addEventListener("message",function(t){const n=t.data.method,r=t.data.id,e=t.data.arg;if(n in P&&"function"==typeof P[n])try{const t=P[n](e);postMessage({id:r,method:n,success:!0,response:t})}catch(t){postMessage({id:r,method:n,success:!1,response:t.message}),console.error(t)}}),postMessage({id:void 0,method:"init",success:!0,response:void 0});';function IP(){let e=new Blob([TP]);return URL.createObjectURL(e)}var iT=["log","warn","error"],Hu="[Replay] ";function $m(e,t="info"){kn({category:"console",data:{logger:"replay"},level:t,message:`${Hu}${e}`},{level:t})}function wP(){let e=!1,t=!1,n={exception:()=>{},infoTick:()=>{},setConfig:r=>{e=!!r.captureExceptions,t=!!r.traceInternals}};return re?(iT.forEach(r=>{n[r]=(...o)=>{C[r](Hu,...o),t&&$m(o.join(""),gs(r))}}),n.exception=(r,...o)=>{o.length&&n.error&&n.error(...o),C.error(Hu,r),e?Gr(r,{mechanism:{handled:!0,type:"auto.function.replay.debug"}}):t&&$m(r,"error")},n.infoTick=(...r)=>{C.log(Hu,...r),t&&setTimeout(()=>$m(r[0]),0)}):iT.forEach(r=>{n[r]=()=>{}}),n}var oe=wP(),Il=class extends Error{constructor(){super(`Event buffer exceeded maximum size of ${hh}.`)}},Ku=class{constructor(){this.events=[],this._totalSize=0,this.hasCheckout=!1,this.waitForCheckout=!1}get hasEvents(){return this.events.length>0}get type(){return"sync"}destroy(){this.events=[]}async addEvent(t){let n=JSON.stringify(t).length;if(this._totalSize+=n,this._totalSize>hh)throw new Il;this.events.push(t)}finish(){return new Promise(t=>{let n=this.events;this.clear(),t(JSON.stringify(n))})}clear(){this.events=[],this._totalSize=0,this.hasCheckout=!1}getEarliestTimestamp(){let t=null;for(let{timestamp:n}of this.events)(t===null||n<t)&&(t=n);return t===null?t:Eh(t)}},ih=class{constructor(t){this._onMessage=({data:n})=>{let r=n;if(typeof r.id!="number")return;let o=this._pending.get(r.id);if(!(!o||o.method!==r.method)){if(this._pending.delete(r.id),!r.success){re&&oe.error("Error in compression worker: ",r.response),o.reject(new Error("Error in compression worker"));return}o.resolve(r.response)}},this._worker=t,this._id=0,this._pending=new Map,this._worker.addEventListener("message",this._onMessage)}ensureReady(){return this._ensureReadyPromise?this._ensureReadyPromise:(this._ensureReadyPromise=new Promise((t,n)=>{this._worker.addEventListener("message",({data:r})=>{r.success?t():(re&&oe.warn("Received worker message with unsuccessful status",r),n(new Error("Received worker message with unsuccessful status")))},{once:!0}),this._worker.addEventListener("error",r=>{re&&oe.warn("Failed to load Replay compression worker",r),n(new Error(`Failed to load Replay compression worker: ${r instanceof ErrorEvent&&r.message?r.message:"Unknown error. This can happen due to CSP policy restrictions, network issues, or the worker script failing to load."}`))},{once:!0})}),this._ensureReadyPromise)}destroy(){re&&oe.log("Destroying compression worker"),this._worker.removeEventListener("message",this._onMessage),this._pending.forEach(t=>t.reject(new Error("Worker destroyed"))),this._pending.clear(),this._worker.terminate()}postMessage(t,n){let r=this._getAndIncrementId();return new Promise((o,i)=>{this._pending.set(r,{method:t,resolve:o,reject:i});try{this._worker.postMessage({id:r,method:t,arg:n})}catch(s){this._pending.delete(r),i(s)}})}_getAndIncrementId(){return this._id++}},sh=class{constructor(t){this._worker=new ih(t),this._earliestTimestamp=null,this._totalSize=0,this.hasCheckout=!1,this.waitForCheckout=!1}get hasEvents(){return!!this._earliestTimestamp}get type(){return"worker"}ensureReady(){return this._worker.ensureReady()}destroy(){this._worker.destroy()}addEvent(t){let n=Eh(t.timestamp);(!this._earliestTimestamp||n<this._earliestTimestamp)&&(this._earliestTimestamp=n);let r=JSON.stringify(t);return this._totalSize+=r.length,this._totalSize>hh?Promise.reject(new Il):this._sendEventToWorker(r)}finish(){return this._finishRequest()}clear(){this._earliestTimestamp=null,this._totalSize=0,this.hasCheckout=!1,this._worker.postMessage("clear").then(null,t=>{re&&oe.exception(t,'Sending "clear" message to worker failed',t)})}getEarliestTimestamp(){return this._earliestTimestamp}_sendEventToWorker(t){return this._worker.postMessage("addEvent",t)}async _finishRequest(){let t=await this._worker.postMessage("finish");return this._earliestTimestamp=null,this._totalSize=0,t}},ah=class{constructor(t){this._fallback=new Ku,this._compression=new sh(t),this._used=this._fallback,this._ensureWorkerIsLoadedPromise=this._ensureWorkerIsLoaded()}get waitForCheckout(){return this._used.waitForCheckout}get type(){return this._used.type}get hasEvents(){return this._used.hasEvents}get hasCheckout(){return this._used.hasCheckout}set hasCheckout(t){this._used.hasCheckout=t}set waitForCheckout(t){this._used.waitForCheckout=t}destroy(){this._fallback.destroy(),this._compression.destroy()}clear(){return this._used.clear()}getEarliestTimestamp(){return this._used.getEarliestTimestamp()}addEvent(t){return this._used.addEvent(t)}async finish(){return await this.ensureWorkerIsLoaded(),this._used.finish()}ensureWorkerIsLoaded(){return this._ensureWorkerIsLoadedPromise}async _ensureWorkerIsLoaded(){try{await this._compression.ensureReady()}catch(t){re&&oe.exception(t,"Failed to load the compression worker, falling back to simple buffer");return}await this._switchToCompressionWorker()}async _switchToCompressionWorker(){let{events:t,hasCheckout:n,waitForCheckout:r}=this._fallback,o=[];for(let i of t)o.push(this._compression.addEvent(i));this._compression.hasCheckout=n,this._compression.waitForCheckout=r,this._used=this._compression;try{await Promise.all(o),this._fallback.clear()}catch(i){re&&oe.exception(i,"Failed to add events when switching buffers.")}}};function CP({useCompression:e,workerUrl:t}){if(e&&window.Worker){let n=RP(t);if(n)return n}return re&&oe.log("Using simple buffer"),new Ku}function RP(e){try{let t=e||xP();if(!t)return;re&&oe.log(`Using compression worker${e?` from ${e}`:""}`);let n=new Worker(t);return new ah(n)}catch(t){re&&oe.exception(t,"Failed to create compression worker")}}function xP(){return typeof __SENTRY_EXCLUDE_REPLAY_WORKER__>"u"||!__SENTRY_EXCLUDE_REPLAY_WORKER__?IP():""}function Ih(){try{return"sessionStorage"in je&&!!je.sessionStorage}catch{return!1}}function bP(e){kP(),e.session=void 0}function kP(){if(Ih())try{je.sessionStorage.removeItem(ph)}catch{}}function BT(e){return e===void 0?!1:Math.random()<e}function sd(e){if(Ih())try{je.sessionStorage.setItem(ph,JSON.stringify(e))}catch{}}function HT(e){let t=Date.now(),n=e.id||at(),r=e.started||t,o=e.lastActivity||t,i=e.segmentId||0,s=e.sampled,a=e.previousSessionId,l=e.dirty||!1;return{id:n,started:r,lastActivity:o,segmentId:i,sampled:s,previousSessionId:a,dirty:l}}function NP(e,t){return BT(e)?"session":t?"buffer":!1}function sT({sessionSampleRate:e,allowBuffering:t,stickySession:n=!1},{previousSessionId:r}={}){let o=NP(e,t),i=HT({sampled:o,previousSessionId:r});return n&&sd(i),i}function AP(){if(!Ih())return null;try{let e=je.sessionStorage.getItem(ph);if(!e)return null;let t=JSON.parse(e);return re&&oe.infoTick("Loading existing session"),HT(t)}catch{return null}}function lh(e,t,n=+new Date){return e===null||t===void 0||t<0?!0:t===0?!1:e+t<=n}function MP(e,{maxReplayDuration:t,sessionIdleExpire:n,targetTime:r=Date.now()}){return lh(e.started,t,r)||lh(e.lastActivity,n,r)}function Ju(e,{sessionIdleExpire:t,maxReplayDuration:n}){return!(!MP(e,{sessionIdleExpire:t,maxReplayDuration:n})||e.sampled==="buffer"&&e.segmentId===0)}function zm({sessionIdleExpire:e,maxReplayDuration:t,previousSessionId:n},r){let o=r.stickySession&&AP();return o?Ju(o,{sessionIdleExpire:e,maxReplayDuration:t})?(re&&oe.infoTick("Session in sessionStorage is expired, creating new one..."),sT(r,{previousSessionId:o.id})):o:(re&&oe.infoTick("Creating new session"),sT(r,{previousSessionId:n}))}function PP(e){return e.type===me.Custom}function wh(e,t,n){return zT(e,t)?($T(e,t,n),!0):!1}function LP(e,t,n){return zT(e,t)?$T(e,t,n):Promise.resolve(null)}async function $T(e,t,n){let{eventBuffer:r}=e;if(!r||r.waitForCheckout&&!n)return null;let o=e.recordingMode==="buffer";try{n&&o&&r.clear(),n&&(r.hasCheckout=!0,r.waitForCheckout=!1);let i=e.getOptions(),s=OP(t,i.beforeAddRecordingEvent);return s?await r.addEvent(s):void 0}catch(i){let s=i&&i instanceof Il,a=s?"eventBufferOverflow":"eventBufferError",l=$();if(l){let c=s?"buffer_overflow":"internal_sdk_error";l.recordDroppedEvent(c,"replay")}if(s&&o)return r.clear(),r.waitForCheckout=!0,null;e.handleException(i),await e.stop({reason:a})}}function zT(e,t){if(!e.eventBuffer||e.isPaused()||!e.isEnabled())return!1;let n=Eh(t.timestamp);return n+e.timeouts.sessionIdlePause<Date.now()?!1:n>e.getContext().initialTimestamp+e.getOptions().maxReplayDuration?(re&&oe.infoTick(`Skipping event with timestamp ${n} because it is after maxReplayDuration`),!1):!0}function OP(e,t){try{if(typeof t=="function"&&PP(e))return t(e)}catch(n){return re&&oe.exception(n,"An error occurred in the `beforeAddRecordingEvent` callback, skipping the event..."),null}return e}function Ch(e){return!e.type}function ch(e){return e.type==="transaction"}function DP(e){return e.type==="replay_event"}function aT(e){return e.type==="feedback"}function UP(e){return(t,n)=>{if(!e.isEnabled()||!Ch(t)&&!ch(t))return;let r=n.statusCode;if(!(!r||r<200||r>=300)){if(ch(t)){FP(e,t);return}BP(e,t)}}}function FP(e,t){let n=e.getContext();t.contexts?.trace?.trace_id&&n.traceIds.size<100&&n.traceIds.add(t.contexts.trace.trace_id)}function BP(e,t){let n=e.getContext();if(t.event_id&&n.errorIds.size<100&&n.errorIds.add(t.event_id),e.recordingMode!=="buffer"||!t.tags?.replayId)return;let{beforeErrorSampling:r}=e.getOptions();typeof r=="function"&&!r(t)||Ii(async()=>{try{await e.sendBufferedReplayOrFlush()}catch(o){e.handleException(o)}})}function HP(e){return t=>{!e.isEnabled()||!Ch(t)||$P(e,t)}}function $P(e,t){let n=t.exception?.values?.[0]?.value;if(typeof n=="string"&&(n.match(/(reactjs\.org\/docs\/error-decoder\.html\?invariant=|react\.dev\/errors\/)(418|419|422|423|425)/)||n.match(/(does not match server-rendered HTML|Hydration failed because)/i))){let r=br({category:"replay.hydrate-error",data:{url:hn()}});xl(e,r)}}function zP(e){let t=$();t&&t.on("beforeAddBreadcrumb",n=>jP(e,n))}function jP(e,t){if(!e.isEnabled()||!jT(t))return;let n=WP(t);n&&xl(e,n)}function WP(e){return!jT(e)||["fetch","xhr","sentry.event","sentry.transaction"].includes(e.category)||e.category.startsWith("ui.")?null:e.category==="console"?GP(e):br(e)}function GP(e){let t=e.data?.arguments;if(!Array.isArray(t)||t.length===0)return br(e);let n=!1,r=t.map(o=>{if(!o)return o;if(typeof o=="string")return o.length>Du?(n=!0,`${o.slice(0,Du)}\u2026`):o;if(typeof o=="object")try{let i=$t(o,7);return JSON.stringify(i).length>Du?(n=!0,`${JSON.stringify(i,null,2).slice(0,Du)}\u2026`):i}catch{}return o});return br({...e,data:{...e.data,arguments:r,...n?{_meta:{warnings:["CONSOLE_ARG_TRUNCATED"]}}:{}}})}function jT(e){return!!e.category}function VP(e,t){return e.type||!e.exception?.values?.length?!1:!!t.originalException?.__rrweb__}function Xu(){let e=te().getPropagationContext().dsc;e&&delete e.replay_id;let t=Me();if(t){let n=ht(t);delete n.replay_id}}function lT(e){let t=te().getPropagationContext().dsc;t&&(t.replay_id=e);let n=Me();if(n){let r=ht(n);r.replay_id=e}}function qP(e,t){e.triggerUserActivity(),e.addUpdate(()=>t.timestamp?(e.throttledAddEvent({type:me.Custom,timestamp:t.timestamp*1e3,data:{tag:"breadcrumb",payload:{timestamp:t.timestamp,type:"default",category:"sentry.feedback",data:{feedbackId:t.event_id}}}}),!1):!0)}function YP(e,t){return e.recordingMode!=="buffer"||t.message===mh||!t.exception||t.type?!1:BT(e.getOptions().errorSampleRate)}function KP(e){return Object.assign((t,n)=>{if(e.session&&Ju(e.session,{maxReplayDuration:e.getOptions().maxReplayDuration,sessionIdleExpire:e.timeouts.sessionIdleExpire})&&Xu(),!e.isEnabled()||e.isPaused())return t;if(DP(t))return delete t.breadcrumbs,t;if(!Ch(t)&&!ch(t)&&!aT(t))return t;if(!e.checkAndHandleExpiredSession())return Xu(),t;if(aT(t))return e.flush(),t.contexts.feedback.replay_id=e.getSessionId(),qP(e,t),t;if(VP(t,n)&&!e.getOptions()._experiments.captureExceptions)return re&&oe.log("Ignoring error from rrweb internals",t),null;let o=YP(e,t);if((o||e.recordingMode==="session")&&(t.tags={...t.tags,replayId:e.getSessionId()}),o&&e.recordingMode==="buffer"&&e.session?.sampled==="buffer"){let s=e.session;s.dirty=!0,e.getOptions().stickySession&&sd(s)}return t},{id:"Replay"})}function ad(e,t){return t.map(({type:n,start:r,end:o,name:i,data:s})=>{let a=e.throttledAddEvent({type:me.Custom,timestamp:r,data:{tag:"performanceSpan",payload:{op:n,description:i,startTimestamp:r,endTimestamp:o,data:s}}});return typeof a=="string"?Promise.resolve(null):a})}function JP(e){let{from:t,to:n}=e,r=Date.now()/1e3;return{type:"navigation.push",start:r,end:r,name:n,data:{previous:t}}}function XP(e){return t=>{if(!e.isEnabled())return;let n=JP(t);n!==null&&(e.getContext().urls.push(n.name),e.triggerUserActivity(),e.addUpdate(()=>(ad(e,[n]),!1)))}}function QP(e,t){return re&&e.getOptions()._experiments.traceInternals?!1:Xp(t,$())}function WT(e,t){e.isEnabled()&&t!==null&&(QP(e,t.name)||e.addUpdate(()=>(ad(e,[t]),!0)))}function ld(e){if(!e)return;let t=new TextEncoder;try{if(typeof e=="string")return t.encode(e).length;if(e instanceof URLSearchParams)return t.encode(e.toString()).length;if(e instanceof FormData){let n=Au(e);return t.encode(n).length}if(e instanceof Blob)return e.size;if(e instanceof ArrayBuffer)return e.byteLength}catch{}}function GT(e){if(!e)return;let t=parseInt(e,10);return isNaN(t)?void 0:t}function Qu(e,t){if(!e)return{headers:{},size:void 0,_meta:{warnings:[t]}};let n={...e._meta},r=n.warnings||[];return n.warnings=[...r,t],e._meta=n,e}function VT(e,t){if(!t)return null;let{startTimestamp:n,endTimestamp:r,url:o,method:i,statusCode:s,request:a,response:l}=t;return{type:e,start:n/1e3,end:r/1e3,name:o,data:{method:i,statusCode:s,request:a,response:l}}}function wl(e){return{headers:{},size:e,_meta:{warnings:["URL_SKIPPED"]}}}function No(e,t,n){if(!t&&Object.keys(e).length===0)return;if(!t)return{headers:e};if(!n)return{headers:e,size:t};let r={headers:e,size:t},{body:o,warnings:i}=ZP(n);return r.body=o,i?.length&&(r._meta={warnings:i}),r}function uh(e,t){return Object.entries(e).reduce((n,[r,o])=>{let i=r.toLowerCase();return t.includes(i)&&e[r]&&(n[i]=o),n},{})}function ZP(e){if(!e||typeof e!="string")return{body:e};let t=e.length>zE,n=eL(e);if(t){let r=e.slice(0,zE);return n?{body:r,warnings:["MAYBE_JSON_TRUNCATED"]}:{body:`${r}\u2026`,warnings:["TEXT_TRUNCATED"]}}if(n)try{return{body:JSON.parse(e)}}catch{}return{body:e}}function eL(e){let t=e[0],n=e[e.length-1];return t==="["&&n==="]"||t==="{"&&n==="}"}function Zu(e,t){let n=tL(e);return Nt(n,t)}function tL(e,t=je.document.baseURI){if(e.startsWith("http://")||e.startsWith("https://")||e.startsWith(je.location.origin))return e;let n=new URL(e,t);if(n.origin!==new URL(t).origin)return e;let r=n.href;return!e.endsWith("/")&&r.endsWith("/")?r.slice(0,-1):r}async function nL(e,t,n){try{let r=await oL(e,t,n),o=VT("resource.fetch",r);WT(n.replay,o)}catch(r){re&&oe.exception(r,"Failed to capture fetch breadcrumb")}}function rL(e,t){let{input:n,response:r}=t,o=n?Pu(n):void 0,i=ld(o),s=r?GT(r.headers.get("content-length")):void 0;i!==void 0&&(e.data.request_body_size=i),s!==void 0&&(e.data.response_body_size=s)}async function oL(e,t,n){let r=Date.now(),{startTimestamp:o=r,endTimestamp:i=r}=t,{url:s,method:a,status_code:l=0,request_body_size:c,response_body_size:u}=e.data,f=Zu(s,n.networkDetailAllowUrls)&&!Zu(s,n.networkDetailDenyUrls),p=f?iL(n,t.input,c):wl(c),h=await sL(f,n,t.response,u);return{startTimestamp:o,endTimestamp:i,url:s,method:a,statusCode:l,request:p,response:h}}function iL({networkCaptureBodies:e,networkRequestHeaders:t},n,r){let o=n?cL(n,t):{};if(!e)return No(o,r,void 0);let i=Pu(n),[s,a]=Mu(i,oe),l=No(o,r,s);return a?Qu(l,a):l}async function sL(e,{networkCaptureBodies:t,networkResponseHeaders:n},r,o){if(!e&&o!==void 0)return wl(o);let i=r?qT(r.headers,n):{};if(!r||!t&&o!==void 0)return No(i,o,void 0);let[s,a]=await lL(r),l=aL(s,{networkCaptureBodies:t,responseBodySize:o,captureDetails:e,headers:i});return a?Qu(l,a):l}function aL(e,{networkCaptureBodies:t,responseBodySize:n,captureDetails:r,headers:o}){try{let i=e?.length&&n===void 0?ld(e):n;return r?t?No(o,i,e):No(o,i,void 0):wl(i)}catch(i){return re&&oe.exception(i,"Failed to serialize response body"),No(o,n,void 0)}}async function lL(e){let t=uL(e);if(!t)return[void 0,"BODY_PARSE_ERROR"];try{return[await dL(t)]}catch(n){return n instanceof Error&&n.message.indexOf("Timeout")>-1?(re&&oe.warn("Parsing text body from response timed out"),[void 0,"BODY_PARSE_TIMEOUT"]):(re&&oe.exception(n,"Failed to get text body from response"),[void 0,"BODY_PARSE_ERROR"])}}function qT(e,t){let n={};return t.forEach(r=>{e.get(r)&&(n[r]=e.get(r))}),n}function cL(e,t){return e.length===1&&typeof e[0]!="string"?cT(e[0],t):e.length===2?cT(e[1],t):{}}function cT(e,t){if(!e)return{};let n=e.headers;return n?n instanceof Headers?qT(n,t):Array.isArray(n)?{}:uh(n,t):{}}function uL(e){try{return e.clone()}catch(t){re&&oe.exception(t,"Failed to clone response body")}}function dL(e){return new Promise((t,n)=>{let r=Ii(()=>n(new Error("Timeout while trying to read response body")),500);fL(e).then(o=>t(o),o=>n(o)).finally(()=>clearTimeout(r))})}async function fL(e){return await e.text()}async function pL(e,t,n){try{let r=hL(e,t,n),o=VT("resource.xhr",r);WT(n.replay,o)}catch(r){re&&oe.exception(r,"Failed to capture xhr breadcrumb")}}function mL(e,t){let{xhr:n,input:r}=t;if(!n)return;let o=ld(r),i=n.getResponseHeader("content-length")?GT(n.getResponseHeader("content-length")):SL(n.response,n.responseType);o!==void 0&&(e.data.request_body_size=o),i!==void 0&&(e.data.response_body_size=i)}function hL(e,t,n){let r=Date.now(),{startTimestamp:o=r,endTimestamp:i=r,input:s,xhr:a}=t,{url:l,method:c,status_code:u=0,request_body_size:f,response_body_size:p}=e.data;if(!l)return null;if(!a||!Zu(l,n.networkDetailAllowUrls)||Zu(l,n.networkDetailDenyUrls)){let A=wl(f),I=wl(p);return{startTimestamp:o,endTimestamp:i,url:l,method:c,statusCode:u,request:A,response:I}}let h=a[ur],y=h?uh(h.request_headers,n.networkRequestHeaders):{},_=uh(dl(a),n.networkResponseHeaders),[T,g]=n.networkCaptureBodies?Mu(s,oe):[void 0],[S,E]=n.networkCaptureBodies?gL(a):[void 0],R=No(y,f,T),M=No(_,p,S);return{startTimestamp:o,endTimestamp:i,url:l,method:c,statusCode:u,request:g?Qu(R,g):R,response:E?Qu(M,E):M}}function gL(e){let t=[];try{return[e.responseText]}catch(n){t.push(n)}try{return yL(e.response,e.responseType)}catch(n){t.push(n)}return re&&oe.warn("Failed to get xhr response body",...t),[void 0]}function yL(e,t){try{if(typeof e=="string")return[e];if(e instanceof Document)return[e.body.outerHTML];if(t==="json"&&e&&typeof e=="object")return[JSON.stringify(e)];if(!e)return[void 0]}catch(n){return re&&oe.exception(n,"Failed to serialize body",e),[void 0,"BODY_PARSE_ERROR"]}return re&&oe.log("Skipping network body because of body type",e),[void 0,"UNPARSEABLE_BODY_TYPE"]}function SL(e,t){try{let n=t==="json"&&e&&typeof e=="object"?JSON.stringify(e):e;return ld(n)}catch{return}}function _L(e){let t=$();try{let{networkDetailAllowUrls:n,networkDetailDenyUrls:r,networkCaptureBodies:o,networkRequestHeaders:i,networkResponseHeaders:s}=e.getOptions(),a={replay:e,networkDetailAllowUrls:n,networkDetailDenyUrls:r,networkCaptureBodies:o,networkRequestHeaders:i,networkResponseHeaders:s};t&&t.on("beforeAddBreadcrumb",(l,c)=>vL(a,l,c))}catch{}}function vL(e,t,n){if(t.data)try{EL(t)&&IL(n)&&(mL(t,n),pL(t,n,e)),TL(t)&&wL(n)&&(rL(t,n),nL(t,n,e))}catch(r){re&&oe.exception(r,"Error when enriching network breadcrumb")}}function EL(e){return e.category==="xhr"}function TL(e){return e.category==="fetch"}function IL(e){return e?.xhr}function wL(e){return e?.input!==void 0}function CL(e){let t=$();cl(oP(e)),Qr(XP(e)),zP(e),_L(e);let n=KP(e);Ka(n),t&&(t.on("beforeSendEvent",HP(e)),t.on("afterSendEvent",UP(e)),t.on("createDsc",r=>{let o=e.getSessionId();o&&e.isEnabled()&&e.recordingMode==="session"&&e.checkAndHandleExpiredSession()&&(r.replay_id=o)}),t.on("spanStart",r=>{e.lastActiveSpan=r}),t.on("spanEnd",r=>{e.lastActiveSpan=r}),t.on("beforeSendFeedback",async(r,o)=>{let i=e.getSessionId();o?.includeReplay&&e.isEnabled()&&i&&r.contexts?.feedback&&(r.contexts.feedback.source==="api"&&await e.sendBufferedReplayOrFlush(),r.contexts.feedback.replay_id=i)}),t.on("openFeedbackWidget",async()=>{await e.sendBufferedReplayOrFlush()}))}async function RL(e){try{return Promise.all(ad(e,[xL(je.performance.memory)]))}catch{return[]}}function xL(e){let{jsHeapSizeLimit:t,totalJSHeapSize:n,usedJSHeapSize:r}=e,o=Date.now()/1e3;return{type:"memory",name:"memory",start:o,end:o,data:{memory:{jsHeapSizeLimit:t,totalJSHeapSize:n,usedJSHeapSize:r}}}}function bL(e,t,n){return Zp(e,t,{...n,setTimeoutImpl:Ii})}var Bu=G.navigator;function kL(){return/iPhone|iPad|iPod/i.test(Bu?.userAgent??"")||/Macintosh/i.test(Bu?.userAgent??"")&&Bu?.maxTouchPoints&&Bu?.maxTouchPoints>1?{sampling:{mousemove:!1}}:{}}function NL(e){let t=!1;return(n,r)=>{if(!e.checkAndHandleExpiredSession()){re&&oe.warn("Received replay event after session expired.");return}let o=r||!t;t=!0,AL(n),e.clickDetector&&ZM(e.clickDetector,n),e.addUpdate(()=>{if(e.recordingMode==="buffer"&&o&&e.setInitialState(),!wh(e,n,o))return!0;if(!o)return!1;let i=e.session;if(PL(e,o),e.recordingMode==="buffer"&&i&&e.eventBuffer&&!i.dirty){let s=e.eventBuffer.getEarliestTimestamp();s&&(re&&oe.log(`Updating session start time to earliest event in buffer to ${new Date(s)}`),i.started=s,e.getOptions().stickySession&&sd(i))}return i?.previousSessionId||e.recordingMode==="session"&&e.flush(),!0})}}function AL(e){let t=e.data;if(!(e.type!==me.IncrementalSnapshot||!t||typeof t!="object"||!("source"in t)||t.source!==se.Mutation||!("attributes"in t)||!Array.isArray(t.attributes)))for(let n of t.attributes){let r=fr.mirror.getNode(n.id),o=r&&fr.mirror.getMeta(r);if(o?.type===id.Element)for(let[i,s]of Object.entries(n.attributes))s===null?delete o.attributes[i]:o.attributes[i]=s}}function ML(e){let t=e.getOptions();return{type:me.Custom,timestamp:Date.now(),data:{tag:"options",payload:{shouldRecordCanvas:e.isRecordingCanvas(),sessionSampleRate:t.sessionSampleRate,errorSampleRate:t.errorSampleRate,useCompressionOption:t.useCompression,blockAllMedia:t.blockAllMedia,maskAllText:t.maskAllText,maskAllInputs:t.maskAllInputs,useCompression:e.eventBuffer?e.eventBuffer.type==="worker":!1,networkDetailHasUrls:t.networkDetailAllowUrls.length>0,networkCaptureBodies:t.networkCaptureBodies,networkRequestHasHeaders:t.networkRequestHeaders.length>0,networkResponseHasHeaders:t.networkResponseHeaders.length>0}}}}function PL(e,t){!t||e.session?.segmentId!==0||wh(e,ML(e),!1)}function LL(e){if(!e)return null;try{return e.nodeType===e.ELEMENT_NODE?e:e.parentElement}catch{return null}}function OL(e,t,n,r){return en(ja(e,as(e),r,n),[[{type:"replay_event"},e],[{type:"replay_recording",length:typeof t=="string"?new TextEncoder().encode(t).length:t.length},t]])}function DL({recordingData:e,headers:t}){let n,r=`${JSON.stringify(t)}
|
|
31
31
|
`;if(typeof e=="string")n=`${r}${e}`;else{let i=new TextEncoder().encode(r);n=new Uint8Array(i.length+e.length),n.set(i),n.set(e,i.length)}return n}async function UL({client:e,scope:t,replayId:n,event:r}){let o=typeof e._integrations=="object"&&e._integrations!==null&&!Array.isArray(e._integrations)?Object.keys(e._integrations):void 0,i={event_id:n,integrations:o};e.emit("preprocessEvent",r,i);let s=await Va(e.getOptions(),r,i,t,e,Xe());if(!s)return null;e.emit("postprocessEvent",s,i),s.platform=s.platform||"javascript";let a=e.getSdkMetadata(),{name:l,version:c,settings:u}=a?.sdk||{};return s.sdk={...s.sdk,name:l||"sentry.javascript.unknown",version:c||"0.0.0",settings:u},s}async function FL({recordingData:e,replayId:t,segmentId:n,eventContext:r,timestamp:o,session:i}){let s=DL({recordingData:e,headers:{segment_id:n}}),{urls:a,errorIds:l,traceIds:c,initialTimestamp:u}=r,f=$(),p=te(),h=f?.getTransport(),y=f?.getDsn();if(!f||!h||!y||!i.sampled)return Promise.resolve({});let _={type:C1,replay_start_timestamp:u/1e3,timestamp:o/1e3,error_ids:l,trace_ids:c,urls:a,replay_id:t,segment_id:n,replay_type:i.sampled},T=await UL({scope:p,client:f,replayId:t,event:_});if(!T)return f.recordDroppedEvent("event_processor","replay"),re&&oe.log("An event processor returned `null`, will not send event."),Promise.resolve({});delete T.sdkProcessingMetadata;let g=OL(T,s,y,f.getOptions().tunnel),S;try{S=await h.send(g)}catch(R){let M=new Error(mh);try{M.cause=R}catch{}throw M}let E=Za({},S);if(Qa(E,"replay"))throw new Cl(E);if(typeof S.statusCode=="number"&&(S.statusCode<200||S.statusCode>=300))throw new ed(S.statusCode);return S}var ed=class extends Error{constructor(t){super(`Transport returned status code ${t}`)}},Cl=class extends Error{constructor(t){super("Rate limit hit"),this.rateLimits=t}},td=class extends Error{constructor(){super("Session is too long, not sending replay")}};async function YT(e,t={count:0,interval:A1}){let{recordingData:n,onError:r}=e;if(n.length)try{return await FL(e),!0}catch(o){if(o instanceof ed||o instanceof Cl)throw o;if(mi("Replays",{_retryCount:t.count}),r&&r(o),t.count>=M1){let i=new Error(`${mh} - max retries exceeded`);try{i.cause=o}catch{}throw i}return t.interval*=++t.count,new Promise((i,s)=>{Ii(async()=>{try{await YT(e,t),i(!0)}catch(a){s(a)}},t.interval)})}}var KT="__THROTTLED",BL="__SKIPPED";function HL(e,t,n){let r=new Map,o=a=>{let l=a-n;r.forEach((c,u)=>{u<l&&r.delete(u)})},i=()=>[...r.values()].reduce((a,l)=>a+l,0),s=!1;return(...a)=>{let l=Math.floor(Date.now()/1e3);if(o(l),i()>=t){let u=s;return s=!0,u?BL:KT}s=!1;let c=r.get(l)||0;return r.set(l,c+1),e(...a)}}var dh=class{constructor({options:t,recordingOptions:n}){this.eventBuffer=null,this.performanceEntries=[],this.replayPerformanceEntries=[],this.recordingMode="session",this.timeouts={sessionIdlePause:R1,sessionIdleExpire:x1},this._lastActivity=Date.now(),this._isEnabled=!1,this._isPaused=!1,this._requiresManualStart=!1,this._hasInitializedCoreListeners=!1,this._context={errorIds:new Set,traceIds:new Set,urls:[],initialTimestamp:Date.now(),initialUrl:""},this._recordingOptions=n,this._options=t,this._debouncedFlush=bL(()=>this._flush(),this._options.flushMinDelay,{maxWait:this._options.flushMaxDelay}),this._throttledAddEvent=HL((s,a)=>LP(this,s,a),300,5);let{slowClickTimeout:r,slowClickIgnoreSelectors:o}=this.getOptions(),i=r?{threshold:Math.min(P1,r),timeout:r,scrollTimeout:L1,ignoreSelector:o?o.join(","):""}:void 0;if(i&&(this.clickDetector=new oh(this,i)),re){let s=t._experiments;oe.setConfig({captureExceptions:!!s.captureExceptions,traceInternals:!!s.traceInternals})}this._handleVisibilityChange=()=>{je.document.visibilityState==="visible"?this._doChangeToForegroundTasks():this._doChangeToBackgroundTasks()},this._handleWindowBlur=()=>{let s=br({category:"ui.blur"});this._doChangeToBackgroundTasks(s)},this._handleWindowFocus=()=>{let s=br({category:"ui.focus"});this._doChangeToForegroundTasks(s)},this._handleKeyboardEvent=s=>{lP(this,s)}}getContext(){return this._context}isEnabled(){return this._isEnabled}isPaused(){return this._isPaused}isRecordingCanvas(){return!!this._canvas}getOptions(){return this._options}handleException(t){re&&oe.exception(t),this._options.onError&&this._options.onError(t)}initializeSampling(t){let{errorSampleRate:n,sessionSampleRate:r}=this._options,o=n<=0&&r<=0;if(this._requiresManualStart=o,!o){if(this._initializeSessionForSampling(t),!this.session){re&&oe.exception(new Error("Unable to initialize and create session"));return}this.session.sampled!==!1&&(this.recordingMode=this.session.sampled==="buffer"&&this.session.segmentId===0?"buffer":"session",re&&oe.infoTick(`Starting replay in ${this.recordingMode} mode`),this._initializeRecording())}}start(){if(this._isEnabled&&this.recordingMode==="session"){re&&oe.log("Recording is already in progress");return}if(this._isEnabled&&this.recordingMode==="buffer"){re&&oe.log("Buffering is in progress, call `flush()` to save the replay");return}re&&oe.infoTick("Starting replay in session mode"),this._updateUserActivity();let t=zm({maxReplayDuration:this._options.maxReplayDuration,sessionIdleExpire:this.timeouts.sessionIdleExpire},{stickySession:this._options.stickySession,sessionSampleRate:1,allowBuffering:!1});this.session=t,this.recordingMode="session",this._initializeRecording()}startBuffering(){if(this._isEnabled){re&&oe.log("Buffering is in progress, call `flush()` to save the replay");return}re&&oe.infoTick("Starting replay in buffer mode");let t=zm({sessionIdleExpire:this.timeouts.sessionIdleExpire,maxReplayDuration:this._options.maxReplayDuration},{stickySession:this._options.stickySession,sessionSampleRate:0,allowBuffering:!0});this.session=t,this.recordingMode="buffer",this._initializeRecording()}startRecording(){try{let t=this._canvas;this._stopRecording=fr({...this._recordingOptions,...this.recordingMode==="buffer"?{checkoutEveryNms:N1}:this._options._experiments.continuousCheckout&&{checkoutEveryNms:Math.max(36e4,this._options._experiments.continuousCheckout)},emit:NL(this),...kL(),onMutation:this._onMutationHandler.bind(this),...t?{recordCanvas:t.recordCanvas,getCanvasManager:t.getCanvasManager,sampling:t.sampling,dataURLOptions:t.dataURLOptions}:{}})}catch(t){this.handleException(t)}}stopRecording(){try{return this._stopRecording&&(this._stopRecording(),this._stopRecording=void 0),!0}catch(t){return this.handleException(t),!1}}async stop({forceFlush:t=!1,reason:n}={}){if(!this._isEnabled)return;this._isEnabled=!1,this.recordingMode="buffer";let r=n??"manual";$()?.emit("replayEnd",{sessionId:this.session?.id,reason:r});try{re&&oe.log(`Stopping Replay triggered by ${r}`),Xu(),this._removeListeners(),this.stopRecording(),this._debouncedFlush.cancel(),t&&await this._flush({force:!0}),this.eventBuffer?.destroy(),this.eventBuffer=null,bP(this)}catch(o){this.handleException(o)}}pause(){this._isPaused||(this._isPaused=!0,this.stopRecording(),re&&oe.log("Pausing replay"))}resume(){!this._isPaused||!this._checkSession()||(this._isPaused=!1,this.startRecording(),re&&oe.log("Resuming replay"))}async sendBufferedReplayOrFlush({continueRecording:t=!0}={}){if(this.recordingMode==="session")return this.flushImmediate();let n=Date.now();re&&oe.log("Converting buffer to session"),await this.flushImmediate();let r=this.stopRecording();!t||!r||this.recordingMode!=="session"&&(this.recordingMode="session",this.session&&(this.session.dirty=!1,this._updateUserActivity(n),this._updateSessionActivity(n),this._maybeSaveSession(),lT(this.session.id)),this.startRecording())}addUpdate(t){let n=t();this.recordingMode==="buffer"||!this._isEnabled||n!==!0&&this._debouncedFlush()}triggerUserActivity(){if(this._updateUserActivity(),!this._stopRecording){if(!this._checkSession())return;this.resume();return}this.checkAndHandleExpiredSession(),this._updateSessionActivity()}updateUserActivity(){this._updateUserActivity(),this._updateSessionActivity()}conditionalFlush(){return this.recordingMode==="buffer"?Promise.resolve():this.flushImmediate()}flush(){return this._debouncedFlush()}flushImmediate(){return this._debouncedFlush(),this._debouncedFlush.flush()}cancelFlush(){this._debouncedFlush.cancel()}getSessionId(t){if(!(t&&this.session?.sampled===!1))return this.session?.id}checkAndHandleExpiredSession(){if(this._lastActivity&&lh(this._lastActivity,this.timeouts.sessionIdlePause)&&this.session?.sampled==="session"){this.pause();return}return!!this._checkSession()}setInitialState(){let t=`${je.location.pathname}${je.location.hash}${je.location.search}`,n=`${je.location.origin}${t}`;this.performanceEntries=[],this.replayPerformanceEntries=[],this._clearContext(),this._context.initialUrl=n,this._context.initialTimestamp=Date.now(),this._context.urls.push(n)}throttledAddEvent(t,n){let r=this._throttledAddEvent(t,n);if(r===KT){let o=br({category:"replay.throttled"});this.addUpdate(()=>!wh(this,{type:jM,timestamp:o.timestamp||0,data:{tag:"breadcrumb",payload:o,metric:!0}}))}return r}getCurrentRoute(){let t=this.lastActiveSpan||Me(),n=t&&be(t),o=(n&&ne(n).data||{})[vt];if(!(!n||!o||!["route","custom"].includes(o)))return ne(n).description}_initializeRecording(){this.setInitialState(),this._updateSessionActivity(),this.eventBuffer=CP({useCompression:this._options.useCompression,workerUrl:this._options.workerUrl}),this._removeListeners(),this._addListeners(),this._isEnabled=!0,this._isPaused=!1,this.session&&$()?.emit("replayStart",{sessionId:this.session.id,recordingMode:this.recordingMode}),this.startRecording(),this.recordingMode==="session"&&this.session&&lT(this.session.id)}_initializeSessionForSampling(t){let n=this._options.errorSampleRate>0,r=zm({sessionIdleExpire:this.timeouts.sessionIdleExpire,maxReplayDuration:this._options.maxReplayDuration,previousSessionId:t},{stickySession:this._options.stickySession,sessionSampleRate:this._options.sessionSampleRate,allowBuffering:n});this.session=r}_checkSession(){if(!this.session)return!1;let t=this.session;return Ju(t,{sessionIdleExpire:this.timeouts.sessionIdleExpire,maxReplayDuration:this._options.maxReplayDuration})?(this._refreshSession(t),!1):!0}async _refreshSession(t){this._isEnabled&&(await this.stop({reason:"sessionExpired"}),this.initializeSampling(t.id))}_addListeners(){try{je.document.addEventListener("visibilitychange",this._handleVisibilityChange),je.addEventListener("blur",this._handleWindowBlur),je.addEventListener("focus",this._handleWindowFocus),je.addEventListener("keydown",this._handleKeyboardEvent),this.clickDetector&&this.clickDetector.addListeners(),this._hasInitializedCoreListeners||(CL(this),this._hasInitializedCoreListeners=!0)}catch(t){this.handleException(t)}this._performanceCleanupCallback=EP(this)}_removeListeners(){try{je.document.removeEventListener("visibilitychange",this._handleVisibilityChange),je.removeEventListener("blur",this._handleWindowBlur),je.removeEventListener("focus",this._handleWindowFocus),je.removeEventListener("keydown",this._handleKeyboardEvent),this.clickDetector&&this.clickDetector.removeListeners(),this._performanceCleanupCallback&&this._performanceCleanupCallback()}catch(t){this.handleException(t)}}_doChangeToBackgroundTasks(t){if(!this.session)return;if(Ju(this.session,{maxReplayDuration:this._options.maxReplayDuration,sessionIdleExpire:this.timeouts.sessionIdleExpire})){Xu();return}t&&this._createCustomBreadcrumb(t),this.conditionalFlush()}_doChangeToForegroundTasks(t){if(!this.session)return;if(!this.checkAndHandleExpiredSession()){re&&oe.log("Document has become active, but session has expired");return}t&&this._createCustomBreadcrumb(t)}_updateUserActivity(t=Date.now()){this._lastActivity=t}_updateSessionActivity(t=Date.now()){this.session&&(this.session.lastActivity=t,this._maybeSaveSession())}_createCustomBreadcrumb(t){this.addUpdate(()=>{this.throttledAddEvent({type:me.Custom,timestamp:t.timestamp||0,data:{tag:"breadcrumb",payload:t}})})}_addPerformanceEntries(){let t=fP(this.performanceEntries).concat(this.replayPerformanceEntries);if(this.performanceEntries=[],this.replayPerformanceEntries=[],this._requiresManualStart){let n=this._context.initialTimestamp/1e3;t=t.filter(r=>r.start>=n)}return Promise.all(ad(this,t))}_clearContext(){this._context.errorIds.clear(),this._context.traceIds.clear(),this._context.urls=[]}_updateInitialTimestampFromEventBuffer(){let{session:t,eventBuffer:n}=this;if(!t||!n||this._requiresManualStart||t.segmentId)return;let r=n.getEarliestTimestamp();r&&r<this._context.initialTimestamp&&(this._context.initialTimestamp=r)}_popEventContext(){let t={initialTimestamp:this._context.initialTimestamp,initialUrl:this._context.initialUrl,errorIds:Array.from(this._context.errorIds),traceIds:Array.from(this._context.traceIds),urls:this._context.urls};return this._clearContext(),t}async _runFlush(){let t=this.getSessionId();if(!this.session||!this.eventBuffer||!t){re&&oe.error("No session or eventBuffer found to flush.");return}if(await this._addPerformanceEntries(),!!this.eventBuffer?.hasEvents&&(await RL(this),!!this.eventBuffer&&t===this.getSessionId()))try{this._updateInitialTimestampFromEventBuffer();let n=Date.now();if(n-this._context.initialTimestamp>this._options.maxReplayDuration+3e4)throw new td;let r=this._popEventContext(),o=this.session.segmentId++;this._maybeSaveSession();let i=await this.eventBuffer.finish();await YT({replayId:t,recordingData:i,segmentId:o,eventContext:r,session:this.session,timestamp:n,onError:s=>this.handleException(s)})}catch(n){this.handleException(n),this.stop({reason:"sendError"});let r=$();if(r){let o;n instanceof Cl?o="ratelimit_backoff":n instanceof td?o="invalid":o="send_error",r.recordDroppedEvent(o,"replay")}}}async _flush({force:t=!1}={}){if(!this._isEnabled&&!t)return;if(!this.checkAndHandleExpiredSession()){re&&oe.error("Attempting to finish replay event after session expired.");return}if(!this.session)return;let n=this.session.started,o=Date.now()-n;this._debouncedFlush.cancel();let i=o<this._options.minReplayDuration,s=o>this._options.maxReplayDuration+5e3;if(i||s){re&&oe.log(`Session duration (${Math.floor(o/1e3)}s) is too ${i?"short":"long"}, not sending replay.`),i&&this._debouncedFlush();return}let a=this.eventBuffer;a&&this.session.segmentId===0&&!a.hasCheckout&&re&&oe.log("Flushing initial segment without checkout.");let l=!!this._flushLock;this._flushLock||(this._flushLock=this._runFlush());try{await this._flushLock}catch(c){this.handleException(c)}finally{this._flushLock=void 0,l&&this._debouncedFlush()}}_maybeSaveSession(){this.session&&this._options.stickySession&&sd(this.session)}_onMutationHandler(t){let{ignoreMutations:n}=this._options._experiments;if(n?.length&&t.some(a=>{let l=LL(a.target),c=n.join(",");return l?.matches(c)}))return!1;let r=t.length,o=this._options.mutationLimit,i=this._options.mutationBreadcrumbLimit,s=o&&r>o;if(r>i||s){let a=br({category:"replay.mutations",data:{count:r,limit:s}});this._createCustomBreadcrumb(a)}return s?(this.stop({reason:"mutationLimit",forceFlush:this.recordingMode==="session"}),!1):!0}};function ml(e,t){return[...e,...t].join(",")}function $L({mask:e,unmask:t,block:n,unblock:r,ignore:o}){let i=["base","iframe[srcdoc]:not([src])"],s=ml(e,[".sentry-mask","[data-sentry-mask]"]),a=ml(t,[]);return{maskTextSelector:s,unmaskTextSelector:a,blockSelector:ml(n,[".sentry-block","[data-sentry-block]",...i]),unblockSelector:ml(r,[]),ignoreSelector:ml(o,[".sentry-ignore","[data-sentry-ignore]",'input[type="file"]'])}}function zL({el:e,key:t,maskAttributes:n,maskAllText:r,privacyOptions:o,value:i}){if(o.unmaskTextSelector&&e.matches(o.unmaskTextSelector))return i;let s=n.includes(t),a=r&&t==="value"&&e.tagName==="INPUT"&&["submit","button"].includes(e.getAttribute("type")||"");return s||a?i.replace(/[\S]/g,"*"):i}var uT='img,image,svg,video,object,picture,embed,map,audio,link[rel="icon"],link[rel="apple-touch-icon"]',jL=["content-length","content-type","accept"],WL=Symbol.for("sentry__originalRequestBody"),dT=!1,fT=!1;function GL(){if(typeof Request>"u"||fT)return;let e=Request;try{let t=function(n,r){let o=new e(n,r);return r?.body!=null&&(o[WL]=r.body),o};t.prototype=e.prototype,G.Request=t,fT=!0}catch{}}var Rh=(e=>new fh(e)),fh=class{constructor({flushMinDelay:t=b1,flushMaxDelay:n=k1,minReplayDuration:r=O1,maxReplayDuration:o=jE,stickySession:i=!0,useCompression:s=!0,workerUrl:a,_experiments:l={},maskAllText:c=!0,maskAllInputs:u=!0,blockAllMedia:f=!0,mutationBreadcrumbLimit:p=750,mutationLimit:h=1e4,slowClickTimeout:y=7e3,slowClickIgnoreSelectors:_=[],networkDetailAllowUrls:T=[],networkDetailDenyUrls:g=[],networkCaptureBodies:S=!0,networkRequestHeaders:E=[],networkResponseHeaders:R=[],mask:M=[],maskAttributes:A=["title","placeholder","aria-label"],unmask:I=[],block:N=[],unblock:U=[],ignore:x=[],maskFn:H,beforeAddRecordingEvent:j,beforeErrorSampling:he,onError:X,attachRawBodyFromRequest:Ze=!1}={}){this.name="Replay";let fe=$L({mask:M,unmask:I,block:N,unblock:U,ignore:x});if(this._recordingOptions={maskAllInputs:u,maskAllText:c,maskInputOptions:{password:!0},maskTextFn:H,maskInputFn:H,maskAttributeFn:(de,D,ge)=>zL({maskAttributes:A,maskAllText:c,privacyOptions:fe,key:de,value:D,el:ge}),...fe,slimDOMOptions:"all",inlineStylesheet:!0,inlineImages:!1,collectFonts:!0,errorHandler:de=>{try{de.__rrweb__=!0}catch{}},recordCrossOriginIframes:!!l.recordCrossOriginIframes},this._initialOptions={flushMinDelay:t,flushMaxDelay:n,minReplayDuration:Math.min(r,D1),maxReplayDuration:Math.min(o,jE),stickySession:i,useCompression:s,workerUrl:a,blockAllMedia:f,maskAllInputs:u,maskAllText:c,mutationBreadcrumbLimit:p,mutationLimit:h,slowClickTimeout:y,slowClickIgnoreSelectors:_,networkDetailAllowUrls:T,networkDetailDenyUrls:g,networkCaptureBodies:S,networkRequestHeaders:pT(E),networkResponseHeaders:pT(R),beforeAddRecordingEvent:j,beforeErrorSampling:he,onError:X,attachRawBodyFromRequest:Ze,_experiments:l},this._initialOptions.blockAllMedia&&(this._recordingOptions.blockSelector=this._recordingOptions.blockSelector?`${this._recordingOptions.blockSelector},${uT}`:uT,this._recordingOptions.ignoreCSSAttributes=new Set(["background-image"])),this._isInitialized&&jn())throw new Error("Multiple Sentry Session Replay instances are not supported");this._isInitialized=!0}get _isInitialized(){return dT}set _isInitialized(t){dT=t}afterAllSetup(t){!jn()||this._replay||(this._initialOptions.attachRawBodyFromRequest&&GL(),this._setup(t),this._initialize(t))}start(){this._replay&&this._replay.start()}startBuffering(){this._replay&&this._replay.startBuffering()}stop(){return this._replay?this._replay.stop({forceFlush:this._replay.recordingMode==="session",reason:"manual"}):Promise.resolve()}flush(t){return this._replay?this._replay.isEnabled()?this._replay.sendBufferedReplayOrFlush(t):(this._replay.start(),Promise.resolve()):Promise.resolve()}getReplayId(t){if(this._replay?.isEnabled())return this._replay.getSessionId(t)}getRecordingMode(){if(this._replay?.isEnabled())return this._replay.recordingMode}processSpan(t){let n=this.getReplayId(!0);n&&Io(t,{"sentry.replay_id":n})}_initialize(t){this._replay&&(this._maybeLoadFromReplayCanvasIntegration(t),this._replay.initializeSampling())}_setup(t){let n=VL(this._initialOptions,t);this._replay=new dh({options:n,recordingOptions:this._recordingOptions})}_maybeLoadFromReplayCanvasIntegration(t){try{let n=t.getIntegrationByName("ReplayCanvas");if(!n)return;this._replay._canvas=n.getOptions()}catch{}}};function VL(e,t){let n=t.getOptions(),r={sessionSampleRate:0,errorSampleRate:0,...e},o=bn(n.replaysSessionSampleRate),i=bn(n.replaysOnErrorSampleRate);return o==null&&i==null&&kt(()=>{console.warn("Replay is disabled because neither `replaysSessionSampleRate` nor `replaysOnErrorSampleRate` are set.")}),o!=null&&(r.sessionSampleRate=o),i!=null&&(r.errorSampleRate=i),r}function pT(e){return[...jL,...e.map(t=>t.toLowerCase())]}function JT(e){return e.split(",").some(t=>t.trim().startsWith("sentry-"))}function xh(e){try{return new URL(e,ee.location.origin).href}catch{return}}function XT(e){return e.entryType==="resource"&&"initiatorType"in e&&typeof e.nextHopProtocol=="string"&&(e.initiatorType==="fetch"||e.initiatorType==="xmlhttprequest")}function bh(e){try{return new Headers(e)}catch{return}}var kh={traceFetch:!0,traceXHR:!0,enableHTTPTimings:!0,trackFetchStreamPerformance:!1};function ZT(e,t){let{traceFetch:n,traceXHR:r,shouldCreateSpanForRequest:o,enableHTTPTimings:i,tracePropagationTargets:s,onRequestSpanStart:a,onRequestSpanEnd:l}={...kh,...t},c=typeof o=="function"?o:h=>!0,u=h=>YL(h,s),f={},p=e.getOptions().propagateTraceparent;n&&Co(h=>{let y=im(h,c,u,f,{propagateTraceparent:p,onRequestSpanEnd:l});if(y){let _=xh(h.fetchData.url),T=_?zn(_).host:void 0;y.setAttributes({"http.url":_?Wt(_):void 0,"server.address":T}),i&&QT(y,e),a?.(y,{headers:h.headers})}}),r&&ul(h=>{let y=KL(h,c,u,f,p,l);y&&(i&&QT(y,e),a?.(y,{headers:bh(h.xhr.__sentry_xhr_v3__?.request_headers)}))})}var qL=300;function QT(e,t){let{url:n}=ne(e).data;if(!n||typeof n!="string")return;let r=()=>{setTimeout(o)};if(Mt(t)){let i=e.end.bind(e);e.end=s=>{let a=s??Ae(),l=!1,c=()=>{l||(l=!0,setTimeout(o),i(a),clearTimeout(u))};r=c;let u=setTimeout(c,qL)}}let o=cr("resource",({entries:i})=>{i.forEach(s=>{XT(s)&&s.name.endsWith(n)&&(e.setAttributes(al(s)),r())})})}function YL(e,t){let n=hn();if(n){let r,o;try{r=new URL(e,n),o=new URL(n).origin}catch{return!1}let i=r.origin===o;return t?Nt(r.toString(),t)||i&&Nt(r.pathname,t):i}else{let r=!!e.match(/^\/(?!\/)/);return t?Nt(e,t):r}}function KL(e,t,n,r,o,i){let s=e.xhr,a=s?.[ur];if(!s||s.__sentry_own_request__||!a)return;let{url:l,method:c}=a,u=Et()&&t(l);if(e.endTimestamp){let S=s.__sentry_xhr_span_id__;if(!S)return;let E=r[S];E&&(u&&a.status_code!==void 0&&(rs(E,a.status_code),E.end(),i?.(E,{headers:bh(dl(s)),error:e.error})),delete r[S]);return}let f=xh(l),p=f?zn(f):zn(l),h=Wt(Zc(l)),y=$(),T=!!Me()||!!y&&Mt(y),g=u&&T?wt({name:`${c} ${h}`,attributes:{url:Wt(l),type:"xhr","http.method":c,"http.url":f?Wt(f):void 0,"server.address":p?.host,[we]:"auto.http.browser",[qe]:"http.client",...p?.search&&{"http.query":p?.search},...p?.hash&&{"http.fragment":p?.hash}}}):new At;return u&&!T&&y?.recordDroppedEvent("no_parent_span","span"),s.__sentry_xhr_span_id__=g.spanContext().spanId,r[s.__sentry_xhr_span_id__]=g,n(l)&&JL(s,Et()&&T?g:void 0,o),y&&y.emit("beforeOutgoingRequestSpan",g,e),g}function JL(e,t,n){let{"sentry-trace":r,baggage:o,traceparent:i}=hs({span:t,propagateTraceparent:n});r&&XL(e,r,o,i)}function XL(e,t,n,r){let o=e.__sentry_xhr_v3__?.request_headers;if(!(o?.["sentry-trace"]||!e.setRequestHeader))try{if(e.setRequestHeader("sentry-trace",t),r&&!o?.traceparent&&e.setRequestHeader("traceparent",r),n){let i=o?.baggage;(!i||!JT(i))&&e.setRequestHeader("baggage",n)}}catch{}}var eI=new WeakMap,tI=new WeakMap,QL=9e4,ZL=["text/event-stream","application/x-ndjson","application/stream+json"],nI=()=>({name:"FetchStreamPerformance",setup(){fu(e=>{if(e.response){let t=eI.get(e.response);if(t&&e.endTimestamp){t.end(e.endTimestamp);let n=tI.get(e.response);n&&clearTimeout(n)}}}),Co(e=>{if(e.endTimestamp&&e.response){let t=e.response.headers?.get("content-type")||"";if(e.response.headers?.get("content-length")||!ZL.some(l=>t.startsWith(l)))return;let n=e.fetchData?.url||"",r=e.fetchData?.method||"GET",o=Ir(n),i=n.startsWith("data:")?Wt(n):o?us(o):n,s=wt({name:`${r} ${i}`,startTime:e.endTimestamp,attributes:{url:Wt(n),"http.method":r,type:"fetch",[qe]:"http.client.stream",[we]:"auto.http.browser.stream"}});eI.set(e.response,s);let a=setTimeout(()=>{s.isRecording()&&s.end()},QL);tI.set(e.response,a)}})}});function rI(){ee.document?ee.document.addEventListener("visibilitychange",()=>{let e=Me();if(!e)return;let t=be(e);if(ee.document.hidden&&t){let n="cancelled",{op:r,status:o}=ne(t);et&&C.log(`[Tracing] Transaction: ${n} -> since tab moved to the background, op: ${r}`),o||t.setStatus({code:2,message:n}),t.setAttribute("sentry.cancellation_reason","document.hidden"),t.end()}}):et&&C.warn("[Tracing] Could not set up background tab detection due to lack of global document")}var eO=3600,oI="sentry_previous_trace",tO="sentry.previous_trace";function iI(e,{linkPreviousTrace:t,consistentTraceSampling:n}){let r=t==="session-storage",o=r?oO():void 0;e.on("spanStart",s=>{if(be(s)!==s)return;let a=te().getPropagationContext();o=nO(o,s,a),r&&rO(o)});let i=!0;n&&e.on("beforeSampling",s=>{if(!o)return;let a=te(),l=a.getPropagationContext();if(i&&l.parentSpanId){i=!1;return}a.setPropagationContext({...l,dsc:{...l.dsc,sample_rate:String(o.sampleRate),sampled:String(Nh(o.spanContext))},sampleRand:o.sampleRand}),s.parentSampled=Nh(o.spanContext),s.parentSampleRate=o.sampleRate,s.spanAttributes={...s.spanAttributes,[ts]:o.sampleRate}})}function nO(e,t,n){let r=ne(t);function o(){try{let a=Number(r.data?.[$r]??n.dsc?.sample_rate);return Number.isNaN(a)?0:a}catch{return 0}}let i={spanContext:t.spanContext(),startTimestamp:r.start_timestamp,sampleRate:o(),sampleRand:n.sampleRand};if(!e)return i;let s=e.spanContext;return s.traceId===r.trace_id?e:(Date.now()/1e3-e.startTimestamp<=eO&&(et&&C.log(`Adding previous_trace \`${JSON.stringify(s)}\` link to span \`${JSON.stringify({op:r.op,...t.spanContext()})}\``),t.addLink({context:s,attributes:{[Uc]:"previous_trace"}}),t.setAttribute(tO,`${s.traceId}-${s.spanId}-${Nh(s)?1:0}`)),i)}function rO(e){try{ee.sessionStorage.setItem(oI,JSON.stringify(e))}catch(t){et&&C.warn("Could not store previous trace in sessionStorage",t)}}function oO(){try{let e=ee.sessionStorage?.getItem(oI);return JSON.parse(e)}catch{return}}function Nh(e){return e.traceFlags===1}var iO="BrowserTracing",sO=/Googlebot|Google-InspectionTool|Storebot-Google|Bingbot|Slurp|DuckDuckBot|Baiduspider|YandexBot|Facebot|facebookexternalhit|LinkedInBot|Twitterbot|Applebot/i;function uI(){let e=ee.navigator;return e?.userAgent?sO.test(e.userAgent):!1}var aO={...cs,instrumentNavigation:!0,instrumentPageLoad:!0,markBackgroundSpan:!0,enableLongTask:!0,enableLongAnimationFrame:!0,enableInp:!0,ignoreResourceSpans:[],ignorePerformanceApiSpans:[],detectRedirects:!0,linkPreviousTrace:"in-memory",consistentTraceSampling:!1,enableReportPageLoaded:!1,_experiments:{},...kh},Ah=((e={})=>{"enableElementTiming"in e&&kt(()=>{console.warn("[Sentry] `enableElementTiming` is deprecated and no longer has any effect. Use the standalone `elementTimingIntegration` instead.")});let t={name:void 0,source:void 0},n=ee.document,{enableInp:r,enableLongTask:o,enableLongAnimationFrame:i,_experiments:{enableInteractions:s,enableStandaloneClsSpans:a,enableStandaloneLcpSpans:l},beforeStartSpan:c,idleTimeout:u,finalTimeout:f,childSpanTimeout:p,markBackgroundSpan:h,traceFetch:y,traceXHR:_,trackFetchStreamPerformance:T,shouldCreateSpanForRequest:g,enableHTTPTimings:S,ignoreResourceSpans:E,ignorePerformanceApiSpans:R,instrumentPageLoad:M,instrumentNavigation:A,detectRedirects:I,linkPreviousTrace:N,consistentTraceSampling:U,enableReportPageLoaded:x,onRequestSpanStart:H,onRequestSpanEnd:j}={...aO,...e},he=uI(),X,Ze,fe;function de(D,ge,Q=!0){let ae=ge.op==="pageload",Re=ge.name,Te=c?c(ge):ge,St=Te.attributes||{};if(Re!==Te.name&&(St[vt]="custom",Te.attributes=St),!Q){let it=dn();wt({...Te,startTime:it}).end(it);return}t.name=Te.name,t.source=St[vt];let ot=Xc(Te,{idleTimeout:u,finalTimeout:f,childSpanTimeout:p,disableAutoFinish:ae,beforeSpanEnd:it=>{X?.();let In=Mt(D);Im(it,{recordClsOnPageloadSpan:!In&&!a,recordLcpOnPageloadSpan:!In&&!l,ignoreResourceSpans:E,ignorePerformanceApiSpans:R,spanStreamingEnabled:In}),lI(D,void 0);let Dt=te(),wn=Dt.getPropagationContext();Dt.setPropagationContext({...wn,traceId:ot.spanContext().traceId,sampled:mn(ot),dsc:ht(it)}),ae&&(fe=void 0)},trimIdleSpanEndTimestamp:!x});ae&&x&&(fe=ot),lI(D,ot);function bt(){n&&["interactive","complete"].includes(n.readyState)&&D.emit("idleSpanEnableAutoFinish",ot)}ae&&!x&&n&&(n.addEventListener("readystatechange",()=>{bt()}),bt())}return{name:iO,setup(D){if(he){et&&C.log("[Tracing] Skipping browserTracingIntegration setup for bot user agent.");return}Wc();let ge=Mt(D);if(X=_m({recordClsStandaloneSpans:ge?void 0:a||!1,recordLcpStandaloneSpans:ge?void 0:l||!1,client:D}),ge?(km(D),Nm(D),r&&Am()):r&&Rm(),i&&G.PerformanceObserver&&PerformanceObserver.supportedEntryTypes?.includes("long-animation-frame")?Em():o&&vm(),s&&Tm(),I&&n){let ae=()=>{Ze=Ae()};addEventListener("click",ae,{capture:!0}),addEventListener("keydown",ae,{capture:!0,passive:!0})}function Q(){let ae=bl(D);ae&&!ne(ae).timestamp&&(et&&C.log(`[Tracing] Finishing current active span with op: ${ne(ae).op}`),ae.setAttribute(zr,"cancelled"),ae.end())}D.on("startNavigationSpan",(ae,Re)=>{if($()!==D)return;if(Re?.isRedirect){et&&C.warn("[Tracing] Detected redirect, navigation span will not be the root span, but a child span."),de(D,{op:"navigation.redirect",...ae},!1);return}Ze=void 0,Q(),Xe().setPropagationContext({traceId:Zt(),sampleRand:Math.random(),propagationSpanId:Et()?void 0:zt()});let Te=te();Te.setPropagationContext({traceId:Zt(),sampleRand:Math.random(),propagationSpanId:Et()?void 0:zt()}),Te.setSDKProcessingMetadata({normalizedRequest:void 0}),de(D,{op:"navigation",...ae,parentSpan:null,forceTransaction:!0})}),D.on("startPageLoadSpan",(ae,Re={})=>{if($()!==D)return;Q();let Te=Re.sentryTrace||sI("sentry-trace")||aI("sentry-trace"),St=Re.baggage||sI("baggage")||aI("baggage"),ot=Ip(Te,St),bt=te();bt.setPropagationContext(ot),Et()||(bt.getPropagationContext().propagationSpanId=zt()),bt.setSDKProcessingMetadata({normalizedRequest:Ss()}),de(D,{op:"pageload",...ae})}),D.on("endPageloadSpan",()=>{x&&fe&&(fe.setAttribute(zr,"reportPageLoaded"),fe.end())})},afterAllSetup(D){if(he)return;let ge=hn();if(N!=="off"&&iI(D,{linkPreviousTrace:N,consistentTraceSampling:U}),ee.location){if(M){let Q=He();dI(D,{name:ee.location.pathname,startTime:Q?Q/1e3:void 0,attributes:{[vt]:"url",[we]:"auto.pageload.browser"}})}A&&Qr(({to:Q,from:ae})=>{if(ae===void 0&&ge?.indexOf(Q)!==-1){ge=void 0;return}ge=void 0;let Re=Ir(Q),Te=bl(D),St=Te&&I&&cO(Te,Ze);fI(D,{name:Re?.pathname||ee.location.pathname,attributes:{[vt]:"url",[we]:"auto.navigation.browser"}},{url:Q,isRedirect:St})})}h&&rI(),s&&lO(D,u,f,p,t),r&&xm(),ZT(D,{traceFetch:y,traceXHR:_,tracePropagationTargets:D.getOptions().tracePropagationTargets,shouldCreateSpanForRequest:g,enableHTTPTimings:S,onRequestSpanStart:H,onRequestSpanEnd:j}),T&&D.addIntegration(nI())}}});function dI(e,t,n){e.emit("startPageLoadSpan",t,n),te().setTransactionName(t.name);let r=bl(e);return r&&e.emit("afterStartPageLoadSpan",r),r}function fI(e,t,n){let{url:r,isRedirect:o}=n||{};e.emit("beforeStartNavigationSpan",t,{isRedirect:o}),e.emit("startNavigationSpan",t,{isRedirect:o});let i=te();return i.setTransactionName(t.name),r&&!o&&i.setSDKProcessingMetadata({normalizedRequest:{...Ss(),url:r}}),bl(e)}function sI(e){return ee.document?.querySelector(`meta[name=${e}]`)?.getAttribute("content")||void 0}function aI(e){return ee.performance?.getEntriesByType?.("navigation")[0]?.serverTiming?.find(r=>r.name===e)?.description}function lO(e,t,n,r,o){let i=ee.document,s,a=()=>{let l="ui.action.click",c=bl(e);if(c){let u=ne(c).op;if(["navigation","pageload"].includes(u)){et&&C.warn(`[Tracing] Did not create ${l} span because a pageload or navigation span is in progress.`);return}}if(s&&(s.setAttribute(zr,"interactionInterrupted"),s.end(),s=void 0),!o.name){et&&C.warn(`[Tracing] Did not create ${l} transaction because _latestRouteName is missing.`);return}s=Xc({name:o.name,op:l,attributes:{[vt]:o.source||"url"}},{idleTimeout:t,finalTimeout:n,childSpanTimeout:r})};i&&addEventListener("click",a,{capture:!0})}var pI="_sentry_idleSpan";function bl(e){return e[pI]}function lI(e,t){Ve(e,pI,t)}var cI=1.5;function cO(e,t){let n=ne(e),r=dn(),o=n.start_timestamp;return!(r-o>cI||t&&r-t<=cI)}var bI=Cn(eo(),1);function xI(e){return Fn(e)&&"nativeEvent"in e&&"preventDefault"in e&&"stopPropagation"in e}function Uh(e){let t={...e};nl(t,"react"),mi("react",{version:bI.version});let n=Um(t);return Zi(CO),n}function CO(e){return xI(e)?"[SyntheticEvent]":fl(e)}var kI=Cn(eo(),1);function RO(e){let t=e.match(/^([^.]+)/);return t!==null&&parseInt(t[0])>=17}function xO(e,t){let n=new WeakSet;function r(o,i){if(!n.has(o)){if(o.cause)return n.add(o),r(o.cause,i);o.cause=i}}r(e,t)}function NI(e,{componentStack:t},n){if(RO(kI.version)&&Un(e)&&t){let r=new Error(e.message);r.name=`React ErrorBoundary ${e.name}`,r.stack=t,xO(e,r)}return $n(r=>(r.setContext("react",{componentStack:t}),Gr(e,n)))}var Ci=Cn(eo(),1);var AI=typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__;var Fh={componentStack:null,error:null,eventId:null},Ds=class extends Ci.Component{constructor(t){super(t),this.state=Fh,this._openFallbackReportDialog=!0;let n=$();n&&t.showDialog&&(this._openFallbackReportDialog=!1,this._cleanupHook=n.on("afterSendEvent",r=>{!r.type&&this._lastEventId&&r.event_id===this._lastEventId&&Ou({...t.dialogOptions,eventId:this._lastEventId})}))}componentDidCatch(t,n){let{componentStack:r}=n,{beforeCapture:o,onError:i,showDialog:s,dialogOptions:a}=this.props;$n(l=>{o&&o(l,t,r);let c=this.props.handled!=null?this.props.handled:!!this.props.fallback,u=NI(t,n,{mechanism:{handled:c,type:"auto.function.react.error_boundary"}});i&&i(t,r,u),s&&(this._lastEventId=u,this._openFallbackReportDialog&&Ou({...a,eventId:u})),this.setState({error:t,componentStack:r,eventId:u})})}componentDidMount(){let{onMount:t}=this.props;t&&t()}componentWillUnmount(){let{error:t,componentStack:n,eventId:r}=this.state,{onUnmount:o}=this.props;o&&(this.state===Fh?o(null,null,null):o(t,n,r)),this._cleanupHook&&(this._cleanupHook(),this._cleanupHook=void 0)}resetErrorBoundary(){let{onReset:t}=this.props,{error:n,componentStack:r,eventId:o}=this.state;t&&t(n,r,o),this.setState(Fh)}render(){let{fallback:t,children:n}=this.props,r=this.state;if(r.componentStack===null)return typeof n=="function"?n():n;let o=typeof t=="function"?Ci.createElement(t,{error:r.error,componentStack:r.componentStack,resetError:()=>this.resetErrorBoundary(),eventId:r.eventId}):t;return Ci.isValidElement(o)?o:(t&&AI&&C.warn("fallback did not produce a valid ReactElement"),null)}};function Bh(e,t){if(e==null||e==="")return t;let n=typeof e=="number"?e:Number(e);return Number.isFinite(n)&&n>=0&&n<=1?n:t}var to=window.__vidfarmSentry,PI=to?.dsn?.trim()||"";if(PI){let e=to?.environment?.trim()||"development",t=e==="production"?.1:1,n=e==="production"?.1:1,r=["localhost",window.location.origin,`${window.location.origin}/api`],o=Array.from(new Set([...r,...to?.tracePropagationTargets??[]].filter(Boolean)));Uh({dsn:PI,environment:e,release:to?.release?.trim()||void 0,integrations:[Ah(),Rh({maskAllText:!0,blockAllMedia:!0})],tracesSampleRate:Bh(to?.tracesSampleRate,t),tracePropagationTargets:o,replaysSessionSampleRate:Bh(to?.replaysSessionSampleRate,n),replaysOnErrorSampleRate:Bh(to?.replaysOnErrorSampleRate,1),enableLogs:to?.enableLogs??!0,sendDefaultPii:to?.sendDefaultPii??!0})}var Gi=Cn(eo(),1),ZR=Cn(Mf(),1),ex=Cn(ZC(),1);var eR=e=>{let t,n=new Set,r=(c,u)=>{let f=typeof c=="function"?c(t):c;if(!Object.is(f,t)){let p=t;t=u??(typeof f!="object"||f===null)?f:Object.assign({},t,f),n.forEach(h=>h(t,p))}},o=()=>t,a={setState:r,getState:o,getInitialState:()=>l,subscribe:c=>(n.add(c),()=>n.delete(c))},l=t=e(r,o,a);return a},Pf=(e=>e?eR(e):eR);var Ec=Cn(eo(),1);var NU=e=>e;function tR(e,t=NU){let n=Ec.default.useSyncExternalStore(e.subscribe,Ec.default.useCallback(()=>t(e.getState()),[e,t]),Ec.default.useCallback(()=>t(e.getInitialState()),[e,t]));return Ec.default.useDebugValue(n),n}var AU="[vidfarm]";function MU(e){if(e!=="debug")return!0;if(typeof window>"u")return!1;try{return new URLSearchParams(window.location.search).has("debug")||window.localStorage?.getItem("VIDFARM_DEBUG")==="1"}catch{return!1}}function eS(e,t,n){let r={event:t,detail:n,timestamp:new Date().toISOString()};typeof window<"u"&&(window.__VIDFARM_DEBUG_LOGS__=window.__VIDFARM_DEBUG_LOGS__??[],window.__VIDFARM_DEBUG_LOGS__.push(r),window.__VIDFARM_DEBUG_LOGS__.length>1e3&&window.__VIDFARM_DEBUG_LOGS__.splice(0,window.__VIDFARM_DEBUG_LOGS__.length-1e3)),MU(e)&&console[e==="debug"?"log":e](AU,t,n??"")}function Or(e,t){eS("info",e,t)}function nR(e,t){eS("warn",e,t)}function po(e,t){eS("error",e,t)}function rR(){typeof window>"u"||window.__VIDFARM_DEBUG_HOOKS__||(window.__VIDFARM_DEBUG_HOOKS__=!0,Or("boot.hooks-installed",{href:window.location.href,readyState:document.readyState,userAgent:navigator.userAgent}),window.addEventListener("error",e=>{po("window.error",{message:e.message,filename:e.filename,lineno:e.lineno,colno:e.colno,error:e.error instanceof Error?e.error.stack:e.error})}),window.addEventListener("unhandledrejection",e=>{po("window.unhandledrejection",{reason:e.reason instanceof Error?e.reason.stack:e.reason})}))}var PU="vidfarm:flockposter-cache:v1",LU="public",Lf={channels:[],posts:[],channelsUpdatedAt:null,calendarUpdatedAt:null,calendarRangeStart:null,calendarRangeEnd:null};function sR(e){return`${PU}_${e?.trim()||LU}`}function nS(e){if(typeof window>"u")return Lf;try{let t=window.localStorage.getItem(sR(e));if(!t)return Lf;let n=JSON.parse(t);return!n||typeof n!="object"?Lf:{channels:Array.isArray(n.channels)?n.channels:[],posts:Array.isArray(n.posts)?n.posts:[],channelsUpdatedAt:typeof n.channelsUpdatedAt=="string"?n.channelsUpdatedAt:null,calendarUpdatedAt:typeof n.calendarUpdatedAt=="string"?n.calendarUpdatedAt:null,calendarRangeStart:typeof n.calendarRangeStart=="string"?n.calendarRangeStart:null,calendarRangeEnd:typeof n.calendarRangeEnd=="string"?n.calendarRangeEnd:null}}catch{return Lf}}function oR(e,t){if(!(typeof window>"u"))try{window.localStorage.setItem(sR(t),JSON.stringify(e))}catch{}}function aR(e){let t=nS(e);return Pf((n,r)=>({...t,setChannelsData:o=>{let i=r(),s={...i,channels:[...i.channels.filter(iR),...o.filter(a=>!iR(a))],channelsUpdatedAt:new Date().toISOString()};oR(s,e),n(s)},setCalendarData:o=>{let i=r(),s=OU([...i.channels,...o.channels]),a=o.replaceRange?DU(i.posts,o.posts,o.rangeStart,o.rangeEnd):tS([...i.posts,...o.posts]),l={...i,channels:s,posts:a,channelsUpdatedAt:new Date().toISOString(),calendarUpdatedAt:new Date().toISOString(),calendarRangeStart:UU(i.calendarRangeStart,o.rangeStart),calendarRangeEnd:FU(i.calendarRangeEnd,o.rangeEnd)};oR(l,e),n(l)}}))}function OU(e){return[...new Map(e.map(t=>[t.id,t])).values()]}function iR(e){return e.id.startsWith("email:")||e.platform?.toLowerCase()==="email"}function tS(e){return[...new Map(e.map(t=>[t.id,t])).values()]}function DU(e,t,n,r){let o=Date.parse(n),i=Date.parse(r);return Number.isNaN(o)||Number.isNaN(i)?tS([...e,...t]):tS([...e.filter(s=>{let a=Date.parse(s.scheduledAt);return Number.isNaN(a)||a<o||a>i}),...t])}function UU(e,t){return e?Date.parse(t)<Date.parse(e)?t:e:t}function FU(e,t){return e?Date.parse(t)>Date.parse(e)?t:e:t}function lR(e){return Pf(t=>({boot:e,hydratedAt:null,setHydratedAt:n=>t({hydratedAt:n})}))}var k=Cn(eo(),1),Wi=Cn(Mf(),1);var d=Cn(Tc(),1);function fR(){if(typeof window>"u")return null;try{let e=new URL(window.location.href).pathname.match(/^\/editor\/[^/]+\/fork\/([^/]+)\/?$/);if(!e)return null;let t=decodeURIComponent(e[1]);return t==="new"?null:t}catch{return null}}var Vf=1024*1024,DR=50*Vf,GU=2*Vf,VU=3*Vf,qU=Math.floor(3.5*Vf),YU=2048,UR="chat";function pa(e){let t=e.id||e.attachment_id||e.file_id||"",n=e.fileName||e.file_name,r=e.contentType||e.content_type,o=e.viewUrl||e.view_url||"";return!t||!n||!r||!o?null:{id:t,fileName:n,contentType:r,viewUrl:o,sizeBytes:typeof e.sizeBytes=="number"?e.sizeBytes:e.size_bytes,folderPath:e.folderPath??e.folder_path??""}}function jf(e){return e.contentType.startsWith("image/")}function uS(e){return e.contentType.startsWith("video/")}var KU=new Set(["apng","avif","gif","jpeg","jpg","png","svg","webp"]),JU=new Set(["m4v","mov","mp4","mpeg","mpg","ogv","webm"]),pR=1200,rS=24,oS=80,XU=/^data:([^;,]+)[^,]*,/i,mR=/authorization|api[-_]?key|secret|token|vidfarm-api-key/i,QU=48e3,iS=14,ZU=12e3,eF=1200,tF=30;function Bf(e){if(e==null||e==="")return"";if(typeof e=="string")try{return JSON.stringify(JSON.parse(e),null,2)}catch{return e}return JSON.stringify(e,null,2)}function Hf(e){let t=XU.exec(e);return t?`[${t[1]} data URL omitted, ${e.length.toLocaleString()} chars]`:e.length>pR?`${e.slice(0,pR)}\u2026 [truncated ${e.length.toLocaleString()} chars]`:e}function ji(e,t=0){if(e==null)return e;if(typeof e=="string")return Hf(e);if(typeof e=="number"||typeof e=="boolean")return e;if(typeof e=="bigint")return e.toString();if(!(typeof e=="function"||typeof e=="symbol")){if(t>=8)return"[nested payload omitted]";if(Array.isArray(e)){let n=e.slice(0,rS).map(r=>ji(r,t+1));return e.length>rS&&n.push(`[${e.length-rS} more items omitted]`),n}if(typeof e=="object"){let n={},r=Object.entries(e);for(let[o,i]of r.slice(0,oS)){let s=ji(i,t+1);s!==void 0&&(n[o]=s)}return r.length>oS&&(n.__omitted_keys=r.length-oS),n}return String(e)}}function FR(e){return ji(e)}function Cc(e){return{...e,request:{...e.request,headers:Object.fromEntries(Object.entries(e.request.headers).map(([t,n])=>[t,mR.test(t)?"[redacted]":Hf(n)])),body:ji(e.request.body)},result:{...e.result,headers:Object.fromEntries(Object.entries(e.result.headers).map(([t,n])=>[t,mR.test(t)?"[redacted]":Hf(n)])),body:ji(e.result.body),error:e.result.error?Hf(e.result.error):e.result.error}}}function nF(){let e=new Date,t=null,n=null;try{t=new Intl.DateTimeFormat(void 0,{dateStyle:"full",timeStyle:"long"}).format(e)}catch{t=e.toString()}try{n=Intl.DateTimeFormat().resolvedOptions().timeZone||null}catch{n=null}return{currentDateTime:e.toISOString(),localDateTime:t,timeZone:n}}function BR(e){return e.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function sS(e){let t=BR(e);return t=t.replace(/`([^`]+)`/g,"<code>$1</code>"),t=t.replace(/\*\*([^*]+)\*\*/g,"<strong>$1</strong>"),t=t.replace(/(^|[^\*])\*([^*]+)\*(?!\*)/g,"$1<em>$2</em>"),t=t.replace(/\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g,'<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>'),t=t.replace(/(^|[\s(])(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/g,'$1<a href="$2" target="_blank" rel="noopener noreferrer">$2</a>'),t}function HR(e){let t=e.replace(/\r\n/g,`
|
|
32
32
|
`).trim();return t?t.split(/\n{2,}/).map(r=>{let o=r.trim();if(!o)return"";if(o.startsWith("```")&&o.endsWith("```")){let l=o.replace(/^```[^\n]*\n?/,"").replace(/\n?```$/,"");return`<pre><code>${BR(l)}</code></pre>`}let i=o.split(`
|
|
33
|
-
`);return i.every(l=>/^[-*]\s+/.test(l.trim()))?`<ul>${i.map(c=>c.trim().replace(/^[-*]\s+/,"")).map(c=>`<li>${sS(c)}</li>`).join("")}</ul>`:i.every(l=>/^\d+\.\s+/.test(l.trim()))?`<ol>${i.map(c=>c.trim().replace(/^\d+\.\s+/,"")).map(c=>`<li>${sS(c)}</li>`).join("")}</ol>`:`<p>${i.map(l=>sS(l.trim())).join("<br />")}</p>`}).filter(Boolean).join(""):""}function rF(e){return e.replace(/[_-]+/g," ").replace(/\s+/g," ").trim().replace(/\b\w/g,t=>t.toUpperCase())}function oF(e){return/^item \d+$/i.test(e.trim())||/^output$/i.test(e.trim())}function iF(e){try{let n=new URL(e).searchParams.get("key");return n?.trim()?n.trim().replace(/^\/+/,""):null}catch{return null}}function Wf(e){try{return decodeURIComponent(e)}catch{return e}}function mS(e){let t=iF(e);if(t){let n=Wf(t.split("/").filter(Boolean).pop()||"");if(n)return n}try{let n=new URL(e).pathname;return Wf(n.split("/").filter(Boolean).pop()||"")}catch{return""}}function $R(e){return mS(e)||"Output"}function zR(e,t){let n=mS(e);return n||t.trim().replace(/[\\/:*?"<>|]+/g,"-")||"download"}function sF(e){let n=mS(e).split(".").pop()?.trim().toLowerCase()||"";return KU.has(n)?"image":JU.has(n)?"video":null}function aF(e){let t=new Set,n=/\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g,r=/(^|[\s(])(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/gm,o=null;for(;(o=n.exec(e))!==null;)t.add(o[2]);for(;(o=r.exec(e))!==null;)t.add(o[2]);return[...t]}function lF(e,t=[]){let n=new Set(t),r=new Set,o=[];for(let i of aF(e)){if(n.has(i)||r.has(i))continue;let s=sF(i);s&&(r.add(i),o.push({kind:s,url:i,label:$R(i)}))}return o}function dS(e,t,n=new Set,r=[]){if(!(t.length>=12||e==null)){if(typeof e=="string"){let o=e.trim();if(/^https?:\/\//i.test(o)&&!n.has(o)){n.add(o);let i=r.length?r[r.length-1]||"Output":"",s=rF(i),a=$R(o);t.push({label:a!=="Output"?a:s&&!oF(i)?s:a,url:o})}return}if(Array.isArray(e)){for(let[o,i]of e.entries())if(dS(i,t,n,[...r,`item ${o+1}`]),t.length>=12)return;return}if(typeof e=="object"){for(let[o,i]of Object.entries(e))if(dS(i,t,n,[...r,o]),t.length>=12)return}}}function hR(e){return[`Started
|
|
33
|
+
`);return i.every(l=>/^[-*]\s+/.test(l.trim()))?`<ul>${i.map(c=>c.trim().replace(/^[-*]\s+/,"")).map(c=>`<li>${sS(c)}</li>`).join("")}</ul>`:i.every(l=>/^\d+\.\s+/.test(l.trim()))?`<ol>${i.map(c=>c.trim().replace(/^\d+\.\s+/,"")).map(c=>`<li>${sS(c)}</li>`).join("")}</ol>`:`<p>${i.map(l=>sS(l.trim())).join("<br />")}</p>`}).filter(Boolean).join(""):""}function rF(e){return e.replace(/[_-]+/g," ").replace(/\s+/g," ").trim().replace(/\b\w/g,t=>t.toUpperCase())}function oF(e){return/^item \d+$/i.test(e.trim())||/^output$/i.test(e.trim())}function iF(e){try{let n=new URL(e).searchParams.get("key");return n?.trim()?n.trim().replace(/^\/+/,""):null}catch{return null}}function Wf(e){try{return decodeURIComponent(e)}catch{return e}}function mS(e){let t=iF(e);if(t){let n=Wf(t.split("/").filter(Boolean).pop()||"");if(n)return n}try{let n=new URL(e).pathname;return Wf(n.split("/").filter(Boolean).pop()||"")}catch{return""}}function $R(e){return mS(e)||"Output"}function zR(e,t){let n=mS(e);return n||t.trim().replace(/[\\/:*?"<>|]+/g,"-")||"download"}function sF(e){let n=mS(e).split(".").pop()?.trim().toLowerCase()||"";return KU.has(n)?"image":JU.has(n)?"video":null}function aF(e){let t=new Set,n=/\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g,r=/(^|[\s(])(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/gm,o=null;for(;(o=n.exec(e))!==null;)t.add(o[2]);for(;(o=r.exec(e))!==null;)t.add(o[2]);return[...t]}function lF(e,t=[]){let n=new Set(t),r=new Set,o=[];for(let i of aF(e)){if(n.has(i)||r.has(i))continue;let s=sF(i);s&&(r.add(i),o.push({kind:s,url:i,label:$R(i)}))}return o}function dS(e,t,n=new Set,r=[]){if(!(t.length>=12||e==null)){if(typeof e=="string"){let o=e.trim();if(/^https?:\/\//i.test(o)&&!n.has(o)){n.add(o);let i=r.length?r[r.length-1]||"Output":"",s=rF(i),a=$R(o);t.push({label:a!=="Output"?a:s&&!oF(i)?s:a,url:o})}return}if(Array.isArray(e)){for(let[o,i]of e.entries())if(dS(i,t,n,[...r,`item ${o+1}`]),t.length>=12)return;return}if(typeof e=="object"){for(let[o,i]of Object.entries(e))if(dS(i,t,n,[...r,o]),t.length>=12)return}}}function hR(e){return[`Started job \`${e.job_id}\`${e.tracer?` with tracer \`${e.tracer}\``:""}.`,"If it takes a while, ask for an update later and I can check it for you."].join(`
|
|
34
34
|
|
|
35
35
|
`)}function hS(e){return typeof e=="string"&&e.startsWith("primitive:brainstorm_")}function gS(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!n||typeof n!="object")continue;let r=n,o={artifact_id:typeof r.artifact_id=="string"?r.artifact_id:void 0,kind:typeof r.kind=="string"?r.kind:void 0,storage_key:typeof r.storage_key=="string"?r.storage_key:void 0,public_url:typeof r.public_url=="string"?r.public_url:void 0,metadata:r.metadata&&typeof r.metadata=="object"?r.metadata:null,created_at:typeof r.created_at=="string"?r.created_at:void 0};(o.public_url||o.storage_key)&&t.push(o)}return t}function jR(e){return e?Wf(e.split("/").filter(Boolean).pop()||"result.json"):"JSON result"}function cF(e){return Wf(e?.split("/").filter(Boolean).pop()||"")}function uF(e){switch(e){case"primitive:brainstorm_hooks":return"Hooks JSON";case"primitive:brainstorm_angles":return"Angles JSON";case"primitive:brainstorm_awareness_stages":return"Awareness JSON";case"primitive:brainstorm_coldstart":return"Coldstart JSON";default:return"Brainstorm JSON"}}function WR(e){if(e.status!=="succeeded"||!hS(e.primitive_id))return[];let t=[];for(let[n,r]of gS(e.artifacts).entries()){let o=r.public_url?.trim(),i=r.storage_key?.trim();if(!(r.kind==="json"||!!(o&&/\.json(?:[?#]|$)/i.test(o))||!!(i&&/\.json$/i.test(i)))||!o)continue;let a=jR(r.storage_key),l=uF(e.primitive_id);t.push({key:r.artifact_id||`${e.job_id}:${o}:${n}`,url:o,label:a==="result.json"?l:`${l} \u2022 ${a}`,primitiveId:e.primitive_id,primitiveType:e.primitive_type,jobId:e.job_id})}return t}function dF(e){return e==="primitive:brainstorm_awareness_stages"?"Awareness response":"Brainstorm response"}function GR(e){if(e.status!=="succeeded"||!hS(e.primitive_id))return[];let t=[];for(let[n,r]of gS(e.artifacts).entries()){let o=r.public_url?.trim(),i=r.storage_key?.trim(),s=cF(i),a=/^prompt\./i.test(s),l=r.kind==="text"?!!(o&&/\.md(?:[?#]|$)/i.test(o)||i&&/\.md$/i.test(i)):!!(o&&/\.md(?:[?#]|$)/i.test(o)||i&&/\.md$/i.test(i)),c=!!(o&&/\.txt(?:[?#]|$)/i.test(o)||i&&/\.txt$/i.test(i));if(!o||a||!l&&!c)continue;let u=dF(e.primitive_id);t.push({key:r.artifact_id||`${e.job_id}:${o}:${n}`,url:o,label:s==="response.md"||s==="response.txt"?u:jR(i),jobId:e.job_id,format:l?"markdown":"text"})}return t}function Df(e){if(e.status==="succeeded"){let t=[];dS(e.result,t);let n=[`Render \`${e.job_id}\` succeeded.`];return hS(e.primitive_id)&&(WR(e).length||GR(e).length)&&(n.push(""),n.push("Open the result below. It contains the brainstorm output you can review, copy, and reuse.")),t.length&&(n.push(""),n.push("Outputs:"),n.push(...t.map(({url:r,label:o})=>`- [${o}](${r})`))),n.join(`
|
|
36
36
|
`)}return e.status==="failed"?`Render \`${e.job_id}\` failed.${e.error?.message?` ${e.error.message}`:""}`:e.status==="cancelled"?`Render \`${e.job_id}\` was cancelled.`:`Render \`${e.job_id}\` is ${e.status}.`}function Ic(e,t){let n=e.trim(),r=t.trim();return!r||n.includes(r)?e:n?`${n}
|
|
@@ -42,7 +42,7 @@ ${r}`:r}var fF=48;function pF(e){return e.scrollHeight-e.scrollTop-e.clientHeigh
|
|
|
42
42
|
`):null}function kF(e){let t=e.length-1;return e.map((n,r)=>{let o=bF(n.attachments);return{role:n.role,content:[...n.text?[{type:"text",text:n.text}]:[],...o?[{type:"text",text:o}]:[],...n.attachments.map(i=>({type:"file",data:r===t&&i.transportData||i.viewUrl,mediaType:i.contentType}))]}})}function NF(){let t=window.__vidfarmFlockPosterCache?.readSnapshot?.();if(!t)return{};let n=Array.isArray(t?.channels)?t.channels.map(r=>r&&typeof r=="object"?r:null).filter(r=>typeof r?.id=="string"&&!!r.id.trim()).map(r=>({id:String(r?.id||""),name:typeof r?.name=="string"?r.name:null,title:typeof r?.title=="string"?r.title:null,handle:typeof r?.handle=="string"?r.handle:null,platform:typeof r?.platform=="string"?r.platform:null,status:typeof r?.status=="string"?r.status:null})):[];return n.length||t?.channelsUpdatedAt?{scheduleChannels:n,scheduleChannelsUpdatedAt:t?.channelsUpdatedAt??null}:{}}function AF(){let e=window.__vidfarmLibrarySelection?.readSelectedPosts?.();return{selectedPosts:Array.isArray(e?.posts)?e.posts.map(n=>n&&typeof n=="object"?n:null).filter(n=>typeof n?.post_id=="string"&&!!n.post_id.trim()).map(n=>({post_id:String(n?.post_id||""),title:typeof n?.title=="string"?n.title:null,caption:typeof n?.caption=="string"?n.caption:null,tracer:typeof n?.tracer=="string"?n.tracer:null,status:typeof n?.status=="string"?n.status:null,share_url:typeof n?.share_url=="string"?n.share_url:null,media:Array.isArray(n?.media)?n.media.slice(0,8).map(r=>r&&typeof r=="object"?r:null).filter(Boolean).map(r=>({url:typeof r?.url=="string"?r.url:null,kind:typeof r?.kind=="string"?r.kind:null,role:typeof r?.role=="string"?r.role:null,content_type:typeof r?.content_type=="string"?r.content_type:null})):[]})):[],selectedPostsUpdatedAt:e?.updatedAt??null}}async function MF(e,t){if(!e.body)throw new Error("Chat response did not include a body.");let n=e.body.getReader(),r=new TextDecoder,o="";for(;;){let{done:i,value:s}=await n.read();if(i)break;o+=r.decode(s,{stream:!0});let a=o.split(`
|
|
43
43
|
|
|
44
44
|
`);o=a.pop()??"";for(let l of a){let c=l.split(`
|
|
45
|
-
`).map(h=>h.trim()).find(h=>h.startsWith("data:"));if(!c)continue;let u=c.slice(5).trim();if(u==="[DONE]")continue;let f;try{f=JSON.parse(u)}catch{continue}if(!f||typeof f!="object")continue;let p=f;if(p.type==="text-delta"&&typeof p.delta=="string")t.onDelta(p.delta);else if(p.type==="status"){let h=typeof p.status=="string"?p.status:typeof p.message=="string"?p.message:null;h&&t.onStatus&&t.onStatus(h)}else p.type==="tool-call"&&typeof p.toolCallId=="string"&&typeof p.toolName=="string"&&t.onToolCall?t.onToolCall({toolCallId:p.toolCallId,toolName:p.toolName,args:p.args&&typeof p.args=="object"?p.args:void 0}):p.type==="tool-result"&&typeof p.toolCallId=="string"&&typeof p.toolName=="string"&&t.onToolResult?t.onToolResult({toolCallId:p.toolCallId,toolName:p.toolName,result:p.result}):p.type==="error"&&t.onError&&t.onError?.(typeof p.errorText=="string"?p.errorText:typeof p.error?.message=="string"?p.error.message:"Unable to read assistant response.")}}}function PF(e){return{threads:`vidfarm-editor-chat-threads:${e}`,activeThread:`vidfarm-editor-chat-active-thread:${e}`}}function LF(){if(typeof window>"u")return null;try{return window.sessionStorage}catch{try{return window.localStorage}catch{return null}}}function IR(){return`thread-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function $f(e){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`${e}-${crypto.randomUUID()}`:`${e}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function tr(e){let t=new Set,n=[];for(let r of e){let o=r.trim();!o||t.has(o)||(t.add(o),n.push(o))}return n}function lS(...e){return tr(e.flat())}function OF(e){let t=e.trim();return!t||t.startsWith("archived_")?t:`archived_${t}`}function fS(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID().replace(/-/g,"").slice(-8):Math.random().toString(16).slice(2,10).padEnd(8,"0").slice(0,8)}function DF(e){return(e.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"tracer").slice(0,28)}function UF(e,t){let n=DF(e),r="";do r=`${n}-${fS()}`;while(t.includes(r));return r}function FF(e,t){let n=e.trim();if(!n)return"";if(/-[a-z0-9]{8}$/i.test(n))return n;let r=`${n}-${fS()}`;for(;t.includes(r);)r=`${n}-${fS()}`;return r}function zf(){let e=new URLSearchParams(window.location.search),t=[...e.getAll("tracers"),...e.getAll("tracer")],n=[];for(let r of t){let o=r.trim();if(!o)continue;let i=o.startsWith("[")&&o.endsWith("]")?o.slice(1,-1):o;n.push(...i.split(",").map(s=>s.trim().replace(/^["']|["']$/g,"")))}return tr(n)}function wR(){let e=new URLSearchParams(window.location.search);return(e.get("thread_id")||e.get("threadId")||e.get("chat_id")||e.get("chatId")||"").trim()}function Uf(e){let t=e.trim().replace(/\s+/g," ");return t?t.length>42?`${t.slice(0,42).trimEnd()}\u2026`:t:"New chat"}function CR(e,t){return e.map(n=>({id:n.id,templateId:n.templateId,title:n.title,createdAt:n.createdAt,updatedAt:n.updatedAt,lastMessageAt:n.lastMessageAt??null,messageCount:Math.max(n.messageCount??0,n.messages.length),tracers:n.tracers,hiddenFromView:n.hiddenFromView,messages:(n.id===t?n.messages.slice(-tF):[]).map(r=>({id:r.id,role:r.role,text:r.text,attachments:r.attachments.map(o=>({id:o.id,fileName:o.fileName,contentType:o.contentType,viewUrl:o.viewUrl})),toolExchanges:r.toolExchanges?.map(o=>({...o,args:ji(o.args),result:FR(o.result)})),httpExchanges:r.httpExchanges?.map(Cc)}))}))}function BF(e,t){if(!e)return[];try{let n=JSON.parse(e);return Array.isArray(n)?n.filter(r=>r&&typeof r.id=="string").map(r=>({id:r.id,templateId:typeof r.templateId=="string"&&r.templateId.trim()?r.templateId:t,title:typeof r.title=="string"&&r.title.trim()?r.title:"New chat",createdAt:typeof r.createdAt=="string"?r.createdAt:new Date().toISOString(),updatedAt:typeof r.updatedAt=="string"?r.updatedAt:new Date().toISOString(),lastMessageAt:typeof r.lastMessageAt=="string"?r.lastMessageAt:null,messageCount:Math.max(typeof r.messageCount=="number"?r.messageCount:0,Array.isArray(r.messages)?r.messages.length:0),tracers:tr(Array.isArray(r.tracers)?r.tracers.filter(o=>typeof o=="string"):[]),hiddenFromView:r.hiddenFromView===!0,messages:Array.isArray(r.messages)?r.messages.map(o=>({id:o.id,role:o.role,text:o.text,attachments:Array.isArray(o.attachments)?o.attachments:[],toolExchanges:Array.isArray(o.toolExchanges)?o.toolExchanges:[],httpExchanges:Array.isArray(o.httpExchanges)?o.httpExchanges:[]})):[]})):[]}catch{return[]}}function RR(e,t){return!e||typeof e.id!="string"?null:{id:e.id,templateId:typeof e.templateId=="string"&&e.templateId.trim()?e.templateId:t,title:typeof e.title=="string"&&e.title.trim()?e.title:"New chat",createdAt:typeof e.createdAt=="string"?e.createdAt:new Date().toISOString(),updatedAt:typeof e.updatedAt=="string"?e.updatedAt:new Date().toISOString(),lastMessageAt:typeof e.lastMessageAt=="string"?e.lastMessageAt:null,messageCount:Math.max(typeof e.messageCount=="number"?e.messageCount:0,Array.isArray(e.messages)?e.messages.length:0),tracers:tr(Array.isArray(e.tracers)?e.tracers.filter(n=>typeof n=="string"):[]),hiddenFromView:e.hiddenFromView===!0,messages:Array.isArray(e.messages)?e.messages.map(n=>({id:n.id,role:n.role,text:n.text,attachments:Array.isArray(n.attachments)?n.attachments:[],toolExchanges:Array.isArray(n.toolExchanges)?n.toolExchanges:[],httpExchanges:Array.isArray(n.httpExchanges)?n.httpExchanges:[]})):[]}}function xR(e,t){let n=new Map;for(let r of t){let o=e.find(i=>i.id===r.id);n.set(r.id,{...r,lastMessageAt:r.lastMessageAt??o?.lastMessageAt??null,messageCount:Math.max(r.messageCount??0,o?.messageCount??0,r.messages.length,o?.messages.length??0),messages:r.messages.length?r.messages:o?.messages??[]})}for(let r of e)n.has(r.id)||n.set(r.id,r);return[...n.values()].sort((r,o)=>Date.parse(o.updatedAt)-Date.parse(r.updatedAt))}function HF(e){return[...e].sort((t,n)=>Date.parse(n.updatedAt)-Date.parse(t.updatedAt))}function wc(e,t){return t.length?e.tracers.some(n=>t.some(r=>$F(n,r))):!0}function $F(e,t){let n=e.trim(),r=t.trim();return!n||!r?!1:n===r?!0:n.startsWith(`${r}-`)&&/-[a-z0-9]{8}$/i.test(n)}function zF(e){return(0,d.jsxs)("div",{className:"vf-editor-chat-attachment",children:[(0,d.jsx)("span",{className:"vf-editor-chat-attachment-name",children:e.attachment.fileName}),e.onRemove?(0,d.jsx)("button",{type:"button",className:"vf-editor-chat-attachment-remove","aria-label":"Remove attachment",onClick:e.onRemove,children:"\xD7"}):null]})}function yS(){return(0,d.jsxs)("svg",{viewBox:"0 0 20 20",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",focusable:"false",children:[(0,d.jsx)("path",{d:"M10 3v9"}),(0,d.jsx)("path",{d:"m6.5 8.5 3.5 3.5 3.5-3.5"}),(0,d.jsx)("path",{d:"M4 16h12"})]})}function jF(){return(0,d.jsxs)("svg",{viewBox:"0 0 20 20",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",focusable:"false",children:[(0,d.jsx)("path",{d:"M4.2 15.8c1.6.5 3.1-.1 3.7-1.7.6-1.4 1.8-2.1 3.5-2.1"}),(0,d.jsx)("path",{d:"m10.7 11.6 5.2-5.2a1.9 1.9 0 0 0-2.7-2.7L8 8.9"}),(0,d.jsx)("path",{d:"m7.9 9 3.1 3.1"}),(0,d.jsx)("path",{d:"M3.5 16.5c1.4.5 3.6.5 4.9-.8"})]})}function SS(){return(0,d.jsxs)("svg",{viewBox:"0 0 20 20",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",focusable:"false",children:[(0,d.jsx)("path",{d:"M8.4 11.6a3.2 3.2 0 0 0 4.5 0l2.2-2.2a3.2 3.2 0 0 0-4.5-4.5L9.4 6.1"}),(0,d.jsx)("path",{d:"M11.6 8.4a3.2 3.2 0 0 0-4.5 0L4.9 10.6a3.2 3.2 0 0 0 4.5 4.5l1.2-1.2"})]})}function _S(){return(0,d.jsxs)("svg",{viewBox:"0 0 20 20",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",focusable:"false",children:[(0,d.jsx)("rect",{x:"7",y:"7",width:"9",height:"9",rx:"2"}),(0,d.jsx)("path",{d:"M5 12H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h6a2 2 0 0 1 2 2v1"})]})}function Ff(e){return(0,d.jsx)("svg",{viewBox:"0 0 20 20",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",focusable:"false",style:{transform:e.open?"rotate(90deg)":"rotate(0deg)"},children:(0,d.jsx)("path",{d:"m7 4 6 6-6 6"})})}function KR(e){let t=e.label.trim().replace(/[\\/:*?"<>|]+/g,"-");if(t)return t;try{return new URL(e.url,window.location.href).pathname.split("/").filter(Boolean).pop()||"media"}catch{return"media"}}function bR(e,t=!1){if(typeof window>"u"||e.kind!=="image"||!e.url)return"";let n=new URL("/inpaint",window.location.origin),r=window.__vidfarmEditorTracers,i=(r?.get()??zf())[0]||(t?r?.add()??"":"");return i&&n.searchParams.set("tracer",i),n.searchParams.set("source_image_url",e.url),n.searchParams.set("source_image_name",e.label||KR(e)),n.toString()}function WF(e){let[t,n]=(0,k.useState)(!1),[r,o]=(0,k.useState)(""),{onClose:i}=e,s=e.gallery?.length?e.gallery:[e.preview],a=Math.max(0,s.findIndex(T=>T.url===e.preview.url)),[l,c]=(0,k.useState)(a),u=s[l]||e.preview,f=s.length>1,p=u.kind==="image",h=p&&bR(u,!1)||"/inpaint";(0,k.useEffect)(()=>{n(!0)},[]),(0,k.useEffect)(()=>{o("")},[u.url]);let y=async()=>{try{if(navigator.clipboard?.writeText)await navigator.clipboard.writeText(u.url);else{let T=document.createElement("textarea");T.value=u.url,T.style.position="fixed",T.style.opacity="0",document.body.appendChild(T),T.focus(),T.select(),document.execCommand("copy"),document.body.removeChild(T)}o("done")}catch{o("error")}window.setTimeout(()=>o(""),1600)},_=T=>{let g=bR(u,!0);if(!g){T.preventDefault();return}T.preventDefault(),window.open(g,"_blank","noopener,noreferrer")};return(0,k.useEffect)(()=>{let T=g=>{if(g.key==="Escape"){i();return}f&&(g.key==="ArrowLeft"?(g.preventDefault(),c(S=>(S-1+s.length)%s.length)):g.key==="ArrowRight"&&(g.preventDefault(),c(S=>(S+1)%s.length)))};return window.addEventListener("keydown",T),()=>window.removeEventListener("keydown",T)},[f,s.length,i]),t?(0,Wi.createPortal)((0,d.jsx)("div",{className:"vf-editor-chat-media-modal-backdrop",onClick:e.onClose,children:(0,d.jsxs)("div",{className:"vf-editor-chat-media-modal",onClick:T=>T.stopPropagation(),children:[(0,d.jsxs)("div",{className:"vf-editor-chat-media-modal-header",children:[(0,d.jsx)("a",{className:"vf-editor-chat-media-modal-link",href:u.url,target:"_blank",rel:"noopener noreferrer",children:f?`${u.label} (${l+1} of ${s.length})`:u.label}),(0,d.jsxs)("div",{className:"vf-editor-chat-media-modal-actions",children:[f?(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("button",{type:"button",className:"vf-editor-chat-media-modal-control",onClick:()=>c(T=>(T-1+s.length)%s.length),"aria-label":"Previous image",title:"Previous image",children:"\u2039"}),(0,d.jsx)("button",{type:"button",className:"vf-editor-chat-media-modal-control",onClick:()=>c(T=>(T+1)%s.length),"aria-label":"Next image",title:"Next image",children:"\u203A"})]}):null,p?(0,d.jsx)("a",{className:"vf-editor-chat-media-modal-control",href:h,target:"_blank",rel:"noopener noreferrer",onClick:_,"aria-label":"Open image editor",title:"Image edit",children:(0,d.jsx)(jF,{})}):null,(0,d.jsx)("a",{className:"vf-editor-chat-media-modal-control",href:u.url,download:KR(u),"aria-label":"Download media",title:"Download",children:(0,d.jsx)(yS,{})}),(0,d.jsx)("button",{type:"button",className:"vf-editor-chat-media-modal-control","data-state":r,onClick:()=>{y()},"aria-label":r==="done"?"Media URL copied":r==="error"?"Unable to copy media URL":"Copy media URL",title:r==="done"?"Copied":r==="error"?"Copy failed":"Copy link",children:(0,d.jsx)(SS,{})}),(0,d.jsx)("button",{type:"button",className:"vf-editor-chat-media-modal-control",onClick:e.onClose,"aria-label":"Close media preview",title:"Close",children:"\xD7"})]})]}),(0,d.jsx)("div",{className:"vf-editor-chat-media-modal-body",children:u.kind==="image"?(0,d.jsx)("img",{src:u.url,alt:u.label,className:"vf-editor-chat-media-modal-image"}):(0,d.jsx)("video",{src:u.url,className:"vf-editor-chat-media-modal-video",controls:!0,autoPlay:!0,playsInline:!0})})]})}),document.body):null}function GF(e){let[t,n]=(0,k.useState)(!1);return(0,d.jsx)("button",{type:"button",className:"vf-editor-chat-message-thumb-button is-image",onClick:()=>e.onOpenModal(e.preview,e.previews),"aria-label":`Preview ${e.preview.label}`,title:e.preview.label,"data-error":t?"true":"false",children:t?(0,d.jsx)("span",{className:"vf-editor-chat-message-thumb-fallback",children:"Preview unavailable"}):(0,d.jsx)("img",{src:e.preview.url,alt:e.preview.label,className:"vf-editor-chat-message-attachment-thumb",loading:"lazy",onError:()=>n(!0)})})}function kR(e){return(0,d.jsx)("div",{className:"vf-editor-chat-message-attachment-row",children:(0,d.jsxs)("button",{type:"button",className:"vf-editor-chat-message-thumb-button",onClick:()=>e.onOpenModal(e.preview),"aria-label":`Preview ${e.preview.label}`,children:[(0,d.jsx)("video",{src:e.preview.url,className:"vf-editor-chat-message-attachment-thumb vf-editor-chat-message-video-thumb",preload:"metadata",muted:!0,playsInline:!0}),(0,d.jsx)("span",{className:"vf-editor-chat-message-video-play","aria-hidden":"true"})]})})}function NR(e){return e.previews.length?(0,d.jsx)("div",{className:"vf-editor-chat-message-image-rail","aria-label":"Image previews",children:e.previews.map(t=>(0,d.jsx)(GF,{preview:t,previews:e.previews,onOpenModal:e.onOpenModal},t.url))}):null}function VF(e){return(0,d.jsxs)("div",{className:"vf-editor-chat-composer-attachment-item",children:[jf(e.attachment)?(0,d.jsx)("img",{src:e.attachment.viewUrl,alt:e.attachment.fileName,className:"vf-editor-chat-composer-attachment-thumb"}):(0,d.jsx)("div",{className:"vf-editor-chat-composer-attachment-file","aria-hidden":"true",children:e.attachment.fileName.slice(0,1).toUpperCase()}),(0,d.jsx)("div",{className:"vf-editor-chat-composer-attachment-meta",children:(0,d.jsx)("span",{className:"vf-editor-chat-composer-attachment-name",children:e.attachment.fileName})}),(0,d.jsx)("button",{type:"button",className:"vf-editor-chat-composer-attachment-remove","aria-label":`Remove ${e.attachment.fileName}`,onClick:e.onRemove,children:"\xD7"})]})}function qF(e){let[t,n]=(0,k.useState)(!1),[r,o]=(0,k.useState)(!1),i=Bf(e.exchange.request.body),s=Bf(e.exchange.result.body),a=e.exchange.request.url,l=a.length>52?`${a.slice(0,52).trimEnd()}...`:a,c=e.exchange.result.status>=400||!!e.exchange.result.error,u=e.exchange.result.status>=200&&e.exchange.result.status<300;return(0,k.useEffect)(()=>{o(!0)},[]),(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("div",{className:"vf-editor-chat-http-card",children:(0,d.jsxs)("button",{type:"button",className:"vf-editor-chat-http-card-header",onClick:()=>n(!0),"aria-label":`Open HTTP details for ${e.exchange.request.method} ${a}`,children:[(0,d.jsx)("span",{className:"vf-editor-chat-http-pill",children:e.exchange.request.method}),(0,d.jsx)("span",{className:"vf-editor-chat-http-url",title:a,children:l}),(0,d.jsxs)("span",{className:"vf-editor-chat-http-status","data-error":c?"true":"false","data-success":u?"true":"false",children:[e.exchange.result.status,e.exchange.result.statusText?` ${e.exchange.result.statusText}`:""]}),(0,d.jsx)("span",{className:"vf-editor-chat-http-expand","aria-hidden":"true",children:"+"})]})}),r&&t?(0,Wi.createPortal)((0,d.jsx)("div",{className:"vf-editor-chat-http-modal-backdrop",onClick:()=>n(!1),children:(0,d.jsxs)("div",{className:"vf-editor-chat-http-modal",onClick:f=>f.stopPropagation(),children:[(0,d.jsxs)("div",{className:"vf-editor-chat-http-modal-header",children:[(0,d.jsxs)("div",{className:"vf-editor-chat-http-modal-header-main",children:[(0,d.jsx)("span",{className:"vf-editor-chat-http-pill",children:e.exchange.request.method}),(0,d.jsx)("span",{className:"vf-editor-chat-http-modal-url",children:a}),(0,d.jsxs)("span",{className:"vf-editor-chat-http-status","data-error":c?"true":"false","data-success":u?"true":"false",children:[e.exchange.result.status,e.exchange.result.statusText?` ${e.exchange.result.statusText}`:""]})]}),(0,d.jsx)("button",{type:"button",className:"vf-editor-chat-http-modal-close",onClick:()=>n(!1),"aria-label":"Close HTTP details",children:"\xD7"})]}),(0,d.jsxs)("div",{className:"vf-editor-chat-http-card-body is-modal",children:[e.exchange.explanation?(0,d.jsx)("div",{className:"vf-editor-chat-http-note",children:e.exchange.explanation}):null,(0,d.jsxs)("div",{className:"vf-editor-chat-http-block",children:[(0,d.jsx)("div",{className:"vf-editor-chat-http-label",children:"URL"}),(0,d.jsx)("pre",{className:"vf-editor-chat-http-pre",children:a})]}),i?(0,d.jsxs)("div",{className:"vf-editor-chat-http-block",children:[(0,d.jsx)("div",{className:"vf-editor-chat-http-label",children:"Request"}),(0,d.jsx)("pre",{className:"vf-editor-chat-http-pre",children:i})]}):null,(0,d.jsxs)("div",{className:"vf-editor-chat-http-block",children:[(0,d.jsx)("div",{className:"vf-editor-chat-http-label",children:"Response"}),(0,d.jsx)("pre",{className:"vf-editor-chat-http-pre",children:e.exchange.result.error||s||"(empty)"})]}),Object.keys(e.exchange.result.headers).length?(0,d.jsxs)("div",{className:"vf-editor-chat-http-block",children:[(0,d.jsx)("div",{className:"vf-editor-chat-http-label",children:"Headers"}),(0,d.jsx)("pre",{className:"vf-editor-chat-http-pre",children:Bf(e.exchange.result.headers)})]}):null]})]})}),document.body):null]})}function AR(e){return typeof e=="string"?JSON.stringify(e):typeof e=="number"||typeof e=="boolean"?String(e):e===null?"null":JSON.stringify(e)}function vS(e){if(navigator.clipboard?.writeText)return navigator.clipboard.writeText(e);let t=document.createElement("textarea");return t.value=e,t.style.position="fixed",t.style.opacity="0",document.body.appendChild(t),t.focus(),t.select(),document.execCommand("copy"),document.body.removeChild(t),Promise.resolve()}function Dr(e){return(0,d.jsxs)("div",{className:"vf-editor-chat-json-line",style:{paddingLeft:`${e.depth*18+12}px`},children:[(0,d.jsx)("button",{type:"button",className:"vf-editor-chat-json-copy","aria-label":"Copy line",title:"Copy line",onClick:()=>e.onCopy(e.text),children:(0,d.jsx)(_S,{})}),(0,d.jsx)("span",{className:"vf-editor-chat-json-line-text",children:e.text})]})}function pS(e){let t=e.value,n=e.isLast?"":",";if(Array.isArray(t)){let r=e.path,o=e.collapsedPaths.has(r),i=`${e.linePrefix??""}[`;return t.length?o?(0,d.jsxs)("div",{className:"vf-editor-chat-json-toggle-row",children:[(0,d.jsx)("button",{type:"button",className:"vf-editor-chat-json-toggle-icon",onClick:()=>e.togglePath(r),"aria-label":"Expand JSON block",children:(0,d.jsx)(Ff,{open:!1})}),(0,d.jsx)(Dr,{text:`${e.linePrefix??""}[ \u2026 ]${n}`,depth:e.depth,onCopy:e.onCopy})]}):(0,d.jsxs)("div",{children:[(0,d.jsxs)("div",{className:"vf-editor-chat-json-toggle-row",children:[(0,d.jsx)("button",{type:"button",className:"vf-editor-chat-json-toggle-icon",onClick:()=>e.togglePath(r),"aria-label":"Collapse JSON block",children:(0,d.jsx)(Ff,{open:!0})}),(0,d.jsx)(Dr,{text:i,depth:e.depth,onCopy:e.onCopy})]}),t.map((s,a)=>(0,d.jsx)(pS,{value:s,depth:e.depth+1,path:`${r}.${a}`,isLast:a===t.length-1,collapsedPaths:e.collapsedPaths,togglePath:e.togglePath,onCopy:e.onCopy},`${r}:${a}`)),(0,d.jsx)(Dr,{text:`]${n}`,depth:e.depth,onCopy:e.onCopy})]}):(0,d.jsx)(Dr,{text:`${e.linePrefix??""}[]${n}`,depth:e.depth,onCopy:e.onCopy})}if(t&&typeof t=="object"){let r=Object.entries(t),o=e.path,i=e.collapsedPaths.has(o),s=`${e.linePrefix??""}{`;return r.length?i?(0,d.jsxs)("div",{className:"vf-editor-chat-json-toggle-row",children:[(0,d.jsx)("button",{type:"button",className:"vf-editor-chat-json-toggle-icon",onClick:()=>e.togglePath(o),"aria-label":"Expand JSON block",children:(0,d.jsx)(Ff,{open:!1})}),(0,d.jsx)(Dr,{text:`${e.linePrefix??""}{ \u2026 }${n}`,depth:e.depth,onCopy:e.onCopy})]}):(0,d.jsxs)("div",{children:[(0,d.jsxs)("div",{className:"vf-editor-chat-json-toggle-row",children:[(0,d.jsx)("button",{type:"button",className:"vf-editor-chat-json-toggle-icon",onClick:()=>e.togglePath(o),"aria-label":"Collapse JSON block",children:(0,d.jsx)(Ff,{open:!0})}),(0,d.jsx)(Dr,{text:s,depth:e.depth,onCopy:e.onCopy})]}),r.map(([a,l],c)=>{let u=`${JSON.stringify(a)}: `;return l&&typeof l=="object"?(0,d.jsx)(pS,{value:l,depth:e.depth+1,linePrefix:u,path:`${o}.${a}`,isLast:c===r.length-1,collapsedPaths:e.collapsedPaths,togglePath:e.togglePath,onCopy:e.onCopy},`${o}:${a}`):(0,d.jsx)(Dr,{text:`${u}${AR(l)}${c===r.length-1?"":","}`,depth:e.depth+1,onCopy:e.onCopy},`${o}:${a}`)}),(0,d.jsx)(Dr,{text:`}${n}`,depth:e.depth,onCopy:e.onCopy})]}):(0,d.jsx)(Dr,{text:`${e.linePrefix??""}{}${n}`,depth:e.depth,onCopy:e.onCopy})}return(0,d.jsx)(Dr,{text:`${e.linePrefix??""}${AR(t)}${n}`,depth:e.depth,onCopy:e.onCopy})}function JR(e){let[t,n]=(0,k.useState)(new Set),[r,o]=(0,k.useState)(""),i=a=>{n(l=>{let c=new Set(l);return c.has(a)?c.delete(a):c.add(a),c})},s=async a=>{try{await vS(a),o("done")}catch{o("error")}window.setTimeout(()=>o(""),1400)};return(0,d.jsxs)("div",{className:"vf-editor-chat-json-viewer",children:[(0,d.jsxs)("div",{className:"vf-editor-chat-json-toolbar",children:[(0,d.jsx)("span",{className:"vf-editor-chat-json-file",children:e.storageKey}),(0,d.jsx)("span",{className:"vf-editor-chat-json-copy-state","data-state":r,children:r==="done"?"Copied line":r==="error"?"Copy failed":"Hover a line to copy"})]}),(0,d.jsx)("div",{className:"vf-editor-chat-json-scroll",children:(0,d.jsx)(pS,{value:e.value,depth:0,path:"root",collapsedPaths:t,togglePath:i,onCopy:s})})]})}function YF(e){let[t,n]=(0,k.useState)(!1),[r,o]=(0,k.useState)(""),i=zR(e.artifact.url,`${e.artifact.label}.json`),s=Bf(e.data);(0,k.useEffect)(()=>{n(!0)},[]);let a=async()=>{try{await vS(s),o("done")}catch{o("error")}window.setTimeout(()=>o(""),1600)};return(0,k.useEffect)(()=>{let l=c=>{c.key==="Escape"&&e.onClose()};return window.addEventListener("keydown",l),()=>window.removeEventListener("keydown",l)},[e]),t?(0,Wi.createPortal)((0,d.jsx)("div",{className:"vf-editor-chat-media-modal-backdrop",onClick:e.onClose,children:(0,d.jsxs)("div",{className:"vf-editor-chat-json-modal",onClick:l=>l.stopPropagation(),children:[(0,d.jsxs)("div",{className:"vf-editor-chat-media-modal-header",children:[(0,d.jsx)("a",{className:"vf-editor-chat-media-modal-link",href:e.artifact.url,target:"_blank",rel:"noopener noreferrer",children:e.artifact.label}),(0,d.jsxs)("div",{className:"vf-editor-chat-media-modal-actions",children:[(0,d.jsx)("button",{type:"button",className:"vf-editor-chat-media-modal-control","data-state":r,onClick:()=>{a()},title:r==="done"?"Copied":r==="error"?"Copy failed":"Copy JSON","aria-label":r==="done"?"JSON copied":r==="error"?"Unable to copy JSON":"Copy JSON",children:(0,d.jsx)(_S,{})}),(0,d.jsx)("a",{className:"vf-editor-chat-media-modal-control",href:e.artifact.url,download:i,title:"Download JSON","aria-label":"Download JSON",children:(0,d.jsx)(yS,{})}),(0,d.jsx)("a",{className:"vf-editor-chat-media-modal-control",href:e.artifact.url,target:"_blank",rel:"noopener noreferrer",title:"Open raw JSON","aria-label":"Open raw JSON",children:(0,d.jsx)(SS,{})}),(0,d.jsx)("button",{type:"button",className:"vf-editor-chat-media-modal-control",onClick:e.onClose,"aria-label":"Close JSON preview",title:"Close",children:"\xD7"})]})]}),(0,d.jsx)("div",{className:"vf-editor-chat-json-modal-body",children:(0,d.jsx)(JR,{value:e.data,storageKey:e.artifact.label})})]})}),document.body):null}function KF(e){let[t,n]=(0,k.useState)(!1),[r,o]=(0,k.useState)(!1),[i,s]=(0,k.useState)(null),[a,l]=(0,k.useState)(null),[c,u]=(0,k.useState)(!1),f=async()=>{if(!(i!==null||c)){u(!0),l(null);try{let _=await(await fetch(e.artifact.url,{credentials:"omit"})).json();s(_)}catch(y){l(y instanceof Error?y.message:"Unable to load JSON artifact.")}finally{u(!1)}}},p=()=>{let y=!t;n(y),y&&f()},h=()=>{f(),o(!0)};return(0,d.jsxs)(d.Fragment,{children:[(0,d.jsxs)("div",{className:"vf-editor-chat-json-card",children:[(0,d.jsxs)("div",{className:"vf-editor-chat-json-card-head",children:[(0,d.jsxs)("div",{children:[(0,d.jsx)("div",{className:"vf-editor-chat-json-card-kicker",children:"JSON result"}),(0,d.jsx)("div",{className:"vf-editor-chat-json-card-title",children:e.artifact.label})]}),(0,d.jsxs)("div",{className:"vf-editor-chat-json-card-actions",children:[(0,d.jsx)("button",{type:"button",className:"vf-editor-chat-json-card-action",onClick:p,children:t?"Hide preview":"Preview JSON"}),(0,d.jsx)("button",{type:"button",className:"vf-editor-chat-json-card-action is-strong",onClick:h,children:"Open"})]})]}),t?(0,d.jsx)("div",{className:"vf-editor-chat-json-card-body",children:c?(0,d.jsx)("div",{className:"vf-editor-chat-json-state",children:"Loading JSON\u2026"}):a?(0,d.jsx)("div",{className:"vf-editor-chat-json-state is-error",children:a}):i!==null?(0,d.jsx)(JR,{value:i,storageKey:e.artifact.label}):null}):null]}),r&&i!==null?(0,d.jsx)(YF,{artifact:e.artifact,data:i,onClose:()=>o(!1)}):null]})}function XR(e){return e.format==="markdown"?(0,d.jsx)("div",{className:"vf-editor-chat-doc-markdown",dangerouslySetInnerHTML:{__html:HR(e.text)}}):(0,d.jsx)("pre",{className:"vf-editor-chat-doc-pre",children:e.text})}function JF(e){let[t,n]=(0,k.useState)(!1),[r,o]=(0,k.useState)(""),i=e.artifact.format==="markdown"?".md":".txt",s=zR(e.artifact.url,`${e.artifact.label}${i}`);(0,k.useEffect)(()=>{n(!0)},[]);let a=async()=>{try{await vS(e.text),o("done")}catch{o("error")}window.setTimeout(()=>o(""),1600)};return(0,k.useEffect)(()=>{let l=c=>{c.key==="Escape"&&e.onClose()};return window.addEventListener("keydown",l),()=>window.removeEventListener("keydown",l)},[e]),t?(0,Wi.createPortal)((0,d.jsx)("div",{className:"vf-editor-chat-media-modal-backdrop",onClick:e.onClose,children:(0,d.jsxs)("div",{className:"vf-editor-chat-json-modal",onClick:l=>l.stopPropagation(),children:[(0,d.jsxs)("div",{className:"vf-editor-chat-media-modal-header",children:[(0,d.jsx)("a",{className:"vf-editor-chat-media-modal-link",href:e.artifact.url,target:"_blank",rel:"noopener noreferrer",children:e.artifact.label}),(0,d.jsxs)("div",{className:"vf-editor-chat-media-modal-actions",children:[(0,d.jsx)("button",{type:"button",className:"vf-editor-chat-media-modal-control","data-state":r,onClick:()=>{a()},title:r==="done"?"Copied":r==="error"?"Copy failed":e.artifact.format==="markdown"?"Copy markdown":"Copy text","aria-label":r==="done"?"Document copied":r==="error"?"Unable to copy document":e.artifact.format==="markdown"?"Copy markdown":"Copy text",children:(0,d.jsx)(_S,{})}),(0,d.jsx)("a",{className:"vf-editor-chat-media-modal-control",href:e.artifact.url,download:s,title:e.artifact.format==="markdown"?"Download markdown":"Download text","aria-label":e.artifact.format==="markdown"?"Download markdown":"Download text",children:(0,d.jsx)(yS,{})}),(0,d.jsx)("a",{className:"vf-editor-chat-media-modal-control",href:e.artifact.url,target:"_blank",rel:"noopener noreferrer",title:"Open raw file","aria-label":"Open raw file",children:(0,d.jsx)(SS,{})}),(0,d.jsx)("button",{type:"button",className:"vf-editor-chat-media-modal-control",onClick:e.onClose,"aria-label":"Close document preview",title:"Close",children:"\xD7"})]})]}),(0,d.jsx)("div",{className:"vf-editor-chat-json-modal-body",children:(0,d.jsx)("div",{className:"vf-editor-chat-doc-viewer",children:(0,d.jsx)(XR,{text:e.text,format:e.artifact.format})})})]})}),document.body):null}function XF(e){let[t,n]=(0,k.useState)(!1),[r,o]=(0,k.useState)(!1),[i,s]=(0,k.useState)(null),[a,l]=(0,k.useState)(null),[c,u]=(0,k.useState)(!1),f=async()=>{if(!(i!==null||c)){u(!0),l(null);try{let _=await(await fetch(e.artifact.url,{credentials:"omit"})).text();s(_)}catch(y){l(y instanceof Error?y.message:"Unable to load document artifact.")}finally{u(!1)}}},p=()=>{let y=!t;n(y),y&&f()},h=()=>{f(),o(!0)};return(0,d.jsxs)(d.Fragment,{children:[(0,d.jsxs)("div",{className:"vf-editor-chat-json-card",children:[(0,d.jsxs)("div",{className:"vf-editor-chat-json-card-head",children:[(0,d.jsxs)("div",{children:[(0,d.jsx)("div",{className:"vf-editor-chat-json-card-kicker",children:e.artifact.format==="markdown"?"Markdown result":"Text result"}),(0,d.jsx)("div",{className:"vf-editor-chat-json-card-title",children:e.artifact.label})]}),(0,d.jsxs)("div",{className:"vf-editor-chat-json-card-actions",children:[(0,d.jsx)("button",{type:"button",className:"vf-editor-chat-json-card-action",onClick:p,children:t?"Hide preview":"Preview"}),(0,d.jsx)("button",{type:"button",className:"vf-editor-chat-json-card-action is-strong",onClick:h,children:"Open"})]})]}),t?(0,d.jsx)("div",{className:"vf-editor-chat-json-card-body",children:c?(0,d.jsx)("div",{className:"vf-editor-chat-json-state",children:"Loading document\u2026"}):a?(0,d.jsx)("div",{className:"vf-editor-chat-json-state is-error",children:a}):i!==null?(0,d.jsx)("div",{className:"vf-editor-chat-doc-viewer is-inline",children:(0,d.jsx)(XR,{text:i,format:e.artifact.format})}):null}):null]}),r&&i!==null?(0,d.jsx)(JF,{artifact:e.artifact,text:i,onClose:()=>o(!1)}):null]})}var QF=(0,k.memo)(function(t){let n=t.message.role==="assistant",r=t.message.text.trim().length>0,o=r?HR(t.message.text):"",[i,s]=(0,k.useState)(null),a=t.message.attachments.filter(jf),l=t.message.attachments.filter(uS),c=t.message.attachments.filter(_=>!jf(_)&&!uS(_)),u=r?lF(t.message.text,t.message.attachments.map(_=>_.viewUrl)):[],f=u.filter(_=>_.kind==="image"),p=u.filter(_=>_.kind==="video"),h=(t.message.httpExchanges??[]).flatMap(_=>{let T=$i(_.result.body);return T?WR(T):[]}).filter((_,T,g)=>g.findIndex(S=>S.url===_.url)===T),y=(t.message.httpExchanges??[]).flatMap(_=>{let T=$i(_.result.body);return T?GR(T):[]}).filter((_,T,g)=>g.findIndex(S=>S.url===_.url)===T);return(0,d.jsxs)("div",{className:`vf-editor-chat-message ${n?"is-assistant":"is-user"}`,children:[(0,d.jsx)("div",{className:"vf-editor-chat-message-meta",children:n?"Copilot":"You"}),(0,d.jsxs)("div",{className:"vf-editor-chat-bubble","data-pending":t.message.isPending?"true":"false",children:[t.message.attachments.length?(0,d.jsxs)("div",{className:"vf-editor-chat-message-attachments",children:[c.map(_=>(0,d.jsx)("div",{className:"vf-editor-chat-message-attachment-row",children:(0,d.jsx)("a",{className:"vf-editor-chat-message-preview-link",href:_.viewUrl,target:"_blank",rel:"noopener noreferrer",children:(0,d.jsx)(zF,{attachment:_})})},_.id)),(0,d.jsx)(NR,{previews:a.map(_=>({kind:"image",url:_.viewUrl,label:_.fileName})),onOpenModal:(_,T)=>s({preview:_,gallery:T})}),l.map(_=>(0,d.jsx)(kR,{preview:{kind:"video",url:_.viewUrl,label:_.fileName},onOpenModal:T=>s({preview:T,gallery:[T]})},_.id))]}):null,t.message.statusText?(0,d.jsxs)("div",{className:"vf-editor-chat-message-status","aria-live":"polite",children:[(0,d.jsx)("span",{className:"vf-editor-chat-status-dot"}),t.message.statusText]}):null,t.message.httpExchanges?.length?(0,d.jsx)("div",{className:"vf-editor-chat-http-list",children:t.message.httpExchanges.map((_,T)=>(0,d.jsx)(qF,{exchange:_},`${_.request.method}:${_.request.url}:${T}`))}):null,r?(0,d.jsx)("div",{className:"vf-editor-chat-message-body",dangerouslySetInnerHTML:{__html:o}}):t.message.isPending?(0,d.jsxs)("div",{className:"vf-editor-chat-message-loading","aria-hidden":"true",children:[(0,d.jsx)("span",{}),(0,d.jsx)("span",{}),(0,d.jsx)("span",{})]}):null,u.length?(0,d.jsxs)("div",{className:"vf-editor-chat-message-attachments",children:[(0,d.jsx)(NR,{previews:f,onOpenModal:(_,T)=>s({preview:_,gallery:T})}),p.map(_=>(0,d.jsx)(kR,{preview:_,onOpenModal:T=>s({preview:T,gallery:[T]})},_.url))]}):null,h.length?(0,d.jsx)("div",{className:"vf-editor-chat-json-list",children:h.map(_=>(0,d.jsx)(KF,{artifact:_},_.key))}):null,y.length?(0,d.jsx)("div",{className:"vf-editor-chat-json-list",children:y.map(_=>(0,d.jsx)(XF,{artifact:_},_.key))}):null]}),i?(0,d.jsx)(WF,{preview:i.preview,gallery:i.gallery,onClose:()=>s(null)}):null]})});function MR(e){if(!e||e<=0)return"Unknown size";let t=["B","KB","MB","GB"],n=e,r=0;for(;n>=1024&&r<t.length-1;)n/=1024,r+=1;return`${n>=10||r===0?n.toFixed(0):n.toFixed(1)} ${t[r]}`}function PR(e){return jf(e.file)?(0,d.jsx)("img",{className:"vf-editor-upload-file-thumb",src:e.file.viewUrl,alt:e.file.fileName}):uS(e.file)?(0,d.jsx)("video",{className:"vf-editor-upload-file-thumb",src:e.file.viewUrl,muted:!0,playsInline:!0}):(0,d.jsx)("div",{className:"vf-editor-upload-file-icon","aria-hidden":"true",children:e.file.fileName.slice(0,1).toUpperCase()})}function mo(e){return e.split("/").map(t=>t.trim()).filter(Boolean).join("/")}function Gf(e,t){return mo([e,t].filter(Boolean).join("/"))}function LR(e){let t=mo(e).split("/").filter(Boolean);return t.pop(),t.join("/")}function OR(e){return mo(e).split("/").filter(Boolean).at(-1)||"All files"}function ZF(e){let t=mo(e.currentFolder),n=t?`${t}/`:"",r=new Map;for(let o of e.folders){let i=mo(o);if(!i||t&&i===t||!i.startsWith(n))continue;let a=i.slice(n.length).split("/")[0];a&&r.set(a,Gf(t,a))}for(let o of e.files){let i=mo(o.folderPath??"");if(!i||t&&i===t||!i.startsWith(n))continue;let a=i.slice(n.length).split("/")[0];a&&r.set(a,Gf(t,a))}return Array.from(r.entries()).map(([o,i])=>({name:o,path:i})).sort((o,i)=>o.name.localeCompare(i.name))}function cS(e){return e.name==="share"?(0,d.jsxs)("svg",{viewBox:"0 0 24 24","aria-hidden":"true",focusable:"false",children:[(0,d.jsx)("path",{d:"M14 4h6v6"}),(0,d.jsx)("path",{d:"M10 14 20 4"}),(0,d.jsx)("path",{d:"M20 14v4a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h4"})]}):e.name==="link"?(0,d.jsxs)("svg",{viewBox:"0 0 24 24","aria-hidden":"true",focusable:"false",children:[(0,d.jsx)("path",{d:"M10 13a5 5 0 0 0 7.07 0l2.12-2.12a5 5 0 0 0-7.07-7.07L11 4.93"}),(0,d.jsx)("path",{d:"M14 11a5 5 0 0 0-7.07 0L4.81 13.12a5 5 0 0 0 7.07 7.07L13 19.07"})]}):(0,d.jsxs)("svg",{viewBox:"0 0 24 24","aria-hidden":"true",focusable:"false",children:[(0,d.jsx)("path",{d:"M3 6h18"}),(0,d.jsx)("path",{d:"M8 6V4h8v2"}),(0,d.jsx)("path",{d:"M19 6 18 20H6L5 6"}),(0,d.jsx)("path",{d:"M10 11v5"}),(0,d.jsx)("path",{d:"M14 11v5"})]})}function eB(e){let[t,n]=(0,k.useState)("my-files"),[r,o]=(0,k.useState)([]),[i,s]=(0,k.useState)([]),[a,l]=(0,k.useState)([]),[c,u]=(0,k.useState)(()=>new Set),[f,p]=(0,k.useState)([]),[h,y]=(0,k.useState)([]),[_,T]=(0,k.useState)(()=>new Set),[g,S]=(0,k.useState)(null),[E,R]=(0,k.useState)(!1),[M,A]=(0,k.useState)(""),[I,N]=(0,k.useState)(null),[U,x]=(0,k.useState)(null),[H,j]=(0,k.useState)(null),[he,X]=(0,k.useState)(null),[Ze,fe]=(0,k.useState)(null),de=(0,k.useRef)(null),D=(0,k.useRef)(null),ge=(0,k.useMemo)(()=>{let P=f.map(ie=>({...ie,recentSource:"generated"}));return[...h.map(ie=>({...ie,recentSource:"temporary"})),...P].sort((ie,Y)=>{let Ie=ie.createdAt?Date.parse(ie.createdAt):0;return(Y.createdAt?Date.parse(Y.createdAt):0)-Ie})},[f,h]),Q=t==="upload"?r:t==="my-files"?i.filter(P=>c.has(P.id)):t==="recents"?ge.filter(P=>_.has(P.id)):[];async function ae(){let P=await IF(e.apiKey);s(P.attachments),l(P.folders)}async function Re(P){R(!0);try{let[V,ie]=P?[await TR(e.apiKey,P),null]:await Promise.all([TR(e.apiKey),wF(e.apiKey)]);p(Y=>P?[...Y,...V.media]:V.media),ie&&y(ie.files),S(V.nextCursor),P||T(new Set)}finally{R(!1)}}(0,k.useEffect)(()=>{e.open&&(X(null),j(null),ae().catch(P=>X(P instanceof Error?P.message:"Unable to load My Files.")),Re().catch(P=>X(P instanceof Error?P.message:"Unable to load recent media.")))},[e.open]);function Te(){o([]),u(new Set),T(new Set),j(null),X(null),N(null),x(null),e.onClose()}async function St(P){try{if(navigator.clipboard?.writeText)await navigator.clipboard.writeText(P);else{let V=document.createElement("textarea");V.value=P,V.style.position="fixed",V.style.opacity="0",document.body.appendChild(V),V.focus(),V.select(),document.execCommand("copy"),document.body.removeChild(V)}j("File URL copied.")}catch{X("Unable to copy file URL.")}}async function ot(P,V){if(!P.length)return;X(null);let ie=[];for(let Y of P)try{if(j(`Uploading ${Y.name}...`),V==="upload"){let dt=await YR({apiKey:e.apiKey,file:Y,folderPath:UR}),J=await qR({attachment:dt,file:Y,currentInlineBytes:VR([...r,...ie])});ie.push(J);continue}let Ie=await TF({apiKey:e.apiKey,file:Y,folderPath:M,maxBytes:DR,limitLabel:"50 MB"});ie.push(Ie)}catch(Ie){X(Ie instanceof Error?Ie.message:"Upload failed.")}V==="upload"?(o(Y=>[...Y,...ie]),await Re().catch(Y=>X(Y instanceof Error?Y.message:"Unable to refresh recent files."))):V==="my-files"&&(await ae(),u(Y=>new Set([...Y,...ie.map(Ie=>Ie.id)]))),ie.length&&j(`${ie.length} file${ie.length===1?"":"s"} uploaded.`)}async function bt(P,V){let ie=V==="my-files"?`/api/v1/user/me/attachments/${encodeURIComponent(P.id)}`:`/api/v1/user/me/temporary-files/${encodeURIComponent(P.id)}`,Y=await fetch(ie,{method:"DELETE",headers:ut(e.apiKey,"application/json")}),Ie=await Y.json().catch(()=>({}));if(!Y.ok)throw new Error(Ie.error||"Unable to delete file.");V==="my-files"&&(s(dt=>dt.filter(J=>J.id!==P.id)),u(dt=>{let J=new Set(dt);return J.delete(P.id),J})),fe(null),j("File deleted.")}async function it(P){if(P!=="my-files"||!U||U.mode!=="create")return;let V=Gf(U.baseFolder,U.value);if(!V){X("Choose a folder name.");return}let ie=await fetch("/api/v1/user/me/attachments/folders",{method:"POST",headers:ut(e.apiKey,"application/json"),body:JSON.stringify({folder_path:V})}),Y=await ie.json().catch(()=>({}));if(!ie.ok){X(Y.error||"Unable to create folder.");return}l(Ie=>Array.from(new Set([...Ie,V])).sort()),x(null),j("Folder created.")}async function In(P,V){if(P!=="my-files"||!U||U.mode!=="rename")return;let ie=U.value.trim(),Y=Gf(LR(V),ie);if(!Y||Y===V)return;let Ie=await fetch("/api/v1/user/me/attachments/folders",{method:"PATCH",headers:ut(e.apiKey,"application/json"),body:JSON.stringify({from_folder_path:V,to_folder_path:Y})}),dt=await Ie.json().catch(()=>({}));if(!Ie.ok){X(dt.error||"Unable to rename folder.");return}A(J=>J===V||J.startsWith(`${V}/`)?`${Y}${J.slice(V.length)}`:J),await ae(),N(null),x(null),j("Folder renamed.")}async function Dt(P,V){if(P!=="my-files")return;let ie=await fetch("/api/v1/user/me/attachments/folders",{method:"DELETE",headers:ut(e.apiKey,"application/json"),body:JSON.stringify({folder_path:V})}),Y=await ie.json().catch(()=>({}));if(!ie.ok){X(Y.error||"Unable to delete folder.");return}A(Ie=>Ie===V||Ie.startsWith(`${V}/`)?LR(V):Ie),await ae(),N(null),x(null),j("Folder deleted.")}function wn(P){let V=a,ie=i,Y=M,Ie=A,dt=ZF({folders:V,files:ie,currentFolder:Y}),J=mo(Y).split("/").filter(Boolean);return(0,d.jsxs)("div",{className:"vf-editor-upload-browser",children:[(0,d.jsxs)("div",{className:"vf-editor-upload-browser-toolbar",children:[(0,d.jsxs)("div",{className:"vf-editor-upload-breadcrumb","aria-label":"Current folder",children:[(0,d.jsx)("button",{type:"button","data-current":!Y,onClick:()=>Ie(""),children:"files"}),J.map(($e,ye)=>{let Je=J.slice(0,ye+1).join("/");return(0,d.jsxs)("span",{className:"vf-editor-upload-breadcrumb-segment",children:[(0,d.jsx)("span",{"aria-hidden":"true",children:"/"}),(0,d.jsx)("button",{type:"button","data-current":Je===Y,onClick:()=>Ie(Je),children:$e})]},Je)})]}),(0,d.jsx)("button",{type:"button",onClick:()=>x({mode:"create",scope:"my-files",baseFolder:Y,value:""}),children:"New folder"})]}),dt.length?(0,d.jsx)("div",{className:"vf-editor-upload-folder-grid",children:dt.map($e=>(0,d.jsxs)("article",{className:"vf-editor-upload-folder-row",children:[(0,d.jsxs)("button",{type:"button",className:"vf-editor-upload-folder-open",onClick:()=>Ie($e.path),children:[(0,d.jsx)("span",{className:"vf-editor-upload-folder-icon","aria-hidden":"true"}),(0,d.jsx)("span",{children:$e.name})]}),(0,d.jsx)("button",{type:"button",className:"vf-editor-upload-folder-menu-button","aria-label":`Folder actions for ${$e.name}`,onClick:()=>N(I===$e.path?null:$e.path),children:"..."}),I===$e.path?(0,d.jsxs)("div",{className:"vf-editor-upload-folder-menu",children:[(0,d.jsx)("button",{type:"button",onClick:()=>x({mode:"rename",scope:"my-files",folderPath:$e.path,value:OR($e.path)}),children:"Rename"}),(0,d.jsx)("button",{type:"button","data-danger":"true",onClick:()=>x({mode:"delete",scope:"my-files",folderPath:$e.path,value:""}),children:"Delete"})]}):null]},$e.path))}):null]})}function nr(P,V){let ie=V==="my-files"?c.has(P.id):V==="recents"?_.has(P.id):!1,Y="s3Url"in P&&P.s3Url?P.s3Url:P.viewUrl;return(0,d.jsxs)("article",{className:"vf-editor-upload-file-card","data-selected":ie?"true":"false",children:[(0,d.jsxs)("button",{type:"button",className:"vf-editor-upload-file-select",onClick:()=>{if(V==="temporary"){St(Y);return}(V==="recents"?T:u)(dt=>{let J=new Set(dt);return J.has(P.id)?J.delete(P.id):J.add(P.id),J})},children:[(0,d.jsx)(PR,{file:P}),(0,d.jsxs)("span",{className:"vf-editor-upload-file-main",children:[(0,d.jsx)("span",{className:"vf-editor-upload-file-name",children:P.fileName}),(0,d.jsxs)("span",{className:"vf-editor-upload-file-meta",children:[MR(P.sizeBytes),P.folderPath?` \xB7 ${P.folderPath}`:""]})]})]}),(0,d.jsxs)("div",{className:"vf-editor-upload-file-actions",children:[V==="my-files"||V==="recents"?(0,d.jsx)("span",{className:"vf-editor-upload-selection-indicator","data-selected":ie?"true":"false","aria-hidden":"true",children:ie?"\u2713":""}):null,(0,d.jsx)("a",{href:P.viewUrl,target:"_blank",rel:"noreferrer","aria-label":`View ${P.fileName}`,children:(0,d.jsx)(cS,{name:"share"})}),(0,d.jsx)("button",{type:"button","aria-label":`Copy URL for ${P.fileName}`,onClick:()=>{St(Y)},children:(0,d.jsx)(cS,{name:"link"})}),V==="recents"?null:(0,d.jsx)("button",{type:"button","aria-label":`Delete ${P.fileName}`,onClick:()=>fe(Ze===P.id?null:P.id),children:(0,d.jsx)(cS,{name:"trash"})})]}),V!=="recents"&&Ze===P.id?(0,d.jsxs)("div",{className:"vf-editor-upload-popconfirm",children:[(0,d.jsx)("span",{children:"Delete this file?"}),(0,d.jsx)("button",{type:"button",onClick:()=>fe(null),children:"Cancel"}),(0,d.jsx)("button",{type:"button","data-danger":"true",onClick:()=>{bt(P,V)},children:"Delete"})]}):null]},P.id)}function Vi(){if(!U)return null;let P=U.mode==="create"?"New folder":U.mode==="rename"?"Rename folder":"Delete folder",V=U.mode==="delete"?U.folderPath:"";return(0,d.jsxs)("div",{className:"vf-editor-upload-folder-dialog",role:"dialog","aria-label":P,children:[(0,d.jsx)("div",{className:"vf-editor-upload-folder-dialog-title",children:P}),U.mode==="delete"?(0,d.jsxs)("div",{className:"vf-editor-upload-folder-dialog-copy",children:["Delete ",(0,d.jsx)("strong",{children:V})," and all files inside it?"]}):(0,d.jsx)("input",{value:U.value,autoFocus:!0,placeholder:"folder-name",onChange:ie=>x({...U,value:ie.target.value}),onKeyDown:ie=>{ie.key==="Enter"&&(ie.preventDefault(),U.mode==="create"?it(U.scope):In(U.scope,U.folderPath))}}),(0,d.jsxs)("div",{className:"vf-editor-upload-folder-dialog-actions",children:[(0,d.jsx)("button",{type:"button",onClick:()=>x(null),children:"Cancel"}),U.mode==="create"?(0,d.jsx)("button",{type:"button",className:"vf-editor-upload-confirm",onClick:()=>{it(U.scope)},children:"Create"}):U.mode==="rename"?(0,d.jsx)("button",{type:"button",className:"vf-editor-upload-confirm",onClick:()=>{In(U.scope,U.folderPath)},children:"Rename"}):(0,d.jsx)("button",{type:"button","data-danger":"true",onClick:()=>{Dt(U.scope,U.folderPath)},children:"Delete"})]})]})}if(!e.open)return null;let Zo=i.filter(P=>mo(P.folderPath??"")===mo(M));return(0,Wi.createPortal)((0,d.jsx)("div",{className:"vf-editor-upload-drawer-backdrop",children:(0,d.jsxs)("aside",{className:"vf-editor-upload-drawer","aria-label":"Upload drawer",children:[(0,d.jsxs)("div",{className:"vf-editor-upload-header",children:[(0,d.jsxs)("div",{children:[(0,d.jsx)("div",{className:"vf-editor-upload-title",children:"Upload"}),(0,d.jsx)("div",{className:"vf-editor-upload-subtitle",children:"Upload, attach, and copy file URLs."})]}),(0,d.jsx)("button",{type:"button",className:"vf-editor-upload-close","aria-label":"Close upload drawer",onClick:Te,children:"\xD7"})]}),(0,d.jsxs)("div",{className:"vf-editor-upload-tabs",role:"tablist",children:[(0,d.jsx)("button",{type:"button","data-active":t==="upload",onClick:()=>n("upload"),children:"Upload file"}),(0,d.jsx)("button",{type:"button","data-active":t==="my-files",onClick:()=>n("my-files"),children:"My Files"}),(0,d.jsx)("button",{type:"button","data-active":t==="recents",onClick:()=>n("recents"),children:"Recents"})]}),(0,d.jsxs)("div",{className:"vf-editor-upload-body",children:[he?(0,d.jsx)("div",{className:"vf-editor-upload-status","data-tone":"error",children:he}):null,H?(0,d.jsx)("div",{className:"vf-editor-upload-status",children:H}):null,Vi(),t==="upload"?(0,d.jsxs)(d.Fragment,{children:[(0,d.jsxs)("button",{type:"button",className:"vf-editor-upload-drop",onClick:()=>de.current?.click(),children:["Upload files to chat",(0,d.jsx)("span",{children:"Stored in Recents and attached after Confirm. Images get compressed inline previews when possible; other files attach by URL. Max 100 MB each."})]}),(0,d.jsx)("input",{ref:de,type:"file",multiple:!0,hidden:!0,onChange:P=>{ot(Array.from(P.target.files??[]),"upload"),P.target.value=""}}),(0,d.jsx)("div",{className:"vf-editor-upload-list",children:r.map(P=>(0,d.jsxs)("article",{className:"vf-editor-upload-file-card","data-selected":"true",children:[(0,d.jsx)(PR,{file:P}),(0,d.jsxs)("span",{className:"vf-editor-upload-file-main",children:[(0,d.jsx)("span",{className:"vf-editor-upload-file-name",children:P.fileName}),(0,d.jsx)("span",{className:"vf-editor-upload-file-meta",children:MR(P.sizeBytes)})]}),(0,d.jsx)("button",{type:"button",onClick:()=>o(V=>V.filter(ie=>ie.id!==P.id)),children:"\xD7"})]},P.id))})]}):t==="my-files"?(0,d.jsxs)(d.Fragment,{children:[(0,d.jsxs)("button",{type:"button",className:"vf-editor-upload-drop",onClick:()=>D.current?.click(),children:["Add to My Files",(0,d.jsxs)("span",{children:["Uploads into ",OR(M)," and auto-selects. Max 50 MB each."]})]}),(0,d.jsx)("input",{ref:D,type:"file",multiple:!0,hidden:!0,onChange:P=>{ot(Array.from(P.target.files??[]),"my-files"),P.target.value=""}}),wn("my-files"),(0,d.jsx)("div",{className:"vf-editor-upload-list",children:Zo.length?Zo.map(P=>nr(P,"my-files")):(0,d.jsx)("div",{className:"vf-editor-upload-empty",children:"No files in this folder."})})]}):t==="recents"?(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("div",{className:"vf-editor-upload-list",children:ge.length?ge.map(P=>nr(P,"recents")):(0,d.jsx)("div",{className:"vf-editor-upload-empty",children:E?"Loading recent files...":"No recent files yet."})}),g?(0,d.jsx)("button",{type:"button",className:"vf-editor-upload-more",disabled:E,onClick:()=>{Re(g).catch(P=>X(P instanceof Error?P.message:"Unable to load more recent media."))},children:E?"Loading...":"Load more generated media"}):null]}):null]}),(0,d.jsxs)("div",{className:"vf-editor-upload-footer",children:[(0,d.jsx)("button",{type:"button",onClick:Te,children:"Cancel"}),(0,d.jsxs)("div",{className:"vf-editor-upload-footer-confirm",children:[(0,d.jsxs)("span",{children:[Q.length," file",Q.length===1?"":"s"," selected"]}),(0,d.jsx)("button",{type:"button",className:"vf-editor-upload-confirm",disabled:!Q.length,onClick:()=>{e.onConfirm(Q),Te()},children:"Confirm"})]})]})]})}),document.body)}function QR({boot:e}){let t=e.template.templateId==="chat-brainstorm",n=t&&e.template.persistentHistorySidebar===!0,r=(0,k.useMemo)(()=>PF(e.template.templateId),[e.template.templateId]),o=(0,k.useMemo)(()=>LF(),[]),i=(0,k.useRef)(null),s=(0,k.useRef)(null),a=(0,k.useRef)(!0),l=(0,k.useRef)(!1),c=(0,k.useRef)(null),u=(0,k.useRef)(null),f=(0,k.useRef)(new Map),p=(0,k.useRef)({nextAvailableAt:0}),h=(0,k.useRef)([]),y=(0,k.useRef)(new Set),[_,T]=(0,k.useState)([]),[g,S]=(0,k.useState)(null),[E,R]=(0,k.useState)(null),[M,A]=(0,k.useState)(null),[I,N]=(0,k.useState)(""),[U,x]=(0,k.useState)([]),[H,j]=(0,k.useState)(null),[he,X]=(0,k.useState)(null),[Ze,fe]=(0,k.useState)(null),[de,D]=(0,k.useState)(!1),[ge,Q]=(0,k.useState)(!1),[ae,Re]=(0,k.useState)(!1),[Te,St]=(0,k.useState)(!1),[ot,bt]=(0,k.useState)(!1),[it,In]=(0,k.useState)(!1),[Dt,wn]=(0,k.useState)(null),[nr,Vi]=(0,k.useState)(!1),[Zo,P]=(0,k.useState)(null),[V,ie]=(0,k.useState)(!1),[Y,Ie]=(0,k.useState)(()=>{let m=typeof window<"u"?window.__vidfarmEditorTracers:null;if(m)return m.get();if(typeof window<"u"){let v=zf();if(v.length)return v}return tr(e.template.tracers||[])}),dt=(0,k.useMemo)(()=>{if(!e.threadsUrl)return null;let m=new URL(e.threadsUrl,window.location.origin);return t||m.searchParams.set("template_id",e.template.templateId),m.searchParams.set("include_messages","false"),m.searchParams.set("limit",t?"200":"50"),m.toString()},[e.template.templateId,e.threadsUrl,t]),J=m=>e.threadsUrl?new URL(`${e.threadsUrl.replace(/\/$/,"")}/${encodeURIComponent(m)}`,window.location.origin).toString():null;(0,k.useEffect)(()=>{let m=BF(o?.getItem(r.threads)??null,e.template.templateId),v=o?.getItem(r.activeThread)??null,w=wR(),b=window.__vidfarmEditorTracers?.get()??zf(),F=w&&!m.some(le=>le.id===w)?[{id:w,templateId:e.template.templateId,title:"Loading chat",createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),lastMessageAt:null,messageCount:0,tracers:b,hiddenFromView:!1,messages:[]},...m]:m,K=F.filter(le=>!le.hiddenFromView),z=K.find(le=>wc(le,b));h.current=F,T(F),w&&K.some(le=>le.id===w)?S(w):v&&K.some(le=>le.id===v)&&(!b.length||K.some(le=>le.id===v&&wc(le,b)))?S(v):S(z?.id??K[0]?.id??null),D(!0)},[e.template.templateId,o,r]),(0,k.useEffect)(()=>{if(!e.vidfarmApiKey||!dt)return;let m=new AbortController;return(async()=>{try{let v=[],w=null,b=new Set;do{let F=new URL(dt);w&&F.searchParams.set("cursor",w);let K=await fetch(F.toString(),{method:"GET",headers:ut(e.vidfarmApiKey),signal:m.signal});if(!K.ok)return;let z=await K.json().catch(()=>null);Array.isArray(z?.threads)&&v.push(...z.threads.map(pe=>RR(pe,e.template.templateId)).filter(pe=>!!pe));let le=typeof z?.next_cursor=="string"&&z.next_cursor?z.next_cursor:null;!le||b.has(le)?w=null:(b.add(le),w=le)}while(w&&!m.signal.aborted);if(!v.length)return;T(F=>{let K=xR(F,v);return h.current=K,K}),S(F=>F&&h.current.some(K=>K.id===F)?F:v[0]?.id??F)}catch(v){if(v instanceof DOMException&&v.name==="AbortError")return}})(),()=>{m.abort()}},[e.template.templateId,e.vidfarmApiKey,dt]),(0,k.useEffect)(()=>{h.current=_},[_]);let[$e,ye]=(0,k.useState)(()=>fR());(0,k.useEffect)(()=>{let m=()=>{ye(fR())};return window.addEventListener("popstate",m),()=>{window.removeEventListener("popstate",m)}},[]);async function Je(m){if(!e.vidfarmApiKey){P("Sign in to see forks.");return}if(!nr&&!(!m?.force&&Dt!==null)){Vi(!0),P(null);try{let v=await fetch("/api/v1/compositions",{method:"GET",headers:ut(e.vidfarmApiKey)});if(!v.ok){P(v.status===401?"Sign in to see forks.":`Failed to load forks (${v.status}).`),wn([]);return}let w=await v.json().catch(()=>null),F=(Array.isArray(w?.forks)?w.forks:[]).map(K=>{if(!K||typeof K!="object")return null;let z=K,le=typeof z.fork_id=="string"?z.fork_id:null;return le?{forkId:le,templateId:typeof z.template_id=="string"?z.template_id:null,parentForkId:typeof z.parent_fork_id=="string"?z.parent_fork_id:null,parentVersion:typeof z.parent_version=="number"?z.parent_version:null,title:typeof z.title=="string"?z.title:null,visibility:typeof z.visibility=="string"?z.visibility:null,latestVersion:typeof z.latest_version=="number"?z.latest_version:null,ownerCustomerId:typeof z.owner_customer_id=="string"?z.owner_customer_id:null,createdAt:typeof z.created_at=="string"?z.created_at:null,updatedAt:typeof z.updated_at=="string"?z.updated_at:null}:null}).filter(K=>!!K).filter(K=>K.templateId===e.template.templateId).sort((K,z)=>String(z.updatedAt??"").localeCompare(String(K.updatedAt??"")));wn(F)}catch{P("Could not load forks. Please try again."),wn([])}finally{Vi(!1)}}}(0,k.useEffect)(()=>{it&&Dt===null&&!nr&&Je()},[it]),(0,k.useEffect)(()=>{let m=window.__vidfarmEditorTracers;if(m)return Ie(m.get()),m.subscribe(w=>Ie(w));let v=()=>{let w=zf();Ie(w.length?w:tr(e.template.tracers||[]))};return v(),window.addEventListener("popstate",v),()=>{window.removeEventListener("popstate",v)}},[e.template.tracers]);let Se=(0,k.useRef)(_),Ur=(0,k.useRef)(g);(0,k.useEffect)(()=>{Se.current=_,Ur.current=g},[_,g]),(0,k.useEffect)(()=>{if(!de)return;let m=window.setTimeout(()=>{try{o?.setItem(r.threads,JSON.stringify(CR(Se.current,Ur.current)))}catch(v){console.warn("Unable to persist editor chat threads.",v)}},300);return()=>window.clearTimeout(m)},[g,o,de,r,_]),(0,k.useEffect)(()=>{if(de)try{g?o?.setItem(r.activeThread,g):o?.removeItem(r.activeThread)}catch(m){console.warn("Unable to persist active editor chat thread.",m)}},[g,o,de,r]),(0,k.useEffect)(()=>{if(!de||typeof window>"u")return;let m=new URL(window.location.href),v=m.searchParams.get("thread_id");if(g){if(v===g)return;m.searchParams.set("thread_id",g)}else{if(!v)return;m.searchParams.delete("thread_id")}window.history.replaceState({},"",m.toString())},[g,de]);let Jt=(0,k.useMemo)(()=>_.find(m=>m.id===g)??null,[g,_]),qi=(0,k.useMemo)(()=>_.find(m=>m.id===M?.threadId)??null,[M?.threadId,_]);(0,k.useEffect)(()=>{if(!de||!e.vidfarmApiKey||!g)return;let m=h.current.find(z=>z.id===g);if(y.current.has(g))return;let v=wR();if(!!(m&&(m.messageCount??0)===0&&m.messages.length===0)){y.current.add(g);return}let b=J(g);if(!b)return;let F=new AbortController;return!m?.messages.length&&R(g),(async()=>{try{let z=await fetch(b,{method:"GET",headers:ut(e.vidfarmApiKey),signal:F.signal});if(!z.ok){let ce=!!(m&&g!==v),ue=!!(m&&(m.messageCount??0)===0&&m.messages.length===0);z.status===404&&!ce&&!ue&&j(`Chat ID ${g} was not found for this account.`),y.current.add(g);return}let le=await z.json().catch(()=>null),pe=le?.thread?RR(le.thread,e.template.templateId):null;if(!pe)return;y.current.add(pe.id),j(null),T(ce=>{let ue=xR(ce,[pe]);return h.current=ue,ue})}catch(z){if(z instanceof DOMException&&z.name==="AbortError")return}finally{F.signal.aborted||R(z=>z===g?null:z)}})(),()=>{F.abort(),R(z=>z===g?null:z)}},[g,e.vidfarmApiKey,e.threadsUrl,de]),(0,k.useEffect)(()=>{if(!de||Jt&&!Jt.hiddenFromView)return;let m=_.find(v=>!v.hiddenFromView&&wc(v,Y));S(m?.id??_.find(v=>!v.hiddenFromView)?.id??null)},[Jt,de,_,Y]);let Kf=(0,k.useMemo)(()=>Jt?.tracers.length?Jt.tracers:Y,[Jt?.tracers,Y]),Jf=(0,k.useMemo)(()=>_.filter(m=>!m.hiddenFromView).sort((m,v)=>{let w=wc(m,Y),b=wc(v,Y);return w!==b?w?-1:1:Date.parse(v.updatedAt)-Date.parse(m.updatedAt)}),[_,Y]),IS=Kf[0]??null,Xf=Jt?.messages??[],wS=he!==null,Qf=!!(g&&he===g),CS=(0,k.useMemo)(()=>(I.trim()||U.length)&&!wS,[I,U.length,wS]);(0,k.useEffect)(()=>{!de||!e.vidfarmApiKey||!Jt||!Jt.messages.length||_x(Jt)},[Jt,e.vidfarmApiKey,de]);async function Rc(m,v){if(!e.vidfarmApiKey||!e.threadsUrl||!m.messages.length)return;let w=J(m.id);w&&await fetch(w,{method:"PATCH",headers:ut(e.vidfarmApiKey,"application/json"),body:JSON.stringify({template_id:e.template.templateId,title:v?.title??m.title,tracers:v?.tracers??m.tracers,hidden_from_view:v?.hiddenFromView??m.hiddenFromView===!0,archived:v?.archived})}).catch(()=>{})}async function nx(m){if(!e.vidfarmApiKey||!e.threadsUrl||!m.messages.length)return;let v=J(m.threadId);v&&await fetch(`${v}/exchanges`,{method:"POST",headers:ut(e.vidfarmApiKey,"application/json"),body:JSON.stringify({template_id:m.templateId??e.template.templateId,title:m.title||"New chat",tracers:m.tracers,messages:m.messages.map(w=>({id:w.id,role:w.role,text:w.text,attachments:w.attachments.map(b=>({id:b.id,fileName:b.fileName,contentType:b.contentType,viewUrl:b.viewUrl})),toolExchanges:w.toolExchanges,httpExchanges:w.httpExchanges?.map(Cc)}))})}).catch(()=>{})}async function rx(m){if(!e.vidfarmApiKey||!e.threadsUrl)return;let v=J(m);v&&await fetch(v,{method:"DELETE",headers:ut(e.vidfarmApiKey)}).catch(()=>{})}function RS(m){let v=new URL(window.location.href);m.length?v.searchParams.set("tracers",m.join(",")):v.searchParams.delete("tracers"),window.history.replaceState({},"",v.toString()),window.dispatchEvent(new CustomEvent("vidfarm:editor-tracers-changed",{detail:{tracers:m}}))}function ma(m){let v=tr(m),w=window.__vidfarmEditorTracers;if(w){w.set(v);return}Ie(v),RS(v)}function xS(){let m=window.__vidfarmEditorTracers;if(m)return m.add();let v=UF(e.template.templateSlug,Y);return ma([v,...Y]),v}function bS(m){let v=window.__vidfarmEditorTracers?.get()??Y,w=m?FF(m,v):null,b=window.__vidfarmEditorTracers;return b?b.add(w??void 0):w?(ma([w,...v.filter(F=>F!==w)]),w):xS()}function ox(m){let v=m.trim();if(!v)return;let w=window.__vidfarmEditorTracers;w?w.add(v):Y.includes(v)||ma([v,...Y]),Jt&&ft(Jt.id,b=>({...b,tracers:[v,...b.tracers.filter(F=>F!==v)],updatedAt:new Date().toISOString()}))}function ix(m){let v=window.__vidfarmEditorTracers;if(v){v.remove(m);return}let w=Y.filter(b=>b!==m);ma(w)}(0,k.useEffect)(()=>{RS(Y)},[Y]),(0,k.useEffect)(()=>{let m=s.current;if(!m)return;let v=()=>{a.current=pF(m),a.current||(l.current=!1)};return v(),m.addEventListener("scroll",v,{passive:!0}),()=>{m.removeEventListener("scroll",v)}},[]),(0,k.useLayoutEffect)(()=>{let m=s.current;if(!m)return;let v=c.current!==g;c.current=g,(v||l.current||a.current)&&(m.scrollTo({top:m.scrollHeight,behavior:"auto"}),a.current=!0,l.current=!1)},[Xf,g]),(0,k.useEffect)(()=>()=>{u.current?.abortController.abort(),u.current=null;for(let m of f.current.values())m.timeoutId!==null&&window.clearTimeout(m.timeoutId),m.abortController?.abort();f.current.clear()},[]),(0,k.useEffect)(()=>{if(!M)return;let m=()=>A(null);return document.addEventListener("click",m),window.addEventListener("resize",m),window.addEventListener("scroll",m,!0),()=>{document.removeEventListener("click",m),window.removeEventListener("resize",m),window.removeEventListener("scroll",m,!0)}},[M]),(0,k.useEffect)(()=>{let m=()=>{if(document.visibilityState!=="visible"||!navigator.onLine)return;let v=Date.now();for(let w of f.current.values())w.inFlight||w.nextPollAt!==null&&w.nextPollAt<=v&&w.runPoll&&ep(w,w.runPoll,w.nextPollAt-v)};return window.addEventListener("online",m),document.addEventListener("visibilitychange",m),()=>{window.removeEventListener("online",m),document.removeEventListener("visibilitychange",m)}},[]);function sx(m){if(Jt)return Jt.id;let v=new Date().toISOString(),w=IR(),b={id:w,templateId:e.template.templateId,title:Uf(m||""),createdAt:v,updatedAt:v,lastMessageAt:null,messageCount:0,tracers:tr(Y),messages:[]};return h.current=[b,...h.current],T(F=>[b,...F]),S(w),w}function Zf(m){let v=new Date().toISOString(),w=tr(m?.tracers??Y),b=IR(),F={id:b,templateId:e.template.templateId,title:m?.title||"New chat",createdAt:v,updatedAt:v,lastMessageAt:null,messageCount:0,tracers:w,messages:[]};return h.current=[F,...h.current],T(K=>[F,...K]),m?.activate!==!1&&(S(b),N(""),x([]),j(null)),A(null),b}function kS(){Zf(),bt(!1)}function ax(m){let v=_.find(b=>b.id===m);if(!v||!window.confirm(`Delete conversation "${v.title}"?`))return;let w=_.filter(b=>b.id!==m);h.current=h.current.filter(b=>b.id!==m);for(let[b,F]of f.current.entries())F.threadId===m&&ha(b);T(w),g===m&&S(w[0]?.id??null),j(null),A(null),rx(m)}function ft(m,v){let w=HF(h.current.map(b=>b.id===m?v(b):b));h.current=w,T(w)}function lx(m,v){let w=tr(v);ft(m,F=>({...F,tracers:lS(F.tracers,w),updatedAt:new Date().toISOString()}));let b=h.current.find(F=>F.id===m);b&&Rc({...b,tracers:lS(b.tracers,w),updatedAt:new Date().toISOString()},{tracers:lS(b.tracers,w)})}function NS(m,v){let w=m.trim();return w?h.current.find(b=>!b.hiddenFromView&&b.id!==v&&b.tracers.includes(w))?.id??null:null}function cx(m,v){let w=NS(m);return w||Zf({tracers:[m],title:v?.title||`Tracer ${m}`,activate:v?.activate??!1})}function ux(m){let v=m.toLowerCase();return/(?:own|separate|different|new)\s+(?:tracer\s+and\s+)?chat\s+threads?/.test(v)||/chat\s+threads?.{0,80}(?:own|separate|different|new)\s+tracers?/.test(v)||/each.{0,80}(?:own|separate|different|new).{0,80}chat\s+threads?/.test(v)||/(?:own|separate|different|new)\s+tracers?/.test(v)||/(?:each|every|per|one\s+per).{0,80}(?:own|separate|different|new).{0,80}tracers?/.test(v)||/(?:own|separate|different|new)\s+tracers?.{0,80}(?:each|every|per|outputs?|pieces?|posts?|jobs?|generations?)/.test(v)||/(?:outputs?|pieces?|posts?|jobs?|generations?).{0,80}(?:own|separate|different|new)\s+tracers?/.test(v)}function dx(m){let v=NS(m.tracer,m.sourceThreadId);if(!v&&!m.shouldCreateThread)return null;let w=v??cx(m.tracer,{title:`Tracer ${m.tracer}`,activate:!1});if(!w||w===m.sourceThreadId)return null;let b=$f("assistant"),F=new Date().toISOString(),K=m.job.status==="succeeded"||m.job.status==="failed"||m.job.status==="cancelled"?Df(m.job):hR(m.job),z=m.job.status==="succeeded"||m.job.status==="failed"||m.job.status==="cancelled"?null:`Job ${m.job.job_id} is being tracked. ${tp()}`,le={id:b,role:"assistant",text:K,attachments:[],httpExchanges:m.httpExchange?[m.httpExchange]:[],statusText:z,isPending:!1};ft(w,ce=>({...ce,updatedAt:F,messages:[...ce.messages,le]}));let pe=h.current.find(ce=>ce.id===w);return pe&&nx({threadId:w,templateId:pe.templateId,title:pe.title,tracers:pe.tracers,messages:[le]}),{threadId:w,messageId:b}}function fx(m){let v=_.find(F=>F.id===m);if(!v)return;let w=window.prompt("Thread tracers, comma separated",v.tracers.join(", "));if(w===null)return;let b=tr(w.split(","));ft(m,F=>({...F,tracers:b,updatedAt:new Date().toISOString()})),Rc(v,{tracers:b}),A(null)}function px(m){let v=_.find(F=>F.id===m);if(!v||!window.confirm(`Archive conversation "${v.title}"? Its tracer links will be prefixed with archived_.`))return;let b=tr(v.tracers.map(OF));ft(m,F=>({...F,tracers:b,updatedAt:new Date().toISOString()})),Rc(v,{tracers:b,archived:!0}),A(null)}function mx(m){let v=_.find(b=>b.id===m);if(!(!v||!window.confirm(`Remove conversation "${v.title}" from this frontend view? The thread and tracer links stay available; Delete removes the thread completely.`))){for(let[b,F]of f.current.entries())F.threadId===m&&ha(b);if(ft(m,b=>({...b,hiddenFromView:!0,updatedAt:new Date().toISOString()})),g===m){let b=Jf.find(F=>F.id!==m);S(b?.id??null)}A(null),j(null),Rc(v,{hiddenFromView:!0})}}async function hx(m){try{if(navigator.clipboard?.writeText)await navigator.clipboard.writeText(m);else{let v=document.createElement("textarea");v.value=m,v.setAttribute("readonly",""),v.style.position="fixed",v.style.opacity="0",document.body.appendChild(v),v.select(),document.execCommand("copy"),document.body.removeChild(v)}j(null)}catch{j("Unable to copy chat ID.")}finally{A(null)}}function gx(m,v){if(M?.threadId===m){A(null);return}let w=v.getBoundingClientRect(),b=148;A({threadId:m,top:w.bottom+6,left:Math.max(8,Math.min(window.innerWidth-b-8,w.right-b))})}function ha(m){let v=f.current.get(m);v&&(v.timeoutId!==null&&window.clearTimeout(v.timeoutId),v.abortController?.abort(),f.current.delete(m))}function ga(m,v,w){let b=f.current.get(m);b&&ep(b,v,w)}function ep(m,v,w){m.timeoutId!==null&&window.clearTimeout(m.timeoutId);let b=Math.max(_R,w);m.nextPollAt=Date.now()+b,m.timeoutId=window.setTimeout(()=>{m.timeoutId=null,v()},b)}function Yi(){return f.current.size>=yR?hF:gR}function Ki(m=Yi()){if(m>=6e4){let v=Math.round(m/6e4);return`${v} min${v===1?"":"s"}`}return`${Math.round(m/1e3)}s`}function tp(m=Yi()){return f.current.size>=yR?`Many renders are active, so the next check is in ${Ki(m)}.`:`Checking again gently every ${Ki(m)}.`}function yx(){let m=Yi();if(m===gR)return;let v=Date.now();for(let w of f.current.values()){if(w.inFlight||!w.runPoll)continue;(w.nextPollAt===null?0:w.nextPollAt-v)<m&&ep(w,w.runPoll,m)}}function Sx(m){let v=Math.max(m,p.current.nextAvailableAt);return p.current.nextAvailableAt=v+gF,v-m}function np(m){let v=vR(m.threadId,m.assistantMessageId,m.jobId);if(f.current.has(v))return;f.current.set(v,{timeoutId:null,abortController:null,runPoll:null,inFlight:!1,nextPollAt:null,lastPollAt:null,attempts:0,threadId:m.threadId});let w=async()=>{let K=f.current.get(v);if(!K||K.inFlight)return;let z=Date.now(),le=Yi();if(K.lastPollAt!==null&&z-K.lastPollAt<le){ga(v,w,le-(z-K.lastPollAt));return}if(K.attempts>=SR){ft(m.threadId,ce=>({...ce,updatedAt:new Date().toISOString(),messages:ce.messages.map(ue=>ue.id===m.assistantMessageId?{...ue,statusText:"Background polling stopped after multiple checks. Open the job route when you want to refresh again."}:ue)})),ha(v);return}if(document.visibilityState!=="visible"||!navigator.onLine){ga(v,w,le);return}let pe=Sx(Date.now());if(pe>0){ga(v,w,pe);return}K.inFlight=!0,K.lastPollAt=z,K.nextPollAt=null,K.attempts+=1,K.abortController=new AbortController;try{ft(m.threadId,Fe=>({...Fe,updatedAt:new Date().toISOString(),messages:Fe.messages.map(Z=>Z.id===m.assistantMessageId?{...Z,statusText:`Job ${m.jobId} is being tracked. ${tp(le)}`}:Z)}));let ce=m.primitiveId||yF(m.sourceRequestUrl)?`/api/v1/primitives/jobs/${encodeURIComponent(m.jobId)}`:`/api/v1/templates/${encodeURIComponent(e.template.templateId)}/jobs/${encodeURIComponent(m.jobId)}`,ue=await fetch(ce,{method:"GET",headers:ut(e.vidfarmApiKey),signal:K.abortController.signal}),cn=await ue.json().catch(()=>null),ya=Object.fromEntries(ue.headers.entries()),W=$i(cn);if(ft(m.threadId,Fe=>({...Fe,updatedAt:new Date().toISOString(),messages:Fe.messages.map(Z=>{if(Z.id!==m.assistantMessageId)return Z;let ve=mF(Z.httpExchanges,Cc({explanation:`Automatic ${Ki(le)} job status check for ${m.jobId}`,pollJobId:m.jobId,pollMode:"automatic",request:{method:"GET",url:ce,headers:Object.fromEntries(ut(e.vidfarmApiKey).entries())},result:{status:ue.status,statusText:ue.statusText,headers:ya,body:cn}})),ke=W?W.status==="succeeded"?`Render ${W.job_id} succeeded.`:W.status==="failed"||W.status==="cancelled"?`Render ${W.job_id} ${W.status}.${W.error?.message?` ${W.error.message}`:""}`:`Render ${W.job_id} is ${W.status}. Next check in ${Ki(le)}.`:`Render ${m.jobId} checked. Next check in ${Ki(le)}.`;return{...Z,httpExchanges:ve,statusText:ke,text:W&&(W.status==="succeeded"||W.status==="failed"||W.status==="cancelled")?Ic(Z.text,Df(W)):Z.text}})})),W&&(W.status==="succeeded"||W.status==="failed"||W.status==="cancelled")){ha(v);return}}catch(ce){if(ce instanceof DOMException&&ce.name==="AbortError")return;ft(m.threadId,ue=>({...ue,updatedAt:new Date().toISOString(),messages:ue.messages.map(cn=>cn.id===m.assistantMessageId?{...cn,statusText:`Automatic polling paused after an error. It will retry in ${Ki()}.`}:cn)}))}finally{let ce=f.current.get(v);if(!ce)return;ce.inFlight=!1,ce.abortController=null,ce.attempts<SR&&ce.timeoutId===null&&f.current.has(v)&&ga(v,w,Yi())}},b=f.current.get(v);b&&(b.runPoll=w),f.current.get(v)&&(ga(v,w,m.initialDelayMs??Yi()),yx())}function _x(m){for(let v of m.messages)if(!(v.role!=="assistant"||!v.httpExchanges?.length))for(let w of v.httpExchanges){if(w.request.method!=="POST")continue;let b=$i(w.result.body),F=vR(m.id,v.id,b?.job_id??"");!b||fa(b.status)||f.current.has(F)||v.httpExchanges.some(z=>{let le=$i(z.result.body);return le?.job_id===b.job_id&&fa(le.status)})||np({threadId:m.id,assistantMessageId:v.id,jobId:b.job_id,tracer:b.tracer,initialStatus:b.status,primitiveId:b.primitive_id,sourceRequestUrl:w.request.url,initialDelayMs:_R})}}async function rp(m){if(!m.length)return;j(null);let v=[],w=null;for(let b of m)try{let F=await YR({apiKey:e.vidfarmApiKey,file:b,folderPath:UR}),K=await qR({attachment:F,file:b,currentInlineBytes:VR([...U,...v])});v.push(K)}catch(F){w=F instanceof Error?F.message:"Unable to upload attachment."}w&&v.length===0&&j(w),v.length&&(x(b=>[...b,...v]),w&&j(w))}async function vx(m){let v=Array.from(m.target.files??[]);await rp(v),m.target.value=""}async function Ex(m){let v=Array.from(m.clipboardData.files??[]).filter(w=>w.size>0);v.length&&(m.preventDefault(),await rp(v))}async function Tx(m){m.preventDefault(),Q(!1);let v=Array.from(m.dataTransfer.files??[]).filter(w=>w.size>0);v.length&&await rp(v)}async function Ix(m,v,w){let b=w??{},F=e.vidfarmApiKey,K=window.location.origin,z=ut(F,"application/json"),le=ut(F),pe=Z=>new Promise(ve=>setTimeout(ve,Z)),ce=(Z,ve)=>{ft(m,ke=>({...ke,updatedAt:new Date().toISOString(),messages:ke.messages.map(Ne=>Ne.id===v?{...Ne,isPending:!1,statusText:Z??Ne.statusText,text:ve?Ic(Ne.text,ve):Ne.text}:Ne)}))},ue=async Z=>{let ve=await Z.text();try{return ve?JSON.parse(ve):null}catch{return null}},cn=async Z=>{let ve=Date.now()+3e5;for(;;){let ke=await fetch(new URL(`/api/v1/videos/${encodeURIComponent(Z)}`,K),{headers:le}),Ne=await ue(ke),Be=String(Ne?.status??"");if(Be==="ready")return Ne;if(Be==="failed")throw new Error(`source video download failed${Ne?.error?`: ${Ne.error}`:""}.`);if(Date.now()>ve)throw new Error("source video download timed out.");await pe(5e3)}},ya=Z=>{let ve=Ee=>typeof Ee=="string"&&Ee.trim()?Ee.trim():null,ke=Z?.result&&typeof Z.result=="object"?Z.result:{},Ne=ke.output&&typeof ke.output=="object"?ke.output:ke,Be=ve(Ne?.primary_file_url)??ve(Ne?.video?.file_url)??ve(Ne?.image?.file_url)??ve(Ne?.render?.output_url);if(Be)return Be;if(Array.isArray(Ne?.files))for(let Ee of Ne.files){let Le=ve(typeof Ee=="string"?Ee:Ee?.file_url??Ee?.url);if(Le)return Le}if(Array.isArray(Z?.artifacts))for(let Ee of Z.artifacts){let Le=ve(Ee?.public_url);if(Le)return Le}return null},W=async Z=>{let ve=Date.now()+48e4;for(;;){await pe(5e3);let ke=await fetch(new URL(`/api/v1/user/me/jobs/${encodeURIComponent(Z)}`,K),{headers:le}),Ne=await ue(ke),Be=String(Ne?.status??""),Ee=ya(Ne);if(Ee)return Ee;if(Be==="failed"||Be==="cancelled")throw new Error(`generation ${Be}.`);if(Date.now()>ve)throw new Error("generation timed out.")}},Fe=async(Z,ve)=>{let ke=await(await fetch(Z)).blob(),Ne=await fetch(new URL("/discover/templates/upload/presign",K),{method:"POST",headers:z,body:JSON.stringify({file_name:"generated.mp4",content_type:"video/mp4",size_bytes:ke.size})}),Be=await ue(Ne);if(!Ne.ok)throw new Error(Be?.error||`upload presign failed (${Ne.status})`);let Ee=Be?.storage_key,Le=Be?.file_name||"generated.mp4";if(Be?.transport==="presigned"&&Be?.upload?.url){let Oe=await fetch(Be.upload.url,{method:Be.upload.method||"PUT",headers:Be.upload.headers||{},body:ke});if(!Oe.ok)throw new Error(`upload failed (${Oe.status})`)}else{let Oe=new FormData;Oe.append("file",ke,"generated.mp4");let Xt=await fetch(new URL(Be?.upload?.url||"/discover/templates/upload",K),{method:"POST",headers:le,body:Oe}),_t=await ue(Xt);if(!Xt.ok||!_t?.storage_key)throw new Error(_t?.error||`upload failed (${Xt.status})`);Ee=_t.storage_key,Le=_t.file_name||"generated.mp4"}if(!Ee)throw new Error("upload did not return a storage key.");let ho=await fetch(new URL("/discover/templates",K),{method:"POST",headers:z,body:JSON.stringify({upload:{storage_key:Ee,file_name:Le},title:ve,origin:"raw"})}),Ut=await ue(ho);if(!ho.ok)throw new Error(Ut?.error||`ingest failed (${ho.status})`);return Ut};try{if(!F){ce(null,"\u26A0\uFE0F You need to be logged in to create a video.");return}let Z=b.mode==="replicate"?"replicate":b.mode==="generate"?"generate":null,ve,ke;if(Z==="replicate"){let Xt=(b.source_url??"").trim();if(!/^https?:\/\//i.test(Xt)){ce(null,"\u26A0\uFE0F I need a video URL (TikTok/YouTube/Instagram/X) to replicate.");return}ke=(b.instructions??"").trim()||null,ce("Fetching the source video\u2026");let _t=await fetch(new URL("/discover/templates",K),{method:"POST",headers:z,body:JSON.stringify({source_url:Xt})}),Fr=await ue(_t);if(!_t.ok)throw new Error(Fr?.error||`couldn't fetch that URL (${_t.status})`);ve=Fr?.status==="ready"?Fr:await cn(Fr?.inspiration_id)}else if(Z==="generate"){let Xt=(b.prompt??"").trim();if(!Xt){ce(null,"\u26A0\uFE0F Tell me what the video should be about and I'll create it.");return}ke=Xt,ce("Generating your video\u2026 (this can take a couple of minutes)");let _t=await fetch(new URL("/api/v1/primitives/videos/generate",K),{method:"POST",headers:z,body:JSON.stringify({tracer:`chat-create-${Date.now().toString(36)}`,payload:{prompt:Xt}})}),Fr=await ue(_t);if(!_t.ok)throw new Error(Fr?.error||`couldn't start generation (${_t.status})`);let Rx=await W(Fr?.job_id);ce("Building an editable template from the generated video\u2026");let op=await Fe(Rx,Xt.slice(0,80));ve=op?.status==="ready"?op:await cn(op?.inspiration_id)}else{ce(null,"\u26A0\uFE0F I couldn't tell whether to generate a new video or replicate a URL \u2014 try rephrasing.");return}let Ne=ve?.template_id,Be=ve?.inspiration_id;if(!Ne||!Be)throw new Error("the template wasn't created from the video.");ce(Z==="replicate"?"Recreating the scenes\u2026 (about a minute)":"Analyzing into an editable timeline\u2026");let Ee=await fetch(new URL(`/api/v1/inspirations/${encodeURIComponent(Be)}/decompose`,K),{method:"POST",headers:z,body:JSON.stringify({user_prompt:ke})});if(!Ee.ok){let Xt=await ue(Ee);throw new Error(Xt?.error||`scene analysis failed (${Ee.status})`)}ce("Finalizing your editable copy\u2026");let Le=await fetch(new URL("/api/v1/compositions",K),{method:"POST",headers:z,body:JSON.stringify({template_id:Ne})}),ho=await ue(Le);if(!Le.ok)throw new Error(ho?.error||`couldn't create an editable copy (${Le.status})`);let Ut=ho?.fork_id,Oe=`${K}/editor/${encodeURIComponent(Ne)}${Ut?`/fork/${encodeURIComponent(Ut)}`:""}`;ce("Your video is ready.",`\u2705 Your video is ready \u2014 [Open it in the editor](${Oe}).`)}catch(Z){ce(null,`\u26A0\uFE0F I couldn't finish creating the video: ${Z instanceof Error?Z.message:String(Z)}`)}}async function AS(){if(!CS)return;l.current=!0;let m=sx(I),v=new Date().toISOString(),w=h.current.find(pe=>pe.id===m),b={id:$f("user"),role:"user",text:I.trim(),attachments:U},F={id:$f("assistant"),role:"assistant",text:"",attachments:[],statusText:"Waiting for AI response\u2026",isPending:!0},K=w?.messages??[],z=xF([...K,b]);ft(m,pe=>({...pe,title:pe.messages.length===0?Uf(b.text):pe.title,updatedAt:v,messages:[...pe.messages,b,F]})),N(""),x([]),j(null),X(m),fe("Waiting for AI response\u2026");let le=new AbortController;u.current={abortController:le,threadId:m,assistantMessageId:F.id};try{let pe=JSON.stringify({messages:kF(z),thread_id:m,thread_template_id:w?.templateId??e.template.templateId,thread_title:K.length===0?Uf(b.text):w?.title??Uf(b.text),thread_tracers:Kf,client_context:nF(),user_message:{id:b.id,role:b.role,text:b.text,attachments:b.attachments.map(W=>({id:W.id,fileName:W.fileName,contentType:W.contentType,viewUrl:W.viewUrl}))},assistant_message:{id:F.id},template:{...e.template,tracers:Kf,defaultRequestTracer:IS,activeTracer:IS},cached_context:{...e.cachedContext,...NF(),...AF()}});Or("chat.send.attempt",{thread_id:m,template_id:e.template.templateId,message_count:z.length,attachment_count:b.attachments.length,text_length:b.text.length});let ce=Date.now(),ue=await fetch(e.apiUrl||"/api/v1/editor-chat",{method:"POST",headers:ut(e.vidfarmApiKey,"application/json"),signal:le.signal,body:pe});if(!ue.ok){let W=await ue.json().catch(()=>({}));throw po("chat.send.rejected",{thread_id:m,status:ue.status,error:typeof W?.error=="string"?W.error:null}),new Error(typeof W?.error=="string"?W.error:`Chat failed with status ${ue.status}.`)}Or("chat.send.stream_open",{thread_id:m,latency_ms:Date.now()-ce});let cn=new Map,ya=ux(b.text);await MF(ue,{onDelta:W=>{fe("AI is responding\u2026"),ft(m,Fe=>({...Fe,updatedAt:new Date().toISOString(),messages:Fe.messages.map(Z=>Z.id===F.id?{...Z,text:`${Z.text}${W}`,statusText:"AI is responding\u2026",isPending:!1}:Z)}))},onStatus:W=>{fe(W),ft(m,Fe=>({...Fe,messages:Fe.messages.map(Z=>Z.id===F.id?{...Z,statusText:W,isPending:!Z.text}:Z)}))},onToolCall:W=>{cn.set(W.toolCallId,{toolName:W.toolName,args:W.args}),ft(m,Fe=>({...Fe,updatedAt:new Date().toISOString(),messages:Fe.messages.map(Z=>Z.id===F.id?{...Z,toolExchanges:[...Z.toolExchanges??[],{toolCallId:W.toolCallId,toolName:W.toolName,args:ji(W.args),status:"pending"}]}:Z)}))},onToolResult:W=>{let Fe=FR(W.result),Z=cn.get(W.toolCallId);if(W.toolName==="create_video"&&Ix(m,F.id,W.result),W.toolName==="frontend_action"){let Ee=W.result;if(Ee?.action==="add_tracer")bS(Ee.tracer??void 0);else if(Ee?.action==="remove_tracer"&&Ee.tracer)ix(Ee.tracer);else if(Ee?.action==="activate_tracer"&&Ee.tracer)ox(Ee.tracer);else if(Ee?.action==="create_thread"){let Le=Ee.tracer?bS(Ee.tracer):xS();Zf({tracers:Le?[Le]:[],title:Le?`Tracer ${Le}`:"New chat",activate:!1})}}let ve=W.result,ke=$i(ve?.response?.body),Ne=ve?.request&&ve?.response?Cc({explanation:ve.explanation??null,request:ve.request,result:ve.response}):void 0,Be=ve?.request?.method==="POST"&&ke?.tracer?dx({sourceThreadId:m,tracer:ke.tracer,job:ke,httpExchange:Ne,shouldCreateThread:ya}):null;Be&&ke&&!fa(ke.status)&&np({threadId:Be.threadId,assistantMessageId:Be.messageId,jobId:ke.job_id,tracer:ke.tracer,initialStatus:ke.status,primitiveId:ke.primitive_id,sourceRequestUrl:ve?.request?.url}),ft(m,Ee=>({...Ee,updatedAt:new Date().toISOString(),messages:Ee.messages.map(Le=>{if(Le.id!==F.id)return Le;let ho=(Le.toolExchanges??[]).map(_t=>_t.toolCallId===W.toolCallId?{..._t,result:Fe,status:typeof W.result?.error=="string"?"error":"complete"}:_t),Ut=W.result,Oe=$i(Ut?.response?.body),Xt=Ut?.request&&Ut?.response?[...Le.httpExchanges??[],Cc({explanation:Ut.explanation??null,request:Ut.request,result:Ut.response})]:Le.httpExchanges;if(Z&&cn.delete(W.toolCallId),Ut?.request?.method==="POST"&&Oe?.tracer){let _t=window.__vidfarmEditorTracers;_t?_t.add(Oe.tracer):ma([Oe.tracer,...Y.filter(Fr=>Fr!==Oe.tracer)]),lx(m,[Oe.tracer])}return Oe&&!Be&&!fa(Oe.status)&&np({threadId:m,assistantMessageId:F.id,jobId:Oe.job_id,tracer:Oe.tracer,initialStatus:Oe.status,primitiveId:Oe.primitive_id,sourceRequestUrl:Ut?.request?.url}),{...Le,toolExchanges:ho,httpExchanges:Xt,statusText:Oe&&!fa(Oe.status)?`Job ${Oe.job_id} is being tracked. ${tp()}`:Le.statusText,isPending:!1,text:Oe&&Ut?.request?.method==="POST"&&Ut?.response?.status===202?Ic(Le.text,hR(Oe)):Oe&&fa(Oe.status)||Oe?Ic(Le.text,Df(Oe)):Le.text}})}))},onError:W=>{po("chat.stream.error",{thread_id:m,message:W}),j(W),fe(null),ft(m,Fe=>({...Fe,messages:Fe.messages.filter(Z=>Z.id!==F.id)}))}}),Or("chat.stream.completed",{thread_id:m,duration_ms:Date.now()-ce}),ft(m,W=>({...W,updatedAt:new Date().toISOString(),messages:W.messages.map(Fe=>Fe.id===F.id?{...Fe,statusText:Fe.statusText?.includes("being tracked")?Fe.statusText:null,isPending:!1}:Fe)}))}catch(pe){if(pe instanceof DOMException&&pe.name==="AbortError"){nR("chat.send.aborted",{thread_id:m}),j(null),fe(null),ft(m,ce=>({...ce,updatedAt:new Date().toISOString(),messages:ce.messages.map(ue=>ue.id!==F.id?ue:!!(ue.text.trim()||ue.toolExchanges?.length||ue.httpExchanges?.length)?{...ue,statusText:"Stopped.",isPending:!1}:{...ue,text:"Stopped.",statusText:null,isPending:!1})}));return}po("chat.send.failed",{thread_id:m,message:pe instanceof Error?pe.message:String(pe)}),j(pe instanceof Error?pe.message:"Unable to send chat message."),fe(null),ft(m,ce=>({...ce,messages:ce.messages.map(ue=>ue.id===F.id?{...ue,text:pe instanceof Error?`Error: ${pe.message}`:"Error: Unable to send chat message.",statusText:null,isPending:!1}:ue)}))}finally{u.current?.assistantMessageId===F.id&&(u.current=null),X(pe=>pe===m?null:pe),fe(null)}}function wx(){fe("Stopping\u2026");let m=u.current;m&&ft(m.threadId,v=>({...v,updatedAt:new Date().toISOString(),messages:v.messages.map(w=>w.id===m.assistantMessageId?{...w,statusText:"Stopping\u2026"}:w)})),u.current?.abortController.abort()}(0,k.useEffect)(()=>()=>{u.current?.abortController.abort();for(let m of f.current.keys())ha(m);try{o?.setItem(r.threads,JSON.stringify(CR(Se.current,Ur.current)))}catch{}},[o,r]);function Cx(m){m.key==="Enter"&&!m.shiftKey&&(m.preventDefault(),AS())}let MS=(0,d.jsx)("div",{className:`vf-editor-chat-thread-list${t?" vf-editor-chat-thread-list-sidebar":""}`,role:"tablist","aria-label":"Conversation threads",children:Jf.length?Jf.map(m=>(0,d.jsxs)("div",{role:"tab","aria-selected":m.id===g,className:"vf-editor-chat-thread-chip","data-active":m.id===g?"true":"false",children:[(0,d.jsxs)("button",{type:"button",className:"vf-editor-chat-thread-chip-main",onClick:()=>{S(m.id),j(null),A(null),bt(!1)},children:[(0,d.jsx)("span",{className:"vf-editor-chat-thread-chip-title",children:m.title}),m.tracers.length?(0,d.jsxs)("span",{className:"vf-editor-chat-thread-chip-tracers",children:[m.tracers.slice(0,2).join(", "),m.tracers.length>2?` +${m.tracers.length-2}`:""]}):null]}),(0,d.jsx)("div",{className:"vf-editor-chat-thread-menu-wrap",children:(0,d.jsx)("button",{type:"button",className:"vf-editor-chat-thread-chip-menu","aria-label":`Actions for ${m.title}`,onClick:v=>{v.stopPropagation(),gx(m.id,v.currentTarget)},children:"..."})})]},m.id)):(0,d.jsx)("div",{className:"vf-editor-chat-thread-empty",children:"Start a chat to create your first conversation thread."})});return(0,d.jsxs)("div",{className:"vf-editor-chat-shell","data-mobile-open":ae?"true":"false","data-mobile-expanded":Te?"true":"false","data-layout":t?"brainstorm":"default",children:[(0,d.jsx)("button",{type:"button",className:"vf-editor-chat-mobile-fab","aria-label":"Open chat","aria-expanded":ae,onClick:()=>{St(!1),Re(!0)},children:(0,d.jsx)("svg",{viewBox:"0 0 24 24","aria-hidden":"true",focusable:"false",children:(0,d.jsx)("path",{d:"M20 11.5a7.5 7.5 0 0 1-9.8 7.1L4 20l1.5-5.3A7.5 7.5 0 1 1 20 11.5Z"})})}),H?(0,d.jsx)("div",{className:"vf-editor-chat-error",role:"status",children:H}):null,(0,d.jsxs)("div",{className:`${t?"vf-editor-chat-body vf-editor-chat-brainstorm-layout":"vf-editor-chat-body"}${n?" has-sidebar":""}`,"data-history-open":ot||it?"true":"false",children:[n?(0,d.jsxs)("aside",{className:"vf-editor-chat-history-pane",children:[(0,d.jsx)("div",{className:"vf-editor-chat-history-header",children:(0,d.jsxs)("div",{className:"vf-editor-chat-history-header-main",children:[(0,d.jsxs)("a",{className:"vf-editor-chat-back-button",href:"/discover","aria-label":"Back to Discover",children:[(0,d.jsx)("svg",{viewBox:"0 0 20 20",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,d.jsx)("path",{d:"m12 4-6 6 6 6"})}),"Discover"]}),(0,d.jsx)("div",{className:"vf-editor-chat-history-kicker",children:"Chat history"})]})}),(0,d.jsx)("button",{type:"button",className:"vf-editor-chat-new-thread vf-editor-chat-new-thread-sidebar",onClick:kS,children:"New chat"}),MS]}):null,(0,d.jsxs)("div",{className:"vf-editor-chat-thread",children:[(0,d.jsxs)("div",{className:"vf-editor-chat-header",children:[(0,d.jsxs)("div",{className:"vf-editor-chat-header-row",children:[(0,d.jsx)("a",{className:"vf-editor-chat-back-button vf-editor-chat-back-button--header",href:"/discover","aria-label":"Back to Discover",children:(0,d.jsx)("svg",{viewBox:"0 0 20 20",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,d.jsx)("path",{d:"m12 4-6 6 6 6"})})}),(0,d.jsx)("button",{type:"button",className:"vf-editor-chat-history-icon","aria-label":ot?"Back to chat":"Open chat history","aria-pressed":ot,onClick:()=>{bt(m=>!m),In(!1)},children:ot?(0,d.jsx)("svg",{viewBox:"0 0 20 20",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,d.jsx)("path",{d:"m12 4-6 6 6 6"})}):(0,d.jsxs)("svg",{viewBox:"0 0 20 20",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,d.jsx)("circle",{cx:"10",cy:"10",r:"7.2"}),(0,d.jsx)("path",{d:"M10 6v4l2.6 1.6"})]})}),(0,d.jsx)("button",{type:"button",className:"vf-editor-chat-history-icon vf-editor-chat-branches-icon","aria-label":it?"Back to chat":"Open template forks","aria-pressed":it,onClick:()=>{In(m=>!m),bt(!1)},children:it?(0,d.jsx)("svg",{viewBox:"0 0 20 20",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,d.jsx)("path",{d:"m12 4-6 6 6 6"})}):(0,d.jsxs)("svg",{viewBox:"0 0 20 20",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,d.jsx)("circle",{cx:"5.5",cy:"4.5",r:"1.9"}),(0,d.jsx)("circle",{cx:"5.5",cy:"15.5",r:"1.9"}),(0,d.jsx)("circle",{cx:"14.5",cy:"8",r:"1.9"}),(0,d.jsx)("path",{d:"M5.5 6.4v7.2"}),(0,d.jsx)("path",{d:"M5.5 13.6c0-3.2 2.4-3.6 4.4-3.9 2-.3 4.6-.5 4.6-3.7"})]})}),(0,d.jsxs)("div",{className:"vf-editor-chat-header-titles",children:[(0,d.jsx)("div",{className:"vf-editor-chat-header-title",children:"Vidfarm"}),(0,d.jsx)("div",{className:"vf-editor-chat-header-subtitle",children:ot?"Chat history":it?"Template forks":e.template.templateTitle})]}),(0,d.jsx)("button",{type:"button",className:"vf-editor-chat-new-thread",onClick:kS,children:"New chat"}),(0,d.jsx)("button",{type:"button",className:"vf-editor-chat-expand","aria-label":Te?"Shrink chat":"Expand chat","aria-pressed":Te,onClick:()=>St(m=>!m),children:Te?(0,d.jsxs)("svg",{viewBox:"0 0 20 20","aria-hidden":"true",focusable:"false",children:[(0,d.jsx)("path",{d:"M16.5 8.5h-5v-5"}),(0,d.jsx)("path",{d:"M11.5 8.5 17 3"}),(0,d.jsx)("path",{d:"M3.5 11.5h5v5"}),(0,d.jsx)("path",{d:"M8.5 11.5 3 17"})]}):(0,d.jsxs)("svg",{viewBox:"0 0 20 20","aria-hidden":"true",focusable:"false",children:[(0,d.jsx)("path",{d:"M11.5 3.5h5v5"}),(0,d.jsx)("path",{d:"M16.5 3.5 11 9"}),(0,d.jsx)("path",{d:"M8.5 16.5h-5v-5"}),(0,d.jsx)("path",{d:"M3.5 16.5 9 11"})]})}),(0,d.jsx)("button",{type:"button",className:"vf-editor-chat-minimize","aria-label":"Minimize chat",onClick:()=>Re(!1),children:"\xD7"})]}),M&&qi?(0,Wi.createPortal)((0,d.jsxs)("div",{className:"vf-editor-chat-thread-menu",role:"menu",style:{top:M.top,left:M.left},onClick:m=>m.stopPropagation(),children:[(0,d.jsx)("button",{type:"button",onClick:()=>hx(qi.id),children:"Copy Chat ID"}),(0,d.jsx)("button",{type:"button",onClick:()=>fx(qi.id),children:"Edit tracers"}),(0,d.jsx)("button",{type:"button",onClick:()=>mx(qi.id),children:"Remove from view"}),(0,d.jsx)("button",{type:"button",onClick:()=>px(qi.id),children:"Archive thread"}),(0,d.jsx)("button",{type:"button","data-danger":"true",onClick:()=>ax(qi.id),children:"Delete"})]}),document.body):null]}),(0,d.jsx)("div",{className:"vf-editor-chat-viewport",ref:s,children:ot?(0,d.jsx)("div",{className:"vf-editor-chat-history-panel",children:MS}):it?(0,d.jsxs)("div",{className:"vf-editor-chat-history-panel vf-editor-chat-branches-panel",children:[(0,d.jsxs)("div",{className:"vf-editor-chat-branches-header",children:[(0,d.jsxs)("div",{className:"vf-editor-chat-branches-header-main",children:[(0,d.jsx)("div",{className:"vf-editor-chat-branches-kicker",children:"Forks"}),(0,d.jsxs)("div",{className:"vf-editor-chat-branches-title",children:[Dt?.length??0," fork",(Dt?.length??0)===1?"":"s"," of this template"]})]}),(0,d.jsx)("button",{type:"button",className:"vf-editor-chat-branches-refresh",onClick:()=>{Je({force:!0})},disabled:nr,"aria-label":"Refresh forks",children:nr?"Loading\u2026":"Refresh"})]}),Zo?(0,d.jsx)("div",{className:"vf-editor-chat-thread-empty",role:"status",children:Zo}):nr&&!Dt?(0,d.jsx)("div",{className:"vf-editor-chat-thread-empty",children:"Loading forks\u2026"}):Dt&&Dt.length?(0,d.jsx)("div",{className:"vf-editor-chat-thread-list",children:Dt.map(m=>{let v=$e===m.forkId,w=`/editor/${encodeURIComponent(e.template.templateId)}/fork/${encodeURIComponent(m.forkId)}`,b=m.title&&m.title.trim()?m.title:m.forkId,F=m.parentForkId?` \xB7 forked from ${m.parentForkId.slice(0,12)}${m.parentVersion?`#v${m.parentVersion}`:""}`:"",K=m.latestVersion&&m.latestVersion>0?` \xB7 v${m.latestVersion}`:"";return(0,d.jsx)("div",{role:"listitem",className:"vf-editor-chat-thread-chip","data-active":v?"true":"false",children:(0,d.jsxs)("a",{className:"vf-editor-chat-thread-chip-main vf-editor-chat-branch-chip-link",href:w,target:"_blank",rel:"noopener noreferrer",children:[(0,d.jsxs)("span",{className:"vf-editor-chat-thread-chip-title",children:[b,v?(0,d.jsx)("span",{className:"vf-editor-chat-branch-current-badge",children:"current"}):null]}),(0,d.jsxs)("span",{className:"vf-editor-chat-thread-chip-tracers",children:[m.visibility??"private",K,F]})]})},m.forkId)})}):(0,d.jsx)("div",{className:"vf-editor-chat-thread-empty",children:"No forks yet for this template."})]}):Xf.length?Xf.map(m=>(0,d.jsx)(QF,{message:m},m.id)):g&&E===g?(0,d.jsxs)("div",{className:"vf-editor-chat-empty",children:[(0,d.jsx)("div",{className:"vf-editor-chat-kicker",children:"Loading chat"}),(0,d.jsxs)("h2",{children:["Opening ",g]})]}):(0,d.jsxs)("div",{className:"vf-editor-chat-empty",children:[(0,d.jsx)("div",{className:"vf-editor-chat-kicker",children:"AI Copilot"}),(0,d.jsx)("h2",{children:t?"Start a new chat.":"Repurpose this video."}),(0,d.jsx)("p",{children:t?"Use the brainstorm tools to go from zero context to angles, hooks, and a strategy you can actually test.":"Use the brainstorm tools to turn this video into a native ad for your product, spot product-placement opportunities, and shape the timeline you can actually test. You can also connect from your own AI coding agent, including Claude Code or OpenAI Codex, and ask it to work against this composition."}),(0,d.jsx)("div",{className:"vf-editor-chat-empty-prompts","aria-label":"Example prompts",children:t?(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("div",{children:"I don't know where to start"}),(0,d.jsx)("div",{children:"Help me think of persuasive angles"}),(0,d.jsx)("div",{children:"Help me think of viral hooks"})]}):(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("div",{children:"I don't know where to start"}),(0,d.jsx)("div",{children:"Repurpose this video into a social media native ad for my product"}),(0,d.jsx)("div",{children:"Help me identify product placement opportunities in this video for my product"})]})})]})}),(0,d.jsx)("div",{className:"vf-editor-chat-footer",hidden:ot||it,children:(0,d.jsxs)("div",{className:"vf-editor-chat-composer","data-drop-target":ge?"true":"false",onDragEnter:m=>{m.preventDefault(),Q(!0)},onDragOver:m=>{m.preventDefault(),ge||Q(!0)},onDragLeave:m=>{m.preventDefault();let v=m.relatedTarget;v instanceof Node&&m.currentTarget.contains(v)||Q(!1)},onDrop:m=>{Tx(m)},children:[ge?(0,d.jsx)("div",{className:"vf-editor-chat-dropzone-hint",children:"Drop files to attach"}):null,U.length?(0,d.jsx)("div",{className:"vf-editor-chat-composer-attachments-strip",children:U.map(m=>(0,d.jsx)(VF,{attachment:m,onRemove:()=>x(v=>v.filter(w=>w.id!==m.id))},m.id))}):null,(0,d.jsxs)("div",{className:"vf-editor-chat-composer-row",children:[(0,d.jsx)("button",{type:"button",className:"vf-editor-chat-attach-button","aria-label":"Open upload drawer",onClick:()=>ie(!0),children:"\u{1F4CE}"}),(0,d.jsx)("textarea",{rows:1,placeholder:t?"Describe the offer, audience, or strategy problem you want help with...":"Ask it to call a route, inspect jobs, save config, or continue this thread...",className:"vf-editor-chat-input",value:I,onChange:m=>N(m.target.value),onKeyDown:Cx,onPaste:m=>{Ex(m)}}),(0,d.jsx)("button",{type:"button",className:"vf-editor-chat-send-button",onClick:()=>{if(Qf){wx();return}AS()},disabled:Qf?!1:!CS,children:Qf?"Stop":"Send"})]}),(0,d.jsx)("input",{ref:i,type:"file",accept:"image/*,video/*,audio/*,application/pdf,text/plain,text/markdown",multiple:!0,hidden:!0,onChange:m=>{vx(m)}})]})})]})]}),(0,d.jsx)(eB,{apiKey:e.vidfarmApiKey,open:V,onClose:()=>ie(!1),onConfirm:m=>x(v=>[...v,...m])})]})}var Tn=Cn(Tc(),1);rR();function tB(){let e=document.getElementById("page-runtime-boot");return e?.textContent?JSON.parse(e.textContent):null}function qf(e){let t=new Date;return t.setDate(t.getDate()+e),t.toISOString()}async function nB(e){if(!e.userId)return;let t=e.store.getState();if(!e.force&&t.channels.length&&t.channelsUpdatedAt)return;let n=new URLSearchParams({start_date:qf(-7),end_date:qf(30)}),r=await fetch(`/u/${encodeURIComponent(e.userId)}/calendar/feed?${n.toString()}`,{headers:{accept:"application/json"}}),o=await r.json().catch(()=>null);!r.ok||!o||(e.store.getState().setCalendarData({channels:Array.isArray(o.channels)?o.channels:[],posts:Array.isArray(o.posts)?o.posts:[],rangeStart:o.startDate||qf(-7),rangeEnd:o.endDate||qf(30),replaceRange:!0}),window.dispatchEvent(new CustomEvent("vidfarm:flockposter-cache-updated")))}function rB({boot:e}){let t=(0,Gi.useMemo)(()=>lR(e),[e]),n=tR(t,i=>i.boot.title),[r,o]=(0,Gi.useState)(null);return(0,Gi.useEffect)(()=>{t.getState().setHydratedAt(new Date().toISOString()),document.documentElement.dataset.reactRuntime="true",document.documentElement.dataset.reactRuntimePage=e.pageKind,document.title=n},[e.pageKind,t,n]),(0,Gi.useEffect)(()=>{if(!e.editorChat)return;let i=document.querySelector("[data-template-editor-chat-root]");o(i instanceof HTMLElement?i:null)},[e.editorChat]),e.editorChat&&r?(0,ZR.createPortal)((0,Tn.jsx)(Ds,{fallback:(0,Tn.jsx)(oB,{}),children:(0,Tn.jsx)(QR,{boot:e.editorChat})}),r):null}function oB(){return(0,Tn.jsxs)("div",{style:{display:"grid",placeItems:"center",height:"100%",padding:"24px",textAlign:"center",gap:"12px",color:"#5c6a82"},children:[(0,Tn.jsx)("div",{style:{fontSize:"0.72rem",fontWeight:800,letterSpacing:"0.14em",textTransform:"uppercase"},children:"Chat error"}),(0,Tn.jsx)("div",{style:{fontSize:"0.92rem"},children:"Something went wrong loading the chat. Reload the page to try again."}),(0,Tn.jsx)("button",{type:"button",onClick:()=>window.location.reload(),style:{marginTop:"4px",minHeight:"34px",padding:"0 16px",border:"1px solid rgba(191, 164, 109, 0.34)",borderRadius:"999px",background:"rgba(255, 255, 255, 0.92)",color:"#243041",fontWeight:700,cursor:"pointer"},children:"Reload"})]})}var Qo=tB(),ES=document.getElementById("page-runtime-root"),TS=aR(Qo?.userId??null),Yf=null;function tx(e={}){return!e.force&&Yf||(Yf=nB({userId:Qo?.userId??null,store:TS,force:e.force}).catch(()=>{})),Yf}window.__vidfarmFlockPosterCache={readSnapshot:()=>nS(Qo?.userId??null),ensureHydrated:tx,setChannelsData:e=>{TS.getState().setChannelsData(e),window.dispatchEvent(new CustomEvent("vidfarm:flockposter-cache-updated"))},setCalendarData:e=>{TS.getState().setCalendarData(e),window.dispatchEvent(new CustomEvent("vidfarm:flockposter-cache-updated"))}};tx();Or("page_runtime.boot",{has_boot:!!Qo,has_root:!!ES,page_kind:Qo?.pageKind??null,editor_chat_template_id:Qo?.editorChat?.template?.templateId??null});Qo&&ES&&(0,ex.createRoot)(ES).render((0,Tn.jsx)(Ds,{fallback:(0,Tn.jsx)(Tn.Fragment,{}),onError:e=>po("page_runtime.render_error",{message:e instanceof Error?e.message:String(e)}),children:(0,Tn.jsx)(rB,{boot:Qo})}));
|
|
45
|
+
`).map(h=>h.trim()).find(h=>h.startsWith("data:"));if(!c)continue;let u=c.slice(5).trim();if(u==="[DONE]")continue;let f;try{f=JSON.parse(u)}catch{continue}if(!f||typeof f!="object")continue;let p=f;if(p.type==="text-delta"&&typeof p.delta=="string")t.onDelta(p.delta);else if(p.type==="status"){let h=typeof p.status=="string"?p.status:typeof p.message=="string"?p.message:null;h&&t.onStatus&&t.onStatus(h)}else p.type==="tool-call"&&typeof p.toolCallId=="string"&&typeof p.toolName=="string"&&t.onToolCall?t.onToolCall({toolCallId:p.toolCallId,toolName:p.toolName,args:p.args&&typeof p.args=="object"?p.args:void 0}):p.type==="tool-result"&&typeof p.toolCallId=="string"&&typeof p.toolName=="string"&&t.onToolResult?t.onToolResult({toolCallId:p.toolCallId,toolName:p.toolName,result:p.result}):p.type==="error"&&t.onError&&t.onError?.(typeof p.errorText=="string"?p.errorText:typeof p.error?.message=="string"?p.error.message:"Unable to read assistant response.")}}}function PF(e){return{threads:`vidfarm-editor-chat-threads:${e}`,activeThread:`vidfarm-editor-chat-active-thread:${e}`}}function LF(){if(typeof window>"u")return null;try{return window.sessionStorage}catch{try{return window.localStorage}catch{return null}}}function IR(){return`thread-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function $f(e){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`${e}-${crypto.randomUUID()}`:`${e}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function tr(e){let t=new Set,n=[];for(let r of e){let o=r.trim();!o||t.has(o)||(t.add(o),n.push(o))}return n}function lS(...e){return tr(e.flat())}function OF(e){let t=e.trim();return!t||t.startsWith("archived_")?t:`archived_${t}`}function fS(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID().replace(/-/g,"").slice(-8):Math.random().toString(16).slice(2,10).padEnd(8,"0").slice(0,8)}function DF(e){return(e.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"tracer").slice(0,28)}function UF(e,t){let n=DF(e),r="";do r=`${n}-${fS()}`;while(t.includes(r));return r}function FF(e,t){let n=e.trim();if(!n)return"";if(/-[a-z0-9]{8}$/i.test(n))return n;let r=`${n}-${fS()}`;for(;t.includes(r);)r=`${n}-${fS()}`;return r}function zf(){let e=new URLSearchParams(window.location.search),t=[...e.getAll("tracers"),...e.getAll("tracer")],n=[];for(let r of t){let o=r.trim();if(!o)continue;let i=o.startsWith("[")&&o.endsWith("]")?o.slice(1,-1):o;n.push(...i.split(",").map(s=>s.trim().replace(/^["']|["']$/g,"")))}return tr(n)}function wR(){let e=new URLSearchParams(window.location.search);return(e.get("thread_id")||e.get("threadId")||e.get("chat_id")||e.get("chatId")||"").trim()}function Uf(e){let t=e.trim().replace(/\s+/g," ");return t?t.length>42?`${t.slice(0,42).trimEnd()}\u2026`:t:"New chat"}function CR(e,t){return e.map(n=>({id:n.id,templateId:n.templateId,title:n.title,createdAt:n.createdAt,updatedAt:n.updatedAt,lastMessageAt:n.lastMessageAt??null,messageCount:Math.max(n.messageCount??0,n.messages.length),tracers:n.tracers,hiddenFromView:n.hiddenFromView,messages:(n.id===t?n.messages.slice(-tF):[]).map(r=>({id:r.id,role:r.role,text:r.text,attachments:r.attachments.map(o=>({id:o.id,fileName:o.fileName,contentType:o.contentType,viewUrl:o.viewUrl})),toolExchanges:r.toolExchanges?.map(o=>({...o,args:ji(o.args),result:FR(o.result)})),httpExchanges:r.httpExchanges?.map(Cc)}))}))}function BF(e,t){if(!e)return[];try{let n=JSON.parse(e);return Array.isArray(n)?n.filter(r=>r&&typeof r.id=="string").map(r=>({id:r.id,templateId:typeof r.templateId=="string"&&r.templateId.trim()?r.templateId:t,title:typeof r.title=="string"&&r.title.trim()?r.title:"New chat",createdAt:typeof r.createdAt=="string"?r.createdAt:new Date().toISOString(),updatedAt:typeof r.updatedAt=="string"?r.updatedAt:new Date().toISOString(),lastMessageAt:typeof r.lastMessageAt=="string"?r.lastMessageAt:null,messageCount:Math.max(typeof r.messageCount=="number"?r.messageCount:0,Array.isArray(r.messages)?r.messages.length:0),tracers:tr(Array.isArray(r.tracers)?r.tracers.filter(o=>typeof o=="string"):[]),hiddenFromView:r.hiddenFromView===!0,messages:Array.isArray(r.messages)?r.messages.map(o=>({id:o.id,role:o.role,text:o.text,attachments:Array.isArray(o.attachments)?o.attachments:[],toolExchanges:Array.isArray(o.toolExchanges)?o.toolExchanges:[],httpExchanges:Array.isArray(o.httpExchanges)?o.httpExchanges:[]})):[]})):[]}catch{return[]}}function RR(e,t){return!e||typeof e.id!="string"?null:{id:e.id,templateId:typeof e.templateId=="string"&&e.templateId.trim()?e.templateId:t,title:typeof e.title=="string"&&e.title.trim()?e.title:"New chat",createdAt:typeof e.createdAt=="string"?e.createdAt:new Date().toISOString(),updatedAt:typeof e.updatedAt=="string"?e.updatedAt:new Date().toISOString(),lastMessageAt:typeof e.lastMessageAt=="string"?e.lastMessageAt:null,messageCount:Math.max(typeof e.messageCount=="number"?e.messageCount:0,Array.isArray(e.messages)?e.messages.length:0),tracers:tr(Array.isArray(e.tracers)?e.tracers.filter(n=>typeof n=="string"):[]),hiddenFromView:e.hiddenFromView===!0,messages:Array.isArray(e.messages)?e.messages.map(n=>({id:n.id,role:n.role,text:n.text,attachments:Array.isArray(n.attachments)?n.attachments:[],toolExchanges:Array.isArray(n.toolExchanges)?n.toolExchanges:[],httpExchanges:Array.isArray(n.httpExchanges)?n.httpExchanges:[]})):[]}}function xR(e,t){let n=new Map;for(let r of t){let o=e.find(i=>i.id===r.id);n.set(r.id,{...r,lastMessageAt:r.lastMessageAt??o?.lastMessageAt??null,messageCount:Math.max(r.messageCount??0,o?.messageCount??0,r.messages.length,o?.messages.length??0),messages:r.messages.length?r.messages:o?.messages??[]})}for(let r of e)n.has(r.id)||n.set(r.id,r);return[...n.values()].sort((r,o)=>Date.parse(o.updatedAt)-Date.parse(r.updatedAt))}function HF(e){return[...e].sort((t,n)=>Date.parse(n.updatedAt)-Date.parse(t.updatedAt))}function wc(e,t){return t.length?e.tracers.some(n=>t.some(r=>$F(n,r))):!0}function $F(e,t){let n=e.trim(),r=t.trim();return!n||!r?!1:n===r?!0:n.startsWith(`${r}-`)&&/-[a-z0-9]{8}$/i.test(n)}function zF(e){return(0,d.jsxs)("div",{className:"vf-editor-chat-attachment",children:[(0,d.jsx)("span",{className:"vf-editor-chat-attachment-name",children:e.attachment.fileName}),e.onRemove?(0,d.jsx)("button",{type:"button",className:"vf-editor-chat-attachment-remove","aria-label":"Remove attachment",onClick:e.onRemove,children:"\xD7"}):null]})}function yS(){return(0,d.jsxs)("svg",{viewBox:"0 0 20 20",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",focusable:"false",children:[(0,d.jsx)("path",{d:"M10 3v9"}),(0,d.jsx)("path",{d:"m6.5 8.5 3.5 3.5 3.5-3.5"}),(0,d.jsx)("path",{d:"M4 16h12"})]})}function jF(){return(0,d.jsxs)("svg",{viewBox:"0 0 20 20",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",focusable:"false",children:[(0,d.jsx)("path",{d:"M4.2 15.8c1.6.5 3.1-.1 3.7-1.7.6-1.4 1.8-2.1 3.5-2.1"}),(0,d.jsx)("path",{d:"m10.7 11.6 5.2-5.2a1.9 1.9 0 0 0-2.7-2.7L8 8.9"}),(0,d.jsx)("path",{d:"m7.9 9 3.1 3.1"}),(0,d.jsx)("path",{d:"M3.5 16.5c1.4.5 3.6.5 4.9-.8"})]})}function SS(){return(0,d.jsxs)("svg",{viewBox:"0 0 20 20",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",focusable:"false",children:[(0,d.jsx)("path",{d:"M8.4 11.6a3.2 3.2 0 0 0 4.5 0l2.2-2.2a3.2 3.2 0 0 0-4.5-4.5L9.4 6.1"}),(0,d.jsx)("path",{d:"M11.6 8.4a3.2 3.2 0 0 0-4.5 0L4.9 10.6a3.2 3.2 0 0 0 4.5 4.5l1.2-1.2"})]})}function _S(){return(0,d.jsxs)("svg",{viewBox:"0 0 20 20",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",focusable:"false",children:[(0,d.jsx)("rect",{x:"7",y:"7",width:"9",height:"9",rx:"2"}),(0,d.jsx)("path",{d:"M5 12H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h6a2 2 0 0 1 2 2v1"})]})}function Ff(e){return(0,d.jsx)("svg",{viewBox:"0 0 20 20",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",focusable:"false",style:{transform:e.open?"rotate(90deg)":"rotate(0deg)"},children:(0,d.jsx)("path",{d:"m7 4 6 6-6 6"})})}function KR(e){let t=e.label.trim().replace(/[\\/:*?"<>|]+/g,"-");if(t)return t;try{return new URL(e.url,window.location.href).pathname.split("/").filter(Boolean).pop()||"media"}catch{return"media"}}function bR(e,t=!1){if(typeof window>"u"||e.kind!=="image"||!e.url)return"";let n=new URL("/tools/image",window.location.origin),r=window.__vidfarmEditorTracers,i=(r?.get()??zf())[0]||(t?r?.add()??"":"");return i&&n.searchParams.set("tracer",i),n.searchParams.set("source_image_url",e.url),n.searchParams.set("source_image_name",e.label||KR(e)),n.toString()}function WF(e){let[t,n]=(0,k.useState)(!1),[r,o]=(0,k.useState)(""),{onClose:i}=e,s=e.gallery?.length?e.gallery:[e.preview],a=Math.max(0,s.findIndex(T=>T.url===e.preview.url)),[l,c]=(0,k.useState)(a),u=s[l]||e.preview,f=s.length>1,p=u.kind==="image",h=p&&bR(u,!1)||"/tools/image";(0,k.useEffect)(()=>{n(!0)},[]),(0,k.useEffect)(()=>{o("")},[u.url]);let y=async()=>{try{if(navigator.clipboard?.writeText)await navigator.clipboard.writeText(u.url);else{let T=document.createElement("textarea");T.value=u.url,T.style.position="fixed",T.style.opacity="0",document.body.appendChild(T),T.focus(),T.select(),document.execCommand("copy"),document.body.removeChild(T)}o("done")}catch{o("error")}window.setTimeout(()=>o(""),1600)},_=T=>{let g=bR(u,!0);if(!g){T.preventDefault();return}T.preventDefault(),window.open(g,"_blank","noopener,noreferrer")};return(0,k.useEffect)(()=>{let T=g=>{if(g.key==="Escape"){i();return}f&&(g.key==="ArrowLeft"?(g.preventDefault(),c(S=>(S-1+s.length)%s.length)):g.key==="ArrowRight"&&(g.preventDefault(),c(S=>(S+1)%s.length)))};return window.addEventListener("keydown",T),()=>window.removeEventListener("keydown",T)},[f,s.length,i]),t?(0,Wi.createPortal)((0,d.jsx)("div",{className:"vf-editor-chat-media-modal-backdrop",onClick:e.onClose,children:(0,d.jsxs)("div",{className:"vf-editor-chat-media-modal",onClick:T=>T.stopPropagation(),children:[(0,d.jsxs)("div",{className:"vf-editor-chat-media-modal-header",children:[(0,d.jsx)("a",{className:"vf-editor-chat-media-modal-link",href:u.url,target:"_blank",rel:"noopener noreferrer",children:f?`${u.label} (${l+1} of ${s.length})`:u.label}),(0,d.jsxs)("div",{className:"vf-editor-chat-media-modal-actions",children:[f?(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("button",{type:"button",className:"vf-editor-chat-media-modal-control",onClick:()=>c(T=>(T-1+s.length)%s.length),"aria-label":"Previous image",title:"Previous image",children:"\u2039"}),(0,d.jsx)("button",{type:"button",className:"vf-editor-chat-media-modal-control",onClick:()=>c(T=>(T+1)%s.length),"aria-label":"Next image",title:"Next image",children:"\u203A"})]}):null,p?(0,d.jsx)("a",{className:"vf-editor-chat-media-modal-control",href:h,target:"_blank",rel:"noopener noreferrer",onClick:_,"aria-label":"Open image editor",title:"Image edit",children:(0,d.jsx)(jF,{})}):null,(0,d.jsx)("a",{className:"vf-editor-chat-media-modal-control",href:u.url,download:KR(u),"aria-label":"Download media",title:"Download",children:(0,d.jsx)(yS,{})}),(0,d.jsx)("button",{type:"button",className:"vf-editor-chat-media-modal-control","data-state":r,onClick:()=>{y()},"aria-label":r==="done"?"Media URL copied":r==="error"?"Unable to copy media URL":"Copy media URL",title:r==="done"?"Copied":r==="error"?"Copy failed":"Copy link",children:(0,d.jsx)(SS,{})}),(0,d.jsx)("button",{type:"button",className:"vf-editor-chat-media-modal-control",onClick:e.onClose,"aria-label":"Close media preview",title:"Close",children:"\xD7"})]})]}),(0,d.jsx)("div",{className:"vf-editor-chat-media-modal-body",children:u.kind==="image"?(0,d.jsx)("img",{src:u.url,alt:u.label,className:"vf-editor-chat-media-modal-image"}):(0,d.jsx)("video",{src:u.url,className:"vf-editor-chat-media-modal-video",controls:!0,autoPlay:!0,playsInline:!0})})]})}),document.body):null}function GF(e){let[t,n]=(0,k.useState)(!1);return(0,d.jsx)("button",{type:"button",className:"vf-editor-chat-message-thumb-button is-image",onClick:()=>e.onOpenModal(e.preview,e.previews),"aria-label":`Preview ${e.preview.label}`,title:e.preview.label,"data-error":t?"true":"false",children:t?(0,d.jsx)("span",{className:"vf-editor-chat-message-thumb-fallback",children:"Preview unavailable"}):(0,d.jsx)("img",{src:e.preview.url,alt:e.preview.label,className:"vf-editor-chat-message-attachment-thumb",loading:"lazy",onError:()=>n(!0)})})}function kR(e){return(0,d.jsx)("div",{className:"vf-editor-chat-message-attachment-row",children:(0,d.jsxs)("button",{type:"button",className:"vf-editor-chat-message-thumb-button",onClick:()=>e.onOpenModal(e.preview),"aria-label":`Preview ${e.preview.label}`,children:[(0,d.jsx)("video",{src:e.preview.url,className:"vf-editor-chat-message-attachment-thumb vf-editor-chat-message-video-thumb",preload:"metadata",muted:!0,playsInline:!0}),(0,d.jsx)("span",{className:"vf-editor-chat-message-video-play","aria-hidden":"true"})]})})}function NR(e){return e.previews.length?(0,d.jsx)("div",{className:"vf-editor-chat-message-image-rail","aria-label":"Image previews",children:e.previews.map(t=>(0,d.jsx)(GF,{preview:t,previews:e.previews,onOpenModal:e.onOpenModal},t.url))}):null}function VF(e){return(0,d.jsxs)("div",{className:"vf-editor-chat-composer-attachment-item",children:[jf(e.attachment)?(0,d.jsx)("img",{src:e.attachment.viewUrl,alt:e.attachment.fileName,className:"vf-editor-chat-composer-attachment-thumb"}):(0,d.jsx)("div",{className:"vf-editor-chat-composer-attachment-file","aria-hidden":"true",children:e.attachment.fileName.slice(0,1).toUpperCase()}),(0,d.jsx)("div",{className:"vf-editor-chat-composer-attachment-meta",children:(0,d.jsx)("span",{className:"vf-editor-chat-composer-attachment-name",children:e.attachment.fileName})}),(0,d.jsx)("button",{type:"button",className:"vf-editor-chat-composer-attachment-remove","aria-label":`Remove ${e.attachment.fileName}`,onClick:e.onRemove,children:"\xD7"})]})}function qF(e){let[t,n]=(0,k.useState)(!1),[r,o]=(0,k.useState)(!1),i=Bf(e.exchange.request.body),s=Bf(e.exchange.result.body),a=e.exchange.request.url,l=a.length>52?`${a.slice(0,52).trimEnd()}...`:a,c=e.exchange.result.status>=400||!!e.exchange.result.error,u=e.exchange.result.status>=200&&e.exchange.result.status<300;return(0,k.useEffect)(()=>{o(!0)},[]),(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("div",{className:"vf-editor-chat-http-card",children:(0,d.jsxs)("button",{type:"button",className:"vf-editor-chat-http-card-header",onClick:()=>n(!0),"aria-label":`Open HTTP details for ${e.exchange.request.method} ${a}`,children:[(0,d.jsx)("span",{className:"vf-editor-chat-http-pill",children:e.exchange.request.method}),(0,d.jsx)("span",{className:"vf-editor-chat-http-url",title:a,children:l}),(0,d.jsxs)("span",{className:"vf-editor-chat-http-status","data-error":c?"true":"false","data-success":u?"true":"false",children:[e.exchange.result.status,e.exchange.result.statusText?` ${e.exchange.result.statusText}`:""]}),(0,d.jsx)("span",{className:"vf-editor-chat-http-expand","aria-hidden":"true",children:"+"})]})}),r&&t?(0,Wi.createPortal)((0,d.jsx)("div",{className:"vf-editor-chat-http-modal-backdrop",onClick:()=>n(!1),children:(0,d.jsxs)("div",{className:"vf-editor-chat-http-modal",onClick:f=>f.stopPropagation(),children:[(0,d.jsxs)("div",{className:"vf-editor-chat-http-modal-header",children:[(0,d.jsxs)("div",{className:"vf-editor-chat-http-modal-header-main",children:[(0,d.jsx)("span",{className:"vf-editor-chat-http-pill",children:e.exchange.request.method}),(0,d.jsx)("span",{className:"vf-editor-chat-http-modal-url",children:a}),(0,d.jsxs)("span",{className:"vf-editor-chat-http-status","data-error":c?"true":"false","data-success":u?"true":"false",children:[e.exchange.result.status,e.exchange.result.statusText?` ${e.exchange.result.statusText}`:""]})]}),(0,d.jsx)("button",{type:"button",className:"vf-editor-chat-http-modal-close",onClick:()=>n(!1),"aria-label":"Close HTTP details",children:"\xD7"})]}),(0,d.jsxs)("div",{className:"vf-editor-chat-http-card-body is-modal",children:[e.exchange.explanation?(0,d.jsx)("div",{className:"vf-editor-chat-http-note",children:e.exchange.explanation}):null,(0,d.jsxs)("div",{className:"vf-editor-chat-http-block",children:[(0,d.jsx)("div",{className:"vf-editor-chat-http-label",children:"URL"}),(0,d.jsx)("pre",{className:"vf-editor-chat-http-pre",children:a})]}),i?(0,d.jsxs)("div",{className:"vf-editor-chat-http-block",children:[(0,d.jsx)("div",{className:"vf-editor-chat-http-label",children:"Request"}),(0,d.jsx)("pre",{className:"vf-editor-chat-http-pre",children:i})]}):null,(0,d.jsxs)("div",{className:"vf-editor-chat-http-block",children:[(0,d.jsx)("div",{className:"vf-editor-chat-http-label",children:"Response"}),(0,d.jsx)("pre",{className:"vf-editor-chat-http-pre",children:e.exchange.result.error||s||"(empty)"})]}),Object.keys(e.exchange.result.headers).length?(0,d.jsxs)("div",{className:"vf-editor-chat-http-block",children:[(0,d.jsx)("div",{className:"vf-editor-chat-http-label",children:"Headers"}),(0,d.jsx)("pre",{className:"vf-editor-chat-http-pre",children:Bf(e.exchange.result.headers)})]}):null]})]})}),document.body):null]})}function AR(e){return typeof e=="string"?JSON.stringify(e):typeof e=="number"||typeof e=="boolean"?String(e):e===null?"null":JSON.stringify(e)}function vS(e){if(navigator.clipboard?.writeText)return navigator.clipboard.writeText(e);let t=document.createElement("textarea");return t.value=e,t.style.position="fixed",t.style.opacity="0",document.body.appendChild(t),t.focus(),t.select(),document.execCommand("copy"),document.body.removeChild(t),Promise.resolve()}function Dr(e){return(0,d.jsxs)("div",{className:"vf-editor-chat-json-line",style:{paddingLeft:`${e.depth*18+12}px`},children:[(0,d.jsx)("button",{type:"button",className:"vf-editor-chat-json-copy","aria-label":"Copy line",title:"Copy line",onClick:()=>e.onCopy(e.text),children:(0,d.jsx)(_S,{})}),(0,d.jsx)("span",{className:"vf-editor-chat-json-line-text",children:e.text})]})}function pS(e){let t=e.value,n=e.isLast?"":",";if(Array.isArray(t)){let r=e.path,o=e.collapsedPaths.has(r),i=`${e.linePrefix??""}[`;return t.length?o?(0,d.jsxs)("div",{className:"vf-editor-chat-json-toggle-row",children:[(0,d.jsx)("button",{type:"button",className:"vf-editor-chat-json-toggle-icon",onClick:()=>e.togglePath(r),"aria-label":"Expand JSON block",children:(0,d.jsx)(Ff,{open:!1})}),(0,d.jsx)(Dr,{text:`${e.linePrefix??""}[ \u2026 ]${n}`,depth:e.depth,onCopy:e.onCopy})]}):(0,d.jsxs)("div",{children:[(0,d.jsxs)("div",{className:"vf-editor-chat-json-toggle-row",children:[(0,d.jsx)("button",{type:"button",className:"vf-editor-chat-json-toggle-icon",onClick:()=>e.togglePath(r),"aria-label":"Collapse JSON block",children:(0,d.jsx)(Ff,{open:!0})}),(0,d.jsx)(Dr,{text:i,depth:e.depth,onCopy:e.onCopy})]}),t.map((s,a)=>(0,d.jsx)(pS,{value:s,depth:e.depth+1,path:`${r}.${a}`,isLast:a===t.length-1,collapsedPaths:e.collapsedPaths,togglePath:e.togglePath,onCopy:e.onCopy},`${r}:${a}`)),(0,d.jsx)(Dr,{text:`]${n}`,depth:e.depth,onCopy:e.onCopy})]}):(0,d.jsx)(Dr,{text:`${e.linePrefix??""}[]${n}`,depth:e.depth,onCopy:e.onCopy})}if(t&&typeof t=="object"){let r=Object.entries(t),o=e.path,i=e.collapsedPaths.has(o),s=`${e.linePrefix??""}{`;return r.length?i?(0,d.jsxs)("div",{className:"vf-editor-chat-json-toggle-row",children:[(0,d.jsx)("button",{type:"button",className:"vf-editor-chat-json-toggle-icon",onClick:()=>e.togglePath(o),"aria-label":"Expand JSON block",children:(0,d.jsx)(Ff,{open:!1})}),(0,d.jsx)(Dr,{text:`${e.linePrefix??""}{ \u2026 }${n}`,depth:e.depth,onCopy:e.onCopy})]}):(0,d.jsxs)("div",{children:[(0,d.jsxs)("div",{className:"vf-editor-chat-json-toggle-row",children:[(0,d.jsx)("button",{type:"button",className:"vf-editor-chat-json-toggle-icon",onClick:()=>e.togglePath(o),"aria-label":"Collapse JSON block",children:(0,d.jsx)(Ff,{open:!0})}),(0,d.jsx)(Dr,{text:s,depth:e.depth,onCopy:e.onCopy})]}),r.map(([a,l],c)=>{let u=`${JSON.stringify(a)}: `;return l&&typeof l=="object"?(0,d.jsx)(pS,{value:l,depth:e.depth+1,linePrefix:u,path:`${o}.${a}`,isLast:c===r.length-1,collapsedPaths:e.collapsedPaths,togglePath:e.togglePath,onCopy:e.onCopy},`${o}:${a}`):(0,d.jsx)(Dr,{text:`${u}${AR(l)}${c===r.length-1?"":","}`,depth:e.depth+1,onCopy:e.onCopy},`${o}:${a}`)}),(0,d.jsx)(Dr,{text:`}${n}`,depth:e.depth,onCopy:e.onCopy})]}):(0,d.jsx)(Dr,{text:`${e.linePrefix??""}{}${n}`,depth:e.depth,onCopy:e.onCopy})}return(0,d.jsx)(Dr,{text:`${e.linePrefix??""}${AR(t)}${n}`,depth:e.depth,onCopy:e.onCopy})}function JR(e){let[t,n]=(0,k.useState)(new Set),[r,o]=(0,k.useState)(""),i=a=>{n(l=>{let c=new Set(l);return c.has(a)?c.delete(a):c.add(a),c})},s=async a=>{try{await vS(a),o("done")}catch{o("error")}window.setTimeout(()=>o(""),1400)};return(0,d.jsxs)("div",{className:"vf-editor-chat-json-viewer",children:[(0,d.jsxs)("div",{className:"vf-editor-chat-json-toolbar",children:[(0,d.jsx)("span",{className:"vf-editor-chat-json-file",children:e.storageKey}),(0,d.jsx)("span",{className:"vf-editor-chat-json-copy-state","data-state":r,children:r==="done"?"Copied line":r==="error"?"Copy failed":"Hover a line to copy"})]}),(0,d.jsx)("div",{className:"vf-editor-chat-json-scroll",children:(0,d.jsx)(pS,{value:e.value,depth:0,path:"root",collapsedPaths:t,togglePath:i,onCopy:s})})]})}function YF(e){let[t,n]=(0,k.useState)(!1),[r,o]=(0,k.useState)(""),i=zR(e.artifact.url,`${e.artifact.label}.json`),s=Bf(e.data);(0,k.useEffect)(()=>{n(!0)},[]);let a=async()=>{try{await vS(s),o("done")}catch{o("error")}window.setTimeout(()=>o(""),1600)};return(0,k.useEffect)(()=>{let l=c=>{c.key==="Escape"&&e.onClose()};return window.addEventListener("keydown",l),()=>window.removeEventListener("keydown",l)},[e]),t?(0,Wi.createPortal)((0,d.jsx)("div",{className:"vf-editor-chat-media-modal-backdrop",onClick:e.onClose,children:(0,d.jsxs)("div",{className:"vf-editor-chat-json-modal",onClick:l=>l.stopPropagation(),children:[(0,d.jsxs)("div",{className:"vf-editor-chat-media-modal-header",children:[(0,d.jsx)("a",{className:"vf-editor-chat-media-modal-link",href:e.artifact.url,target:"_blank",rel:"noopener noreferrer",children:e.artifact.label}),(0,d.jsxs)("div",{className:"vf-editor-chat-media-modal-actions",children:[(0,d.jsx)("button",{type:"button",className:"vf-editor-chat-media-modal-control","data-state":r,onClick:()=>{a()},title:r==="done"?"Copied":r==="error"?"Copy failed":"Copy JSON","aria-label":r==="done"?"JSON copied":r==="error"?"Unable to copy JSON":"Copy JSON",children:(0,d.jsx)(_S,{})}),(0,d.jsx)("a",{className:"vf-editor-chat-media-modal-control",href:e.artifact.url,download:i,title:"Download JSON","aria-label":"Download JSON",children:(0,d.jsx)(yS,{})}),(0,d.jsx)("a",{className:"vf-editor-chat-media-modal-control",href:e.artifact.url,target:"_blank",rel:"noopener noreferrer",title:"Open raw JSON","aria-label":"Open raw JSON",children:(0,d.jsx)(SS,{})}),(0,d.jsx)("button",{type:"button",className:"vf-editor-chat-media-modal-control",onClick:e.onClose,"aria-label":"Close JSON preview",title:"Close",children:"\xD7"})]})]}),(0,d.jsx)("div",{className:"vf-editor-chat-json-modal-body",children:(0,d.jsx)(JR,{value:e.data,storageKey:e.artifact.label})})]})}),document.body):null}function KF(e){let[t,n]=(0,k.useState)(!1),[r,o]=(0,k.useState)(!1),[i,s]=(0,k.useState)(null),[a,l]=(0,k.useState)(null),[c,u]=(0,k.useState)(!1),f=async()=>{if(!(i!==null||c)){u(!0),l(null);try{let _=await(await fetch(e.artifact.url,{credentials:"omit"})).json();s(_)}catch(y){l(y instanceof Error?y.message:"Unable to load JSON artifact.")}finally{u(!1)}}},p=()=>{let y=!t;n(y),y&&f()},h=()=>{f(),o(!0)};return(0,d.jsxs)(d.Fragment,{children:[(0,d.jsxs)("div",{className:"vf-editor-chat-json-card",children:[(0,d.jsxs)("div",{className:"vf-editor-chat-json-card-head",children:[(0,d.jsxs)("div",{children:[(0,d.jsx)("div",{className:"vf-editor-chat-json-card-kicker",children:"JSON result"}),(0,d.jsx)("div",{className:"vf-editor-chat-json-card-title",children:e.artifact.label})]}),(0,d.jsxs)("div",{className:"vf-editor-chat-json-card-actions",children:[(0,d.jsx)("button",{type:"button",className:"vf-editor-chat-json-card-action",onClick:p,children:t?"Hide preview":"Preview JSON"}),(0,d.jsx)("button",{type:"button",className:"vf-editor-chat-json-card-action is-strong",onClick:h,children:"Open"})]})]}),t?(0,d.jsx)("div",{className:"vf-editor-chat-json-card-body",children:c?(0,d.jsx)("div",{className:"vf-editor-chat-json-state",children:"Loading JSON\u2026"}):a?(0,d.jsx)("div",{className:"vf-editor-chat-json-state is-error",children:a}):i!==null?(0,d.jsx)(JR,{value:i,storageKey:e.artifact.label}):null}):null]}),r&&i!==null?(0,d.jsx)(YF,{artifact:e.artifact,data:i,onClose:()=>o(!1)}):null]})}function XR(e){return e.format==="markdown"?(0,d.jsx)("div",{className:"vf-editor-chat-doc-markdown",dangerouslySetInnerHTML:{__html:HR(e.text)}}):(0,d.jsx)("pre",{className:"vf-editor-chat-doc-pre",children:e.text})}function JF(e){let[t,n]=(0,k.useState)(!1),[r,o]=(0,k.useState)(""),i=e.artifact.format==="markdown"?".md":".txt",s=zR(e.artifact.url,`${e.artifact.label}${i}`);(0,k.useEffect)(()=>{n(!0)},[]);let a=async()=>{try{await vS(e.text),o("done")}catch{o("error")}window.setTimeout(()=>o(""),1600)};return(0,k.useEffect)(()=>{let l=c=>{c.key==="Escape"&&e.onClose()};return window.addEventListener("keydown",l),()=>window.removeEventListener("keydown",l)},[e]),t?(0,Wi.createPortal)((0,d.jsx)("div",{className:"vf-editor-chat-media-modal-backdrop",onClick:e.onClose,children:(0,d.jsxs)("div",{className:"vf-editor-chat-json-modal",onClick:l=>l.stopPropagation(),children:[(0,d.jsxs)("div",{className:"vf-editor-chat-media-modal-header",children:[(0,d.jsx)("a",{className:"vf-editor-chat-media-modal-link",href:e.artifact.url,target:"_blank",rel:"noopener noreferrer",children:e.artifact.label}),(0,d.jsxs)("div",{className:"vf-editor-chat-media-modal-actions",children:[(0,d.jsx)("button",{type:"button",className:"vf-editor-chat-media-modal-control","data-state":r,onClick:()=>{a()},title:r==="done"?"Copied":r==="error"?"Copy failed":e.artifact.format==="markdown"?"Copy markdown":"Copy text","aria-label":r==="done"?"Document copied":r==="error"?"Unable to copy document":e.artifact.format==="markdown"?"Copy markdown":"Copy text",children:(0,d.jsx)(_S,{})}),(0,d.jsx)("a",{className:"vf-editor-chat-media-modal-control",href:e.artifact.url,download:s,title:e.artifact.format==="markdown"?"Download markdown":"Download text","aria-label":e.artifact.format==="markdown"?"Download markdown":"Download text",children:(0,d.jsx)(yS,{})}),(0,d.jsx)("a",{className:"vf-editor-chat-media-modal-control",href:e.artifact.url,target:"_blank",rel:"noopener noreferrer",title:"Open raw file","aria-label":"Open raw file",children:(0,d.jsx)(SS,{})}),(0,d.jsx)("button",{type:"button",className:"vf-editor-chat-media-modal-control",onClick:e.onClose,"aria-label":"Close document preview",title:"Close",children:"\xD7"})]})]}),(0,d.jsx)("div",{className:"vf-editor-chat-json-modal-body",children:(0,d.jsx)("div",{className:"vf-editor-chat-doc-viewer",children:(0,d.jsx)(XR,{text:e.text,format:e.artifact.format})})})]})}),document.body):null}function XF(e){let[t,n]=(0,k.useState)(!1),[r,o]=(0,k.useState)(!1),[i,s]=(0,k.useState)(null),[a,l]=(0,k.useState)(null),[c,u]=(0,k.useState)(!1),f=async()=>{if(!(i!==null||c)){u(!0),l(null);try{let _=await(await fetch(e.artifact.url,{credentials:"omit"})).text();s(_)}catch(y){l(y instanceof Error?y.message:"Unable to load document artifact.")}finally{u(!1)}}},p=()=>{let y=!t;n(y),y&&f()},h=()=>{f(),o(!0)};return(0,d.jsxs)(d.Fragment,{children:[(0,d.jsxs)("div",{className:"vf-editor-chat-json-card",children:[(0,d.jsxs)("div",{className:"vf-editor-chat-json-card-head",children:[(0,d.jsxs)("div",{children:[(0,d.jsx)("div",{className:"vf-editor-chat-json-card-kicker",children:e.artifact.format==="markdown"?"Markdown result":"Text result"}),(0,d.jsx)("div",{className:"vf-editor-chat-json-card-title",children:e.artifact.label})]}),(0,d.jsxs)("div",{className:"vf-editor-chat-json-card-actions",children:[(0,d.jsx)("button",{type:"button",className:"vf-editor-chat-json-card-action",onClick:p,children:t?"Hide preview":"Preview"}),(0,d.jsx)("button",{type:"button",className:"vf-editor-chat-json-card-action is-strong",onClick:h,children:"Open"})]})]}),t?(0,d.jsx)("div",{className:"vf-editor-chat-json-card-body",children:c?(0,d.jsx)("div",{className:"vf-editor-chat-json-state",children:"Loading document\u2026"}):a?(0,d.jsx)("div",{className:"vf-editor-chat-json-state is-error",children:a}):i!==null?(0,d.jsx)("div",{className:"vf-editor-chat-doc-viewer is-inline",children:(0,d.jsx)(XR,{text:i,format:e.artifact.format})}):null}):null]}),r&&i!==null?(0,d.jsx)(JF,{artifact:e.artifact,text:i,onClose:()=>o(!1)}):null]})}var QF=(0,k.memo)(function(t){let n=t.message.role==="assistant",r=t.message.text.trim().length>0,o=r?HR(t.message.text):"",[i,s]=(0,k.useState)(null),a=t.message.attachments.filter(jf),l=t.message.attachments.filter(uS),c=t.message.attachments.filter(_=>!jf(_)&&!uS(_)),u=r?lF(t.message.text,t.message.attachments.map(_=>_.viewUrl)):[],f=u.filter(_=>_.kind==="image"),p=u.filter(_=>_.kind==="video"),h=(t.message.httpExchanges??[]).flatMap(_=>{let T=$i(_.result.body);return T?WR(T):[]}).filter((_,T,g)=>g.findIndex(S=>S.url===_.url)===T),y=(t.message.httpExchanges??[]).flatMap(_=>{let T=$i(_.result.body);return T?GR(T):[]}).filter((_,T,g)=>g.findIndex(S=>S.url===_.url)===T);return(0,d.jsxs)("div",{className:`vf-editor-chat-message ${n?"is-assistant":"is-user"}`,children:[(0,d.jsx)("div",{className:"vf-editor-chat-message-meta",children:n?"Copilot":"You"}),(0,d.jsxs)("div",{className:"vf-editor-chat-bubble","data-pending":t.message.isPending?"true":"false",children:[t.message.attachments.length?(0,d.jsxs)("div",{className:"vf-editor-chat-message-attachments",children:[c.map(_=>(0,d.jsx)("div",{className:"vf-editor-chat-message-attachment-row",children:(0,d.jsx)("a",{className:"vf-editor-chat-message-preview-link",href:_.viewUrl,target:"_blank",rel:"noopener noreferrer",children:(0,d.jsx)(zF,{attachment:_})})},_.id)),(0,d.jsx)(NR,{previews:a.map(_=>({kind:"image",url:_.viewUrl,label:_.fileName})),onOpenModal:(_,T)=>s({preview:_,gallery:T})}),l.map(_=>(0,d.jsx)(kR,{preview:{kind:"video",url:_.viewUrl,label:_.fileName},onOpenModal:T=>s({preview:T,gallery:[T]})},_.id))]}):null,t.message.statusText?(0,d.jsxs)("div",{className:"vf-editor-chat-message-status","aria-live":"polite",children:[(0,d.jsx)("span",{className:"vf-editor-chat-status-dot"}),t.message.statusText]}):null,t.message.httpExchanges?.length?(0,d.jsx)("div",{className:"vf-editor-chat-http-list",children:t.message.httpExchanges.map((_,T)=>(0,d.jsx)(qF,{exchange:_},`${_.request.method}:${_.request.url}:${T}`))}):null,r?(0,d.jsx)("div",{className:"vf-editor-chat-message-body",dangerouslySetInnerHTML:{__html:o}}):t.message.isPending?(0,d.jsxs)("div",{className:"vf-editor-chat-message-loading","aria-hidden":"true",children:[(0,d.jsx)("span",{}),(0,d.jsx)("span",{}),(0,d.jsx)("span",{})]}):null,u.length?(0,d.jsxs)("div",{className:"vf-editor-chat-message-attachments",children:[(0,d.jsx)(NR,{previews:f,onOpenModal:(_,T)=>s({preview:_,gallery:T})}),p.map(_=>(0,d.jsx)(kR,{preview:_,onOpenModal:T=>s({preview:T,gallery:[T]})},_.url))]}):null,h.length?(0,d.jsx)("div",{className:"vf-editor-chat-json-list",children:h.map(_=>(0,d.jsx)(KF,{artifact:_},_.key))}):null,y.length?(0,d.jsx)("div",{className:"vf-editor-chat-json-list",children:y.map(_=>(0,d.jsx)(XF,{artifact:_},_.key))}):null]}),i?(0,d.jsx)(WF,{preview:i.preview,gallery:i.gallery,onClose:()=>s(null)}):null]})});function MR(e){if(!e||e<=0)return"Unknown size";let t=["B","KB","MB","GB"],n=e,r=0;for(;n>=1024&&r<t.length-1;)n/=1024,r+=1;return`${n>=10||r===0?n.toFixed(0):n.toFixed(1)} ${t[r]}`}function PR(e){return jf(e.file)?(0,d.jsx)("img",{className:"vf-editor-upload-file-thumb",src:e.file.viewUrl,alt:e.file.fileName}):uS(e.file)?(0,d.jsx)("video",{className:"vf-editor-upload-file-thumb",src:e.file.viewUrl,muted:!0,playsInline:!0}):(0,d.jsx)("div",{className:"vf-editor-upload-file-icon","aria-hidden":"true",children:e.file.fileName.slice(0,1).toUpperCase()})}function mo(e){return e.split("/").map(t=>t.trim()).filter(Boolean).join("/")}function Gf(e,t){return mo([e,t].filter(Boolean).join("/"))}function LR(e){let t=mo(e).split("/").filter(Boolean);return t.pop(),t.join("/")}function OR(e){return mo(e).split("/").filter(Boolean).at(-1)||"All files"}function ZF(e){let t=mo(e.currentFolder),n=t?`${t}/`:"",r=new Map;for(let o of e.folders){let i=mo(o);if(!i||t&&i===t||!i.startsWith(n))continue;let a=i.slice(n.length).split("/")[0];a&&r.set(a,Gf(t,a))}for(let o of e.files){let i=mo(o.folderPath??"");if(!i||t&&i===t||!i.startsWith(n))continue;let a=i.slice(n.length).split("/")[0];a&&r.set(a,Gf(t,a))}return Array.from(r.entries()).map(([o,i])=>({name:o,path:i})).sort((o,i)=>o.name.localeCompare(i.name))}function cS(e){return e.name==="share"?(0,d.jsxs)("svg",{viewBox:"0 0 24 24","aria-hidden":"true",focusable:"false",children:[(0,d.jsx)("path",{d:"M14 4h6v6"}),(0,d.jsx)("path",{d:"M10 14 20 4"}),(0,d.jsx)("path",{d:"M20 14v4a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h4"})]}):e.name==="link"?(0,d.jsxs)("svg",{viewBox:"0 0 24 24","aria-hidden":"true",focusable:"false",children:[(0,d.jsx)("path",{d:"M10 13a5 5 0 0 0 7.07 0l2.12-2.12a5 5 0 0 0-7.07-7.07L11 4.93"}),(0,d.jsx)("path",{d:"M14 11a5 5 0 0 0-7.07 0L4.81 13.12a5 5 0 0 0 7.07 7.07L13 19.07"})]}):(0,d.jsxs)("svg",{viewBox:"0 0 24 24","aria-hidden":"true",focusable:"false",children:[(0,d.jsx)("path",{d:"M3 6h18"}),(0,d.jsx)("path",{d:"M8 6V4h8v2"}),(0,d.jsx)("path",{d:"M19 6 18 20H6L5 6"}),(0,d.jsx)("path",{d:"M10 11v5"}),(0,d.jsx)("path",{d:"M14 11v5"})]})}function eB(e){let[t,n]=(0,k.useState)("my-files"),[r,o]=(0,k.useState)([]),[i,s]=(0,k.useState)([]),[a,l]=(0,k.useState)([]),[c,u]=(0,k.useState)(()=>new Set),[f,p]=(0,k.useState)([]),[h,y]=(0,k.useState)([]),[_,T]=(0,k.useState)(()=>new Set),[g,S]=(0,k.useState)(null),[E,R]=(0,k.useState)(!1),[M,A]=(0,k.useState)(""),[I,N]=(0,k.useState)(null),[U,x]=(0,k.useState)(null),[H,j]=(0,k.useState)(null),[he,X]=(0,k.useState)(null),[Ze,fe]=(0,k.useState)(null),de=(0,k.useRef)(null),D=(0,k.useRef)(null),ge=(0,k.useMemo)(()=>{let P=f.map(ie=>({...ie,recentSource:"generated"}));return[...h.map(ie=>({...ie,recentSource:"temporary"})),...P].sort((ie,Y)=>{let Ie=ie.createdAt?Date.parse(ie.createdAt):0;return(Y.createdAt?Date.parse(Y.createdAt):0)-Ie})},[f,h]),Q=t==="upload"?r:t==="my-files"?i.filter(P=>c.has(P.id)):t==="recents"?ge.filter(P=>_.has(P.id)):[];async function ae(){let P=await IF(e.apiKey);s(P.attachments),l(P.folders)}async function Re(P){R(!0);try{let[V,ie]=P?[await TR(e.apiKey,P),null]:await Promise.all([TR(e.apiKey),wF(e.apiKey)]);p(Y=>P?[...Y,...V.media]:V.media),ie&&y(ie.files),S(V.nextCursor),P||T(new Set)}finally{R(!1)}}(0,k.useEffect)(()=>{e.open&&(X(null),j(null),ae().catch(P=>X(P instanceof Error?P.message:"Unable to load My Files.")),Re().catch(P=>X(P instanceof Error?P.message:"Unable to load recent media.")))},[e.open]);function Te(){o([]),u(new Set),T(new Set),j(null),X(null),N(null),x(null),e.onClose()}async function St(P){try{if(navigator.clipboard?.writeText)await navigator.clipboard.writeText(P);else{let V=document.createElement("textarea");V.value=P,V.style.position="fixed",V.style.opacity="0",document.body.appendChild(V),V.focus(),V.select(),document.execCommand("copy"),document.body.removeChild(V)}j("File URL copied.")}catch{X("Unable to copy file URL.")}}async function ot(P,V){if(!P.length)return;X(null);let ie=[];for(let Y of P)try{if(j(`Uploading ${Y.name}...`),V==="upload"){let dt=await YR({apiKey:e.apiKey,file:Y,folderPath:UR}),J=await qR({attachment:dt,file:Y,currentInlineBytes:VR([...r,...ie])});ie.push(J);continue}let Ie=await TF({apiKey:e.apiKey,file:Y,folderPath:M,maxBytes:DR,limitLabel:"50 MB"});ie.push(Ie)}catch(Ie){X(Ie instanceof Error?Ie.message:"Upload failed.")}V==="upload"?(o(Y=>[...Y,...ie]),await Re().catch(Y=>X(Y instanceof Error?Y.message:"Unable to refresh recent files."))):V==="my-files"&&(await ae(),u(Y=>new Set([...Y,...ie.map(Ie=>Ie.id)]))),ie.length&&j(`${ie.length} file${ie.length===1?"":"s"} uploaded.`)}async function bt(P,V){let ie=V==="my-files"?`/api/v1/user/me/attachments/${encodeURIComponent(P.id)}`:`/api/v1/user/me/temporary-files/${encodeURIComponent(P.id)}`,Y=await fetch(ie,{method:"DELETE",headers:ut(e.apiKey,"application/json")}),Ie=await Y.json().catch(()=>({}));if(!Y.ok)throw new Error(Ie.error||"Unable to delete file.");V==="my-files"&&(s(dt=>dt.filter(J=>J.id!==P.id)),u(dt=>{let J=new Set(dt);return J.delete(P.id),J})),fe(null),j("File deleted.")}async function it(P){if(P!=="my-files"||!U||U.mode!=="create")return;let V=Gf(U.baseFolder,U.value);if(!V){X("Choose a folder name.");return}let ie=await fetch("/api/v1/user/me/attachments/folders",{method:"POST",headers:ut(e.apiKey,"application/json"),body:JSON.stringify({folder_path:V})}),Y=await ie.json().catch(()=>({}));if(!ie.ok){X(Y.error||"Unable to create folder.");return}l(Ie=>Array.from(new Set([...Ie,V])).sort()),x(null),j("Folder created.")}async function In(P,V){if(P!=="my-files"||!U||U.mode!=="rename")return;let ie=U.value.trim(),Y=Gf(LR(V),ie);if(!Y||Y===V)return;let Ie=await fetch("/api/v1/user/me/attachments/folders",{method:"PATCH",headers:ut(e.apiKey,"application/json"),body:JSON.stringify({from_folder_path:V,to_folder_path:Y})}),dt=await Ie.json().catch(()=>({}));if(!Ie.ok){X(dt.error||"Unable to rename folder.");return}A(J=>J===V||J.startsWith(`${V}/`)?`${Y}${J.slice(V.length)}`:J),await ae(),N(null),x(null),j("Folder renamed.")}async function Dt(P,V){if(P!=="my-files")return;let ie=await fetch("/api/v1/user/me/attachments/folders",{method:"DELETE",headers:ut(e.apiKey,"application/json"),body:JSON.stringify({folder_path:V})}),Y=await ie.json().catch(()=>({}));if(!ie.ok){X(Y.error||"Unable to delete folder.");return}A(Ie=>Ie===V||Ie.startsWith(`${V}/`)?LR(V):Ie),await ae(),N(null),x(null),j("Folder deleted.")}function wn(P){let V=a,ie=i,Y=M,Ie=A,dt=ZF({folders:V,files:ie,currentFolder:Y}),J=mo(Y).split("/").filter(Boolean);return(0,d.jsxs)("div",{className:"vf-editor-upload-browser",children:[(0,d.jsxs)("div",{className:"vf-editor-upload-browser-toolbar",children:[(0,d.jsxs)("div",{className:"vf-editor-upload-breadcrumb","aria-label":"Current folder",children:[(0,d.jsx)("button",{type:"button","data-current":!Y,onClick:()=>Ie(""),children:"files"}),J.map(($e,ye)=>{let Je=J.slice(0,ye+1).join("/");return(0,d.jsxs)("span",{className:"vf-editor-upload-breadcrumb-segment",children:[(0,d.jsx)("span",{"aria-hidden":"true",children:"/"}),(0,d.jsx)("button",{type:"button","data-current":Je===Y,onClick:()=>Ie(Je),children:$e})]},Je)})]}),(0,d.jsx)("button",{type:"button",onClick:()=>x({mode:"create",scope:"my-files",baseFolder:Y,value:""}),children:"New folder"})]}),dt.length?(0,d.jsx)("div",{className:"vf-editor-upload-folder-grid",children:dt.map($e=>(0,d.jsxs)("article",{className:"vf-editor-upload-folder-row",children:[(0,d.jsxs)("button",{type:"button",className:"vf-editor-upload-folder-open",onClick:()=>Ie($e.path),children:[(0,d.jsx)("span",{className:"vf-editor-upload-folder-icon","aria-hidden":"true"}),(0,d.jsx)("span",{children:$e.name})]}),(0,d.jsx)("button",{type:"button",className:"vf-editor-upload-folder-menu-button","aria-label":`Folder actions for ${$e.name}`,onClick:()=>N(I===$e.path?null:$e.path),children:"..."}),I===$e.path?(0,d.jsxs)("div",{className:"vf-editor-upload-folder-menu",children:[(0,d.jsx)("button",{type:"button",onClick:()=>x({mode:"rename",scope:"my-files",folderPath:$e.path,value:OR($e.path)}),children:"Rename"}),(0,d.jsx)("button",{type:"button","data-danger":"true",onClick:()=>x({mode:"delete",scope:"my-files",folderPath:$e.path,value:""}),children:"Delete"})]}):null]},$e.path))}):null]})}function nr(P,V){let ie=V==="my-files"?c.has(P.id):V==="recents"?_.has(P.id):!1,Y="s3Url"in P&&P.s3Url?P.s3Url:P.viewUrl;return(0,d.jsxs)("article",{className:"vf-editor-upload-file-card","data-selected":ie?"true":"false",children:[(0,d.jsxs)("button",{type:"button",className:"vf-editor-upload-file-select",onClick:()=>{if(V==="temporary"){St(Y);return}(V==="recents"?T:u)(dt=>{let J=new Set(dt);return J.has(P.id)?J.delete(P.id):J.add(P.id),J})},children:[(0,d.jsx)(PR,{file:P}),(0,d.jsxs)("span",{className:"vf-editor-upload-file-main",children:[(0,d.jsx)("span",{className:"vf-editor-upload-file-name",children:P.fileName}),(0,d.jsxs)("span",{className:"vf-editor-upload-file-meta",children:[MR(P.sizeBytes),P.folderPath?` \xB7 ${P.folderPath}`:""]})]})]}),(0,d.jsxs)("div",{className:"vf-editor-upload-file-actions",children:[V==="my-files"||V==="recents"?(0,d.jsx)("span",{className:"vf-editor-upload-selection-indicator","data-selected":ie?"true":"false","aria-hidden":"true",children:ie?"\u2713":""}):null,(0,d.jsx)("a",{href:P.viewUrl,target:"_blank",rel:"noreferrer","aria-label":`View ${P.fileName}`,children:(0,d.jsx)(cS,{name:"share"})}),(0,d.jsx)("button",{type:"button","aria-label":`Copy URL for ${P.fileName}`,onClick:()=>{St(Y)},children:(0,d.jsx)(cS,{name:"link"})}),V==="recents"?null:(0,d.jsx)("button",{type:"button","aria-label":`Delete ${P.fileName}`,onClick:()=>fe(Ze===P.id?null:P.id),children:(0,d.jsx)(cS,{name:"trash"})})]}),V!=="recents"&&Ze===P.id?(0,d.jsxs)("div",{className:"vf-editor-upload-popconfirm",children:[(0,d.jsx)("span",{children:"Delete this file?"}),(0,d.jsx)("button",{type:"button",onClick:()=>fe(null),children:"Cancel"}),(0,d.jsx)("button",{type:"button","data-danger":"true",onClick:()=>{bt(P,V)},children:"Delete"})]}):null]},P.id)}function Vi(){if(!U)return null;let P=U.mode==="create"?"New folder":U.mode==="rename"?"Rename folder":"Delete folder",V=U.mode==="delete"?U.folderPath:"";return(0,d.jsxs)("div",{className:"vf-editor-upload-folder-dialog",role:"dialog","aria-label":P,children:[(0,d.jsx)("div",{className:"vf-editor-upload-folder-dialog-title",children:P}),U.mode==="delete"?(0,d.jsxs)("div",{className:"vf-editor-upload-folder-dialog-copy",children:["Delete ",(0,d.jsx)("strong",{children:V})," and all files inside it?"]}):(0,d.jsx)("input",{value:U.value,autoFocus:!0,placeholder:"folder-name",onChange:ie=>x({...U,value:ie.target.value}),onKeyDown:ie=>{ie.key==="Enter"&&(ie.preventDefault(),U.mode==="create"?it(U.scope):In(U.scope,U.folderPath))}}),(0,d.jsxs)("div",{className:"vf-editor-upload-folder-dialog-actions",children:[(0,d.jsx)("button",{type:"button",onClick:()=>x(null),children:"Cancel"}),U.mode==="create"?(0,d.jsx)("button",{type:"button",className:"vf-editor-upload-confirm",onClick:()=>{it(U.scope)},children:"Create"}):U.mode==="rename"?(0,d.jsx)("button",{type:"button",className:"vf-editor-upload-confirm",onClick:()=>{In(U.scope,U.folderPath)},children:"Rename"}):(0,d.jsx)("button",{type:"button","data-danger":"true",onClick:()=>{Dt(U.scope,U.folderPath)},children:"Delete"})]})]})}if(!e.open)return null;let Zo=i.filter(P=>mo(P.folderPath??"")===mo(M));return(0,Wi.createPortal)((0,d.jsx)("div",{className:"vf-editor-upload-drawer-backdrop",children:(0,d.jsxs)("aside",{className:"vf-editor-upload-drawer","aria-label":"Upload drawer",children:[(0,d.jsxs)("div",{className:"vf-editor-upload-header",children:[(0,d.jsxs)("div",{children:[(0,d.jsx)("div",{className:"vf-editor-upload-title",children:"Upload"}),(0,d.jsx)("div",{className:"vf-editor-upload-subtitle",children:"Upload, attach, and copy file URLs."})]}),(0,d.jsx)("button",{type:"button",className:"vf-editor-upload-close","aria-label":"Close upload drawer",onClick:Te,children:"\xD7"})]}),(0,d.jsxs)("div",{className:"vf-editor-upload-tabs",role:"tablist",children:[(0,d.jsx)("button",{type:"button","data-active":t==="upload",onClick:()=>n("upload"),children:"Upload file"}),(0,d.jsx)("button",{type:"button","data-active":t==="my-files",onClick:()=>n("my-files"),children:"My Files"}),(0,d.jsx)("button",{type:"button","data-active":t==="recents",onClick:()=>n("recents"),children:"Recents"})]}),(0,d.jsxs)("div",{className:"vf-editor-upload-body",children:[he?(0,d.jsx)("div",{className:"vf-editor-upload-status","data-tone":"error",children:he}):null,H?(0,d.jsx)("div",{className:"vf-editor-upload-status",children:H}):null,Vi(),t==="upload"?(0,d.jsxs)(d.Fragment,{children:[(0,d.jsxs)("button",{type:"button",className:"vf-editor-upload-drop",onClick:()=>de.current?.click(),children:["Upload files to chat",(0,d.jsx)("span",{children:"Stored in Recents and attached after Confirm. Images get compressed inline previews when possible; other files attach by URL. Max 100 MB each."})]}),(0,d.jsx)("input",{ref:de,type:"file",multiple:!0,hidden:!0,onChange:P=>{ot(Array.from(P.target.files??[]),"upload"),P.target.value=""}}),(0,d.jsx)("div",{className:"vf-editor-upload-list",children:r.map(P=>(0,d.jsxs)("article",{className:"vf-editor-upload-file-card","data-selected":"true",children:[(0,d.jsx)(PR,{file:P}),(0,d.jsxs)("span",{className:"vf-editor-upload-file-main",children:[(0,d.jsx)("span",{className:"vf-editor-upload-file-name",children:P.fileName}),(0,d.jsx)("span",{className:"vf-editor-upload-file-meta",children:MR(P.sizeBytes)})]}),(0,d.jsx)("button",{type:"button",onClick:()=>o(V=>V.filter(ie=>ie.id!==P.id)),children:"\xD7"})]},P.id))})]}):t==="my-files"?(0,d.jsxs)(d.Fragment,{children:[(0,d.jsxs)("button",{type:"button",className:"vf-editor-upload-drop",onClick:()=>D.current?.click(),children:["Add to My Files",(0,d.jsxs)("span",{children:["Uploads into ",OR(M)," and auto-selects. Max 50 MB each."]})]}),(0,d.jsx)("input",{ref:D,type:"file",multiple:!0,hidden:!0,onChange:P=>{ot(Array.from(P.target.files??[]),"my-files"),P.target.value=""}}),wn("my-files"),(0,d.jsx)("div",{className:"vf-editor-upload-list",children:Zo.length?Zo.map(P=>nr(P,"my-files")):(0,d.jsx)("div",{className:"vf-editor-upload-empty",children:"No files in this folder."})})]}):t==="recents"?(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("div",{className:"vf-editor-upload-list",children:ge.length?ge.map(P=>nr(P,"recents")):(0,d.jsx)("div",{className:"vf-editor-upload-empty",children:E?"Loading recent files...":"No recent files yet."})}),g?(0,d.jsx)("button",{type:"button",className:"vf-editor-upload-more",disabled:E,onClick:()=>{Re(g).catch(P=>X(P instanceof Error?P.message:"Unable to load more recent media."))},children:E?"Loading...":"Load more generated media"}):null]}):null]}),(0,d.jsxs)("div",{className:"vf-editor-upload-footer",children:[(0,d.jsx)("button",{type:"button",onClick:Te,children:"Cancel"}),(0,d.jsxs)("div",{className:"vf-editor-upload-footer-confirm",children:[(0,d.jsxs)("span",{children:[Q.length," file",Q.length===1?"":"s"," selected"]}),(0,d.jsx)("button",{type:"button",className:"vf-editor-upload-confirm",disabled:!Q.length,onClick:()=>{e.onConfirm(Q),Te()},children:"Confirm"})]})]})]})}),document.body)}function QR({boot:e}){let t=e.template.templateId==="chat-brainstorm",n=t&&e.template.persistentHistorySidebar===!0,r=(0,k.useMemo)(()=>PF(e.template.templateId),[e.template.templateId]),o=(0,k.useMemo)(()=>LF(),[]),i=(0,k.useRef)(null),s=(0,k.useRef)(null),a=(0,k.useRef)(!0),l=(0,k.useRef)(!1),c=(0,k.useRef)(null),u=(0,k.useRef)(null),f=(0,k.useRef)(new Map),p=(0,k.useRef)({nextAvailableAt:0}),h=(0,k.useRef)([]),y=(0,k.useRef)(new Set),[_,T]=(0,k.useState)([]),[g,S]=(0,k.useState)(null),[E,R]=(0,k.useState)(null),[M,A]=(0,k.useState)(null),[I,N]=(0,k.useState)(""),[U,x]=(0,k.useState)([]),[H,j]=(0,k.useState)(null),[he,X]=(0,k.useState)(null),[Ze,fe]=(0,k.useState)(null),[de,D]=(0,k.useState)(!1),[ge,Q]=(0,k.useState)(!1),[ae,Re]=(0,k.useState)(!1),[Te,St]=(0,k.useState)(!1),[ot,bt]=(0,k.useState)(!1),[it,In]=(0,k.useState)(!1),[Dt,wn]=(0,k.useState)(null),[nr,Vi]=(0,k.useState)(!1),[Zo,P]=(0,k.useState)(null),[V,ie]=(0,k.useState)(!1),[Y,Ie]=(0,k.useState)(()=>{let m=typeof window<"u"?window.__vidfarmEditorTracers:null;if(m)return m.get();if(typeof window<"u"){let v=zf();if(v.length)return v}return tr(e.template.tracers||[])}),dt=(0,k.useMemo)(()=>{if(!e.threadsUrl)return null;let m=new URL(e.threadsUrl,window.location.origin);return t||m.searchParams.set("template_id",e.template.templateId),m.searchParams.set("include_messages","false"),m.searchParams.set("limit",t?"200":"50"),m.toString()},[e.template.templateId,e.threadsUrl,t]),J=m=>e.threadsUrl?new URL(`${e.threadsUrl.replace(/\/$/,"")}/${encodeURIComponent(m)}`,window.location.origin).toString():null;(0,k.useEffect)(()=>{let m=BF(o?.getItem(r.threads)??null,e.template.templateId),v=o?.getItem(r.activeThread)??null,w=wR(),b=window.__vidfarmEditorTracers?.get()??zf(),F=w&&!m.some(le=>le.id===w)?[{id:w,templateId:e.template.templateId,title:"Loading chat",createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),lastMessageAt:null,messageCount:0,tracers:b,hiddenFromView:!1,messages:[]},...m]:m,K=F.filter(le=>!le.hiddenFromView),z=K.find(le=>wc(le,b));h.current=F,T(F),w&&K.some(le=>le.id===w)?S(w):v&&K.some(le=>le.id===v)&&(!b.length||K.some(le=>le.id===v&&wc(le,b)))?S(v):S(z?.id??K[0]?.id??null),D(!0)},[e.template.templateId,o,r]),(0,k.useEffect)(()=>{if(!e.vidfarmApiKey||!dt)return;let m=new AbortController;return(async()=>{try{let v=[],w=null,b=new Set;do{let F=new URL(dt);w&&F.searchParams.set("cursor",w);let K=await fetch(F.toString(),{method:"GET",headers:ut(e.vidfarmApiKey),signal:m.signal});if(!K.ok)return;let z=await K.json().catch(()=>null);Array.isArray(z?.threads)&&v.push(...z.threads.map(pe=>RR(pe,e.template.templateId)).filter(pe=>!!pe));let le=typeof z?.next_cursor=="string"&&z.next_cursor?z.next_cursor:null;!le||b.has(le)?w=null:(b.add(le),w=le)}while(w&&!m.signal.aborted);if(!v.length)return;T(F=>{let K=xR(F,v);return h.current=K,K}),S(F=>F&&h.current.some(K=>K.id===F)?F:v[0]?.id??F)}catch(v){if(v instanceof DOMException&&v.name==="AbortError")return}})(),()=>{m.abort()}},[e.template.templateId,e.vidfarmApiKey,dt]),(0,k.useEffect)(()=>{h.current=_},[_]);let[$e,ye]=(0,k.useState)(()=>fR());(0,k.useEffect)(()=>{let m=()=>{ye(fR())};return window.addEventListener("popstate",m),()=>{window.removeEventListener("popstate",m)}},[]);async function Je(m){if(!e.vidfarmApiKey){P("Sign in to see forks.");return}if(!nr&&!(!m?.force&&Dt!==null)){Vi(!0),P(null);try{let v=await fetch("/api/v1/compositions",{method:"GET",headers:ut(e.vidfarmApiKey)});if(!v.ok){P(v.status===401?"Sign in to see forks.":`Failed to load forks (${v.status}).`),wn([]);return}let w=await v.json().catch(()=>null),F=(Array.isArray(w?.forks)?w.forks:[]).map(K=>{if(!K||typeof K!="object")return null;let z=K,le=typeof z.fork_id=="string"?z.fork_id:null;return le?{forkId:le,templateId:typeof z.template_id=="string"?z.template_id:null,parentForkId:typeof z.parent_fork_id=="string"?z.parent_fork_id:null,parentVersion:typeof z.parent_version=="number"?z.parent_version:null,title:typeof z.title=="string"?z.title:null,visibility:typeof z.visibility=="string"?z.visibility:null,latestVersion:typeof z.latest_version=="number"?z.latest_version:null,ownerCustomerId:typeof z.owner_customer_id=="string"?z.owner_customer_id:null,createdAt:typeof z.created_at=="string"?z.created_at:null,updatedAt:typeof z.updated_at=="string"?z.updated_at:null}:null}).filter(K=>!!K).filter(K=>K.templateId===e.template.templateId).sort((K,z)=>String(z.updatedAt??"").localeCompare(String(K.updatedAt??"")));wn(F)}catch{P("Could not load forks. Please try again."),wn([])}finally{Vi(!1)}}}(0,k.useEffect)(()=>{it&&Dt===null&&!nr&&Je()},[it]),(0,k.useEffect)(()=>{let m=window.__vidfarmEditorTracers;if(m)return Ie(m.get()),m.subscribe(w=>Ie(w));let v=()=>{let w=zf();Ie(w.length?w:tr(e.template.tracers||[]))};return v(),window.addEventListener("popstate",v),()=>{window.removeEventListener("popstate",v)}},[e.template.tracers]);let Se=(0,k.useRef)(_),Ur=(0,k.useRef)(g);(0,k.useEffect)(()=>{Se.current=_,Ur.current=g},[_,g]),(0,k.useEffect)(()=>{if(!de)return;let m=window.setTimeout(()=>{try{o?.setItem(r.threads,JSON.stringify(CR(Se.current,Ur.current)))}catch(v){console.warn("Unable to persist editor chat threads.",v)}},300);return()=>window.clearTimeout(m)},[g,o,de,r,_]),(0,k.useEffect)(()=>{if(de)try{g?o?.setItem(r.activeThread,g):o?.removeItem(r.activeThread)}catch(m){console.warn("Unable to persist active editor chat thread.",m)}},[g,o,de,r]),(0,k.useEffect)(()=>{if(!de||typeof window>"u")return;let m=new URL(window.location.href),v=m.searchParams.get("thread_id");if(g){if(v===g)return;m.searchParams.set("thread_id",g)}else{if(!v)return;m.searchParams.delete("thread_id")}window.history.replaceState({},"",m.toString())},[g,de]);let Jt=(0,k.useMemo)(()=>_.find(m=>m.id===g)??null,[g,_]),qi=(0,k.useMemo)(()=>_.find(m=>m.id===M?.threadId)??null,[M?.threadId,_]);(0,k.useEffect)(()=>{if(!de||!e.vidfarmApiKey||!g)return;let m=h.current.find(z=>z.id===g);if(y.current.has(g))return;let v=wR();if(!!(m&&(m.messageCount??0)===0&&m.messages.length===0)){y.current.add(g);return}let b=J(g);if(!b)return;let F=new AbortController;return!m?.messages.length&&R(g),(async()=>{try{let z=await fetch(b,{method:"GET",headers:ut(e.vidfarmApiKey),signal:F.signal});if(!z.ok){let ce=!!(m&&g!==v),ue=!!(m&&(m.messageCount??0)===0&&m.messages.length===0);z.status===404&&!ce&&!ue&&j(`Chat ID ${g} was not found for this account.`),y.current.add(g);return}let le=await z.json().catch(()=>null),pe=le?.thread?RR(le.thread,e.template.templateId):null;if(!pe)return;y.current.add(pe.id),j(null),T(ce=>{let ue=xR(ce,[pe]);return h.current=ue,ue})}catch(z){if(z instanceof DOMException&&z.name==="AbortError")return}finally{F.signal.aborted||R(z=>z===g?null:z)}})(),()=>{F.abort(),R(z=>z===g?null:z)}},[g,e.vidfarmApiKey,e.threadsUrl,de]),(0,k.useEffect)(()=>{if(!de||Jt&&!Jt.hiddenFromView)return;let m=_.find(v=>!v.hiddenFromView&&wc(v,Y));S(m?.id??_.find(v=>!v.hiddenFromView)?.id??null)},[Jt,de,_,Y]);let Kf=(0,k.useMemo)(()=>Jt?.tracers.length?Jt.tracers:Y,[Jt?.tracers,Y]),Jf=(0,k.useMemo)(()=>_.filter(m=>!m.hiddenFromView).sort((m,v)=>{let w=wc(m,Y),b=wc(v,Y);return w!==b?w?-1:1:Date.parse(v.updatedAt)-Date.parse(m.updatedAt)}),[_,Y]),IS=Kf[0]??null,Xf=Jt?.messages??[],wS=he!==null,Qf=!!(g&&he===g),CS=(0,k.useMemo)(()=>(I.trim()||U.length)&&!wS,[I,U.length,wS]);(0,k.useEffect)(()=>{!de||!e.vidfarmApiKey||!Jt||!Jt.messages.length||_x(Jt)},[Jt,e.vidfarmApiKey,de]);async function Rc(m,v){if(!e.vidfarmApiKey||!e.threadsUrl||!m.messages.length)return;let w=J(m.id);w&&await fetch(w,{method:"PATCH",headers:ut(e.vidfarmApiKey,"application/json"),body:JSON.stringify({template_id:e.template.templateId,title:v?.title??m.title,tracers:v?.tracers??m.tracers,hidden_from_view:v?.hiddenFromView??m.hiddenFromView===!0,archived:v?.archived})}).catch(()=>{})}async function nx(m){if(!e.vidfarmApiKey||!e.threadsUrl||!m.messages.length)return;let v=J(m.threadId);v&&await fetch(`${v}/exchanges`,{method:"POST",headers:ut(e.vidfarmApiKey,"application/json"),body:JSON.stringify({template_id:m.templateId??e.template.templateId,title:m.title||"New chat",tracers:m.tracers,messages:m.messages.map(w=>({id:w.id,role:w.role,text:w.text,attachments:w.attachments.map(b=>({id:b.id,fileName:b.fileName,contentType:b.contentType,viewUrl:b.viewUrl})),toolExchanges:w.toolExchanges,httpExchanges:w.httpExchanges?.map(Cc)}))})}).catch(()=>{})}async function rx(m){if(!e.vidfarmApiKey||!e.threadsUrl)return;let v=J(m);v&&await fetch(v,{method:"DELETE",headers:ut(e.vidfarmApiKey)}).catch(()=>{})}function RS(m){let v=new URL(window.location.href);m.length?v.searchParams.set("tracers",m.join(",")):v.searchParams.delete("tracers"),window.history.replaceState({},"",v.toString()),window.dispatchEvent(new CustomEvent("vidfarm:editor-tracers-changed",{detail:{tracers:m}}))}function ma(m){let v=tr(m),w=window.__vidfarmEditorTracers;if(w){w.set(v);return}Ie(v),RS(v)}function xS(){let m=window.__vidfarmEditorTracers;if(m)return m.add();let v=UF(e.template.templateSlug,Y);return ma([v,...Y]),v}function bS(m){let v=window.__vidfarmEditorTracers?.get()??Y,w=m?FF(m,v):null,b=window.__vidfarmEditorTracers;return b?b.add(w??void 0):w?(ma([w,...v.filter(F=>F!==w)]),w):xS()}function ox(m){let v=m.trim();if(!v)return;let w=window.__vidfarmEditorTracers;w?w.add(v):Y.includes(v)||ma([v,...Y]),Jt&&ft(Jt.id,b=>({...b,tracers:[v,...b.tracers.filter(F=>F!==v)],updatedAt:new Date().toISOString()}))}function ix(m){let v=window.__vidfarmEditorTracers;if(v){v.remove(m);return}let w=Y.filter(b=>b!==m);ma(w)}(0,k.useEffect)(()=>{RS(Y)},[Y]),(0,k.useEffect)(()=>{let m=s.current;if(!m)return;let v=()=>{a.current=pF(m),a.current||(l.current=!1)};return v(),m.addEventListener("scroll",v,{passive:!0}),()=>{m.removeEventListener("scroll",v)}},[]),(0,k.useLayoutEffect)(()=>{let m=s.current;if(!m)return;let v=c.current!==g;c.current=g,(v||l.current||a.current)&&(m.scrollTo({top:m.scrollHeight,behavior:"auto"}),a.current=!0,l.current=!1)},[Xf,g]),(0,k.useEffect)(()=>()=>{u.current?.abortController.abort(),u.current=null;for(let m of f.current.values())m.timeoutId!==null&&window.clearTimeout(m.timeoutId),m.abortController?.abort();f.current.clear()},[]),(0,k.useEffect)(()=>{if(!M)return;let m=()=>A(null);return document.addEventListener("click",m),window.addEventListener("resize",m),window.addEventListener("scroll",m,!0),()=>{document.removeEventListener("click",m),window.removeEventListener("resize",m),window.removeEventListener("scroll",m,!0)}},[M]),(0,k.useEffect)(()=>{let m=()=>{if(document.visibilityState!=="visible"||!navigator.onLine)return;let v=Date.now();for(let w of f.current.values())w.inFlight||w.nextPollAt!==null&&w.nextPollAt<=v&&w.runPoll&&ep(w,w.runPoll,w.nextPollAt-v)};return window.addEventListener("online",m),document.addEventListener("visibilitychange",m),()=>{window.removeEventListener("online",m),document.removeEventListener("visibilitychange",m)}},[]);function sx(m){if(Jt)return Jt.id;let v=new Date().toISOString(),w=IR(),b={id:w,templateId:e.template.templateId,title:Uf(m||""),createdAt:v,updatedAt:v,lastMessageAt:null,messageCount:0,tracers:tr(Y),messages:[]};return h.current=[b,...h.current],T(F=>[b,...F]),S(w),w}function Zf(m){let v=new Date().toISOString(),w=tr(m?.tracers??Y),b=IR(),F={id:b,templateId:e.template.templateId,title:m?.title||"New chat",createdAt:v,updatedAt:v,lastMessageAt:null,messageCount:0,tracers:w,messages:[]};return h.current=[F,...h.current],T(K=>[F,...K]),m?.activate!==!1&&(S(b),N(""),x([]),j(null)),A(null),b}function kS(){Zf(),bt(!1)}function ax(m){let v=_.find(b=>b.id===m);if(!v||!window.confirm(`Delete conversation "${v.title}"?`))return;let w=_.filter(b=>b.id!==m);h.current=h.current.filter(b=>b.id!==m);for(let[b,F]of f.current.entries())F.threadId===m&&ha(b);T(w),g===m&&S(w[0]?.id??null),j(null),A(null),rx(m)}function ft(m,v){let w=HF(h.current.map(b=>b.id===m?v(b):b));h.current=w,T(w)}function lx(m,v){let w=tr(v);ft(m,F=>({...F,tracers:lS(F.tracers,w),updatedAt:new Date().toISOString()}));let b=h.current.find(F=>F.id===m);b&&Rc({...b,tracers:lS(b.tracers,w),updatedAt:new Date().toISOString()},{tracers:lS(b.tracers,w)})}function NS(m,v){let w=m.trim();return w?h.current.find(b=>!b.hiddenFromView&&b.id!==v&&b.tracers.includes(w))?.id??null:null}function cx(m,v){let w=NS(m);return w||Zf({tracers:[m],title:v?.title||`Tracer ${m}`,activate:v?.activate??!1})}function ux(m){let v=m.toLowerCase();return/(?:own|separate|different|new)\s+(?:tracer\s+and\s+)?chat\s+threads?/.test(v)||/chat\s+threads?.{0,80}(?:own|separate|different|new)\s+tracers?/.test(v)||/each.{0,80}(?:own|separate|different|new).{0,80}chat\s+threads?/.test(v)||/(?:own|separate|different|new)\s+tracers?/.test(v)||/(?:each|every|per|one\s+per).{0,80}(?:own|separate|different|new).{0,80}tracers?/.test(v)||/(?:own|separate|different|new)\s+tracers?.{0,80}(?:each|every|per|outputs?|pieces?|posts?|jobs?|generations?)/.test(v)||/(?:outputs?|pieces?|posts?|jobs?|generations?).{0,80}(?:own|separate|different|new)\s+tracers?/.test(v)}function dx(m){let v=NS(m.tracer,m.sourceThreadId);if(!v&&!m.shouldCreateThread)return null;let w=v??cx(m.tracer,{title:`Tracer ${m.tracer}`,activate:!1});if(!w||w===m.sourceThreadId)return null;let b=$f("assistant"),F=new Date().toISOString(),K=m.job.status==="succeeded"||m.job.status==="failed"||m.job.status==="cancelled"?Df(m.job):hR(m.job),z=m.job.status==="succeeded"||m.job.status==="failed"||m.job.status==="cancelled"?null:`Job ${m.job.job_id} is being tracked. ${tp()}`,le={id:b,role:"assistant",text:K,attachments:[],httpExchanges:m.httpExchange?[m.httpExchange]:[],statusText:z,isPending:!1};ft(w,ce=>({...ce,updatedAt:F,messages:[...ce.messages,le]}));let pe=h.current.find(ce=>ce.id===w);return pe&&nx({threadId:w,templateId:pe.templateId,title:pe.title,tracers:pe.tracers,messages:[le]}),{threadId:w,messageId:b}}function fx(m){let v=_.find(F=>F.id===m);if(!v)return;let w=window.prompt("Thread tracers, comma separated",v.tracers.join(", "));if(w===null)return;let b=tr(w.split(","));ft(m,F=>({...F,tracers:b,updatedAt:new Date().toISOString()})),Rc(v,{tracers:b}),A(null)}function px(m){let v=_.find(F=>F.id===m);if(!v||!window.confirm(`Archive conversation "${v.title}"? Its tracer links will be prefixed with archived_.`))return;let b=tr(v.tracers.map(OF));ft(m,F=>({...F,tracers:b,updatedAt:new Date().toISOString()})),Rc(v,{tracers:b,archived:!0}),A(null)}function mx(m){let v=_.find(b=>b.id===m);if(!(!v||!window.confirm(`Remove conversation "${v.title}" from this frontend view? The thread and tracer links stay available; Delete removes the thread completely.`))){for(let[b,F]of f.current.entries())F.threadId===m&&ha(b);if(ft(m,b=>({...b,hiddenFromView:!0,updatedAt:new Date().toISOString()})),g===m){let b=Jf.find(F=>F.id!==m);S(b?.id??null)}A(null),j(null),Rc(v,{hiddenFromView:!0})}}async function hx(m){try{if(navigator.clipboard?.writeText)await navigator.clipboard.writeText(m);else{let v=document.createElement("textarea");v.value=m,v.setAttribute("readonly",""),v.style.position="fixed",v.style.opacity="0",document.body.appendChild(v),v.select(),document.execCommand("copy"),document.body.removeChild(v)}j(null)}catch{j("Unable to copy chat ID.")}finally{A(null)}}function gx(m,v){if(M?.threadId===m){A(null);return}let w=v.getBoundingClientRect(),b=148;A({threadId:m,top:w.bottom+6,left:Math.max(8,Math.min(window.innerWidth-b-8,w.right-b))})}function ha(m){let v=f.current.get(m);v&&(v.timeoutId!==null&&window.clearTimeout(v.timeoutId),v.abortController?.abort(),f.current.delete(m))}function ga(m,v,w){let b=f.current.get(m);b&&ep(b,v,w)}function ep(m,v,w){m.timeoutId!==null&&window.clearTimeout(m.timeoutId);let b=Math.max(_R,w);m.nextPollAt=Date.now()+b,m.timeoutId=window.setTimeout(()=>{m.timeoutId=null,v()},b)}function Yi(){return f.current.size>=yR?hF:gR}function Ki(m=Yi()){if(m>=6e4){let v=Math.round(m/6e4);return`${v} min${v===1?"":"s"}`}return`${Math.round(m/1e3)}s`}function tp(m=Yi()){return f.current.size>=yR?`Many renders are active, so the next check is in ${Ki(m)}.`:`Checking again gently every ${Ki(m)}.`}function yx(){let m=Yi();if(m===gR)return;let v=Date.now();for(let w of f.current.values()){if(w.inFlight||!w.runPoll)continue;(w.nextPollAt===null?0:w.nextPollAt-v)<m&&ep(w,w.runPoll,m)}}function Sx(m){let v=Math.max(m,p.current.nextAvailableAt);return p.current.nextAvailableAt=v+gF,v-m}function np(m){let v=vR(m.threadId,m.assistantMessageId,m.jobId);if(f.current.has(v))return;f.current.set(v,{timeoutId:null,abortController:null,runPoll:null,inFlight:!1,nextPollAt:null,lastPollAt:null,attempts:0,threadId:m.threadId});let w=async()=>{let K=f.current.get(v);if(!K||K.inFlight)return;let z=Date.now(),le=Yi();if(K.lastPollAt!==null&&z-K.lastPollAt<le){ga(v,w,le-(z-K.lastPollAt));return}if(K.attempts>=SR){ft(m.threadId,ce=>({...ce,updatedAt:new Date().toISOString(),messages:ce.messages.map(ue=>ue.id===m.assistantMessageId?{...ue,statusText:"Background polling stopped after multiple checks. Open the job route when you want to refresh again."}:ue)})),ha(v);return}if(document.visibilityState!=="visible"||!navigator.onLine){ga(v,w,le);return}let pe=Sx(Date.now());if(pe>0){ga(v,w,pe);return}K.inFlight=!0,K.lastPollAt=z,K.nextPollAt=null,K.attempts+=1,K.abortController=new AbortController;try{ft(m.threadId,Fe=>({...Fe,updatedAt:new Date().toISOString(),messages:Fe.messages.map(Z=>Z.id===m.assistantMessageId?{...Z,statusText:`Job ${m.jobId} is being tracked. ${tp(le)}`}:Z)}));let ce=m.primitiveId||yF(m.sourceRequestUrl)?`/api/v1/primitives/jobs/${encodeURIComponent(m.jobId)}`:`/api/v1/templates/${encodeURIComponent(e.template.templateId)}/jobs/${encodeURIComponent(m.jobId)}`,ue=await fetch(ce,{method:"GET",headers:ut(e.vidfarmApiKey),signal:K.abortController.signal}),cn=await ue.json().catch(()=>null),ya=Object.fromEntries(ue.headers.entries()),W=$i(cn);if(ft(m.threadId,Fe=>({...Fe,updatedAt:new Date().toISOString(),messages:Fe.messages.map(Z=>{if(Z.id!==m.assistantMessageId)return Z;let ve=mF(Z.httpExchanges,Cc({explanation:`Automatic ${Ki(le)} job status check for ${m.jobId}`,pollJobId:m.jobId,pollMode:"automatic",request:{method:"GET",url:ce,headers:Object.fromEntries(ut(e.vidfarmApiKey).entries())},result:{status:ue.status,statusText:ue.statusText,headers:ya,body:cn}})),ke=W?W.status==="succeeded"?`Render ${W.job_id} succeeded.`:W.status==="failed"||W.status==="cancelled"?`Render ${W.job_id} ${W.status}.${W.error?.message?` ${W.error.message}`:""}`:`Render ${W.job_id} is ${W.status}. Next check in ${Ki(le)}.`:`Render ${m.jobId} checked. Next check in ${Ki(le)}.`;return{...Z,httpExchanges:ve,statusText:ke,text:W&&(W.status==="succeeded"||W.status==="failed"||W.status==="cancelled")?Ic(Z.text,Df(W)):Z.text}})})),W&&(W.status==="succeeded"||W.status==="failed"||W.status==="cancelled")){ha(v);return}}catch(ce){if(ce instanceof DOMException&&ce.name==="AbortError")return;ft(m.threadId,ue=>({...ue,updatedAt:new Date().toISOString(),messages:ue.messages.map(cn=>cn.id===m.assistantMessageId?{...cn,statusText:`Automatic polling paused after an error. It will retry in ${Ki()}.`}:cn)}))}finally{let ce=f.current.get(v);if(!ce)return;ce.inFlight=!1,ce.abortController=null,ce.attempts<SR&&ce.timeoutId===null&&f.current.has(v)&&ga(v,w,Yi())}},b=f.current.get(v);b&&(b.runPoll=w),f.current.get(v)&&(ga(v,w,m.initialDelayMs??Yi()),yx())}function _x(m){for(let v of m.messages)if(!(v.role!=="assistant"||!v.httpExchanges?.length))for(let w of v.httpExchanges){if(w.request.method!=="POST")continue;let b=$i(w.result.body),F=vR(m.id,v.id,b?.job_id??"");!b||fa(b.status)||f.current.has(F)||v.httpExchanges.some(z=>{let le=$i(z.result.body);return le?.job_id===b.job_id&&fa(le.status)})||np({threadId:m.id,assistantMessageId:v.id,jobId:b.job_id,tracer:b.tracer,initialStatus:b.status,primitiveId:b.primitive_id,sourceRequestUrl:w.request.url,initialDelayMs:_R})}}async function rp(m){if(!m.length)return;j(null);let v=[],w=null;for(let b of m)try{let F=await YR({apiKey:e.vidfarmApiKey,file:b,folderPath:UR}),K=await qR({attachment:F,file:b,currentInlineBytes:VR([...U,...v])});v.push(K)}catch(F){w=F instanceof Error?F.message:"Unable to upload attachment."}w&&v.length===0&&j(w),v.length&&(x(b=>[...b,...v]),w&&j(w))}async function vx(m){let v=Array.from(m.target.files??[]);await rp(v),m.target.value=""}async function Ex(m){let v=Array.from(m.clipboardData.files??[]).filter(w=>w.size>0);v.length&&(m.preventDefault(),await rp(v))}async function Tx(m){m.preventDefault(),Q(!1);let v=Array.from(m.dataTransfer.files??[]).filter(w=>w.size>0);v.length&&await rp(v)}async function Ix(m,v,w){let b=w??{},F=e.vidfarmApiKey,K=window.location.origin,z=ut(F,"application/json"),le=ut(F),pe=Z=>new Promise(ve=>setTimeout(ve,Z)),ce=(Z,ve)=>{ft(m,ke=>({...ke,updatedAt:new Date().toISOString(),messages:ke.messages.map(Ne=>Ne.id===v?{...Ne,isPending:!1,statusText:Z??Ne.statusText,text:ve?Ic(Ne.text,ve):Ne.text}:Ne)}))},ue=async Z=>{let ve=await Z.text();try{return ve?JSON.parse(ve):null}catch{return null}},cn=async Z=>{let ve=Date.now()+3e5;for(;;){let ke=await fetch(new URL(`/api/v1/videos/${encodeURIComponent(Z)}`,K),{headers:le}),Ne=await ue(ke),Be=String(Ne?.status??"");if(Be==="ready")return Ne;if(Be==="failed")throw new Error(`source video download failed${Ne?.error?`: ${Ne.error}`:""}.`);if(Date.now()>ve)throw new Error("source video download timed out.");await pe(5e3)}},ya=Z=>{let ve=Ee=>typeof Ee=="string"&&Ee.trim()?Ee.trim():null,ke=Z?.result&&typeof Z.result=="object"?Z.result:{},Ne=ke.output&&typeof ke.output=="object"?ke.output:ke,Be=ve(Ne?.primary_file_url)??ve(Ne?.video?.file_url)??ve(Ne?.image?.file_url)??ve(Ne?.render?.output_url);if(Be)return Be;if(Array.isArray(Ne?.files))for(let Ee of Ne.files){let Le=ve(typeof Ee=="string"?Ee:Ee?.file_url??Ee?.url);if(Le)return Le}if(Array.isArray(Z?.artifacts))for(let Ee of Z.artifacts){let Le=ve(Ee?.public_url);if(Le)return Le}return null},W=async Z=>{let ve=Date.now()+48e4;for(;;){await pe(5e3);let ke=await fetch(new URL(`/api/v1/user/me/jobs/${encodeURIComponent(Z)}`,K),{headers:le}),Ne=await ue(ke),Be=String(Ne?.status??""),Ee=ya(Ne);if(Ee)return Ee;if(Be==="failed"||Be==="cancelled")throw new Error(`generation ${Be}.`);if(Date.now()>ve)throw new Error("generation timed out.")}},Fe=async(Z,ve)=>{let ke=await(await fetch(Z)).blob(),Ne=await fetch(new URL("/discover/templates/upload/presign",K),{method:"POST",headers:z,body:JSON.stringify({file_name:"generated.mp4",content_type:"video/mp4",size_bytes:ke.size})}),Be=await ue(Ne);if(!Ne.ok)throw new Error(Be?.error||`upload presign failed (${Ne.status})`);let Ee=Be?.storage_key,Le=Be?.file_name||"generated.mp4";if(Be?.transport==="presigned"&&Be?.upload?.url){let Oe=await fetch(Be.upload.url,{method:Be.upload.method||"PUT",headers:Be.upload.headers||{},body:ke});if(!Oe.ok)throw new Error(`upload failed (${Oe.status})`)}else{let Oe=new FormData;Oe.append("file",ke,"generated.mp4");let Xt=await fetch(new URL(Be?.upload?.url||"/discover/templates/upload",K),{method:"POST",headers:le,body:Oe}),_t=await ue(Xt);if(!Xt.ok||!_t?.storage_key)throw new Error(_t?.error||`upload failed (${Xt.status})`);Ee=_t.storage_key,Le=_t.file_name||"generated.mp4"}if(!Ee)throw new Error("upload did not return a storage key.");let ho=await fetch(new URL("/discover/templates",K),{method:"POST",headers:z,body:JSON.stringify({upload:{storage_key:Ee,file_name:Le},title:ve,origin:"raw"})}),Ut=await ue(ho);if(!ho.ok)throw new Error(Ut?.error||`ingest failed (${ho.status})`);return Ut};try{if(!F){ce(null,"\u26A0\uFE0F You need to be logged in to create a video.");return}let Z=b.mode==="replicate"?"replicate":b.mode==="generate"?"generate":null,ve,ke;if(Z==="replicate"){let Xt=(b.source_url??"").trim();if(!/^https?:\/\//i.test(Xt)){ce(null,"\u26A0\uFE0F I need a video URL (TikTok/YouTube/Instagram/X) to replicate.");return}ke=(b.instructions??"").trim()||null,ce("Fetching the source video\u2026");let _t=await fetch(new URL("/discover/templates",K),{method:"POST",headers:z,body:JSON.stringify({source_url:Xt})}),Fr=await ue(_t);if(!_t.ok)throw new Error(Fr?.error||`couldn't fetch that URL (${_t.status})`);ve=Fr?.status==="ready"?Fr:await cn(Fr?.inspiration_id)}else if(Z==="generate"){let Xt=(b.prompt??"").trim();if(!Xt){ce(null,"\u26A0\uFE0F Tell me what the video should be about and I'll create it.");return}ke=Xt,ce("Generating your video\u2026 (this can take a couple of minutes)");let _t=await fetch(new URL("/api/v1/primitives/videos/generate",K),{method:"POST",headers:z,body:JSON.stringify({tracer:`chat-create-${Date.now().toString(36)}`,payload:{prompt:Xt}})}),Fr=await ue(_t);if(!_t.ok)throw new Error(Fr?.error||`couldn't start generation (${_t.status})`);let Rx=await W(Fr?.job_id);ce("Building an editable template from the generated video\u2026");let op=await Fe(Rx,Xt.slice(0,80));ve=op?.status==="ready"?op:await cn(op?.inspiration_id)}else{ce(null,"\u26A0\uFE0F I couldn't tell whether to generate a new video or replicate a URL \u2014 try rephrasing.");return}let Ne=ve?.template_id,Be=ve?.inspiration_id;if(!Ne||!Be)throw new Error("the template wasn't created from the video.");ce(Z==="replicate"?"Recreating the scenes\u2026 (about a minute)":"Analyzing into an editable timeline\u2026");let Ee=await fetch(new URL(`/api/v1/inspirations/${encodeURIComponent(Be)}/decompose`,K),{method:"POST",headers:z,body:JSON.stringify({user_prompt:ke})});if(!Ee.ok){let Xt=await ue(Ee);throw new Error(Xt?.error||`scene analysis failed (${Ee.status})`)}ce("Finalizing your editable copy\u2026");let Le=await fetch(new URL("/api/v1/compositions",K),{method:"POST",headers:z,body:JSON.stringify({template_id:Ne})}),ho=await ue(Le);if(!Le.ok)throw new Error(ho?.error||`couldn't create an editable copy (${Le.status})`);let Ut=ho?.fork_id,Oe=`${K}/editor/${encodeURIComponent(Ne)}${Ut?`/fork/${encodeURIComponent(Ut)}`:""}`;ce("Your video is ready.",`\u2705 Your video is ready \u2014 [Open it in the editor](${Oe}).`)}catch(Z){ce(null,`\u26A0\uFE0F I couldn't finish creating the video: ${Z instanceof Error?Z.message:String(Z)}`)}}async function AS(){if(!CS)return;l.current=!0;let m=sx(I),v=new Date().toISOString(),w=h.current.find(pe=>pe.id===m),b={id:$f("user"),role:"user",text:I.trim(),attachments:U},F={id:$f("assistant"),role:"assistant",text:"",attachments:[],statusText:"Waiting for AI response\u2026",isPending:!0},K=w?.messages??[],z=xF([...K,b]);ft(m,pe=>({...pe,title:pe.messages.length===0?Uf(b.text):pe.title,updatedAt:v,messages:[...pe.messages,b,F]})),N(""),x([]),j(null),X(m),fe("Waiting for AI response\u2026");let le=new AbortController;u.current={abortController:le,threadId:m,assistantMessageId:F.id};try{let pe=JSON.stringify({messages:kF(z),thread_id:m,thread_template_id:w?.templateId??e.template.templateId,thread_title:K.length===0?Uf(b.text):w?.title??Uf(b.text),thread_tracers:Kf,client_context:nF(),user_message:{id:b.id,role:b.role,text:b.text,attachments:b.attachments.map(W=>({id:W.id,fileName:W.fileName,contentType:W.contentType,viewUrl:W.viewUrl}))},assistant_message:{id:F.id},template:{...e.template,tracers:Kf,defaultRequestTracer:IS,activeTracer:IS},cached_context:{...e.cachedContext,...NF(),...AF()}});Or("chat.send.attempt",{thread_id:m,template_id:e.template.templateId,message_count:z.length,attachment_count:b.attachments.length,text_length:b.text.length});let ce=Date.now(),ue=await fetch(e.apiUrl||"/api/v1/editor-chat",{method:"POST",headers:ut(e.vidfarmApiKey,"application/json"),signal:le.signal,body:pe});if(!ue.ok){let W=await ue.json().catch(()=>({}));throw po("chat.send.rejected",{thread_id:m,status:ue.status,error:typeof W?.error=="string"?W.error:null}),new Error(typeof W?.error=="string"?W.error:`Chat failed with status ${ue.status}.`)}Or("chat.send.stream_open",{thread_id:m,latency_ms:Date.now()-ce});let cn=new Map,ya=ux(b.text);await MF(ue,{onDelta:W=>{fe("AI is responding\u2026"),ft(m,Fe=>({...Fe,updatedAt:new Date().toISOString(),messages:Fe.messages.map(Z=>Z.id===F.id?{...Z,text:`${Z.text}${W}`,statusText:"AI is responding\u2026",isPending:!1}:Z)}))},onStatus:W=>{fe(W),ft(m,Fe=>({...Fe,messages:Fe.messages.map(Z=>Z.id===F.id?{...Z,statusText:W,isPending:!Z.text}:Z)}))},onToolCall:W=>{cn.set(W.toolCallId,{toolName:W.toolName,args:W.args}),ft(m,Fe=>({...Fe,updatedAt:new Date().toISOString(),messages:Fe.messages.map(Z=>Z.id===F.id?{...Z,toolExchanges:[...Z.toolExchanges??[],{toolCallId:W.toolCallId,toolName:W.toolName,args:ji(W.args),status:"pending"}]}:Z)}))},onToolResult:W=>{let Fe=FR(W.result),Z=cn.get(W.toolCallId);if(W.toolName==="create_video"&&Ix(m,F.id,W.result),W.toolName==="frontend_action"){let Ee=W.result;if(Ee?.action==="add_tracer")bS(Ee.tracer??void 0);else if(Ee?.action==="remove_tracer"&&Ee.tracer)ix(Ee.tracer);else if(Ee?.action==="activate_tracer"&&Ee.tracer)ox(Ee.tracer);else if(Ee?.action==="create_thread"){let Le=Ee.tracer?bS(Ee.tracer):xS();Zf({tracers:Le?[Le]:[],title:Le?`Tracer ${Le}`:"New chat",activate:!1})}}let ve=W.result,ke=$i(ve?.response?.body),Ne=ve?.request&&ve?.response?Cc({explanation:ve.explanation??null,request:ve.request,result:ve.response}):void 0,Be=ve?.request?.method==="POST"&&ke?.tracer?dx({sourceThreadId:m,tracer:ke.tracer,job:ke,httpExchange:Ne,shouldCreateThread:ya}):null;Be&&ke&&!fa(ke.status)&&np({threadId:Be.threadId,assistantMessageId:Be.messageId,jobId:ke.job_id,tracer:ke.tracer,initialStatus:ke.status,primitiveId:ke.primitive_id,sourceRequestUrl:ve?.request?.url}),ft(m,Ee=>({...Ee,updatedAt:new Date().toISOString(),messages:Ee.messages.map(Le=>{if(Le.id!==F.id)return Le;let ho=(Le.toolExchanges??[]).map(_t=>_t.toolCallId===W.toolCallId?{..._t,result:Fe,status:typeof W.result?.error=="string"?"error":"complete"}:_t),Ut=W.result,Oe=$i(Ut?.response?.body),Xt=Ut?.request&&Ut?.response?[...Le.httpExchanges??[],Cc({explanation:Ut.explanation??null,request:Ut.request,result:Ut.response})]:Le.httpExchanges;if(Z&&cn.delete(W.toolCallId),Ut?.request?.method==="POST"&&Oe?.tracer){let _t=window.__vidfarmEditorTracers;_t?_t.add(Oe.tracer):ma([Oe.tracer,...Y.filter(Fr=>Fr!==Oe.tracer)]),lx(m,[Oe.tracer])}return Oe&&!Be&&!fa(Oe.status)&&np({threadId:m,assistantMessageId:F.id,jobId:Oe.job_id,tracer:Oe.tracer,initialStatus:Oe.status,primitiveId:Oe.primitive_id,sourceRequestUrl:Ut?.request?.url}),{...Le,toolExchanges:ho,httpExchanges:Xt,statusText:Oe&&!fa(Oe.status)?`Job ${Oe.job_id} is being tracked. ${tp()}`:Le.statusText,isPending:!1,text:Oe&&Ut?.request?.method==="POST"&&Ut?.response?.status===202?Ic(Le.text,hR(Oe)):Oe&&fa(Oe.status)||Oe?Ic(Le.text,Df(Oe)):Le.text}})}))},onError:W=>{po("chat.stream.error",{thread_id:m,message:W}),j(W),fe(null),ft(m,Fe=>({...Fe,messages:Fe.messages.filter(Z=>Z.id!==F.id)}))}}),Or("chat.stream.completed",{thread_id:m,duration_ms:Date.now()-ce}),ft(m,W=>({...W,updatedAt:new Date().toISOString(),messages:W.messages.map(Fe=>Fe.id===F.id?{...Fe,statusText:Fe.statusText?.includes("being tracked")?Fe.statusText:null,isPending:!1}:Fe)}))}catch(pe){if(pe instanceof DOMException&&pe.name==="AbortError"){nR("chat.send.aborted",{thread_id:m}),j(null),fe(null),ft(m,ce=>({...ce,updatedAt:new Date().toISOString(),messages:ce.messages.map(ue=>ue.id!==F.id?ue:!!(ue.text.trim()||ue.toolExchanges?.length||ue.httpExchanges?.length)?{...ue,statusText:"Stopped.",isPending:!1}:{...ue,text:"Stopped.",statusText:null,isPending:!1})}));return}po("chat.send.failed",{thread_id:m,message:pe instanceof Error?pe.message:String(pe)}),j(pe instanceof Error?pe.message:"Unable to send chat message."),fe(null),ft(m,ce=>({...ce,messages:ce.messages.map(ue=>ue.id===F.id?{...ue,text:pe instanceof Error?`Error: ${pe.message}`:"Error: Unable to send chat message.",statusText:null,isPending:!1}:ue)}))}finally{u.current?.assistantMessageId===F.id&&(u.current=null),X(pe=>pe===m?null:pe),fe(null)}}function wx(){fe("Stopping\u2026");let m=u.current;m&&ft(m.threadId,v=>({...v,updatedAt:new Date().toISOString(),messages:v.messages.map(w=>w.id===m.assistantMessageId?{...w,statusText:"Stopping\u2026"}:w)})),u.current?.abortController.abort()}(0,k.useEffect)(()=>()=>{u.current?.abortController.abort();for(let m of f.current.keys())ha(m);try{o?.setItem(r.threads,JSON.stringify(CR(Se.current,Ur.current)))}catch{}},[o,r]);function Cx(m){m.key==="Enter"&&!m.shiftKey&&(m.preventDefault(),AS())}let MS=(0,d.jsx)("div",{className:`vf-editor-chat-thread-list${t?" vf-editor-chat-thread-list-sidebar":""}`,role:"tablist","aria-label":"Conversation threads",children:Jf.length?Jf.map(m=>(0,d.jsxs)("div",{role:"tab","aria-selected":m.id===g,className:"vf-editor-chat-thread-chip","data-active":m.id===g?"true":"false",children:[(0,d.jsxs)("button",{type:"button",className:"vf-editor-chat-thread-chip-main",onClick:()=>{S(m.id),j(null),A(null),bt(!1)},children:[(0,d.jsx)("span",{className:"vf-editor-chat-thread-chip-title",children:m.title}),m.tracers.length?(0,d.jsxs)("span",{className:"vf-editor-chat-thread-chip-tracers",children:[m.tracers.slice(0,2).join(", "),m.tracers.length>2?` +${m.tracers.length-2}`:""]}):null]}),(0,d.jsx)("div",{className:"vf-editor-chat-thread-menu-wrap",children:(0,d.jsx)("button",{type:"button",className:"vf-editor-chat-thread-chip-menu","aria-label":`Actions for ${m.title}`,onClick:v=>{v.stopPropagation(),gx(m.id,v.currentTarget)},children:"..."})})]},m.id)):(0,d.jsx)("div",{className:"vf-editor-chat-thread-empty",children:"Start a chat to create your first conversation thread."})});return(0,d.jsxs)("div",{className:"vf-editor-chat-shell","data-mobile-open":ae?"true":"false","data-mobile-expanded":Te?"true":"false","data-layout":t?"brainstorm":"default",children:[(0,d.jsx)("button",{type:"button",className:"vf-editor-chat-mobile-fab","aria-label":"Open chat","aria-expanded":ae,onClick:()=>{St(!1),Re(!0)},children:(0,d.jsx)("svg",{viewBox:"0 0 24 24","aria-hidden":"true",focusable:"false",children:(0,d.jsx)("path",{d:"M20 11.5a7.5 7.5 0 0 1-9.8 7.1L4 20l1.5-5.3A7.5 7.5 0 1 1 20 11.5Z"})})}),H?(0,d.jsx)("div",{className:"vf-editor-chat-error",role:"status",children:H}):null,(0,d.jsxs)("div",{className:`${t?"vf-editor-chat-body vf-editor-chat-brainstorm-layout":"vf-editor-chat-body"}${n?" has-sidebar":""}`,"data-history-open":ot||it?"true":"false",children:[n?(0,d.jsxs)("aside",{className:"vf-editor-chat-history-pane",children:[(0,d.jsx)("div",{className:"vf-editor-chat-history-header",children:(0,d.jsxs)("div",{className:"vf-editor-chat-history-header-main",children:[(0,d.jsxs)("a",{className:"vf-editor-chat-back-button",href:"/discover","aria-label":"Back to Discover",children:[(0,d.jsx)("svg",{viewBox:"0 0 20 20",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,d.jsx)("path",{d:"m12 4-6 6 6 6"})}),"Discover"]}),(0,d.jsx)("div",{className:"vf-editor-chat-history-kicker",children:"Chat history"})]})}),(0,d.jsx)("button",{type:"button",className:"vf-editor-chat-new-thread vf-editor-chat-new-thread-sidebar",onClick:kS,children:"New chat"}),MS]}):null,(0,d.jsxs)("div",{className:"vf-editor-chat-thread",children:[(0,d.jsxs)("div",{className:"vf-editor-chat-header",children:[(0,d.jsxs)("div",{className:"vf-editor-chat-header-row",children:[(0,d.jsx)("a",{className:"vf-editor-chat-back-button vf-editor-chat-back-button--header",href:"/discover","aria-label":"Back to Discover",children:(0,d.jsx)("svg",{viewBox:"0 0 20 20",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,d.jsx)("path",{d:"m12 4-6 6 6 6"})})}),(0,d.jsx)("button",{type:"button",className:"vf-editor-chat-history-icon","aria-label":ot?"Back to chat":"Open chat history","aria-pressed":ot,onClick:()=>{bt(m=>!m),In(!1)},children:ot?(0,d.jsx)("svg",{viewBox:"0 0 20 20",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,d.jsx)("path",{d:"m12 4-6 6 6 6"})}):(0,d.jsxs)("svg",{viewBox:"0 0 20 20",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,d.jsx)("circle",{cx:"10",cy:"10",r:"7.2"}),(0,d.jsx)("path",{d:"M10 6v4l2.6 1.6"})]})}),(0,d.jsx)("button",{type:"button",className:"vf-editor-chat-history-icon vf-editor-chat-branches-icon","aria-label":it?"Back to chat":"Open template forks","aria-pressed":it,onClick:()=>{In(m=>!m),bt(!1)},children:it?(0,d.jsx)("svg",{viewBox:"0 0 20 20",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,d.jsx)("path",{d:"m12 4-6 6 6 6"})}):(0,d.jsxs)("svg",{viewBox:"0 0 20 20",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,d.jsx)("circle",{cx:"5.5",cy:"4.5",r:"1.9"}),(0,d.jsx)("circle",{cx:"5.5",cy:"15.5",r:"1.9"}),(0,d.jsx)("circle",{cx:"14.5",cy:"8",r:"1.9"}),(0,d.jsx)("path",{d:"M5.5 6.4v7.2"}),(0,d.jsx)("path",{d:"M5.5 13.6c0-3.2 2.4-3.6 4.4-3.9 2-.3 4.6-.5 4.6-3.7"})]})}),(0,d.jsxs)("div",{className:"vf-editor-chat-header-titles",children:[(0,d.jsx)("div",{className:"vf-editor-chat-header-title",children:"Vidfarm"}),(0,d.jsx)("div",{className:"vf-editor-chat-header-subtitle",children:ot?"Chat history":it?"Template forks":e.template.templateTitle})]}),(0,d.jsx)("button",{type:"button",className:"vf-editor-chat-new-thread",onClick:kS,children:"New chat"}),(0,d.jsx)("button",{type:"button",className:"vf-editor-chat-expand","aria-label":Te?"Shrink chat":"Expand chat","aria-pressed":Te,onClick:()=>St(m=>!m),children:Te?(0,d.jsxs)("svg",{viewBox:"0 0 20 20","aria-hidden":"true",focusable:"false",children:[(0,d.jsx)("path",{d:"M16.5 8.5h-5v-5"}),(0,d.jsx)("path",{d:"M11.5 8.5 17 3"}),(0,d.jsx)("path",{d:"M3.5 11.5h5v5"}),(0,d.jsx)("path",{d:"M8.5 11.5 3 17"})]}):(0,d.jsxs)("svg",{viewBox:"0 0 20 20","aria-hidden":"true",focusable:"false",children:[(0,d.jsx)("path",{d:"M11.5 3.5h5v5"}),(0,d.jsx)("path",{d:"M16.5 3.5 11 9"}),(0,d.jsx)("path",{d:"M8.5 16.5h-5v-5"}),(0,d.jsx)("path",{d:"M3.5 16.5 9 11"})]})}),(0,d.jsx)("button",{type:"button",className:"vf-editor-chat-minimize","aria-label":"Minimize chat",onClick:()=>Re(!1),children:"\xD7"})]}),M&&qi?(0,Wi.createPortal)((0,d.jsxs)("div",{className:"vf-editor-chat-thread-menu",role:"menu",style:{top:M.top,left:M.left},onClick:m=>m.stopPropagation(),children:[(0,d.jsx)("button",{type:"button",onClick:()=>hx(qi.id),children:"Copy Chat ID"}),(0,d.jsx)("button",{type:"button",onClick:()=>fx(qi.id),children:"Edit tracers"}),(0,d.jsx)("button",{type:"button",onClick:()=>mx(qi.id),children:"Remove from view"}),(0,d.jsx)("button",{type:"button",onClick:()=>px(qi.id),children:"Archive thread"}),(0,d.jsx)("button",{type:"button","data-danger":"true",onClick:()=>ax(qi.id),children:"Delete"})]}),document.body):null]}),(0,d.jsx)("div",{className:"vf-editor-chat-viewport",ref:s,children:ot?(0,d.jsx)("div",{className:"vf-editor-chat-history-panel",children:MS}):it?(0,d.jsxs)("div",{className:"vf-editor-chat-history-panel vf-editor-chat-branches-panel",children:[(0,d.jsxs)("div",{className:"vf-editor-chat-branches-header",children:[(0,d.jsxs)("div",{className:"vf-editor-chat-branches-header-main",children:[(0,d.jsx)("div",{className:"vf-editor-chat-branches-kicker",children:"Forks"}),(0,d.jsxs)("div",{className:"vf-editor-chat-branches-title",children:[Dt?.length??0," fork",(Dt?.length??0)===1?"":"s"," of this template"]})]}),(0,d.jsx)("button",{type:"button",className:"vf-editor-chat-branches-refresh",onClick:()=>{Je({force:!0})},disabled:nr,"aria-label":"Refresh forks",children:nr?"Loading\u2026":"Refresh"})]}),Zo?(0,d.jsx)("div",{className:"vf-editor-chat-thread-empty",role:"status",children:Zo}):nr&&!Dt?(0,d.jsx)("div",{className:"vf-editor-chat-thread-empty",children:"Loading forks\u2026"}):Dt&&Dt.length?(0,d.jsx)("div",{className:"vf-editor-chat-thread-list",children:Dt.map(m=>{let v=$e===m.forkId,w=`/editor/${encodeURIComponent(e.template.templateId)}/fork/${encodeURIComponent(m.forkId)}`,b=m.title&&m.title.trim()?m.title:m.forkId,F=m.parentForkId?` \xB7 forked from ${m.parentForkId.slice(0,12)}${m.parentVersion?`#v${m.parentVersion}`:""}`:"",K=m.latestVersion&&m.latestVersion>0?` \xB7 v${m.latestVersion}`:"";return(0,d.jsx)("div",{role:"listitem",className:"vf-editor-chat-thread-chip","data-active":v?"true":"false",children:(0,d.jsxs)("a",{className:"vf-editor-chat-thread-chip-main vf-editor-chat-branch-chip-link",href:w,target:"_blank",rel:"noopener noreferrer",children:[(0,d.jsxs)("span",{className:"vf-editor-chat-thread-chip-title",children:[b,v?(0,d.jsx)("span",{className:"vf-editor-chat-branch-current-badge",children:"current"}):null]}),(0,d.jsxs)("span",{className:"vf-editor-chat-thread-chip-tracers",children:[m.visibility??"private",K,F]})]})},m.forkId)})}):(0,d.jsx)("div",{className:"vf-editor-chat-thread-empty",children:"No forks yet for this template."})]}):Xf.length?Xf.map(m=>(0,d.jsx)(QF,{message:m},m.id)):g&&E===g?(0,d.jsxs)("div",{className:"vf-editor-chat-empty",children:[(0,d.jsx)("div",{className:"vf-editor-chat-kicker",children:"Loading chat"}),(0,d.jsxs)("h2",{children:["Opening ",g]})]}):(0,d.jsxs)("div",{className:"vf-editor-chat-empty",children:[(0,d.jsx)("div",{className:"vf-editor-chat-kicker",children:"AI Copilot"}),(0,d.jsx)("h2",{children:t?"Start a new chat.":"Repurpose this video."}),(0,d.jsx)("p",{children:t?"Use the brainstorm tools to go from zero context to angles, hooks, and a strategy you can actually test.":"Use the brainstorm tools to turn this video into a native ad for your product, spot product-placement opportunities, and shape the timeline you can actually test. You can also connect from your own AI coding agent, including Claude Code or OpenAI Codex, and ask it to work against this composition."}),(0,d.jsx)("div",{className:"vf-editor-chat-empty-prompts","aria-label":"Example prompts",children:t?(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("div",{children:"I don't know where to start"}),(0,d.jsx)("div",{children:"Help me think of persuasive angles"}),(0,d.jsx)("div",{children:"Help me think of viral hooks"})]}):(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("div",{children:"I don't know where to start"}),(0,d.jsx)("div",{children:"Repurpose this video into a social media native ad for my product"}),(0,d.jsx)("div",{children:"Help me identify product placement opportunities in this video for my product"})]})})]})}),(0,d.jsx)("div",{className:"vf-editor-chat-footer",hidden:ot||it,children:(0,d.jsxs)("div",{className:"vf-editor-chat-composer","data-drop-target":ge?"true":"false",onDragEnter:m=>{m.preventDefault(),Q(!0)},onDragOver:m=>{m.preventDefault(),ge||Q(!0)},onDragLeave:m=>{m.preventDefault();let v=m.relatedTarget;v instanceof Node&&m.currentTarget.contains(v)||Q(!1)},onDrop:m=>{Tx(m)},children:[ge?(0,d.jsx)("div",{className:"vf-editor-chat-dropzone-hint",children:"Drop files to attach"}):null,U.length?(0,d.jsx)("div",{className:"vf-editor-chat-composer-attachments-strip",children:U.map(m=>(0,d.jsx)(VF,{attachment:m,onRemove:()=>x(v=>v.filter(w=>w.id!==m.id))},m.id))}):null,(0,d.jsxs)("div",{className:"vf-editor-chat-composer-row",children:[(0,d.jsx)("button",{type:"button",className:"vf-editor-chat-attach-button","aria-label":"Open upload drawer",onClick:()=>ie(!0),children:"\u{1F4CE}"}),(0,d.jsx)("textarea",{rows:1,placeholder:t?"Describe the offer, audience, or strategy problem you want help with...":"Ask it to call a route, inspect jobs, save config, or continue this thread...",className:"vf-editor-chat-input",value:I,onChange:m=>N(m.target.value),onKeyDown:Cx,onPaste:m=>{Ex(m)}}),(0,d.jsx)("button",{type:"button",className:"vf-editor-chat-send-button",onClick:()=>{if(Qf){wx();return}AS()},disabled:Qf?!1:!CS,children:Qf?"Stop":"Send"})]}),(0,d.jsx)("input",{ref:i,type:"file",accept:"image/*,video/*,audio/*,application/pdf,text/plain,text/markdown",multiple:!0,hidden:!0,onChange:m=>{vx(m)}})]})})]})]}),(0,d.jsx)(eB,{apiKey:e.vidfarmApiKey,open:V,onClose:()=>ie(!1),onConfirm:m=>x(v=>[...v,...m])})]})}var Tn=Cn(Tc(),1);rR();function tB(){let e=document.getElementById("page-runtime-boot");return e?.textContent?JSON.parse(e.textContent):null}function qf(e){let t=new Date;return t.setDate(t.getDate()+e),t.toISOString()}async function nB(e){if(!e.userId)return;let t=e.store.getState();if(!e.force&&t.channels.length&&t.channelsUpdatedAt)return;let n=new URLSearchParams({start_date:qf(-7),end_date:qf(30)}),r=await fetch(`/u/${encodeURIComponent(e.userId)}/calendar/feed?${n.toString()}`,{headers:{accept:"application/json"}}),o=await r.json().catch(()=>null);!r.ok||!o||(e.store.getState().setCalendarData({channels:Array.isArray(o.channels)?o.channels:[],posts:Array.isArray(o.posts)?o.posts:[],rangeStart:o.startDate||qf(-7),rangeEnd:o.endDate||qf(30),replaceRange:!0}),window.dispatchEvent(new CustomEvent("vidfarm:flockposter-cache-updated")))}function rB({boot:e}){let t=(0,Gi.useMemo)(()=>lR(e),[e]),n=tR(t,i=>i.boot.title),[r,o]=(0,Gi.useState)(null);return(0,Gi.useEffect)(()=>{t.getState().setHydratedAt(new Date().toISOString()),document.documentElement.dataset.reactRuntime="true",document.documentElement.dataset.reactRuntimePage=e.pageKind,document.title=n},[e.pageKind,t,n]),(0,Gi.useEffect)(()=>{if(!e.editorChat)return;let i=document.querySelector("[data-template-editor-chat-root]");o(i instanceof HTMLElement?i:null)},[e.editorChat]),e.editorChat&&r?(0,ZR.createPortal)((0,Tn.jsx)(Ds,{fallback:(0,Tn.jsx)(oB,{}),children:(0,Tn.jsx)(QR,{boot:e.editorChat})}),r):null}function oB(){return(0,Tn.jsxs)("div",{style:{display:"grid",placeItems:"center",height:"100%",padding:"24px",textAlign:"center",gap:"12px",color:"#5c6a82"},children:[(0,Tn.jsx)("div",{style:{fontSize:"0.72rem",fontWeight:800,letterSpacing:"0.14em",textTransform:"uppercase"},children:"Chat error"}),(0,Tn.jsx)("div",{style:{fontSize:"0.92rem"},children:"Something went wrong loading the chat. Reload the page to try again."}),(0,Tn.jsx)("button",{type:"button",onClick:()=>window.location.reload(),style:{marginTop:"4px",minHeight:"34px",padding:"0 16px",border:"1px solid rgba(191, 164, 109, 0.34)",borderRadius:"999px",background:"rgba(255, 255, 255, 0.92)",color:"#243041",fontWeight:700,cursor:"pointer"},children:"Reload"})]})}var Qo=tB(),ES=document.getElementById("page-runtime-root"),TS=aR(Qo?.userId??null),Yf=null;function tx(e={}){return!e.force&&Yf||(Yf=nB({userId:Qo?.userId??null,store:TS,force:e.force}).catch(()=>{})),Yf}window.__vidfarmFlockPosterCache={readSnapshot:()=>nS(Qo?.userId??null),ensureHydrated:tx,setChannelsData:e=>{TS.getState().setChannelsData(e),window.dispatchEvent(new CustomEvent("vidfarm:flockposter-cache-updated"))},setCalendarData:e=>{TS.getState().setCalendarData(e),window.dispatchEvent(new CustomEvent("vidfarm:flockposter-cache-updated"))}};tx();Or("page_runtime.boot",{has_boot:!!Qo,has_root:!!ES,page_kind:Qo?.pageKind??null,editor_chat_template_id:Qo?.editorChat?.template?.templateId??null});Qo&&ES&&(0,ex.createRoot)(ES).render((0,Tn.jsx)(Ds,{fallback:(0,Tn.jsx)(Tn.Fragment,{}),onError:e=>po("page_runtime.render_error",{message:e instanceof Error?e.message:String(e)}),children:(0,Tn.jsx)(rB,{boot:Qo})}));
|
|
46
46
|
/*! Bundled license information:
|
|
47
47
|
|
|
48
48
|
react/cjs/react.production.min.js:
|