@veltdev/sdk 4.4.0-beta.12 → 4.4.0-beta.13
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/package.json +1 -1
- package/velt.js +4 -4
package/velt.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var SNIPPYLY_VERSION = '4.4.0-beta.
|
|
1
|
+
var SNIPPYLY_VERSION = '4.4.0-beta.13';
|
|
2
2
|
(function(m,w){"use strict";function rt(){var e=K.splice(0,K.length);for(ie=0;e.length;)e.shift().call(null,e.shift())}function me(e,t){for(var n=0,r=e.length;n<r;n++)Te(e[n],t)}function ot(e){for(var t,n=0,r=e.length;n<r;n++)t=e[n],U(t,q[pe(t)])}function fe(e){return function(t){Lt(t)&&(Te(t,e),L.length&&me(t.querySelectorAll(L),e))}}function pe(e){var t=le.call(e,"is"),n=e.nodeName.toUpperCase(),r=v.call(D,t?Y+t.toUpperCase():x+n);return t&&-1<r&&!De(n,t)?-1:r}function De(e,t){return-1<L.indexOf(e+'[is="'+t+'"]')}function Ie(e){var t=e.currentTarget,n=e.attrChange,r=e.attrName,o=e.target,l=e[W]||2,a=e[He]||3;!ce||o&&o!==t||!t[y]||r==="style"||e.prevValue===e.newValue&&(e.newValue!==""||n!==l&&n!==a)||t[y](r,n===l?null:e.prevValue,n===a?null:e.newValue)}function Fe(e){var t=fe(e);return function(n){K.push(t,n.target),ie&&clearTimeout(ie),ie=setTimeout(rt,1)}}function de(e){nt&&(nt=!1,e.currentTarget.removeEventListener(Ze,de)),L.length&&me((e.target||u).querySelectorAll(L),e.detail===E?E:b),R&&at()}function lt(e,t){var n=this;Ye.call(n,e,t),Me.call(n,{target:n})}function Se(e,t,n){var r=t.apply(e,n),o=pe(r);return-1<o&&U(r,q[o]),n.pop()&&L.length&&ot(r.querySelectorAll(L)),r}function he(e,t){Tt(e,t),$?$.observe(e,gt):(ue&&(e.setAttribute=lt,e[H]=Ee(e),e[g](st,Me)),e[g](N,Ie)),e[k]&&ce&&(e.created=!0,e[k](),e.created=!1)}function at(){for(var e,t=0,n=G.length;t<n;t++)e=G[t],V.contains(e)||(n--,G.splice(t--,1),Te(e,E))}function Ve(e){throw new Error("A "+e+" type is already registered")}function Te(e,t){var n,r,o=pe(e);-1<o&&!Mt.call(e,"TEMPLATE")&&(Q(e,q[o]),o=0,t!==b||e[b]?t!==E||e[E]||(e[b]=!1,e[E]=!0,r="disconnected",o=1):(e[E]=!1,e[b]=!0,r="connected",o=1,R&&v.call(G,e)<0&&G.push(e)),o&&(n=e[t+O]||e[r+O])&&n.call(e))}function z(){}function Pe(e,t,n){var r=n&&n[_]||"",o=t.prototype,l=Ce(o),a=t.observedAttributes||ye,s={prototype:l};oe(l,k,{value:function(){if(te)te=!1;else if(!this[B]){this[B]=!0,new t(this),o[k]&&o[k].call(this);var i=j[ne.get(t)];(!Z||i.create.length>1)&&_e(this)}}}),oe(l,y,{value:function(i){-1<v.call(a,i)&&o[y]&&o[y].apply(this,arguments)}}),o[qe]&&oe(l,ut,{value:o[qe]}),o[Be]&&oe(l,ct,{value:o[Be]}),r&&(s[_]=r),e=e.toUpperCase(),j[e]={constructor:t,create:r?[r,re(e)]:[e]},ne.set(t,e),u[S](e.toLowerCase(),s),Le(e),P[e].r()}function Re(e){var t=j[e.toUpperCase()];return t&&t.constructor}function Ue(e){return typeof e=="string"?e:e&&e.is||""}function _e(e){for(var t,n=e[y],r=n?e.attributes:ye,o=r.length;o--;)t=r[o],n.call(e,t.name||t.nodeName,null,t.value||t.nodeValue)}function Le(e){return e=e.toUpperCase(),e in P||(P[e]={},P[e].p=new Xe(function(t){P[e].r=t})),P[e].p}function ke(){C&&delete m.customElements,I(m,"customElements",{configurable:!0,value:new z}),I(m,"CustomElementRegistry",{configurable:!0,value:z});for(var e=it.get(/^HTML[A-Z]*[a-z]/),t=e.length;t--;function(n){var r=m[n];if(r){m[n]=function(o){var l,a;return o||(o=this),o[B]||(te=!0,l=j[ne.get(o.constructor)],a=Z&&l.create.length===1,o=a?Reflect.construct(r,ye,l.constructor):u.createElement.apply(u,l.create),o[B]=!0,te=!1,a||_e(o)),o},m[n].prototype=r.prototype;try{r.prototype.constructor=m[n]}catch{dt=!0,I(r,B,{value:m[n]})}}}(e[t]));u.createElement=function(n,r){var o=Ue(r);return o?Ae.call(this,n,re(o)):Ae.call(this,n)},et||(Oe=!0,u[S](""))}var u=m.document,T=m.Object,it=function(e){var t,n,r,o,l=/^[A-Z]+[a-z]/,a=function(p){var f,h=[];for(f in i)p.test(f)&&h.push(f);return h},s=function(p,f){(f=f.toLowerCase())in i||(i[p]=(i[p]||[]).concat(f),i[f]=i[f.toUpperCase()]=p)},i=(T.create||T)(null),c={};for(n in e)for(o in e[n])for(r=e[n][o],i[o]=r,t=0;t<r.length;t++)i[r[t].toLowerCase()]=i[r[t].toUpperCase()]=o;return c.get=function(p){return typeof p=="string"?i[p]||(l.test(p)?[]:""):a(p)},c.set=function(p,f){return l.test(p)?s(p,f):s(f,p),c},c}({collections:{HTMLAllCollection:["all"],HTMLCollection:["forms"],HTMLFormControlsCollection:["elements"],HTMLOptionsCollection:["options"]},elements:{Element:["element"],HTMLAnchorElement:["a"],HTMLAppletElement:["applet"],HTMLAreaElement:["area"],HTMLAttachmentElement:["attachment"],HTMLAudioElement:["audio"],HTMLBRElement:["br"],HTMLBaseElement:["base"],HTMLBodyElement:["body"],HTMLButtonElement:["button"],HTMLCanvasElement:["canvas"],HTMLContentElement:["content"],HTMLDListElement:["dl"],HTMLDataElement:["data"],HTMLDataListElement:["datalist"],HTMLDetailsElement:["details"],HTMLDialogElement:["dialog"],HTMLDirectoryElement:["dir"],HTMLDivElement:["div"],HTMLDocument:["document"],HTMLElement:["element","abbr","address","article","aside","b","bdi","bdo","cite","code","command","dd","dfn","dt","em","figcaption","figure","footer","header","i","kbd","mark","nav","noscript","rp","rt","ruby","s","samp","section","small","strong","sub","summary","sup","u","var","wbr"],HTMLEmbedElement:["embed"],HTMLFieldSetElement:["fieldset"],HTMLFontElement:["font"],HTMLFormElement:["form"],HTMLFrameElement:["frame"],HTMLFrameSetElement:["frameset"],HTMLHRElement:["hr"],HTMLHeadElement:["head"],HTMLHeadingElement:["h1","h2","h3","h4","h5","h6"],HTMLHtmlElement:["html"],HTMLIFrameElement:["iframe"],HTMLImageElement:["img"],HTMLInputElement:["input"],HTMLKeygenElement:["keygen"],HTMLLIElement:["li"],HTMLLabelElement:["label"],HTMLLegendElement:["legend"],HTMLLinkElement:["link"],HTMLMapElement:["map"],HTMLMarqueeElement:["marquee"],HTMLMediaElement:["media"],HTMLMenuElement:["menu"],HTMLMenuItemElement:["menuitem"],HTMLMetaElement:["meta"],HTMLMeterElement:["meter"],HTMLModElement:["del","ins"],HTMLOListElement:["ol"],HTMLObjectElement:["object"],HTMLOptGroupElement:["optgroup"],HTMLOptionElement:["option"],HTMLOutputElement:["output"],HTMLParagraphElement:["p"],HTMLParamElement:["param"],HTMLPictureElement:["picture"],HTMLPreElement:["pre"],HTMLProgressElement:["progress"],HTMLQuoteElement:["blockquote","q","quote"],HTMLScriptElement:["script"],HTMLSelectElement:["select"],HTMLShadowElement:["shadow"],HTMLSlotElement:["slot"],HTMLSourceElement:["source"],HTMLSpanElement:["span"],HTMLStyleElement:["style"],HTMLTableCaptionElement:["caption"],HTMLTableCellElement:["td","th"],HTMLTableColElement:["col","colgroup"],HTMLTableElement:["table"],HTMLTableRowElement:["tr"],HTMLTableSectionElement:["thead","tbody","tfoot"],HTMLTemplateElement:["template"],HTMLTextAreaElement:["textarea"],HTMLTimeElement:["time"],HTMLTitleElement:["title"],HTMLTrackElement:["track"],HTMLUListElement:["ul"],HTMLUnknownElement:["unknown","vhgroupv","vkeygen"],HTMLVideoElement:["video"]},nodes:{Attr:["node"],Audio:["audio"],CDATASection:["node"],CharacterData:["node"],Comment:["#comment"],Document:["#document"],DocumentFragment:["#document-fragment"],DocumentType:["node"],HTMLDocument:["#document"],Image:["img"],Option:["option"],ProcessingInstruction:["node"],ShadowRoot:["#shadow-root"],Text:["#text"],XMLDocument:["xml"]}});typeof w!="object"&&(w={type:w||"auto"});var K,Me,X,Ee,$,ve,Q,U,A,S="registerElement",xe=1e5*m.Math.random()>>0,H="__"+S+xe,g="addEventListener",b="attached",O="Callback",E="detached",_="extends",y="attributeChanged"+O,ut=b+O,qe="connected"+O,Be="disconnected"+O,k="created"+O,ct=E+O,W="ADDITION",He="REMOVAL",N="DOMAttrModified",Ze="DOMContentLoaded",st="DOMSubtreeModified",x="<",Y="=",mt=/^[A-Z][._A-Z0-9]*-[-._A-Z0-9]*$/,ft=["ANNOTATION-XML","COLOR-PROFILE","FONT-FACE","FONT-FACE-SRC","FONT-FACE-URI","FONT-FACE-FORMAT","FONT-FACE-NAME","MISSING-GLYPH"],D=[],q=[],L="",V=u.documentElement,v=D.indexOf||function(e){for(var t=this.length;t--&&this[t]!==e;);return t},ge=T.prototype,be=ge.hasOwnProperty,J=ge.isPrototypeOf,I=T.defineProperty,ye=[],ee=T.getOwnPropertyDescriptor,je=T.getOwnPropertyNames,pt=T.getPrototypeOf,Ge=T.setPrototypeOf,ze=!!T.__proto__,dt=!1,B="__dreCEv1",C=m.customElements,Z=!/^force/.test(w.type)&&!!(C&&C.define&&C.get&&C.whenDefined),Ke=T.create||T,ht=m.Map||function(){var e,t=[],n=[];return{get:function(r){return n[v.call(t,r)]},set:function(r,o){e=v.call(t,r),e<0?n[t.push(r)-1]=o:n[e]=o}}},Xe=m.Promise||function(e){function t(l){for(r=!0;n.length;)n.shift()(l)}var n=[],r=!1,o={catch:function(){return o},then:function(l){return n.push(l),r&&setTimeout(t,1),o}};return e(t),o},te=!1,j=Ke(null),P=Ke(null),ne=new ht,re=function(e){return e.toLowerCase()},Ce=T.create||function e(t){return t?(e.prototype=t,new e):this},Tt=Ge||(ze?function(e,t){return e.__proto__=t,e}:je&&ee?function(){function e(t,n){for(var r,o=je(n),l=0,a=o.length;l<a;l++)r=o[l],be.call(t,r)||I(t,r,ee(n,r))}return function(t,n){do e(t,n);while((n=pt(n))&&!J.call(n,t));return t}}():function(e,t){for(var n in t)e[n]=t[n];return e}),F=m.MutationObserver||m.WebKitMutationObserver,$e=m.HTMLAnchorElement,d=(m.HTMLElement||m.Element||m.Node).prototype,R=!J.call(d,V),oe=R?function(e,t,n){return e[t]=n.value,e}:I,Lt=R?function(e){return e.nodeType===1}:function(e){return J.call(d,e)},G=R&&[],Qe=d.attachShadow,We=d.cloneNode,Mt=d.closest||function(e){for(var t=this;t&&t.nodeName!==e;)t=t.parentNode;return t},we=d.dispatchEvent,le=d.getAttribute,Et=d.hasAttribute,vt=d.removeAttribute,Ye=d.setAttribute,ae=u.createElement,Ht=u.importNode,Ae=ae,gt=F&&{attributes:!0,characterData:!0,attributeOldValue:!0},Je=F||function(e){ue=!1,V.removeEventListener(N,Je)},ie=0,et=S in u&&!/^force-all/.test(w.type),tt=!0,Oe=!1,ue=!0,nt=!0,ce=!0;if(F&&(A=u.createElement("div"),A.innerHTML="<div><div></div></div>",new F(function(e,t){if(e[0]&&e[0].type=="childList"&&!e[0].removedNodes[0].childNodes.length){A=ee(d,"innerHTML");var n=A&&A.set;n&&I(d,"innerHTML",{set:function(r){for(;this.lastChild;)this.removeChild(this.lastChild);n.call(this,r)}})}t.disconnect(),A=null}).observe(A,{childList:!0,subtree:!0}),A.innerHTML=""),et||(Ge||ze?(Q=function(e,t){J.call(t,e)||he(e,t)},U=he):(Q=function(e,t){e[H]||(e[H]=T(!0),he(e,t))},U=Q),R?(ue=!1,function(){var e=ee(d,g),t=e.value,n=function(l){var a=new CustomEvent(N,{bubbles:!0});a.attrName=l,a.prevValue=le.call(this,l),a.newValue=null,a[He]=a.attrChange=2,vt.call(this,l),we.call(this,a)},r=function(l,a){var s=Et.call(this,l),i=s&&le.call(this,l),c=new CustomEvent(N,{bubbles:!0});Ye.call(this,l,a),c.attrName=l,c.prevValue=s?i:null,c.newValue=a,s?c.MODIFICATION=c.attrChange=1:c[W]=c.attrChange=0,we.call(this,c)},o=function(l){var a,s=l.currentTarget,i=s[H],c=l.propertyName;i.hasOwnProperty(c)&&(i=i[c],a=new CustomEvent(N,{bubbles:!0}),a.attrName=i.name,a.prevValue=i.value||null,a.newValue=i.value=s[c]||null,a.prevValue==null?a[W]=a.attrChange=0:a.MODIFICATION=a.attrChange=1,we.call(s,a))};e.value=function(l,a,s){l===N&&this[y]&&this.setAttribute!==r&&(this[H]={className:{name:"class",value:this.className}},this.setAttribute=r,this.removeAttribute=n,t.call(this,"propertychange",o)),t.call(this,l,a,s)},I(d,g,e)}()):F||(V[g](N,Je),V.setAttribute(H,1),V.removeAttribute(H),ue&&(Me=function(e){var t,n,r,o=this;if(o===e.target){t=o[H],o[H]=n=Ee(o);for(r in n){if(!(r in t))return X(0,o,r,t[r],n[r],W);if(n[r]!==t[r])return X(1,o,r,t[r],n[r],"MODIFICATION")}for(r in t)if(!(r in n))return X(2,o,r,t[r],n[r],He)}},X=function(e,t,n,r,o,l){var a={attrChange:e,currentTarget:t,attrName:n,prevValue:r,newValue:o};a[l]=e,Ie(a)},Ee=function(e){for(var t,n,r={},o=e.attributes,l=0,a=o.length;l<a;l++)t=o[l],(n=t.name)!=="setAttribute"&&(r[n]=t.value);return r})),u[S]=function(e,t){if(n=e.toUpperCase(),tt&&(tt=!1,F?($=function(i,c){function p(f,h){for(var M=0,se=f.length;M<se;h(f[M++]));}return new F(function(f){for(var h,M,se,Ne=0,bt=f.length;Ne<bt;Ne++)h=f[Ne],h.type==="childList"?(p(h.addedNodes,i),p(h.removedNodes,c)):(M=h.target,ce&&M[y]&&h.attributeName!=="style"&&(se=le.call(M,h.attributeName))!==h.oldValue&&M[y](h.attributeName,h.oldValue,se))})}(fe(b),fe(E)),ve=function(i){return $.observe(i,{childList:!0,subtree:!0}),i},ve(u),Qe&&(d.attachShadow=function(){return ve(Qe.apply(this,arguments))})):(K=[],u[g]("DOMNodeInserted",Fe(b)),u[g]("DOMNodeRemoved",Fe(E))),u[g](Ze,de),u[g]("readystatechange",de),u.importNode=function(i,c){switch(i.nodeType){case 1:return Se(u,Ht,[i,!!c]);case 11:for(var p=u.createDocumentFragment(),f=i.childNodes,h=f.length,M=0;M<h;M++)p.appendChild(u.importNode(f[M],!!c));return p;default:return We.call(i,!!c)}},d.cloneNode=function(i){return Se(this,We,[!!i])}),Oe)return Oe=!1;if(-2<v.call(D,Y+n)+v.call(D,x+n)&&Ve(e),!mt.test(n)||-1<v.call(ft,n))throw new Error("The type "+e+" is invalid");var n,r,o=function(){return a?u.createElement(s,n):u.createElement(s)},l=t||ge,a=be.call(l,_),s=a?t[_].toUpperCase():n;return a&&-1<v.call(D,x+s)&&Ve(s),r=D.push((a?Y:x)+n)-1,L=L.concat(L.length?",":"",a?s+'[is="'+e.toLowerCase()+'"]':s),o.prototype=q[r]=be.call(l,"prototype")?l.prototype:Ce(d),L.length&&me(u.querySelectorAll(L),b),o},u.createElement=Ae=function(e,t){var n=Ue(t),r=n?ae.call(u,e,re(n)):ae.call(u,e),o=""+e,l=v.call(D,(n?Y:x)+(n||o).toUpperCase()),a=-1<l;return n&&(r.setAttribute("is",n=n.toLowerCase()),a&&(a=De(o.toUpperCase(),n))),ce=!u.createElement.innerHTMLHelper,a&&U(r,q[l]),r}),addEventListener("beforeunload",function(){delete u.createElement,delete u.importNode,delete u[S]},!1),z.prototype={constructor:z,define:Z?function(e,t,n){if(n)Pe(e,t,n);else{var r=e.toUpperCase();j[r]={constructor:t,create:[r]},ne.set(t,r),C.define(e,t)}}:Pe,get:Z?function(e){return C.get(e)||Re(e)}:Re,whenDefined:Z?function(e){return Xe.race([C.whenDefined(e),Le(e)])}:Le},!C||/^force/.test(w.type))ke();else if(!w.noBuiltIn)try{(function(e,t,n){var r=new RegExp(`^<a\\s+is=('|")`+n+"\\1></a>$");if(t[_]="a",e.prototype=Ce($e.prototype),e.prototype.constructor=e,m.customElements.define(n,e,t),!r.test(u.createElement("a",{is:n}).outerHTML)||!r.test(new e().outerHTML))throw t})(function e(){return Reflect.construct($e,[],e)},{},"document-register-element-a"+xe)}catch{ke()}if(!w.noBuiltIn)try{if(ae.call(u,"a","a").outerHTML.indexOf("is")<0)throw{}}catch{re=function(t){return{is:t.toLowerCase()}}}})(window);
|
|
3
3
|
|
|
4
4
|
var kfe=Object.create;var Dw=Object.defineProperty,Rfe=Object.defineProperties,Nfe=Object.getOwnPropertyDescriptor,Ffe=Object.getOwnPropertyDescriptors,Lfe=Object.getOwnPropertyNames,ww=Object.getOwnPropertySymbols,fz=Object.getPrototypeOf,f9=Object.prototype.hasOwnProperty,vz=Object.prototype.propertyIsEnumerable,Bfe=Reflect.get;var hz=(n,o,t)=>o in n?Dw(n,o,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[o]=t,I=(n,o)=>{for(var t in o||={})f9.call(o,t)&&hz(n,t,o[t]);if(ww)for(var t of ww(o))vz.call(o,t)&&hz(n,t,o[t]);return n},T=(n,o)=>Rfe(n,Ffe(o));var v9=(n,o)=>{var t={};for(var e in n)f9.call(n,e)&&o.indexOf(e)<0&&(t[e]=n[e]);if(n!=null&&ww)for(var e of ww(n))o.indexOf(e)<0&&vz.call(n,e)&&(t[e]=n[e]);return t};var Vfe=(n,o)=>()=>(o||n((o={exports:{}}).exports,o),o.exports),Aw=(n,o)=>{for(var t in o)Dw(n,t,{get:o[t],enumerable:!0})},Ufe=(n,o,t,e)=>{if(o&&typeof o=="object"||typeof o=="function")for(let i of Lfe(o))!f9.call(n,i)&&i!==t&&Dw(n,i,{get:()=>o[i],enumerable:!(e=Nfe(o,i))||e.enumerable});return n};var Cz=(n,o,t)=>(t=n!=null?kfe(fz(n)):{},Ufe(o||!n||!n.__esModule?Dw(t,"default",{value:n,enumerable:!0}):t,n));var Pd=(n,o,t)=>Bfe(fz(n),t,o);var ee=(n,o,t)=>new Promise((e,i)=>{var r=c=>{try{s(t.next(c))}catch(p){i(p)}},a=c=>{try{s(t.throw(c))}catch(p){i(p)}},s=c=>c.done?e(c.value):Promise.resolve(c.value).then(r,a);s((t=t.apply(n,o)).next())});var RH=Vfe((Xqi,kH)=>{"use strict";var Ct={};Ct.generateIdentifier=function(){return Math.random().toString(36).substring(2,12)};Ct.localCName=Ct.generateIdentifier();Ct.splitLines=function(n){return n.trim().split(`
|
|
@@ -166,7 +166,7 @@ Content-Type: `+p.contentType+`\r
|
|
|
166
166
|
d="M4.646 4.646a.5.5 0 0 1 .708 0L8 7.293l2.646-2.647a.5.5 0 0 1 .708.708L8.707 8l2.647 2.646a.5.5 0 0 1-.708.708L8 8.707l-2.646 2.647a.5.5 0 0 1-.708-.708L7.293 8 4.646 5.354a.5.5 0 0 1 0-.708z"
|
|
167
167
|
/>
|
|
168
168
|
</svg>
|
|
169
|
-
`},dt.CommentAnnotationPriorityMap={P0:{id:"P0",name:"P0",color:"var(--velt-error, #FF7162)",lightColor:"var(--velt-error-light, #F7E7E7) "},P1:{id:"P1",name:"P1",color:"var(--velt-warning, #ECB000)",lightColor:"var(--velt-warning-light, #FEFCEA)"},P2:{id:"P2",name:"P2",color:"var(--velt-text-7, #777E91)",lightColor:"var(--velt-background-1, #F3F3F5)"}},dt.WorkspaceRoles=[{id:mo.COMMENTER?.toLowerCase(),name:mo.COMMENTER,description:"Can comment on this project",permissions:[]},{id:mo.ADMIN?.toLowerCase(),name:mo.ADMIN,description:"Can comment on all projects and has access to the portal",permissions:[]}],dt.DocumentAccessTypeMap={[di.PUBLIC]:{id:di.PUBLIC,name:di.PUBLIC,description:"Anyone with link can view"},[di.RESTRICTED]:{id:di.RESTRICTED,name:di.RESTRICTED,description:"Only people with access can view"}},dt.DocumentAccessTypeMapSF={[di.PUBLIC]:{id:di.PUBLIC,name:di.PUBLIC,description:"Anyone with the link can comment after logging in."},[di.RESTRICTED]:{id:di.RESTRICTED,name:di.RESTRICTED,description:"Only people added to this project can comment."}},dt.CommentCategoryMap={bug:{id:"bug",name:"Bug",color:"#FF7162"},feedback:{id:"feedback",name:"Feedback",color:"#00C48C"},question:{id:"question",name:"Question",color:"#FFD166"}},dt.OVERLAY_POSITIONS=[{originX:"end",originY:"top",overlayX:"start",overlayY:"top"},{originX:"start",originY:"bottom",overlayX:"start",overlayY:"top"},{originX:"end",originY:"bottom",overlayX:"end",overlayY:"top"},{originX:"center",originY:"bottom",overlayX:"center",overlayY:"top"},{originX:"start",originY:"top",overlayX:"start",overlayY:"bottom"},{originX:"end",originY:"top",overlayX:"end",overlayY:"bottom"},{originX:"center",originY:"top",overlayX:"center",overlayY:"bottom"},{originX:"start",originY:"top",overlayX:"end",overlayY:"top"},{originX:"start",originY:"bottom",overlayX:"end",overlayY:"bottom"},{originX:"start",originY:"center",overlayX:"end",overlayY:"center"},{originX:"end",originY:"bottom",overlayX:"start",overlayY:"bottom"},{originX:"end",originY:"center",overlayX:"start",overlayY:"center"}],dt.OVERLAY_POSITIONS_FOR_POPOVER_MODE=[{originX:"end",originY:"top",overlayX:"start",overlayY:"top"},{originX:"end",originY:"center",overlayX:"start",overlayY:"center"},{originX:"end",originY:"bottom",overlayX:"start",overlayY:"bottom"},{originX:"start",originY:"top",overlayX:"end",overlayY:"top"},{originX:"start",originY:"center",overlayX:"end",overlayY:"center"},{originX:"start",originY:"bottom",overlayX:"end",overlayY:"bottom"}];var U=dt;var fn=(n,o=0)=>{try{let t=3735928559^o,e=1103547991^o;for(let i=0,r;i<n.length;i++)r=n.charCodeAt(i),t=Math.imul(t^r,2654435761),e=Math.imul(e^r,1597334677);return t=Math.imul(t^t>>>16,2246822507)^Math.imul(e^e>>>13,3266489909),e=Math.imul(e^e>>>16,2246822507)^Math.imul(t^t>>>13,3266489909),4294967296*(2097151&e)+(t>>>0)}catch(t){return pt.catch("Error in cyrb53: ",t),0}},JOe=()=>{try{return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^crypto.getRandomValues(new Uint8Array(1))[0]&15>>+n/4).toString(16))}catch(n){return pt.catch("Error in uuidv4: ",n),""}},Rt=n=>{try{return Ea.hashStr(n)}catch(o){return pt.catch("Error in hashStr: ",o),n}},ud=n=>fn(n).toString(),uV=n=>Rt(n),hd=n=>Rt(n).toString(),hl=n=>Rt(n).toString(),om=n=>{try{if(n)return typeof n=="string"?Ea.hashStr(n):Array.isArray(n)?Ea.hashStr(n.join("-")):"";{let o=JOe();return Ea.hashStr(o)}}catch(o){return pt.catch("Error in getMultiThreadAnnotationId: ",o),""}},Xi=(n,o,t)=>{try{if(n&&o){if(n.featureAllowList&&n.featureAllowList.length&&!n.featureAllowList.includes(t)||n.userIdAllowList&&n.userIdAllowList.length&&!n.userIdAllowList.includes(o.userId)||n.userGroupIdAllowList&&n.userGroupIdAllowList.length&&!n.userGroupIdAllowList.includes(o.groupId||"")||n.userPlanAllowList&&n.userPlanAllowList.length&&!n.userPlanAllowList.includes(o.plan||""))return!1;if(n.urlAllowList){let e=window.location.href;if(n.urlAllowList.length&&!n.urlAllowList.filter(i=>e.includes(i)).length)return!1}return!0}return!1}catch(e){return pt.catch("Error in isFeatureAllowed: ",e),!1}},xn=()=>{try{let n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",o="";for(let t=0;t<20;t++)o+=n.charAt(Math.floor(Math.random()*n.length));return o}catch(n){return pt.catch("Error in utils generateId: ",n),""}},Sp=n=>{try{let o=0;if(n){let t=new Date().getTime();o=Math.abs(t-n)}return o}catch(o){return pt.catch("Error in utils getFirebaseTimeDiffInMins: ",o),0}};var Mie=()=>{try{return Zn.debugMode||!!sessionStorage.getItem("debugMode")||!!sessionStorage.getItem("forceDebugMode")}catch(n){return pt.catch("Error in showLogs: ",n),!1}},Xo=n=>{try{return typeof n!="object"?Object.assign({},...Object.keys(n).sort().map(o=>({[o]:n[o]&&typeof n[o]=="object"?Xo(n[o]):n[o]}))):n}catch(o){return pt.catch("Error in sortObjectByKeys: ",o),n}},hV=(n,o,t)=>ee(void 0,null,function*(){try{let e=yield t6e(o),i=new Uint8Array(new TextEncoder().encode(t)).slice(0,16),r=new TextEncoder().encode(n),a=yield window.crypto.subtle.encrypt({name:"AES-CBC",iv:i},e,r);return btoa(String.fromCharCode(...new Uint8Array(a)))}catch(e){return pt.catch("Error in encrypt: ",e),n}}),fV=(n,o,t)=>ee(void 0,null,function*(){try{let e=yield e6e(o),i=new Uint8Array(new TextEncoder().encode(t)).slice(0,16),r=new Uint8Array(atob(n).split("").map(s=>s.charCodeAt(0))),a=yield window.crypto.subtle.decrypt({name:"AES-CBC",iv:i},e,r);return new TextDecoder().decode(a)}catch(e){return pt.catch("Error in decrypt: ",e),n}}),e6e=n=>ee(void 0,null,function*(){try{let o=new TextEncoder().encode(n),t=new Uint8Array(32);return t.fill(0),t.set(o.slice(0,32)),yield window.crypto.subtle.importKey("raw",t,"AES-CBC",!1,["decrypt"])}catch(o){throw pt.catch("Error in importDecryptKey:",o),o}}),bp=(n,o)=>ee(void 0,null,function*(){try{let t="Velt"+o;return yield hV(JSON.stringify(n),t,Rt(t))}catch(t){return pt.catch("Error in encryptData: ",t),n}}),Pie=(n,o)=>ee(void 0,null,function*(){try{let t="Velt"+o,e=yield fV(n,t,Rt(t));return JSON.parse(e)}catch(t){return pt.catch("Error in decryptData: ",t),null}}),$O=n=>{try{switch(n?.region){case"asiaSouthEast1":return"asiaSouthEast1";case"asiaNorthEast1":return"asiaNorthEast1";case"europeWest1":return"europeWest1";default:return"usCentral1"}}catch(o){return pt.catch("Error in getRegion: ",o),"usCentral1"}},t6e=n=>ee(void 0,null,function*(){try{let o=new TextEncoder().encode(n),t=new Uint8Array(32);return t.fill(0),t.set(o.slice(0,32)),yield window.crypto.subtle.importKey("raw",t,"AES-CBC",!1,["encrypt"])}catch(o){throw pt.catch("Error in importKey:",o),o}}),kie=n=>{try{if(n&&typeof n=="object"){let o=Xo(n);return fn(JSON.stringify(o))}else return null}catch(o){return pt.catch("Error in utils generateLocationId: ",o),null}},ji=(n,o=[])=>(n?.tagName?.toLowerCase().indexOf("velt-")>=0&&![U.TAGS.VELT_VIDEO_PLAYER.toLowerCase()].includes(n?.tagName?.toLowerCase())||n?.tagName?.toLowerCase().indexOf("snippyly-")>=0||n?.className?.split&&(n?.className?.split(" ")?.indexOf("snippyly-overlay-panel")>=0||n?.className?.split(" ")?.indexOf("cdk-overlay-container")>=0))&&!o?.includes(n?.tagName?.toLowerCase())?!0:n?.parentNode&&ji(n?.parentNode,o),xo=n=>{try{return!!document?.body?.contains(n)}catch(o){return pt.catch("Error in utils isElementInsideBody: ",o),!1}};var Co=(n,o)=>{try{return Object.prototype.toString.call(n)===Object.prototype.toString.call(o)?Object.prototype.toString.call(n)==="[object Object]"||Object.prototype.toString.call(n)==="[object Array]"?Object.keys(n).length!==Object.keys(o).length?!1:Object.keys(n).every(t=>Co(n[t],o[t])):n===o:!1}catch(t){return pt.catch("Error in utils deepCompare: ",t),!1}},nv=(n,o,t=1)=>{try{if(o){let e=n6e(o.textContent,n,t);if(e>=0){let i=(o?.ownerDocument).createNodeIterator(o,NodeFilter.SHOW_TEXT),r,a=[];for(;r=i.nextNode();)a.push(r);let s=[],c=e,p=n.length,h=c+p,_=0;for(let E=0;E<a.length;E++){let D=a[E],B=_;if(_+=D.textContent?.length,_>=c&&!s.length?s.push({textNode:D,startOffset:c-B}):_>=c&&_<h&&s.push({textNode:D}),_>=h){if(s.length===1&&s[0].textNode===D){s.push({textNode:D,endOffset:c-B+n.length});break}let G=p;s.forEach(X=>{G-=X.textNode.textContent?.length-(X.startOffset||0)}),s.push({textNode:D,endOffset:G});break}}return s}}return[]}catch(e){return pt.catch("Error in utils calculateNodes: ",e),[]}},n6e=(n,o,t=1)=>{try{if(n?.includes(o)){let e=n.split(o,t);return e.length===t?e.join(o).length:-1}else return-1}catch(e){return pt.catch("Error in utils getTextPosition: ",e),-1}},Au=(n,o,t,e,i)=>{try{let r=new Range;r.setStart(n,o),r.setEnd(t,e);let a=r.toString(),s=0;if(n.nodeType===Node.TEXT_NODE){let c=n,p="";if(c)for(;c=c.previousSibling;)p=(c.textContent||"")+p;if(p){let h=new RegExp(im(i),"g");s=(p.match(h)||[]).length}}if(a){let c=new RegExp(im(i),"g");return(a.match(c)||[]).length+s}else return s}catch(r){return pt.catch("Error in utils getSelectedTextOccurrenceInRange: ",r),0}},im=n=>{try{return n&&typeof n=="string"?n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"):n}catch(o){return pt.catch("Error in utils escapeRegExp: ",o),n}},iv=n=>{try{return n==null?null:n.scrollHeight>n.clientHeight?n:iv(n?.parentNode)}catch(o){return pt.catch("Error in utils getScrollableParent: ",o),null}},yp=n=>{try{return n==null?[]:n.scrollHeight>n.clientHeight?[n,...yp(n?.parentNode)]:yp(n?.parentNode)}catch(o){return pt.catch("Error in utils getScrollableParents: ",o),[]}},vV=(n,o)=>{try{if(n&&o){let t=n.getBoundingClientRect(),e=o.getBoundingClientRect(),i=t.top-e.top+(o.tagName?.toLowerCase()==="html"?0:o.scrollTop),r=t.left-e.left;return{top:i,left:r}}else return null}catch(t){return pt.catch("Error in utils getRelativeTopLeftPosition: ",t),null}},ov=(n,o)=>`${fn(n+"_"+o)}`,_i=()=>{try{let n=new Zi;return n.url=window.location.href,n.path=window.location.pathname,n.queryParams=window.location.search,n.baseUrl=window.location.origin,n.title=document.title,n}catch(n){pt.catch("Error in utils getPageInfo: ",n);return}},fd=n=>{try{return n?n?.hasAttribute&&n?.hasAttribute(U.ATTRIBUTES.VELT_COMMENT_DISABLED)?!0:fd(n?.parentElement):!1}catch(o){return pt.catch("Error in utils isCommentDisabledOnElement: ",o),!1}},HO=n=>{try{return n?n?.hasAttribute&&n?.hasAttribute(U.ATTRIBUTES.VELT_TAG_DISABLED)?!0:HO(n?.parentElement):!1}catch(o){return pt.catch("Error in utils isTagDisabledOnElement: ",o),!1}},zO=n=>{try{return n?n?.hasAttribute&&n?.hasAttribute(U.ATTRIBUTES.VELT_ARROW_DISABLED)?!0:zO(n?.parentElement):!1}catch(o){return pt.catch("Error in utils isArrowDisabledOnElement: ",o),!1}},GO=n=>{try{return n?n?.hasAttribute&&n?.hasAttribute(U.ATTRIBUTES.VELT_AREA_DISABLED)?!0:GO(n?.parentElement):!1}catch(o){return pt.catch("Error in utils isAreaDisabledOnElement: ",o),!1}},WO=n=>{try{return n?n?.hasAttribute&&n?.hasAttribute(U.ATTRIBUTES.VELT_RECORDER_DISABLED)?!0:WO(n?.parentElement):!1}catch(o){return pt.catch("Error in utils isRecorderDisabledOnElement: ",o),!1}};var Ta=()=>{try{return window?.Snippyly?.version}catch(n){return pt.catch("Error in utils getSdkVersion: ",n),null}},qO=n=>{try{let o=new URL(n);return Object.values(U.URL_PARAMS).forEach(t=>{o.searchParams.delete(t)}),o.href}catch(o){return pt.catch("Error in utils excludeSnippylyParamsFromUrl: ",o),n}},fs=n=>{try{navigator.clipboard.writeText(n)}catch(o){pt.catch("Error in copyToClipboard: ",o)}},rS=n=>{try{let o=Rie(n);return o&&typeof o=="string"&&o.includes("/svg")&&(o=o.split("/svg")[0]+"/*[name()='svg']"),o}catch(o){pt.catch("Error in utils getXPath:",o)}},Rie=n=>{try{if(n){if(typeof n=="string")return document.evaluate(n,document,null,0,null);if(!n||n.nodeType!=1)return"";if(n.id&&n?.tagName?.toLowerCase()!=="svg"&&document.querySelectorAll(`[id='${n.id}']`)?.length===1)return"//*[@id='"+n.id+"']";let o=[].filter.call(n.parentNode?.children?n.parentNode?.children:[],function(t){return t.tagName==n.tagName});return Rie(n.parentNode)+"/"+n.tagName.toLowerCase()+(o.length>1?"["+([].indexOf.call(o,n)+1)+"]":"")}}catch(o){pt.catch("Error in utils calculateXPath:",o)}},Nie=n=>{try{let o=[];return n.forEach(t=>{let e={};e.commonAncestorContainer=i6e(t.commonAncestorContainer),e.text=t.toString(),e.occurrence=Au(t.commonAncestorContainer,0,t.startContainer,t.startOffset,t.toString())+1,o.push(e)}),o}catch{return[]}},i6e=n=>{try{if(n.nodeType===Node.TEXT_NODE){let o=1,t=n.previousSibling;for(;t;)t.nodeType===Node.TEXT_NODE&&o++,t=t.previousSibling;return rS(n.parentElement)}else return rS(n)}catch(o){return pt.catch("Error in utils getXPathForText: ",o),rS(n)}},CV=(n,o)=>{try{return n?n?.hasAttribute&&(o&&n.hasAttribute("contenteditable")||n?.getAttribute(U.ATTRIBUTES.VELT_LIVE_SELECTION_ENABLED)==="true")?n:CV(n?.parentElement,o):null}catch(t){return pt.catch("Error in utils getSelectionEnabledElement: ",t),null}},YO=n=>{try{let o,t=[],e=document.createTreeWalker(n,NodeFilter.SHOW_TEXT,null);for(;o=e.nextNode();)t.push(o);return t}catch(o){return pt.catch("Error in utils getTextNodesInsideElement: ",o),[]}},Fie=n=>{try{return n<576||n>=576&&n<767?"Mobile":n>=768&&n<992?"Tablet":n>=992&&n<1520?"Desktop":"Monitor"}catch(o){return pt.catch("Error in utils getDeviceTypeFromDeviceWidth: ",o),""}},Ip=n=>new Promise(o=>setTimeout(o,n)),Lie=(n,o=0)=>new Promise((t,e)=>{let i=document.createElement("video");i.setAttribute("src",URL.createObjectURL(n)),i.load(),i.addEventListener("error",r=>{e("error when loading video file: "+r)}),i.addEventListener("loadedmetadata",()=>{if(i.duration<o){e("video is too short.");return}setTimeout(()=>{i.currentTime=o},200),i.addEventListener("seeked",()=>{let r=document.createElement("canvas");r.width=i.videoWidth,r.height=i.videoHeight;let a=r.getContext("2d");a.drawImage(i,0,0,r.width,r.height),a.canvas.toBlob(s=>{i.remove(),t(s)},"image/jpeg",.75)})})}),Bie=n=>{try{return new Promise((o,t)=>{let e=new FileReader;e.onloadend=()=>o(e.result),e.readAsDataURL(n)})}catch(o){return pt.catch("Error in utils blobToBase64: ",o),Promise.resolve("")}},_V=(n,o="image/jpeg")=>{try{let t=atob(n.split(",")[1]),e=new ArrayBuffer(t.length),i=new Uint8Array(e);for(let r=0;r<t.length;r++)i[r]=t.charCodeAt(r);return new Blob([e],{type:o})}catch(t){return pt.catch("Error in utils base64ToBlob: ",t),null}},Vie=(n,o,t=20)=>new Promise((e,i)=>{let r=new Image;r.crossOrigin="Anonymous",r.onload=()=>{let a=r.width,s=r.height,c=600,p=s/a*c,h="http://www.w3.org/2000/svg",_=document.createElementNS(h,"svg");_.setAttribute("xmlns",h),_.setAttribute("width",c.toString()),_.setAttribute("height",p.toString()),_.setAttribute("viewBox",`0 0 ${c} ${p}`);let E=document.createElementNS(h,"circle"),D=document.createElementNS(h,"polygon"),B=16,G=B+16,X=c/2,he=p/2;if(E.setAttribute("cx",X.toString()),E.setAttribute("cy",he.toString()),E.setAttribute("r",G.toString()),E.setAttribute("fill","lightgrey"),D.setAttribute("points",`${X-B/2},${he-B} ${X-B/2},${he+B} ${X+B},${he}`),D.setAttribute("fill","#ffffff"),_.appendChild(E),_.appendChild(D),o){let we=o.length*16-10,Ee=16*1.5,Pe=(c-we)/2,Ce=p-Ee-10,ue=document.createElementNS(h,"rect");ue.setAttribute("x",Pe.toString()),ue.setAttribute("y",Ce.toString()),ue.setAttribute("width",we.toString()),ue.setAttribute("height",Ee.toString()),ue.setAttribute("fill","#353945b3"),ue.setAttribute("rx","12"),_.appendChild(ue);let Be=document.createElementNS(h,"text");Be.textContent=o,Be.setAttribute("x",(c/2).toString()),Be.setAttribute("y",(Ce+16).toString()),Be.setAttribute("font-size","16"),Be.setAttribute("text-anchor","middle"),Be.setAttribute("fill","white"),_.appendChild(Be)}let Ie=new XMLSerializer().serializeToString(_),Me=new Image,Le=new Blob([Ie],{type:"image/svg+xml;charset=utf-8"}),We=URL.createObjectURL(Le);Me.onload=()=>{let ke=document.createElement("canvas");ke.width=c,ke.height=p;let we=ke.getContext("2d");we.beginPath(),we.moveTo(t,0),we.lineTo(c-t,0),we.quadraticCurveTo(c,0,c,t),we.lineTo(c,p-t),we.quadraticCurveTo(c,p,c-t,p),we.lineTo(t,p),we.quadraticCurveTo(0,p,0,p-t),we.lineTo(0,t),we.quadraticCurveTo(0,0,t,0),we.closePath(),we.clip(),we.drawImage(r,0,0,c,p),we.drawImage(Me,0,0,c,p);let Ee=ke.toDataURL("image/png");e(Ee)},Me.onerror=i,Me.src=We},r.onerror=i,r.src=n});var KO=n=>{try{return n?.replace(/[\n\t\u200D]/g,"")?.split(/\s+/)?.filter(e=>e?.trim()?.length)||[]}catch(o){return pt.catch("Error in utils getWords: ",o),[]}},cr=(n,o=[])=>{try{let t=o.map(e=>`[${e}="${n}"]`).join(",");return document.querySelector(t)}catch(t){return pt.catch("Error in utils getElementByAttributes: ",t),null}},Uie=(n,o=[])=>{try{let t=o.map(e=>`[${e}="${n}"]`).join(",");return document.querySelectorAll(t)}catch(t){return pt.catch("Error in utils getElementsByAttributes: ",t),[]}},rc=n=>{try{let o=Math.floor(n/3600),t=Math.floor((n-o*3600)/60),e=Math.floor(n-o*3600-t*60);return o&&o<10&&(o="0"+o),t<10&&(t="0"+t),e<10&&(e="0"+e),(o?o+":":"")+t+":"+e}catch{return""}},jie=(n,o=10)=>{try{if(!n||!n.currentTime)throw new Error("Invalid video element reference provided");let t=n.currentTime,e=Math.floor(t/o)*o,i=e+o;return{startSlot:rc(e),endSlot:rc(i),timeSlot:rc(e)+" - "+rc(i)}}catch{return null}},yV=(n,o=["@"])=>{try{let t="",e,i=n.getRootNode();if(i instanceof ShadowRoot?e=i?.getSelection():e=window.getSelection(),e?.rangeCount){let r=e.getRangeAt(0),a=r.startOffset,s=r.endOffset,c=r?.commonAncestorContainer?.textContent;c?t=o6e(c,s,o):t=""}return t}catch(t){return pt.catch("Error in utils getWordAtCursor: ",t),""}};var o6e=(n,o,t=["@"])=>{try{let e=-1;for(let i of t){let r=n.lastIndexOf(i,o),a=n.lastIndexOf(i,r-1);r>e&&(i==="@"?a===-1||a!==-1&&n.slice(a,r+1).indexOf(" ")!==-1?e=r:e=a:e=r)}return e!==-1?n.substring(e,o):""}catch(e){return pt.catch("Error in utils getStringFromLastAtSymbol: ",e),""}},$ie=(n,o,t=["@"])=>{try{let e=r6e(n),i=e&&e.getSelection!==void 0?e.getSelection():window.getSelection();if(i?.rangeCount){let r=i.getRangeAt(0),a=r.startOffset,s=r?.commonAncestorContainer?.textContent;if(s){let c=-1;for(let p of t){let h=s.lastIndexOf(p,a),_=s.lastIndexOf(p,h-1);h>c&&(p==="@"?_===-1||_!==-1&&s.slice(_,h+1).indexOf(" ")!==-1?c=h:c=_:c=h)}if(c!==-1){let p=s.substring(0,c),h=s.substring(r.endOffset),_=document.createElement("span");_.textContent=o,_.style.color="var(--velt-accent)";let E=r.commonAncestorContainer;if(E.nodeType===Node.TEXT_NODE){let D=E.parentNode;if(D){let B=document.createTextNode(p),G=document.createTextNode(h);D.replaceChild(G,E),D.insertBefore(_,G),D.insertBefore(B,_)}}}}}}catch(e){pt.catch("Error in utils replaceWordAtCursor: ",e)}},ZO=()=>{try{let o=window.getSelection()?.getRangeAt(0),t=o?.commonAncestorContainer,e=o?.startContainer,i=o?.endContainer,r=[];r.push(t),r.push(e),r.push(i);let a=!1;for(let s of r)if(s&&ji(s,[U.TAGS.SNIPPYLY_TEXT_HIGHLIGHT,U.TAGS.SNIPPYLY_COMMENT_TEXT_PORTAL,U.TAGS.SNIPPYLY_HIGHLIGHT_USER_TEXT,U.TAGS.SNIPPYLY_COMMENT_TEXT])){a=!0;break}return a}catch(n){return pt.catch("Error in utils isTextSelectionIncludesSnippylyElement: ",n),!1}},Hie=(n,o,t)=>{try{let e=document.querySelector(`[id=${n}]`);if(e)e.name=o,e.content=t;else{let i=document.createElement("meta");i.id=n,i.name=o,i.content=t,document.getElementsByTagName("head")[0].appendChild(i)}}catch{}},zie=n=>{try{if(n){let o=document.querySelector(`[id=${n}]`);o&&o.remove()}}catch{}},Gie=()=>{try{let o=new Date().getTimezoneOffset(),t=Math.floor(Math.abs(o)/60),e=Math.abs(o)%60;return`UTC${o>0?"-":"+"}${t?.toString()?.padStart(2,"0")}:${e?.toString()?.padStart(2,"0")}`}catch(n){return pt.catch("Error in utils getTimezone: ",n),""}},Wie=()=>{try{let n=[];return document.querySelectorAll("*").forEach(t=>{(t.scrollHeight>t.clientHeight||t.scrollWidth>t.clientWidth||["auto","scroll"].includes(getComputedStyle(t).overflow))&&n.push(t)}),n}catch(n){return pt.catch("Error in utils getScrollableElements: ",n),[]}},qie=(n,o)=>Math.sqrt((n.x-o.x)**2+(n.y-o.y)**2),SV=(n,o={x:window.innerWidth/2,y:window.innerHeight/2})=>{try{let t=n;for(;t.children.length>0;){let e=null,i=Number.MAX_SAFE_INTEGER;for(let r=0;r<t.children.length;r++){let a=t.children[r],s=a.getBoundingClientRect(),c={x:s.left+s.width/2,y:s.top+s.height/2},p=qie(c,o);(s.top>=0||s.bottom<=window.innerHeight)&&s.width>0&&s.height>0&&p<=i&&(e=a,i=p)}if(e===null)break;t=e}return t}catch(t){return pt.catch("Error in utils getInnermostElement: ",t),null}},Yie=n=>{try{let{offsetWidth:o,offsetHeight:t,scrollTop:e}=n,i=n,r={x:o/2,y:e+t/2};for(;i.children.length>0;){let a=null,s=Number.MAX_SAFE_INTEGER;for(let c=0;c<i.children.length;c++){let p=i.children[c],h={x:p.offsetLeft+p.offsetWidth/2,y:p.offsetTop+p.offsetHeight/2},_=qie(h,r);p.offsetTop>=0&&p.offsetWidth>0&&p.offsetHeight>0&&_<=s&&(a=p,s=_)}if(a===null)break;i=a}return i}catch(o){return pt.catch("Error in utils getNestedInnermostElement: ",o),null}},Kie=()=>{try{let n=window.innerWidth/2,o=window.innerHeight/2,t=document.elementFromPoint(n,o);for(;t&&t.tagName==="BODY";)o+=2,t=document.elementFromPoint(n,o);return t}catch(n){return pt.catch("Error in utils getCenteredBackgroundElement: ",n),null}},bV=(n,o,t=!1)=>{try{let e=n.getBoundingClientRect(),i=o.getBoundingClientRect(),r=o.offsetTop;t&&(r=r-e.height/2+i.height/2),n.scrollTo({top:r,behavior:"smooth"})}catch(e){pt.catch("Error in utils nestedScrollIntoView: ",e)}},XO=(n,o=!0)=>{try{let t=document.body.getBoundingClientRect(),e=n.getBoundingClientRect(),i=e.top-t.top,r=window.innerHeight,a=i;o&&(a=a-r/2+e.height/2),window.scrollTo({top:a,behavior:"smooth"})}catch(t){pt.catch("Error in utils scrollIntoView: ",t)}},Zie=(n=!1)=>{try{let o=!0;return n&&(o=/\sChrome\/[\d.]+ Mobile\s/.test(navigator.userAgent)),"ontouchstart"in window||navigator.maxTouchPoints>0||o}catch(o){return pt.catch("Error in utils isTouchDevice: ",o),!1}},Xie=(n,o,t)=>{try{return(1-t)*n+t*o}catch(e){pt.catch("Error in utils lerp: ",e)}return 0},Qie=(n,o)=>{try{if(n===void 0)return n;if(n=n.replace("#",""),n.length===6){let t=parseInt(n,16),e=(t>>16)+o;e>255&&(e=255),e<0&&(e=0);let i=(t&255)+o;i>255&&(i=255),i<0&&(i=0);let r=(t>>8&255)+o;return r>255&&(r=255),r<0&&(r=0),`#${(i|r<<8|e<<16).toString(16)}`}else return n}catch(t){pt.catch("Error in utils multiplyColor: ",t)}return n},Jie=n=>{try{return n in U.TEXT_COLOR_MAP?U.TEXT_COLOR_MAP[n]:"#141416"}catch(o){return pt.catch("Error in generateUserColor:",o),"#141416"}},ac=()=>{try{let n=localStorage.getItem(U.LOCAL_STORAGE.SNIPPYLY_DEFAULT_MEDIA_SOURCE_OPTIONS);if(n)return JSON.parse(n)}catch(n){return pt.catch("Error in getDefaultMediaStreamOptions:",n),{}}},QO=(n,o)=>{try{let t=o*(Math.PI/180),e=Math.cos(t);return e?n/e:n}catch(t){return pt.catch("Error in calculateHypotenuse:",t),0}},IV=(n,o,t=!0)=>{try{let e=[],i=t?n:n.parentNode;for(;i;)e.push(i),i=i.parentNode;let r=t?o:o.parentNode;for(;r;){if(e.indexOf(r)!==-1)return r;r=r.parentNode}return null}catch(e){return pt.catch("Error in utils findCommonParent: ",e),null}},EV=(n,o,t,e)=>{let i=t.getBoundingClientRect(),r=e.getBoundingClientRect(),a=i.left+n,s=i.top+o,c=a-r.left,p=s-r.top;return{x:c,y:p}},Ep=n=>{try{let o={height:0,width:0};if(typeof n?.getBBox=="function"){let t=n?.getBBox(),e=n?.getBoundingClientRect();o.height=parseFloat(e?.height||t.height||0),o.width=parseFloat(e?.width||t.width||0)}else{let t=window.getComputedStyle(n);if(o.height=n?.clientHeight||parseFloat(t.getPropertyValue("height"))||0,o.width=n?.clientWidth||parseFloat(t.getPropertyValue("width"))||0,n?.getBoundingClientRect&&typeof n?.getBoundingClientRect=="function"){let e=n?.getBoundingClientRect();o?.height||(o.height=e?.height||n?.clientHeight||n?.offsetHeight||0),o?.width||(o.width=e?.width||n?.clientWidth||n?.offsetWidth||0)}}return o}catch(o){return pt.catch("Error in utils getElementDimensions: ",o),{height:0,width:0}}},rm=n=>{try{let o=n;for(;o;){if(window?.getComputedStyle(o)?.getPropertyValue("background-clip")=="text")return!0;o=o?.parentElement}return!1}catch(o){return pt.catch("Error in utils hasParentWithBackgroundClip: ",o),!1}},r6e=n=>{try{let o=n;for(;o;){if(o.toString()==="[object ShadowRoot]")return o;o=o.parentNode}}catch(o){pt.catch("Error in utils findShadowRoot: ",o)}return null},$n=n=>{try{let o=["commentCategories","color","resolved","inProgress","positionX","positionY","screenWidth","screenHeight","screenScrollHeight","screenScrollTop","taggedElementPath","taggedElementRect","targetElement","position","documentParamsId","documentParams","ghostComment","areaAnnotationId","iam","commentSource"],t=JSON.parse(JSON.stringify(n)),e={};return Object.keys(t).forEach(i=>{o.includes(i)||(e[i]=t[i])}),JSON.parse(JSON.stringify(e))}catch(o){return pt.catch("Error in utils getCommentAnnotationForClient: ",o),null}};var rv=n=>n===null||typeof n>"u",av=(n,o)=>{try{return!!n?.closest(`[${o}]`)}catch(t){return pt.catch("Error in utils hasParentWithAttribute: ",t),!1}},xV=(n,o=!0)=>{try{let t=[];if(!n||!(n instanceof HTMLElement))return[];o&&t.push(n);for(let e=0;e<n.children.length;e++){let i=n.children[e];t=t.concat(xV(i))}return t}catch(t){return pt.catch("Error in utils getAllNestedChildren: ",t),[]}},eoe=()=>{try{return document.visibilityState==="hidden"?!1:document.hasFocus()}catch(n){return pt.catch("Error in utils isTabActive: ",n),!1}},TV=n=>{try{let o="",t=n?.getAttribute("src");if(t)o=`${fn(t)}`;else{let e=n?.querySelectorAll("source");if(e&&e.length>0){let r=e[0]?.getAttribute("src");r&&(o=`${fn(r)}`)}}return o}catch{return""}},st=n=>{try{return!(n&&(n?.children?.length>0||n?.textContent?.trim()?.length>0))}catch(o){return pt.catch("Error in utils isTemplateEmpty: ",o),!0}},la=(n,o)=>{try{if(!n||!o)return;let t=[],e="",i=0;for(let c=0;c<o.length;c++){let p=o[c];p==="["?(i++,i===1&&e&&(t.push(e),e=""),e+=p):p==="]"?(i--,e+=p,i===0&&(t.push(e),e="")):p==="."&&i===0?e&&(t.push(e),e=""):e+=p}e&&t.push(e);let r,a=I({},n),s=t.reduce((c,p)=>{if(c==null)return;Pi(c)&&(r=c,c=c());let h=p.match(/^\[([^\[\]]+|(\[[^\[\]]*\]))\]$/);if(h){let E=h[1];if(/^\d+$/.test(E)){let D=parseInt(E,10);return Array.isArray(c)?c[D]:void 0}if(E.startsWith("'")&&E.endsWith("'")||E.startsWith('"')&&E.endsWith('"')){let D=E.slice(1,-1);return c[D]}if(E.includes(".")||E.includes("[")){let D=la(a,E);Pi(D)&&(D=D());let B=D?.toString()||"";return c[B]}if(a[E]!==void 0){let D=a[E];return Pi(D)&&(D=D()),c[D]}return c[E]}let _=p;return(p.startsWith("'")&&p.endsWith("'")||p.startsWith('"')&&p.endsWith('"'))&&(_=p.slice(1,-1)),_==="length"&&Array.isArray(c)?c.length:c[_]},n);return r?zi(()=>{try{let c=I({},n);return t.reduce((p,h)=>{if(p==null)return;Pi(p)&&(p=p());let _=h.match(/^\[([^\[\]]+|(\[[^\[\]]*\]))\]$/);if(_){let D=_[1];if(/^\d+$/.test(D)){let B=parseInt(D,10);return Array.isArray(p)?p[B]:void 0}if(D.startsWith("'")&&D.endsWith("'")||D.startsWith('"')&&D.endsWith('"')){let B=D.slice(1,-1);return p[B]}if(D.includes(".")||D.includes("[")){let B=la(c,D);Pi(B)&&(B=B());let G=B?.toString()||"";return p[G]}if(c[D]!==void 0){let B=c[D];return Pi(B)&&(B=B()),p[B]}return p[D]}let E=h;return(h.startsWith("'")&&h.endsWith("'")||h.startsWith('"')&&h.endsWith('"'))&&(E=h.slice(1,-1)),p[E]},n)}catch{return""}}):s}catch{return""}},Ou=(n,o)=>{try{return!!(n?.locationId&&(n.locationId===o?.locationId||o?.location?.id===String(n.locationId))||n?.location?.id&&(n.location.id===o?.location?.id||n.location.id===String(o?.locationId)))}catch(t){return pt.catch("Error in utils isLocationSame: ",t),!1}},toe=()=>{try{let n=document.activeElement,o=new Set,t=10,e=0;for(;n&&n.shadowRoot&&!(o.has(n)||(o.add(n),n=n.shadowRoot.activeElement,e++,e>t)););return n}catch(n){return pt.catch("Error in utils getActiveElement: ",n),null}},_o=(n,o)=>{try{return typeof n=="object"&&typeof o=="object"?JSON.stringify(n)===JSON.stringify(o):n===o}catch{return!1}},sv=n=>{try{let o=JSON.parse(JSON.stringify(n));return n?.clientDocumentId&&(o.documentId=n.clientDocumentId),n?.clientOrganizationId&&(o.organizationId=n.clientOrganizationId),delete o?.clientDocumentId,delete o?.clientOrganizationId,delete o?.veltFolderId,delete o?.parentVeltFolderId,delete o?.pageInfo,o}catch{return n}},ca=n=>{try{if(!n.some(a=>a?.value?.data))return{};let o=null,t=n.reduce((a,s)=>Math.max(a,s.timestamp),0),e=n.find(a=>a.timestamp===t);if(!e)return{};e?.value?.operation?.type==="removed"&&(o=e?.value?.operation);let r=n.map(a=>a.value).reduce((a,s)=>({data:I(I({},a?.data??{}),s?.data??{})}),{});return r.operation=o,r}catch{return{}}},sc=(n,o,t)=>ee(void 0,null,function*(){try{let e=0;for(;e<=(t.retryCount||0);)try{let i=yield n();if(!i)return{success:!1,statusCode:400,message:`${o} failed: No response received`};if(i.statusCode===void 0)return{success:!1,statusCode:400,message:`${o} failed: Response missing statusCode`};if(i.statusCode!==200){if(e++,e>(t.retryCount||0))return{success:!1,statusCode:i.statusCode,message:`${o} failed after ${e} attempts with status code ${i.statusCode}`};t.retryDelay&&(yield new Promise(r=>setTimeout(r,t.retryDelay)));continue}return i}catch(i){if(e++,e>(t.retryCount||0))return{success:!1,statusCode:500,message:`${o} failed with error: ${i instanceof Error?i.message:"Unknown error"}`};t.retryDelay&&(yield new Promise(r=>setTimeout(r,t.retryDelay)))}return{success:!0,statusCode:200}}catch(e){return{success:!1,statusCode:500,message:`${o} failed with unexpected error: ${e instanceof Error?e.message:"Unknown error"}`}}}),aS=n=>{try{if(n&&typeof n=="object"){let o=JSON.parse(JSON.stringify(n));return o?.clientOrganizationId&&(o.organizationId=o.clientOrganizationId,delete o.clientOrganizationId),o?.clientGroupId&&(o.groupId=o.clientGroupId,delete o.clientGroupId),o?.userSnippylyId&&delete o.userSnippylyId,o}else return null}catch(o){return pt.catch("Error in utils getUserForClient: ",o),null}};var Qe=(()=>{let o=class o{constructor(e){this.functions=e,this.sf=!1,this.defaultProperties={},this.draftEvents=[],this.eventRateLimitCache={},this.EVENT_LIMIT=50,this.TIME_WINDOW_MS=60*1e3;try{this.updateDefaultProperties({sdkVersion:Ta()}),window?.location?.href&&(this.defaultProperties.pageUrl=window.location.href)}catch(i){pt.catch("Error in AnalyticsService constructor: ",i)}}updateDefaultProperties(e={}){this.defaultProperties=I(I({},this.defaultProperties),e)}setInstalledFeature(e){try{this.defaultProperties?.installedFeatures||(this.defaultProperties.installedFeatures=[]),this.defaultProperties.installedFeatures.includes(e)||this.defaultProperties.installedFeatures.push(e)}catch(i){pt.catch("Error in AnalyticsService setInstalledFeature: ",i)}}setFeatureConfig({feature:e,config:i}){try{this.defaultProperties.featureConfigs||(this.defaultProperties.featureConfigs={}),this.defaultProperties.featureConfigs[e]||(this.defaultProperties.featureConfigs[e]={}),this.defaultProperties.featureConfigs[e]=I(I({},this.defaultProperties.featureConfigs[e]),i)}catch(r){pt.catch("Error in AnalyticsService setFeatureConfig: ",r)}}setSF(e){try{this.sf=e}catch(i){pt.catch("Error in AnalyticsService setSF: ",i)}}setAuthService(e){try{this.authService=e}catch(i){pt.catch("Error in AnalyticsService setAuthService: ",i)}}setCommentService(e){try{this.commentService=e}catch(i){pt.catch("Error in AnalyticsService setCommentService: ",i)}}setAreaService(e){try{this.areaService=e}catch(i){pt.catch("Error in AnalyticsService setAreaService: ",i)}}setRecorderAnnotationService(e){try{this.recorderAnnotationService=e}catch(i){pt.catch("Error in AnalyticsService setRecorderAnnotationService: ",i)}}setReactionService(e){try{this.reactionService=e}catch(i){pt.catch("Error in AnalyticsService setReactionService: ",i)}}setUserService(e){try{this.userService=e}catch(i){pt.catch("Error in AnalyticsService setUserService: ",i)}}identifyUser(e,i,r={}){try{this.userId=e;let a=typeof i=="object"?JSON.parse(JSON.stringify(i)):i;this.userService?.userDataProviderAvailable()&&a?.userId&&(a={userId:a.userId}),this.user=a;let s=this.defaultProperties?this.defaultProperties.apiKey:null;if(Zn.production||Zn.staging){let c={userId:e,clientUserId:this.user?.userId,traits:T(I({},a),{apiKey:s,forceReset:r?.forceReset}),properties:this.defaultProperties,sf:this.sf,context:this.getContext()};this.setAnalytics("identify",c)}if(this.userId&&this.draftEvents?.length){let c=this.draftEvents?.slice();this.draftEvents=[],c?.forEach(p=>{switch(p.type){case"track":p?.data?.eventName&&this.trackEvent(p.data.eventName,p.data.properties,p.data.mergeDefaultProperties,p.data.userId);break;default:break}})}}catch(a){pt.catch("Error in AnalyticsService identifyUser: ",a)}}trackPage(e,i="",r={}){try{if((Zn.production||Zn.staging)&&this.userId){let a={userId:this.userId,clientUserId:this.user?.userId,name:e,properties:r,sf:this.sf,context:this.getContext()};this.setAnalytics("page",a)}}catch(a){pt.catch("Error in AnalyticsService trackPage: ",a)}}trackEvent(s){return ee(this,arguments,function*(e,i={},r=!0,a){try{if(this.sf&&Oie.includes(e))return;if(Zn.production||Zn.staging)if(this.userId||a){if(this.eventRateLimitCache[e]?.blockedForSession)return;let c=Date.now();if(this.eventRateLimitCache[e]&&c-this.eventRateLimitCache[e].timestamp<this.TIME_WINDOW_MS){if(this.eventRateLimitCache[e].count>=this.EVENT_LIMIT){if(!this.eventRateLimitCache[e].rateLimitExceededEventTriggered){this.eventRateLimitCache[e].rateLimitExceededEventTriggered=!0,this.eventRateLimitCache[e].blockedForSession=!0;let p=I({eventName:e},i||{});this.triggerTrackEvent(Z.Events.Core.SDK_EVENT_RATE_LIMIT_EXCEEDED,p,r)}return}this.eventRateLimitCache[e].count++}else this.eventRateLimitCache[e]={count:1,timestamp:c,rateLimitExceededEventTriggered:!1,blockedForSession:!1};return this.triggerTrackEvent(e,i,r,a)}else this.draftEvents.push({type:"track",data:{eventName:e,properties:i,mergeDefaultProperties:r,userId:a}})}catch(c){pt.catch("Error in AnalyticsService trackEvent: ",c)}})}triggerTrackEvent(s){return ee(this,arguments,function*(e,i={},r=!0,a){try{r&&(i||(i={}),i=I(I({},i),this.defaultProperties));let c;if(i?.annotationId){let h=i.annotationId;if(!c&&this.commentService){let _=this.commentService.getAnnotationById(h);_?.metadata&&(c=_.metadata),_?.targetElementId&&(i.targetElementId=_.targetElementId);let E=this.commentService.getMultiThreadAnnotationById(h);E?.metadata&&(c=E.metadata),E?.targetElementId&&(i.targetElementId=E.targetElementId)}if(!c&&this.recorderAnnotationService){let _=this.recorderAnnotationService.getAnnotationById(h);_?.metadata&&(c=_.metadata)}if(!c&&this.reactionService){let _=this.reactionService.getAnnotationById(h);_?.metadata&&(c=_.metadata),_?.targetElementId&&(i.targetElementId=_.targetElementId)}if(!c&&this.areaService){let _=this.areaService.getAnnotationById(h);_?.metadata&&(c=_.metadata)}}c&&typeof c=="object"&&(i=I(I({},i),c));let p={userId:this.userId||a,clientUserId:this.user?.userId,event:e,properties:i,sf:this.sf,context:this.getContext()};return this.setAnalytics("track",p)}catch(c){pt.catch("Error in AnalyticsService triggerTrackEvent: ",c)}})}setAnalytics(e,i){return ee(this,null,function*(){try{return navigator.onLine?Cr(this.functions,Zn.cloudFunction.sa,{timeout:20*60*1e3})({type:e,data:i}).catch(a=>{pt.warn("Error in AnalyticsService setAnalytics promise: ",e,a)}):void 0}catch(r){pt.catch("Error in AnalyticsService setAnalytics: ",r)}})}trackAuthenticatedEvent(e,i={},r=!0){try{this.authService?.getUser$&&typeof this.authService?.getUser$()?.subscribe=="function"&&(this.authService.getUser()?this.trackEvent(e,i,r):this.authService?.getUser$()?.pipe(Ne(a=>!!a),Je(1))?.subscribe(()=>{this.trackEvent(e,i,r)}))}catch(a){pt.catch("Error in AnalyticsService trackAuthenticatedEvent: ",a)}}getContext(){try{let e={},i=_i();return e.os={name:i?.deviceInfo?.osName,version:i?.deviceInfo?.osVersion},e.page={path:i?.path,title:i?.title,url:i?.url},e.screen={height:i?.deviceInfo?.screenHeight,width:i?.deviceInfo?.screenWidth},e.app={name:i?.deviceInfo?.browserName,version:i?.deviceInfo?.browserVersion},e.device={type:i?.deviceInfo?.deviceType},e.timezone=Gie(),e.userAgent=i?.deviceInfo?.userAgent,e}catch(e){pt.catch("Error in AnalyticsService getContext: ",e)}}};o.\u0275fac=function(i){return new(i||o)(J(Vo))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var y=(()=>{let o=class o{get debugMode(){return Mie()}get logsEnabled(){return this.logsEnabled$.value}constructor(e){this.analyticsService=e,this.logsEnabled$=new fe(!0),this.log("%c[WB] Creating SERVICE LoggingService","color: blue;")}enableLogs(){try{if(this.logsEnabled$.value===!0)return;this.logsEnabled$.next(!0)}catch(e){this.catch("Error in LoggingService enableLogs: ",e)}}disableLogs(){try{if(this.logsEnabled$.value===!1)return;this.logsEnabled$.next(!1)}catch(e){this.catch("Error in LoggingService disableLogs: ",e)}}log(e,...i){this.debugMode&&console.log(e,...i)}warn(e,...i){this.debugMode&&console.warn(e,...i)}error(e,...i){this.debugMode&&console.error(e,...i)}debug(e,...i){this.debugMode&&console.debug(e,...i)}info(e,...i){this.debugMode&&console.info(e,...i)}catch(e,i,r,a=!1){try{let s=i?.message;this.logsEnabled$.value&&(s?.toLowerCase()?.includes("permission denied")||s?.toLowerCase()?.includes("permission_denied")||(i!==void 0?console.warn("Velt: ",e,i):console.warn("Velt: ",e))),a||this.analyticsService.trackEvent(Z.Events.Core.SDK_ERROR,I({sourceMethod:e,message:(i?.message?i?.message:i)||e,clientUserId:this.analyticsService?.user?.userId,snippylyUserId:this.analyticsService?.user?.userSnippylyId,source:"sdk"},r||{}))}catch{}}};o.\u0275fac=function(i){return new(i||o)(J(Qe))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var noe=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},ioe={};var vd,wV;(function(){var n;function o(we,Ee){function Pe(){}Pe.prototype=Ee.prototype,we.D=Ee.prototype,we.prototype=new Pe,we.prototype.constructor=we,we.C=function(Ce,ue,Be){for(var Se=Array(arguments.length-2),Ut=2;Ut<arguments.length;Ut++)Se[Ut-2]=arguments[Ut];return Ee.prototype[ue].apply(Ce,Se)}}function t(){this.blockSize=-1}function e(){this.blockSize=-1,this.blockSize=64,this.g=Array(4),this.B=Array(this.blockSize),this.o=this.h=0,this.s()}o(e,t),e.prototype.s=function(){this.g[0]=1732584193,this.g[1]=4023233417,this.g[2]=2562383102,this.g[3]=271733878,this.o=this.h=0};function i(we,Ee,Pe){Pe||(Pe=0);var Ce=Array(16);if(typeof Ee=="string")for(var ue=0;16>ue;++ue)Ce[ue]=Ee.charCodeAt(Pe++)|Ee.charCodeAt(Pe++)<<8|Ee.charCodeAt(Pe++)<<16|Ee.charCodeAt(Pe++)<<24;else for(ue=0;16>ue;++ue)Ce[ue]=Ee[Pe++]|Ee[Pe++]<<8|Ee[Pe++]<<16|Ee[Pe++]<<24;Ee=we.g[0],Pe=we.g[1],ue=we.g[2];var Be=we.g[3],Se=Ee+(Be^Pe&(ue^Be))+Ce[0]+3614090360&4294967295;Ee=Pe+(Se<<7&4294967295|Se>>>25),Se=Be+(ue^Ee&(Pe^ue))+Ce[1]+3905402710&4294967295,Be=Ee+(Se<<12&4294967295|Se>>>20),Se=ue+(Pe^Be&(Ee^Pe))+Ce[2]+606105819&4294967295,ue=Be+(Se<<17&4294967295|Se>>>15),Se=Pe+(Ee^ue&(Be^Ee))+Ce[3]+3250441966&4294967295,Pe=ue+(Se<<22&4294967295|Se>>>10),Se=Ee+(Be^Pe&(ue^Be))+Ce[4]+4118548399&4294967295,Ee=Pe+(Se<<7&4294967295|Se>>>25),Se=Be+(ue^Ee&(Pe^ue))+Ce[5]+1200080426&4294967295,Be=Ee+(Se<<12&4294967295|Se>>>20),Se=ue+(Pe^Be&(Ee^Pe))+Ce[6]+2821735955&4294967295,ue=Be+(Se<<17&4294967295|Se>>>15),Se=Pe+(Ee^ue&(Be^Ee))+Ce[7]+4249261313&4294967295,Pe=ue+(Se<<22&4294967295|Se>>>10),Se=Ee+(Be^Pe&(ue^Be))+Ce[8]+1770035416&4294967295,Ee=Pe+(Se<<7&4294967295|Se>>>25),Se=Be+(ue^Ee&(Pe^ue))+Ce[9]+2336552879&4294967295,Be=Ee+(Se<<12&4294967295|Se>>>20),Se=ue+(Pe^Be&(Ee^Pe))+Ce[10]+4294925233&4294967295,ue=Be+(Se<<17&4294967295|Se>>>15),Se=Pe+(Ee^ue&(Be^Ee))+Ce[11]+2304563134&4294967295,Pe=ue+(Se<<22&4294967295|Se>>>10),Se=Ee+(Be^Pe&(ue^Be))+Ce[12]+1804603682&4294967295,Ee=Pe+(Se<<7&4294967295|Se>>>25),Se=Be+(ue^Ee&(Pe^ue))+Ce[13]+4254626195&4294967295,Be=Ee+(Se<<12&4294967295|Se>>>20),Se=ue+(Pe^Be&(Ee^Pe))+Ce[14]+2792965006&4294967295,ue=Be+(Se<<17&4294967295|Se>>>15),Se=Pe+(Ee^ue&(Be^Ee))+Ce[15]+1236535329&4294967295,Pe=ue+(Se<<22&4294967295|Se>>>10),Se=Ee+(ue^Be&(Pe^ue))+Ce[1]+4129170786&4294967295,Ee=Pe+(Se<<5&4294967295|Se>>>27),Se=Be+(Pe^ue&(Ee^Pe))+Ce[6]+3225465664&4294967295,Be=Ee+(Se<<9&4294967295|Se>>>23),Se=ue+(Ee^Pe&(Be^Ee))+Ce[11]+643717713&4294967295,ue=Be+(Se<<14&4294967295|Se>>>18),Se=Pe+(Be^Ee&(ue^Be))+Ce[0]+3921069994&4294967295,Pe=ue+(Se<<20&4294967295|Se>>>12),Se=Ee+(ue^Be&(Pe^ue))+Ce[5]+3593408605&4294967295,Ee=Pe+(Se<<5&4294967295|Se>>>27),Se=Be+(Pe^ue&(Ee^Pe))+Ce[10]+38016083&4294967295,Be=Ee+(Se<<9&4294967295|Se>>>23),Se=ue+(Ee^Pe&(Be^Ee))+Ce[15]+3634488961&4294967295,ue=Be+(Se<<14&4294967295|Se>>>18),Se=Pe+(Be^Ee&(ue^Be))+Ce[4]+3889429448&4294967295,Pe=ue+(Se<<20&4294967295|Se>>>12),Se=Ee+(ue^Be&(Pe^ue))+Ce[9]+568446438&4294967295,Ee=Pe+(Se<<5&4294967295|Se>>>27),Se=Be+(Pe^ue&(Ee^Pe))+Ce[14]+3275163606&4294967295,Be=Ee+(Se<<9&4294967295|Se>>>23),Se=ue+(Ee^Pe&(Be^Ee))+Ce[3]+4107603335&4294967295,ue=Be+(Se<<14&4294967295|Se>>>18),Se=Pe+(Be^Ee&(ue^Be))+Ce[8]+1163531501&4294967295,Pe=ue+(Se<<20&4294967295|Se>>>12),Se=Ee+(ue^Be&(Pe^ue))+Ce[13]+2850285829&4294967295,Ee=Pe+(Se<<5&4294967295|Se>>>27),Se=Be+(Pe^ue&(Ee^Pe))+Ce[2]+4243563512&4294967295,Be=Ee+(Se<<9&4294967295|Se>>>23),Se=ue+(Ee^Pe&(Be^Ee))+Ce[7]+1735328473&4294967295,ue=Be+(Se<<14&4294967295|Se>>>18),Se=Pe+(Be^Ee&(ue^Be))+Ce[12]+2368359562&4294967295,Pe=ue+(Se<<20&4294967295|Se>>>12),Se=Ee+(Pe^ue^Be)+Ce[5]+4294588738&4294967295,Ee=Pe+(Se<<4&4294967295|Se>>>28),Se=Be+(Ee^Pe^ue)+Ce[8]+2272392833&4294967295,Be=Ee+(Se<<11&4294967295|Se>>>21),Se=ue+(Be^Ee^Pe)+Ce[11]+1839030562&4294967295,ue=Be+(Se<<16&4294967295|Se>>>16),Se=Pe+(ue^Be^Ee)+Ce[14]+4259657740&4294967295,Pe=ue+(Se<<23&4294967295|Se>>>9),Se=Ee+(Pe^ue^Be)+Ce[1]+2763975236&4294967295,Ee=Pe+(Se<<4&4294967295|Se>>>28),Se=Be+(Ee^Pe^ue)+Ce[4]+1272893353&4294967295,Be=Ee+(Se<<11&4294967295|Se>>>21),Se=ue+(Be^Ee^Pe)+Ce[7]+4139469664&4294967295,ue=Be+(Se<<16&4294967295|Se>>>16),Se=Pe+(ue^Be^Ee)+Ce[10]+3200236656&4294967295,Pe=ue+(Se<<23&4294967295|Se>>>9),Se=Ee+(Pe^ue^Be)+Ce[13]+681279174&4294967295,Ee=Pe+(Se<<4&4294967295|Se>>>28),Se=Be+(Ee^Pe^ue)+Ce[0]+3936430074&4294967295,Be=Ee+(Se<<11&4294967295|Se>>>21),Se=ue+(Be^Ee^Pe)+Ce[3]+3572445317&4294967295,ue=Be+(Se<<16&4294967295|Se>>>16),Se=Pe+(ue^Be^Ee)+Ce[6]+76029189&4294967295,Pe=ue+(Se<<23&4294967295|Se>>>9),Se=Ee+(Pe^ue^Be)+Ce[9]+3654602809&4294967295,Ee=Pe+(Se<<4&4294967295|Se>>>28),Se=Be+(Ee^Pe^ue)+Ce[12]+3873151461&4294967295,Be=Ee+(Se<<11&4294967295|Se>>>21),Se=ue+(Be^Ee^Pe)+Ce[15]+530742520&4294967295,ue=Be+(Se<<16&4294967295|Se>>>16),Se=Pe+(ue^Be^Ee)+Ce[2]+3299628645&4294967295,Pe=ue+(Se<<23&4294967295|Se>>>9),Se=Ee+(ue^(Pe|~Be))+Ce[0]+4096336452&4294967295,Ee=Pe+(Se<<6&4294967295|Se>>>26),Se=Be+(Pe^(Ee|~ue))+Ce[7]+1126891415&4294967295,Be=Ee+(Se<<10&4294967295|Se>>>22),Se=ue+(Ee^(Be|~Pe))+Ce[14]+2878612391&4294967295,ue=Be+(Se<<15&4294967295|Se>>>17),Se=Pe+(Be^(ue|~Ee))+Ce[5]+4237533241&4294967295,Pe=ue+(Se<<21&4294967295|Se>>>11),Se=Ee+(ue^(Pe|~Be))+Ce[12]+1700485571&4294967295,Ee=Pe+(Se<<6&4294967295|Se>>>26),Se=Be+(Pe^(Ee|~ue))+Ce[3]+2399980690&4294967295,Be=Ee+(Se<<10&4294967295|Se>>>22),Se=ue+(Ee^(Be|~Pe))+Ce[10]+4293915773&4294967295,ue=Be+(Se<<15&4294967295|Se>>>17),Se=Pe+(Be^(ue|~Ee))+Ce[1]+2240044497&4294967295,Pe=ue+(Se<<21&4294967295|Se>>>11),Se=Ee+(ue^(Pe|~Be))+Ce[8]+1873313359&4294967295,Ee=Pe+(Se<<6&4294967295|Se>>>26),Se=Be+(Pe^(Ee|~ue))+Ce[15]+4264355552&4294967295,Be=Ee+(Se<<10&4294967295|Se>>>22),Se=ue+(Ee^(Be|~Pe))+Ce[6]+2734768916&4294967295,ue=Be+(Se<<15&4294967295|Se>>>17),Se=Pe+(Be^(ue|~Ee))+Ce[13]+1309151649&4294967295,Pe=ue+(Se<<21&4294967295|Se>>>11),Se=Ee+(ue^(Pe|~Be))+Ce[4]+4149444226&4294967295,Ee=Pe+(Se<<6&4294967295|Se>>>26),Se=Be+(Pe^(Ee|~ue))+Ce[11]+3174756917&4294967295,Be=Ee+(Se<<10&4294967295|Se>>>22),Se=ue+(Ee^(Be|~Pe))+Ce[2]+718787259&4294967295,ue=Be+(Se<<15&4294967295|Se>>>17),Se=Pe+(Be^(ue|~Ee))+Ce[9]+3951481745&4294967295,we.g[0]=we.g[0]+Ee&4294967295,we.g[1]=we.g[1]+(ue+(Se<<21&4294967295|Se>>>11))&4294967295,we.g[2]=we.g[2]+ue&4294967295,we.g[3]=we.g[3]+Be&4294967295}e.prototype.u=function(we,Ee){Ee===void 0&&(Ee=we.length);for(var Pe=Ee-this.blockSize,Ce=this.B,ue=this.h,Be=0;Be<Ee;){if(ue==0)for(;Be<=Pe;)i(this,we,Be),Be+=this.blockSize;if(typeof we=="string"){for(;Be<Ee;)if(Ce[ue++]=we.charCodeAt(Be++),ue==this.blockSize){i(this,Ce),ue=0;break}}else for(;Be<Ee;)if(Ce[ue++]=we[Be++],ue==this.blockSize){i(this,Ce),ue=0;break}}this.h=ue,this.o+=Ee},e.prototype.v=function(){var we=Array((56>this.h?this.blockSize:2*this.blockSize)-this.h);we[0]=128;for(var Ee=1;Ee<we.length-8;++Ee)we[Ee]=0;var Pe=8*this.o;for(Ee=we.length-8;Ee<we.length;++Ee)we[Ee]=Pe&255,Pe/=256;for(this.u(we),we=Array(16),Ee=Pe=0;4>Ee;++Ee)for(var Ce=0;32>Ce;Ce+=8)we[Pe++]=this.g[Ee]>>>Ce&255;return we};function r(we,Ee){var Pe=s;return Object.prototype.hasOwnProperty.call(Pe,we)?Pe[we]:Pe[we]=Ee(we)}function a(we,Ee){this.h=Ee;for(var Pe=[],Ce=!0,ue=we.length-1;0<=ue;ue--){var Be=we[ue]|0;Ce&&Be==Ee||(Pe[ue]=Be,Ce=!1)}this.g=Pe}var s={};function c(we){return-128<=we&&128>we?r(we,function(Ee){return new a([Ee|0],0>Ee?-1:0)}):new a([we|0],0>we?-1:0)}function p(we){if(isNaN(we)||!isFinite(we))return _;if(0>we)return X(p(-we));for(var Ee=[],Pe=1,Ce=0;we>=Pe;Ce++)Ee[Ce]=we/Pe|0,Pe*=4294967296;return new a(Ee,0)}function h(we,Ee){if(we.length==0)throw Error("number format error: empty string");if(Ee=Ee||10,2>Ee||36<Ee)throw Error("radix out of range: "+Ee);if(we.charAt(0)=="-")return X(h(we.substring(1),Ee));if(0<=we.indexOf("-"))throw Error('number format error: interior "-" character');for(var Pe=p(Math.pow(Ee,8)),Ce=_,ue=0;ue<we.length;ue+=8){var Be=Math.min(8,we.length-ue),Se=parseInt(we.substring(ue,ue+Be),Ee);8>Be?(Be=p(Math.pow(Ee,Be)),Ce=Ce.j(Be).add(p(Se))):(Ce=Ce.j(Pe),Ce=Ce.add(p(Se)))}return Ce}var _=c(0),E=c(1),D=c(16777216);n=a.prototype,n.m=function(){if(G(this))return-X(this).m();for(var we=0,Ee=1,Pe=0;Pe<this.g.length;Pe++){var Ce=this.i(Pe);we+=(0<=Ce?Ce:4294967296+Ce)*Ee,Ee*=4294967296}return we},n.toString=function(we){if(we=we||10,2>we||36<we)throw Error("radix out of range: "+we);if(B(this))return"0";if(G(this))return"-"+X(this).toString(we);for(var Ee=p(Math.pow(we,6)),Pe=this,Ce="";;){var ue=Le(Pe,Ee).g;Pe=he(Pe,ue.j(Ee));var Be=((0<Pe.g.length?Pe.g[0]:Pe.h)>>>0).toString(we);if(Pe=ue,B(Pe))return Be+Ce;for(;6>Be.length;)Be="0"+Be;Ce=Be+Ce}},n.i=function(we){return 0>we?0:we<this.g.length?this.g[we]:this.h};function B(we){if(we.h!=0)return!1;for(var Ee=0;Ee<we.g.length;Ee++)if(we.g[Ee]!=0)return!1;return!0}function G(we){return we.h==-1}n.l=function(we){return we=he(this,we),G(we)?-1:B(we)?0:1};function X(we){for(var Ee=we.g.length,Pe=[],Ce=0;Ce<Ee;Ce++)Pe[Ce]=~we.g[Ce];return new a(Pe,~we.h).add(E)}n.abs=function(){return G(this)?X(this):this},n.add=function(we){for(var Ee=Math.max(this.g.length,we.g.length),Pe=[],Ce=0,ue=0;ue<=Ee;ue++){var Be=Ce+(this.i(ue)&65535)+(we.i(ue)&65535),Se=(Be>>>16)+(this.i(ue)>>>16)+(we.i(ue)>>>16);Ce=Se>>>16,Be&=65535,Se&=65535,Pe[ue]=Se<<16|Be}return new a(Pe,Pe[Pe.length-1]&-2147483648?-1:0)};function he(we,Ee){return we.add(X(Ee))}n.j=function(we){if(B(this)||B(we))return _;if(G(this))return G(we)?X(this).j(X(we)):X(X(this).j(we));if(G(we))return X(this.j(X(we)));if(0>this.l(D)&&0>we.l(D))return p(this.m()*we.m());for(var Ee=this.g.length+we.g.length,Pe=[],Ce=0;Ce<2*Ee;Ce++)Pe[Ce]=0;for(Ce=0;Ce<this.g.length;Ce++)for(var ue=0;ue<we.g.length;ue++){var Be=this.i(Ce)>>>16,Se=this.i(Ce)&65535,Ut=we.i(ue)>>>16,Gt=we.i(ue)&65535;Pe[2*Ce+2*ue]+=Se*Gt,Ie(Pe,2*Ce+2*ue),Pe[2*Ce+2*ue+1]+=Be*Gt,Ie(Pe,2*Ce+2*ue+1),Pe[2*Ce+2*ue+1]+=Se*Ut,Ie(Pe,2*Ce+2*ue+1),Pe[2*Ce+2*ue+2]+=Be*Ut,Ie(Pe,2*Ce+2*ue+2)}for(Ce=0;Ce<Ee;Ce++)Pe[Ce]=Pe[2*Ce+1]<<16|Pe[2*Ce];for(Ce=Ee;Ce<2*Ee;Ce++)Pe[Ce]=0;return new a(Pe,0)};function Ie(we,Ee){for(;(we[Ee]&65535)!=we[Ee];)we[Ee+1]+=we[Ee]>>>16,we[Ee]&=65535,Ee++}function Me(we,Ee){this.g=we,this.h=Ee}function Le(we,Ee){if(B(Ee))throw Error("division by zero");if(B(we))return new Me(_,_);if(G(we))return Ee=Le(X(we),Ee),new Me(X(Ee.g),X(Ee.h));if(G(Ee))return Ee=Le(we,X(Ee)),new Me(X(Ee.g),Ee.h);if(30<we.g.length){if(G(we)||G(Ee))throw Error("slowDivide_ only works with positive integers.");for(var Pe=E,Ce=Ee;0>=Ce.l(we);)Pe=We(Pe),Ce=We(Ce);var ue=ke(Pe,1),Be=ke(Ce,1);for(Ce=ke(Ce,2),Pe=ke(Pe,2);!B(Ce);){var Se=Be.add(Ce);0>=Se.l(we)&&(ue=ue.add(Pe),Be=Se),Ce=ke(Ce,1),Pe=ke(Pe,1)}return Ee=he(we,ue.j(Ee)),new Me(ue,Ee)}for(ue=_;0<=we.l(Ee);){for(Pe=Math.max(1,Math.floor(we.m()/Ee.m())),Ce=Math.ceil(Math.log(Pe)/Math.LN2),Ce=48>=Ce?1:Math.pow(2,Ce-48),Be=p(Pe),Se=Be.j(Ee);G(Se)||0<Se.l(we);)Pe-=Ce,Be=p(Pe),Se=Be.j(Ee);B(Be)&&(Be=E),ue=ue.add(Be),we=he(we,Se)}return new Me(ue,we)}n.A=function(we){return Le(this,we).h},n.and=function(we){for(var Ee=Math.max(this.g.length,we.g.length),Pe=[],Ce=0;Ce<Ee;Ce++)Pe[Ce]=this.i(Ce)&we.i(Ce);return new a(Pe,this.h&we.h)},n.or=function(we){for(var Ee=Math.max(this.g.length,we.g.length),Pe=[],Ce=0;Ce<Ee;Ce++)Pe[Ce]=this.i(Ce)|we.i(Ce);return new a(Pe,this.h|we.h)},n.xor=function(we){for(var Ee=Math.max(this.g.length,we.g.length),Pe=[],Ce=0;Ce<Ee;Ce++)Pe[Ce]=this.i(Ce)^we.i(Ce);return new a(Pe,this.h^we.h)};function We(we){for(var Ee=we.g.length+1,Pe=[],Ce=0;Ce<Ee;Ce++)Pe[Ce]=we.i(Ce)<<1|we.i(Ce-1)>>>31;return new a(Pe,we.h)}function ke(we,Ee){var Pe=Ee>>5;Ee%=32;for(var Ce=we.g.length-Pe,ue=[],Be=0;Be<Ce;Be++)ue[Be]=0<Ee?we.i(Be+Pe)>>>Ee|we.i(Be+Pe+1)<<32-Ee:we.i(Be+Pe);return new a(ue,we.h)}e.prototype.digest=e.prototype.v,e.prototype.reset=e.prototype.s,e.prototype.update=e.prototype.u,wV=ioe.Md5=e,a.prototype.add=a.prototype.add,a.prototype.multiply=a.prototype.j,a.prototype.modulo=a.prototype.A,a.prototype.compare=a.prototype.l,a.prototype.toNumber=a.prototype.m,a.prototype.toString=a.prototype.toString,a.prototype.getBits=a.prototype.i,a.fromNumber=p,a.fromString=h,vd=ioe.Integer=a}).apply(typeof noe<"u"?noe:typeof self<"u"?self:typeof window<"u"?window:{});var JO=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},Cd={};var DV,a6e,lv,AV,sS,e6,OV,MV,PV;(function(){var n,o=typeof Object.defineProperties=="function"?Object.defineProperty:function(L,Q,le){return L==Array.prototype||L==Object.prototype||(L[Q]=le.value),L};function t(L){L=[typeof globalThis=="object"&&globalThis,L,typeof window=="object"&&window,typeof self=="object"&&self,typeof JO=="object"&&JO];for(var Q=0;Q<L.length;++Q){var le=L[Q];if(le&&le.Math==Math)return le}throw Error("Cannot find global object")}var e=t(this);function i(L,Q){if(Q)e:{var le=e;L=L.split(".");for(var ye=0;ye<L.length-1;ye++){var ze=L[ye];if(!(ze in le))break e;le=le[ze]}L=L[L.length-1],ye=le[L],Q=Q(ye),Q!=ye&&Q!=null&&o(le,L,{configurable:!0,writable:!0,value:Q})}}function r(L,Q){L instanceof String&&(L+="");var le=0,ye=!1,ze={next:function(){if(!ye&&le<L.length){var tt=le++;return{value:Q(tt,L[tt]),done:!1}}return ye=!0,{done:!0,value:void 0}}};return ze[Symbol.iterator]=function(){return ze},ze}i("Array.prototype.values",function(L){return L||function(){return r(this,function(Q,le){return le})}});var a=a||{},s=this||self;function c(L){var Q=typeof L;return Q=Q!="object"?Q:L?Array.isArray(L)?"array":Q:"null",Q=="array"||Q=="object"&&typeof L.length=="number"}function p(L){var Q=typeof L;return Q=="object"&&L!=null||Q=="function"}function h(L,Q,le){return L.call.apply(L.bind,arguments)}function _(L,Q,le){if(!L)throw Error();if(2<arguments.length){var ye=Array.prototype.slice.call(arguments,2);return function(){var ze=Array.prototype.slice.call(arguments);return Array.prototype.unshift.apply(ze,ye),L.apply(Q,ze)}}return function(){return L.apply(Q,arguments)}}function E(L,Q,le){return E=Function.prototype.bind&&Function.prototype.bind.toString().indexOf("native code")!=-1?h:_,E.apply(null,arguments)}function D(L,Q){var le=Array.prototype.slice.call(arguments,1);return function(){var ye=le.slice();return ye.push.apply(ye,arguments),L.apply(this,ye)}}function B(L,Q){function le(){}le.prototype=Q.prototype,L.aa=Q.prototype,L.prototype=new le,L.prototype.constructor=L,L.Qb=function(ye,ze,tt){for(var wt=Array(arguments.length-2),no=2;no<arguments.length;no++)wt[no-2]=arguments[no];return Q.prototype[ze].apply(ye,wt)}}function G(L){let Q=L.length;if(0<Q){let le=Array(Q);for(let ye=0;ye<Q;ye++)le[ye]=L[ye];return le}return[]}function X(L,Q){for(let le=1;le<arguments.length;le++){let ye=arguments[le];if(c(ye)){let ze=L.length||0,tt=ye.length||0;L.length=ze+tt;for(let wt=0;wt<tt;wt++)L[ze+wt]=ye[wt]}else L.push(ye)}}class he{constructor(Q,le){this.i=Q,this.j=le,this.h=0,this.g=null}get(){let Q;return 0<this.h?(this.h--,Q=this.g,this.g=Q.next,Q.next=null):Q=this.i(),Q}}function Ie(L){return/^[\s\xa0]*$/.test(L)}function Me(){var L=s.navigator;return L&&(L=L.userAgent)?L:""}function Le(L){return Le[" "](L),L}Le[" "]=function(){};var We=Me().indexOf("Gecko")!=-1&&!(Me().toLowerCase().indexOf("webkit")!=-1&&Me().indexOf("Edge")==-1)&&!(Me().indexOf("Trident")!=-1||Me().indexOf("MSIE")!=-1)&&Me().indexOf("Edge")==-1;function ke(L,Q,le){for(let ye in L)Q.call(le,L[ye],ye,L)}function we(L,Q){for(let le in L)Q.call(void 0,L[le],le,L)}function Ee(L){let Q={};for(let le in L)Q[le]=L[le];return Q}let Pe="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" ");function Ce(L,Q){let le,ye;for(let ze=1;ze<arguments.length;ze++){ye=arguments[ze];for(le in ye)L[le]=ye[le];for(let tt=0;tt<Pe.length;tt++)le=Pe[tt],Object.prototype.hasOwnProperty.call(ye,le)&&(L[le]=ye[le])}}function ue(L){var Q=1;L=L.split(":");let le=[];for(;0<Q&&L.length;)le.push(L.shift()),Q--;return L.length&&le.push(L.join(":")),le}function Be(L){s.setTimeout(()=>{throw L},0)}function Se(){var L=Fn;let Q=null;return L.g&&(Q=L.g,L.g=L.g.next,L.g||(L.h=null),Q.next=null),Q}class Ut{constructor(){this.h=this.g=null}add(Q,le){let ye=Gt.get();ye.set(Q,le),this.h?this.h.next=ye:this.g=ye,this.h=ye}}var Gt=new he(()=>new Dt,L=>L.reset());class Dt{constructor(){this.next=this.g=this.h=null}set(Q,le){this.h=Q,this.g=le,this.next=null}reset(){this.next=this.g=this.h=null}}let It,Nt=!1,Fn=new Ut,eo=()=>{let L=s.Promise.resolve(void 0);It=()=>{L.then(ii)}};var ii=()=>{for(var L;L=Se();){try{L.h.call(L.g)}catch(le){Be(le)}var Q=Gt;Q.j(L),100>Q.h&&(Q.h++,L.next=Q.g,Q.g=L)}Nt=!1};function Oi(){this.s=this.s,this.C=this.C}Oi.prototype.s=!1,Oi.prototype.ma=function(){this.s||(this.s=!0,this.N())},Oi.prototype.N=function(){if(this.C)for(;this.C.length;)this.C.shift()()};function dn(L,Q){this.type=L,this.g=this.target=Q,this.defaultPrevented=!1}dn.prototype.h=function(){this.defaultPrevented=!0};var ui=function(){if(!s.addEventListener||!Object.defineProperty)return!1;var L=!1,Q=Object.defineProperty({},"passive",{get:function(){L=!0}});try{let le=()=>{};s.addEventListener("test",le,Q),s.removeEventListener("test",le,Q)}catch{}return L}();function Mi(L,Q){if(dn.call(this,L?L.type:""),this.relatedTarget=this.g=this.target=null,this.button=this.screenY=this.screenX=this.clientY=this.clientX=0,this.key="",this.metaKey=this.shiftKey=this.altKey=this.ctrlKey=!1,this.state=null,this.pointerId=0,this.pointerType="",this.i=null,L){var le=this.type=L.type,ye=L.changedTouches&&L.changedTouches.length?L.changedTouches[0]:null;if(this.target=L.target||L.srcElement,this.g=Q,Q=L.relatedTarget){if(We){e:{try{Le(Q.nodeName);var ze=!0;break e}catch{}ze=!1}ze||(Q=null)}}else le=="mouseover"?Q=L.fromElement:le=="mouseout"&&(Q=L.toElement);this.relatedTarget=Q,ye?(this.clientX=ye.clientX!==void 0?ye.clientX:ye.pageX,this.clientY=ye.clientY!==void 0?ye.clientY:ye.pageY,this.screenX=ye.screenX||0,this.screenY=ye.screenY||0):(this.clientX=L.clientX!==void 0?L.clientX:L.pageX,this.clientY=L.clientY!==void 0?L.clientY:L.pageY,this.screenX=L.screenX||0,this.screenY=L.screenY||0),this.button=L.button,this.key=L.key||"",this.ctrlKey=L.ctrlKey,this.altKey=L.altKey,this.shiftKey=L.shiftKey,this.metaKey=L.metaKey,this.pointerId=L.pointerId||0,this.pointerType=typeof L.pointerType=="string"?L.pointerType:Am[L.pointerType]||"",this.state=L.state,this.i=L,L.defaultPrevented&&Mi.aa.h.call(this)}}B(Mi,dn);var Am={2:"touch",3:"pen",4:"mouse"};Mi.prototype.h=function(){Mi.aa.h.call(this);var L=this.i;L.preventDefault?L.preventDefault():L.returnValue=!1};var go="closure_listenable_"+(1e6*Math.random()|0),Ws=0;function Br(L,Q,le,ye,ze){this.listener=L,this.proxy=null,this.src=Q,this.type=le,this.capture=!!ye,this.ha=ze,this.key=++Ws,this.da=this.fa=!1}function qs(L){L.da=!0,L.listener=null,L.proxy=null,L.src=null,L.ha=null}function wl(L){this.src=L,this.g={},this.h=0}wl.prototype.add=function(L,Q,le,ye,ze){var tt=L.toString();L=this.g[tt],L||(L=this.g[tt]=[],this.h++);var wt=og(L,Q,ye,ze);return-1<wt?(Q=L[wt],le||(Q.fa=!1)):(Q=new Br(Q,this.src,tt,!!ye,ze),Q.fa=le,L.push(Q)),Q};function _c(L,Q){var le=Q.type;if(le in L.g){var ye=L.g[le],ze=Array.prototype.indexOf.call(ye,Q,void 0),tt;(tt=0<=ze)&&Array.prototype.splice.call(ye,ze,1),tt&&(qs(Q),L.g[le].length==0&&(delete L.g[le],L.h--))}}function og(L,Q,le,ye){for(var ze=0;ze<L.length;++ze){var tt=L[ze];if(!tt.da&&tt.listener==Q&&tt.capture==!!le&&tt.ha==ye)return ze}return-1}var Dl="closure_lm_"+(1e6*Math.random()|0),rg={};function oh(L,Q,le,ye,ze){if(ye&&ye.once)return ag(L,Q,le,ye,ze);if(Array.isArray(Q)){for(var tt=0;tt<Q.length;tt++)oh(L,Q[tt],le,ye,ze);return null}return le=Sc(le),L&&L[go]?L.K(Q,le,p(ye)?!!ye.capture:!!ye,ze):Om(L,Q,le,!1,ye,ze)}function Om(L,Q,le,ye,ze,tt){if(!Q)throw Error("Invalid event type");var wt=p(ze)?!!ze.capture:!!ze,no=Mm(L);if(no||(L[Dl]=no=new wl(L)),le=no.add(Q,le,ye,wt,tt),le.proxy)return le;if(ye=rh(),le.proxy=ye,ye.src=L,ye.listener=le,L.addEventListener)ui||(ze=wt),ze===void 0&&(ze=!1),L.addEventListener(Q.toString(),ye,ze);else if(L.attachEvent)L.attachEvent(dw(Q.toString()),ye);else if(L.addListener&&L.removeListener)L.addListener(ye);else throw Error("addEventListener and attachEvent are unavailable.");return le}function rh(){function L(le){return Q.call(L.src,L.listener,le)}let Q=qC;return L}function ag(L,Q,le,ye,ze){if(Array.isArray(Q)){for(var tt=0;tt<Q.length;tt++)ag(L,Q[tt],le,ye,ze);return null}return le=Sc(le),L&&L[go]?L.L(Q,le,p(ye)?!!ye.capture:!!ye,ze):Om(L,Q,le,!0,ye,ze)}function WC(L,Q,le,ye,ze){if(Array.isArray(Q))for(var tt=0;tt<Q.length;tt++)WC(L,Q[tt],le,ye,ze);else ye=p(ye)?!!ye.capture:!!ye,le=Sc(le),L&&L[go]?(L=L.i,Q=String(Q).toString(),Q in L.g&&(tt=L.g[Q],le=og(tt,le,ye,ze),-1<le&&(qs(tt[le]),Array.prototype.splice.call(tt,le,1),tt.length==0&&(delete L.g[Q],L.h--)))):L&&(L=Mm(L))&&(Q=L.g[Q.toString()],L=-1,Q&&(L=og(Q,le,ye,ze)),(le=-1<L?Q[L]:null)&&ah(le))}function ah(L){if(typeof L!="number"&&L&&!L.da){var Q=L.src;if(Q&&Q[go])_c(Q.i,L);else{var le=L.type,ye=L.proxy;Q.removeEventListener?Q.removeEventListener(le,ye,L.capture):Q.detachEvent?Q.detachEvent(dw(le),ye):Q.addListener&&Q.removeListener&&Q.removeListener(ye),(le=Mm(Q))?(_c(le,L),le.h==0&&(le.src=null,Q[Dl]=null)):qs(L)}}}function dw(L){return L in rg?rg[L]:rg[L]="on"+L}function qC(L,Q){if(L.da)L=!0;else{Q=new Mi(Q,this);var le=L.listener,ye=L.ha||L.src;L.fa&&ah(L),L=le.call(ye,Q)}return L}function Mm(L){return L=L[Dl],L instanceof wl?L:null}var yc="__closure_events_fn_"+(1e9*Math.random()>>>0);function Sc(L){return typeof L=="function"?L:(L[yc]||(L[yc]=function(Q){return L.handleEvent(Q)}),L[yc])}function Er(){Oi.call(this),this.i=new wl(this),this.M=this,this.F=null}B(Er,Oi),Er.prototype[go]=!0,Er.prototype.removeEventListener=function(L,Q,le,ye){WC(this,L,Q,le,ye)};function Vr(L,Q){var le,ye=L.F;if(ye)for(le=[];ye;ye=ye.F)le.push(ye);if(L=L.M,ye=Q.type||Q,typeof Q=="string")Q=new dn(Q,L);else if(Q instanceof dn)Q.target=Q.target||L;else{var ze=Q;Q=new dn(ye,L),Ce(Q,ze)}if(ze=!0,le)for(var tt=le.length-1;0<=tt;tt--){var wt=Q.g=le[tt];ze=sg(wt,ye,!0,Q)&&ze}if(wt=Q.g=L,ze=sg(wt,ye,!0,Q)&&ze,ze=sg(wt,ye,!1,Q)&&ze,le)for(tt=0;tt<le.length;tt++)wt=Q.g=le[tt],ze=sg(wt,ye,!1,Q)&&ze}Er.prototype.N=function(){if(Er.aa.N.call(this),this.i){var L=this.i,Q;for(Q in L.g){for(var le=L.g[Q],ye=0;ye<le.length;ye++)qs(le[ye]);delete L.g[Q],L.h--}}this.F=null},Er.prototype.K=function(L,Q,le,ye){return this.i.add(String(L),Q,!1,le,ye)},Er.prototype.L=function(L,Q,le,ye){return this.i.add(String(L),Q,!0,le,ye)};function sg(L,Q,le,ye){if(Q=L.i.g[String(Q)],!Q)return!0;Q=Q.concat();for(var ze=!0,tt=0;tt<Q.length;++tt){var wt=Q[tt];if(wt&&!wt.da&&wt.capture==le){var no=wt.listener,na=wt.ha||wt.src;wt.fa&&_c(L.i,wt),ze=no.call(na,ye)!==!1&&ze}}return ze&&!ye.defaultPrevented}function sh(L,Q,le){if(typeof L=="function")le&&(L=E(L,le));else if(L&&typeof L.handleEvent=="function")L=E(L.handleEvent,L);else throw Error("Invalid listener argument");return 2147483647<Number(Q)?-1:s.setTimeout(L,Q||0)}function YC(L){L.g=sh(()=>{L.g=null,L.i&&(L.i=!1,YC(L))},L.l);let Q=L.h;L.h=null,L.m.apply(null,Q)}class lh extends Oi{constructor(Q,le){super(),this.m=Q,this.l=le,this.h=null,this.i=!1,this.g=null}j(Q){this.h=arguments,this.g?this.i=!0:YC(this)}N(){super.N(),this.g&&(s.clearTimeout(this.g),this.g=null,this.i=!1,this.h=null)}}function bc(L){Oi.call(this),this.h=L,this.g={}}B(bc,Oi);var Ys=[];function Pm(L){ke(L.g,function(Q,le){this.g.hasOwnProperty(le)&&ah(Q)},L),L.g={}}bc.prototype.N=function(){bc.aa.N.call(this),Pm(this)},bc.prototype.handleEvent=function(){throw Error("EventHandler.handleEvent not implemented")};var lg=s.JSON.stringify,KC=s.JSON.parse,l9=class{stringify(L){return s.JSON.stringify(L,void 0)}parse(L){return s.JSON.parse(L,void 0)}};function Ad(){}Ad.prototype.h=null;function cg(L){return L.h||(L.h=L.i())}function pw(){}var Al={OPEN:"a",kb:"b",Ja:"c",wb:"d"};function ZC(){dn.call(this,"d")}B(ZC,dn);function XC(){dn.call(this,"c")}B(XC,dn);var uo={},km=null;function ch(){return km=km||new Er}uo.La="serverreachability";function QC(L){dn.call(this,uo.La,L)}B(QC,dn);function Rm(L){let Q=ch();Vr(Q,new QC(Q))}uo.STAT_EVENT="statevent";function JC(L,Q){dn.call(this,uo.STAT_EVENT,L),this.stat=Q}B(JC,dn);function Ur(L){let Q=ch();Vr(Q,new JC(Q,L))}uo.Ma="timingevent";function gw(L,Q){dn.call(this,uo.Ma,L),this.size=Q}B(gw,dn);function pa(L,Q){if(typeof L!="function")throw Error("Fn must not be null and must be a function");return s.setTimeout(function(){L()},Q)}function Ic(){this.g=!0}Ic.prototype.xa=function(){this.g=!1};function uw(L,Q,le,ye,ze,tt){L.info(function(){if(L.g)if(tt)for(var wt="",no=tt.split("&"),na=0;na<no.length;na++){var Si=no[na].split("=");if(1<Si.length){var ga=Si[0];Si=Si[1];var ua=ga.split("_");wt=2<=ua.length&&ua[1]=="type"?wt+(ga+"="+Si+"&"):wt+(ga+"=redacted&")}}else wt=null;else wt=tt;return"XMLHTTP REQ ("+ye+") [attempt "+ze+"]: "+Q+`
|
|
169
|
+
`},dt.CommentAnnotationPriorityMap={P0:{id:"P0",name:"P0",color:"var(--velt-error, #FF7162)",lightColor:"var(--velt-error-light, #F7E7E7) "},P1:{id:"P1",name:"P1",color:"var(--velt-warning, #ECB000)",lightColor:"var(--velt-warning-light, #FEFCEA)"},P2:{id:"P2",name:"P2",color:"var(--velt-text-7, #777E91)",lightColor:"var(--velt-background-1, #F3F3F5)"}},dt.WorkspaceRoles=[{id:mo.COMMENTER?.toLowerCase(),name:mo.COMMENTER,description:"Can comment on this project",permissions:[]},{id:mo.ADMIN?.toLowerCase(),name:mo.ADMIN,description:"Can comment on all projects and has access to the portal",permissions:[]}],dt.DocumentAccessTypeMap={[di.PUBLIC]:{id:di.PUBLIC,name:di.PUBLIC,description:"Anyone with link can view"},[di.RESTRICTED]:{id:di.RESTRICTED,name:di.RESTRICTED,description:"Only people with access can view"}},dt.DocumentAccessTypeMapSF={[di.PUBLIC]:{id:di.PUBLIC,name:di.PUBLIC,description:"Anyone with the link can comment after logging in."},[di.RESTRICTED]:{id:di.RESTRICTED,name:di.RESTRICTED,description:"Only people added to this project can comment."}},dt.CommentCategoryMap={bug:{id:"bug",name:"Bug",color:"#FF7162"},feedback:{id:"feedback",name:"Feedback",color:"#00C48C"},question:{id:"question",name:"Question",color:"#FFD166"}},dt.OVERLAY_POSITIONS=[{originX:"end",originY:"top",overlayX:"start",overlayY:"top"},{originX:"start",originY:"bottom",overlayX:"start",overlayY:"top"},{originX:"end",originY:"bottom",overlayX:"end",overlayY:"top"},{originX:"center",originY:"bottom",overlayX:"center",overlayY:"top"},{originX:"start",originY:"top",overlayX:"start",overlayY:"bottom"},{originX:"end",originY:"top",overlayX:"end",overlayY:"bottom"},{originX:"center",originY:"top",overlayX:"center",overlayY:"bottom"},{originX:"start",originY:"top",overlayX:"end",overlayY:"top"},{originX:"start",originY:"bottom",overlayX:"end",overlayY:"bottom"},{originX:"start",originY:"center",overlayX:"end",overlayY:"center"},{originX:"end",originY:"bottom",overlayX:"start",overlayY:"bottom"},{originX:"end",originY:"center",overlayX:"start",overlayY:"center"}],dt.OVERLAY_POSITIONS_FOR_POPOVER_MODE=[{originX:"end",originY:"top",overlayX:"start",overlayY:"top"},{originX:"end",originY:"center",overlayX:"start",overlayY:"center"},{originX:"end",originY:"bottom",overlayX:"start",overlayY:"bottom"},{originX:"start",originY:"top",overlayX:"end",overlayY:"top"},{originX:"start",originY:"center",overlayX:"end",overlayY:"center"},{originX:"start",originY:"bottom",overlayX:"end",overlayY:"bottom"}];var U=dt;var fn=(n,o=0)=>{try{let t=3735928559^o,e=1103547991^o;for(let i=0,r;i<n.length;i++)r=n.charCodeAt(i),t=Math.imul(t^r,2654435761),e=Math.imul(e^r,1597334677);return t=Math.imul(t^t>>>16,2246822507)^Math.imul(e^e>>>13,3266489909),e=Math.imul(e^e>>>16,2246822507)^Math.imul(t^t>>>13,3266489909),4294967296*(2097151&e)+(t>>>0)}catch(t){return pt.catch("Error in cyrb53: ",t),0}},JOe=()=>{try{return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^crypto.getRandomValues(new Uint8Array(1))[0]&15>>+n/4).toString(16))}catch(n){return pt.catch("Error in uuidv4: ",n),""}},Rt=n=>{try{return Ea.hashStr(n)}catch(o){return pt.catch("Error in hashStr: ",o),n}},ud=n=>fn(n).toString(),uV=n=>Rt(n),hd=n=>Rt(n).toString(),hl=n=>Rt(n).toString(),om=n=>{try{if(n)return typeof n=="string"?Ea.hashStr(n):Array.isArray(n)?Ea.hashStr(n.join("-")):"";{let o=JOe();return Ea.hashStr(o)}}catch(o){return pt.catch("Error in getMultiThreadAnnotationId: ",o),""}},Xi=(n,o,t)=>{try{if(n&&o){if(n.featureAllowList&&n.featureAllowList.length&&!n.featureAllowList.includes(t)||n.userIdAllowList&&n.userIdAllowList.length&&!n.userIdAllowList.includes(o.userId)||n.userGroupIdAllowList&&n.userGroupIdAllowList.length&&!n.userGroupIdAllowList.includes(o.groupId||"")||n.userPlanAllowList&&n.userPlanAllowList.length&&!n.userPlanAllowList.includes(o.plan||""))return!1;if(n.urlAllowList){let e=window.location.href;if(n.urlAllowList.length&&!n.urlAllowList.filter(i=>e.includes(i)).length)return!1}return!0}return!1}catch(e){return pt.catch("Error in isFeatureAllowed: ",e),!1}},xn=()=>{try{let n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",o="";for(let t=0;t<20;t++)o+=n.charAt(Math.floor(Math.random()*n.length));return o}catch(n){return pt.catch("Error in utils generateId: ",n),""}},Sp=n=>{try{let o=0;if(n){let t=new Date().getTime();o=Math.abs(t-n)}return o}catch(o){return pt.catch("Error in utils getFirebaseTimeDiffInMins: ",o),0}};var Mie=()=>{try{return Zn.debugMode||!!sessionStorage.getItem("debugMode")||!!sessionStorage.getItem("forceDebugMode")}catch(n){return pt.catch("Error in showLogs: ",n),!1}},Xo=n=>{try{return typeof n!="object"?Object.assign({},...Object.keys(n).sort().map(o=>({[o]:n[o]&&typeof n[o]=="object"?Xo(n[o]):n[o]}))):n}catch(o){return pt.catch("Error in sortObjectByKeys: ",o),n}},hV=(n,o,t)=>ee(void 0,null,function*(){try{let e=yield t6e(o),i=new Uint8Array(new TextEncoder().encode(t)).slice(0,16),r=new TextEncoder().encode(n),a=yield window.crypto.subtle.encrypt({name:"AES-CBC",iv:i},e,r);return btoa(String.fromCharCode(...new Uint8Array(a)))}catch(e){return pt.catch("Error in encrypt: ",e),n}}),fV=(n,o,t)=>ee(void 0,null,function*(){try{let e=yield e6e(o),i=new Uint8Array(new TextEncoder().encode(t)).slice(0,16),r=new Uint8Array(atob(n).split("").map(s=>s.charCodeAt(0))),a=yield window.crypto.subtle.decrypt({name:"AES-CBC",iv:i},e,r);return new TextDecoder().decode(a)}catch(e){return pt.catch("Error in decrypt: ",e),n}}),e6e=n=>ee(void 0,null,function*(){try{let o=new TextEncoder().encode(n),t=new Uint8Array(32);return t.fill(0),t.set(o.slice(0,32)),yield window.crypto.subtle.importKey("raw",t,"AES-CBC",!1,["decrypt"])}catch(o){throw pt.catch("Error in importDecryptKey:",o),o}}),bp=(n,o)=>ee(void 0,null,function*(){try{let t="Velt"+o;return yield hV(JSON.stringify(n),t,Rt(t))}catch(t){return pt.catch("Error in encryptData: ",t),n}}),Pie=(n,o)=>ee(void 0,null,function*(){try{let t="Velt"+o,e=yield fV(n,t,Rt(t));return JSON.parse(e)}catch(t){return pt.catch("Error in decryptData: ",t),null}}),$O=n=>{try{switch(n?.region){case"asiaSouthEast1":return"asiaSouthEast1";case"asiaNorthEast1":return"asiaNorthEast1";case"europeWest1":return"europeWest1";default:return"usCentral1"}}catch(o){return pt.catch("Error in getRegion: ",o),"usCentral1"}},t6e=n=>ee(void 0,null,function*(){try{let o=new TextEncoder().encode(n),t=new Uint8Array(32);return t.fill(0),t.set(o.slice(0,32)),yield window.crypto.subtle.importKey("raw",t,"AES-CBC",!1,["encrypt"])}catch(o){throw pt.catch("Error in importKey:",o),o}}),kie=n=>{try{if(n&&typeof n=="object"){let o=Xo(n);return fn(JSON.stringify(o))}else return null}catch(o){return pt.catch("Error in utils generateLocationId: ",o),null}},ji=(n,o=[])=>(n?.tagName?.toLowerCase().indexOf("velt-")>=0&&![U.TAGS.VELT_VIDEO_PLAYER.toLowerCase()].includes(n?.tagName?.toLowerCase())||n?.tagName?.toLowerCase().indexOf("snippyly-")>=0||n?.className?.split&&(n?.className?.split(" ")?.indexOf("snippyly-overlay-panel")>=0||n?.className?.split(" ")?.indexOf("cdk-overlay-container")>=0))&&!o?.includes(n?.tagName?.toLowerCase())?!0:n?.parentNode&&ji(n?.parentNode,o),xo=n=>{try{return!!document?.body?.contains(n)}catch(o){return pt.catch("Error in utils isElementInsideBody: ",o),!1}};var Co=(n,o)=>{try{return Object.prototype.toString.call(n)===Object.prototype.toString.call(o)?Object.prototype.toString.call(n)==="[object Object]"||Object.prototype.toString.call(n)==="[object Array]"?Object.keys(n).length!==Object.keys(o).length?!1:Object.keys(n).every(t=>Co(n[t],o[t])):n===o:!1}catch(t){return pt.catch("Error in utils deepCompare: ",t),!1}},nv=(n,o,t=1)=>{try{if(o){let e=n6e(o.textContent,n,t);if(e>=0){let i=(o?.ownerDocument).createNodeIterator(o,NodeFilter.SHOW_TEXT),r,a=[];for(;r=i.nextNode();)a.push(r);let s=[],c=e,p=n.length,h=c+p,_=0;for(let E=0;E<a.length;E++){let D=a[E],B=_;if(_+=D.textContent?.length,_>=c&&!s.length?s.push({textNode:D,startOffset:c-B}):_>=c&&_<h&&s.push({textNode:D}),_>=h){if(s.length===1&&s[0].textNode===D){s.push({textNode:D,endOffset:c-B+n.length});break}let G=p;s.forEach(X=>{G-=X.textNode.textContent?.length-(X.startOffset||0)}),s.push({textNode:D,endOffset:G});break}}return s}}return[]}catch(e){return pt.catch("Error in utils calculateNodes: ",e),[]}},n6e=(n,o,t=1)=>{try{if(n?.includes(o)){let e=n.split(o,t);return e.length===t?e.join(o).length:-1}else return-1}catch(e){return pt.catch("Error in utils getTextPosition: ",e),-1}},Au=(n,o,t,e,i)=>{try{let r=new Range;r.setStart(n,o),r.setEnd(t,e);let a=r.toString(),s=0;if(n.nodeType===Node.TEXT_NODE){let c=n,p="";if(c)for(;c=c.previousSibling;)p=(c.textContent||"")+p;if(p){let h=new RegExp(im(i),"g");s=(p.match(h)||[]).length}}if(a){let c=new RegExp(im(i),"g");return(a.match(c)||[]).length+s}else return s}catch(r){return pt.catch("Error in utils getSelectedTextOccurrenceInRange: ",r),0}},im=n=>{try{return n&&typeof n=="string"?n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"):n}catch(o){return pt.catch("Error in utils escapeRegExp: ",o),n}},iv=n=>{try{return n==null?null:n.scrollHeight>n.clientHeight?n:iv(n?.parentNode)}catch(o){return pt.catch("Error in utils getScrollableParent: ",o),null}},yp=n=>{try{return n==null?[]:n.scrollHeight>n.clientHeight?[n,...yp(n?.parentNode)]:yp(n?.parentNode)}catch(o){return pt.catch("Error in utils getScrollableParents: ",o),[]}},vV=(n,o)=>{try{if(n&&o){let t=n.getBoundingClientRect(),e=o.getBoundingClientRect(),i=t.top-e.top+(o.tagName?.toLowerCase()==="html"?0:o.scrollTop),r=t.left-e.left;return{top:i,left:r}}else return null}catch(t){return pt.catch("Error in utils getRelativeTopLeftPosition: ",t),null}},ov=(n,o)=>`${fn(n+"_"+o)}`,_i=()=>{try{let n=new Zi;return n.url=window.location.href,n.path=window.location.pathname,n.queryParams=window.location.search,n.baseUrl=window.location.origin,n.title=document.title,n}catch(n){pt.catch("Error in utils getPageInfo: ",n);return}},fd=n=>{try{return n?n?.hasAttribute&&n?.hasAttribute(U.ATTRIBUTES.VELT_COMMENT_DISABLED)?!0:fd(n?.parentElement):!1}catch(o){return pt.catch("Error in utils isCommentDisabledOnElement: ",o),!1}},HO=n=>{try{return n?n?.hasAttribute&&n?.hasAttribute(U.ATTRIBUTES.VELT_TAG_DISABLED)?!0:HO(n?.parentElement):!1}catch(o){return pt.catch("Error in utils isTagDisabledOnElement: ",o),!1}},zO=n=>{try{return n?n?.hasAttribute&&n?.hasAttribute(U.ATTRIBUTES.VELT_ARROW_DISABLED)?!0:zO(n?.parentElement):!1}catch(o){return pt.catch("Error in utils isArrowDisabledOnElement: ",o),!1}},GO=n=>{try{return n?n?.hasAttribute&&n?.hasAttribute(U.ATTRIBUTES.VELT_AREA_DISABLED)?!0:GO(n?.parentElement):!1}catch(o){return pt.catch("Error in utils isAreaDisabledOnElement: ",o),!1}},WO=n=>{try{return n?n?.hasAttribute&&n?.hasAttribute(U.ATTRIBUTES.VELT_RECORDER_DISABLED)?!0:WO(n?.parentElement):!1}catch(o){return pt.catch("Error in utils isRecorderDisabledOnElement: ",o),!1}};var Ta=()=>{try{return window?.Snippyly?.version}catch(n){return pt.catch("Error in utils getSdkVersion: ",n),null}},qO=n=>{try{let o=new URL(n);return Object.values(U.URL_PARAMS).forEach(t=>{o.searchParams.delete(t)}),o.href}catch(o){return pt.catch("Error in utils excludeSnippylyParamsFromUrl: ",o),n}},fs=n=>{try{navigator.clipboard.writeText(n)}catch(o){pt.catch("Error in copyToClipboard: ",o)}},rS=n=>{try{let o=Rie(n);return o&&typeof o=="string"&&o.includes("/svg")&&(o=o.split("/svg")[0]+"/*[name()='svg']"),o}catch(o){pt.catch("Error in utils getXPath:",o)}},Rie=n=>{try{if(n){if(typeof n=="string")return document.evaluate(n,document,null,0,null);if(!n||n.nodeType!=1)return"";if(n.id&&n?.tagName?.toLowerCase()!=="svg"&&document.querySelectorAll(`[id='${n.id}']`)?.length===1)return"//*[@id='"+n.id+"']";let o=[].filter.call(n.parentNode?.children?n.parentNode?.children:[],function(t){return t.tagName==n.tagName});return Rie(n.parentNode)+"/"+n.tagName.toLowerCase()+(o.length>1?"["+([].indexOf.call(o,n)+1)+"]":"")}}catch(o){pt.catch("Error in utils calculateXPath:",o)}},Nie=n=>{try{let o=[];return n.forEach(t=>{let e={};e.commonAncestorContainer=i6e(t.commonAncestorContainer),e.text=t.toString(),e.occurrence=Au(t.commonAncestorContainer,0,t.startContainer,t.startOffset,t.toString())+1,o.push(e)}),o}catch{return[]}},i6e=n=>{try{if(n.nodeType===Node.TEXT_NODE){let o=1,t=n.previousSibling;for(;t;)t.nodeType===Node.TEXT_NODE&&o++,t=t.previousSibling;return rS(n.parentElement)}else return rS(n)}catch(o){return pt.catch("Error in utils getXPathForText: ",o),rS(n)}},CV=(n,o)=>{try{return n?n?.hasAttribute&&(o&&n.hasAttribute("contenteditable")||n?.getAttribute(U.ATTRIBUTES.VELT_LIVE_SELECTION_ENABLED)==="true")?n:CV(n?.parentElement,o):null}catch(t){return pt.catch("Error in utils getSelectionEnabledElement: ",t),null}},YO=n=>{try{let o,t=[],e=document.createTreeWalker(n,NodeFilter.SHOW_TEXT,null);for(;o=e.nextNode();)t.push(o);return t}catch(o){return pt.catch("Error in utils getTextNodesInsideElement: ",o),[]}},Fie=n=>{try{return n<576||n>=576&&n<767?"Mobile":n>=768&&n<992?"Tablet":n>=992&&n<1520?"Desktop":"Monitor"}catch(o){return pt.catch("Error in utils getDeviceTypeFromDeviceWidth: ",o),""}},Ip=n=>new Promise(o=>setTimeout(o,n)),Lie=(n,o=0)=>new Promise((t,e)=>{let i=document.createElement("video");i.setAttribute("src",URL.createObjectURL(n)),i.load(),i.addEventListener("error",r=>{e("error when loading video file: "+r)}),i.addEventListener("loadedmetadata",()=>{if(i.duration<o){e("video is too short.");return}setTimeout(()=>{i.currentTime=o},200),i.addEventListener("seeked",()=>{let r=document.createElement("canvas");r.width=i.videoWidth,r.height=i.videoHeight;let a=r.getContext("2d");a.drawImage(i,0,0,r.width,r.height),a.canvas.toBlob(s=>{i.remove(),t(s)},"image/jpeg",.75)})})}),Bie=n=>{try{return new Promise((o,t)=>{let e=new FileReader;e.onloadend=()=>o(e.result),e.readAsDataURL(n)})}catch(o){return pt.catch("Error in utils blobToBase64: ",o),Promise.resolve("")}},_V=(n,o="image/jpeg")=>{try{let t=atob(n.split(",")[1]),e=new ArrayBuffer(t.length),i=new Uint8Array(e);for(let r=0;r<t.length;r++)i[r]=t.charCodeAt(r);return new Blob([e],{type:o})}catch(t){return pt.catch("Error in utils base64ToBlob: ",t),null}},Vie=(n,o,t=20)=>new Promise((e,i)=>{let r=new Image;r.crossOrigin="Anonymous",r.onload=()=>{let a=r.width,s=r.height,c=600,p=s/a*c,h="http://www.w3.org/2000/svg",_=document.createElementNS(h,"svg");_.setAttribute("xmlns",h),_.setAttribute("width",c.toString()),_.setAttribute("height",p.toString()),_.setAttribute("viewBox",`0 0 ${c} ${p}`);let E=document.createElementNS(h,"circle"),D=document.createElementNS(h,"polygon"),B=16,G=B+16,X=c/2,he=p/2;if(E.setAttribute("cx",X.toString()),E.setAttribute("cy",he.toString()),E.setAttribute("r",G.toString()),E.setAttribute("fill","lightgrey"),D.setAttribute("points",`${X-B/2},${he-B} ${X-B/2},${he+B} ${X+B},${he}`),D.setAttribute("fill","#ffffff"),_.appendChild(E),_.appendChild(D),o){let we=o.length*16-10,Ee=16*1.5,Pe=(c-we)/2,Ce=p-Ee-10,ue=document.createElementNS(h,"rect");ue.setAttribute("x",Pe.toString()),ue.setAttribute("y",Ce.toString()),ue.setAttribute("width",we.toString()),ue.setAttribute("height",Ee.toString()),ue.setAttribute("fill","#353945b3"),ue.setAttribute("rx","12"),_.appendChild(ue);let Be=document.createElementNS(h,"text");Be.textContent=o,Be.setAttribute("x",(c/2).toString()),Be.setAttribute("y",(Ce+16).toString()),Be.setAttribute("font-size","16"),Be.setAttribute("text-anchor","middle"),Be.setAttribute("fill","white"),_.appendChild(Be)}let Ie=new XMLSerializer().serializeToString(_),Me=new Image,Le=new Blob([Ie],{type:"image/svg+xml;charset=utf-8"}),We=URL.createObjectURL(Le);Me.onload=()=>{let ke=document.createElement("canvas");ke.width=c,ke.height=p;let we=ke.getContext("2d");we.beginPath(),we.moveTo(t,0),we.lineTo(c-t,0),we.quadraticCurveTo(c,0,c,t),we.lineTo(c,p-t),we.quadraticCurveTo(c,p,c-t,p),we.lineTo(t,p),we.quadraticCurveTo(0,p,0,p-t),we.lineTo(0,t),we.quadraticCurveTo(0,0,t,0),we.closePath(),we.clip(),we.drawImage(r,0,0,c,p),we.drawImage(Me,0,0,c,p);let Ee=ke.toDataURL("image/png");e(Ee)},Me.onerror=i,Me.src=We},r.onerror=i,r.src=n});var KO=n=>{try{return n?.replace(/[\n\t\u200D]/g,"")?.split(/\s+/)?.filter(e=>e?.trim()?.length)||[]}catch(o){return pt.catch("Error in utils getWords: ",o),[]}},cr=(n,o=[])=>{try{let t=o.map(e=>`[${e}="${n}"]`).join(",");return document.querySelector(t)}catch(t){return pt.catch("Error in utils getElementByAttributes: ",t),null}},Uie=(n,o=[])=>{try{let t=o.map(e=>`[${e}="${n}"]`).join(",");return document.querySelectorAll(t)}catch(t){return pt.catch("Error in utils getElementsByAttributes: ",t),[]}},rc=n=>{try{let o=Math.floor(n/3600),t=Math.floor((n-o*3600)/60),e=Math.floor(n-o*3600-t*60);return o&&o<10&&(o="0"+o),t<10&&(t="0"+t),e<10&&(e="0"+e),(o?o+":":"")+t+":"+e}catch{return""}},jie=(n,o=10)=>{try{if(!n||!n.currentTime)throw new Error("Invalid video element reference provided");let t=n.currentTime,e=Math.floor(t/o)*o,i=e+o;return{startSlot:rc(e),endSlot:rc(i),timeSlot:rc(e)+" - "+rc(i)}}catch{return null}},yV=(n,o=["@"])=>{try{let t="",e,i=n.getRootNode();if(i instanceof ShadowRoot?e=i?.getSelection():e=window.getSelection(),e?.rangeCount){let r=e.getRangeAt(0),a=r.startOffset,s=r.endOffset,c=r?.commonAncestorContainer?.textContent;c?t=o6e(c,s,o):t=""}return t}catch(t){return pt.catch("Error in utils getWordAtCursor: ",t),""}};var o6e=(n,o,t=["@"])=>{try{let e=-1;for(let i of t){let r=n.lastIndexOf(i,o),a=n.lastIndexOf(i,r-1);r>e&&(i==="@"?a===-1||a!==-1&&n.slice(a,r+1).indexOf(" ")!==-1?e=r:e=a:e=r)}return e!==-1?n.substring(e,o):""}catch(e){return pt.catch("Error in utils getStringFromLastAtSymbol: ",e),""}},$ie=(n,o,t=["@"])=>{try{let e=r6e(n),i=e&&e.getSelection!==void 0?e.getSelection():window.getSelection();if(i?.rangeCount){let r=i.getRangeAt(0),a=r.startOffset,s=r?.commonAncestorContainer?.textContent;if(s){let c=-1;for(let p of t){let h=s.lastIndexOf(p,a),_=s.lastIndexOf(p,h-1);h>c&&(p==="@"?_===-1||_!==-1&&s.slice(_,h+1).indexOf(" ")!==-1?c=h:c=_:c=h)}if(c!==-1){let p=s.substring(0,c),h=s.substring(r.endOffset),_=document.createElement("span");_.textContent=o,_.style.color="var(--velt-accent)";let E=r.commonAncestorContainer;if(E.nodeType===Node.TEXT_NODE){let D=E.parentNode;if(D){let B=document.createTextNode(p),G=document.createTextNode(h);D.replaceChild(G,E),D.insertBefore(_,G),D.insertBefore(B,_)}}}}}}catch(e){pt.catch("Error in utils replaceWordAtCursor: ",e)}},ZO=()=>{try{let o=window.getSelection()?.getRangeAt(0),t=o?.commonAncestorContainer,e=o?.startContainer,i=o?.endContainer,r=[];r.push(t),r.push(e),r.push(i);let a=!1;for(let s of r)if(s&&ji(s,[U.TAGS.SNIPPYLY_TEXT_HIGHLIGHT,U.TAGS.SNIPPYLY_COMMENT_TEXT_PORTAL,U.TAGS.SNIPPYLY_HIGHLIGHT_USER_TEXT,U.TAGS.SNIPPYLY_COMMENT_TEXT])){a=!0;break}return a}catch(n){return pt.catch("Error in utils isTextSelectionIncludesSnippylyElement: ",n),!1}},Hie=(n,o,t)=>{try{let e=document.querySelector(`[id=${n}]`);if(e)e.name=o,e.content=t;else{let i=document.createElement("meta");i.id=n,i.name=o,i.content=t,document.getElementsByTagName("head")[0].appendChild(i)}}catch{}},zie=n=>{try{if(n){let o=document.querySelector(`[id=${n}]`);o&&o.remove()}}catch{}},Gie=()=>{try{let o=new Date().getTimezoneOffset(),t=Math.floor(Math.abs(o)/60),e=Math.abs(o)%60;return`UTC${o>0?"-":"+"}${t?.toString()?.padStart(2,"0")}:${e?.toString()?.padStart(2,"0")}`}catch(n){return pt.catch("Error in utils getTimezone: ",n),""}},Wie=()=>{try{let n=[];return document.querySelectorAll("*").forEach(t=>{(t.scrollHeight>t.clientHeight||t.scrollWidth>t.clientWidth||["auto","scroll"].includes(getComputedStyle(t).overflow))&&n.push(t)}),n}catch(n){return pt.catch("Error in utils getScrollableElements: ",n),[]}},qie=(n,o)=>Math.sqrt((n.x-o.x)**2+(n.y-o.y)**2),SV=(n,o={x:window.innerWidth/2,y:window.innerHeight/2})=>{try{let t=n;for(;t.children.length>0;){let e=null,i=Number.MAX_SAFE_INTEGER;for(let r=0;r<t.children.length;r++){let a=t.children[r],s=a.getBoundingClientRect(),c={x:s.left+s.width/2,y:s.top+s.height/2},p=qie(c,o);(s.top>=0||s.bottom<=window.innerHeight)&&s.width>0&&s.height>0&&p<=i&&(e=a,i=p)}if(e===null)break;t=e}return t}catch(t){return pt.catch("Error in utils getInnermostElement: ",t),null}},Yie=n=>{try{let{offsetWidth:o,offsetHeight:t,scrollTop:e}=n,i=n,r={x:o/2,y:e+t/2};for(;i.children.length>0;){let a=null,s=Number.MAX_SAFE_INTEGER;for(let c=0;c<i.children.length;c++){let p=i.children[c],h={x:p.offsetLeft+p.offsetWidth/2,y:p.offsetTop+p.offsetHeight/2},_=qie(h,r);p.offsetTop>=0&&p.offsetWidth>0&&p.offsetHeight>0&&_<=s&&(a=p,s=_)}if(a===null)break;i=a}return i}catch(o){return pt.catch("Error in utils getNestedInnermostElement: ",o),null}},Kie=()=>{try{let n=window.innerWidth/2,o=window.innerHeight/2,t=document.elementFromPoint(n,o);for(;t&&t.tagName==="BODY";)o+=2,t=document.elementFromPoint(n,o);return t}catch(n){return pt.catch("Error in utils getCenteredBackgroundElement: ",n),null}},bV=(n,o,t=!1)=>{try{let e=n.getBoundingClientRect(),i=o.getBoundingClientRect(),r=o.offsetTop;t&&(r=r-e.height/2+i.height/2),n.scrollTo({top:r,behavior:"smooth"})}catch(e){pt.catch("Error in utils nestedScrollIntoView: ",e)}},XO=(n,o=!0)=>{try{let t=document.body.getBoundingClientRect(),e=n.getBoundingClientRect(),i=e.top-t.top,r=window.innerHeight,a=i;o&&(a=a-r/2+e.height/2),window.scrollTo({top:a,behavior:"smooth"})}catch(t){pt.catch("Error in utils scrollIntoView: ",t)}},Zie=(n=!1)=>{try{let o=!0;return n&&(o=/\sChrome\/[\d.]+ Mobile\s/.test(navigator.userAgent)),"ontouchstart"in window||navigator.maxTouchPoints>0||o}catch(o){return pt.catch("Error in utils isTouchDevice: ",o),!1}},Xie=(n,o,t)=>{try{return(1-t)*n+t*o}catch(e){pt.catch("Error in utils lerp: ",e)}return 0},Qie=(n,o)=>{try{if(n===void 0)return n;if(n=n.replace("#",""),n.length===6){let t=parseInt(n,16),e=(t>>16)+o;e>255&&(e=255),e<0&&(e=0);let i=(t&255)+o;i>255&&(i=255),i<0&&(i=0);let r=(t>>8&255)+o;return r>255&&(r=255),r<0&&(r=0),`#${(i|r<<8|e<<16).toString(16)}`}else return n}catch(t){pt.catch("Error in utils multiplyColor: ",t)}return n},Jie=n=>{try{return n in U.TEXT_COLOR_MAP?U.TEXT_COLOR_MAP[n]:"#141416"}catch(o){return pt.catch("Error in generateUserColor:",o),"#141416"}},ac=()=>{try{let n=localStorage.getItem(U.LOCAL_STORAGE.SNIPPYLY_DEFAULT_MEDIA_SOURCE_OPTIONS);if(n)return JSON.parse(n)}catch(n){return pt.catch("Error in getDefaultMediaStreamOptions:",n),{}}},QO=(n,o)=>{try{let t=o*(Math.PI/180),e=Math.cos(t);return e?n/e:n}catch(t){return pt.catch("Error in calculateHypotenuse:",t),0}},IV=(n,o,t=!0)=>{try{let e=[],i=t?n:n.parentNode;for(;i;)e.push(i),i=i.parentNode;let r=t?o:o.parentNode;for(;r;){if(e.indexOf(r)!==-1)return r;r=r.parentNode}return null}catch(e){return pt.catch("Error in utils findCommonParent: ",e),null}},EV=(n,o,t,e)=>{let i=t.getBoundingClientRect(),r=e.getBoundingClientRect(),a=i.left+n,s=i.top+o,c=a-r.left,p=s-r.top;return{x:c,y:p}},Ep=n=>{try{let o={height:0,width:0};if(typeof n?.getBBox=="function"){let t=n?.getBBox(),e=n?.getBoundingClientRect();o.height=parseFloat(e?.height||t.height||0),o.width=parseFloat(e?.width||t.width||0)}else{let t=window.getComputedStyle(n);if(o.height=n?.clientHeight||parseFloat(t.getPropertyValue("height"))||0,o.width=n?.clientWidth||parseFloat(t.getPropertyValue("width"))||0,n?.getBoundingClientRect&&typeof n?.getBoundingClientRect=="function"){let e=n?.getBoundingClientRect();o?.height||(o.height=e?.height||n?.clientHeight||n?.offsetHeight||0),o?.width||(o.width=e?.width||n?.clientWidth||n?.offsetWidth||0)}}return o}catch(o){return pt.catch("Error in utils getElementDimensions: ",o),{height:0,width:0}}},rm=n=>{try{let o=n;for(;o;){if(window?.getComputedStyle(o)?.getPropertyValue("background-clip")=="text")return!0;o=o?.parentElement}return!1}catch(o){return pt.catch("Error in utils hasParentWithBackgroundClip: ",o),!1}},r6e=n=>{try{let o=n;for(;o;){if(o.toString()==="[object ShadowRoot]")return o;o=o.parentNode}}catch(o){pt.catch("Error in utils findShadowRoot: ",o)}return null},$n=n=>{try{let o=["commentCategories","color","resolved","inProgress","positionX","positionY","screenWidth","screenHeight","screenScrollHeight","screenScrollTop","taggedElementPath","taggedElementRect","targetElement","position","documentParamsId","documentParams","ghostComment","areaAnnotationId","iam","commentSource"],t=JSON.parse(JSON.stringify(n)),e={};return Object.keys(t).forEach(i=>{o.includes(i)||(e[i]=t[i])}),JSON.parse(JSON.stringify(e))}catch(o){return pt.catch("Error in utils getCommentAnnotationForClient: ",o),null}};var rv=n=>n===null||typeof n>"u",av=(n,o)=>{try{return!!n?.closest(`[${o}]`)}catch(t){return pt.catch("Error in utils hasParentWithAttribute: ",t),!1}},xV=(n,o=!0)=>{try{let t=[];if(!n||!(n instanceof HTMLElement))return[];o&&t.push(n);for(let e=0;e<n.children.length;e++){let i=n.children[e];t=t.concat(xV(i))}return t}catch(t){return pt.catch("Error in utils getAllNestedChildren: ",t),[]}},eoe=()=>{try{return document.visibilityState==="hidden"?!1:document.hasFocus()}catch(n){return pt.catch("Error in utils isTabActive: ",n),!1}},TV=n=>{try{let o="",t=n?.getAttribute("src");if(t)o=`${fn(t)}`;else{let e=n?.querySelectorAll("source");if(e&&e.length>0){let r=e[0]?.getAttribute("src");r&&(o=`${fn(r)}`)}}return o}catch{return""}},st=n=>{try{return!(n&&(n?.children?.length>0||n?.textContent?.trim()?.length>0))}catch(o){return pt.catch("Error in utils isTemplateEmpty: ",o),!0}},la=(n,o)=>{try{if(!n||!o)return;let t=[],e="",i=0;for(let c=0;c<o.length;c++){let p=o[c];p==="["?(i++,i===1&&e&&(t.push(e),e=""),e+=p):p==="]"?(i--,e+=p,i===0&&(t.push(e),e="")):p==="."&&i===0?e&&(t.push(e),e=""):e+=p}e&&t.push(e);let r,a=I({},n),s=t.reduce((c,p)=>{if(c==null)return;Pi(c)&&(r=c,c=c());let h=p.match(/^\[([^\[\]]+|(\[[^\[\]]*\]))\]$/);if(h){let E=h[1];if(/^\d+$/.test(E)){let D=parseInt(E,10);return Array.isArray(c)?c[D]:void 0}if(E.startsWith("'")&&E.endsWith("'")||E.startsWith('"')&&E.endsWith('"')){let D=E.slice(1,-1);return c[D]}if(E.includes(".")||E.includes("[")){let D=la(a,E);Pi(D)&&(D=D());let B=D?.toString()||"";return c[B]}if(a[E]!==void 0){let D=a[E];return Pi(D)&&(D=D()),c[D]}return c[E]}let _=p;return(p.startsWith("'")&&p.endsWith("'")||p.startsWith('"')&&p.endsWith('"'))&&(_=p.slice(1,-1)),_==="length"&&Array.isArray(c)?c.length:c[_]},n);return r?zi(()=>{try{let c=I({},n);return t.reduce((p,h)=>{if(p==null)return;Pi(p)&&(p=p());let _=h.match(/^\[([^\[\]]+|(\[[^\[\]]*\]))\]$/);if(_){let D=_[1];if(/^\d+$/.test(D)){let B=parseInt(D,10);return Array.isArray(p)?p[B]:void 0}if(D.startsWith("'")&&D.endsWith("'")||D.startsWith('"')&&D.endsWith('"')){let B=D.slice(1,-1);return p[B]}if(D.includes(".")||D.includes("[")){let B=la(c,D);Pi(B)&&(B=B());let G=B?.toString()||"";return p[G]}if(c[D]!==void 0){let B=c[D];return Pi(B)&&(B=B()),p[B]}return p[D]}let E=h;return(h.startsWith("'")&&h.endsWith("'")||h.startsWith('"')&&h.endsWith('"'))&&(E=h.slice(1,-1)),p[E]},n)}catch{return""}}):s}catch{return""}},Ou=(n,o)=>{try{return!!(n?.locationId&&(n.locationId===o?.locationId||o?.location?.id===String(n.locationId))||n?.location?.id&&(n.location.id===o?.location?.id||n.location.id===String(o?.locationId)))}catch(t){return pt.catch("Error in utils isLocationSame: ",t),!1}},toe=()=>{try{let n=document.activeElement,o=new Set,t=10,e=0;for(;n&&n.shadowRoot&&!(o.has(n)||(o.add(n),n=n.shadowRoot.activeElement,e++,e>t)););return n}catch(n){return pt.catch("Error in utils getActiveElement: ",n),null}},_o=(n,o)=>{try{return typeof n=="object"&&typeof o=="object"?JSON.stringify(n)===JSON.stringify(o):n===o}catch{return!1}},sv=n=>{try{let o=JSON.parse(JSON.stringify(n));return n?.clientDocumentId&&(o.documentId=n.clientDocumentId),n?.clientOrganizationId&&(o.organizationId=n.clientOrganizationId),delete o?.clientDocumentId,delete o?.clientOrganizationId,delete o?.veltFolderId,delete o?.parentVeltFolderId,delete o?.pageInfo,o}catch{return n}},ca=n=>{try{if(!n.some(a=>a?.value?.data))return{};let o=null,t=n.reduce((a,s)=>Math.max(a,s.timestamp),0),e=n.find(a=>a.timestamp===t);if(!e)return{};e?.value?.operation?.type==="removed"&&(o=e?.value?.operation);let r=n.map(a=>a.value).reduce((a,s)=>({data:I(I({},a?.data??{}),s?.data??{})}),{});return r.operation=o,r}catch{return{}}},sc=(n,o,t)=>ee(void 0,null,function*(){try{let e=0;for(;e<=(t.retryCount||0);)try{let i=yield n();if(!i)return{success:!1,statusCode:400,message:`${o} failed: No response received`};if(i.statusCode===void 0)return{success:!1,statusCode:400,message:`${o} failed: Response missing statusCode`};if(i.statusCode!==200){if(e++,e>(t.retryCount||0))return{success:!1,statusCode:i.statusCode,message:`${o} failed after ${e} attempts with status code ${i.statusCode}`};t.retryDelay&&(yield new Promise(r=>setTimeout(r,t.retryDelay)));continue}return i}catch(i){if(e++,e>(t.retryCount||0))return{success:!1,statusCode:500,message:`${o} failed with error: ${i instanceof Error?i.message:"Unknown error"}`};t.retryDelay&&(yield new Promise(r=>setTimeout(r,t.retryDelay)))}return{success:!0,statusCode:200}}catch(e){return{success:!1,statusCode:500,message:`${o} failed with unexpected error: ${e instanceof Error?e.message:"Unknown error"}`}}}),aS=n=>{try{if(n&&typeof n=="object"){let o=JSON.parse(JSON.stringify(n));return o?.clientOrganizationId&&(o.organizationId=o.clientOrganizationId,delete o.clientOrganizationId),o?.clientGroupId&&(o.groupId=o.clientGroupId,delete o.clientGroupId),o?.userSnippylyId&&delete o.userSnippylyId,o}else return null}catch(o){return pt.catch("Error in utils getUserForClient: ",o),null}};var Qe=(()=>{let o=class o{constructor(e){this.functions=e,this.sf=!1,this.defaultProperties={},this.draftEvents=[],this.eventRateLimitCache={},this.EVENT_LIMIT=50,this.TIME_WINDOW_MS=60*1e3;try{this.updateDefaultProperties({sdkVersion:Ta()}),window?.location?.href&&(this.defaultProperties.pageUrl=window.location.href)}catch(i){pt.catch("Error in AnalyticsService constructor: ",i)}}updateDefaultProperties(e={}){this.defaultProperties=I(I({},this.defaultProperties),e)}setInstalledFeature(e){try{this.defaultProperties?.installedFeatures||(this.defaultProperties.installedFeatures=[]),this.defaultProperties.installedFeatures.includes(e)||this.defaultProperties.installedFeatures.push(e)}catch(i){pt.catch("Error in AnalyticsService setInstalledFeature: ",i)}}setFeatureConfig({feature:e,config:i}){try{this.defaultProperties.featureConfigs||(this.defaultProperties.featureConfigs={}),this.defaultProperties.featureConfigs[e]||(this.defaultProperties.featureConfigs[e]={}),this.defaultProperties.featureConfigs[e]=I(I({},this.defaultProperties.featureConfigs[e]),i)}catch(r){pt.catch("Error in AnalyticsService setFeatureConfig: ",r)}}setSF(e){try{this.sf=e}catch(i){pt.catch("Error in AnalyticsService setSF: ",i)}}setAuthService(e){try{this.authService=e}catch(i){pt.catch("Error in AnalyticsService setAuthService: ",i)}}setCommentService(e){try{this.commentService=e}catch(i){pt.catch("Error in AnalyticsService setCommentService: ",i)}}setAreaService(e){try{this.areaService=e}catch(i){pt.catch("Error in AnalyticsService setAreaService: ",i)}}setRecorderAnnotationService(e){try{this.recorderAnnotationService=e}catch(i){pt.catch("Error in AnalyticsService setRecorderAnnotationService: ",i)}}setReactionService(e){try{this.reactionService=e}catch(i){pt.catch("Error in AnalyticsService setReactionService: ",i)}}setUserService(e){try{this.userService=e}catch(i){pt.catch("Error in AnalyticsService setUserService: ",i)}}identifyUser(e,i,r={}){try{this.userId=e;let a=typeof i=="object"?JSON.parse(JSON.stringify(i)):i;this.userService?.userDataProviderAvailable()&&a?.userId&&(a={userId:a.userId}),this.user=a;let s=this.defaultProperties?this.defaultProperties.apiKey:null;if(Zn.production||Zn.staging){let c={userId:e,clientUserId:this.user?.userId,traits:T(I({},a),{apiKey:s,forceReset:r?.forceReset}),properties:this.defaultProperties,sf:this.sf,context:this.getContext()};this.setAnalytics("identify",c)}if(this.userId&&this.draftEvents?.length){let c=this.draftEvents?.slice();this.draftEvents=[],c?.forEach(p=>{switch(p.type){case"track":p?.data?.eventName&&this.trackEvent(p.data.eventName,p.data.properties,p.data.mergeDefaultProperties,p.data.userId);break;default:break}})}}catch(a){pt.catch("Error in AnalyticsService identifyUser: ",a)}}trackPage(e,i="",r={}){try{if((Zn.production||Zn.staging)&&this.userId){let a={userId:this.userId,clientUserId:this.user?.userId,name:e,properties:r,sf:this.sf,context:this.getContext()};this.setAnalytics("page",a)}}catch(a){pt.catch("Error in AnalyticsService trackPage: ",a)}}trackEvent(s){return ee(this,arguments,function*(e,i={},r=!0,a){try{if(this.sf&&Oie.includes(e))return;if(Zn.production||Zn.staging)if(this.userId||a){if(this.eventRateLimitCache[e]?.blockedForSession)return;let c=Date.now();if(this.eventRateLimitCache[e]&&c-this.eventRateLimitCache[e].timestamp<this.TIME_WINDOW_MS){if(this.eventRateLimitCache[e].count>=this.EVENT_LIMIT){if(!this.eventRateLimitCache[e].rateLimitExceededEventTriggered){this.eventRateLimitCache[e].rateLimitExceededEventTriggered=!0,this.eventRateLimitCache[e].blockedForSession=!0;let p=I({eventName:e},i||{});this.triggerTrackEvent(Z.Events.Core.SDK_EVENT_RATE_LIMIT_EXCEEDED,p,r)}return}this.eventRateLimitCache[e].count++}else this.eventRateLimitCache[e]={count:1,timestamp:c,rateLimitExceededEventTriggered:!1,blockedForSession:!1};return this.triggerTrackEvent(e,i,r,a)}else this.draftEvents.push({type:"track",data:{eventName:e,properties:i,mergeDefaultProperties:r,userId:a}})}catch(c){pt.catch("Error in AnalyticsService trackEvent: ",c)}})}triggerTrackEvent(s){return ee(this,arguments,function*(e,i={},r=!0,a){try{r&&(i||(i={}),i=I(I({},i),this.defaultProperties));let c;if(i?.annotationId){let h=i.annotationId;if(!c&&this.commentService){let _=this.commentService.getAnnotationById(h);_?.metadata&&(c=_.metadata),_?.targetElementId&&(i.targetElementId=_.targetElementId);let E=this.commentService.getMultiThreadAnnotationById(h);E?.metadata&&(c=E.metadata),E?.targetElementId&&(i.targetElementId=E.targetElementId)}if(!c&&this.recorderAnnotationService){let _=this.recorderAnnotationService.getAnnotationById(h);_?.metadata&&(c=_.metadata)}if(!c&&this.reactionService){let _=this.reactionService.getAnnotationById(h);_?.metadata&&(c=_.metadata),_?.targetElementId&&(i.targetElementId=_.targetElementId)}if(!c&&this.areaService){let _=this.areaService.getAnnotationById(h);_?.metadata&&(c=_.metadata)}}c&&typeof c=="object"&&(i=I(I({},i),c)),i&&typeof i=="object"&&(i=T(I({},i),{userId:this.userId||a,clientUserId:this.user?.userId}));let p={userId:this.userId||a,clientUserId:this.user?.userId,event:e,properties:i,sf:this.sf,context:this.getContext()};return this.setAnalytics("track",p)}catch(c){pt.catch("Error in AnalyticsService triggerTrackEvent: ",c)}})}setAnalytics(e,i){return ee(this,null,function*(){try{return navigator.onLine?Cr(this.functions,Zn.cloudFunction.sa,{timeout:20*60*1e3})({type:e,data:i}).catch(a=>{pt.warn("Error in AnalyticsService setAnalytics promise: ",e,a)}):void 0}catch(r){pt.catch("Error in AnalyticsService setAnalytics: ",r)}})}trackAuthenticatedEvent(e,i={},r=!0){try{this.authService?.getUser$&&typeof this.authService?.getUser$()?.subscribe=="function"&&(this.authService.getUser()?this.trackEvent(e,i,r):this.authService?.getUser$()?.pipe(Ne(a=>!!a),Je(1))?.subscribe(()=>{this.trackEvent(e,i,r)}))}catch(a){pt.catch("Error in AnalyticsService trackAuthenticatedEvent: ",a)}}getContext(){try{let e={},i=_i();return e.os={name:i?.deviceInfo?.osName,version:i?.deviceInfo?.osVersion},e.page={path:i?.path,title:i?.title,url:i?.url},e.screen={height:i?.deviceInfo?.screenHeight,width:i?.deviceInfo?.screenWidth},e.app={name:i?.deviceInfo?.browserName,version:i?.deviceInfo?.browserVersion},e.device={type:i?.deviceInfo?.deviceType},e.timezone=Gie(),e.userAgent=i?.deviceInfo?.userAgent,e}catch(e){pt.catch("Error in AnalyticsService getContext: ",e)}}};o.\u0275fac=function(i){return new(i||o)(J(Vo))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var y=(()=>{let o=class o{get debugMode(){return Mie()}get logsEnabled(){return this.logsEnabled$.value}constructor(e){this.analyticsService=e,this.logsEnabled$=new fe(!0),this.log("%c[WB] Creating SERVICE LoggingService","color: blue;")}enableLogs(){try{if(this.logsEnabled$.value===!0)return;this.logsEnabled$.next(!0)}catch(e){this.catch("Error in LoggingService enableLogs: ",e)}}disableLogs(){try{if(this.logsEnabled$.value===!1)return;this.logsEnabled$.next(!1)}catch(e){this.catch("Error in LoggingService disableLogs: ",e)}}log(e,...i){this.debugMode&&console.log(e,...i)}warn(e,...i){this.debugMode&&console.warn(e,...i)}error(e,...i){this.debugMode&&console.error(e,...i)}debug(e,...i){this.debugMode&&console.debug(e,...i)}info(e,...i){this.debugMode&&console.info(e,...i)}catch(e,i,r,a=!1){try{let s=i?.message;this.logsEnabled$.value&&(s?.toLowerCase()?.includes("permission denied")||s?.toLowerCase()?.includes("permission_denied")||(i!==void 0?console.warn("Velt: ",e,i):console.warn("Velt: ",e))),a||this.analyticsService.trackEvent(Z.Events.Core.SDK_ERROR,I({sourceMethod:e,message:(i?.message?i?.message:i)||e,clientUserId:this.analyticsService?.user?.userId,snippylyUserId:this.analyticsService?.user?.userSnippylyId,source:"sdk"},r||{}))}catch{}}};o.\u0275fac=function(i){return new(i||o)(J(Qe))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var noe=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},ioe={};var vd,wV;(function(){var n;function o(we,Ee){function Pe(){}Pe.prototype=Ee.prototype,we.D=Ee.prototype,we.prototype=new Pe,we.prototype.constructor=we,we.C=function(Ce,ue,Be){for(var Se=Array(arguments.length-2),Ut=2;Ut<arguments.length;Ut++)Se[Ut-2]=arguments[Ut];return Ee.prototype[ue].apply(Ce,Se)}}function t(){this.blockSize=-1}function e(){this.blockSize=-1,this.blockSize=64,this.g=Array(4),this.B=Array(this.blockSize),this.o=this.h=0,this.s()}o(e,t),e.prototype.s=function(){this.g[0]=1732584193,this.g[1]=4023233417,this.g[2]=2562383102,this.g[3]=271733878,this.o=this.h=0};function i(we,Ee,Pe){Pe||(Pe=0);var Ce=Array(16);if(typeof Ee=="string")for(var ue=0;16>ue;++ue)Ce[ue]=Ee.charCodeAt(Pe++)|Ee.charCodeAt(Pe++)<<8|Ee.charCodeAt(Pe++)<<16|Ee.charCodeAt(Pe++)<<24;else for(ue=0;16>ue;++ue)Ce[ue]=Ee[Pe++]|Ee[Pe++]<<8|Ee[Pe++]<<16|Ee[Pe++]<<24;Ee=we.g[0],Pe=we.g[1],ue=we.g[2];var Be=we.g[3],Se=Ee+(Be^Pe&(ue^Be))+Ce[0]+3614090360&4294967295;Ee=Pe+(Se<<7&4294967295|Se>>>25),Se=Be+(ue^Ee&(Pe^ue))+Ce[1]+3905402710&4294967295,Be=Ee+(Se<<12&4294967295|Se>>>20),Se=ue+(Pe^Be&(Ee^Pe))+Ce[2]+606105819&4294967295,ue=Be+(Se<<17&4294967295|Se>>>15),Se=Pe+(Ee^ue&(Be^Ee))+Ce[3]+3250441966&4294967295,Pe=ue+(Se<<22&4294967295|Se>>>10),Se=Ee+(Be^Pe&(ue^Be))+Ce[4]+4118548399&4294967295,Ee=Pe+(Se<<7&4294967295|Se>>>25),Se=Be+(ue^Ee&(Pe^ue))+Ce[5]+1200080426&4294967295,Be=Ee+(Se<<12&4294967295|Se>>>20),Se=ue+(Pe^Be&(Ee^Pe))+Ce[6]+2821735955&4294967295,ue=Be+(Se<<17&4294967295|Se>>>15),Se=Pe+(Ee^ue&(Be^Ee))+Ce[7]+4249261313&4294967295,Pe=ue+(Se<<22&4294967295|Se>>>10),Se=Ee+(Be^Pe&(ue^Be))+Ce[8]+1770035416&4294967295,Ee=Pe+(Se<<7&4294967295|Se>>>25),Se=Be+(ue^Ee&(Pe^ue))+Ce[9]+2336552879&4294967295,Be=Ee+(Se<<12&4294967295|Se>>>20),Se=ue+(Pe^Be&(Ee^Pe))+Ce[10]+4294925233&4294967295,ue=Be+(Se<<17&4294967295|Se>>>15),Se=Pe+(Ee^ue&(Be^Ee))+Ce[11]+2304563134&4294967295,Pe=ue+(Se<<22&4294967295|Se>>>10),Se=Ee+(Be^Pe&(ue^Be))+Ce[12]+1804603682&4294967295,Ee=Pe+(Se<<7&4294967295|Se>>>25),Se=Be+(ue^Ee&(Pe^ue))+Ce[13]+4254626195&4294967295,Be=Ee+(Se<<12&4294967295|Se>>>20),Se=ue+(Pe^Be&(Ee^Pe))+Ce[14]+2792965006&4294967295,ue=Be+(Se<<17&4294967295|Se>>>15),Se=Pe+(Ee^ue&(Be^Ee))+Ce[15]+1236535329&4294967295,Pe=ue+(Se<<22&4294967295|Se>>>10),Se=Ee+(ue^Be&(Pe^ue))+Ce[1]+4129170786&4294967295,Ee=Pe+(Se<<5&4294967295|Se>>>27),Se=Be+(Pe^ue&(Ee^Pe))+Ce[6]+3225465664&4294967295,Be=Ee+(Se<<9&4294967295|Se>>>23),Se=ue+(Ee^Pe&(Be^Ee))+Ce[11]+643717713&4294967295,ue=Be+(Se<<14&4294967295|Se>>>18),Se=Pe+(Be^Ee&(ue^Be))+Ce[0]+3921069994&4294967295,Pe=ue+(Se<<20&4294967295|Se>>>12),Se=Ee+(ue^Be&(Pe^ue))+Ce[5]+3593408605&4294967295,Ee=Pe+(Se<<5&4294967295|Se>>>27),Se=Be+(Pe^ue&(Ee^Pe))+Ce[10]+38016083&4294967295,Be=Ee+(Se<<9&4294967295|Se>>>23),Se=ue+(Ee^Pe&(Be^Ee))+Ce[15]+3634488961&4294967295,ue=Be+(Se<<14&4294967295|Se>>>18),Se=Pe+(Be^Ee&(ue^Be))+Ce[4]+3889429448&4294967295,Pe=ue+(Se<<20&4294967295|Se>>>12),Se=Ee+(ue^Be&(Pe^ue))+Ce[9]+568446438&4294967295,Ee=Pe+(Se<<5&4294967295|Se>>>27),Se=Be+(Pe^ue&(Ee^Pe))+Ce[14]+3275163606&4294967295,Be=Ee+(Se<<9&4294967295|Se>>>23),Se=ue+(Ee^Pe&(Be^Ee))+Ce[3]+4107603335&4294967295,ue=Be+(Se<<14&4294967295|Se>>>18),Se=Pe+(Be^Ee&(ue^Be))+Ce[8]+1163531501&4294967295,Pe=ue+(Se<<20&4294967295|Se>>>12),Se=Ee+(ue^Be&(Pe^ue))+Ce[13]+2850285829&4294967295,Ee=Pe+(Se<<5&4294967295|Se>>>27),Se=Be+(Pe^ue&(Ee^Pe))+Ce[2]+4243563512&4294967295,Be=Ee+(Se<<9&4294967295|Se>>>23),Se=ue+(Ee^Pe&(Be^Ee))+Ce[7]+1735328473&4294967295,ue=Be+(Se<<14&4294967295|Se>>>18),Se=Pe+(Be^Ee&(ue^Be))+Ce[12]+2368359562&4294967295,Pe=ue+(Se<<20&4294967295|Se>>>12),Se=Ee+(Pe^ue^Be)+Ce[5]+4294588738&4294967295,Ee=Pe+(Se<<4&4294967295|Se>>>28),Se=Be+(Ee^Pe^ue)+Ce[8]+2272392833&4294967295,Be=Ee+(Se<<11&4294967295|Se>>>21),Se=ue+(Be^Ee^Pe)+Ce[11]+1839030562&4294967295,ue=Be+(Se<<16&4294967295|Se>>>16),Se=Pe+(ue^Be^Ee)+Ce[14]+4259657740&4294967295,Pe=ue+(Se<<23&4294967295|Se>>>9),Se=Ee+(Pe^ue^Be)+Ce[1]+2763975236&4294967295,Ee=Pe+(Se<<4&4294967295|Se>>>28),Se=Be+(Ee^Pe^ue)+Ce[4]+1272893353&4294967295,Be=Ee+(Se<<11&4294967295|Se>>>21),Se=ue+(Be^Ee^Pe)+Ce[7]+4139469664&4294967295,ue=Be+(Se<<16&4294967295|Se>>>16),Se=Pe+(ue^Be^Ee)+Ce[10]+3200236656&4294967295,Pe=ue+(Se<<23&4294967295|Se>>>9),Se=Ee+(Pe^ue^Be)+Ce[13]+681279174&4294967295,Ee=Pe+(Se<<4&4294967295|Se>>>28),Se=Be+(Ee^Pe^ue)+Ce[0]+3936430074&4294967295,Be=Ee+(Se<<11&4294967295|Se>>>21),Se=ue+(Be^Ee^Pe)+Ce[3]+3572445317&4294967295,ue=Be+(Se<<16&4294967295|Se>>>16),Se=Pe+(ue^Be^Ee)+Ce[6]+76029189&4294967295,Pe=ue+(Se<<23&4294967295|Se>>>9),Se=Ee+(Pe^ue^Be)+Ce[9]+3654602809&4294967295,Ee=Pe+(Se<<4&4294967295|Se>>>28),Se=Be+(Ee^Pe^ue)+Ce[12]+3873151461&4294967295,Be=Ee+(Se<<11&4294967295|Se>>>21),Se=ue+(Be^Ee^Pe)+Ce[15]+530742520&4294967295,ue=Be+(Se<<16&4294967295|Se>>>16),Se=Pe+(ue^Be^Ee)+Ce[2]+3299628645&4294967295,Pe=ue+(Se<<23&4294967295|Se>>>9),Se=Ee+(ue^(Pe|~Be))+Ce[0]+4096336452&4294967295,Ee=Pe+(Se<<6&4294967295|Se>>>26),Se=Be+(Pe^(Ee|~ue))+Ce[7]+1126891415&4294967295,Be=Ee+(Se<<10&4294967295|Se>>>22),Se=ue+(Ee^(Be|~Pe))+Ce[14]+2878612391&4294967295,ue=Be+(Se<<15&4294967295|Se>>>17),Se=Pe+(Be^(ue|~Ee))+Ce[5]+4237533241&4294967295,Pe=ue+(Se<<21&4294967295|Se>>>11),Se=Ee+(ue^(Pe|~Be))+Ce[12]+1700485571&4294967295,Ee=Pe+(Se<<6&4294967295|Se>>>26),Se=Be+(Pe^(Ee|~ue))+Ce[3]+2399980690&4294967295,Be=Ee+(Se<<10&4294967295|Se>>>22),Se=ue+(Ee^(Be|~Pe))+Ce[10]+4293915773&4294967295,ue=Be+(Se<<15&4294967295|Se>>>17),Se=Pe+(Be^(ue|~Ee))+Ce[1]+2240044497&4294967295,Pe=ue+(Se<<21&4294967295|Se>>>11),Se=Ee+(ue^(Pe|~Be))+Ce[8]+1873313359&4294967295,Ee=Pe+(Se<<6&4294967295|Se>>>26),Se=Be+(Pe^(Ee|~ue))+Ce[15]+4264355552&4294967295,Be=Ee+(Se<<10&4294967295|Se>>>22),Se=ue+(Ee^(Be|~Pe))+Ce[6]+2734768916&4294967295,ue=Be+(Se<<15&4294967295|Se>>>17),Se=Pe+(Be^(ue|~Ee))+Ce[13]+1309151649&4294967295,Pe=ue+(Se<<21&4294967295|Se>>>11),Se=Ee+(ue^(Pe|~Be))+Ce[4]+4149444226&4294967295,Ee=Pe+(Se<<6&4294967295|Se>>>26),Se=Be+(Pe^(Ee|~ue))+Ce[11]+3174756917&4294967295,Be=Ee+(Se<<10&4294967295|Se>>>22),Se=ue+(Ee^(Be|~Pe))+Ce[2]+718787259&4294967295,ue=Be+(Se<<15&4294967295|Se>>>17),Se=Pe+(Be^(ue|~Ee))+Ce[9]+3951481745&4294967295,we.g[0]=we.g[0]+Ee&4294967295,we.g[1]=we.g[1]+(ue+(Se<<21&4294967295|Se>>>11))&4294967295,we.g[2]=we.g[2]+ue&4294967295,we.g[3]=we.g[3]+Be&4294967295}e.prototype.u=function(we,Ee){Ee===void 0&&(Ee=we.length);for(var Pe=Ee-this.blockSize,Ce=this.B,ue=this.h,Be=0;Be<Ee;){if(ue==0)for(;Be<=Pe;)i(this,we,Be),Be+=this.blockSize;if(typeof we=="string"){for(;Be<Ee;)if(Ce[ue++]=we.charCodeAt(Be++),ue==this.blockSize){i(this,Ce),ue=0;break}}else for(;Be<Ee;)if(Ce[ue++]=we[Be++],ue==this.blockSize){i(this,Ce),ue=0;break}}this.h=ue,this.o+=Ee},e.prototype.v=function(){var we=Array((56>this.h?this.blockSize:2*this.blockSize)-this.h);we[0]=128;for(var Ee=1;Ee<we.length-8;++Ee)we[Ee]=0;var Pe=8*this.o;for(Ee=we.length-8;Ee<we.length;++Ee)we[Ee]=Pe&255,Pe/=256;for(this.u(we),we=Array(16),Ee=Pe=0;4>Ee;++Ee)for(var Ce=0;32>Ce;Ce+=8)we[Pe++]=this.g[Ee]>>>Ce&255;return we};function r(we,Ee){var Pe=s;return Object.prototype.hasOwnProperty.call(Pe,we)?Pe[we]:Pe[we]=Ee(we)}function a(we,Ee){this.h=Ee;for(var Pe=[],Ce=!0,ue=we.length-1;0<=ue;ue--){var Be=we[ue]|0;Ce&&Be==Ee||(Pe[ue]=Be,Ce=!1)}this.g=Pe}var s={};function c(we){return-128<=we&&128>we?r(we,function(Ee){return new a([Ee|0],0>Ee?-1:0)}):new a([we|0],0>we?-1:0)}function p(we){if(isNaN(we)||!isFinite(we))return _;if(0>we)return X(p(-we));for(var Ee=[],Pe=1,Ce=0;we>=Pe;Ce++)Ee[Ce]=we/Pe|0,Pe*=4294967296;return new a(Ee,0)}function h(we,Ee){if(we.length==0)throw Error("number format error: empty string");if(Ee=Ee||10,2>Ee||36<Ee)throw Error("radix out of range: "+Ee);if(we.charAt(0)=="-")return X(h(we.substring(1),Ee));if(0<=we.indexOf("-"))throw Error('number format error: interior "-" character');for(var Pe=p(Math.pow(Ee,8)),Ce=_,ue=0;ue<we.length;ue+=8){var Be=Math.min(8,we.length-ue),Se=parseInt(we.substring(ue,ue+Be),Ee);8>Be?(Be=p(Math.pow(Ee,Be)),Ce=Ce.j(Be).add(p(Se))):(Ce=Ce.j(Pe),Ce=Ce.add(p(Se)))}return Ce}var _=c(0),E=c(1),D=c(16777216);n=a.prototype,n.m=function(){if(G(this))return-X(this).m();for(var we=0,Ee=1,Pe=0;Pe<this.g.length;Pe++){var Ce=this.i(Pe);we+=(0<=Ce?Ce:4294967296+Ce)*Ee,Ee*=4294967296}return we},n.toString=function(we){if(we=we||10,2>we||36<we)throw Error("radix out of range: "+we);if(B(this))return"0";if(G(this))return"-"+X(this).toString(we);for(var Ee=p(Math.pow(we,6)),Pe=this,Ce="";;){var ue=Le(Pe,Ee).g;Pe=he(Pe,ue.j(Ee));var Be=((0<Pe.g.length?Pe.g[0]:Pe.h)>>>0).toString(we);if(Pe=ue,B(Pe))return Be+Ce;for(;6>Be.length;)Be="0"+Be;Ce=Be+Ce}},n.i=function(we){return 0>we?0:we<this.g.length?this.g[we]:this.h};function B(we){if(we.h!=0)return!1;for(var Ee=0;Ee<we.g.length;Ee++)if(we.g[Ee]!=0)return!1;return!0}function G(we){return we.h==-1}n.l=function(we){return we=he(this,we),G(we)?-1:B(we)?0:1};function X(we){for(var Ee=we.g.length,Pe=[],Ce=0;Ce<Ee;Ce++)Pe[Ce]=~we.g[Ce];return new a(Pe,~we.h).add(E)}n.abs=function(){return G(this)?X(this):this},n.add=function(we){for(var Ee=Math.max(this.g.length,we.g.length),Pe=[],Ce=0,ue=0;ue<=Ee;ue++){var Be=Ce+(this.i(ue)&65535)+(we.i(ue)&65535),Se=(Be>>>16)+(this.i(ue)>>>16)+(we.i(ue)>>>16);Ce=Se>>>16,Be&=65535,Se&=65535,Pe[ue]=Se<<16|Be}return new a(Pe,Pe[Pe.length-1]&-2147483648?-1:0)};function he(we,Ee){return we.add(X(Ee))}n.j=function(we){if(B(this)||B(we))return _;if(G(this))return G(we)?X(this).j(X(we)):X(X(this).j(we));if(G(we))return X(this.j(X(we)));if(0>this.l(D)&&0>we.l(D))return p(this.m()*we.m());for(var Ee=this.g.length+we.g.length,Pe=[],Ce=0;Ce<2*Ee;Ce++)Pe[Ce]=0;for(Ce=0;Ce<this.g.length;Ce++)for(var ue=0;ue<we.g.length;ue++){var Be=this.i(Ce)>>>16,Se=this.i(Ce)&65535,Ut=we.i(ue)>>>16,Gt=we.i(ue)&65535;Pe[2*Ce+2*ue]+=Se*Gt,Ie(Pe,2*Ce+2*ue),Pe[2*Ce+2*ue+1]+=Be*Gt,Ie(Pe,2*Ce+2*ue+1),Pe[2*Ce+2*ue+1]+=Se*Ut,Ie(Pe,2*Ce+2*ue+1),Pe[2*Ce+2*ue+2]+=Be*Ut,Ie(Pe,2*Ce+2*ue+2)}for(Ce=0;Ce<Ee;Ce++)Pe[Ce]=Pe[2*Ce+1]<<16|Pe[2*Ce];for(Ce=Ee;Ce<2*Ee;Ce++)Pe[Ce]=0;return new a(Pe,0)};function Ie(we,Ee){for(;(we[Ee]&65535)!=we[Ee];)we[Ee+1]+=we[Ee]>>>16,we[Ee]&=65535,Ee++}function Me(we,Ee){this.g=we,this.h=Ee}function Le(we,Ee){if(B(Ee))throw Error("division by zero");if(B(we))return new Me(_,_);if(G(we))return Ee=Le(X(we),Ee),new Me(X(Ee.g),X(Ee.h));if(G(Ee))return Ee=Le(we,X(Ee)),new Me(X(Ee.g),Ee.h);if(30<we.g.length){if(G(we)||G(Ee))throw Error("slowDivide_ only works with positive integers.");for(var Pe=E,Ce=Ee;0>=Ce.l(we);)Pe=We(Pe),Ce=We(Ce);var ue=ke(Pe,1),Be=ke(Ce,1);for(Ce=ke(Ce,2),Pe=ke(Pe,2);!B(Ce);){var Se=Be.add(Ce);0>=Se.l(we)&&(ue=ue.add(Pe),Be=Se),Ce=ke(Ce,1),Pe=ke(Pe,1)}return Ee=he(we,ue.j(Ee)),new Me(ue,Ee)}for(ue=_;0<=we.l(Ee);){for(Pe=Math.max(1,Math.floor(we.m()/Ee.m())),Ce=Math.ceil(Math.log(Pe)/Math.LN2),Ce=48>=Ce?1:Math.pow(2,Ce-48),Be=p(Pe),Se=Be.j(Ee);G(Se)||0<Se.l(we);)Pe-=Ce,Be=p(Pe),Se=Be.j(Ee);B(Be)&&(Be=E),ue=ue.add(Be),we=he(we,Se)}return new Me(ue,we)}n.A=function(we){return Le(this,we).h},n.and=function(we){for(var Ee=Math.max(this.g.length,we.g.length),Pe=[],Ce=0;Ce<Ee;Ce++)Pe[Ce]=this.i(Ce)&we.i(Ce);return new a(Pe,this.h&we.h)},n.or=function(we){for(var Ee=Math.max(this.g.length,we.g.length),Pe=[],Ce=0;Ce<Ee;Ce++)Pe[Ce]=this.i(Ce)|we.i(Ce);return new a(Pe,this.h|we.h)},n.xor=function(we){for(var Ee=Math.max(this.g.length,we.g.length),Pe=[],Ce=0;Ce<Ee;Ce++)Pe[Ce]=this.i(Ce)^we.i(Ce);return new a(Pe,this.h^we.h)};function We(we){for(var Ee=we.g.length+1,Pe=[],Ce=0;Ce<Ee;Ce++)Pe[Ce]=we.i(Ce)<<1|we.i(Ce-1)>>>31;return new a(Pe,we.h)}function ke(we,Ee){var Pe=Ee>>5;Ee%=32;for(var Ce=we.g.length-Pe,ue=[],Be=0;Be<Ce;Be++)ue[Be]=0<Ee?we.i(Be+Pe)>>>Ee|we.i(Be+Pe+1)<<32-Ee:we.i(Be+Pe);return new a(ue,we.h)}e.prototype.digest=e.prototype.v,e.prototype.reset=e.prototype.s,e.prototype.update=e.prototype.u,wV=ioe.Md5=e,a.prototype.add=a.prototype.add,a.prototype.multiply=a.prototype.j,a.prototype.modulo=a.prototype.A,a.prototype.compare=a.prototype.l,a.prototype.toNumber=a.prototype.m,a.prototype.toString=a.prototype.toString,a.prototype.getBits=a.prototype.i,a.fromNumber=p,a.fromString=h,vd=ioe.Integer=a}).apply(typeof noe<"u"?noe:typeof self<"u"?self:typeof window<"u"?window:{});var JO=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},Cd={};var DV,a6e,lv,AV,sS,e6,OV,MV,PV;(function(){var n,o=typeof Object.defineProperties=="function"?Object.defineProperty:function(L,Q,le){return L==Array.prototype||L==Object.prototype||(L[Q]=le.value),L};function t(L){L=[typeof globalThis=="object"&&globalThis,L,typeof window=="object"&&window,typeof self=="object"&&self,typeof JO=="object"&&JO];for(var Q=0;Q<L.length;++Q){var le=L[Q];if(le&&le.Math==Math)return le}throw Error("Cannot find global object")}var e=t(this);function i(L,Q){if(Q)e:{var le=e;L=L.split(".");for(var ye=0;ye<L.length-1;ye++){var ze=L[ye];if(!(ze in le))break e;le=le[ze]}L=L[L.length-1],ye=le[L],Q=Q(ye),Q!=ye&&Q!=null&&o(le,L,{configurable:!0,writable:!0,value:Q})}}function r(L,Q){L instanceof String&&(L+="");var le=0,ye=!1,ze={next:function(){if(!ye&&le<L.length){var tt=le++;return{value:Q(tt,L[tt]),done:!1}}return ye=!0,{done:!0,value:void 0}}};return ze[Symbol.iterator]=function(){return ze},ze}i("Array.prototype.values",function(L){return L||function(){return r(this,function(Q,le){return le})}});var a=a||{},s=this||self;function c(L){var Q=typeof L;return Q=Q!="object"?Q:L?Array.isArray(L)?"array":Q:"null",Q=="array"||Q=="object"&&typeof L.length=="number"}function p(L){var Q=typeof L;return Q=="object"&&L!=null||Q=="function"}function h(L,Q,le){return L.call.apply(L.bind,arguments)}function _(L,Q,le){if(!L)throw Error();if(2<arguments.length){var ye=Array.prototype.slice.call(arguments,2);return function(){var ze=Array.prototype.slice.call(arguments);return Array.prototype.unshift.apply(ze,ye),L.apply(Q,ze)}}return function(){return L.apply(Q,arguments)}}function E(L,Q,le){return E=Function.prototype.bind&&Function.prototype.bind.toString().indexOf("native code")!=-1?h:_,E.apply(null,arguments)}function D(L,Q){var le=Array.prototype.slice.call(arguments,1);return function(){var ye=le.slice();return ye.push.apply(ye,arguments),L.apply(this,ye)}}function B(L,Q){function le(){}le.prototype=Q.prototype,L.aa=Q.prototype,L.prototype=new le,L.prototype.constructor=L,L.Qb=function(ye,ze,tt){for(var wt=Array(arguments.length-2),no=2;no<arguments.length;no++)wt[no-2]=arguments[no];return Q.prototype[ze].apply(ye,wt)}}function G(L){let Q=L.length;if(0<Q){let le=Array(Q);for(let ye=0;ye<Q;ye++)le[ye]=L[ye];return le}return[]}function X(L,Q){for(let le=1;le<arguments.length;le++){let ye=arguments[le];if(c(ye)){let ze=L.length||0,tt=ye.length||0;L.length=ze+tt;for(let wt=0;wt<tt;wt++)L[ze+wt]=ye[wt]}else L.push(ye)}}class he{constructor(Q,le){this.i=Q,this.j=le,this.h=0,this.g=null}get(){let Q;return 0<this.h?(this.h--,Q=this.g,this.g=Q.next,Q.next=null):Q=this.i(),Q}}function Ie(L){return/^[\s\xa0]*$/.test(L)}function Me(){var L=s.navigator;return L&&(L=L.userAgent)?L:""}function Le(L){return Le[" "](L),L}Le[" "]=function(){};var We=Me().indexOf("Gecko")!=-1&&!(Me().toLowerCase().indexOf("webkit")!=-1&&Me().indexOf("Edge")==-1)&&!(Me().indexOf("Trident")!=-1||Me().indexOf("MSIE")!=-1)&&Me().indexOf("Edge")==-1;function ke(L,Q,le){for(let ye in L)Q.call(le,L[ye],ye,L)}function we(L,Q){for(let le in L)Q.call(void 0,L[le],le,L)}function Ee(L){let Q={};for(let le in L)Q[le]=L[le];return Q}let Pe="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" ");function Ce(L,Q){let le,ye;for(let ze=1;ze<arguments.length;ze++){ye=arguments[ze];for(le in ye)L[le]=ye[le];for(let tt=0;tt<Pe.length;tt++)le=Pe[tt],Object.prototype.hasOwnProperty.call(ye,le)&&(L[le]=ye[le])}}function ue(L){var Q=1;L=L.split(":");let le=[];for(;0<Q&&L.length;)le.push(L.shift()),Q--;return L.length&&le.push(L.join(":")),le}function Be(L){s.setTimeout(()=>{throw L},0)}function Se(){var L=Fn;let Q=null;return L.g&&(Q=L.g,L.g=L.g.next,L.g||(L.h=null),Q.next=null),Q}class Ut{constructor(){this.h=this.g=null}add(Q,le){let ye=Gt.get();ye.set(Q,le),this.h?this.h.next=ye:this.g=ye,this.h=ye}}var Gt=new he(()=>new Dt,L=>L.reset());class Dt{constructor(){this.next=this.g=this.h=null}set(Q,le){this.h=Q,this.g=le,this.next=null}reset(){this.next=this.g=this.h=null}}let It,Nt=!1,Fn=new Ut,eo=()=>{let L=s.Promise.resolve(void 0);It=()=>{L.then(ii)}};var ii=()=>{for(var L;L=Se();){try{L.h.call(L.g)}catch(le){Be(le)}var Q=Gt;Q.j(L),100>Q.h&&(Q.h++,L.next=Q.g,Q.g=L)}Nt=!1};function Oi(){this.s=this.s,this.C=this.C}Oi.prototype.s=!1,Oi.prototype.ma=function(){this.s||(this.s=!0,this.N())},Oi.prototype.N=function(){if(this.C)for(;this.C.length;)this.C.shift()()};function dn(L,Q){this.type=L,this.g=this.target=Q,this.defaultPrevented=!1}dn.prototype.h=function(){this.defaultPrevented=!0};var ui=function(){if(!s.addEventListener||!Object.defineProperty)return!1;var L=!1,Q=Object.defineProperty({},"passive",{get:function(){L=!0}});try{let le=()=>{};s.addEventListener("test",le,Q),s.removeEventListener("test",le,Q)}catch{}return L}();function Mi(L,Q){if(dn.call(this,L?L.type:""),this.relatedTarget=this.g=this.target=null,this.button=this.screenY=this.screenX=this.clientY=this.clientX=0,this.key="",this.metaKey=this.shiftKey=this.altKey=this.ctrlKey=!1,this.state=null,this.pointerId=0,this.pointerType="",this.i=null,L){var le=this.type=L.type,ye=L.changedTouches&&L.changedTouches.length?L.changedTouches[0]:null;if(this.target=L.target||L.srcElement,this.g=Q,Q=L.relatedTarget){if(We){e:{try{Le(Q.nodeName);var ze=!0;break e}catch{}ze=!1}ze||(Q=null)}}else le=="mouseover"?Q=L.fromElement:le=="mouseout"&&(Q=L.toElement);this.relatedTarget=Q,ye?(this.clientX=ye.clientX!==void 0?ye.clientX:ye.pageX,this.clientY=ye.clientY!==void 0?ye.clientY:ye.pageY,this.screenX=ye.screenX||0,this.screenY=ye.screenY||0):(this.clientX=L.clientX!==void 0?L.clientX:L.pageX,this.clientY=L.clientY!==void 0?L.clientY:L.pageY,this.screenX=L.screenX||0,this.screenY=L.screenY||0),this.button=L.button,this.key=L.key||"",this.ctrlKey=L.ctrlKey,this.altKey=L.altKey,this.shiftKey=L.shiftKey,this.metaKey=L.metaKey,this.pointerId=L.pointerId||0,this.pointerType=typeof L.pointerType=="string"?L.pointerType:Am[L.pointerType]||"",this.state=L.state,this.i=L,L.defaultPrevented&&Mi.aa.h.call(this)}}B(Mi,dn);var Am={2:"touch",3:"pen",4:"mouse"};Mi.prototype.h=function(){Mi.aa.h.call(this);var L=this.i;L.preventDefault?L.preventDefault():L.returnValue=!1};var go="closure_listenable_"+(1e6*Math.random()|0),Ws=0;function Br(L,Q,le,ye,ze){this.listener=L,this.proxy=null,this.src=Q,this.type=le,this.capture=!!ye,this.ha=ze,this.key=++Ws,this.da=this.fa=!1}function qs(L){L.da=!0,L.listener=null,L.proxy=null,L.src=null,L.ha=null}function wl(L){this.src=L,this.g={},this.h=0}wl.prototype.add=function(L,Q,le,ye,ze){var tt=L.toString();L=this.g[tt],L||(L=this.g[tt]=[],this.h++);var wt=og(L,Q,ye,ze);return-1<wt?(Q=L[wt],le||(Q.fa=!1)):(Q=new Br(Q,this.src,tt,!!ye,ze),Q.fa=le,L.push(Q)),Q};function _c(L,Q){var le=Q.type;if(le in L.g){var ye=L.g[le],ze=Array.prototype.indexOf.call(ye,Q,void 0),tt;(tt=0<=ze)&&Array.prototype.splice.call(ye,ze,1),tt&&(qs(Q),L.g[le].length==0&&(delete L.g[le],L.h--))}}function og(L,Q,le,ye){for(var ze=0;ze<L.length;++ze){var tt=L[ze];if(!tt.da&&tt.listener==Q&&tt.capture==!!le&&tt.ha==ye)return ze}return-1}var Dl="closure_lm_"+(1e6*Math.random()|0),rg={};function oh(L,Q,le,ye,ze){if(ye&&ye.once)return ag(L,Q,le,ye,ze);if(Array.isArray(Q)){for(var tt=0;tt<Q.length;tt++)oh(L,Q[tt],le,ye,ze);return null}return le=Sc(le),L&&L[go]?L.K(Q,le,p(ye)?!!ye.capture:!!ye,ze):Om(L,Q,le,!1,ye,ze)}function Om(L,Q,le,ye,ze,tt){if(!Q)throw Error("Invalid event type");var wt=p(ze)?!!ze.capture:!!ze,no=Mm(L);if(no||(L[Dl]=no=new wl(L)),le=no.add(Q,le,ye,wt,tt),le.proxy)return le;if(ye=rh(),le.proxy=ye,ye.src=L,ye.listener=le,L.addEventListener)ui||(ze=wt),ze===void 0&&(ze=!1),L.addEventListener(Q.toString(),ye,ze);else if(L.attachEvent)L.attachEvent(dw(Q.toString()),ye);else if(L.addListener&&L.removeListener)L.addListener(ye);else throw Error("addEventListener and attachEvent are unavailable.");return le}function rh(){function L(le){return Q.call(L.src,L.listener,le)}let Q=qC;return L}function ag(L,Q,le,ye,ze){if(Array.isArray(Q)){for(var tt=0;tt<Q.length;tt++)ag(L,Q[tt],le,ye,ze);return null}return le=Sc(le),L&&L[go]?L.L(Q,le,p(ye)?!!ye.capture:!!ye,ze):Om(L,Q,le,!0,ye,ze)}function WC(L,Q,le,ye,ze){if(Array.isArray(Q))for(var tt=0;tt<Q.length;tt++)WC(L,Q[tt],le,ye,ze);else ye=p(ye)?!!ye.capture:!!ye,le=Sc(le),L&&L[go]?(L=L.i,Q=String(Q).toString(),Q in L.g&&(tt=L.g[Q],le=og(tt,le,ye,ze),-1<le&&(qs(tt[le]),Array.prototype.splice.call(tt,le,1),tt.length==0&&(delete L.g[Q],L.h--)))):L&&(L=Mm(L))&&(Q=L.g[Q.toString()],L=-1,Q&&(L=og(Q,le,ye,ze)),(le=-1<L?Q[L]:null)&&ah(le))}function ah(L){if(typeof L!="number"&&L&&!L.da){var Q=L.src;if(Q&&Q[go])_c(Q.i,L);else{var le=L.type,ye=L.proxy;Q.removeEventListener?Q.removeEventListener(le,ye,L.capture):Q.detachEvent?Q.detachEvent(dw(le),ye):Q.addListener&&Q.removeListener&&Q.removeListener(ye),(le=Mm(Q))?(_c(le,L),le.h==0&&(le.src=null,Q[Dl]=null)):qs(L)}}}function dw(L){return L in rg?rg[L]:rg[L]="on"+L}function qC(L,Q){if(L.da)L=!0;else{Q=new Mi(Q,this);var le=L.listener,ye=L.ha||L.src;L.fa&&ah(L),L=le.call(ye,Q)}return L}function Mm(L){return L=L[Dl],L instanceof wl?L:null}var yc="__closure_events_fn_"+(1e9*Math.random()>>>0);function Sc(L){return typeof L=="function"?L:(L[yc]||(L[yc]=function(Q){return L.handleEvent(Q)}),L[yc])}function Er(){Oi.call(this),this.i=new wl(this),this.M=this,this.F=null}B(Er,Oi),Er.prototype[go]=!0,Er.prototype.removeEventListener=function(L,Q,le,ye){WC(this,L,Q,le,ye)};function Vr(L,Q){var le,ye=L.F;if(ye)for(le=[];ye;ye=ye.F)le.push(ye);if(L=L.M,ye=Q.type||Q,typeof Q=="string")Q=new dn(Q,L);else if(Q instanceof dn)Q.target=Q.target||L;else{var ze=Q;Q=new dn(ye,L),Ce(Q,ze)}if(ze=!0,le)for(var tt=le.length-1;0<=tt;tt--){var wt=Q.g=le[tt];ze=sg(wt,ye,!0,Q)&&ze}if(wt=Q.g=L,ze=sg(wt,ye,!0,Q)&&ze,ze=sg(wt,ye,!1,Q)&&ze,le)for(tt=0;tt<le.length;tt++)wt=Q.g=le[tt],ze=sg(wt,ye,!1,Q)&&ze}Er.prototype.N=function(){if(Er.aa.N.call(this),this.i){var L=this.i,Q;for(Q in L.g){for(var le=L.g[Q],ye=0;ye<le.length;ye++)qs(le[ye]);delete L.g[Q],L.h--}}this.F=null},Er.prototype.K=function(L,Q,le,ye){return this.i.add(String(L),Q,!1,le,ye)},Er.prototype.L=function(L,Q,le,ye){return this.i.add(String(L),Q,!0,le,ye)};function sg(L,Q,le,ye){if(Q=L.i.g[String(Q)],!Q)return!0;Q=Q.concat();for(var ze=!0,tt=0;tt<Q.length;++tt){var wt=Q[tt];if(wt&&!wt.da&&wt.capture==le){var no=wt.listener,na=wt.ha||wt.src;wt.fa&&_c(L.i,wt),ze=no.call(na,ye)!==!1&&ze}}return ze&&!ye.defaultPrevented}function sh(L,Q,le){if(typeof L=="function")le&&(L=E(L,le));else if(L&&typeof L.handleEvent=="function")L=E(L.handleEvent,L);else throw Error("Invalid listener argument");return 2147483647<Number(Q)?-1:s.setTimeout(L,Q||0)}function YC(L){L.g=sh(()=>{L.g=null,L.i&&(L.i=!1,YC(L))},L.l);let Q=L.h;L.h=null,L.m.apply(null,Q)}class lh extends Oi{constructor(Q,le){super(),this.m=Q,this.l=le,this.h=null,this.i=!1,this.g=null}j(Q){this.h=arguments,this.g?this.i=!0:YC(this)}N(){super.N(),this.g&&(s.clearTimeout(this.g),this.g=null,this.i=!1,this.h=null)}}function bc(L){Oi.call(this),this.h=L,this.g={}}B(bc,Oi);var Ys=[];function Pm(L){ke(L.g,function(Q,le){this.g.hasOwnProperty(le)&&ah(Q)},L),L.g={}}bc.prototype.N=function(){bc.aa.N.call(this),Pm(this)},bc.prototype.handleEvent=function(){throw Error("EventHandler.handleEvent not implemented")};var lg=s.JSON.stringify,KC=s.JSON.parse,l9=class{stringify(L){return s.JSON.stringify(L,void 0)}parse(L){return s.JSON.parse(L,void 0)}};function Ad(){}Ad.prototype.h=null;function cg(L){return L.h||(L.h=L.i())}function pw(){}var Al={OPEN:"a",kb:"b",Ja:"c",wb:"d"};function ZC(){dn.call(this,"d")}B(ZC,dn);function XC(){dn.call(this,"c")}B(XC,dn);var uo={},km=null;function ch(){return km=km||new Er}uo.La="serverreachability";function QC(L){dn.call(this,uo.La,L)}B(QC,dn);function Rm(L){let Q=ch();Vr(Q,new QC(Q))}uo.STAT_EVENT="statevent";function JC(L,Q){dn.call(this,uo.STAT_EVENT,L),this.stat=Q}B(JC,dn);function Ur(L){let Q=ch();Vr(Q,new JC(Q,L))}uo.Ma="timingevent";function gw(L,Q){dn.call(this,uo.Ma,L),this.size=Q}B(gw,dn);function pa(L,Q){if(typeof L!="function")throw Error("Fn must not be null and must be a function");return s.setTimeout(function(){L()},Q)}function Ic(){this.g=!0}Ic.prototype.xa=function(){this.g=!1};function uw(L,Q,le,ye,ze,tt){L.info(function(){if(L.g)if(tt)for(var wt="",no=tt.split("&"),na=0;na<no.length;na++){var Si=no[na].split("=");if(1<Si.length){var ga=Si[0];Si=Si[1];var ua=ga.split("_");wt=2<=ua.length&&ua[1]=="type"?wt+(ga+"="+Si+"&"):wt+(ga+"=redacted&")}}else wt=null;else wt=tt;return"XMLHTTP REQ ("+ye+") [attempt "+ze+"]: "+Q+`
|
|
170
170
|
`+le+`
|
|
171
171
|
`+wt})}function hw(L,Q,le,ye,ze,tt,wt){L.info(function(){return"XMLHTTP RESP ("+ye+") [ attempt "+ze+"]: "+Q+`
|
|
172
172
|
`+le+`
|
|
@@ -192,7 +192,7 @@ This typically indicates that your device does not have a healthy Internet conne
|
|
|
192
192
|
<img src="${o||this.thumbnailWithPlayIconUrl||this.thumbnailUrl}" />
|
|
193
193
|
</a>
|
|
194
194
|
`}};var Pp=class{constructor(){this.type="recorder",this.recordingType="audio",this.mode="floating",this.attachment=null,this.attachments=[],this.pageInfo=new Zi}};var hM=class{constructor(){this.type="rewriter",this.rewriterType="copywriter",this.pageInfo=new Zi}};var NS=class{constructor(){this.screenWidth=0,this.screenHeight=0,this.screenScrollHeight=0}};var kp=class{constructor(){this.pageInfo=new Zi}},FS=function(n){return n.Start="start",n.End="end",n}(FS||{}),Bv=function(n){return n.Avatar="avatar",n.Label="label",n}(Bv||{});var fM=class{constructor(){this.sources=[],this.playerState=new LS}},LS=class{constructor(){this.volume=1}};var BS=class{constructor(){this.to=[],this.resolved=!1,this.type="tag",this.pageInfo=new Zi}};var Rp=class{constructor(){this.visibility="private"}};var vM=class{constructor(){this.reactions=[],this.type="reaction",this.pageInfo=new Zi,this.isReactionResolverUsed=!1}};var CM=class{};var $t=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.analyticsService=i,this.config$=new fe(null),this.disableLogsConfig$=new fe({warnings:!0,suppressAll:!1}),this.apiKey$=new fe(""),this.baseFeatureAllowList=[],this.sf$=new fe(!1),this.sdkType$=new fe("core"),this.logsEnabled$=new fe(!0);try{this.sdkType$.subscribe(r=>{this.analyticsService.updateDefaultProperties({sdkType:r})},r=>{this.loggingService.catch("Error in ConfigService sdkType$: ",r)}),this.logsEnabled$.subscribe(r=>{r?this.loggingService.enableLogs():this.loggingService.disableLogs(),pt.logsEnabled=r},r=>{this.loggingService.catch("Error in ConfigService logsEnabled$: ",r)})}catch(r){this.loggingService.catch("Error in ConfigService constructor: ",r)}}initConfig(e){try{e.featureAllowList?.length||(e.featureAllowList=Object.values(Re)),this.baseFeatureAllowList=e.featureAllowList?.slice(),this.config$.next(e)}catch(i){this.loggingService.catch("Error in ConfigService initConfig: ",i)}}setApiKey(e){this.apiKey$.next(e)}getApiKey(){return this.apiKey$.value}getApiKey$(){return this.apiKey$.asObservable()}getConfig(){return this.config$.value}getConfig$(){return this.config$.asObservable()}disableFeatures(e){try{let i=this.config$.value;i&&(e?.length?i.featureAllowList=this.baseFeatureAllowList.filter(r=>!e.includes(r)):i.featureAllowList=this.baseFeatureAllowList.slice()),this.config$.next(i)}catch(i){this.loggingService.catch("Error in ConfigService disableFeatures: ",i)}}setSF(e){try{this.sf$.next(e),this.analyticsService.setSF(e)}catch(i){this.loggingService.catch("Error in ConfigService setSF: ",i)}}getSF(){try{return this.sf$.value}catch(e){return this.loggingService.catch("Error in ConfigService getSF: ",e),!1}}getSF$(){try{return this.sf$.asObservable()}catch(e){return this.loggingService.catch("Error in ConfigService getSF$: ",e),re(!1)}}setSdkType(e){try{this.sdkType$.next(e)}catch(i){this.loggingService.catch("Error in ConfigService setSdkType: ",i)}}getSdkType(){try{return this.sdkType$.value}catch(e){return this.loggingService.catch("Error in ConfigService getSdkType: ",e),"core"}}getSdkType$(){try{return this.sdkType$.asObservable()}catch(e){return this.loggingService.catch("Error in ConfigService getSdkType$: ",e),re("core")}}enableLogs(){try{if(this.logsEnabled$.value===!0)return;this.logsEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in ConfigService enableLogs: ",e)}}disableLogs(e){try{e&&this.disableLogsConfig$.next({warnings:e.warnings??!0,suppressAll:e.suppressAll??!1}),e?.warnings!==!1&&this.logsEnabled$.next(!1)}catch(i){this.loggingService.catch("Error in ConfigService disableLogs: ",i)}}getDisableLogsConfig(){return this.disableLogsConfig$.value}getDisableLogsConfig$(){return this.disableLogsConfig$.asObservable()}};o.\u0275fac=function(i){return new(i||o)(J(y),J(Qe))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var zae=(()=>{let o=class o{constructor(e){this.loggingService=e,this.initLocalStorageData()}initLocalStorageData(){this.loggingService.log("%c[WB] Calling FUNCTION: initLocalStorageData","color: green;"),this.getLocalStorageData(),this.getSessionStorageData()}getLocalStorageData(){this.loggingService.log("%c[WB] Calling FUNCTION: getLocalStorageData","color: green;");try{let e=localStorage?.getItem(U.LOCALSTORAGE_DATA_ID);if(e)return JSON.parse(e);{let i=new zu;return this.setLocalStorageData(i),i}}catch(e){return this.loggingService.catch("Error in getLocalStorageData:",e),new zu}}setLocalStorageData(e){this.loggingService.log("%c[WB] Calling FUNCTION: setLocalStorageData","color: green;");try{if(e){let i=JSON.stringify(e);localStorage?.setItem(U.LOCALSTORAGE_DATA_ID,i)}}catch(i){this.loggingService.catch("Error in setLocalStorageData:",i)}}deleteLocalStorageData(){this.loggingService.log("%c[WB] Calling FUNCTION: deleteLocalStorageData","color: green;"),localStorage?.removeItem(U.LOCALSTORAGE_DATA_ID)}getSessionStorageData(){this.loggingService.log("%c[WB] Calling FUNCTION: getSessionStorageData","color: green;");try{let e=sessionStorage?.getItem(U.LOCALSTORAGE_DATA_ID);if(e)return JSON.parse(e);{let i=new zu;return this.setSessionStorageData(i),i}}catch(e){return this.loggingService.catch("Error in getSessionStorageData:",e),new zu}}setSessionStorageData(e){this.loggingService.log("%c[WB] Calling FUNCTION: setSessionStorageData","color: green;");try{if(e){let i=JSON.stringify(e);sessionStorage?.setItem(U.LOCALSTORAGE_DATA_ID,i)}}catch(i){this.loggingService.catch("Error in setSessionStorageData:",i)}}deleteSessionStorageData(){this.loggingService.log("%c[WB] Calling FUNCTION: deleteSessionStorageData","color: green;");try{sessionStorage?.removeItem(U.LOCALSTORAGE_DATA_ID)}catch(e){this.loggingService.catch("Error in deleteSessionStorageData:",e)}}};o.\u0275fac=function(i){return new(i||o)(J(y))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var gm=(()=>{let o=class o{constructor(e,i){this.localStorageService=e,this.loggingService=i,this.avatarList=[{userId:"1",name:"Bear",photoUrl:"https://snippyly.com/assets/avatars/avatar-bear.svg",type:"anonymous"},{userId:"2",name:"Beaver",photoUrl:"https://snippyly.com/assets/avatars/avatar-beaver.svg",type:"anonymous"},{userId:"3",name:"Bunny",photoUrl:"https://snippyly.com/assets/avatars/avatar-bunny.svg",type:"anonymous"},{userId:"4",name:"Cat",photoUrl:"https://snippyly.com/assets/avatars/avatar-cat.svg",type:"anonymous"},{userId:"5",name:"Cow",photoUrl:"https://snippyly.com/assets/avatars/avatar-cow.svg",type:"anonymous"},{userId:"6",name:"Dinosaur",photoUrl:"https://snippyly.com/assets/avatars/avatar-dinosaur.svg",type:"anonymous"},{userId:"7",name:"Elephant",photoUrl:"https://snippyly.com/assets/avatars/avatar-elephant.svg",type:"anonymous"},{userId:"8",name:"Monkey",photoUrl:"https://snippyly.com/assets/avatars/avatar-monkey.svg",type:"anonymous"},{userId:"9",name:"Hedgehog",photoUrl:"https://snippyly.com/assets/avatars/avatar-hedgehog.svg",type:"anonymous"},{userId:"10",name:"Hippo",photoUrl:"https://snippyly.com/assets/avatars/avatar-hippo.svg",type:"anonymous"},{userId:"11",name:"Horse",photoUrl:"https://snippyly.com/assets/avatars/avatar-horse.svg",type:"anonymous"},{userId:"12",name:"Kitten",photoUrl:"https://snippyly.com/assets/avatars/avatar-kitten.svg",type:"anonymous"},{userId:"13",name:"Octopus",photoUrl:"https://snippyly.com/assets/avatars/avatar-octopus.svg",type:"anonymous"},{userId:"14",name:"Oink",photoUrl:"https://snippyly.com/assets/avatars/avatar-oink.svg",type:"anonymous"},{userId:"15",name:"Panda",photoUrl:"https://snippyly.com/assets/avatars/avatar-panda.svg",type:"anonymous"},{userId:"16",name:"Penguin",photoUrl:"https://snippyly.com/assets/avatars/avatar-penguin.svg",type:"anonymous"},{userId:"17",name:"Rabbit",photoUrl:"https://snippyly.com/assets/avatars/avatar-rabbit.svg",type:"anonymous"},{userId:"18",name:"Tiger",photoUrl:"https://snippyly.com/assets/avatars/avatar-tiger.svg",type:"anonymous"}],this.loggingService.log("%c[WB] Creating SERVICE AvatarService","color: blue;")}getSessionAvatar(){this.loggingService.log("%c[WB] Calling FUNCTION: getSessionAvatar","color: green;");try{let e=new wo,i=this.localStorageService.getSessionStorageData();if(i.snippylyAvatar)e=i.snippylyAvatar;else{let r=this.generateUserAvatar();i.snippylyAvatar=r,this.localStorageService.setSessionStorageData(i)}return e}catch(e){return this.loggingService.catch("Error in getSessionAvatar:",e),new wo}}generateUserAvatar(){this.loggingService.log("%c[WB] Calling FUNCTION: generateUserAvatar","color: green;");try{let e=Math.floor(Math.random()*this.avatarList.length),i=this.avatarList[e];return i.color=this.generateUserColor(),i}catch(e){return this.loggingService.catch("Error in generateUserAvatar:",e),this.avatarList[0]}}generateUserColor(e){this.loggingService.log("%c[WB] Calling FUNCTION: generateUserColor","color: green;");try{if(e)return U.AVATAR_COLOR_LIST[e%U.AVATAR_COLOR_LIST.length];let i=Math.floor(Math.random()*U.AVATAR_COLOR_LIST.length);return U.AVATAR_COLOR_LIST[i]}catch(i){return this.loggingService.catch("Error in generateUserColor:",i),""}}generateUserImage(){this.loggingService.log("%c[WB] Calling FUNCTION: generateUserImage","color: green;");try{return this.getSessionAvatar().photoUrl}catch(e){return this.loggingService.catch("Error in generateUserImage:",e),""}}};o.\u0275fac=function(i){return new(i||o)(J(zae),J(y))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Np=(()=>{let o=class o{constructor(e){this.loggingService=e,this.actionSubjects=new Map,this.subscriptions=[]}triggerAction(e,i){try{this.actionSubjects.has(e)||this.actionSubjects.set(e,new et),this.actionSubjects.get(e)?.next(i)}catch(r){this.loggingService.catch("Error in CoreActionsService triggerAction: ",r)}}onAction(e){try{return this.actionSubjects.has(e)||this.actionSubjects.set(e,new et),this.actionSubjects.get(e)?.asObservable()}catch(i){return this.loggingService.catch("Error in CoreActionsService onAction: ",i),re(null)}}};o.\u0275fac=function(i){return new(i||o)(J(y))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var{entries:ese,setPrototypeOf:Gae,isFrozen:fPe,getPrototypeOf:vPe,getOwnPropertyDescriptor:CPe}=Object,{freeze:qa,seal:_l,create:tse}=Object,{apply:r$,construct:a$}=typeof Reflect<"u"&&Reflect;qa||(qa=function(o){return o});_l||(_l=function(o){return o});r$||(r$=function(o,t,e){return o.apply(t,e)});a$||(a$=function(o,t){return new o(...t)});var _M=Ya(Array.prototype.forEach),_Pe=Ya(Array.prototype.lastIndexOf),Wae=Ya(Array.prototype.pop),US=Ya(Array.prototype.push),yPe=Ya(Array.prototype.splice),SM=Ya(String.prototype.toLowerCase),e$=Ya(String.prototype.toString),qae=Ya(String.prototype.match),jS=Ya(String.prototype.replace),SPe=Ya(String.prototype.indexOf),bPe=Ya(String.prototype.trim),gc=Ya(Object.prototype.hasOwnProperty),Wa=Ya(RegExp.prototype.test),$S=IPe(TypeError);function Ya(n){return function(o){o instanceof RegExp&&(o.lastIndex=0);for(var t=arguments.length,e=new Array(t>1?t-1:0),i=1;i<t;i++)e[i-1]=arguments[i];return r$(n,o,e)}}function IPe(n){return function(){for(var o=arguments.length,t=new Array(o),e=0;e<o;e++)t[e]=arguments[e];return a$(n,t)}}function ti(n,o){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:SM;Gae&&Gae(n,null);let e=o.length;for(;e--;){let i=o[e];if(typeof i=="string"){let r=t(i);r!==i&&(fPe(o)||(o[e]=r),i=r)}n[i]=!0}return n}function EPe(n){for(let o=0;o<n.length;o++)gc(n,o)||(n[o]=null);return n}function Gu(n){let o=tse(null);for(let[t,e]of ese(n))gc(n,t)&&(Array.isArray(e)?o[t]=EPe(e):e&&typeof e=="object"&&e.constructor===Object?o[t]=Gu(e):o[t]=e);return o}function HS(n,o){for(;n!==null;){let e=CPe(n,o);if(e){if(e.get)return Ya(e.get);if(typeof e.value=="function")return Ya(e.value)}n=vPe(n)}function t(){return null}return t}var Yae=qa(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","section","select","shadow","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),t$=qa(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","filter","font","g","glyph","glyphref","hkern","image","line","lineargradient","marker","mask","metadata","mpath","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),n$=qa(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),xPe=qa(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),i$=qa(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),TPe=qa(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),Kae=qa(["#text"]),Zae=qa(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","face","for","headers","height","hidden","high","href","hreflang","id","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns","slot"]),o$=qa(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),Xae=qa(["accent","accentunder","align","bevelled","close","columnsalign","columnlines","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lspace","lquote","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),yM=qa(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),wPe=_l(/\{\{[\w\W]*|[\w\W]*\}\}/gm),DPe=_l(/<%[\w\W]*|[\w\W]*%>/gm),APe=_l(/\$\{[\w\W]*/gm),OPe=_l(/^data-[\-\w.\u00B7-\uFFFF]+$/),MPe=_l(/^aria-[\-\w]+$/),nse=_l(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),PPe=_l(/^(?:\w+script|data):/i),kPe=_l(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),ise=_l(/^html$/i),RPe=_l(/^[a-z][.\w]*(-[.\w]+)+$/i),Qae=Object.freeze({__proto__:null,ARIA_ATTR:MPe,ATTR_WHITESPACE:kPe,CUSTOM_ELEMENT:RPe,DATA_ATTR:OPe,DOCTYPE_NAME:ise,ERB_EXPR:DPe,IS_ALLOWED_URI:nse,IS_SCRIPT_OR_DATA:PPe,MUSTACHE_EXPR:wPe,TMPLIT_EXPR:APe}),zS={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,progressingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},NPe=function(){return typeof window>"u"?null:window},FPe=function(o,t){if(typeof o!="object"||typeof o.createPolicy!="function")return null;let e=null,i="data-tt-policy-suffix";t&&t.hasAttribute(i)&&(e=t.getAttribute(i));let r="dompurify"+(e?"#"+e:"");try{return o.createPolicy(r,{createHTML(a){return a},createScriptURL(a){return a}})}catch{return console.warn("TrustedTypes policy "+r+" could not be created."),null}},Jae=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function ose(){let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:NPe(),o=Yt=>ose(Yt);if(o.version="3.2.5",o.removed=[],!n||!n.document||n.document.nodeType!==zS.document||!n.Element)return o.isSupported=!1,o;let{document:t}=n,e=t,i=e.currentScript,{DocumentFragment:r,HTMLTemplateElement:a,Node:s,Element:c,NodeFilter:p,NamedNodeMap:h=n.NamedNodeMap||n.MozNamedAttrMap,HTMLFormElement:_,DOMParser:E,trustedTypes:D}=n,B=c.prototype,G=HS(B,"cloneNode"),X=HS(B,"remove"),he=HS(B,"nextSibling"),Ie=HS(B,"childNodes"),Me=HS(B,"parentNode");if(typeof a=="function"){let Yt=t.createElement("template");Yt.content&&Yt.content.ownerDocument&&(t=Yt.content.ownerDocument)}let Le,We="",{implementation:ke,createNodeIterator:we,createDocumentFragment:Ee,getElementsByTagName:Pe}=t,{importNode:Ce}=e,ue=Jae();o.isSupported=typeof ese=="function"&&typeof Me=="function"&&ke&&ke.createHTMLDocument!==void 0;let{MUSTACHE_EXPR:Be,ERB_EXPR:Se,TMPLIT_EXPR:Ut,DATA_ATTR:Gt,ARIA_ATTR:Dt,IS_SCRIPT_OR_DATA:It,ATTR_WHITESPACE:Nt,CUSTOM_ELEMENT:Fn}=Qae,{IS_ALLOWED_URI:eo}=Qae,ii=null,Oi=ti({},[...Yae,...t$,...n$,...i$,...Kae]),dn=null,ui=ti({},[...Zae,...o$,...Xae,...yM]),Mi=Object.seal(tse(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),Am=null,go=null,Ws=!0,Br=!0,qs=!1,wl=!0,_c=!1,og=!0,Dl=!1,rg=!1,oh=!1,Om=!1,rh=!1,ag=!1,WC=!0,ah=!1,dw="user-content-",qC=!0,Mm=!1,yc={},Sc=null,Er=ti({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]),Vr=null,sg=ti({},["audio","video","img","source","image","track"]),sh=null,YC=ti({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),lh="http://www.w3.org/1998/Math/MathML",bc="http://www.w3.org/2000/svg",Ys="http://www.w3.org/1999/xhtml",Pm=Ys,lg=!1,KC=null,l9=ti({},[lh,bc,Ys],e$),Ad=ti({},["mi","mo","mn","ms","mtext"]),cg=ti({},["annotation-xml"]),pw=ti({},["title","style","font","a","script"]),Al=null,ZC=["application/xhtml+xml","text/html"],XC="text/html",uo=null,km=null,ch=t.createElement("form"),QC=function(Ve){return Ve instanceof RegExp||Ve instanceof Function},Rm=function(){let Ve=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(km&&km===Ve)){if((!Ve||typeof Ve!="object")&&(Ve={}),Ve=Gu(Ve),Al=ZC.indexOf(Ve.PARSER_MEDIA_TYPE)===-1?XC:Ve.PARSER_MEDIA_TYPE,uo=Al==="application/xhtml+xml"?e$:SM,ii=gc(Ve,"ALLOWED_TAGS")?ti({},Ve.ALLOWED_TAGS,uo):Oi,dn=gc(Ve,"ALLOWED_ATTR")?ti({},Ve.ALLOWED_ATTR,uo):ui,KC=gc(Ve,"ALLOWED_NAMESPACES")?ti({},Ve.ALLOWED_NAMESPACES,e$):l9,sh=gc(Ve,"ADD_URI_SAFE_ATTR")?ti(Gu(YC),Ve.ADD_URI_SAFE_ATTR,uo):YC,Vr=gc(Ve,"ADD_DATA_URI_TAGS")?ti(Gu(sg),Ve.ADD_DATA_URI_TAGS,uo):sg,Sc=gc(Ve,"FORBID_CONTENTS")?ti({},Ve.FORBID_CONTENTS,uo):Er,Am=gc(Ve,"FORBID_TAGS")?ti({},Ve.FORBID_TAGS,uo):{},go=gc(Ve,"FORBID_ATTR")?ti({},Ve.FORBID_ATTR,uo):{},yc=gc(Ve,"USE_PROFILES")?Ve.USE_PROFILES:!1,Ws=Ve.ALLOW_ARIA_ATTR!==!1,Br=Ve.ALLOW_DATA_ATTR!==!1,qs=Ve.ALLOW_UNKNOWN_PROTOCOLS||!1,wl=Ve.ALLOW_SELF_CLOSE_IN_ATTR!==!1,_c=Ve.SAFE_FOR_TEMPLATES||!1,og=Ve.SAFE_FOR_XML!==!1,Dl=Ve.WHOLE_DOCUMENT||!1,Om=Ve.RETURN_DOM||!1,rh=Ve.RETURN_DOM_FRAGMENT||!1,ag=Ve.RETURN_TRUSTED_TYPE||!1,oh=Ve.FORCE_BODY||!1,WC=Ve.SANITIZE_DOM!==!1,ah=Ve.SANITIZE_NAMED_PROPS||!1,qC=Ve.KEEP_CONTENT!==!1,Mm=Ve.IN_PLACE||!1,eo=Ve.ALLOWED_URI_REGEXP||nse,Pm=Ve.NAMESPACE||Ys,Ad=Ve.MATHML_TEXT_INTEGRATION_POINTS||Ad,cg=Ve.HTML_INTEGRATION_POINTS||cg,Mi=Ve.CUSTOM_ELEMENT_HANDLING||{},Ve.CUSTOM_ELEMENT_HANDLING&&QC(Ve.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(Mi.tagNameCheck=Ve.CUSTOM_ELEMENT_HANDLING.tagNameCheck),Ve.CUSTOM_ELEMENT_HANDLING&&QC(Ve.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(Mi.attributeNameCheck=Ve.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),Ve.CUSTOM_ELEMENT_HANDLING&&typeof Ve.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(Mi.allowCustomizedBuiltInElements=Ve.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),_c&&(Br=!1),rh&&(Om=!0),yc&&(ii=ti({},Kae),dn=[],yc.html===!0&&(ti(ii,Yae),ti(dn,Zae)),yc.svg===!0&&(ti(ii,t$),ti(dn,o$),ti(dn,yM)),yc.svgFilters===!0&&(ti(ii,n$),ti(dn,o$),ti(dn,yM)),yc.mathMl===!0&&(ti(ii,i$),ti(dn,Xae),ti(dn,yM))),Ve.ADD_TAGS&&(ii===Oi&&(ii=Gu(ii)),ti(ii,Ve.ADD_TAGS,uo)),Ve.ADD_ATTR&&(dn===ui&&(dn=Gu(dn)),ti(dn,Ve.ADD_ATTR,uo)),Ve.ADD_URI_SAFE_ATTR&&ti(sh,Ve.ADD_URI_SAFE_ATTR,uo),Ve.FORBID_CONTENTS&&(Sc===Er&&(Sc=Gu(Sc)),ti(Sc,Ve.FORBID_CONTENTS,uo)),qC&&(ii["#text"]=!0),Dl&&ti(ii,["html","head","body"]),ii.table&&(ti(ii,["tbody"]),delete Am.tbody),Ve.TRUSTED_TYPES_POLICY){if(typeof Ve.TRUSTED_TYPES_POLICY.createHTML!="function")throw $S('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof Ve.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw $S('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');Le=Ve.TRUSTED_TYPES_POLICY,We=Le.createHTML("")}else Le===void 0&&(Le=FPe(D,i)),Le!==null&&typeof We=="string"&&(We=Le.createHTML(""));qa&&qa(Ve),km=Ve}},JC=ti({},[...t$,...n$,...xPe]),Ur=ti({},[...i$,...TPe]),gw=function(Ve){let yt=Me(Ve);(!yt||!yt.tagName)&&(yt={namespaceURI:Pm,tagName:"template"});let Wt=SM(Ve.tagName),to=SM(yt.tagName);return KC[Ve.namespaceURI]?Ve.namespaceURI===bc?yt.namespaceURI===Ys?Wt==="svg":yt.namespaceURI===lh?Wt==="svg"&&(to==="annotation-xml"||Ad[to]):!!JC[Wt]:Ve.namespaceURI===lh?yt.namespaceURI===Ys?Wt==="math":yt.namespaceURI===bc?Wt==="math"&&cg[to]:!!Ur[Wt]:Ve.namespaceURI===Ys?yt.namespaceURI===bc&&!cg[to]||yt.namespaceURI===lh&&!Ad[to]?!1:!Ur[Wt]&&(pw[Wt]||!JC[Wt]):!!(Al==="application/xhtml+xml"&&KC[Ve.namespaceURI]):!1},pa=function(Ve){US(o.removed,{element:Ve});try{Me(Ve).removeChild(Ve)}catch{X(Ve)}},Ic=function(Ve,yt){try{US(o.removed,{attribute:yt.getAttributeNode(Ve),from:yt})}catch{US(o.removed,{attribute:null,from:yt})}if(yt.removeAttribute(Ve),Ve==="is")if(Om||rh)try{pa(yt)}catch{}else try{yt.setAttribute(Ve,"")}catch{}},uw=function(Ve){let yt=null,Wt=null;if(oh)Ve="<remove></remove>"+Ve;else{let Tr=qae(Ve,/^[\r\n\t ]+/);Wt=Tr&&Tr[0]}Al==="application/xhtml+xml"&&Pm===Ys&&(Ve='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+Ve+"</body></html>");let to=Le?Le.createHTML(Ve):Ve;if(Pm===Ys)try{yt=new E().parseFromString(to,Al)}catch{}if(!yt||!yt.documentElement){yt=ke.createDocument(Pm,"template",null);try{yt.documentElement.innerHTML=lg?We:to}catch{}}let xr=yt.body||yt.documentElement;return Ve&&Wt&&xr.insertBefore(t.createTextNode(Wt),xr.childNodes[0]||null),Pm===Ys?Pe.call(yt,Dl?"html":"body")[0]:Dl?yt.documentElement:xr},hw=function(Ve){return we.call(Ve.ownerDocument||Ve,Ve,p.SHOW_ELEMENT|p.SHOW_COMMENT|p.SHOW_TEXT|p.SHOW_PROCESSING_INSTRUCTION|p.SHOW_CDATA_SECTION,null)},Ec=function(Ve){return Ve instanceof _&&(typeof Ve.nodeName!="string"||typeof Ve.textContent!="string"||typeof Ve.removeChild!="function"||!(Ve.attributes instanceof h)||typeof Ve.removeAttribute!="function"||typeof Ve.setAttribute!="function"||typeof Ve.namespaceURI!="string"||typeof Ve.insertBefore!="function"||typeof Ve.hasChildNodes!="function")},fw=function(Ve){return typeof s=="function"&&Ve instanceof s};function Ol(Yt,Ve,yt){_M(Yt,Wt=>{Wt.call(o,Ve,yt,km)})}let mg=function(Ve){let yt=null;if(Ol(ue.beforeSanitizeElements,Ve,null),Ec(Ve))return pa(Ve),!0;let Wt=uo(Ve.nodeName);if(Ol(ue.uponSanitizeElement,Ve,{tagName:Wt,allowedTags:ii}),Ve.hasChildNodes()&&!fw(Ve.firstElementChild)&&Wa(/<[/\w!]/g,Ve.innerHTML)&&Wa(/<[/\w!]/g,Ve.textContent)||Ve.nodeType===zS.progressingInstruction||og&&Ve.nodeType===zS.comment&&Wa(/<[/\w]/g,Ve.data))return pa(Ve),!0;if(!ii[Wt]||Am[Wt]){if(!Am[Wt]&&mh(Wt)&&(Mi.tagNameCheck instanceof RegExp&&Wa(Mi.tagNameCheck,Wt)||Mi.tagNameCheck instanceof Function&&Mi.tagNameCheck(Wt)))return!1;if(qC&&!Sc[Wt]){let to=Me(Ve)||Ve.parentNode,xr=Ie(Ve)||Ve.childNodes;if(xr&&to){let Tr=xr.length;for(let wr=Tr-1;wr>=0;--wr){let Is=G(xr[wr],!0);Is.__removalCount=(Ve.__removalCount||0)+1,to.insertBefore(Is,he(Ve))}}}return pa(Ve),!0}return Ve instanceof c&&!gw(Ve)||(Wt==="noscript"||Wt==="noembed"||Wt==="noframes")&&Wa(/<\/no(script|embed|frames)/i,Ve.innerHTML)?(pa(Ve),!0):(_c&&Ve.nodeType===zS.text&&(yt=Ve.textContent,_M([Be,Se,Ut],to=>{yt=jS(yt,to," ")}),Ve.textContent!==yt&&(US(o.removed,{element:Ve.cloneNode()}),Ve.textContent=yt)),Ol(ue.afterSanitizeElements,Ve,null),!1)},e_=function(Ve,yt,Wt){if(WC&&(yt==="id"||yt==="name")&&(Wt in t||Wt in ch))return!1;if(!(Br&&!go[yt]&&Wa(Gt,yt))){if(!(Ws&&Wa(Dt,yt))){if(!dn[yt]||go[yt]){if(!(mh(Ve)&&(Mi.tagNameCheck instanceof RegExp&&Wa(Mi.tagNameCheck,Ve)||Mi.tagNameCheck instanceof Function&&Mi.tagNameCheck(Ve))&&(Mi.attributeNameCheck instanceof RegExp&&Wa(Mi.attributeNameCheck,yt)||Mi.attributeNameCheck instanceof Function&&Mi.attributeNameCheck(yt))||yt==="is"&&Mi.allowCustomizedBuiltInElements&&(Mi.tagNameCheck instanceof RegExp&&Wa(Mi.tagNameCheck,Wt)||Mi.tagNameCheck instanceof Function&&Mi.tagNameCheck(Wt))))return!1}else if(!sh[yt]){if(!Wa(eo,jS(Wt,Nt,""))){if(!((yt==="src"||yt==="xlink:href"||yt==="href")&&Ve!=="script"&&SPe(Wt,"data:")===0&&Vr[Ve])){if(!(qs&&!Wa(It,jS(Wt,Nt,"")))){if(Wt)return!1}}}}}}return!0},mh=function(Ve){return Ve!=="annotation-xml"&&qae(Ve,Fn)},dg=function(Ve){Ol(ue.beforeSanitizeAttributes,Ve,null);let{attributes:yt}=Ve;if(!yt||Ec(Ve))return;let Wt={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:dn,forceKeepAttr:void 0},to=yt.length;for(;to--;){let xr=yt[to],{name:Tr,namespaceURI:wr,value:Is}=xr,Nm=uo(Tr),ir=Tr==="value"?Is:bPe(Is);if(Wt.attrName=Nm,Wt.attrValue=ir,Wt.keepAttr=!0,Wt.forceKeepAttr=void 0,Ol(ue.uponSanitizeAttribute,Ve,Wt),ir=Wt.attrValue,ah&&(Nm==="id"||Nm==="name")&&(Ic(Tr,Ve),ir=dw+ir),og&&Wa(/((--!?|])>)|<\/(style|title)/i,ir)){Ic(Tr,Ve);continue}if(Wt.forceKeepAttr||(Ic(Tr,Ve),!Wt.keepAttr))continue;if(!wl&&Wa(/\/>/i,ir)){Ic(Tr,Ve);continue}_c&&_M([Be,Se,Ut],dh=>{ir=jS(ir,dh," ")});let Tc=uo(Ve.nodeName);if(e_(Tc,Nm,ir)){if(Le&&typeof D=="object"&&typeof D.getAttributeType=="function"&&!wr)switch(D.getAttributeType(Tc,Nm)){case"TrustedHTML":{ir=Le.createHTML(ir);break}case"TrustedScriptURL":{ir=Le.createScriptURL(ir);break}}try{wr?Ve.setAttributeNS(wr,Tr,ir):Ve.setAttribute(Tr,ir),Ec(Ve)?pa(Ve):Wae(o.removed)}catch{}}}Ol(ue.afterSanitizeAttributes,Ve,null)},xc=function Yt(Ve){let yt=null,Wt=hw(Ve);for(Ol(ue.beforeSanitizeShadowDOM,Ve,null);yt=Wt.nextNode();)Ol(ue.uponSanitizeShadowNode,yt,null),mg(yt),dg(yt),yt.content instanceof r&&Yt(yt.content);Ol(ue.afterSanitizeShadowDOM,Ve,null)};return o.sanitize=function(Yt){let Ve=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},yt=null,Wt=null,to=null,xr=null;if(lg=!Yt,lg&&(Yt="<!-->"),typeof Yt!="string"&&!fw(Yt))if(typeof Yt.toString=="function"){if(Yt=Yt.toString(),typeof Yt!="string")throw $S("dirty is not a string, aborting")}else throw $S("toString is not a function");if(!o.isSupported)return Yt;if(rg||Rm(Ve),o.removed=[],typeof Yt=="string"&&(Mm=!1),Mm){if(Yt.nodeName){let Is=uo(Yt.nodeName);if(!ii[Is]||Am[Is])throw $S("root node is forbidden and cannot be sanitized in-place")}}else if(Yt instanceof s)yt=uw("<!---->"),Wt=yt.ownerDocument.importNode(Yt,!0),Wt.nodeType===zS.element&&Wt.nodeName==="BODY"||Wt.nodeName==="HTML"?yt=Wt:yt.appendChild(Wt);else{if(!Om&&!_c&&!Dl&&Yt.indexOf("<")===-1)return Le&&ag?Le.createHTML(Yt):Yt;if(yt=uw(Yt),!yt)return Om?null:ag?We:""}yt&&oh&&pa(yt.firstChild);let Tr=hw(Mm?Yt:yt);for(;to=Tr.nextNode();)mg(to),dg(to),to.content instanceof r&&xc(to.content);if(Mm)return Yt;if(Om){if(rh)for(xr=Ee.call(yt.ownerDocument);yt.firstChild;)xr.appendChild(yt.firstChild);else xr=yt;return(dn.shadowroot||dn.shadowrootmode)&&(xr=Ce.call(e,xr,!0)),xr}let wr=Dl?yt.outerHTML:yt.innerHTML;return Dl&&ii["!doctype"]&&yt.ownerDocument&&yt.ownerDocument.doctype&&yt.ownerDocument.doctype.name&&Wa(ise,yt.ownerDocument.doctype.name)&&(wr="<!DOCTYPE "+yt.ownerDocument.doctype.name+`>
|
|
195
|
-
`+wr),_c&&_M([Be,Se,Ut],Is=>{wr=jS(wr,Is," ")}),Le&&ag?Le.createHTML(wr):wr},o.setConfig=function(){let Yt=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Rm(Yt),rg=!0},o.clearConfig=function(){km=null,rg=!1},o.isValidAttribute=function(Yt,Ve,yt){km||Rm({});let Wt=uo(Yt),to=uo(Ve);return e_(Wt,to,yt)},o.addHook=function(Yt,Ve){typeof Ve=="function"&&US(ue[Yt],Ve)},o.removeHook=function(Yt,Ve){if(Ve!==void 0){let yt=_Pe(ue[Yt],Ve);return yt===-1?void 0:yPe(ue[Yt],yt,1)[0]}return Wae(ue[Yt])},o.removeHooks=function(Yt){ue[Yt]=[]},o.removeAllHooks=function(){ue=Jae()},o}var s$=ose();var rse={ADD_TAGS:["velt-skeleton-loader"],ADD_ATTR:["border-radius"]},Fe=(()=>{let o=class o{constructor(e,i,r){this.rendererFactory2=e,this.loggingService=i,this.sanitizer=r,this.isVideoEditorHandlingDelete=!1,this.pageScrollHeight=0,this.enableRectSelectionSubject$=new fe(!1),this.enableRectSelection$=this.enableRectSelectionSubject$.asObservable(),this.scrollableElementsIds$=new fe([]),this.mousedown=!1,this.windowMouseDown$=new et,this.windowPointerMove$=new fe(null),this.windowPointerUp$=new fe(null),this.documentSelectionChange$=new fe(null),this.windowClick$=new fe(null),this.windowScroll$=new fe(null),this.windowResize$=new fe(null),this.windowKeyupBackspace$=new fe(null),this.windowKeyupDelete$=new fe(null),this.windowKeyupEsc$=new fe(null),this.windowPopState$=new fe(null),this.documentClick$=new fe(null),this.documentClickSubject$=new et,this.documentFocus$=new fe(null),this.windowKeydownShift$=new fe(null),this.windowKeyupShift$=new fe(null),this.mutation$=new fe(null),this.childListMutation$=new fe(null),this.networkStatus$=new fe(!1),this.xpathCache=new Map,this.xpathCacheId=new Map,this.selectedAnnotationsMap$=new fe({}),this.selectedAnnotationsLocationMap$=new fe({}),this.recordingInProgress$=new fe({}),this.deleteAnnotations$=new fe([]),this.pinHighlighterClass$=new fe(null),this.dialogOpenedInSidebar$=new fe(!1),this.textHighlighterClass$=new fe(null),this.commentPinHighlighter$=new fe(!1),this.deviceInfo$=new fe(new Jn),this.customCss$=new fe(null),this.mutationObserver=null,this.previousMousePosition={pageX:0,pageY:0,clientX:0,clientY:0},this.currentMousePosition={pageX:0,pageY:0,clientX:0,clientY:0,element:{xpath:"",topPercentage:0,leftPercentage:0}},this.nodeMap={},this.unlistenElementScroll={},this.filterSnippylyNodes=a=>{try{let s=[];return a.forEach(c=>{if(!ji(c))if(c instanceof HTMLElement){if(c.className.includes("cdk-overlay-container")||c.className.includes("cdk-overlay-connected-position-bounding-box"))return;if(c.className.includes("cdk-overlay")){let p=!1;c.childNodes.forEach(h=>{ji(h)&&(p=!0)}),p||s.push(c)}else s.push(c)}else s.push(c)}),s}catch(s){return this.loggingService.catch("Error in DomService filterSnippylyNodes: ",s),[]}},this.loggingService.log("%c[WB] Creating CLASS: DomService","color: blue;");try{this.renderer=this.rendererFactory2.createRenderer(null,null);let a=this.calculateScreenSize();this.currentScreenSize$=new fe(a),this.currentMousePosition$=new fe(this.currentMousePosition),this.detectNetworkStatusChange(),this.getScrollableElementsIds$().pipe(Vi(),In(([s,c])=>{try{let p=c.filter(_=>!s.includes(_)),h=s.filter(_=>!c.includes(_));h.length&&h.map(E=>document.getElementById(E)).filter(E=>E).forEach(E=>{this.unlistenElementScroll&&this.unlistenElementScroll[E.id]&&this.unlistenElementScroll[E.id]()}),p.length&&p.map(E=>document.getElementById(E)).filter(E=>E).forEach(E=>{this.unlistenElementScroll[E.id]=this.renderer.listen(E,"scroll",D=>{let B=this.calculateScreenSize();this.currentScreenSize$.next(B)})})}catch(p){this.loggingService.catch("Error in DomService getScrollableElementsIds subscription: ",p)}})).subscribe(()=>{},s=>{this.loggingService.catch("Error in DomService getScrollableElementsIds subscription: ",s)}),this.getSelectedAnnotationsMap$().subscribe(s=>{Object.keys(s||{})?.length?Hie("snippylyUserScalableNo","viewport","width=device-width, user-scalable=no"):zie("snippylyUserScalableNo")},s=>{this.loggingService.catch("Error in DomService getSelectedAnnotationsMap$ subscription: ",s)})}catch(a){this.loggingService.catch("Error in DomService constructor: ",a)}}setDocService(e){try{this.docService=e,this.subscribeToDomEvents()}catch(i){this.loggingService.catch("Error in DomService setDocService: ",i)}}subscribeToDomEvents(){try{this.docService?.getDocumentPaths$().pipe(ce(e=>{e?(this.onWindowResize(),this.onWindowScroll(),this.onPointerDown(),this.onWindowClick(),this.onWindowKeyupBackspace(),this.onWindowKeyupDelete(),this.onWindowKeyupEsc(),this.onWindowPopState(),this.onWindowKeydownShift(),this.onWindowKeyupShift(),this.addPointerMoveListener(),this.addPointerUpListener(),this.addSelectionChangeListener(),this.onDocumentClick(),this.onDocumentFocus()):(this.unsubscribeFromWindowResize(),this.unsubscribeFromWindowScroll(),this.unsubscribeFromPointerDown(),this.unsubscribeFromWindowClick(),this.unsubscribeFromWindowKeyupBackspace(),this.unsubscribeFromWindowKeyupDelete(),this.unsubscribeFromWindowKeyupEsc(),this.unsubscribeFromWindowPopState(),this.unsubscribeFromWindowKeydownShift(),this.unsubscribeFromWindowKeyupShift(),this.unsubscribeFromPointerMoveListener(),this.unsubscribeFromPointerUpListener(),this.unsubscribeFromSelectionChangeListener(),this.unsubscribeFromDocumentClick(),this.unsubscribeFromDocumentFocus(),this.unsetMutationObserver())})).subscribe()}catch(e){this.loggingService.catch("Error in DomService subscribeToDomEvents: ",e)}}setScrollableElementsIds(e){try{e&&e.length&&this.scrollableElementsIds$.next(Array.from(new Set(e)))}catch(i){this.loggingService.catch("Error in DomService setScrollableElementsIds: ",i)}}getScrollableElementsIds$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getScrollableElementsIds$","color: green;"),this.scrollableElementsIds$.asObservable()}removeScrollableElementsIds(){this.scrollableElementsIds$.next([])}setMutationObserver(e){try{this.mutationObserver||(this.loggingService.log("%c[WB] Calling DomService FUNCTION: setMutationObserver","color: green;"),this.loggingService.log("%c[WB] setMutationObserver from: "+e,"color: green;"),this.mutationObserver=new MutationObserver(i=>{try{if(i?.find(a=>a?.attributeName===U.VELT_IGNORE_CHANGE_DETECTION))return;let r=i.filter(a=>a.type==="childList").filter(a=>{let s=a.target;return a.removedNodes.forEach(c=>{let p=c;if(typeof p.getAttribute=="function"){let h=p.getAttribute(U.ATTRIBUTES.VELT_ELEMENT_CACHE_ID);if(h!==null&&h!==""){let _=this.xpathCacheId.get(h);_!==void 0&&(this.xpathCacheId.delete(h),this.xpathCache.delete(_))}}}),ji(s)?!1:!!(this.filterSnippylyNodes(a.addedNodes).length||this.filterSnippylyNodes(a.removedNodes).length)});this.childListMutation$.next(r),r.push(...i.filter(a=>a.type==="attributes").filter(a=>!ji(a.target)).filter(a=>this.filterSnippylyNodes([a.target]).length).filter(a=>{if(a){let s=a.target;return s?.classList?.contains("snippyly-sidebar-panel")?!1:s?!s.getAttribute(U.VELT_IGNORE_CHANGE_DETECTION):!0}return!0})),r=r.filter(a=>{let s=!0;return Object.keys(U.INGNORE_MUTATION_OBSERVER_CHANGE_TAGS).forEach(c=>{a.target?.closest(c)&&(s=!1)}),s}),r=r.filter(a=>a.target&&xo(a.target)),r.length&&this.mutation$.next(r)}catch(r){this.loggingService.catch("Error in DomService change detection: ",r)}}),this.mutationObserver.observe(document.body,{childList:!0,subtree:!0,attributes:!0}))}catch(i){this.loggingService.catch("Error in DomService change detection: ",i)}}unsetMutationObserver(){try{this.mutationObserver&&(this.mutationObserver.disconnect(),this.mutationObserver=null)}catch(e){this.loggingService.catch("Error in DomService unsetMutationObserver: ",e)}}detectNetworkStatusChange(){this.loggingService.log("%c[WB] Calling FUNCTION: detectNetworkStatusChange","color: green;");try{io(oi(window,"offline").pipe(ce(()=>!1)),oi(window,"online").pipe(ce(()=>!0)),new Ft(e=>{e.next(navigator.onLine),e.complete()})).subscribe(e=>{this.networkStatus$.next(e)})}catch(e){this.loggingService.catch("Error in DomService detectNetworkStatusChange: ",e)}}onWindowResize(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowResize","color: green;");try{this.unsubscribeFromWindowResize(),this.unlistenWindowResize=this.renderer.listen("window","resize",e=>{this.windowResize$.next(e);let i=this.calculateScreenSize();this.deviceInfo$.next(new Jn),this.currentScreenSize$.next(i)})}catch(e){this.loggingService.catch("Error in DomService onWindowResize: ",e)}}unsubscribeFromWindowResize(){try{this.unlistenWindowResize&&typeof this.unlistenWindowResize=="function"&&(this.unlistenWindowResize(),this.unlistenWindowResize=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromWindowResize: ",e)}}onWindowScroll(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowScroll","color: green;");try{this.unsubscribeFromWindowScroll(),this.unlistenWindowScroll=this.renderer.listen("window","scroll",e=>{this.windowScroll$.next(e);let i=this.calculateScreenSize();this.currentScreenSize$.next(i)})}catch(e){this.loggingService.catch("Error in DomService onWindowScroll: ",e)}}unsubscribeFromWindowScroll(){try{this.unlistenWindowScroll&&typeof this.unlistenWindowScroll=="function"&&(this.unlistenWindowScroll(),this.unlistenWindowScroll=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromWindowScroll: ",e)}}onPointerDown(){this.loggingService.log("%c[WB] Calling FUNCTION: onPointerDown","color: green;");try{this.unsubscribeFromPointerDown(),this.unlistenPointerDown=this.renderer.listen("window","pointerdown",e=>{this.mousedown=!0,this.windowMouseDown$.next(e),this.setPointerPosition(e)})}catch(e){this.loggingService.catch("Error in DomService onPointerDown: ",e)}}unsubscribeFromPointerDown(){try{this.unlistenPointerDown&&typeof this.unlistenPointerDown=="function"&&(this.unlistenPointerDown(),this.unlistenPointerDown=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromPointerDown: ",e)}}onWindowClick(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowKeyupBackspace","color: green;");try{this.unsubscribeFromWindowClick(),this.unlistenWindowClick=this.renderer.listen("window","click",e=>{this.windowClick$.next(e)})}catch(e){this.loggingService.catch("Error in DomService onWindowClick: ",e)}}unsubscribeFromWindowClick(){try{this.unlistenWindowClick&&typeof this.unlistenWindowClick=="function"&&(this.unlistenWindowClick(),this.unlistenWindowClick=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromWindowClick: ",e)}}onWindowKeyupBackspace(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowKeyupBackspace","color: green;");try{this.unsubscribeFromWindowKeyupBackspace(),this.unlistenWindowKeyupBackspace=this.renderer.listen("window","keyup.backspace",e=>{this.isVideoEditorHandlingDelete||this.windowKeyupBackspace$.next(e)})}catch(e){this.loggingService.catch("Error in DomService onWindowKeyupBackspace: ",e)}}unsubscribeFromWindowKeyupBackspace(){try{this.unlistenWindowKeyupBackspace&&typeof this.unlistenWindowKeyupBackspace=="function"&&(this.unlistenWindowKeyupBackspace(),this.unlistenWindowKeyupBackspace=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromWindowKeyupBackspace: ",e)}}onWindowKeyupDelete(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowKeyupDelete","color: green;");try{this.unsubscribeFromWindowKeyupDelete(),this.unlistenWindowKeyupDelete=this.renderer.listen("window","keyup.delete",e=>{this.isVideoEditorHandlingDelete||this.windowKeyupDelete$.next(e)})}catch(e){this.loggingService.catch("Error in DomService onWindowKeyupDelete: ",e)}}unsubscribeFromWindowKeyupDelete(){try{this.unlistenWindowKeyupDelete&&typeof this.unlistenWindowKeyupDelete=="function"&&(this.unlistenWindowKeyupDelete(),this.unlistenWindowKeyupDelete=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromWindowKeyupDelete: ",e)}}onWindowKeyupEsc(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowKeyupEsc","color: green;");try{this.unsubscribeFromWindowKeyupEsc(),this.unlistenWindowKeyupEsc=this.renderer.listen("window","keyup.esc",e=>{this.windowKeyupEsc$.next(e)})}catch(e){this.loggingService.catch("Error in DomService onWindowKeyupEsc: ",e)}}unsubscribeFromWindowKeyupEsc(){try{this.unlistenWindowKeyupEsc&&typeof this.unlistenWindowKeyupEsc=="function"&&(this.unlistenWindowKeyupEsc(),this.unlistenWindowKeyupEsc=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromWindowKeyupEsc: ",e)}}onWindowPopState(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowPopState","color: green;");try{this.unsubscribeFromWindowPopState(),this.unlistenWindowPopState=this.renderer.listen("window","popstate",e=>{this.windowPopState$.next(e)})}catch(e){this.loggingService.catch("Error in DomService onWindowPopState: ",e)}}unsubscribeFromWindowPopState(){try{this.unlistenWindowPopState&&typeof this.unlistenWindowPopState=="function"&&(this.unlistenWindowPopState(),this.unlistenWindowPopState=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromWindowPopState: ",e)}}onDocumentClick(){this.loggingService.log("%c[WB] Calling FUNCTION: onDocumentClick","color: green;");try{this.unsubscribeFromDocumentClick(),this.documentClickListener=e=>{e?.target?.tagName?.toLowerCase()!==U.TAGS.SUPERFLOW_TOOLBAR&&(this.documentClick$.next(e),this.documentClickSubject$.next(e))},document.addEventListener("click",this.documentClickListener,!0)}catch(e){this.loggingService.catch("Error in DomService onDocumentClick: ",e)}}unsubscribeFromDocumentClick(){try{this.documentClickListener&&typeof this.documentClickListener=="function"&&(document.removeEventListener("click",this.documentClickListener,!0),this.documentClickListener=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromDocumentClick: ",e)}}onDocumentFocus(){this.loggingService.log("%c[WB] Calling FUNCTION: onDocumentFocus","color: green;");try{this.unsubscribeFromDocumentFocus(),this.documentFocusListener=e=>{this.documentFocus$.next(e)},document.addEventListener("focus",this.documentFocusListener,!0)}catch(e){this.loggingService.catch("Error in DomService onDocumentFocus: ",e)}}unsubscribeFromDocumentFocus(){try{this.documentFocusListener&&typeof this.documentFocusListener=="function"&&(document.removeEventListener("focus",this.documentFocusListener,!0),this.documentFocusListener=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromDocumentFocus: ",e)}}onWindowKeydownShift(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowKeydownShift","color: green;");try{this.unsubscribeFromWindowKeydownShift(),this.unlistenWindowKeydownShift=this.renderer.listen("window","keydown.shift",e=>{this.windowKeydownShift$.next(e),this.windowKeyupShift$.next(null)})}catch(e){this.loggingService.catch("Error in DomService onWindowKeydownShift: ",e)}}unsubscribeFromWindowKeydownShift(){try{this.unlistenWindowKeydownShift&&typeof this.unlistenWindowKeydownShift=="function"&&(this.unlistenWindowKeydownShift(),this.unlistenWindowKeydownShift=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromWindowKeydownShift: ",e)}}onWindowKeyupShift(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowKeyupShift","color: green;");try{this.unsubscribeFromWindowKeyupShift(),this.unlistenWindowKeyupShift=this.renderer.listen("window","keyup.shift",e=>{this.windowKeyupShift$.next(e),this.windowKeydownShift$.next(null)})}catch(e){this.loggingService.catch("Error in DomService onWindowKeyupShift: ",e)}}unsubscribeFromWindowKeyupShift(){try{this.unlistenWindowKeyupShift&&typeof this.unlistenWindowKeyupShift=="function"&&(this.unlistenWindowKeyupShift(),this.unlistenWindowKeyupShift=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromWindowKeyupShift: ",e)}}onWindowKeydown$(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowKeydown$","color: green;");try{return oi(window,"keydown")}catch(e){return this.loggingService.catch("Error in DomService onWindowKeydown$: ",e),_g}}addPointerMoveListener(){this.loggingService.log("%c[WB] Calling FUNCTION: addPointerMoveListener","color: green;");try{this.unsubscribeFromPointerMoveListener(),this.unlistenPointerMoveListener=this.renderer.listen("document","pointermove",e=>{this.windowPointerMove$.next(e),this.mouseMoveEvent=e})}catch(e){this.loggingService.catch("Error in DomService addPointerMoveListener: ",e)}}unsubscribeFromPointerMoveListener(){try{this.unlistenPointerMoveListener&&typeof this.unlistenPointerMoveListener=="function"&&(this.unlistenPointerMoveListener(),this.unlistenPointerMoveListener=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromPointerMoveListener: ",e)}}addPointerUpListener(){this.loggingService.log("%c[WB] Calling FUNCTION: addPointerUpListener","color: green;");try{this.unsubscribeFromPointerUpListener(),this.unlistenPointerUpListener=this.renderer.listen("document","pointerup",e=>{this.windowPointerUp$.next(e)})}catch(e){this.loggingService.catch("Error in DomService addPointerUpListener: ",e)}}unsubscribeFromPointerUpListener(){try{this.unlistenPointerUpListener&&typeof this.unlistenPointerUpListener=="function"&&(this.unlistenPointerUpListener(),this.unlistenPointerUpListener=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromPointerUpListener: ",e)}}addSelectionChangeListener(){this.loggingService.log("%c[WB] Calling FUNCTION: addPointerUpListener","color: green;");try{this.unsubscribeFromSelectionChangeListener(),this.unlistenSelectionChangeListener=this.renderer.listen("document","selectionchange",e=>{this.documentSelectionChange$.next(e)})}catch(e){this.loggingService.catch("Error in DomService addPointerUpListener: ",e)}}unsubscribeFromSelectionChangeListener(){try{this.unlistenSelectionChangeListener&&typeof this.unlistenSelectionChangeListener=="function"&&(this.unlistenSelectionChangeListener(),this.unlistenSelectionChangeListener=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromSelectionChangeListener: ",e)}}updateCurrentMousePosition(e){try{if(this.currentMousePosition.pageX=e.pageX,this.currentMousePosition.pageY=e.pageY,this.currentMousePosition.clientX=e.clientX,this.currentMousePosition.clientY=e.clientY,e.target){let i=this.getXPath(e.target),r=e.target;if(i?.includes("name()='svg'")){let _=this.getXPath(i);_&&(r=_.iterateNext()||e.target)}let a=r.getBoundingClientRect(),s=e.clientX-a.x,c=e.clientY-a.y,p=s*100/(a.width||1),h=c*100/(a.height||1);this.currentMousePosition.element={xpath:i,topPercentage:h,leftPercentage:p}}else this.currentMousePosition.element=null;this.currentMousePosition$.next(this.currentMousePosition)}catch(i){this.loggingService.catch("Error in DomService updateCurrentMousePosition: ",i)}}getTargetElementForCursorPosition(e,i=!0,r=!1,a=!0,s){try{let c=e,p=c?.touches?.length?c.touches[0]?.clientX:c.clientX,h=c?.touches?.length?c.touches[0]?.clientY:c.clientY,_=this.getBackgroundElement(p,h,i,r);if(_&&s&&typeof s=="function"&&(_=s(_)),_){let E=this.getXPath(_),D=this.getXPath(_,!0),B=_.getBoundingClientRect(),G=p-B.x,X=h-B.y,he=G*100/(B.width||1),Ie=X*100/(B.height||1),Me={xpath:E,fXpath:D,leftPercentage:he,topPercentage:Ie};if(a){let Le=this.getXPath(_,!0,!0);Me.cfXpath=Le}return Me}else return null}catch(c){return this.loggingService.catch("Error in DomService getTargetElementForCommentPinAnnotation: ",c),null}}getBackgroundElement(e,i,r=!0,a=!1){try{let s=document.elementsFromPoint(e,i),c=[];s.forEach(h=>{ji(h)?c=[]:xo(h)&&c.push(h)}),a&&(c=c.filter(h=>this.isElementVisibleOnScreen(h)));let p=0;return r||c?.forEach((h,_)=>{h.tagName.toLowerCase()==="svg"&&(p=_)}),c[p]}catch(s){return this.loggingService.catch("Error in DomService getBackgroundElement: ",s),null}}getBackgroundVeltElement(e,i){try{let r=document.elementsFromPoint(e,i),a=[];return r.forEach(s=>{ji(s)&&xo(s)&&a.push(s)}),a[0]}catch(r){return this.loggingService.catch("Error in DomService getBackgroundSnippylyElement: ",r),null}}setPointerPosition(e){this.loggingService.log("%c[WB] Calling FUNCTION: setPointerPosition","color: green;");try{this.previousMousePosition.pageX=e.pageX,this.previousMousePosition.pageY=e.pageY,this.currentMousePosition.pageX=e.pageX,this.currentMousePosition.pageY=e.pageY}catch(i){this.loggingService.catch("Error in DomService setPointerPosition: ",i)}}getCurrentWindowSize$(e){return this.loggingService.log("%c[WB] Calling FUNCTION: getCurrentWindowSize","color: green;"),this.currentScreenSize$.asObservable()}getCurrentMousePosition$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getCurrentMousePosition","color: green;"),this.currentMousePosition$.asObservable()}getCurrentWindowSizeValue(){return this.loggingService.log("%c[WB] Calling FUNCTION: getCurrentWindowSizeValue","color: green;"),this.currentScreenSize$.value}getTopLeftPosition(){this.loggingService.log("%c[WB] Calling FUNCTION: getTopLeftPosition","color: green;");try{let e=document?.body?.getBoundingClientRect()||document?.documentElement?.getBoundingClientRect(),i=this.currentMousePosition?.pageX||e.x+200,r=Math.min(i,e.width/2),a=Math.abs(e.y),s=e.y-20;return a>50&&(s=Math.abs(e.y)+180),this.loggingService.log(e),this.loggingService.log(r),this.loggingService.log(s),{topPositionX:r,topPositionY:s}}catch(e){return this.loggingService.catch("Error in DomService getTopLeftPosition: ",e),{topPositionX:0,topPositionY:0}}}toggleSelection(){this.enableRectSelectionSubject$.next(!this.enableRectSelectionSubject$.value)}enableSelection(){this.enableRectSelectionSubject$.next(!0)}disableSelection(){this.enableRectSelectionSubject$.next(!1)}setPinHighlighterClass(e){this.pinHighlighterClass$.next(e)}setTextHighlighterClass(e){this.textHighlighterClass$.next(e)}getTextHighlighterClass(){return this.textHighlighterClass$.asObservable()}enableCommentPinHighlighter(){this.commentPinHighlighter$.next(!0)}disableCommentPinHighlighter(){this.commentPinHighlighter$.next(!1)}getCommentPinHighlighter$(){return this.commentPinHighlighter$.asObservable()}getCommentPinHighlighter(){return this.commentPinHighlighter$?.value}highlightElement(e,i,r){if(e){if(!r&&this.getCommentPinHighlighter()&&(this.pinHighlighterClass$.value?this.addClassToElement(e,this.pinHighlighterClass$.value):this.addClassToElement(e,U.SNIPPYLY_HIGHLIGHT)),i&&!e.hasAttribute(U.ATTRIBUTES.DEFAULT_CURSOR)){let a=e.style.getPropertyValue("cursor"),s=e.style.getPropertyPriority("cursor"),c=a?{defaultCursorValue:a,defaultCursorPriority:s}:"";e.setAttribute(U.ATTRIBUTES.DEFAULT_CURSOR,c?JSON.stringify(c):""),e.style.setProperty("cursor",i,"important")}e.setAttribute(U.SNIPPYLY_HIGHLIGHT,"true"),e.setAttribute(U.VELT_IGNORE_CHANGE_DETECTION,"true")}}removeHighlightFromElement(e){if(e&&(this.pinHighlighterClass$.value&&this.removeClassFromElement(e,this.pinHighlighterClass$.value),this.removeClassFromElement(e,U.SNIPPYLY_HIGHLIGHT),e.removeAttribute(U.SNIPPYLY_HIGHLIGHT),e.removeAttribute(U.VELT_IGNORE_CHANGE_DETECTION),e.hasAttribute(U.ATTRIBUTES.DEFAULT_CURSOR))){try{if(e.style.removeProperty("cursor"),e.getAttribute(U.ATTRIBUTES.DEFAULT_CURSOR)){let i=JSON.parse(e.getAttribute(U.ATTRIBUTES.DEFAULT_CURSOR));e.style.setProperty("cursor",i.defaultCursorValue,i.defaultCursorPriority)}}catch{}e.removeAttribute(U.ATTRIBUTES.DEFAULT_CURSOR)}}highlightUserElement(e,i,r,a=!1){try{e&&(this.addClassToElement(e,U.VELT_LIVE_SELECTION_ON_ELEMENT),a&&this.addClassToElement(e,U.VELT_LIVE_SELECTION_ON_ELEMENT_DEFAULT),e.setAttribute(U.SNIPPYLY_HIGHLIGHT,"true"),e.setAttribute(U.VELT_IGNORE_CHANGE_DETECTION,"true"),i&&!e.style.getPropertyValue(U.VELT_SELECTION_COLOR)&&e.style.setProperty(U.VELT_SELECTION_COLOR,i),r&&e.setAttribute(U.SNIPPYLY_HIGHLIGHT_USER_NAME,r))}catch(s){this.loggingService.catch("Error in DomService highlightUserElement: ",s)}}removeHighlightUserFromElement(e){try{e&&(this.removeClassFromElement(e,U.VELT_LIVE_SELECTION_ON_ELEMENT),this.removeClassFromElement(e,U.VELT_LIVE_SELECTION_ON_ELEMENT_DEFAULT),e.removeAttribute(U.SNIPPYLY_HIGHLIGHT),e.removeAttribute(U.VELT_IGNORE_CHANGE_DETECTION),e.removeAttribute(U.VELT_SELECTION_COLOR),e.removeAttribute(U.SNIPPYLY_HIGHLIGHT_USER_NAME),e.style.removeProperty(U.VELT_SELECTION_COLOR))}catch(i){this.loggingService.catch("Error in DomService removeHighlightUserFromElement: ",i)}}previewHighlightElement(e){e&&e.setAttribute(U.SNIPPYLY_HIGHLIGHT_PREVIEW,"true")}removePreviewHighlightFromElement(e){e&&e.removeAttribute(U.SNIPPYLY_HIGHLIGHT_PREVIEW)}getXPath(e,i=!1,r=!1,a){try{let s=this.calculateXPath(e,i,r,a);if(s&&typeof s=="string"&&s.includes("/svg")){let c=s.split("/"),p=!1;c.forEach((h,_)=>{h.includes("svg")&&(p=!0),p&&(c[_]="svg:"+h)}),s=c.join("/")}return s}catch(s){this.loggingService.catch("Error in DomService getXPath:",s)}}namespaceResolver(e){return e==="svg"?"http://www.w3.org/2000/svg":null}calculateXPath(e,i,r,a){try{if(e){if(typeof e=="string")return document.evaluate(e,a||document,this.namespaceResolver,XPathResult.ANY_TYPE,null);if(!e||e.nodeType!=1)return"";if(e.id&&document.querySelectorAll(`[id='${e.id}']`)?.length===1&&!i)return"//*[@id='"+e.id+"']";if(r&&e.className&&e.className.split){let c=e.className?.split(" ")?.filter(p=>!p?.includes("snippyly")&&!p?.includes("velt")&&!["show-pin-cursor"].includes(p))[0];if(c){let p=this.calculateXPath(e.parentNode,i,r,a)+"/"+e.tagName.toLowerCase(),h=Array.from(e.parentNode?.children||[]).filter(_=>_.nodeType===1&&_.tagName===e.tagName?_.className?.split(" ")?.filter(D=>D?.includes("snippyly")||D?.includes("velt")||["show-pin-cursor"].includes(D))[0]===c:!1);if(h.length>1){let _=h.indexOf(e)+1;p+=`[contains(concat(' ', normalize-space(@class), ' '), ' ${c} ')][${_}]`}else p+=`[contains(concat(' ', normalize-space(@class), ' '), ' ${c} ')]`;return p}}let s=[].filter.call(e.parentNode?.children?e.parentNode?.children:[],function(c){return c.tagName==e.tagName});return this.calculateXPath(e.parentNode,i,r)+"/"+e.tagName.toLowerCase()+(s.length>1?"["+([].indexOf.call(s,e)+1)+"]":"")}}catch(s){this.loggingService.catch("Error in DomService calculateXPath:",s)}}getElementFromXPath(e,i=document){try{if(this.xpathCache.has(e)){let a=this.xpathCache.get(e);if(a!==void 0&&document.contains(a))return a;this.xpathCache.delete(e)}let r=this.getXPath(e,!1,!1,i);if(r){let a=r?.iterateNext();if(a!==null&&typeof a.setAttribute=="function"){let s=xn();a.setAttribute(U.ATTRIBUTES.VELT_ELEMENT_CACHE_ID,s),this.xpathCacheId.set(s,e)}return this.xpathCache.set(e,a),a}return null}catch(r){return this.loggingService.catch("Error in DomService getElementFromXPath:",r),null}}calculateScreenSize(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowResize","color: green;");try{let e=[document?.body?.clientHeight||0,document?.documentElement?.clientHeight||0,window?.innerHeight||0],i=[document?.body?.clientWidth||0,document?.documentElement?.clientWidth||0,window?.innerWidth||0];this.calculatePageScrollHeight(),this.loggingService.log(this.pageScrollHeight),this.loggingService.log(this.nodeMap),this.highestNode=this.nodeMap[this.pageScrollHeight];let r=new NS;return r.screenWidth=Math.max(...i),r.screenHeight=Math.max(...e),r.screenScrollHeight=this.pageScrollHeight,r}catch(e){return this.loggingService.catch("Error in DomService calculateScreenSize:",e),new NS}}calculatePageScrollHeight(){this.loggingService.log("%c[WB] Calling FUNCTION: calculatePageScrollHeight","color: green;");try{this.pageScrollHeight=0,this.findLongestNode(document?.documentElement?.childNodes)}catch(e){this.loggingService.catch("Error in DomService calculatePageScrollHeight: ",e)}}removeSnippylyContent(e){this.loggingService.log("%c[WB] Calling FUNCTION: removeSnippylyContent","color: green;");try{let r=new DOMParser().parseFromString(e,"text/html");r.querySelectorAll("[data-snippyly-cache-id]").forEach(E=>{E.removeAttribute("data-snippyly-cache-id")}),r.querySelectorAll("[data-velt-cache-id]").forEach(E=>{E.removeAttribute("data-velt-cache-id")}),r.querySelectorAll(".comment-text-highlight").forEach(E=>{E?.parentNode?.insertBefore(document.createTextNode(E?.textContent),E),E.remove()});let p=document.createNodeIterator(r,NodeFilter.SHOW_COMMENT),h;for(;h=p.nextNode();)h?.remove();return this.mergeAdjacentTextNodes(r.body),this.sanitizeHtml(r.body.innerHTML)}catch(i){return this.loggingService.catch("Error in DomService removeSnippylyContent: ",i),e}}mergeAdjacentTextNodes(e){try{let i=e.firstChild;for(;i;){if(i.nodeType===Node.TEXT_NODE){let r=i.nextSibling;for(;r&&r.nodeType===Node.TEXT_NODE;)i.textContent+=r.textContent,r.remove(),r=i.nextSibling}i=i.nextSibling}}catch(i){this.loggingService.catch("Error in DomService mergeAdjacentTextNodes: ",i)}}findLongestNode(e){try{for(let i=e.length-1;i>=0;i--){if(e[i]?.scrollHeight&&e[i]?.clientHeight){let r=Math.max(e[i]?.scrollHeight,e[i]?.clientHeight);this.pageScrollHeight=Math.max(r,this.pageScrollHeight),this.nodeMap[r]=e[i]}e[i]?.childNodes?.length&&this.findLongestNode(e[i]?.childNodes)}}catch(i){this.loggingService.catch("Error in DomService findLongestNode: ",i)}}resetSelectedAnnotationsMap(e=!0,i){try{let r=Array.from(document.querySelectorAll(`[${U.ATTRIBUTES.VELT_ANNOTATION_DRAFT}]`)),a=this.getDraftCommentAnnotationDialogs()||[];r.push(...a),r=Array.from(new Set(r));let s=r.map(_=>_.classList.contains("velt-annotation-draft-checked")?(_.classList.remove("velt-annotation-draft-checked"),null):(this.removeClassFromElement(_,"velt-comment-dialog-shake"),setTimeout(()=>{this.addClassToElement(_,"velt-comment-dialog-shake"),_.getAttribute(U.ATTRIBUTES.VELT_ANNOTATION_EDIT_COMMENT)||_.classList.contains("velt-annotation-draft-checked")||this.addClassToElement(_,"velt-annotation-draft-checked")},100),_.getAttribute(U.ATTRIBUTES.VELT_ANNOTATION_DRAFT))).filter(_=>_),c=Object.keys(this.getRecordingInProgress()||{});s=[...s,...c];let p=this.selectedAnnotationsMap$.value;if(e&&this.selectedAnnotationsMap$.value&&Object.keys(this.selectedAnnotationsMap$.value).length){let _=[];Object.keys(p).forEach(E=>{if(p[E]?.type==="tag"){let D=p[E];D?.to?.length||s.includes(E)||_.push(D)}else p[E]?.comments?.length||s.includes(E)||_.push(p[E])}),this.deleteAnnotations$.next(_),this.deleteAnnotations$.next([])}let h={};Object.keys(p).forEach(_=>{if(s.includes(_)&&(h[_]=p[_]),i)switch(i){case"comment":["comment","videoPin"].includes(p[_]?.type)||(h[_]=p[_]);break;default:p[_]?.type!==i&&(h[_]=p[_]);break}}),Object.keys(h).forEach(_=>{let E=h[_]?.multiThreadAnnotationId;E&&!h[E]&&(h[E]={annotationId:E,type:"multiThread"})}),JSON.stringify(this.selectedAnnotationsMap$.value)!==JSON.stringify(h)&&this.selectedAnnotationsMap$.next(h),this.setDialogOpenedInSidebar(!1)}catch(r){this.loggingService.catch("Error in DomService resetSelectedAnnotationsMap: ",r)}}setRecordingInProgress(e,i){try{if(i)this.recordingInProgress$.next(T(I({},this.recordingInProgress$.value),{[e]:i}));else{let r=this.recordingInProgress$.value;delete r[e],this.recordingInProgress$.next(r)}}catch(r){this.loggingService.catch("Error in DomService setRecordingInProgress: ",r)}}resetRecordingInProgress(){try{this.recordingInProgress$.next({})}catch(e){this.loggingService.catch("Error in DomService resetRecordingInProgress: ",e)}}getRecordingInProgress(){try{return this.recordingInProgress$.value}catch(e){return this.loggingService.catch("Error in DomService getRecordingInProgress: ",e),{}}}getDraftCommentAnnotationDialogs(){try{let e=[];return Array.from(document.querySelectorAll(`${U.TAGS.SNIPPYLY_COMMENT_DIALOG}`)).forEach(r=>{if(r?.shadowRoot){let a=r.shadowRoot.querySelector(`[${U.ATTRIBUTES.VELT_ANNOTATION_DRAFT}]`);a&&e.push(a)}else{let a=r.querySelector(`${U.TAGS.VELT_SHADOW_DOM_INTERNAL}`);if(a?.shadowRoot){let s=a.shadowRoot?.querySelector(`[${U.ATTRIBUTES.VELT_ANNOTATION_DRAFT}]`);s&&e.push(s)}else{let s=r.querySelector(`[${U.ATTRIBUTES.VELT_ANNOTATION_DRAFT}]`);s&&e.push(s)}}}),e}catch(e){return this.loggingService.catch("Error in DomService getDraftCommentAnnotationDialogs: ",e),[]}}getSelectedAnnotationsMap(e){try{let i=this.selectedAnnotationsMap$.value;if(e){let r={};return Object.keys(i).forEach(a=>{switch(e){case"comment":["comment","videoPin"].includes(i[a].type)&&(r[a]=i[a]);break;default:i[a].type===e&&(r[a]=i[a]);break}}),r}else return i}catch(i){return this.loggingService.catch("Error in DomService getSelectedAnnotationsMap: ",i),{}}}getSelectedAnnotationsMap$(e){return this.selectedAnnotationsMap$.asObservable().pipe(ce(i=>{if(e){let r={};return Object.keys(i).forEach(a=>{i[a].type===e&&(r[a]=i[a])}),r}else return i}))}getSelectedComments$(){return this.selectedAnnotationsMap$.asObservable().pipe(ce(e=>Object.values(e)))}getSelectedAnnotationsLocationMap(){try{return this.selectedAnnotationsLocationMap$.value}catch(e){return this.loggingService.catch("Error in DomService getSelectedAnnotationsLocationMap: ",e),{}}}getSelectedAnnotationsLocationMap$(){return this.selectedAnnotationsLocationMap$.asObservable()}toggleAnnotationSelection(e,i,r,a=!1){try{r==="sidebarShowReplies"?this.setDialogOpenedInSidebar(!0):this.setDialogOpenedInSidebar(!1);let s=JSON.parse(JSON.stringify(this.selectedAnnotationsMap$.value||{})),c=JSON.parse(JSON.stringify(this.selectedAnnotationsLocationMap$.value||{}));if(s[e.annotationId]&&!a)delete s[e.annotationId];else{(!this.windowKeydownShift$.value||a)&&(s={}),s[e.annotationId]=e,c[e.annotationId]=i;let p=e?.multiThreadAnnotationId;p&&(s[p]={annotationId:p,type:"multiThread"},c[p]=i)}this.selectedAnnotationsMap$.next(s),Object.keys(c).forEach(p=>{s[p]||delete c[p]}),this.selectedAnnotationsLocationMap$.next(c)}catch(s){this.loggingService.catch("Error in DomService toggleAnnotationSelection: ",s)}}setSelectedAnnotationLocation(e,i){try{let r=JSON.parse(JSON.stringify(this.getSelectedAnnotationsLocationMap()||{}));r?.[e]!==i&&(r[e]=i,this.selectedAnnotationsLocationMap$.next(r))}catch(r){this.loggingService.catch("Error in DomService setSelectedAnnotationLocation: ",r)}}updateSelectedAnnotationInMap(e){try{let i=this.selectedAnnotationsMap$.value;e.forEach(r=>{i[r.annotationId]&&(i[r.annotationId]=r)}),this.selectedAnnotationsMap$.next(i)}catch(i){this.loggingService.catch("Error in DomService updateSelectedAnnotationInMap: ",i)}}getDeleteCommmentAnnotations$(){try{return this.deleteAnnotations$.asObservable()}catch(e){return this.loggingService.catch("Error in DomService getDeleteCommmentAnnotations$: ",e),re([])}}getHighestNode(){return this.loggingService.log("%c[WB] Calling FUNCTION: getHighestNode","color: green;"),this.highestNode}onWindowMouseDown$(){return this.windowMouseDown$.asObservable()}onWindowPointerMove$(){return this.windowPointerMove$.asObservable()}onWindowPointerMove(){return this.windowPointerMove$.value}onWindowPointerUp$(){return this.windowPointerUp$.asObservable()}onSelectionChange$(){return this.documentSelectionChange$.asObservable()}onWindowClick$(){return this.windowClick$.asObservable()}onWindowScroll$(){return this.windowScroll$.asObservable()}onWindowResize$(){return this.windowResize$.asObservable()}onWindowKeyupBackspace$(){return this.windowKeyupBackspace$.asObservable()}onWindowKeyupDelete$(){return this.windowKeyupDelete$.asObservable()}onWindowKeyupEsc$(){return this.windowKeyupEsc$.asObservable()}onWindowPopState$(){return this.windowPopState$.asObservable()}onDocumentClick$(){return this.documentClick$.asObservable()}getLastDocumentClick(){return this.documentClick$.value}onDocumentClickSubject$(){return this.documentClickSubject$.asObservable()}onDocumentFocus$(){return this.documentFocus$.asObservable()}onDomChange$(e){try{return this.mutationObserver||this.setMutationObserver(e),this.mutation$.asObservable()}catch(i){return this.loggingService.catch("Error in DomService onDomChange$: ",i),re([])}}getChildListMutation$(){return this.childListMutation$.asObservable()}onNetworkStatusChange$(){return this.networkStatus$.asObservable()}getElementOffset(e,i){try{let r={offsetTop:0,offsetLeft:0},a=e;if(a===i){let s=window.getComputedStyle(e);s.position==="static"&&s.transformStyle!="preserve-3d"&&s.transform=="none"&&(r.offsetLeft=e?.offsetLeft||0,r.offsetTop=e?.offsetTop||0)}if(a!==i)if(e?.closest("svg"))for(;a&&a!==i;){let c=window.getComputedStyle(a);if(a.tagName.toLowerCase()==="svg"||a instanceof SVGElement){let p=a.parentElement;if(p){let h=p.getBoundingClientRect(),_=a.getBoundingClientRect();r.offsetLeft+=_.left-h.left,r.offsetTop+=_.top-h.top}}else c.position==="static"?c.transformStyle!="preserve-3d"&&c.transform=="none"&&(r.offsetLeft+=a?.offsetLeft||0,r.offsetTop+=a?.offsetTop||0):(r.offsetLeft+=a.offsetLeft,r.offsetTop+=a.offsetTop);if(a=a.parentElement,e instanceof SVGElement&&a===i){let p=window.getComputedStyle(a);p.position==="static"&&p.transformStyle!="preserve-3d"&&p.transform=="none"&&(r.offsetLeft+=a?.offsetLeft||0,r.offsetTop+=a?.offsetTop||0)}}else{let c=window.getComputedStyle(a);c.position==="static"?c.transformStyle!="preserve-3d"&&c.transform=="none"&&(r.offsetLeft+=a?.offsetLeft||0,r.offsetTop+=a?.offsetTop||0):(r.offsetLeft+=a.offsetLeft,r.offsetTop+=a.offsetTop)}return r}catch(r){return this.loggingService.catch("Error in DomService getElementOffset: ",r),{offsetTop:0,offsetLeft:0}}}isElementVisible(e){try{if(typeof e?.getBoundingClientRect=="function"){let{width:i,height:r,top:a,bottom:s}=e?.getBoundingClientRect();return i>0||r>0||a<window.innerHeight&&s>0}else return!1}catch(i){return this.loggingService.catch("Error in DomService isElementVisible: ",i),!1}}isElementVisibleOnScreen(e){try{if(e){if(!(e instanceof Element))return!1;let i=e,r=window.getComputedStyle(i);return!(r.display==="none"||r.visibility==="hidden"||parseFloat(r.opacity)===0)}return!1}catch(i){return this.loggingService.catch("Error in DomService isElementVisibleOnScreen: ",i),!1}}getClickAndDragPointsObservable(){return new Ft(e=>{let i=oi(document,"mousedown").pipe(ce(p=>({type:p.type,x:p.clientX+window.scrollX,y:p.clientY+window.scrollY,event:p}))),r=oi(document,"mousemove").pipe(ce(p=>({type:p.type,x:p.clientX+window.scrollX,y:p.clientY+window.scrollY,event:p}))),a=oi(document,"mouseup").pipe(ce(p=>({type:p.type,x:p.clientX+window.scrollX,y:p.clientY+window.scrollY,event:p}))),c=i.pipe(ge(p=>r.pipe(Vi(),ce(([h,_])=>({startPoint:p,prevPoint:h,curPoint:_})),oo(a)))).subscribe(e);return()=>c.unsubscribe()})}drawRectangle(e,i){let r=document.querySelector(".rectangle");r||(r=document.createElement("div"),this.addClassToElement(r,"rectangle"),r.setAttribute(U.ATTRIBUTES.VELT_COMMENT_DISABLED,"true"),r.setAttribute(U.VELT_IGNORE_CHANGE_DETECTION,"true"),document.body.appendChild(r));let a=Math.abs(i.x-e.x),s=Math.abs(i.y-e.y),c=Math.min(e.x,i.x),p=Math.min(e.y,i.y);return r.style.width=`${a}px`,r.style.height=`${s}px`,r.style.left=`${c}px`,r.style.top=`${p}px`,r.style.position="absolute",r.style.border="2px dashed #f00",r.style.pointerEvents="none",r.style.zIndex="2147483577",r}getRange(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: getRange","color: green;"),window.getSelection()?.toString()){let e=window.getSelection();if(e?.rangeCount)return e.getRangeAt(0)}return null}catch(e){return this.loggingService.catch("Error in DomService getRange: ",e),null}}clearTextSelection(){try{this.loggingService.log("%c[WB] Calling FUNCTION: clearTextSelection","color: green;"),window.getSelection&&(window.getSelection()?.empty?window.getSelection()?.empty():window.getSelection()?.removeAllRanges&&window.getSelection()?.removeAllRanges())}catch(e){this.loggingService.catch("Error in DomService clearTextSelection: ",e)}}getTargetTextRangeFromSelectionRange(e){try{let i={},r=e.commonAncestorContainer;r?.nodeType===Node.TEXT_NODE&&(r=r.parentElement);let a=document.body;if(r){let c=this.getTextXPath(r);this.isXpathWithId(c)&&(a=r)}let s=this.getAdditionalLocationContainer(r);if(s&&(a=s),i.commonAncestorContainer=this.getTextXPath(a),i.commonAncestorContainer){let c=this.getElementFromXPath(i.commonAncestorContainer);c&&(i.commonAncestorContainerFXpath=this.getXPath(c,!0),i.commonAncestorContainerCFXpath=this.getXPath(c,!0,!0))}return i.text=e.toString(),i.occurrence=Au(a,0,e.startContainer,e.startOffset,e.toString())+1,i}catch(i){this.loggingService.catch("Error in DomService getTargetTextRangeFromSelectionRange: ",i);return}}getTextXPath(e){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: getTextXPath","color: green;"),e.nodeType===Node.TEXT_NODE){let i=1,r=e.previousSibling;for(;r;)r.nodeType===Node.TEXT_NODE&&i++,r=r.previousSibling;return this.getXPath(e.parentElement)}else return this.getXPath(e)}catch(i){this.loggingService.catch("Error in DomService getTextXPath: ",i);return}}getHostElement(e){try{if(U.NON_NESTABLE_ELEMENTS[e?.tagName?.toLowerCase()]){let r=e?.closest("picture");return r?r?.parentElement:e.parentElement}let i=e.closest("svg");return i?i?.parentElement:e}catch(i){return this.loggingService.catch("Error in DomService getHostElement: ",i),e}}isElementInsideAdditionalLocationContainer(e){try{return!!e?.closest(`[${U.ATTRIBUTES.VELT_LOCATION}], [${U.ATTRIBUTES.VELT_LOCATION_ID}]`)}catch(i){return this.loggingService.catch("Error in DomService isElementInsideAdditionalLocationContainer: ",i),!1}}getAdditionalLocationContainer(e){try{return e?.closest(`[${U.ATTRIBUTES.VELT_LOCATION}], [${U.ATTRIBUTES.VELT_LOCATION_ID}]`)||null}catch(i){return this.loggingService.catch("Error in DomService getAdditionalLocationContainer: ",i),null}}isXpathWithId(e){try{return typeof e=="string"?!!e?.includes("[@id="):!1}catch(i){return this.loggingService.catch("Error in DomService isXpathWithId: ",i),!1}}getListedElements({elementIds:e,elementClassNames:i,elementQuerySelectors:r}){try{let a=[];if(e?.length)for(let s=0;s<e.length;s++){let c=document.getElementById(e[s]);c&&a.push(c)}if(i?.length)for(let s=0;s<i.length;s++){let c=document.getElementsByClassName(i[s]);for(let p=0;p<c.length;p++){let h=c[p];h&&h instanceof HTMLElement&&a.push(h)}}if(r?.length)for(let s=0;s<r.length;s++){let c=document.querySelectorAll(r[s]);for(let p=0;p<c.length;p++){let h=c[p];h&&h instanceof HTMLElement&&a.push(h)}}return a}catch(a){return this.loggingService.catch("Error in DomService getListedElements: ",a),[]}}isElementInsideListedElementIds(e,i){try{if(i?.length){for(let r=0;r<i.length;r++){let a=document.getElementById(i[r]);if(a&&a.contains(e))return!0}return!1}return!0}catch(r){return this.loggingService.catch("Error in DomService isElementInsideListedElementIds: ",r),!1}}isElementInsideListedElementClassNames(e,i){try{if(i?.length){for(let r=0;r<i.length;r++){let a=document.getElementsByClassName(i[r]);for(let s=0;s<a.length;s++)if(a[s].contains(e))return!0}return!1}return!0}catch(r){return this.loggingService.catch("Error in DomService isElementInsideListedElementClassNames: ",r),!1}}isElementInsideListedElementQuerySelectors(e,i){try{if(i?.length){for(let r=0;r<i.length;r++){let a=document.querySelectorAll(i[r]);for(let s=0;s<a.length;s++)if(a[s].contains(e))return!0}return!1}return!0}catch(r){return this.loggingService.catch("Error in DomService isElementInsideListedElementQuerySelectors: ",r),!1}}addClassToElement(e,i){try{this.loggingService.log("%c[WB] Calling FUNCTION: addClassToElement","color: green;"),e&&(e.classList?.contains(i)||e.classList?.add(i))}catch(r){this.loggingService.catch("Error in DomService addClassToElement: ",r)}}removeClassFromElement(e,i){try{this.loggingService.log("%c[WB] Calling FUNCTION: removeClassFromElement","color: green;"),e&&e.classList?.contains(i)&&e.classList?.remove(i)}catch(r){this.loggingService.catch("Error in DomService removeClassFromElement: ",r)}}isElementInsideParentWithAttribute(e,i,r){try{let a=e;for(;a&&a!==document.body;){if(a?.getAttribute&&a?.getAttribute(i)===r)return!0;a=a.parentElement}return!1}catch(a){return this.loggingService.catch("Error in DomService isElementInsideParentWithAttribute: ",a),!1}}setVideoEditorHandlingDelete(e){try{this.isVideoEditorHandlingDelete=e}catch(i){this.loggingService.catch("Error in DomService setVideoEditorHandlingDelete: ",i)}}isVideoEditorHandlingDeleteKey(){try{return this.isVideoEditorHandlingDelete}catch(e){return this.loggingService.catch("Error in DomService isVideoEditorHandlingDeleteKey: ",e),!1}}setCustomCss(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setCustomCss","color: green;"),this.customCss$.next(e)}catch(i){this.loggingService.catch("Error in DomService setCustomCss: ",i)}}getCustomCss$(){try{return this.loggingService.log("%c[WB] Calling FUNCTION: getCustomCss$","color: green;"),this.customCss$.asObservable()}catch(e){return this.loggingService.catch("Error in DomService getCustomCss$: ",e),re(null)}}injectCustomCss(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: injectCustomCss","color: green;");let i=this.customCss$.value;if(i){let r=e?.shadowRoot?.querySelector(`[${U.VELT_CUSTOM_CSS}]`);if(r&&r.remove(),i?.type==="link"){let a=document.createElement("link");a.href=i?.value,a.rel="stylesheet",a.setAttribute(U.VELT_CUSTOM_CSS,"true"),e?.shadowRoot?.appendChild(a)}else{let a=document.createElement("style");a.innerHTML=this.sanitizeHtml(i?.value),a.setAttribute(U.VELT_CUSTOM_CSS,"true"),e?.shadowRoot?.appendChild(a)}}}catch(i){this.loggingService.catch("Error in DomService injectCustomCss: ",i)}}trimCommentHtml(e){try{let i=document.createElement("div");i.innerHTML=e,this.removeEmptyElements(i);let r=i.innerHTML;return r=r.replace(o.MULTIPLE_NBSP_REGEX," ").replace(o.TRIM_NBSP_REGEX,"").trim(),r}catch(i){return this.loggingService.catch("Error in DomService trimCommentHtml: ",i),e}}removeEmptyElements(e){try{let a=function(s){return r.test(s.innerHTML)};var i=a;let r=/^\s*(<br\s*\/?>)?\s*$/;for(;e.firstChild&&a(e.firstChild);)e.removeChild(e.firstChild);for(;e.lastChild&&a(e.lastChild);)e.removeChild(e.lastChild)}catch(r){this.loggingService.catch("Error in DomService removeEmptyElements: ",r)}}normalizeWhitespace(e){try{e.childNodes.forEach(i=>{i.nodeType===Node.TEXT_NODE?i.nodeValue=i.nodeValue?.replace(/\s+/g," ").trim()??"":i.nodeType===Node.ELEMENT_NODE&&this.normalizeWhitespace(i)})}catch(i){this.loggingService.catch("Error in DomService normalizeWhitespace: ",i)}}sanitizeHtml(e){try{return this.loggingService.log("%c[WB] Calling FUNCTION: sanitizeHtml","color: green;"),s$.sanitize(e,rse)}catch(i){return this.loggingService.catch("Error in DomService sanitizeHtml: ",i),""}}sanitizeSvg(e){try{return s$.sanitize(e,rse)}catch(i){return this.loggingService.catch("Error in DomService sanitizeSvg: ",i),e}}setDeviceInfo(){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDeviceInfo","color: green;");let e=new Jn;this.deviceInfo$.next(e)}catch(e){this.loggingService.catch("Error in DomService setDeviceInfo: ",e)}}getDeviceInfo$(){try{return this.loggingService.log("%c[WB] Calling FUNCTION: getDeviceInfo$","color: green;"),this.deviceInfo$.asObservable()}catch(e){return this.loggingService.catch("Error in DomService getDeviceInfo$: ",e),re(new Jn)}}getTabId(){try{let e=sessionStorage.getItem(U.SESSION_STORAGE.VELT_TAB_ID),i=this.getTabIdFromWindowName();return(!e||e!==i)&&(e=xn(),sessionStorage.setItem(U.SESSION_STORAGE.VELT_TAB_ID,e),this.setTabIdToWindowName(e)),e}catch(e){return this.loggingService.catch("Error in DomService getTabId: ",e),null}}getTabIdFromWindowName(){try{return window.name}catch(e){return this.loggingService.catch("Error in DomService getTabIdFromWindowName: ",e),null}}setTabIdToWindowName(e){try{window.name=e}catch(i){this.loggingService.catch("Error in DomService setTabIdToWindowName: ",i)}}getDeviceInfo(){try{return this.loggingService.log("%c[WB] Calling FUNCTION: getDeviceInfo","color: green;"),this.deviceInfo$.value}catch(e){return this.loggingService.catch("Error in DomService getDeviceInfo: ",e),new Jn}}isMobileDevice(){try{return new Jn().getDeviceType()===Zo.MOBILE}catch(e){return this.loggingService.catch("Error in DomService isMobileDevice: ",e),!1}}isTabletDevice(){try{return new Jn().getDeviceType()===Zo.TABLET}catch(e){return this.loggingService.catch("Error in DomService isTabletDevice: ",e),!1}}isDesktopDevice(){try{return new Jn().getDeviceType()===Zo.DESKTOP}catch(e){return this.loggingService.catch("Error in DomService isDesktopDevice: ",e),!1}}deepCloneElement(e){try{var i=document.createElement(e?.tagName);return Array.from(e.attributes).forEach(r=>{i.setAttribute(r.nodeName,r.nodeValue)}),e.childNodes.forEach(r=>{r.nodeType===Node.ELEMENT_NODE?i.appendChild(this.deepCloneElement(r)):r.nodeType===Node.TEXT_NODE&&i.appendChild(document.createTextNode(r.nodeValue))}),i}catch(r){return this.loggingService.catch("Error in DomService deepCloneElement: ",r),e}}setRandomNumberToElementRecursive(e){try{if(!e)return;let i=Math.random().toString(36).substring(7);e&&e.setAttribute&&typeof e.setAttribute=="function"&&(e.getAttribute("velt-wireframe-id")||e.setAttribute("velt-wireframe-id",i)),Array.from(e.children).forEach(a=>{this.setRandomNumberToElementRecursive(a)})}catch(i){this.loggingService.catch("Error in DomService setRandomNumberToElementRecursive: ",i)}}setDialogOpenedInSidebar(e){this.dialogOpenedInSidebar$.next(e)}getDialogOpenedInSidebar(){return this.dialogOpenedInSidebar$.asObservable()}removeWireframeSuffixFromTags(e){if(!e)return;Array.from(e.children).forEach(r=>{if(this.removeWireframeSuffixFromTags(r),r.tagName.toLowerCase().endsWith("-wireframe")){let a=r.tagName.toLowerCase().replace("-wireframe",""),s=document.createElement(a);for(Array.from(r.attributes).forEach(c=>{s.setAttribute(c.name,c.value)});r.firstChild;)s.appendChild(r.firstChild);r.parentNode.replaceChild(s,r)}})}isMonitorDevice(){try{return new Jn().getDeviceType()===Zo.MONITOR}catch(e){return this.loggingService.catch("Error in DomService isMonitorDevice: ",e),!1}}};o.MULTIPLE_NBSP_REGEX=/(?: \s*){2,}/g,o.TRIM_NBSP_REGEX=/^(?: \s*)+|(?: \s*)+$/g,o.\u0275fac=function(i){return new(i||o)(J(qo),J(y),J(Ms))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var je=(()=>{let o=class o{constructor(e,i,r,a,s,c,p,h){this.afAuth=e,this.configService=i,this.avatarService=r,this.coreActionsService=a,this.domService=s,this.functions=c,this.analyticsService=p,this.loggingService=h,this.user$=new fe(null),this.userOptions$=new fe(null),this.userContacts$=new fe(null),this.userOrganization$=new fe(null),this.providedUser=new wo,this.firebaseConfig$=new fe(null),this.advancedQueries$=new fe(null),this.planDetails$=new fe(null),this.signOutPreviousUser$=new fe(null),this.preSignOutFunctions=new Map,this.autoLoginCalled=!1,this.autoLoginRequired=!0,this.config=null,this.getPlanDetailsCalled=!1,this.forceReLoggedIn=!1,this.lastLoggedInUserData=null,this.sessionReLoginCount=0,this.SESSION_RE_LOGIN_COUNT_LIMIT=10,this.sessionReLoginSubscription=null,this.TOKEN_EXPIRED_ERROR_COUNT_LIMIT=3,this.tokenExpiredErrorCount=0,this.loggingService.log("%c[WB] Creating CLASS: AuthService","color: blue;");try{this.analyticsService.setAuthService(this),this.configService.getConfig$().subscribe(_=>{this.config=_}),this.forceReLoggedIn=localStorage.getItem(U.LOCAL_STORAGE.VELT_USER_FORCE_RE_LOGGED_IN)==="true",this.sessionReLoginSubscription=Wn(this.afAuth).pipe(Go(this.afAuth.currentUser),Vi(),ge(([_,E])=>this.domService.onNetworkStatusChange$().pipe(Ne(D=>D),Je(1),ce(()=>({previousUser:_,currentUser:E}))))).subscribe(D=>ee(this,[D],function*({previousUser:_,currentUser:E}){if(!E&&_){let B=_?.stsTokenManager?.expirationTime,G=new Date().getTime(),X=B-G;G>B&&(this.analyticsService.trackEvent(Z.Events.Core.SDK_SESSION_TOKEN_EXPIRED,{apiKey:this.apiKey,user:this.user$.value,lastLoggedInUserData:this.lastLoggedInUserData,timeLeft:X,forceReset:this.userOptions$.value?.forceReset,sessionReLoginCount:this.sessionReLoginCount},!0,this.user$.value?.userSnippylyId),this.user$.value&&_?.uid===this.user$.value?.userSnippylyId&&this.lastLoggedInUserData?.user?.userSnippylyId===this.user$.value?.userSnippylyId&&(this.sessionReLoginCount>this.SESSION_RE_LOGIN_COUNT_LIMIT?(this.analyticsService.trackEvent(Z.Events.Core.SDK_SESSION_RE_LOGIN_COUNT_EXCEEDED,{apiKey:this.apiKey,clientUserId:this.lastLoggedInUserData.user.userId,snippylyUserId:this.lastLoggedInUserData.user.userSnippylyId,timeLeft:X,forceReset:this.userOptions$.value?.forceReset,sessionReLoginCount:this.sessionReLoginCount},!0,this.user$.value?.userSnippylyId),this.sessionReLoginSubscription?.unsubscribe()):(this.sessionReLoginCount++,this.analyticsService.trackEvent(Z.Events.Core.SDK_SESSION_RE_LOGIN_TRIGGERED,{apiKey:this.apiKey,clientUserId:this.lastLoggedInUserData.user.userId,snippylyUserId:this.lastLoggedInUserData.user.userSnippylyId,user:this.getUserWithoutContacts(this.lastLoggedInUserData.user),timeLeft:X,forceReset:this.userOptions$.value?.forceReset,sessionReLoginCount:this.sessionReLoginCount},!0,this.lastLoggedInUserData.user.userSnippylyId),this.initializeClient(this.lastLoggedInUserData.user,this.lastLoggedInUserData.userOptions,this.lastLoggedInUserData.initializeClientToken,this.lastLoggedInUserData.autoLogin,"internal-sessionReLogin"))))}}),_=>{this.loggingService.catch("Error in AuthService sessionReLoginSubscription: ",_)}),this.getUser$().pipe(Kt(_o)).subscribe(_=>{let E=aS(_);this.coreActionsService.triggerAction(gd.USER_UPDATE,E)})}catch(_){this.loggingService.catch("Error in AuthService constructor: ",_)}}setApiKey(e,i){this.loggingService.log("%c[WB] Calling FUNCTION: setApiKey","color: green;",e);try{if(this.apiKey){this.loggingService.log("API key is already set");return}this.apiKey=e,this.configService.setApiKey(this.apiKey),i||(i=new iM),this.configService.initConfig(i),i.debugMode?sessionStorage.setItem("debugMode","true"):sessionStorage.removeItem("debugMode"),this.autoLoginCalled||Wn(this.afAuth).pipe(Je(1)).subscribe(r=>ee(this,null,function*(){if(this.autoLoginCalled=!0,r){let a=yield ad(r,!0).catch(s=>null);if(a){let{user:s}=a?.claims;this.autoLoginRequired&&this.initializeClient(s,this.userOptions$?.value?T(I({},this.userOptions$?.value),{replaceContacts:!1,replaceGroupContacts:!1,replacePrivateContacts:!1}):{},new Date().getTime(),!0,"internal-autoLogin")}}}))}catch(r){this.loggingService.catch("Error in setApiKey: ",r)}}setUsersService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setUsersService","color: green;"),this.usersService=e}catch(i){this.loggingService.catch("Error in setUsersService: ",i)}}setDocService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocService","color: green;"),this.docService=e}catch(i){this.loggingService.catch("Error in setDocService: ",i)}}setContactService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setContactService","color: green;"),this.contactService=e}catch(i){this.loggingService.catch("Error in setContactService: ",i)}}setIamService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setIamService","color: green;"),this.iamService=e}catch(i){this.loggingService.catch("Error in setIamService: ",i)}}setAreaService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setAreaService","color: green;"),this.areaService=e}catch(i){this.loggingService.catch("Error in setAreaService: ",i)}}setCommentService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setCommentService","color: green;"),this.commentService=e}catch(i){this.loggingService.catch("Error in setCommentService: ",i)}}setReactionService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setReactionService","color: green;"),this.reactionService=e}catch(i){this.loggingService.catch("Error in setReactionService: ",i)}}setRecorderAnnotationService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setRecorderAnnotationService","color: green;"),this.recorderAnnotationService=e}catch(i){this.loggingService.catch("Error in setRecorderAnnotationService: ",i)}}setViewsService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setViewsService","color: green;"),this.viewsService=e}catch(i){this.loggingService.catch("Error in setViewsService: ",i)}}setCommonDbService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setCommonDbService","color: green;"),this.commonDbService=e}catch(i){this.loggingService.catch("Error in setCommonDbService: ",i)}}validateOrganizationId(e){if(this.isVersionGreaterThanOrEqualTo4()&&!e?.organizationId)if(this.analyticsService.trackEvent(Z.Events.Core.SDK_VALIDATE_CLIENT_FAILED,{apiKey:this.apiKey,clientUserId:e.userId,snippylyUserId:e.userSnippylyId,message:"Organization Id is not set",forceReset:this.userOptions$.value?.forceReset,user:this.getUserWithoutContacts(e)},!0,e.userSnippylyId),this.configService.getSF())this.loggingService.catch("OrganizationId is not set in Identify method",void 0,void 0,!0);else throw new Error("OrganizationId is not set in Identify method")}initializeClient(e,i,r,a,s){return ee(this,null,function*(){try{if(this.autoLoginRequired=!1,this.userOptions$.next(i),this.initializeClientToken)this.pendingUserLogin=e,this.pendingUserLoginSource=s;else{e.userSnippylyId=ov(this.configService.getApiKey(),e.userId),this.pendingUserLogin=void 0,this.pendingUserLoginSource=void 0,this.initializeClientToken=r;let c=yield Wn(this.afAuth).pipe(Je(1)).toPromise().catch(h=>null),p=!0;if(this.providedUser=JSON.parse(JSON.stringify(e)),c){let h=yield ad(c,!0).catch(D=>null);if(!h)return;let{user:_,firebaseConfig:E}=h.claims;if(c?.uid!==e?.userSnippylyId||e?.groupId!==_?.groupId||e?.organizationId!==_?.organizationId||i?.forceReset||!a&&e?.organizationId&&!this.forceReLoggedIn||this.forceReLoginRequiredForAdvancedQueries(e)||this.forceReLoginRequiredForRegion(e,E))localStorage.setItem(U.LOCAL_STORAGE.VELT_USER_FORCE_RE_LOGGED_IN,"true"),this.forceReLoggedIn=!0,yield this.signOutUser("internal");else{this.loggingService.log("%c[WB] Calling FUNCTION: reinitializeCurrentUser","color: green;"),this.loggingService.log("Keeping user");let D=yield ad(c,!0).catch(he=>null);if(!D)return;let{firebaseConfig:B,user:G,advancedQueries:X}=D.claims;this.validateOrganizationId(e),this.setFirebaseConfig(B),this.setAdvancedQueries(X),G&&(this.providedUser.isAdmin=!!G.isAdmin),this.initializeSignedInUser(c,a),p=!1,this.analyticsService.trackEvent(Z.Events.Core.SDK_USER_AUTH_SUCCESS,{apiKey:this.apiKey,clientUserId:e.userId,snippylyUserId:e.userSnippylyId,authType:"auto",forceReset:this.userOptions$.value?.forceReset,user:this.getUserWithoutContacts(e),source:s})}}if(p){this.analyticsService.trackEvent(Z.Events.Core.SDK_VALIDATE_CLIENT_TRIGGERED,{apiKey:this.apiKey,clientUserId:e.userId,snippylyUserId:e.userSnippylyId,forceReset:this.userOptions$.value?.forceReset,user:this.getUserWithoutContacts(e),source:s},!0,e.userSnippylyId);let h=Cr(this.functions,Zn.cloudFunction.validateClient,{timeout:20*60*1e3}),_=Ta(),E=(yield h({apiKey:this.apiKey,user:e,version:_,authToken:i?.authToken}))?.data;if(E.error){if(this.analyticsService.trackEvent(Z.Events.Core.SDK_VALIDATE_CLIENT_FAILED,{apiKey:this.apiKey,clientUserId:e.userId,snippylyUserId:e.userSnippylyId,message:E.error,forceReset:this.userOptions$.value?.forceReset,user:this.getUserWithoutContacts(e),source:s},!0,e.userSnippylyId),E.error&&typeof E.error=="string"&&E.error?.toLowerCase()?.includes("token expired"))if(this.tokenExpiredErrorCount++,this.tokenExpiredErrorCount<=this.TOKEN_EXPIRED_ERROR_COUNT_LIMIT){let D={code:"token_expired",message:"Token expired"};this.coreActionsService.triggerAction(gd.ERROR,D)}else{let D={code:"too_many_retries",message:"Token expired. Too many retries."};this.coreActionsService.triggerAction(gd.ERROR,D),this.analyticsService.trackEvent(Z.Events.Core.SDK_JWT_EXPIRED_RETRY_EXCEEDED,{apiKey:this.apiKey,clientUserId:e.userId,snippylyUserId:e.userSnippylyId,forceReset:this.userOptions$.value?.forceReset,source:s},!0,e.userSnippylyId)}throw E.error}else this.tokenExpiredErrorCount=0;if(this.analyticsService.trackEvent(Z.Events.Core.SDK_VALIDATE_CLIENT_SUCCESS,{apiKey:this.apiKey,clientUserId:e.userId,snippylyUserId:e.userSnippylyId,forceReset:this.userOptions$.value?.forceReset,user:this.getUserWithoutContacts(e),source:s},!0,e.userSnippylyId),this.validateOrganizationId(e),E.firebaseConfig){this.setFirebaseConfig(E.firebaseConfig),yield this.signInWithCustomToken(e,E.token),this.loggingService.log("new signed in user",this.afAuth.currentUser);let D=yield ad(this.afAuth.currentUser,!0).catch(X=>null);if(!D)return;let{user:B,advancedQueries:G}=D.claims;this.setAdvancedQueries(G),this.providedUser.isAdmin=!!B?.isAdmin,this.initializeSignedInUser(this.afAuth.currentUser,a)}}this.initializeClientToken=0,this.lastLoggedInUserData={user:e,userOptions:i,initializeClientToken:r,autoLogin:a},this.checkForPendingLogin()}return e}catch(c){return this.initializeClientToken=0,this.checkForPendingLogin(),this.loggingService.catch("Error in initializeClient: ",c),Promise.resolve(null)}})}isVersionGreaterThanOrEqualTo4(){try{let e=Ta();return(e?parseInt(e.split(".")?.[0]||"0"):0)>=4}catch(e){return this.loggingService.catch("Error in isVersionGreaterThanOrEqualTo4: ",e),!1}}forceReLoginRequiredForAdvancedQueries(e){try{let i=this.isVersionGreaterThanOrEqualTo4(),r=!1;try{let a=localStorage.getItem(U.LOCAL_STORAGE.VELT_ADVANCED_QUERIES);a&&(r=JSON.parse(a)?.advancedQueriesEnabled)}catch(a){this.loggingService.catch("Error in forceReLoginRequiredForAdvancedQueries: ",a)}return!!(i&&e.organizationId&&!r)}catch(i){return this.loggingService.catch("Error in forceReLoginRequiredForAdvancedQueries: ",i),!1}}forceReLoginRequiredForRegion(e,i){try{return!!(this.isVersionGreaterThanOrEqualTo4()&&e.organizationId&&!i?.region)}catch(r){return this.loggingService.catch("Error in forceReLoginRequiredForRegion: ",r),!1}}checkForPendingLogin(){this.pendingUserLogin&&this.initializeClient(this.pendingUserLogin,this.userOptions$?.value||{},new Date().getTime(),void 0,this.pendingUserLoginSource)}setFirebaseConfig(e){this.loggingService.log("%c[WB] Calling FUNCTION: setFirebaseConfig","color: green;");try{this.firebaseConfig$.value||this.firebaseConfig$.next({firebaseOptions:I(I({},Zn.firebaseConfig),e)})}catch(i){this.loggingService.catch("Error in setFirebaseConfig: ",i)}}getFirebaseConfig$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getFirebaseConfig","color: green;"),this.firebaseConfig$.asObservable()}getFirebaseConfig(){return this.loggingService.log("%c[WB] Calling FUNCTION: getFirebaseConfig","color: green;"),this.firebaseConfig$.value}setAdvancedQueries(e){this.loggingService.log("%c[WB] Calling FUNCTION: setAdvancedQueries","color: green;");try{e&&typeof e=="object"&&localStorage.setItem(U.LOCAL_STORAGE.VELT_ADVANCED_QUERIES,JSON.stringify(e)),this.advancedQueries$.next(e)}catch(i){this.loggingService.catch("Error in setAdvancedQueries: ",i)}}getAdvancedQueries$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getAdvancedQueries$","color: green;"),this.advancedQueries$.asObservable()}getAdvancedQueries(){return this.loggingService.log("%c[WB] Calling FUNCTION: getAdvancedQueries","color: green;"),this.advancedQueries$.value}getAdvancedQueriesEnabled$(){return Dn([this.configService.getConfig$(),this.getAdvancedQueries$()]).pipe(ce(()=>this.getAdvancedQueriesEnabled()),Ln(()=>re(!1)))}getAdvancedQueriesEnabled(){try{return!this.configService.getConfig()?.advancedQueriesDisabled&&!!this.getAdvancedQueries()?.advancedQueriesEnabled}catch(e){return this.loggingService.catch("Error in getAdvancedQueriesEnabled: ",e),!1}}signOutPreviousUser(){return this.signOutPreviousUser$.asObservable()}getUser(){return this.loggingService.log("%c[WB] Calling FUNCTION: getUser","color: green;"),this.afAuth?.currentUser?this.user$.value:null}getUser$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getUser$","color: green;"),Wn(this.afAuth).pipe(ge(e=>e?this.user$.asObservable():re(null)))}getAuthUser(){return this.loggingService.log("%c[WB] Calling FUNCTION: getAuthUser","color: green;"),this.afAuth?.currentUser}getUserOptions(){return this.loggingService.log("%c[WB] Calling FUNCTION: getUserOptions","color: green;"),this.userOptions$.value}getUserOptions$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getUserOptions$","color: green;"),this.userOptions$.asObservable()}updateUser(e){this.loggingService.log("%c[WB] Calling FUNCTION: updateUser","color: green;");try{let i=this.user$.value;if(e.userId&&e.userId!==i?.userId||e?.groupId&&e?.groupId!==i?.groupId||e?.organizationId&&e?.organizationId!==i?.organizationId)this.providedUser=e,this.initializeClient(e,this.userOptions$?.value||{},new Date().getTime(),void 0,"internal-updateUser");else if(this.providedUser=I(I({},this.providedUser),e),i){let r=I(I({},i),e);this.updateUserInternally(r)}}catch(i){this.loggingService.catch("Error in updateUser: ",i)}}signInWithCustomToken(e,i,r="manual"){this.loggingService.log("%c[WB] Calling FUNCTION: signInWithCustomToken","color: green;");try{return gQ(this.afAuth,i).then(a=>(this.analyticsService.trackEvent(Z.Events.Core.SDK_USER_AUTH_SUCCESS,{apiKey:this.apiKey,clientUserId:e.userId,snippylyUserId:e.userSnippylyId,authType:r,forceReset:this.userOptions$.value?.forceReset,user:this.getUserWithoutContacts(e)}),a)).catch(a=>(this.analyticsService.trackEvent(Z.Events.Core.SDK_USER_AUTH_FAILED,{apiKey:this.apiKey,clientUserId:e.userId,snippylyUserId:e.userSnippylyId,authType:r,forceReset:this.userOptions$.value?.forceReset,message:a.message,user:this.getUserWithoutContacts(e)}),a))}catch(a){return this.loggingService.catch("Error in signInWithCustomToken: ",a),Promise.reject(a)}}resetServicesCache(){this.loggingService.log("%c[WB] Calling FUNCTION: resetServicesCache in AuthService","color: green;");try{this.commonDbService?.unsubscribeFromObservables(),this.docService?.clearCache(),this.contactService?.clearCache(),this.iamService?.clearCache(),this.areaService?.clearCache(),this.commentService?.clearCache(),this.reactionService?.clearCache(),this.recorderAnnotationService?.clearCache(),this.viewsService?.clearCache()}catch(e){this.loggingService.catch("Error in resetServicesCache: ",e)}}initializeSignedInUser(e,i){this.loggingService.log("%c[WB] Calling FUNCTION: initializeSignedInUser","color: green;");try{let r=new wo;r.userSnippylyId=e.uid,r.type="signedIn",this.mergeUserWithProvidedUserData(r,i)}catch(r){this.loggingService.catch("Error in initializeSignedInUser: ",r)}}mergeUserWithProvidedUserData(e,i){return ee(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: mergeUserWithProvidedUserData","color: green;");try{e.userId=this.providedUser?.userId||e.userId;let r=null;if(this.usersService?.userDataProviderAvailable()){let a=yield this.usersService.resolveUsers([e.userId]);a&&a[e.userId]&&(r=JSON.parse(JSON.stringify(a[e.userId]||{}))),e=I(I({},e),r||{})}e.name=r?r?.name:this.providedUser?.name||e.name,e.clientUserName=r?r?.clientUserName:this.providedUser?.clientUserName||e.clientUserName,e.photoUrl=r?r?.photoUrl:this.providedUser?.photoUrl||e.photoUrl,e?.photoUrl===void 0&&(e.photoUrl=null),e.email=r?r?.email:this.providedUser?.email||e.email,e.color=r?r?.color:this.providedUser?.color||this.avatarService.generateUserColor(fn(e.userId)),e.textColor=r?r?.textColor:this.providedUser?.textColor||"#FFFFFF",e.initial=r?r?.initial:this.providedUser?.initial||e.initial||e.name?.charAt(0).toUpperCase()||e.email?.charAt(0).toUpperCase(),e.contacts=this.providedUser?.contacts||e.contacts,e.plan=this.providedUser?.plan||e.plan,e.groupId=this.providedUser?.groupId||e.groupId,e.clientGroupId=this.providedUser?.clientGroupId||e.clientGroupId,e.clientOrganizationId=this.providedUser?.clientOrganizationId||e.clientOrganizationId,e.organizationId=this.providedUser?.organizationId||e.organizationId,e.isAdmin=this.providedUser?.isAdmin,e.isReadOnly=this.providedUser?.isReadOnly,e.isAnonymous=this.providedUser?.isAnonymous,e.isGuest=this.providedUser?.isGuest,this.updateUserInternally(e)}catch(r){this.loggingService.catch("Error in mergeUserWithProvidedUserData: ",r)}})}updateUserInternally(e){return ee(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: updateUserInternally","color: green;");try{let i=Object.assign({},e);delete i.contacts,this.analyticsService.identifyUser(e.userSnippylyId,i,{forceReset:this.userOptions$.value?.forceReset}),this.getPlanDetailsCalled||(yield this.getPlanDetailsFromDb()),this.afAuth.currentUser&&(this.user$.next(e),this.updateUserToFirebase(e))}catch(i){this.loggingService.catch("Error in updateUserInternally: ",i)}})}updateUserToFirebase(e){this.loggingService.log("%c[WB] Calling FUNCTION: updateUserToFirebase","color: green;");try{let i=JSON.parse(JSON.stringify(e)),r=T(I({},i),{lastUpdated:new Date})}catch(i){this.loggingService.catch("Error in updateUserToFirebase: ",i)}}getPlanDetailsFromDb(){return ee(this,null,function*(){try{this.getPlanDetailsCalled=!0;let i=yield Cr(this.functions,Zn.cloudFunction.getPlanDetails,{timeout:20*60*1e3})({apiKey:this.configService.getApiKey(),sdkVersion:Ta(),sdkType:this.configService.getSdkType()});return i?.data?.isPlanExpired&&(this.analyticsService.trackEvent(Z.Events.Core.SDK_PLAN_EXPIRED),this.configService.getSF()||console.warn("Velt SDK plan has expired.")),this.planDetails$.next(i?.data||{planInfo:null,isPlanExpired:!1}),i}catch(e){return this.loggingService.catch("Error in getPlanDetailsFromDb: ",e),this.planDetails$.next({planInfo:null,isPlanExpired:!1}),Promise.resolve(null)}})}isPlanExpired$(){return this.planDetails$.pipe(Ne(e=>!!e),ce(e=>!!e?.isPlanExpired))}isPlanExpired(){return this.planDetails$.getValue()?.isPlanExpired}addPreSignOutFuction(e,i){try{this.preSignOutFunctions.set(e,i)}catch(r){this.loggingService.catch("Error in addPreSignOutFuction: ",r)}}setUserOrganization(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setUserOrganization","color: green;");let i=JSON.parse(JSON.stringify(this.userOrganization$.value||{}));this.getUser()?.organizationId===e?.organizationId?(i.metadata=e,this.userOrganization$.next(i)):this.userOrganization$.next(null)}catch(i){this.loggingService.catch("Error in setUserOrganization: ",i)}}setOrganizationUserGroups(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setUserOrganizationGroups","color: green;");let i=JSON.parse(JSON.stringify(this.userOrganization$.value||{}));this.getUser()?.organizationId===i?.metadata?.organizationId&&(i.groups=e,this.userOrganization$.next(i))}catch(i){this.loggingService.catch("Error in setUserOrganizationGroups: ",i)}}getUserOrganization$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getUserOrganization$","color: green;"),this.getUser$().pipe(ge(e=>e?this.userOrganization$.asObservable().pipe(ce(i=>i?.metadata?.organizationId===e.organizationId?i:null)):re(null)))}signOutUser(e="internal"){return ee(this,null,function*(){try{yield this.analyticsService.trackEvent(Z.Events.Core.SDK_USER_SIGN_OUT,{apiKey:this.apiKey,clientUserId:this.user$?.value?.userId,snippylyUserId:this.user$?.value?.userSnippylyId,message:e==="external"?"User Sign out":"System Sign out",user:this.user$?.value?this.getUserWithoutContacts(this.user$?.value):null,forceReset:this.userOptions$.value?.forceReset,source:e});let i=yield Wn(this.afAuth).pipe(Je(1)).toPromise().catch(r=>null);if(i){this.user$.next(null);for(let[r,a]of this.preSignOutFunctions)try{yield a(i)}catch(s){this.loggingService.catch(`Error in signOutUser ${r} function: `,s)}return this.resetServicesCache(),this.user$.next(null),uQ(this.afAuth).catch(r=>{this.loggingService.catch("Error in signOutUser:",r)})}else return Promise.resolve()}catch(i){this.loggingService.catch("Error in signOutUser: ",i)}})}isFeatureAllowed(e){return Xi(this.config,this.user$.value,e)}getUserWithoutContacts(e){try{if(e){let i=JSON.parse(JSON.stringify(e));return delete i.contacts,i}else return null}catch(i){return this.loggingService.catch("Error in getUserWithoutContacts: ",i),null}}getUserForClient(e){try{return aS(e)}catch(i){return this.loggingService.catch("Error in getUserForClient: ",i),null}}};o.\u0275fac=function(i){return new(i||o)(J(vi),J($t),J(gm),J(Np),J(Fe),J(Vo),J(Qe),J(y))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var xd=class{constructor({apiKey:o,documentId:t,organizationId:e,clientDocumentId:i,clientOrganizationId:r}){this.paths={},this.apiKey=o,this.documentId=t,this.organizationId=e,this.clientDocumentId=i,this.clientOrganizationId=r,i&&(this.documentId=ud(i)),r&&(this.organizationId=hd(r)),this.generateDocumentPaths()}generateDocumentPaths(){try{if(this.paths.clientDocumentId=this.clientDocumentId,this.paths.documentId=this.documentId,this.organizationId&&(this.paths.organizationId=this.organizationId,this.paths.clientOrganizationId=this.clientOrganizationId),this.apiKey){let o=`${this.apiKey}`;this.organizationId&&(o=`${o}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${this.paths.organizationId}`),this.documentId&&(this.paths.docs=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/`,this.paths.presence=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_PRESENCE}/`,this.paths.cursor=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_CURSOR}/`,this.paths.comment=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_COMMENT}/`,this.paths.multiThread=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_MULTI_THREAD}/`,this.paths.tag=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_TAG}/`,this.paths.area=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_AREA}/`,this.paths.arrow=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_ARROW}/`,this.paths.selection=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_SELECTION}/`,this.paths.audioHuddle=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_AUDIO_HUDDLE}/`,this.paths.huddle=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_HUDDLE}/`,this.paths.recorder=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_RECORDER}/`,this.paths.flock=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_FOLLOW_ALONG}/`,this.paths.syncVideoPlayer=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_SYNC_VIDEO_PLAYER}/`,this.paths.liveState=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_LIVE_STATE}/`,this.paths.liveStateSingleEditorMode=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_LIVE_STATE}/default/singleEditorMode`,this.paths.reaction=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_REACTION}/`,this.paths.views=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_VIEWS}/`,this.paths.notifications=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_NOTIFICATIONS}/`,this.paths.metadata=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_METADATA}/`,this.paths.users=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_USERS}/`,this.paths.documentIam=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_IAM}/`),this.paths.customerMetadata=`${o}/${U.FIREBASE_PARTIAL_PATH_CUSTOMER_METADATA}/`,this.paths.groupContacts=`${o}/${U.FIREBASE_PARTIAL_PATH_CONTACTS}/${U.FIREBASE_PARTIAL_PATH_GROUPS}/`,this.paths.globalContacts=`${o}/${U.FIREBASE_PARTIAL_PATH_CONTACTS}/${U.FIREBASE_PARTIAL_PATH_GLOBAL}/`,this.paths.logins=`${o}/${U.FIREBASE_PARTIAL_PATH_CONTACTS}/${U.FIREBASE_PARTIAL_PATH_LOGINS}/`,this.paths.userFeedback=`${o}/${U.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${U.FIREBASE_PARTIAL_PATH_FEEDBACK}/`,this.paths.userReportBugs=`${o}/${U.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${U.FIREBASE_PARTIAL_PATH_BUGS}/`,this.paths.userContactUs=`${o}/${U.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${U.FIREBASE_PARTIAL_PATH_CONTACT_US}/`,this.organizationId&&(this.paths.organizationMetadata=`${o}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_METADATA}/`,this.paths.organizationIam=`${o}/${U.FIREBASE_PARTIAL_PATH_IAM}/`,this.paths.organizationGroups=`${o}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_GROUPS}/`,this.paths.organizationNotifications=`${o}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/`,this.documentId&&(this.paths.organizationNotificationsWithDocumentId=`${o}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/`),this.paths.organizationNotificationsLastNotificationTimestamp=`${o}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${U.FIREBASE_PARTIAL_PATH_LAST_NOTIFICATION_TIMESTAMP}/${U.FIREBASE_PARTIAL_PATH_DOCS}/`,this.paths.organizationNotificationsUsers=`${o}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${U.FIREBASE_PARTIAL_PATH_USERS}/`),this.paths.workspaceIam=`${this.apiKey}/${U.FIREBASE_PARTIAL_PATH_IAM}/`}}catch{}}get workspaceIam(){return this.paths.workspaceIam?this.paths.workspaceIam:this.throwError("Workspace IAM path is not available.")}get docs(){return this.paths.docs?this.paths.docs:this.throwError("Docs path is not available.")}get presence(){return this.paths.presence?this.paths.presence:this.throwError("Presence path is not available.")}get cursor(){return this.paths.cursor?this.paths.cursor:this.throwError("Cursor path is not available.")}get area(){return this.paths.area?this.paths.area:this.throwError("Area path is not available.")}get arrow(){return this.paths.arrow?this.paths.arrow:this.throwError("Arrow path is not available.")}get comment(){return this.paths.comment?this.paths.comment:this.throwError("Comment path is not available.")}get multiThread(){return this.paths.multiThread?this.paths.multiThread:this.throwError("Multi thread path is not available.")}get tag(){return this.paths.tag?this.paths.tag:this.throwError("Tag path is not available.")}get selection(){return this.paths.selection?this.paths.selection:this.throwError("Selection path is not available.")}get audioHuddle(){return this.paths.audioHuddle?this.paths.audioHuddle:this.throwError("Audio huddle path is not available.")}get huddle(){return this.paths.huddle?this.paths.huddle:this.throwError("Huddle path is not available.")}get recorder(){return this.paths.recorder?this.paths.recorder:this.throwError("Recorder path is not available.")}get flock(){return this.paths.flock?this.paths.flock:this.throwError("Flock path is not available.")}get syncVideoPlayer(){return this.paths.syncVideoPlayer?this.paths.syncVideoPlayer:this.throwError("Sync video player path is not available.")}get liveState(){return this.paths.liveState?this.paths.liveState:this.throwError("Live state path is not available.")}get liveStateSingleEditorMode(){return this.paths.liveStateSingleEditorMode?this.paths.liveStateSingleEditorMode:this.throwError("Live state single editor mode path is not available.")}get reaction(){return this.paths.reaction?this.paths.reaction:this.throwError("Reaction path is not available.")}get views(){return this.paths.views?this.paths.views:this.throwError("Views path is not available.")}get notifications(){return this.paths.notifications?this.paths.notifications:this.throwError("Notifications path is not available.")}get metadata(){return this.paths.metadata?this.paths.metadata:this.throwError("Metadata path is not available.")}get users(){return this.paths.users?this.paths.users:this.throwError("Users path is not available.")}get documentIam(){return this.paths.documentIam?this.paths.documentIam:this.throwError("Document IAM path is not available.")}get organizationMetadata(){return this.paths.organizationMetadata?this.paths.organizationMetadata:this.throwError("Organization metadata path is not available.")}get organizationIam(){return this.paths.organizationIam?this.paths.organizationIam:this.throwError("Organization IAM path is not available.")}get customerMetadata(){return this.paths.customerMetadata?this.paths.customerMetadata:this.throwError("Customer metadata path is not available.")}get groupContacts(){return this.paths.groupContacts?this.paths.groupContacts:this.throwError("Group contacts path is not available.")}get globalContacts(){return this.paths.globalContacts?this.paths.globalContacts:this.throwError("Global contacts path is not available.")}get logins(){return this.paths.logins?this.paths.logins:this.throwError("Logins path is not available.")}get userFeedback(){return this.paths.userFeedback?this.paths.userFeedback:this.throwError("User feedback path is not available.")}get userReportBugs(){return this.paths.userReportBugs?this.paths.userReportBugs:this.throwError("User report bugs path is not available.")}get userContactUs(){return this.paths.userContactUs?this.paths.userContactUs:this.throwError("User contact us path is not available.")}get organizationGroups(){return this.paths.organizationGroups?this.paths.organizationGroups:this.throwError("Organization groups path is not available.")}get organizationNotifications(){return this.paths.organizationNotifications?this.paths.organizationNotifications:this.throwError("Organization notifications path is not available.")}get organizationNotificationsWithDocumentId(){return this.paths.organizationNotificationsWithDocumentId?this.paths.organizationNotificationsWithDocumentId:this.throwError("Organization notifications with document id path is not available.")}get organizationNotificationsUsers(){return this.paths.organizationNotificationsUsers?this.paths.organizationNotificationsUsers:this.throwError("Organization notifications users path is not available.")}get organizationNotificationsLastNotificationTimestamp(){return this.paths.organizationNotificationsLastNotificationTimestamp?this.paths.organizationNotificationsLastNotificationTimestamp:this.throwError("Organization notifications last notification timestamp path is not available.")}throwError(o){throw{type:"DocumentPaths",message:o,metadata:{apiKey:this.apiKey,documentId:this.documentId,organizationId:this.organizationId}}}};var bM=class{constructor({apiKey:o,documentId:t,organizationId:e,clientDocumentId:i,clientOrganizationId:r,folderId:a,veltFolderId:s}){this.paths={},this.apiKey=o,this.documentId=t,this.organizationId=e,this.veltFolderId=s,i&&(this.documentId=ud(i)),r&&(this.organizationId=hd(r)),a&&(this.folderId=a,this.veltFolderId=hl(a)),this.generateDocumentPaths()}generateDocumentPaths(){try{if(this.paths.clientDocumentId=this.clientDocumentId,this.paths.documentId=this.documentId,this.organizationId&&(this.paths.organizationId=this.organizationId,this.paths.clientOrganizationId=this.clientOrganizationId),this.veltFolderId&&(this.paths.folderId=this.folderId,this.paths.veltFolderId=this.veltFolderId),this.apiKey){let o=`apiKey/${this.apiKey}`;this.organizationId&&(o=`${o}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${this.paths.organizationId}`,this.paths.organization=o,this.paths.folder=`${o}/${U.FIREBASE_PARTIAL_PATH_FOLDERS}`,this.paths.organizationUsers=`${o}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_USERS}`,this.paths.notificationDocs=`${o}/${U.FIREBASE_PARTIAL_PATH_NOTIFICATION_DOCS}`,this.paths.notificationUsers=`${o}/${U.FIREBASE_PARTIAL_PATH_NOTIFICATION_USERS}`,this.paths.organizationGroups=`${o}/${U.FIREBASE_PARTIAL_PATH_GROUPS}`,this.paths.lastNotificationTimestamp=`${o}/${U.FIREBASE_PARTIAL_PATH_LAST_NOTIFICATION_TIMESTAMP}`),this.veltFolderId&&(this.paths.folderUsers=`${o}/${U.FIREBASE_PARTIAL_PATH_FOLDERS}/${this.veltFolderId}/${U.FIREBASE_PARTIAL_PATH_FOLDER_USERS}`),this.documentId&&(this.paths.document=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}`,this.paths.comment=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_COMMENT}`,this.paths.location=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_LOCATION}`,this.paths.multiThread=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_MULTI_THREAD}`,this.paths.area=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_AREA}`,this.paths.recorder=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_RECORDER}`,this.paths.reaction=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_REACTION}`,this.paths.commentViews=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_COMMENT_VIEWS}`,this.paths.notificationViews=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_NOTIFICATION_VIEWS}`,this.paths.documentViews=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_DOCUMENT_VIEWS}`,this.paths.locationViews=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_LOCATION_VIEWS}`,this.paths.documentUsers=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_DOCUMENT_USERS}`,this.paths.docNotification=`${this.paths.notificationDocs}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_DOC_NOTIFICATION}`)}}catch{}}get folder(){return this.paths.folder?this.paths.folder:this.throwError("Folder path is not available.")}get lastNotificationTimestamp(){return this.paths.lastNotificationTimestamp?this.paths.lastNotificationTimestamp:this.throwError("LastNotificationTimestamp path is not available.")}get organizationGroups(){return this.paths.organizationGroups?this.paths.organizationGroups:this.throwError("organizationGroups path is not available.")}get docNotification(){return this.paths.docNotification?this.paths.docNotification:this.throwError("DocNotification path is not available.")}get organization(){return this.paths.organization?this.paths.organization:this.throwError("Organization path is not available.")}get document(){return this.paths.document?this.paths.document:this.throwError("Document path is not available.")}get location(){return this.paths.location?this.paths.location:this.throwError("Location path is not available.")}get area(){return this.paths.area?this.paths.area:this.throwError("Area path is not available.")}get comment(){return this.paths.comment?this.paths.comment:this.throwError("Comment path is not available.")}get commentViews(){return this.paths.commentViews?this.paths.commentViews:this.throwError("CommentViews path is not available.")}get documentViews(){return this.paths.documentViews?this.paths.documentViews:this.throwError("DocumentViews path is not available.")}get locationViews(){return this.paths.locationViews?this.paths.locationViews:this.throwError("LocationViews path is not available.")}get notificationViews(){return this.paths.notificationViews?this.paths.notificationViews:this.throwError("NotificationViews path is not available.")}get documentUsers(){return this.paths.documentUsers?this.paths.documentUsers:this.throwError("DocumentUsers path is not available.")}get folderUsers(){return this.paths.folderUsers?this.paths.folderUsers:this.throwError("FolderUsers path is not available.")}get organizationUsers(){return this.paths.organizationUsers?this.paths.organizationUsers:this.throwError("OrganizationUsers path is not available.")}get notificationDocs(){return this.paths.notificationDocs?this.paths.notificationDocs:this.throwError("NotificationDocs path is not available.")}get notificationUsers(){return this.paths.notificationUsers?this.paths.notificationUsers:this.throwError("NotificationUsers path is not available.")}get multiThread(){return this.paths.multiThread?this.paths.multiThread:this.throwError("Multi thread path is not available.")}get recorder(){return this.paths.recorder?this.paths.recorder:this.throwError("Recorder path is not available.")}get reaction(){return this.paths.reaction?this.paths.reaction:this.throwError("Reaction path is not available.")}throwError(o){throw{type:"DocumentPaths",message:o,metadata:{apiKey:this.apiKey,documentId:this.documentId,organizationId:this.organizationId}}}};var IM=class{};var pn=(()=>{let o=class o{constructor(e,i){this.authService=e,this.loggingService=i,this.db$=new fe(null);try{this.authService.getFirebaseConfig$().subscribe(r=>{r&&this.db$.next(Df(void 0,r.firebaseOptions.databaseURL))},r=>{this.loggingService.catch("Error in DatabaseService constructor: ",r)})}catch(r){this.loggingService.catch("Error in DatabaseService constructor:",r)}}getDb(){return this.db$.asObservable()}};o.\u0275fac=function(i){return new(i||o)(J(je),J(y))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var vs=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.analyticsService=i,this.resolveTimeout=1*60*1e3,this.retrySaveConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.retryDeleteConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.retryGetConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.commentAnnotationDataProvider$=new fe(null),this.commentAnnotationById$=new fe({}),this.getCommentAnnotationById=r=>{try{return this.commentAnnotationDataProviderAvailable()?this.commentAnnotationById$.value?.[r]:void 0}catch(a){this.loggingService.catch("Error in CommentAnnotationsResolverService getCommentAnnotationById:",a);return}};try{this.loggingService.log("CommentAnnotationsResolverService initialized"),this.commentAnnotationDataProvider$.subscribe(r=>{r&&(r.config?.resolveTimeout&&(this.resolveTimeout=r.config.resolveTimeout),r.config?.saveRetryConfig&&(this.retrySaveConfig=r.config.saveRetryConfig),r.config?.deleteRetryConfig&&(this.retryDeleteConfig=r.config.deleteRetryConfig),r.config?.getRetryConfig&&(this.retryGetConfig=r.config.getRetryConfig))})}catch(r){this.loggingService.catch("Error in CommentAnnotationsResolverService constructor:",r)}}getProvider(){try{let e=this.commentAnnotationDataProvider$.getValue();return e||void 0}catch(e){this.loggingService.catch("Error in CommentAnnotationsResolverService getProvider:",e);return}}ngOnDestroy(){try{this.commentAnnotationById$.next({})}catch(e){this.loggingService.catch("Error in CommentAnnotationsResolverService ngOnDestroy:",e)}}resolveCommentAnnotations(e){return ee(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling CommentAnnotationsResolverService FUNCTION: resolveCommentAnnotations","color: green;"),!this.commentAnnotationDataProviderAvailable())return{};let i,r=!1,a=!1,s=()=>{i&&(clearTimeout(i),i=void 0,a=!0)};return new Promise((c,p)=>{i=setTimeout(()=>{a||(r=!0,s(),p(new Error("Comment annotation resolution timeout")))},this.commentAnnotationDataProvider$.value?.config?.resolveTimeout||this.resolveTimeout);let h=this.getProvider();if(!h)return s(),c({});let _={},E=[...new Set(e.commentAnnotationIds||[])],D=T(I({},e),{commentAnnotationIds:E});ee(this,null,function*(){try{if(E.length>0||e.documentIds?.length||e.folderId){let G=sc(()=>h?.get(D)||Promise.resolve(void 0),"getCommentAnnotations",this.retryGetConfig).then(X=>r?{}:(s(),X&&X.statusCode!==200?(this.loggingService.catch(X?.message??"Error in CommentAnnotationsResolverService resolveCommentAnnotations:"),{}):X?.data)).catch(X=>{throw s(),X});try{_=(yield G)||{},this.analyticsService.trackEvent(Z.Events.Resolver.COMMENT_RESOLVER_GET,{sourceMethod:"resolveCommentAnnotations",source:"sdk",commentAnnotationIds:E});let X={};Object.entries(_).forEach(([he,Ie])=>{let Me=this.commentAnnotationById$.value?.[he];Me?Me&&JSON.stringify(Me)!==JSON.stringify(Ie)&&(X[he]=Ie):X[he]=Ie}),Object.keys(X).length>0&&this.commentAnnotationById$.next(I(I({},this.commentAnnotationById$.getValue()),X)),c(X)}catch(X){r||p(X),c(_)}}else s(),c({})}catch(G){s(),p(G)}})})}catch(i){return this.loggingService.catch("Error in CommentAnnotationsResolverService resolveCommentAnnotations:",i),{}}})}saveCommentAnnotation(e){return ee(this,null,function*(){try{this.loggingService.log("%c[WB] Calling CommentAnnotationsResolverService FUNCTION: saveCommentAnnotation","color: green;");let i=this.getProvider();if(!this.commentAnnotationDataProviderAvailable())throw new Error("Comment annotation save data provider not available");let r=JSON.parse(JSON.stringify(this.commentAnnotationById$.getValue()));this.commentAnnotationById$._value=I(I({},r),e.commentAnnotation);let a=yield sc(()=>i?.save({commentAnnotation:e.commentAnnotation,event:e.eventType,commentId:e.commentId,metadata:Object.values(e.commentAnnotation??{})?.[0]?.metadata})||Promise.resolve(void 0),"saveCommentAnnotation",this.retrySaveConfig);return a&&a.statusCode!==200?(this.retrySaveConfig.revertOnFailure&&(this.commentAnnotationById$._value=r),this.loggingService.catch(a?.message??"Error in CommentAnnotationsResolverService saveCommentAnnotation:"),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(Z.Events.Resolver.COMMENT_RESOLVER_SAVE,{sourceMethod:"saveCommentAnnotation",source:"sdk",commentAnnotationIds:Object.keys(e.commentAnnotation),eventType:e.eventType,commentId:e.commentId}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0})}catch(i){return this.loggingService.warn("Error in CommentAnnotationsResolverService saveCommentAnnotation:",i),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0}}})}deleteCommentAnnotation(e,i){return ee(this,null,function*(){try{this.loggingService.log("%c[WB] Calling CommentAnnotationsResolverService FUNCTION: deleteCommentAnnotation","color: green;");let r=this.getProvider();if(!this.commentAnnotationDataProviderAvailable())throw new Error("Comment annotation delete data provider not available");let a=this.commentAnnotationById$.getValue(),s=I({},a);delete s?.[e],this.commentAnnotationById$._value=s;let c=yield sc(()=>r?.delete({commentAnnotationId:e.toString(),metadata:i,event:Ha.COMMENT_ANNOTATION_DELETE})||Promise.resolve(void 0),"deleteCommentAnnotation",this.retryDeleteConfig);return c&&c.statusCode!==200?(this.retryDeleteConfig.revertOnFailure&&(this.commentAnnotationById$._value=a),this.loggingService.catch(c?.message??"Error in CommentAnnotationsResolverService deleteCommentAnnotation:"),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(Z.Events.Resolver.COMMENT_RESOLVER_DELETE,{sourceMethod:"deleteCommentAnnotation",source:"sdk",commentAnnotationId:e.toString()}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0})}catch(r){return this.loggingService.warn("Error in CommentAnnotationsResolverService deleteCommentAnnotation:",r),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0}}})}getCommentAnnotationsById$(){try{return this.commentAnnotationDataProviderAvailable()?(this.loggingService.log("%c[WB] Calling CommentAnnotationsResolverService FUNCTION: getCommentAnnotationsById$","color: green;"),this.commentAnnotationById$.asObservable()):re(void 0)}catch(e){return this.loggingService.catch("Error in CommentAnnotationsResolverService getCommentAnnotationsById$:",e),re(void 0)}}getAnnotationById(e){try{return this.commentAnnotationDataProviderAvailable()?this.commentAnnotationById$.getValue()?.[e]:void 0}catch(i){this.loggingService.catch("Error in CommentAnnotationsResolverService getAnnotationById:",i);return}}setCommentAnnotationDataProvider(e){try{if(e){this.loggingService.log("Setting comment annotation data provider");let r=["get","save","delete"].filter(a=>!(a in e)||typeof e[a]!="function");if(r.length>0){let a=`DataProviders.comment is invalid. The following methods are missing or are not functions: ${r.join(", ")}.`;this.loggingService.catch(a);return}else this.commentAnnotationDataProvider$.next(e)}}catch(i){this.loggingService.catch("Error in CommentAnnotationsResolverService setCommentAnnotationDataProvider:",i)}}commentAnnotationDataProviderAvailable(){try{return!!this.commentAnnotationDataProvider$.getValue()}catch(e){return this.loggingService.catch("Error in CommentAnnotationsResolverService commentAnnotationDataProviderAvailable:",e),!1}}};o.\u0275fac=function(i){return new(i||o)(J(y),J(Qe))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var um=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.analyticsService=i,this.resolveTimeout=1*60*1e3,this.retrySaveConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.retryDeleteConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.retryGetConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.reactionAnnotationDataProvider$=new fe(null),this.reactionAnnotationById$=new fe({}),this.getReactionAnnotationById=r=>{try{return this.reactionAnnotationDataProviderAvailable()?this.reactionAnnotationById$.value?.[r]:void 0}catch(a){this.loggingService.catch("Error in ReactionAnnotationsResolverService getReactionAnnotationById:",a);return}};try{this.loggingService.log("ReactionAnnotationsResolverService initialized"),this.reactionAnnotationDataProvider$.subscribe(r=>{r&&(r.config?.resolveTimeout&&(this.resolveTimeout=r.config.resolveTimeout),r.config?.saveRetryConfig&&(this.retrySaveConfig=r.config.saveRetryConfig),r.config?.deleteRetryConfig&&(this.retryDeleteConfig=r.config.deleteRetryConfig),r.config?.getRetryConfig&&(this.retryGetConfig=r.config.getRetryConfig))})}catch(r){this.loggingService.catch("Error in ReactionAnnotationsResolverService constructor:",r)}}getProvider(){try{let e=this.reactionAnnotationDataProvider$.getValue();return e||void 0}catch(e){this.loggingService.catch("Error in ReactionAnnotationsResolverService getProvider:",e);return}}ngOnDestroy(){try{this.reactionAnnotationById$.next({})}catch(e){this.loggingService.catch("Error in ReactionAnnotationsResolverService ngOnDestroy:",e)}}resolveReactionAnnotations(e){return ee(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling ReactionAnnotationsResolverService FUNCTION: resolveReactionAnnotations","color: green;"),!this.reactionAnnotationDataProviderAvailable())return{};let i,r=!1,a=!1,s=()=>{i&&(clearTimeout(i),i=void 0,a=!0)};return new Promise((c,p)=>{i=setTimeout(()=>{a||(r=!0,s(),p(new Error("Reaction annotation resolution timeout")))},this.reactionAnnotationDataProvider$.value?.config?.resolveTimeout||this.resolveTimeout);let h=this.getProvider();if(!h)return s(),c({});let _={},E=[...new Set(e.reactionAnnotationIds||[])],D=T(I({},e),{reactionAnnotationIds:E});ee(this,null,function*(){try{if(E.length>0||e.documentIds?.length||e.folderId){let G=sc(()=>h?.get(D)||Promise.resolve(void 0),"getReactionAnnotations",this.retryGetConfig).then(X=>r?{}:(s(),X&&X.statusCode!==200?(this.loggingService.catch(X?.message??"Error in ReactionAnnotationsResolverService resolveReactionAnnotations:"),{}):X?.data)).catch(X=>{throw s(),X});try{_=(yield G)||{},this.analyticsService.trackEvent(Z.Events.Resolver.REACTION_RESOLVER_GET,{sourceMethod:"resolveReactionAnnotations",source:"sdk",reactionAnnotationIds:E});let X={};Object.entries(_).forEach(([he,Ie])=>{let Me=this.reactionAnnotationById$.value?.[he];Me?Me&&JSON.stringify(Me)!==JSON.stringify(Ie)&&(X[he]=Ie):X[he]=Ie}),Object.keys(X).length>0&&this.reactionAnnotationById$.next(I(I({},this.reactionAnnotationById$.getValue()),X)),c(X)}catch(X){r||p(X),c(_)}}else s(),c({})}catch(G){s(),p(G)}})})}catch(i){return this.loggingService.catch("Error in ReactionAnnotationsResolverService resolveReactionAnnotations:",i),{}}})}saveReactionAnnotation(e){return ee(this,null,function*(){try{this.loggingService.log("%c[WB] Calling ReactionAnnotationsResolverService FUNCTION: saveReactionAnnotation","color: green;");let i=this.getProvider();if(!this.reactionAnnotationDataProviderAvailable())throw new Error("Reaction annotation save data provider not available");let r=JSON.parse(JSON.stringify(this.reactionAnnotationById$.getValue()));this.reactionAnnotationById$._value=I(I({},r),e);let a={reactionAnnotation:e,event:Ha.REACTION_ADD,metadata:Object.values(e??{})?.[0]?.metadata},s=yield sc(()=>i?.save(a)||Promise.resolve(void 0),"saveReactionAnnotation",this.retrySaveConfig);return s&&s.statusCode!==200?(this.retrySaveConfig.revertOnFailure&&(this.reactionAnnotationById$._value=r),this.loggingService.catch(s?.message??"Error in ReactionAnnotationsResolverService saveReactionAnnotation:"),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(Z.Events.Resolver.REACTION_RESOLVER_SAVE,{sourceMethod:"saveReactionAnnotation",source:"sdk",reactionAnnotationIds:Object.keys(e),eventType:a.event}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0})}catch(i){return this.loggingService.warn("Error in ReactionAnnotationsResolverService saveReactionAnnotation:",i),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0}}})}deleteReactionAnnotation(e,i){return ee(this,null,function*(){try{this.loggingService.log("%c[WB] Calling ReactionAnnotationsResolverService FUNCTION: deleteReactionAnnotation","color: green;");let r=this.getProvider();if(!this.reactionAnnotationDataProviderAvailable())throw new Error("Reaction annotation delete data provider not available");let a=JSON.parse(JSON.stringify(this.reactionAnnotationById$.getValue())),s=I({},a);delete s?.[e],this.reactionAnnotationById$._value=s;let c=yield sc(()=>r?.delete({reactionAnnotationId:e.toString(),metadata:i,event:Ha.REACTION_DELETE})||Promise.resolve(void 0),"deleteReactionAnnotation",this.retryDeleteConfig);return c&&c.statusCode!==200?(this.retryDeleteConfig.revertOnFailure&&(this.reactionAnnotationById$._value=a),this.loggingService.catch(c?.message??"Error in ReactionAnnotationsResolverService deleteReactionAnnotation:"),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(Z.Events.Resolver.REACTION_RESOLVER_DELETE,{sourceMethod:"deleteReactionAnnotation",source:"sdk",reactionAnnotationId:e.toString()}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0})}catch(r){return this.loggingService.warn("Error in ReactionAnnotationsResolverService deleteReactionAnnotation:",r),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0}}})}getReactionAnnotationsById$(){try{return this.reactionAnnotationDataProviderAvailable()?(this.loggingService.log("%c[WB] Calling ReactionAnnotationsResolverService FUNCTION: getReactionAnnotationsById$","color: green;"),this.reactionAnnotationById$.asObservable()):re(void 0)}catch(e){return this.loggingService.catch("Error in ReactionAnnotationsResolverService getReactionAnnotationsById$:",e),re(void 0)}}getAnnotationById(e){try{return this.reactionAnnotationDataProviderAvailable()?this.reactionAnnotationById$.getValue()?.[e]:void 0}catch(i){this.loggingService.catch("Error in ReactionAnnotationsResolverService getAnnotationById:",i);return}}setReactionAnnotationDataProvider(e){try{if(e){this.loggingService.log("Setting reaction annotation data provider");let r=["get","save","delete"].filter(a=>!(a in e)||typeof e[a]!="function");if(r.length>0){let a=`DataProviders.reaction is invalid. The following methods are missing or are not functions: ${r.join(", ")}.`;this.loggingService.catch(a);return}else this.reactionAnnotationDataProvider$.next(e)}}catch(i){this.loggingService.catch("Error in ReactionAnnotationsResolverService setReactionAnnotationDataProvider:",i)}}reactionAnnotationDataProviderAvailable(){try{return!!this.reactionAnnotationDataProvider$.getValue()}catch(e){return this.loggingService.catch("Error in ReactionAnnotationsResolverService reactionAnnotationDataProviderAvailable:",e),!1}}};o.\u0275fac=function(i){return new(i||o)(J(y),J(Qe))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var lt=(()=>{let o=class o{constructor(e,i,r,a,s,c,p,h){this.analyticsService=e,this.authService=i,this.databaseService=r,this.domService=a,this.configService=s,this.loggingService=c,this.commentResolverService=p,this.reactionResolverService=h,this.documentPaths$=new fe(null),this.documentIds$=new fe([]),this.folderConfig$=new fe(null),this.organizationConfig$=new fe(null),this.firestorePaths$=new fe(null),this.location$=new fe(null),this.excludedLocationIds$=new fe([]),this.organizationMetadata$=new fe(null),this.documentMetadata$=new fe(null),this.locationMetadata$=new fe(null),this.customerMetadata$=new fe(null),this.currentDocumentId=null,this.isCustomDocId=!1,this.locations$=new fe({}),this.preDocumentIdChangeFunctions=new Map,this.draftDocumentId=null,this.clientDocumentMetadataMap={},this.uiState=new fe({}),this.lastSetDocumentIdExecutionTime=0,this.lastSetDocumentIdCallTime=0,this.setDocumentIdSubject=new et,this.DEBOUNCE_TIME=5e3,this.MAX_QUEUE_SIZE=100,this.queueSize=0,this.isDocumentIdInDebounceQueue=!1,this.draftLocationMap={location:null,locations:[]};try{this.loggingService.log("%c[WB] Creating CLASS: DocService","color: blue;"),this.domService.setDocService(this),this.authService.setDocService(this),this.setDocumentIdSubject.pipe(jr(this.DEBOUNCE_TIME)).subscribe({next:_=>{try{this.setDocumentIdImpl(_.documentId,_.clientOrganizationId,_.auto,_.avoidAnalytics,_.options),this.lastSetDocumentIdExecutionTime=Date.now(),this.isDocumentIdInDebounceQueue=!1,this.draftLocationMap.location&&this.setLocation(this.draftLocationMap.location),this.draftLocationMap.locations.length>0&&this.draftLocationMap.locations.forEach(E=>{this.addLocation(E)}),this.draftLocationMap={location:null,locations:[]}}finally{this.queueSize--}},error:_=>{this.loggingService.catch("Error in setDocumentId subscription:",_),this.queueSize--}}),this.databaseService.getDb().pipe(Ne(_=>!!_),Je(1)).subscribe(_=>{_&&(this.db=_)}),this.configService.getApiKey$().subscribe(_=>{if(this.apiKey=_,this.apiKey){if(!this.isCustomDocId){let E=qO(window.location.href);this.currentUrl=E}this.analyticsService.updateDefaultProperties({apiKey:_})}}),this.authService.getUser$().subscribe(_=>{_?(this.analyticsService.updateDefaultProperties({organizationId:_?.organizationId,clientOrganizationId:_?.clientOrganizationId}),this.draftDocumentId?(this.setDocumentId(this.draftDocumentId,this.draftOrganizationId,!1,!1,this.draftFolderConfig),this.draftDocumentId=null,this.draftLocationMap.location&&this.setLocation(this.draftLocationMap.location),this.draftLocationMap.locations.length>0&&this.draftLocationMap.locations.forEach(E=>{this.addLocation(E)}),this.draftLocationMap={location:null,locations:[]},this.draftOrganizationId=void 0,this.draftFolderConfig=void 0):this.documentPaths$?.value&&_?.organizationId&&this.documentPaths$.value?.organizationId!==_?.organizationId&&this.setDocumentId(this.documentPaths$.value?.clientDocumentId),this.updateDocumentLocationMetadata(),setTimeout(()=>{this.documentPaths$.value||this.loggingService.catch("Error in DocService constructor:","Please set document id to continue.")},1e4),_?.organizationId&&_?.clientOrganizationId&&this.organizationConfig$.next({organizationId:_?.organizationId,clientOrganizationId:_?.clientOrganizationId})):(this.organizationMetadataSubscription?.unsubscribe(),this.documentMetadataSubscription?.unsubscribe(),this.customerMetadataSubscription?.unsubscribe(),this.documentPaths$.value&&(this.draftDocumentId=this.documentPaths$.value?.clientDocumentId??null,this.draftFolderConfig=this.folderConfig$.value,this.draftLocationMap={location:this.location$.value?.location??null,locations:Object.values(this.locations$.value||{}).map(E=>E.location)},this.currentDocumentId=null,this.location$.next(null),this.documentPaths$.next(null),this.firestorePaths$.next(null)))}),this.documentPaths$.subscribe(_=>{let E={documentId:_?.documentId,clientDocumentId:_?.clientDocumentId};_?.organizationId&&(E.organizationId=_.organizationId,E.clientOrganizationId=_.clientOrganizationId),this.analyticsService.updateDefaultProperties(E),this.domService.resetSelectedAnnotationsMap()}),this.folderConfig$.subscribe(_=>{this.analyticsService.updateDefaultProperties({folderId:_?.folderId,veltFolderId:_?.veltFolderId,allDocuments:_?.allDocuments})}),this.location$.subscribe(_=>{this.analyticsService.updateDefaultProperties({clientLocation:_?.location,locationId:_?.locationId})}),this.organizationMetadata$.subscribe(_=>{this.authService.setUserOrganization(_?.[this.documentPaths$.value?.organizationId])}),this.organizationConfig$.subscribe(_=>{_&&this.updateOrganizationMetadata()}),this.documentPaths$.pipe(Ne(_=>!!_),Je(1)).subscribe(()=>{try{this.subscribeToCustomerMetadata()}catch(_){this.loggingService.catch("Error in DocService subscribeToCustomerMetadata:",_)}},_=>{this.loggingService.catch("Error in DocService subscribeToCustomerMetadata:",_)}),this.loggingService.log("%c[WB] Creating CLASS: DocService 2","color: blue;"),this.onWindowPopstate(),this.onWindowClick()}catch(_){this.loggingService.catch("Error in DocService constructor:",_)}}clearCache(){this.loggingService.log("%c[WB] Calling FUNCTION: clearCache in DocService","color: green;");try{this.folderConfig$.next(null),this.organizationConfig$.next(null),this.organizationMetadata$.next(null),this.documentMetadata$.next(null),this.locationMetadata$.next(null),this.customerMetadata$.next(null)}catch(e){this.loggingService.catch("Error in DocService clearCache: ",e)}}setCommonDbService(e){try{this.commonDbService=e}catch(i){this.loggingService.catch("Error in setCommonDbService:",i)}}setCommentService(e){try{this.commentService=e}catch(i){this.loggingService.catch("Error in setCommentService:",i)}}onWindowPopstate(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowPopstate","color: green;");try{this.domService.onWindowPopState$().subscribe(()=>{this.loggingService.log("location",location.href);let e=qO(location.href);this.currentUrl!==e&&(this.currentUrl=e,!this.isCustomDocId&&this.apiKey&&this.loggingService.log("current url in doc service",this.currentUrl))},e=>{this.loggingService.catch("Error in DocService onWindowPopstate subscription: ",e)})}catch(e){this.loggingService.catch("Error in onWindowPopstate: ",e)}}onWindowClick(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowClick","color: green;");try{this.domService.onWindowClick$().subscribe(()=>{let e=qO(location.href);this.currentUrl!==e&&(this.currentUrl=e,this.isCustomDocId||this.loggingService.log("current url in doc service",this.currentUrl))},e=>{this.loggingService.catch("Error in DocService onWindowClick subscription: ",e)})}catch(e){this.loggingService.catch("Error in onWindowClick: ",e)}}setDocument(e,i){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocument","color: green;"),this.documentIds$.value?.length&&this.documentIds$.next([]);let r=i?.organizationId;this.setDocumentId(e,r,!1,!0),i&&(i.organizationId&&delete i.organizationId,this.clientDocumentMetadata={clientDocumentId:e,documentMetadata:i},this.updateDocumentMetadata()),this.analyticsService.trackEvent(Z.Events.Doc.DOCUMENT_SET,{documentId:e,documentMetadata:i},!0,this.getUserIdForAnalytics())}catch(r){this.loggingService.catch("Error in DocService setDocument:",r)}}shouldSetDocumentsAgain(e,i={}){try{this.loggingService.log("%c[WB] Calling FUNCTION: shouldSetDocumentsAgain","color: green;");let r=this.documentIds$.value.map(c=>c.clientDocumentId),a=this.folderConfig$.value??{};return!e.every(c=>r.includes(c.id))||!Co(a,i)}catch(r){return this.loggingService.catch("Error in DocService shouldSetDocumentsAgain:",r),!0}}setDocuments(e,i){try{if(!this.shouldSetDocumentsAgain(e,i)){this.loggingService.warn("setDocuments called with previous request");return}let r=[];if(e.forEach(a=>{let s=a.id,c=`${fn(s)}`;a?.metadata&&typeof a.metadata=="object"&&(this.clientDocumentMetadataMap[s]=a.metadata),r.push({documentId:c,clientDocumentId:s})}),r?.length===0){this.loggingService.warn("Minimum one document must be set in setDocuments");return}this.documentIds$.next(r),e?.length&&this.setDocumentId(e[0]?.id,i?.organizationId,!1,!1,i),this.analyticsService.trackEvent(Z.Events.Doc.DOCUMENTS_SET,{documentIds:r,options:i},!0,this.getUserIdForAnalytics())}catch(r){this.loggingService.catch("Error in DocService setDocuments:",r)}}setDocumentId(e,i,r=!1,a=!1,s){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocumentId","color: green;"),this.folderConfig$.value&&this.folderConfig$.next(null);let c=Date.now(),p=c-this.lastSetDocumentIdCallTime,h=c-this.lastSetDocumentIdExecutionTime;if(this.lastSetDocumentIdCallTime=c,this.queueSize>=this.MAX_QUEUE_SIZE){this.loggingService.warn("SetDocumentId queue size exceeded limit");return}if(!this.documentPaths$.value&&!this.isDocumentIdInDebounceQueue||p>this.DEBOUNCE_TIME&&h>this.DEBOUNCE_TIME){this.setDocumentIdImpl(e,i,r,a,s),this.lastSetDocumentIdExecutionTime=c;return}this.documentPaths$.next(null),this.isDocumentIdInDebounceQueue=!0,this.draftLocationMap={location:null,locations:[]},this.queueSize++,this.setDocumentIdSubject.next({documentId:e,clientOrganizationId:i,auto:r,avoidAnalytics:a})}catch(c){this.loggingService.catch("Error in setDocumentId:",c)}}setDocumentIdImpl(e,i,r=!1,a=!1,s){this.loggingService.log("%c[WB] Calling FUNCTION: setDocumentIdImpl","color: green;");try{r||(this.isCustomDocId=!0);let c=this.authService.getUser();if(!c){this.draftDocumentId=e,this.draftOrganizationId=i,this.draftFolderConfig=s;return}(s?.folderId||s?.locationId)&&this.folderConfig$.next({folderId:s?.folderId,allDocuments:s?.allDocuments,locationId:s?.locationId,veltFolderId:s?.folderId?hl(s?.folderId):void 0}),this.currentDocumentId&&this.documentPaths$.value&&this.callPreDocumentIdChangeFunctions(this.documentPaths$.value);let p=this.currentDocumentId;if(this.apiKey){let h=`${fn(e)}`,_=c?.organizationId?i?Rt(i):c?.organizationId:void 0;if(this.commentResolverService.resolveCommentAnnotations({documentIds:this.documentIds$.value.map(E=>E.clientDocumentId),organizationId:i??c?.clientOrganizationId??""}),this.reactionResolverService.resolveReactionAnnotations({documentIds:this.documentIds$.value.map(E=>E.clientDocumentId),organizationId:i??c?.clientOrganizationId??""}),_&&this.documentPaths$.value?.organizationId&&_!==this.documentPaths$.value?.organizationId){let E=this.getFolderConfig();this.authService.resetServicesCache(),E&&this.folderConfig$.next(E)}if(this.currentDocumentId!==h||this.documentPaths$.value?.organizationId!==_){this.loggingService.log("setting new docid"),this.currentDocumentId=h;let E=new aM,D=new IM;E.clientDocumentId=e,D.clientDocumentId=e,E.documentId=h,D.documentId=h,_&&(E.organizationId=_,E.clientOrganizationId=i??c?.clientOrganizationId,D.organizationId=_,D.clientOrganizationId=i??c?.clientOrganizationId);let B=`${this.apiKey}`,G=`apiKey/${this.apiKey}`;_&&(B=`${B}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${E.organizationId}`,G=`${G}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${E.organizationId}`),D.organization=`apiKey/${this.apiKey}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}`,D.document=`${G}/${U.FIREBASE_PARTIAL_PATH_DOCS}`,E.presence=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_PRESENCE}/`,E.cursor=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_CURSOR}/`,E.comment=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_COMMENT}/`,D.comment=`${G}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_COMMENT}`,E.multiThread=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_MULTI_THREAD}/`,D.multiThread=`${G}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_MULTI_THREAD}`,E.tag=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_TAG}/`,E.area=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_AREA}/`,D.area=`${G}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_AREA}`,E.arrow=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_ARROW}/`,E.selection=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_SELECTION}/`,E.audioHuddle=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_AUDIO_HUDDLE}/`,E.huddle=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_HUDDLE}/`,E.recorder=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_RECORDER}/`,D.recorder=`${G}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_RECORDER}`,E.flock=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_FOLLOW_ALONG}/`,E.syncVideoPlayer=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_SYNC_VIDEO_PLAYER}/`,E.liveState=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_LIVE_STATE}/`,E.liveStateSingleEditorMode=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_LIVE_STATE}/default/singleEditorMode`,E.reaction=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_REACTION}/`,D.reaction=`${G}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_REACTION}`,E.customerMetadata=`${this.apiKey}/${U.FIREBASE_PARTIAL_PATH_CUSTOMER_METADATA}/`,E.views=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_VIEWS}/`,D.commentViews=`${G}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_COMMENT_VIEWS}`,D.notificationViews=`${G}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_NOTIFICATION_VIEWS}`,D.documentViews=`${G}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_DOCUMENT_VIEWS}`,D.locationViews=`${G}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_LOCATION_VIEWS}`,E.notifications=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_NOTIFICATIONS}/`,E.metadata=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_METADATA}/`,E.users=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_USERS}/`,E.documentIam=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_IAM}/`,E.workspaceIam=`${this.apiKey}/${U.FIREBASE_PARTIAL_PATH_IAM}/`,E.groupContacts=`${B}/${U.FIREBASE_PARTIAL_PATH_CONTACTS}/${U.FIREBASE_PARTIAL_PATH_GROUPS}/`,E.globalContacts=`${B}/${U.FIREBASE_PARTIAL_PATH_CONTACTS}/${U.FIREBASE_PARTIAL_PATH_GLOBAL}/`,E.logins=`${B}/${U.FIREBASE_PARTIAL_PATH_CONTACTS}/${U.FIREBASE_PARTIAL_PATH_LOGINS}/`,E.userFeedback=`${B}/${U.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${U.FIREBASE_PARTIAL_PATH_FEEDBACK}/`,E.userReportBugs=`${B}/${U.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${U.FIREBASE_PARTIAL_PATH_BUGS}/`,E.userContactUs=`${B}/${U.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${U.FIREBASE_PARTIAL_PATH_CONTACT_US}/`,_&&(E.organizationMetadata=`${B}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_METADATA}/`,E.organizationIam=`${B}/${U.FIREBASE_PARTIAL_PATH_IAM}/`,E.organizationGroups=`${B}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_GROUPS}/`,E.organizationNotifications=`${B}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/`,h&&(E.organizationNotificationsWithDocumentId=`${B}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/`),E.organizationNotificationsLastNotificationTimestamp=`${B}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${U.FIREBASE_PARTIAL_PATH_LAST_NOTIFICATION_TIMESTAMP}/${U.FIREBASE_PARTIAL_PATH_DOCS}/`,E.organizationNotificationsUsers=`${B}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${U.FIREBASE_PARTIAL_PATH_USERS}/`),D.organizationUsers=`${G}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_USERS}`,D.documentUsers=`${G}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_DOCUMENT_USERS}`,D.notificationDocs=`${G}/${U.FIREBASE_PARTIAL_PATH_NOTIFICATION_DOCS}`,D.notificationUsers=`${G}/${U.FIREBASE_PARTIAL_PATH_NOTIFICATION_USERS}`,this.documentPaths$.next(E),this.firestorePaths$.next(D),E?.clientOrganizationId&&E?.organizationId&&!(E?.clientOrganizationId===this.organizationConfig$?.value?.clientOrganizationId&&E?.organizationId===this.organizationConfig$?.value?.organizationId)&&this.organizationConfig$.next({organizationId:E?.organizationId,clientOrganizationId:E?.clientOrganizationId}),this.updateFolderMetadata(),this.updateDocumentMetadata(),this.getLocationMetadata(),p&&this.location$.value&&this.removeLocation(),a||this.analyticsService.trackEvent(Z.Events.Doc.DOCUMENT_ID_SET,{documentId:h,clientDocumentId:e},!0,this.getUserIdForAnalytics())}return h}else this.loggingService.catch("Error in setDocumentIdImpl: API key is not provided.")}catch(c){this.loggingService.catch("Error in setDocumentIdImpl: ",c)}}unsetDocumentId(e="internal"){this.loggingService.log("%c[WB] Calling FUNCTION: unsetDocumentId","color: green;");try{this.analyticsService.trackEvent(Z.Events.Doc.DOCUMENT_UNSET,{documentId:this.currentDocumentId,documentMetadata:this.documentMetadata$.value?.[this.currentDocumentId??""],message:e==="external"?"User unset document id":"System unset document id",source:e},!0,this.getUserIdForAnalytics()),this.currentDocumentId&&this.documentPaths$.value&&this.callPreDocumentIdChangeFunctions(this.documentPaths$.value),this.currentDocumentId=null,this.documentPaths$.next(null),this.firestorePaths$.next(null),this.location$.next(null),this.excludedLocationIds$.next([]),this.documentMetadata$.next(null),this.locationMetadata$.next(null),this.customerMetadata$.next(null),this.locations$.next({})}catch(i){this.loggingService.catch("Error in unsetDocumentId: ",i)}}unsetDocuments(e="internal"){this.loggingService.log("%c[WB] Calling FUNCTION: unsetDocuments","color: green;");try{this.unsetDocumentId(e),this.documentIds$.next([])}catch(i){this.loggingService.catch("Error in unsetDocuments: ",i)}}addPreDocumentIdChangeFunction(e,i){try{this.loggingService.log("%c[WB] Calling FUNCTION: addPreDocumentIdChangeFunction","color: green;"),this.preDocumentIdChangeFunctions.set(e,i)}catch(r){this.loggingService.catch("Error in addPreDocumentIdChangeFunction: ",r)}}callPreDocumentIdChangeFunctions(e){return ee(this,null,function*(){try{this.loggingService.log("%c[WB] Calling FUNCTION: callPreDocumentIdChangeFunctions","color: green;");for(let[i,r]of this.preDocumentIdChangeFunctions)try{yield r(e)}catch(a){this.loggingService.catch("Error in callPreDocumentIdChangeFunctions: ",a)}}catch(i){this.loggingService.catch("Error in callPreDocumentIdChangeFunctions: ",i)}})}subscribeToOrganizationMetadata(){this.loggingService.log("%c[WB] Calling FUNCTION: subscribeToOrganizationMetadata","color: green;");try{if(this.organizationMetadataSubscription&&this.organizationMetadataSubscription.unsubscribe(),this.db&&this.authService.getUser()?.organizationId){let e=this.organizationConfig$.value?.organizationId;this.commonDbService?.getData({feature:"organizationMetadata",properties:{apiKey:this.apiKey??"",organizationId:e,field:"metadata"}}).then(i=>{i&&this.organizationMetadata$.next(T(I({},this.organizationMetadata$.value),{[e]:i}))}).catch(i=>{this.loggingService.catch("Error in subscribeToOrganizationMetadata: ",i)})}}catch(e){this.loggingService.catch("Error in subscribeToOrganizationMetadata: ",e)}}subscribeToDocumentMetadata(e){try{if(this.documentMetadataSubscription&&this.documentMetadataSubscription.unsubscribe(),this.db&&this.authService.getUser()){let i=this.documentPaths$.value,r=this.documentMetadata$.value;if(e=e.filter(a=>!r?.[a.documentId]),e?.some(a=>!a?.documentId||!a?.clientDocumentId)||!i)return;if(this.commonDbService?.shouldUseFirestore()){let a=this.getFolderConfig()?.folderId,s=this.getFolderConfig()?.allDocuments,c=[],p={organizationId:i?.clientOrganizationId,folderId:a,allDocuments:s};if(a&&s)c.push(this.fetchDocuments(p));else{let _=[];for(let D=0;D<e.length;D+=20)_.push(e.slice(D,D+20));_.forEach(D=>{let B=JSON.parse(JSON.stringify(p));B.documentIds=D.map(G=>G.clientDocumentId),c.push(this.fetchDocuments(B))})}let h={};c.length>0&&Promise.all(c).then(_=>{_?.forEach(E=>{E?.forEach(D=>{D?.metadata?.documentId&&(h[D.metadata.documentId]=D.metadata)})}),this.documentMetadata$.next(I(I({},this.documentMetadata$.value),h))}).catch(_=>{this.loggingService.catch("Error in subscribeToDocumentMetadata: ",_)})}else r?.[i?.documentId??e?.[0]?.documentId]||this.commonDbService?.queryData({feature:"allDocuments",properties:{apiKey:this.apiKey??"",organizationId:i?.organizationId,documentId:i?.documentId??e?.[0]?.documentId,skipObjectValues:!0}}).then(a=>{a?.documentId&&this.documentMetadata$.next({[a.documentId]:a})}).catch(a=>{this.loggingService.catch("Error in subscribeToDocumentMetadata: ",a)})}}catch(i){this.loggingService.catch("Error in subscribeToDocumentMetadata: ",i)}}getLocationMetadata(){try{if(this.db&&this.authService.getUser()){let e=this.documentPaths$.value,i=this.documentIds$.value,r=this.getFolderConfig()?.folderId,a=this.getFolderConfig()?.allDocuments,s=[],c={organizationId:e?.clientOrganizationId,folderId:r,allDocuments:a};if(r&&a)s.push(this.fetchLocations(c));else{let h=[];for(let E=0;E<i.length;E+=20)h.push(i.slice(E,E+20));h.forEach(E=>{let D=JSON.parse(JSON.stringify(c));D.documentIds=E.map(B=>B.clientDocumentId),s.push(this.fetchLocations(D))})}let p=this.locationMetadata$.value??{};s.length>0&&Promise.all(s).then(h=>{h?.forEach(_=>{_?.forEach(E=>{E?.metadata?.documentId&&(p[E.metadata.documentId]=T(I({},p?.[E.metadata.documentId]??{}),{[E.location.id]:E}))})}),Object.keys(p||{}).length>0&&this.locationMetadata$.next(p)}).catch(h=>{this.loggingService.catch("Error in getLocationMetadata: ",h)})}}catch(e){this.loggingService.catch("Error in getLocationMetadata: ",e)}}getLocationMetadatas(){return this.locationMetadata$.value}subscribeToCustomerMetadata(){this.loggingService.log("%c[WB] Calling FUNCTION: subscribeToCustomerMetadata","color: green;");try{if(this.customerMetadataSubscription)return;this.db&&this.authService.getUser()&&this.documentPaths$.value&&(this.customerMetadataSubscription=this.commonDbService?.dbListener({feature:"customerMetadata",properties:{skipFirestore:!0}}).pipe(Ln(i=>re(null))).subscribe(i=>{this.customerMetadata$.next(i?.data)}))}catch(e){this.loggingService.catch("Error in subscribeToCustomerMetadata: ",e)}}getDocumentId(){return this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentId","color: green;"),this.documentPaths$.value?.documentId}getClientDocumentId(){return this.loggingService.log("%c[WB] Calling FUNCTION: getClientDocumentId","color: green;"),this.documentPaths$.value?.clientDocumentId}getDocumentIds$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentIds$","color: green;"),this.documentIds$.asObservable().pipe(ce(e=>e?.slice()))}getFolderConfig$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getFolderConfig$","color: green;"),this.folderConfig$.asObservable()}getDocumentIds(){return this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentIds","color: green;"),this.documentIds$.value?.slice()}getFolderConfig(){return this.loggingService.log("%c[WB] Calling FUNCTION: getFolderConfig","color: green;"),this.folderConfig$.value}getLocationMetadata$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getLocationMetadata$","color: green;"),this.locationMetadata$.asObservable().pipe()}getDocumentPaths$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentPaths$","color: green;"),this.documentPaths$.asObservable()}getFirestorePaths$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getFirestorePaths$","color: green;"),this.firestorePaths$.asObservable()}getDocumentPaths(){return this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentPaths","color: green;"),this.documentPaths$.value}generateDocumentId(e){try{return`${fn(e)}`}catch(i){return this.loggingService.catch("Error in generateDocumentId: ",i),""}}generateOrganizationId(e){try{return`${Rt(e)}`}catch(i){return this.loggingService.catch("Error in generateOrganizationId: ",i),""}}getFirestorePaths(){return this.loggingService.log("%c[WB] Calling FUNCTION: getFirestorePaths","color: green;"),this.firestorePaths$.value}setLocation(e){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: setLocationImpl","color: green;"),e&&typeof e=="object"){if(e?.version&&(!e?.version?.id||!e?.version?.name)){this.loggingService.catch("Error in setLocationImpl: ","If you're setting version then add id and name fields to version object.");return}let i=Xo(e),r=fn(JSON.stringify(i));this.location$.next({locationId:r,location:i}),this.isDocumentIdInDebounceQueue&&(this.draftLocationMap.location=e),this.updateDocumentLocationMetadata().then(()=>{this.analyticsService.trackEvent(Z.Events.Doc.LOCATION_SET,{location:i,locationId:r},!0,this.getUserIdForAnalytics())})}}catch(i){this.loggingService.catch("Error in setLocationImpl: ",i)}}removeLocation(e,i="internal"){try{if(this.analyticsService.trackEvent(Z.Events.Doc.LOCATION_UNSET,{location:this.location$.value?.location,locationId:this.location$.value?.locationId,message:i==="external"?"User removed location":"System removed location",source:i},!0,this.getUserIdForAnalytics()),e){let r=this.genarateLocationId(e);this.getLocation()?.locationId===r&&(this.location$.next(null),i!=="internal"&&(this.draftLocationMap.location=null)),this.removeCustomLocation(e)}else this.location$.next(null),this.locations$.next({}),i!=="internal"&&(this.draftLocationMap.location=null,this.draftLocationMap.locations=[])}catch(r){this.loggingService.catch("Error in removeLocation: ",r)}}getLocation$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getLocation$","color: green;"),this.location$.asObservable()}getLocation(){return this.loggingService.log("%c[WB] Calling FUNCTION: getLocation$","color: green;"),this.location$.value?JSON.parse(JSON.stringify(this.location$.value)):null}excludeLocationIds(e){try{this.excludedLocationIds$.next([...e])}catch(i){this.loggingService.catch("Error in excludeLocationIds: ",i)}}getExcludedLocationIds$(){try{return this.excludedLocationIds$.asObservable()}catch(e){return this.loggingService.catch("Error in getExcludedLocationIds$: ",e),re([])}}updateOrganizationMetadata(){try{if(this.db&&this.authService.getUser()?.organizationId){let e=this.documentPaths$.value,i=this.organizationConfig$.value?.organizationId;if(!this.organizationMetadata$.value?.[i]){let a=new CM;a.apiKey=this.configService?.getApiKey()??"",a.organizationId=i,a.clientOrganizationId=this.organizationConfig$.value?.clientOrganizationId,this.commonDbService?.updateData({feature:"organizationMetadata",data:JSON.parse(JSON.stringify(a)),properties:{organizationId:i,documentId:e?.documentId??""}}),this.subscribeToOrganizationMetadata()}}}catch(e){this.loggingService.catch("Error in updateOrganizationMetadata: ",e)}}updateFolderMetadata(){return ee(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: updateFolderMetadata","color: green;"),this.db&&this.authService.getUser()&&this.folderConfig$.value){let e=this.documentPaths$.value,i=this.folderConfig$.value;if(!(yield this.commonDbService?.getData({feature:"folderMetadata",properties:{organizationId:e?.organizationId??"",folderId:i?.veltFolderId??""}}))?.metadata){let a={folderId:i?.folderId,veltFolderId:i?.veltFolderId,apiKey:this.configService?.getApiKey()??"",organizationId:e?.organizationId,clientOrganizationId:e?.clientOrganizationId,createdAt:Date.now(),lastUpdated:Date.now(),parentFolderId:"root",veltParentFolderId:"root"};this.commonDbService?.updateData({feature:"folderMetadata",data:JSON.parse(JSON.stringify({metadata:a})),properties:{organizationId:e?.organizationId??"",folderId:i?.veltFolderId??""}})}}}catch(e){this.loggingService.catch("Error in updateFolderMetadata: ",e)}})}updateDocumentMetadata(){return ee(this,null,function*(){try{if(this.db&&this.authService.getUser()){let e=this.documentPaths$.value;if(e){let i=this.getDocumentIds();i.find(a=>a.documentId===e.documentId)||i.push({documentId:e.documentId??"",clientDocumentId:e.clientDocumentId??""});let r=i.map(a=>ee(this,null,function*(){let s=new rM;this.clientDocumentMetadata&&(this.clientDocumentMetadata?.clientDocumentId===e.clientDocumentId&&this.clientDocumentMetadata?.documentMetadata&&(s=I(I({},this.clientDocumentMetadata.documentMetadata),s)),this.clientDocumentMetadata=void 0),this.clientDocumentMetadataMap?.[a.clientDocumentId]&&(s=I(I({},this.clientDocumentMetadataMap[a.clientDocumentId]),s)),s.apiKey=this.configService?.getApiKey()??"",s.documentId=a.documentId,s.clientDocumentId=a.clientDocumentId,s.organizationId=e.organizationId,s.clientOrganizationId=e.clientOrganizationId,s.pageInfo=_i();let c=this.getFolderConfig();s?.pageInfo?.deviceInfo&&delete s?.pageInfo?.deviceInfo;let p=!0,h=this.documentMetadata$.value?.[a.documentId];if(c){let _=yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:a?.documentId??"",organizationId:e?.organizationId??"",field:"metadata"}});_?.clientDocumentId?_?.folderId&&(_?.folderId!==c?.folderId||_?.veltFolderId!==c?.veltFolderId)?(this.loggingService.catch(`Folder id mismatch for document ${a?.clientDocumentId??""}`),p=!1):_?.folderId===c?.folderId?(c?.folderId&&(s.folderId=c.folderId),c?.veltFolderId&&(s.veltFolderId=c.veltFolderId)):(this.loggingService.catch(`Document ${a?.clientDocumentId??""} is not in the folder ${c?.folderId??""}`),p=!1):(c?.folderId&&(s.folderId=c.folderId),c?.veltFolderId&&(s.veltFolderId=c.veltFolderId))}if(h){let _={};Object.entries(s).forEach(([E,D])=>{_[E]=D}),Co(_,h)&&(p=!1)}p&&(yield this.commonDbService?.updateData({feature:"documentMetadata",data:JSON.parse(JSON.stringify(s)),properties:{organizationId:e?.organizationId??"",documentId:a?.documentId??""}}))}));yield Promise.all(r),this.subscribeToDocumentMetadata(i)}}}catch(e){this.loggingService.catch("Error in updateDocumentMetadata: ",e)}})}updateDocumentLocationMetadata(){return ee(this,null,function*(){try{if(this.db&&this.authService.getUser()){let e=this.documentPaths$.value,i=this.location$.value;if(e&&i){let r=this.getDocumentIds();r.find(a=>a.documentId===e.documentId)||r.push({documentId:e.documentId??"",clientDocumentId:e.clientDocumentId??""});for(let a of r){let s=yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:a?.documentId??"",organizationId:e?.organizationId??"",field:"metadata"}}),c=new mM;c.locationId=i?.locationId,c.veltLocationId=uV(i?.location?.id??""),c.location=i?.location,c.pageInfo=_i(),c?.pageInfo?.deviceInfo&&delete c?.pageInfo?.deviceInfo;let p=T(I({},s),{[U.FIREBASE_PARTIAL_PATH_LOCATIONS]:T(I({},s[U.FIREBASE_PARTIAL_PATH_LOCATIONS]??{}),{[i?.locationId]:c})}),h=T(I({},c),{metadata:I({},this.getBaseMetadata()??{})});this.commonDbService?.updateData({feature:"documentMetadata",data:JSON.parse(JSON.stringify(p)),properties:{documentId:a?.documentId??"",organizationId:e?.organizationId??""}}),this.commonDbService?.updateData({feature:"locationMetadata",data:JSON.parse(JSON.stringify(h)),properties:{documentId:a?.documentId??"",organizationId:e?.organizationId??"",id:c.veltLocationId}});let _=this.locationMetadata$.value;if(_||(_={}),i?.location?.id){let E=_?.[a.documentId],D=E?.[i?.location?.id??""];_&&(E||(_[a.documentId]={}),D||(_[a.documentId][i?.location?.id??""]={}),_[a.documentId][i?.location?.id??""]=T(I({},D),{location:i?.location})),Object.keys(_||{}).length>0&&this.locationMetadata$.next(_)}}}}}catch(e){this.loggingService.catch("Error in updateDocumentLocationMetadata: ",e)}})}genarateLocationId(e){try{return e&&typeof e=="object"?fn(JSON.stringify(Xo(e))):0}catch(i){return this.loggingService.catch("Error in genarateLocationId: ",i),0}}addLocation(e){try{let i=null;if(e&&typeof e=="object"){if(e?.version&&(!e?.version?.id||!e?.version?.name)){this.loggingService.catch("Error in setLocation: ","If you're setting version then add id and name fields to version object.");return}let r=I({},e),a=this.locations$.value;e?.id&&Object.keys(a).forEach(p=>{let h=a[p];h.location?.id===e.id&&(r=I(I({},h.location),e),delete a[p])});let s=this.genarateLocationId(r),c={locationId:s,location:r};i=c,this.locations$.next(T(I({},a),{[s]:c})),this.isDocumentIdInDebounceQueue&&this.draftLocationMap.locations.push(r),this.analyticsService.trackEvent(Z.Events.Doc.LOCATION_ADDED,{addedLocation:e,addedLocationId:s},!0,this.getUserIdForAnalytics())}return i}catch(i){return this.loggingService.catch("Error in DocService addLocation:",i),null}}removeCustomLocation(e,i="internal"){try{let r=this.genarateLocationId(e),a=this.locations$.value;a[r]&&(delete a[r],this.locations$.next(I({},a)),i!=="internal"&&this.isDocumentIdInDebounceQueue&&(this.draftLocationMap.locations=this.draftLocationMap.locations.filter(s=>s.id!==e.id)))}catch(r){this.loggingService.catch("Error in DocService removeLocation:",r)}}getLocationByClientLocationId(e){try{let i=this.getLocation()?.location;if(i?.id===e)return i;{let r=this.getLocations();Object.keys(r).forEach(a=>{let s=r[a];s.location?.id===e&&(i=s.location)})}return i}catch(i){this.loggingService.catch("Error in DocService getLocationByClientLocationId:",i);return}}removeLocationIfNotInDom(){try{let e=this.locations$.value,i=document.querySelectorAll(`[${U.ATTRIBUTES.VELT_LOCATION}]`),r=[];i.forEach(a=>{let s=a.getAttribute(U.ATTRIBUTES.VELT_LOCATION);if(s){let c=JSON.parse(s),p=this.genarateLocationId(c);r.push(p)}}),Object.keys(e).forEach(a=>{let s=e[a];r.includes(s.locationId)||delete e[a]}),this.locations$.next(I({},e))}catch(e){this.loggingService.catch("Error in DocService removeLocationIfNotInDom:",e)}}getLocations$(){try{return this.locations$.asObservable()}catch(e){return this.loggingService.catch("Error in DocService getLocations$:",e),re({})}}getLocations(){try{return this.locations$.value}catch(e){return this.loggingService.catch("Error in DocService getLocations:",e),{}}}getLocationFromElement(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: getLocationFromElement","color: green;");let i=null;if(e?.getAttribute(U.ATTRIBUTES.VELT_LOCATION)?i=e:i=e.closest(`[${U.ATTRIBUTES.VELT_LOCATION}]`),i){let r=i?.getAttribute(U.ATTRIBUTES.VELT_LOCATION);if(r){let a=JSON.parse(r);return{locationId:this.genarateLocationId(a),location:a}}}return null}catch(i){return this.loggingService.catch("Error in DocService getLocationFromElement:",i),null}}getElementMapWithLocation(){try{this.loggingService.log("%c[WB] Calling FUNCTION: getElementMapWithLocation","color: green;");let e={};return document.querySelectorAll(`[${U.ATTRIBUTES.VELT_LOCATION}], [${U.ATTRIBUTES.VELT_LOCATION_ID}]`).forEach(r=>{if(r.getAttribute(U.ATTRIBUTES.VELT_LOCATION)){let a=this.getLocationFromElement(r);a?.locationId&&(e[a.locationId]={element:r,location:a})}else if(r.getAttribute(U.ATTRIBUTES.VELT_LOCATION_ID)){let a=r.getAttribute(U.ATTRIBUTES.VELT_LOCATION_ID);if(a){let s=this.getLocationByClientLocationId(a);s?.locationId&&(e[s.locationId]={element:r,location:s});let c={id:a},p=this.genarateLocationId(c);e[a]={element:r,location:{locationId:p,location:c}}}}}),e}catch(e){return this.loggingService.catch("Error in DocService getElementMapWithLocation:",e),{}}}getAdditionLocationFromElement(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: getAdditionLocationFromElement","color: green;");let i;if(i=e?.closest(`[${U.ATTRIBUTES.VELT_LOCATION}], [${U.ATTRIBUTES.VELT_LOCATION_ID}]`),i){if(i?.getAttribute(U.ATTRIBUTES.VELT_LOCATION)){let r=i?.getAttribute(U.ATTRIBUTES.VELT_LOCATION);if(r)return JSON.parse(r)}else if(i?.getAttribute(U.ATTRIBUTES.VELT_LOCATION_ID)){let r=i?.getAttribute(U.ATTRIBUTES.VELT_LOCATION_ID);if(r)return{id:r}}}return null}catch(i){return this.loggingService.catch("Error in DocService getAdditionLocationFromElement:",i),null}}getAdditionalDocumentIdFromElement(e){try{return e?.closest(`[${U.ATTRIBUTES.VELT_DOCUMENT_ID}]`)?.getAttribute(U.ATTRIBUTES.VELT_DOCUMENT_ID)||null}catch(i){return this.loggingService.catch("Error in DocService getAdditionalDocumentIdFromElement:",i),null}}getDocumentMetadata(e){try{return e?this.documentMetadata$.value?.[e]||null:this.documentMetadata$.value?.[this.documentPaths$.value?.documentId??""]||null}catch(i){return this.loggingService.catch("Error in DocService getDocumentMetadata:",i),null}}getAllDocumentMetadata(){try{return Object.values(this.documentMetadata$.value||{})}catch(e){return this.loggingService.catch("Error in DocService getAllDocumentMetadata:",e),[]}}getDocumentMetadataOfAvailableDocuments(){try{this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentMetadataOfAvailableDocuments","color: green;");let e=this.documentMetadata$.value||{},i={},r=this.getFolderConfig();if(r?.veltFolderId&&r?.allDocuments)Object.values(e).forEach(a=>{a?.documentId&&a?.veltFolderId===r?.veltFolderId&&(i[a.documentId]=a)});else{let a=this.documentIds$.value;if(a?.length)a.forEach(s=>{let c=e?.[s.documentId];c&&(i[s.documentId]=c)});else if(this.documentPaths$.value?.documentId){let s=e?.[this.documentPaths$.value?.documentId];s&&(i[this.documentPaths$.value?.documentId]=s)}}return Object.values(i)}catch(e){return this.loggingService.catch("Error in DocService getDocumentMetadataOfAvailableDocuments:",e),[]}}getDocumentMetadata$(e){return this.documentMetadata$.asObservable().pipe(ce(i=>i?.[e??this.documentPaths$.value?.documentId??""]||null))}getOrganizationMetadata(e){return this.organizationMetadata$.value?.[e]||null}getOrganizationMetadata$(e){return this.organizationMetadata$.asObservable().pipe(ce(i=>i?.[e]||null))}getCustomerMetadata(){return this.customerMetadata$.value}getCustomerMetadata$(){return this.customerMetadata$.asObservable()}getOrganizationConfig$(){return this.organizationConfig$.asObservable()}getOrganizationConfig(){return this.organizationConfig$.value}getMetadataFromType(e,i){try{switch(e){case"area":return;case"comment":return i?.multiThreadAnnotationId?this.commentService?.getMultiThreadAnnotationById(i.multiThreadAnnotationId)?.metadata:void 0;case"reaction":case"recorder":return i?.commentAnnotationId?this.commentService?.getAnnotationById(i.commentAnnotationId)?.metadata:void 0;default:return}}catch(r){this.loggingService.catch("Error in DocService getMetadataFromType:",r);return}}getDefaultMetadata({clientDocumentId:e,documentId:i}){try{let r=this.documentPaths$.value;if(!r)return;let a=e||r.clientDocumentId,s=i||r.documentId,c=this.getDocumentMetadata(s);if(!c)return;let p=c?.folderId,h=c?.veltFolderId;return I(I({apiKey:this.configService.getApiKey()??void 0,clientDocumentId:a,clientOrganizationId:r.clientOrganizationId,documentId:s,organizationId:r.organizationId},p?{folderId:p}:{}),h?{veltFolderId:h}:{})}catch(r){this.loggingService.catch("Error in DocService getDefaultMetadata:",r);return}}getBaseMetadata(e,i){try{let r,a;i?.element?r=this.getAdditionalDocumentIdFromElement(i.element)||void 0:i?.clientDocumentId&&(r=i.clientDocumentId),r&&(a=this.generateDocumentId(r));let s=this.getMetadataFromType(e,i),c=this.getDefaultMetadata({clientDocumentId:r,documentId:a});return s||c||{}}catch(r){return this.loggingService.catch("Error in DocService getBaseMetadata:",r),{}}}getServerId({documentId:e,organizationId:i}){try{return e&&(e=this.generateDocumentId(e)),i&&(i=this.generateOrganizationId(i)),{documentId:e,organizationId:i}}catch(r){return this.loggingService.catch("Error in DocService getServerId:",r),null}}fetchDocuments(e){return ee(this,null,function*(){try{if(!this.authService.getUser())return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),[];let r=[];if(!e?.organizationId)return this.loggingService.catch("Error in fetchDocuments: organizationId is required"),[];if(e?.folderId){let s=hl(e?.folderId);r.push(mt("metadata.veltFolderId","==",s))}return e?.documentIds?.length&&!e?.allDocuments&&r.push(mt("metadata.documentId","in",e?.documentIds?.map(s=>this.generateDocumentId(s)).slice(0,30))),yield this.commonDbService?.queryData({feature:"allDocuments",properties:{firestoreQuery:r,apiKey:this.apiKey??"",organizationId:this.generateOrganizationId(e?.organizationId)??this.documentPaths$.value?.organizationId,documentId:this.documentPaths$.value?.documentId}})}catch(i){return this.loggingService.catch("Error in DocService fetchDocuments:",i),[]}})}fetchLocations(e){return ee(this,null,function*(){try{if(!this.authService.getUser())return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),[];let r=[];if(!e?.organizationId)return this.loggingService.catch("Error in fetchLocations: organizationId is required"),[];if(e?.folderId){let s=hl(e?.folderId);r.push(mt("metadata.veltFolderId","==",s))}return e?.documentIds?.length&&!e?.allDocuments&&r.push(mt("metadata.documentId","in",e?.documentIds?.map(s=>this.generateDocumentId(s)).slice(0,30))),yield this.commonDbService?.queryData({feature:"allLocations",properties:{firestoreQuery:r,apiKey:this.apiKey??"",organizationId:this.generateOrganizationId(e?.organizationId)??this.documentPaths$.value?.organizationId,documentId:this.documentPaths$.value?.documentId}})}catch(i){return this.loggingService.catch("Error in DocService fetchLocations:",i),[]}})}updateDocuments(e){return ee(this,null,function*(){try{if(!this.authService.getUser())return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),[];let{organizationId:r,documents:a}=e;if(!r&&(r=this.documentPaths$.value?.clientOrganizationId,!r))return this.loggingService.catch("Error in updateDocuments: organizationId is required"),[];if(!a||a.length===0)return this.loggingService.catch("Error in updateDocuments: documents is required"),[];let s=[],c=this.documentMetadata$.value;a.forEach(p=>{delete p?.organizationId,delete p?.clientDocumentId,delete p?.clientOrganizationId,delete p?.apiKey;let h=ud(p.documentId),_=c?.[h];_&&(c[h]=I(I({},_),p)),p&&this.commonDbService&&s.push(this.commonDbService.updateData({feature:"documentMetadata",data:JSON.parse(JSON.stringify(p)),properties:{organizationId:hd(r),documentId:h}}))}),yield Promise.all(s),this.documentMetadata$.next(c)}catch(i){return this.loggingService.catch("Error in DocService updateDocuments:",i),[]}})}updateLocations(e){return ee(this,null,function*(){try{if(!this.authService.getUser())return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),[];let{organizationId:r,locations:a,documentIds:s}=e;if((!s||s.length===0)&&(s=this.documentIds$.value.map(_=>_.clientDocumentId)??[],s.length===0))return this.loggingService.catch("Error in updateLocations: documentId is required"),[];if(!r&&(r=this.documentPaths$.value?.clientOrganizationId,!r))return this.loggingService.catch("Error in updateLocations: organizationId is required"),[];if(!a||a.length===0)return this.loggingService.catch("Error in updateLocations: locations is required"),[];let c=s.map(_=>ud(_)),p=[],h=this.locationMetadata$.value;h||(h={}),c.forEach(_=>{a.forEach(E=>{let D=this.location$.value;if(E?.id===D?.location?.id&&this.location$.next({locationId:D?.locationId,location:E}),E?.id){delete E?.metadata;let B=uV(E.id),G=h?.[_],X=G?.[E.id];h&&(G||(h[_]={}),X||(h[_][E.id]={}),h[_][E.id]=T(I({},X),{location:E})),E&&this.commonDbService&&p.push(this.commonDbService.updateData({feature:"locationMetadata",data:JSON.parse(JSON.stringify({location:E})),properties:{organizationId:hd(r),documentId:_,id:B}}))}})}),yield Promise.all(p),Object.keys(h||{}).length>0&&this.locationMetadata$.next(h)}catch(i){return this.loggingService.catch("Error in DocService updateLocations:",i),[]}})}fetchFolders(e){return ee(this,null,function*(){try{if(!this.authService.getUser())return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),[];let r=[];if(!e?.organizationId)return this.loggingService.catch("Error in fetchFolders: organizationId is required"),{data:[],parentFolders:[]};let a=[],s=this.generateOrganizationId(e?.organizationId);if(e?.folderId){let c=hl(e?.folderId);r=yield this.commonDbService?.getData({feature:"folder",properties:{folderId:c,apiKey:this.apiKey??"",organizationId:s,documentId:this.documentPaths$.value?.documentId}}),r&&(r=[r]),a=yield this.commonDbService?.queryData({feature:"allFolders",properties:{firestoreQuery:[mt("metadata.veltParentFolderId","==",c)],folderId:c,apiKey:this.apiKey??"",organizationId:s,documentId:this.documentPaths$.value?.documentId}})}else r=yield this.commonDbService?.queryData({feature:"allFolders",properties:{apiKey:this.apiKey??"",organizationId:s,documentId:this.documentPaths$.value?.documentId}});return{data:r,parentFolders:a}}catch(i){return this.loggingService.catch("Error in DocService getFoldersRequest:",i),{data:[],parentFolders:[]}}})}getDocumentIam$(){return this.authService.getUser$().pipe(ge(e=>e?this.documentPaths$.pipe(ge(i=>i?.documentIam?this.commonDbService?.dbListener({feature:"documentIam",properties:{documentId:i.documentId,organizationId:i.organizationId,isCollection:!1}}).pipe(ce(r=>r?.data?.docIamConfig??r?.data),Kt((r,a)=>JSON.stringify(r??{})===JSON.stringify(a??{}))):re(null))):re(null)))}getDocumentAccessType(e){try{return e&&e.features&&e.features.all?e.features.all.restricted?di.RESTRICTED:di.PUBLIC:e&&e.documentAccessType?e.documentAccessType:di.PUBLIC}catch(i){return this.loggingService.catch("Error in DocService getDocumentAccessType:",i),di.PUBLIC}}changeDocumentAccessType(e){return ee(this,null,function*(){try{let i=this.documentPaths$.value;if(i){let r=yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:i?.documentId??"",organizationId:i?.organizationId??"",field:"docIamConfig"}});switch(delete r.documentAccessType,r.features||(r.features={}),r.features.all||(r.features.all={}),e){case di.PUBLIC:r.features.all.restricted=!1;break;case di.RESTRICTED:r.features.all.restricted=!0,r.features.all.guestMode=!1;break;default:break}this.commonDbService?.updateData({feature:"documentAccessType",data:JSON.parse(JSON.stringify(r)),properties:{documentId:i?.documentId??"",organizationId:i?.organizationId??""}})}}catch(i){this.loggingService.catch("Error in DocService changeDocumentAccessType:",i)}})}getUserIdForAnalytics(){try{return this.authService?.getAuthUser()?.uid||this.configService?.getApiKey()||""}catch(e){return this.loggingService.catch("Error in DocService getUserIdForAnalytics:",e),""}}setUIState(e){try{this.uiState.next(I(I({},this.uiState.value),e))}catch(i){this.loggingService.catch("Error in DocService setUIState:",i)}}getUIState$(){return this.uiState.asObservable()}};o.\u0275fac=function(i){return new(i||o)(J(Qe),J(je),J(pn),J(Fe),J($t),J(y),J(vs),J(um))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Hn=(()=>{let o=class o{constructor(e,i,r,a){this.analyticsService=e,this.authService=i,this.docService=r,this.loggingService=a,this.defaultUserDataProvider={get:s=>ee(this,null,function*(){return{}})},this.resolveTimeout=1*60*1e3,this.maxResolveAttempts=1,this.resolveAttempts=new Map,this.subscriptions=new ln,this.userDataProvider$=new fe(null),this.userById$=new fe({}),this.userByIdCalled$=new fe({}),this.pendingResolutions=new Set,this.getUserById=s=>{try{return this.userById$.value?.[s]}catch(c){this.loggingService.catch("Error in UsersService getUserById:",c);return}};try{this.analyticsService.setUserService(this),this.authService.setUsersService(this)}catch(s){this.loggingService.catch("Error in UsersService constructor:",s)}}ngOnDestroy(){try{this.subscriptions.unsubscribe(),this.pendingResolutions.clear(),this.resolveAttempts.clear()}catch(e){this.loggingService.catch("Error in UsersService ngOnDestroy:",e)}}resolveUsers(e,i=!1){return ee(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling UsersService FUNCTION: resolveUsers","color: green;"),this.userDataProvider$.getValue()){let r={},a=[],s={};if(e?.forEach(c=>{let p=this.getUserById(c);p?r[c]=p:this.userByIdCalled$.getValue()[c]?i&&a.push(c):(a.push(c),this.userByIdCalled$.next(T(I({},this.userByIdCalled$.getValue()),{[c]:!0})))}),a.length>0){let c=this.userDataProvider$.getValue();if(c){let p={};try{let h,_=new Promise((E,D)=>{h=setTimeout(()=>{D(new Error("User resolution timeout"))},this.userDataProvider$.getValue()?.resolveTimeout||this.resolveTimeout)});p=yield Promise.race([c.get(a).finally(()=>{clearTimeout(h)}),_]),this.analyticsService.trackEvent(Z.Events.Resolver.USER_RESOLVER_GET,{sourceMethod:"resolveUsers",source:"sdk",userIds:a})}catch(h){this.loggingService.catch("Error in UsersService resolveUsers getUsers:",h,{userIds:a})}finally{a?.forEach(h=>{p[h]||(p[h]={userId:h,name:`User ${h}`})})}Object.entries(p).forEach(([h,_])=>{_&&(r[h]=p?.[h],s[h]=p?.[h])})}}return Object.keys(s).length>0&&this.userById$.next(I(I({},this.userById$.getValue()),s)),r}else return{}}catch(r){return this.loggingService.catch("Error in UsersService resolveUsers:",r),{}}})}subscribeToDocuments(){return this.docService.getDocumentIds$().pipe(In(e=>ee(this,null,function*(){let i=yield this.getUsersFromCentralDb({documentIds:e?.map(r=>r.documentId)});this.resolveUsers(i)})))}getUsersFromCentralDb(i){return ee(this,arguments,function*({documentIds:e}){try{return new Promise(r=>{r(["customuser1","customuser2","customuser3"])})}catch{return[]}})}getUserById$(){try{return this.loggingService.log("%c[WB] Calling UsersService FUNCTION: getUserById$","color: green;"),this.userById$.asObservable()}catch(e){return this.loggingService.catch("Error in UsersService getUserById$:",e),re({})}}setUserDataProvider(e){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setUserDataProvider","color: green;"),this.userDataProvider$.next(e)}catch(i){this.loggingService.catch("Error in UsersService setUserDataProvider:",i)}}userDataProviderAvailable(){try{return this.loggingService.log("%c[WB] Calling UsersService FUNCTION: userDataProviderAvailable","color: green;"),!!this.userDataProvider$.getValue()}catch(e){return this.loggingService.catch("Error in UsersService userDataProviderAvailable:",e),!1}}};o.\u0275fac=function(i){return new(i||o)(J(Qe),J(je),J(lt),J(y))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var ase=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.usersService=i}getUserIdsToResolveFromAreaAnnotations(e){try{this.loggingService.log("%c[WB] Calling AreaUtilsService FUNCTION: getUserIdsToResolveFromAreaAnnotations","color: green;");let i=new Set;for(let r of e)r?.from?.userId&&i.add(r?.from?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in AreaUtilsService getUserIdsToResolveFromAreaAnnotations:",i),[]}}mergeAreaWithUser(e){try{if(this.loggingService.log("%c[WB] Calling AreaUtilsService FUNCTION: mergeAreaWithUser","color: green;"),e?.from?.userId){let i=this.usersService.getUserById(e?.from?.userId);i&&(e.from=i)}return e}catch(i){return this.loggingService.catch("Error in AreaUtilsService mergeAreaWithUser:",i),e}}formatAreaData(e){try{return this.loggingService.log("%c[WB] Calling AreaUtilsService FUNCTION: formatAreaData","color: green;"),this.usersService.userDataProviderAvailable()&&e?.from?.userId&&(e.from={userId:e.from.userId}),e}catch(i){return this.loggingService.catch("Error in AreaUtilsService formatAreaData:",i),e}}};o.\u0275fac=function(i){return new(i||o)(J(y),J(Hn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var sse=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.usersService=i}getUserIdsToResolveFromArrowAnnotations(e){try{this.loggingService.log("%c[WB] Calling ArrowUtilsService FUNCTION: getUserIdsToResolveFromArrowAnnotations","color: green;");let i=new Set;for(let r of e)r?.from?.userId&&i.add(r?.from?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in ArrowUtilsService getUserIdsToResolveFromArrowAnnotations:",i),[]}}mergeArrowWithUser(e){try{if(this.loggingService.log("%c[WB] Calling ArrowUtilsService FUNCTION: mergeArrowWithUser","color: green;"),e?.from?.userId){let i=this.usersService.getUserById(e?.from?.userId);i&&(e.from=i)}return e}catch(i){return this.loggingService.catch("Error in ArrowUtilsService mergeArrowWithUser:",i),e}}formatArrowData(e){try{return this.loggingService.log("%c[WB] Calling ArrowUtilsService FUNCTION: formatArrowData","color: green;"),this.usersService.userDataProviderAvailable()&&e?.from?.userId&&(e.from={userId:e.from.userId}),e}catch(i){return this.loggingService.catch("Error in ArrowUtilsService formatArrowData:",i),e}}};o.\u0275fac=function(i){return new(i||o)(J(y),J(Hn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Fp=class{static getFirestoreProdDbName(o,t){return t?.storeDbId??(this.isTestingDb(t?.databaseURL??"")?"sdktest":`apikey${o.toLowerCase()}`)}static isTestingDb(o){try{return o.includes("-test")}catch(t){return pt.error("Error in isTestingDb:",t),!1}}};var Lp=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.analyticsService=i,this.retrySaveConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.retryDeleteConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.attachmentDataProvider$=new fe(null);try{this.loggingService.log("AttachmentResolverService initialized"),this.attachmentDataProvider$.subscribe(r=>{r&&(r.config?.saveRetryConfig&&(this.retrySaveConfig=r.config.saveRetryConfig),r.config?.deleteRetryConfig&&(this.retryDeleteConfig=r.config.deleteRetryConfig))})}catch(r){this.loggingService.catch("Error in AttachmentResolverService constructor:",r)}}getProvider(){try{let e=this.attachmentDataProvider$.getValue();return e||void 0}catch(e){this.loggingService.catch("Error in AttachmentResolverService getProvider:",e);return}}saveAttachment(e){return ee(this,null,function*(){try{this.loggingService.log("%c[WB] Calling AttachmentResolverService FUNCTION: saveAttachment","color: green;");let i=this.getProvider();if(!this.attachmentDataProviderAvailable())throw new Error("Attachment save data provider not available");let r=yield sc(()=>i?.save({attachment:e.attachment,event:e.eventType,metadata:e.attachment.metadata})||Promise.resolve(void 0),"saveAttachment",this.retrySaveConfig);if(r?.statusCode!==200){this.loggingService.catch(r?.message??"Error in AttachmentResolverService saveAttachment:");return}return this.analyticsService.trackEvent(Z.Events.Resolver.ATTACHMENT_RESOLVER_SAVE,{sourceMethod:"saveAttachment",source:"sdk",attachmentId:e.attachment.attachmentId,eventType:e.eventType}),r}catch(i){this.loggingService.warn("Error in AttachmentResolverService saveAttachment:",i);return}})}deleteAttachment(r){return ee(this,arguments,function*({attachmentId:e,metadata:i}){try{this.loggingService.log("%c[WB] Calling AttachmentResolverService FUNCTION: deleteAttachment","color: green;");let a=this.getProvider();if(!this.attachmentDataProviderAvailable())throw new Error("Attachment delete data provider not available");let s=yield sc(()=>a?.delete({attachmentId:e,metadata:i,event:Ha.ATTACHMENT_DELETE})||Promise.resolve(void 0),"deleteAttachment",this.retryDeleteConfig);return s?.statusCode!==200?(this.loggingService.catch(s?.message??"Error in AttachmentResolverService deleteAttachment:"),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(Z.Events.Resolver.ATTACHMENT_RESOLVER_DELETE,{sourceMethod:"deleteAttachment",source:"sdk",attachmentId:e}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0})}catch(a){return this.loggingService.warn("Error in AttachmentResolverService deleteAttachment:",a),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0}}})}setAttachmentDataProvider(e){try{if(e){this.loggingService.log("Setting attachment data provider");let r=["save","delete"].filter(a=>!(a in e)||typeof e[a]!="function");if(r.length>0){let a=`DataProviders.attachment is invalid. The following methods are missing or are not functions: ${r.join(", ")}.`;this.loggingService.catch(a);return}else this.attachmentDataProvider$.next(e)}}catch(i){this.loggingService.catch("Error in AttachmentResolverService setAttachmentDataProvider:",i)}}attachmentDataProviderAvailable(){try{return!!this.attachmentDataProvider$.getValue()}catch(e){return this.loggingService.catch("Error in AttachmentResolverService attachmentDataProviderAvailable:",e),!1}}};o.\u0275fac=function(i){return new(i||o)(J(y),J(Qe))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Uv=(()=>{let o=class o{constructor(e,i,r,a,s,c,p){this.loggingService=e,this.usersService=i,this.authService=r,this.functions=a,this.configService=s,this.commentAnnotationsResolverService=c,this.attachmentResolverService=p,this.notificationActionTypeMap={[jt.NEWLY_ADDED]:Ha.COMMENT_ANNOTATION_ADD,[jt.ADDED]:Ha.COMMENT_ADD,[jt.UPDATED]:Ha.COMMENT_UPDATE,[jt.DELETED]:Ha.COMMENT_DELETE}}setNotificationService(e){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: setNotificationService","color: green;"),this.notificationService=e}catch(i){this.loggingService.catch("Error in CommentUtilsService setNotificationService: ",i)}}getUserIdsToResolveFromComments(e){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: getUserIdsToResolveFromComments","color: green;");let i=new Set;for(let r of e){if(r?.from?.userId&&i.add(r?.from?.userId),r?.comments)for(let a of r?.comments){if(a?.from?.userId&&i.add(a?.from?.userId),a?.to)for(let s of a?.to)s?.userId&&i.add(s?.userId);if(a?.taggedUserContacts)for(let s of a?.taggedUserContacts)s?.userId&&i.add(s?.userId)}if(r?.assignedTo?.userId&&i.add(r?.assignedTo?.userId),r?.subscribedUsers)for(let a of Object.values(r?.subscribedUsers))a.user.userId&&i.add(a.user.userId);if(r?.unsubscribedUsers)for(let a of Object.values(r?.unsubscribedUsers))a.user.userId&&i.add(a.user.userId)}return Array.from(i)}catch(i){return this.loggingService.catch("Error in CommentUtilsService getUserIdsToResolveFromComments:",i),[]}}mergeCommentWithUser(e){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: mergeCommentWithUser","color: green;"),e?.from?.userId){let i=this.usersService.getUserById(e?.from?.userId);i&&(e.from=i)}if(e?.comments)for(let i of e?.comments){if(i?.from?.userId){let a=this.usersService.getUserById(i?.from?.userId);a&&(i.from=a)}i?.to&&(i.to=i?.to?.map(a=>{if(a?.userId){let s=this.usersService.getUserById(a?.userId);if(s)return I(I({},a),s)}return a})),i?.taggedUserContacts&&(i.taggedUserContacts=i?.taggedUserContacts?.map(a=>{if(a?.contact){let s=this.usersService.getUserById(a?.contact?.userId);s&&(a.contact=s,(s?.name||s?.email)&&(a.text=`@${s?.name||s?.email}`))}return a})),(i?.taggedUserContacts?.filter((a,s,c)=>c.findIndex(p=>p.text===a.text)===s)||[]).forEach(a=>{if(a?.text){let s=new RegExp(im(`{{${a.userId}}}`),"g");i.commentText=i.commentText?.replaceAll(s,a.text),i.commentHtml=i.commentHtml?.replaceAll(s,a.text)}})}if(e?.assignedTo?.userId){let i=this.usersService.getUserById(e?.assignedTo?.userId);i&&(e.assignedTo=i)}if(e?.subscribedUsers)for(let i of Object.values(e?.subscribedUsers)){let r=this.usersService.getUserById(i.user.userId);r&&e?.subscribedUsers?.id?.user&&(e.subscribedUsers.id.user=r)}if(e?.unsubscribedUsers)for(let i of Object.values(e?.unsubscribedUsers)){let r=this.usersService.getUserById(i.user.userId);r&&e?.unsubscribedUsers?.id?.user&&(e.unsubscribedUsers.id.user=r)}return e}catch(i){return this.loggingService.catch("Error in CommentUtilsService mergeCommentWithUser:",i),e}}formatCommentData(e){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: formatCommentData","color: green;"),e?.comments?.forEach(i=>{i?.commentText&&i?.commentText?.length>0&&(i.isCommentTextAvailable=!0)}),this.usersService.userDataProviderAvailable()){if(e?.from?.userId&&(e.from={userId:e.from.userId}),e?.assignedTo?.userId&&(e.assignedTo={userId:e.assignedTo.userId}),e?.subscribedUsers)for(let i of Object.keys(e?.subscribedUsers))e.subscribedUsers[i].user={userId:e?.subscribedUsers[i].user.userId};if(e?.unsubscribedUsers)for(let i of Object.keys(e?.unsubscribedUsers))e.unsubscribedUsers[i].user={userId:e?.unsubscribedUsers[i].user.userId}}return e?.comments&&(e.comments=e?.comments?.map(i=>this.formatCommentThreadData(i))),e}catch(i){return this.loggingService.catch("Error in CommentUtilsService formatCommentData:",i),e}}mergeStrippedDataWithCommentAnnotations(e){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: mergeStrippedDataWithCommentAnnotations","color: green;"),!this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())return e;let i=this.commentAnnotationsResolverService.getAnnotationById(e?.annotationId),r=this.attachmentResolverService.attachmentDataProviderAvailable();return i&&e?.comments?.forEach(a=>{let s=i?.comments?.[a?.commentId];if(s){a.commentHtml=s?.commentHtml,a.commentText=s?.commentText;let c=s?.attachments;r&&c&&a.attachments?.forEach(p=>{let h=p?.attachmentId;c?.[h]&&(p.name=c?.[h]?.name,p.url=c?.[h]?.url)})}}),e}catch(i){return this.loggingService.catch("Error in CommentUtilsService mergeStrippedDataWithCommentAnnotations:",i),e}}mergeLocationWithCommentAnnotations(e,i){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: mergeLocationWithCommentAnnotations","color: green;");let r=e?.location?.id,a=e?.metadata?.documentId;if(!r||!a)return e;let s=i?.[a]?.[r];return s&&(e.location=s?.location),e}catch(r){return this.loggingService.catch("Error in CommentUtilsService mergeLocationWithCommentAnnotations:",r),e}}isCommentsDataChanged(e,i){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: isCommentsDataChanged","color: green;");let r=this.commentAnnotationsResolverService.getCommentAnnotationById(i);return r?!Co(e,r):!0}catch(r){return this.loggingService.catch("Error in CommentUtilsService isCommentsDataChanged:",r),!0}}stripCommentAnnotationData({data:e,actionType:i}){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: stripCommentAnnotationData","color: green;"),!this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable()||!i)return{originalData:e,strippedData:null};let r=this.attachmentResolverService.attachmentDataProviderAvailable(),a=this.notificationActionTypeMap?.[i];if(!a)return{originalData:e,strippedData:null};let s={},c=null;if(e&&e.annotationId){let p=e.annotationId;if(s[p]={annotationId:p,metadata:sv(e.metadata??{}),comments:{}},e.comments?.forEach(E=>{if(E.commentId){let D;r&&(D={},E.attachments?.forEach(B=>{D[B.attachmentId]={attachmentId:B.attachmentId,name:B.name,url:B.url}})),s[p].comments[E.commentId]=I(I(I({commentId:E.commentId},E?.commentHtml&&{commentHtml:E?.commentHtml}),E?.commentText&&{commentText:E?.commentText}),D&&{attachments:D})}}),!this.isCommentsDataChanged(s[p],p))return{strippedData:null,originalData:e};let _=new ko;Object.assign(_,e),_.comments=e.comments?.map(E=>{let D=new pc;if(Object.assign(D,E),D.isCommentResolverUsed=!0,r){let B=D.attachments?.map(G=>(G.isAttachmentResolverUsed=!0,delete G?.name,delete G?.url,G));D.attachments=B}return delete D?.commentHtml,delete D?.commentText,D})||[],c=_}return{strippedData:s,originalData:c,eventType:a}}catch(r){return this.loggingService.catch("Error in CommentAnnotationsResolverService stripCommentAnnotationData:",r),{strippedData:null,originalData:null}}}formatCommentThreadData(e){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: formatCommentThreadData","color: green;"),this.usersService.userDataProviderAvailable()){e?.from?.userId&&(e.from={userId:e.from.userId}),e?.to&&(e.to=e?.to?.map(r=>r?.userId?{userId:r.userId}:r)),e?.taggedUserContacts&&(e.taggedUserContacts=e?.taggedUserContacts?.map(r=>r?.contact?T(I({},r),{contact:{userId:r.userId}}):r));let i=e?.taggedUserContacts?.filter((r,a,s)=>s.findIndex(c=>c.text===r.text)===a)||[];i.forEach(r=>{if(r?.text){let a=new RegExp(im(r.text),"g");e.commentText=e.commentText?.replaceAll(a,s=>`{{${r.userId}}}`),e.commentHtml=e.commentHtml?.replaceAll(a,s=>`{{${r.userId}}}`)}}),i.forEach(r=>{r?.text&&(r.text="")})}return e}catch(i){return this.loggingService.catch("Error in CommentUtilsService formatCommentThreadData:",i),e}}handleCommentEncryption(s){return ee(this,arguments,function*({data:e,firestorePath:i,extraData:r,eventType:a}){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: handleCommentEncryption","color: green;");let c=$O(this.authService.getFirebaseConfig()?.firebaseOptions),p=Cr(this.functions,Zn.cloudFunction?.[c]?.setEncryptedData,{timeout:20*60*1e3});if(r){r=this.notificationService?.processNotificationData(r),r.annotationData=e;let D=r?.targetAnnotationData?.commentId;if(D){let B=e?.comments?.find(G=>G?.commentId===D);B&&(r.targetAnnotationData=B)}}let h=Fp.getFirestoreProdDbName(this.configService.getApiKey()??"",this.authService.getFirebaseConfig()?.firebaseOptions),_={path:i??"",data:e??{},dbId:h??"",notificationData:r||void 0,notificationURL:Zn.firebaseNotificationsDatabaseURL,feature:"comment",eventType:a??"PATCH",sdkVersion:Ta()},E=yield bp(_,this.authService.getUser()?.userId??"");yield p({veltData:E})}catch(c){this.loggingService.catch("Error in CommentUtilsService handleCommentEncryption:",c)}})}};o.\u0275fac=function(i){return new(i||o)(J(y),J(Hn),J(je),J(Vo),J($t),J(vs),J(Lp))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var lse=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.usersService=i}getUserIdsToResolveFromUserIamData(e){try{this.loggingService.log("%c[WB] Calling ContactUtilsService FUNCTION: getUserIdsToResolveFromUserIamData","color: green;");let i=new Set;if(e?.length)for(let r of e)r?.user?.userId&&i.add(r?.user?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in ContactUtilsService getUserIdsToResolveFromUserIamData: ",i),[]}}mergeUserIamWithUser(e){try{if(this.loggingService.log("%c[WB] Calling ContactUtilsService FUNCTION: mergeUserIamWithUser","color: green;"),e?.user?.userId){let i=this.usersService.getUserById(e?.user?.userId);i&&(e=T(I({},e),{user:i}))}return e}catch(i){return this.loggingService.catch("Error in ContactUtilsService mergeUserIamWithUser: ",i),e}}};o.\u0275fac=function(i){return new(i||o)(J(y),J(Hn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var cse=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.usersService=i}getUserIdsToResolveFromCursorUsers(e){try{this.loggingService.log("%c[WB] Calling CursorUtilsService FUNCTION: getUserIdsToResolveFromCursorUsers","color: green;");let i=new Set;for(let r of e)r?.userId&&i.add(r?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in CursorUtilsService getUserIdsToResolveFromCursorUsers:",i),[]}}mergeCursorUserWithUser(e){try{if(this.loggingService.log("%c[WB] Calling CursorUtilsService FUNCTION: mergeCursorUserWithUser","color: green;"),this.usersService.userDataProviderAvailable()&&e?.userId){let i=this.usersService.getUserById(e?.userId);i&&(e=I(I({},e),i))}return e}catch(i){return this.loggingService.catch("Error in CursorUtilsService mergeCursorUserWithUser:",i),e}}formatCursorUserData(e){try{if(this.loggingService.log("%c[WB] Calling CursorUtilsService FUNCTION: formatCursorUserData","color: green;"),this.usersService.userDataProviderAvailable()){let i=["userId","comment","positionX","positionY","screenWidth","screenHeight","screenScrollHeight","onlineStatus","userSnippylyId","color","textColor","timestamp","type","selections","documentParamsId","documentParams","locationId","location","targetElement","position","isReadOnly","isAnonymous","pageInfo"];Object.keys(e).forEach(r=>{i.includes(r)||(e[r]=null)})}return e}catch(i){return this.loggingService.catch("Error in CursorUtilsService formatCursorUserData:",i),e}}};o.\u0275fac=function(i){return new(i||o)(J(y),J(Hn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var xM=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.usersService=i}getUserIdsToResolveFromHuddleAttendees(e){try{this.loggingService.log("%c[WB] Calling HuddleUtilsService FUNCTION: getUserIdsToResolveFromHuddleAttendees","color: green;");let i=new Set;for(let r of e)r?.userId&&i.add(r?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in HuddleUtilsService getUserIdsToResolveFromHuddleAttendees:",i),[]}}mergeHuddleAttendeeWithUser(e){try{if(this.loggingService.log("%c[WB] Calling HuddleUtilsService FUNCTION: mergeHuddleAttendeeWithUser","color: green;"),e?.userId){let i=this.usersService.getUserById(e?.userId);i&&(e=I(I({},e),i))}return e}catch(i){return this.loggingService.catch("Error in HuddleUtilsService mergeHuddleAttendeeWithUser:",i),e}}formatHuddleAttendeeData(e){try{if(this.usersService.userDataProviderAvailable()){let i=["userId","userSnippylyId","state","timestamp","initialHuddleMode","streamMetadata","initialHuddleType","huddleOnCursorMode"];Object.keys(e).forEach(r=>{i.includes(r)||(e[r]=null)})}return e}catch(i){return this.loggingService.catch("Error in HuddleUtilsService formatHuddleAttendeeData:",i),e}}getUserIdsToResolveFromHuddleMessages(e){try{this.loggingService.log("%c[WB] Calling HuddleUtilsService FUNCTION: getUserIdsToResolveFromHuddleMessages","color: green;");let i=new Set;for(let r of e)r?.from?.userId&&i.add(r?.from?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in HuddleUtilsService getUserIdsToResolveFromHuddleMessages:",i),[]}}mergeHuddleMessageWithUser(e){try{if(this.loggingService.log("%c[WB] Calling HuddleUtilsService FUNCTION: mergeHuddleMessageWithUser","color: green;"),e?.from?.userId){let i=this.usersService.getUserById(e?.from?.userId);i&&(e.from=i)}return e}catch(i){return this.loggingService.catch("Error in HuddleUtilsService mergeHuddleMessageWithUser:",i),e}}resolveUsersFromHuddleMessages(e){return ee(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling HuddleUtilsService FUNCTION: resolveUsersFromHuddleMessages","color: green;"),this.usersService.userDataProviderAvailable()){let i=this.getUserIdsToResolveFromHuddleMessages(e),r=yield this.usersService.resolveUsers(i);for(let a of e)a?.from?.userId&&r[a.from.userId]&&(a.from=r[a.from.userId])}return e}catch(i){return this.loggingService.catch("Error in HuddleUtilsService resolveUsersFromHuddleMessages:",i),e}})}formatHuddleMessageData(e){try{return this.loggingService.log("%c[WB] Calling HuddleUtilsService FUNCTION: formatHuddleMessageData","color: green;"),this.usersService.userDataProviderAvailable()&&e?.from?.userId&&(e.from={userId:e.from.userId}),e}catch(i){return this.loggingService.catch("Error in HuddleUtilsService formatHuddleMessageData:",i),e}}};o.\u0275fac=function(i){return new(i||o)(J(y),J(Hn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var dse=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.usersService=i}getUserIdsToResolveFromLiveStateCustom(e){try{let i=new Set;return e?.updatedBy&&i.add(e?.updatedBy?.userId),Array.from(i)}catch(i){return this.loggingService.catch("Error in LiveStateUtilsService getUserIdsToResolveFromLiveStateCustom:",i),[]}}mergeLiveStateCustomWithUser(e){try{if(e?.updatedBy?.userId){let i=this.usersService.getUserById(e?.updatedBy?.userId);i&&(e.updatedBy=i)}return e}catch(i){return this.loggingService.catch("Error in LiveStateUtilsService mergeLiveStateCustomWithUser:",i),e}}formatLiveStateCustomData(e){try{return this.usersService.userDataProviderAvailable()&&e?.updatedBy&&(e.updatedBy={userId:e.updatedBy.userId}),e}catch(i){return this.loggingService.catch("Error in LiveStateUtilsService formatLiveStateCustomData:",i),e}}getUserIdsToResolveFromLiveStateCustoms(e){try{let i=new Set;for(let r of e)r?.updatedBy?.userId&&i.add(r?.updatedBy?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in LiveStateUtilsService getUserIdsToResolveFromLiveStateCustoms:",i),[]}}getUserIdsToResolveFromLiveStates(e){try{let i=new Set;return e?.default?.singleEditorMode?.editor?.userId&&i.add(e?.default?.singleEditorMode?.editor?.userId),Array.from(i)}catch(i){return this.loggingService.catch("Error in LiveStateUtilsService getUserIdsToResolveFromLiveStates:",i),[]}}mergeLiveStateWithUser(e){try{if(e?.default?.singleEditorMode?.editor?.userId){let i=this.usersService.getUserById(e?.default?.singleEditorMode?.editor?.userId);i&&(e.default.singleEditorMode.editor=i)}if(e?.default?.singleEditorMode?.requestEditorAccess?.user?.userId){let i=this.usersService.getUserById(e?.default?.singleEditorMode?.requestEditorAccess?.user?.userId);i&&(e.default.singleEditorMode.requestEditorAccess.user=i)}return e}catch(i){return this.loggingService.catch("Error in LiveStateUtilsService mergeLiveStateWithUser:",i),e}}formatLiveStateSingleEditorModeData(e){try{return this.usersService.userDataProviderAvailable()&&(e?.editor?.userId&&(e.editor={userId:e.editor.userId}),e?.requestEditorAccess?.user?.userId&&(e.requestEditorAccess.user={userId:e.requestEditorAccess.user.userId})),e}catch(i){return this.loggingService.catch("Error in LiveStateUtilsService formatLiveStateSingleEditorModeData:",i),e}}mergeLiveStateCustomsWithUsers(e){try{for(let i of e)if(i?.updatedBy?.userId){let r=this.usersService.getUserById(i?.updatedBy?.userId);r&&(i.updatedBy=r)}return e}catch(i){return this.loggingService.catch("Error in mergeLiveStateCustomsWithUsers:",i),e}}};o.\u0275fac=function(i){return new(i||o)(J(y),J(Hn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var pse=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.usersService=i}getUserIdsToResolveFromMultiThreads(e){try{let i=new Set;for(let r of e)r?.from?.userId&&i.add(r?.from?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in MultiThreadUtilsService getUserIdsToResolveFromMultiThreads:",i),[]}}mergeMultiThreadWithUser(e){try{if(e?.from?.userId){let i=this.usersService.getUserById(e?.from?.userId);i&&(e.from=i)}return e}catch(i){return this.loggingService.catch("Error in MultiThreadUtilsService mergeMultiThreadWithUser:",i),e}}formatMultiThreadData(e){try{return this.usersService.userDataProviderAvailable()&&(e?.from?.userId&&(e.from={userId:e.from.userId}),e?.commentAnnotationsMap&&(e.commentAnnotationsMap=null)),e}catch(i){return this.loggingService.catch("Error in MultiThreadUtilsService formatMultiThreadData:",i),e}}};o.\u0275fac=function(i){return new(i||o)(J(y),J(Hn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var jv=(()=>{let o=class o{constructor(e,i,r){this.authService=e,this.loggingService=i,this.usersService=r}getUserIdsToResolveFromRecorders(e){try{let i=new Set;for(let r of e)r?.from?.userId&&i.add(r?.from?.userId),r?.transcription?.from?.userId&&i.add(r?.transcription?.from?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in RecorderUtilsService getUserIdsToResolveFromRecorders:",i),[]}}mergeRecorderWithUser(e){try{if(e?.from?.userId){let i=this.usersService.getUserById(e?.from?.userId);i&&(e.from=i)}if(e?.transcription?.from?.userId){let i=this.usersService.getUserById(e?.transcription?.from?.userId);i&&(e.transcription.from=i)}return e}catch(i){return this.loggingService.catch("Error in RecorderUtilsService mergeRecorderWithUser:",i),e}}formatRecorderData(e,i){try{return e.transcription=e?.transcription?T(I({},e.transcription),{lastUpdated:i}):void 0,this.usersService.userDataProviderAvailable()&&(e?.from?.userId&&(e.from={userId:e.from.userId}),e?.transcription?.from?.userId&&(e.transcription.from={userId:e.transcription.from.userId})),e}catch(r){return this.loggingService.catch("Error in RecorderUtilsService formatRecorderData:",r),e}}formatRecorderDataForWhisperTranscription(e){try{return this.usersService.userDataProviderAvailable()&&e?.fromUser?.userId&&(e.fromUser={userId:e.fromUser?.userId}),e}catch(i){return this.loggingService.catch("Error in RecorderUtilsService formatRecorderDataForWhisperTranscription:",i),e}}encryptRecorderAnnotation(e){return ee(this,null,function*(){try{return yield bp(e,this.authService.getUser()?.userId??"")}catch(i){this.loggingService.catch("Error in RecorderUtilsService encryptRecorderAnnotation:",i);return}})}};o.\u0275fac=function(i){return new(i||o)(J(je),J(y),J(Hn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var TM=(()=>{let o=class o{constructor(e,i,r,a,s,c){this.commentUtilsService=e,this.recorderUtilsService=i,this.loggingService=r,this.usersService=a,this.authService=s,this.commentAnnotationsResolverService=c}getUserIdsToResolveFromNotifications(e){try{let i=new Set;for(let r of e){let{notification:a}=r;switch(a?.actionUser?.userId&&i.add(a?.actionUser?.userId),a?.displayHeadlineMessageTemplateData?.actionUser?.userId&&i.add(a?.displayHeadlineMessageTemplateData?.actionUser?.userId),a?.displayHeadlineMessageTemplateData?.recipientUser?.userId&&i.add(a?.displayHeadlineMessageTemplateData?.recipientUser?.userId),a?.notificationSource){case"comment":if(a?.notificationSourceData){let s=this.commentUtilsService.getUserIdsToResolveFromComments([a?.notificationSourceData]);for(let c of s)i.add(c)}break}}return Array.from(i)}catch(i){return this.loggingService.catch("Error in ReactionUtilsService getUserIdsToResolveFromRecorders:",i),[]}}mergeStrippedDataWithNotification(e){try{if(this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: mergeStrippedDataWithNotification","color: green;"),!this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())return e;let i=this.commentAnnotationsResolverService.getAnnotationById(e?.notification?.targetAnnotationId),r=e?.raw?.targetAnnotationData?.commentId,a=i?.comments?.[r]?.commentText,s=i?.comments?.[r]?.commentHtml;return a&&s&&e?.raw?.notificationSource==="comment"&&(e.notification.displayBodyMessageTemplate=a,e.raw.targetAnnotationData.commentText=a,e.raw.targetAnnotationData.commentHtml=s),e}catch(i){return this.loggingService.catch("Error in NotificationUtilsService mergeStrippedDataWithNotification:",i),e}}mergeLocationWithNotification(e,i){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: mergeLocationWithNotification","color: green;");let r=e?.notification?.notificationSourceData?.location?.id,a=e?.notification?.notificationSourceData?.metadata?.documentId;if(!r||!a)return e;let s=i?.[a]?.[r];return s&&(e.notification.notificationSourceData.location=s?.location,e?.raw?.annotationData?.location&&(e.raw.annotationData.location=s?.location)),e}catch(r){return this.loggingService.catch("Error in NotificationUtilsService mergeLocationWithNotification:",r),e}}mergeNotificationWithUser(e){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: mergeNotificationWithUser","color: green;");let{notification:i}=e;if(i?.actionUser?.userId){let r=this.usersService.getUserById(i?.actionUser?.userId);r&&(i.actionUser=r)}if(i?.displayHeadlineMessageTemplateData?.actionUser?.userId){let r=this.usersService.getUserById(i?.displayHeadlineMessageTemplateData?.actionUser?.userId);r&&(i.displayHeadlineMessageTemplateData.actionUser=r)}if(i?.displayHeadlineMessageTemplateData?.recipientUser?.userId){let r=this.usersService.getUserById(i?.displayHeadlineMessageTemplateData?.recipientUser?.userId);r&&(i.displayHeadlineMessageTemplateData.recipientUser=r)}switch(i?.notificationSource){case"comment":i?.notificationSourceData&&this.commentUtilsService.mergeCommentWithUser(i?.notificationSourceData);break}return e}catch(i){return this.loggingService.catch("Error in NotificationUtilsService mergeNotificationWithUser:",i),e}}formatNotification(e,i){try{switch(typeof e=="object"&&(e=JSON.parse(JSON.stringify(e))),this.usersService.userDataProviderAvailable()&&e?.actionUser&&(e.actionUser={userId:e.actionUser.userId}),e.notificationSource){case"comment":this.commentUtilsService.formatCommentData(e.annotationData),this.commentUtilsService.formatCommentThreadData(e.targetAnnotationData);break;case"recorder":this.recorderUtilsService.formatRecorderData(e.annotationData,i);break}return e}catch(r){return this.loggingService.catch("Error in NotificationUtilsService formatNotification: ",r),e}}getTargetAnnotationIdsFromNotifications(e){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: getTargetAnnotationIdsFromNotifications","color: green;");let i=[];return Object.values(e).forEach(r=>{r?.notification?.targetAnnotationId&&r?.raw?.notificationSource==="comment"&&i.push(r.notification.targetAnnotationId)}),i}catch(i){return this.loggingService.catch("Error in NotificationUtilsService getTargetAnnotationIdsFromNotifications:",i),[]}}handleNotificationEncryption(i){return ee(this,arguments,function*({data:e}){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: handleNotificationEncryption","color: green;");let r="notificationwithdocumentidstoencryptanddecryptonsdk"+(this.authService.getUser()?.userId??"");return yield bp(e,r)}catch(r){return this.loggingService.catch("Error in NotificationUtilsService handleNotificationEncryption:",r),e}})}};o.\u0275fac=function(i){return new(i||o)(J(Uv),J(jv),J(y),J(Hn),J(je),J(vs))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var use=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.usersService=i}getUserIdsToResolveFromPresenceUsers(e){try{let i=new Set;for(let r of e)r?.userId&&i.add(r?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in PresenceUtilsService getUserIdsToResolveFromPresenceUsers:",i),[]}}mergePresenceUserWithUser(e){try{if(this.usersService.userDataProviderAvailable()&&e?.userId){let i=this.usersService.getUserById(e?.userId);i&&(e=I(I({},e),i))}return e}catch(i){return this.loggingService.catch("Error in PresenceUtilsService mergePresenceUserWithUser:",i),e}}formatPresenceUserData(e){try{if(this.usersService.userDataProviderAvailable()){let i=["userId","onlineStatus","userSnippylyId","color","textColor","timestamp","type","selections","documentParamsId","documentParams","locationId","location","isReadOnly","isAnonymous","pageInfo"];Object.keys(e).forEach(r=>{i.includes(r)||(e[r]=null)})}return e}catch(i){return this.loggingService.catch("Error in PresenceUtilsService formatPresenceUserData:",i),e}}};o.\u0275fac=function(i){return new(i||o)(J(y),J(Hn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var hse=(()=>{let o=class o{constructor(e,i,r,a,s,c){this.loggingService=e,this.usersService=i,this.authService=r,this.functions=a,this.configService=s,this.reactionAnnotationsResolverService=c}getUserIdsToResolveFromReactions(e){try{let i=new Set;for(let r of e)if(r?.from?.userId&&i.add(r?.from?.userId),r?.reactions?.length)for(let a of r?.reactions)a?.from?.userId&&i.add(a?.from?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in ReactionUtilsService getUserIdsToResolveFromRecorders:",i),[]}}handleReactionEncryption(a){return ee(this,arguments,function*({data:e,firestorePath:i,eventType:r}){try{let s=$O(this.authService.getFirebaseConfig()?.firebaseOptions),c=Cr(this.functions,Zn.cloudFunction?.[s]?.setEncryptedData,{timeout:20*60*1e3}),p=Fp.getFirestoreProdDbName(this.configService.getApiKey()??"",this.authService.getFirebaseConfig()?.firebaseOptions),h=this.authService.getUser()?.userId??"",_={path:i??"",data:e??{},dbId:p??"",feature:"reaction",eventType:r??"PATCH",sdkVersion:Ta()},E=yield bp(_,h);yield c({veltData:E})}catch(s){this.loggingService.catch("Error in handleReactionEncryption:",s)}})}mergeReactionWithUser(e){try{if(this.usersService.userDataProviderAvailable()){if(e?.from?.userId){let i=this.usersService.getUserById(e?.from?.userId);i&&(e.from=i)}if(e?.reactions?.length){for(let i of e?.reactions)if(i?.from?.userId){let r=this.usersService.getUserById(i?.from?.userId);r&&(i.from=r)}}}return e}catch(i){return this.loggingService.catch("Error in ReactionUtilsService mergeReactionWithUser:",i),e}}formatReactionData(e){try{return this.usersService.userDataProviderAvailable()&&e?.from?.userId&&(e.from={userId:e.from.userId}),e.reactions=e?.reactions?.map(i=>(this.usersService.userDataProviderAvailable()&&i?.from?.userId&&(i.from={userId:i.from.userId}),i)),e}catch(i){return this.loggingService.catch("Error in ReactionUtilsService formatReactionData:",i),e}}isReactionDataChanged(e,i){try{this.loggingService.log("%c[WB] Calling ReactionUtilsService FUNCTION: isReactionDataChanged","color: green;");let r=this.reactionAnnotationsResolverService.getReactionAnnotationById(i);return r?!Co(e,r):!0}catch(r){return this.loggingService.catch("Error in ReactionUtilsService isReactionDataChanged:",r),!0}}stripReactionAnnotationData(e){try{if(this.loggingService.log("%c[WB] Calling ReactionUtilsService FUNCTION: stripReactionAnnotationData","color: green;"),!this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable())return{originalData:e,strippedData:null};let i={};if(e&&e.annotationId){let r=e.annotationId;if(i[r]={annotationId:r,metadata:sv(e.metadata??{}),icon:e.icon},!this.isReactionDataChanged(i[r],r))return{strippedData:null,originalData:e};delete e?.icon,e.isReactionResolverUsed=!0}return{strippedData:i,originalData:e}}catch(i){return this.loggingService.catch("Error in ReactionUtilsService stripReactionAnnotationData:",i),{strippedData:null,originalData:null}}}mergeStrippedDataWithReactionAnnotations(e){try{if(this.loggingService.log("%c[WB] Calling ReactionUtilsService FUNCTION: mergeStrippedDataWithReactionAnnotations","color: green;"),!this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable())return e;let i=this.reactionAnnotationsResolverService.getReactionAnnotationById(e?.annotationId);return i&&i.icon&&(e.icon=i.icon),e}catch(i){return this.loggingService.catch("Error in ReactionUtilsService mergeStrippedDataWithReactionAnnotations:",i),e}}};o.\u0275fac=function(i){return new(i||o)(J(y),J(Hn),J(je),J(Vo),J($t),J(um))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var fse=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.usersService=i}getUserIdsToResolveFromSelections(e){try{let i=new Set;for(let r of e)r?.user?.userId&&i.add(r.user.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in SelectionUtilsService getUserIdsToResolveFromSelections:",i),[]}}mergeSelectionWithUser(e){try{if(e?.user?.userId){let i=this.usersService.getUserById(e?.user?.userId);i&&(e.user=i)}return e}catch(i){return this.loggingService.catch("Error in SelectionUtilsService mergeSelectionWithUser:",i),e}}formatSelectionData(e){try{return this.usersService.userDataProviderAvailable()&&e?.user?.userId&&(e.user={userId:e.user.userId}),e}catch(i){return this.loggingService.catch("Error in SelectionUtilsService formatSelectionData:",i),e}}};o.\u0275fac=function(i){return new(i||o)(J(y),J(Hn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var vse=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.usersService=i}getUserIdsToResolveFromTags(e){try{let i=new Set;for(let r of e)if(r?.from?.userId&&i.add(r.from.userId),r?.to?.length)for(let a of r.to)a?.userId&&i.add(a.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in TagUtilsService getUserIdsToResolveFromTags:",i),[]}}mergeTagWithUser(e){try{if(e?.from?.userId){let i=this.usersService.getUserById(e?.from?.userId);i&&(e.from=i)}return e?.to?.length&&(e.to=e.to.map(i=>{if(i?.userId){let r=this.usersService.getUserById(i?.userId);r&&(i=r)}return i})),e}catch(i){return this.loggingService.catch("Error in TagUtilsService mergeTagWithUser:",i),e}}formatTagData(e){try{return this.usersService.userDataProviderAvailable()&&(e?.from?.userId&&(e.from={userId:e.from.userId}),e?.to?.length&&(e.to=e.to.map(i=>(i?.userId&&(i={userId:i.userId}),i)))),e}catch(i){return this.loggingService.catch("Error in TagUtilsService formatTagData:",i),e}}};o.\u0275fac=function(i){return new(i||o)(J(y),J(Hn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var $v=(()=>{let o=class o{constructor(e,i,r,a,s,c,p,h,_,E,D,B,G,X,he,Ie,Me,Le,We){this.areaUtilsService=e,this.arrowUtilsService=i,this.commentUtilsService=r,this.contactUtilsService=a,this.cursorUtilsService=s,this.huddleUtilsService=c,this.liveStateUtilsService=p,this.loggingService=h,this.multiThreadUtilsService=_,this.notificationUtilsService=E,this.presenceUtilsService=D,this.reactionUtilsService=B,this.recorderUtilsService=G,this.selectionUtilsService=X,this.tagUtilsService=he,this.usersService=Ie,this.docService=Me,this.commentAnnotationsResolverService=Le,this.reactionAnnotationsResolverService=We}getFirestorePath({feature:e,properties:i,documentPaths:r,apiKey:a}){try{if(!a)return;let{documentId:s,organizationId:c,folderId:p}=i;c||(c=r?.organizationId);let h=new bM({apiKey:a,documentId:s?`${s}`:"",organizationId:c?`${c}`:"",veltFolderId:p?`${p}`:void 0});switch(e){case"comment":return i?.documentId&&i?.id&&h?.comment?`${h?.comment}/${i?.id}`:void 0;case"allComments":return i?.documentId&&h?.comment?`${h?.comment}`:void 0;case"multiThread":return i?.documentId&&i?.id&&h?.multiThread?`${h?.multiThread}/${i?.id}`:void 0;case"allMultiThreads":return i?.documentId&&h?.multiThread?`${h?.multiThread}`:void 0;case"allLastNotificationTimestamp":return h?.lastNotificationTimestamp?`${h?.lastNotificationTimestamp}`:void 0;case"lastNotificationTimestamp":return i?.id&&h?.lastNotificationTimestamp?`${h?.lastNotificationTimestamp}/${i?.id}`:void 0;case"area":return i?.documentId&&i?.id&&h?.area?`${h?.area}/${i?.id}`:void 0;case"allAreas":return i?.documentId&&h?.area?`${h?.area}`:void 0;case"allDocuments":return h?.document?`${h?.document}`:void 0;case"allLocations":return h?.location?`${h?.location}`:void 0;case"allFolders":return h?.folder?`${h?.folder}`:void 0;case"folder":return h?.folder&&i.folderId?`${h?.folder}/${i.folderId}`:void 0;case"documentUserAccess":return i?.documentId&&i?.id&&h?.documentUsers?`${h?.documentUsers}/${i?.id}`:void 0;case"reaction":return i?.documentId&&i?.id&&h?.reaction?`${h?.reaction}/${i?.id}`:void 0;case"allReactions":return i?.documentId&&h?.reaction?`${h?.reaction}`:void 0;case"recorder":return i?.documentId&&i?.id&&h?.recorder?`${h?.recorder}/${i?.id}`:void 0;case"allRecorders":return i?.documentId&&h?.recorder?`${h?.recorder}`:void 0;case"documentAccessType":return i?.documentId&&h?.document?`${h?.document}/${i?.documentId}`:void 0;case"organizationMetadata":return h?.organization?`${h?.organization}`:void 0;case"documentIam":case"documentMetadata":return i?.documentId&&h?.document?`${h?.document}/${i?.documentId}`:void 0;case"folderMetadata":return i?.folderId&&h?.folder?`${h?.folder}/${i?.folderId}`:void 0;case"locationMetadata":return i?.documentId&&h?.location&&i?.id?`${h?.location}/${i?.id}`:void 0;case"documentUser":return i?.documentId&&i?.id&&h?.documentUsers?`${h?.documentUsers}/${i?.id}`:void 0;case"allDocumentUsers":return i?.documentId&&h?.documentUsers?`${h?.documentUsers}`:void 0;case"allFolderUsers":return i?.folderId&&h?.folderUsers?`${h?.folderUsers}`:void 0;case"allOrganizationGroups":return h?.organizationGroups?`${h?.organizationGroups}`:void 0;case"allOrganizationUsers":return h?.organizationUsers?`${h?.organizationUsers}`:void 0;case"commentViews":return i?.documentId&&i?.id&&h?.commentViews?`${h?.commentViews}/${i?.id}`:void 0;case"allCommentViews":return i?.documentId&&h?.commentViews?`${h?.commentViews}`:void 0;case"notificationViewsTimestamp":return i?.documentId&&i?.id&&h?.notificationViews?`${h?.notificationViews}/${i?.id}`:void 0;case"allDocumentViews":return i?.documentId&&h?.documentViews?`${h?.documentViews}`:void 0;case"documentViews":case"documentMetadataViews":case"documentDayViews":case"documentUsersViews":return i?.documentId&&i?.id&&h?.documentViews?`${h?.documentViews}/${i?.id}`:void 0;case"locationDayViews":case"locationUsersViews":case"locationViews":case"locationMetadataViews":case"location":return i?.documentId&&i?.id&&h?.locationViews?`${h?.locationViews}/${i?.id}`:void 0;case"allLocationViews":return i?.documentId&&h?.locationViews?`${h?.locationViews}`:void 0;case"allDocNotifications":return i?.documentId&&h?.docNotification?`${h?.docNotification}`:void 0;case"docNotificationViews":case"docNotification":return i?.documentId&&i?.id&&h?.docNotification?`${h?.docNotification}/${i?.id}`:void 0;case"userNotificationViews":case"userNotification":return i?.userId&&i?.id&&h?.notificationUsers?`${h?.notificationUsers}/${i?.userId}/${U.FIREBASE_PARTIAL_PATH_USER_NOTIFICATION}/${i?.id}`:void 0;case"allDocNotifications":return i?.documentId&&h?.docNotification?`${h?.docNotification}`:void 0;case"allUserNotifications":return i?.userId&&h?.notificationUsers?`${h?.notificationUsers}/${i?.userId}/${U.FIREBASE_PARTIAL_PATH_USER_NOTIFICATION}`:void 0;default:throw new Error(`Unknown feature: ${e}`)}}catch(s){this.loggingService.catch("Error in CommonDbUtilsService getFirestorePath:",s);return}}getFirestoreCollectionGroupPath(e){try{switch(e){case"allComments":return U.FIREBASE_PARTIAL_PATH_COMMENT;case"allDocuments":return U.FIREBASE_PARTIAL_PATH_DOCS;case"allLocations":return U.FIREBASE_PARTIAL_PATH_LOCATION;case"allMultiThreads":return U.FIREBASE_PARTIAL_PATH_MULTI_THREAD;case"allAreas":return U.FIREBASE_PARTIAL_PATH_AREA;case"allReactions":return U.FIREBASE_PARTIAL_PATH_REACTION;case"allRecorders":return U.FIREBASE_PARTIAL_PATH_RECORDER;case"allDocumentViews":return U.FIREBASE_PARTIAL_PATH_DOCUMENT_VIEWS;case"allCommentViews":return U.FIREBASE_PARTIAL_PATH_COMMENT_VIEWS;case"allLocationViews":return U.FIREBASE_PARTIAL_PATH_LOCATION_VIEWS;case"allDocumentUsers":return U.FIREBASE_PARTIAL_PATH_DOCUMENT_USERS;case"allFolderUsers":return U.FIREBASE_PARTIAL_PATH_FOLDER_USERS;default:throw new Error(`Unknown feature: ${e}`)}}catch(i){this.loggingService.catch("Error in CommonDbUtilsService getFirestoreCollectionGroupPath:",i);return}}getDocumentPath({feature:e,properties:i,defaultDocumentPaths:r,apiKey:a,useFirestore:s}){try{if(!a)return;let{documentId:c,organizationId:p}=i;p||(p=r?.organizationId);let h=new xd({apiKey:a,documentId:c?`${c}`:"",organizationId:p?`${p}`:""});switch(e){case"allComments":return!s&&i?.documentId&&h?.comment?`${h?.comment}`:void 0;case"allGlobalContacts":return i?.documentId&&h?.globalContacts?`${h?.globalContacts}`:void 0;case"globalContacts":return i?.documentId&&i?.userId&&h?.globalContacts?`${h?.globalContacts}${i?.userId}`:void 0;case"groupContacts":return i?.documentId&&i?.groupId&&h?.groupContacts?`${h?.groupContacts}${i?.groupId}`:void 0;case"groupContactsUser":return i?.documentId&&i?.groupId&&i?.userId&&h?.groupContacts?`${h?.groupContacts}${i?.groupId}/${i?.userId}`:void 0;case"allLoginContacts":return i?.documentId&&i?.userId&&h?.logins?`${h?.logins}${i?.userId}/contacts`:void 0;case"allLogins":return i?.documentId&&h?.logins?`${h?.logins}`:void 0;case"logins":return i?.documentId&&i?.userId&&h?.logins?`${h?.logins}${i?.userId}`:void 0;case"customerMetadata":return h?.customerMetadata?`${h?.customerMetadata}`:void 0;case"allArrows":return i?.documentId&&h?.arrow?`${h?.arrow}`:void 0;case"arrow":return i?.documentId&&h?.arrow&&i.id?`${h?.arrow}${i.id}`:void 0;case"allCursors":return i?.documentId&&h?.cursor?`${h?.cursor}`:void 0;case"cursor":return i?.documentId&&h?.cursor&&i.id?`${h?.cursor}${i.id}`:void 0;case"flockUser":return i?.documentId&&h?.flock&&i.id?`${h?.flock}users/${i.id}`:void 0;case"flockSession":return i?.documentId&&h?.flock&&i.id?`${h?.flock}sessions/${i.id}`:void 0;case"allHuddleAttendees":return i?.documentId&&h?.huddle?`${h?.huddle}attendees`:void 0;case"huddleAttendee":return i?.documentId&&h?.huddle&&i.id?`${h?.huddle}attendees/${i.id}`:void 0;case"huddleAttendeeState":return i?.documentId&&h?.huddle&&i.id?`${h?.huddle}attendees/${i.id}/state`:void 0;case"allHuddleInvitees":return i?.documentId&&h?.huddle?`${h?.huddle}invitees`:void 0;case"huddleConnection":return i?.documentId&&h?.huddle&&i.id?`${h?.huddle}connections/${i.id}`:void 0;case"huddleIceCandidate":return i?.documentId&&h?.huddle&&i.id?`${h?.huddle}iceCandidates/${i.id}`:void 0;case"allHuddleIceCandidates":return i?.documentId&&h?.huddle?`${h?.huddle}iceCandidates`:void 0;case"allHuddleMessages":return i?.documentId&&h?.huddle?`${h?.huddle}messages`:void 0;case"huddleMessage":return i?.documentId&&h?.huddle&&i.id?`${h?.huddle}messages/${i.id}`:void 0;case"allLiveStates":return i?.documentId&&h?.liveState?`${h?.liveState}`:void 0;case"allLiveStateCustoms":return i?.documentId&&h?.liveState?`${h?.liveState}custom`:void 0;case"liveStateCustom":return i?.documentId&&h?.liveState&&i?.id?`${h?.liveState}custom/${i.id}`:void 0;case"liveStateSingleEditorMode":return i?.documentId&&h?.liveStateSingleEditorMode?`${h?.liveStateSingleEditorMode}`:void 0;case"liveStateAutoSyncStateCurrent":return i?.documentId&&h?.liveState?`${h?.liveState}default/autoSyncState/current`:void 0;case"liveStateAutoSyncStateHistoryId":return i?.documentId&&h?.liveState&&i?.id?`${h?.liveState}default/autoSyncState/history/${i.id}`:void 0;case"presence":return i?.documentId&&h?.presence&&i?.userId?`${h?.presence}${i?.userId}`:void 0;case"allPresence":return i?.documentId&&h?.presence?`${h?.presence}`:void 0;case"workspaceIam":return h?.workspaceIam?`${h?.workspaceIam}`:void 0;case"selection":return i?.documentId&&h?.selection&&i?.userId?`${h?.selection}${i?.userId}`:void 0;case"allSelections":return i?.documentId&&h?.selection?`${h?.selection}`:void 0;case"syncVideoPlayer":return i?.documentId&&h?.syncVideoPlayer?`${h?.syncVideoPlayer}`:void 0;case"allTags":return i?.documentId&&h?.tag?`${h?.tag}`:void 0;case"tag":return i?.documentId&&h?.tag&&i?.id?`${h?.tag}${i?.id}`:void 0;case"userContactUs":return i?.documentId&&h?.userContactUs?`${h?.userContactUs}`:void 0;case"userFeedback":return i?.documentId&&h?.userFeedback?`${h?.userFeedback}`:void 0;case"userReportBug":return i?.documentId&&h?.userReportBugs?`${h?.userReportBugs}`:void 0;case"comment":return!s&&i?.documentId&&i?.id&&h?.comment?`${h?.comment}${i?.id}`:void 0;case"allMultiThreads":return!s&&i?.documentId&&h?.multiThread?`${h?.multiThread}`:void 0;case"multiThread":return!s&&i?.documentId&&i?.id&&h?.multiThread?`${h?.multiThread}${i?.id}`:void 0;case"allLastNotificationTimestamp":return!s&&h?.organizationNotificationsLastNotificationTimestamp?`${h?.organizationNotificationsLastNotificationTimestamp}`:void 0;case"lastNotificationTimestamp":return!s&&i?.id&&h?.organizationNotificationsLastNotificationTimestamp?`${h?.organizationNotificationsLastNotificationTimestamp}${i?.id}`:void 0;case"documentIam":return!s&&i?.documentId&&h?.documentIam?`${h?.documentIam}`:void 0;case"documentMetadata":return!s&&i?.documentId&&h?.metadata?`${h?.metadata}`:void 0;case"allDocuments":return!s&&h?.docs&&i?.documentId?`${h?.docs}/${i?.documentId}/${U.FIREBASE_PARTIAL_PATH_METADATA}`:void 0;case"allAreas":return!s&&i?.documentId&&h?.area?`${h?.area}`:void 0;case"area":return!s&&i?.id&&h?.area?`${h?.area}${i?.id}`:void 0;case"documentUserAccess":return!s&&i?.id&&h?.documentIam?`${h?.documentIam}users/${i?.id}`:void 0;case"documentUser":return!s&&i?.documentId&&i?.id&&h?.documentIam?`${h?.documentIam}users/${i?.id}`:void 0;case"allDocumentUsers":return!s&&i?.documentId&&h?.documentIam?`${h?.documentIam}users/`:void 0;case"allOrganizationGroups":return!s&&h?.organizationGroups?`${h?.organizationGroups}`:void 0;case"allOrganizationUsers":return!s&&h?.organizationIam?`${h?.organizationIam}users/`:void 0;case"reaction":return!s&&i?.id&&h?.reaction?`${h?.reaction}${i?.id}`:void 0;case"allReactions":return!s&&i?.documentId&&h?.reaction?`${h?.reaction}`:void 0;case"recorder":return!s&&i?.documentId&&i?.id&&h?.recorder?`${h?.recorder}${i?.id}`:void 0;case"allRecorders":return!s&&i?.documentId&&h?.recorder?`${h?.recorder}`:void 0;case"organizationMetadata":return!s&&h?.organizationMetadata?`${h?.organizationMetadata}`:void 0;case"documentAccessType":return!s&&h?.documentIam?`${h?.documentIam}`:void 0;case"documentIam":return!s&&h?.documentIam?`${h?.documentIam}`:void 0;case"documentMetadata":return!s&&i?.documentId&&h?.metadata?`${h?.metadata}`:void 0;case"commentViews":return!s&&i?.documentId&&i?.id&&h?.views?`${h?.views}comment/${i?.id}`:void 0;case"allDocumentViews":return!s&&i?.documentId&&h?.views?`${h?.views}documentViews/`:void 0;case"documentViews":return!s&&i?.documentId&&i?.id&&h?.views?`${h?.views}documentViews/${i?.id}`:void 0;case"allCommentViews":return!s&&i?.documentId&&h?.views?`${h?.views}comment/`:void 0;case"allLocationViews":return!s&&i?.documentId&&h?.views?`${h?.views}locationViews/`:void 0;case"notificationViewsTimestamp":return!s&&i?.id&&i?.user&&h?.views?`${h?.views}notification/${i?.id}/views/${i?.user}`:void 0;case"documentUsersViews":return!s&&i?.id&&i?.user&&i?.date&&h?.views?`${h?.views}documentViews/${i?.id}/users/${i?.user}/${i?.date}`:void 0;case"documentMetadataViews":return!s&&i?.id&&h?.views?`${h?.views}documentViews/${i?.id}/metadata`:void 0;case"documentDayViews":return!s&&i?.id&&i?.date&&i?.user&&h?.views?`${h?.views}documentViews/${i?.id}/day/${i?.date}/${i?.user}`:void 0;case"locationViews":return!s&&i?.id&&h?.views?`${h?.views}locationViews/${i?.id}/location`:void 0;case"location":return!s&&i?.id&&h?.views?`${h?.views}locationViews/${i?.id}`:void 0;case"locationUsersViews":return!s&&i?.id&&i?.user&&i?.date&&h?.views?`${h?.views}locationViews/${i?.id}/users/${i?.user}/${i?.date}`:void 0;case"locationMetadataViews":return!s&&i?.id&&h?.views?`${h?.views}locationViews/${i?.id}/metadata`:void 0;case"locationDayViews":return!s&&i?.id&&i?.date&&i?.user&&h?.views?`${h?.views}locationViews/${i?.id}/day/${i?.date}/${i?.user}`:void 0;case"docNotificationViews":case"docNotification":return i?.documentId&&i?.id&&h?.organizationNotificationsWithDocumentId?`${h?.organizationNotificationsWithDocumentId}${i?.id}`:void 0;case"allDocNotifications":return i?.documentId&&h?.organizationNotificationsWithDocumentId?`${h?.organizationNotificationsWithDocumentId}`:void 0;case"allUserNotifications":return i?.userId&&h?.organizationNotificationsUsers?`${h?.organizationNotificationsUsers}${i?.userId}`:void 0;case"userNotificationViews":case"userNotification":return i?.userId&&i?.id&&h?.organizationNotificationsUsers?`${h?.organizationNotificationsUsers}${i?.userId}/${i?.id}`:void 0;case"locationMetadata":return;case"allLocations":return;case"folderMetadata":return;default:throw new Error(`Unknown feature: ${e}`)}}catch(c){this.loggingService.catch("Error in CommonDbUtilsService getDocumentPath:",c);return}}resolveAnnotations(r){return ee(this,arguments,function*({data:e,feature:i}){try{if(e&&e?.length>0)switch(i){case"allComments":{this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable()&&this.commentAnnotationsResolverService.resolveCommentAnnotations({commentAnnotationIds:e,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""});break}case"allReactions":{this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable()&&this.reactionAnnotationsResolverService.resolveReactionAnnotations({reactionAnnotationIds:e,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""});break}default:break}}catch(a){this.loggingService.catch(`Error in CommonDbUtilsService resolveAnnotations: ${i}`,a)}})}formatResponse(c){return ee(this,arguments,function*({feature:e,data:i,shouldAwait:r=!1,forceResolve:a=!1,shouldCommentAnnotationsResolverAwait:s=!1}){try{if(this.usersService.userDataProviderAvailable()){let p=[];switch(e){case"allAreas":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.areaUtilsService.getUserIdsToResolveFromAreaAnnotations(Object.values(i)));break}case"allArrows":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.arrowUtilsService.getUserIdsToResolveFromArrowAnnotations(Object.values(i)));break}case"allCursors":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.cursorUtilsService.getUserIdsToResolveFromCursorUsers(Object.values(i)));break}case"allComments":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.commentUtilsService.getUserIdsToResolveFromComments(Object.values(i)));break}case"allDocumentUsers":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.contactUtilsService.getUserIdsToResolveFromUserIamData(Object.values(i)));break}case"allFolderUsers":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.contactUtilsService.getUserIdsToResolveFromUserIamData(Object.values(i)));break}case"allOrganizationUsers":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.contactUtilsService.getUserIdsToResolveFromUserIamData(Object.values(i)));break}case"allMultiThreads":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.multiThreadUtilsService.getUserIdsToResolveFromMultiThreads(Object.values(i)));break}case"allDocNotifications":{i&&typeof i=="object"&&(p=this.notificationUtilsService.getUserIdsToResolveFromNotifications(Array.isArray(i)?i:Object.values(i)));break}case"allUserNotifications":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.notificationUtilsService.getUserIdsToResolveFromNotifications(Object.values(i)));break}case"allPresence":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.presenceUtilsService.getUserIdsToResolveFromPresenceUsers(Object.values(i)));break}case"allRecorders":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.recorderUtilsService.getUserIdsToResolveFromRecorders(Object.values(i)));break}case"allReactions":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.reactionUtilsService.getUserIdsToResolveFromReactions(Object.values(i)));break}case"allTags":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.tagUtilsService.getUserIdsToResolveFromTags(Object.values(i)));break}case"allHuddleAttendees":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.huddleUtilsService.getUserIdsToResolveFromHuddleAttendees(Object.values(i)));break}case"liveStateCustom":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.liveStateUtilsService.getUserIdsToResolveFromLiveStateCustom(i));break}case"allLiveStateCustoms":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.liveStateUtilsService.getUserIdsToResolveFromLiveStateCustoms(Object.values(i)));break}case"allLiveStates":{i&&typeof i=="object"&&(p=this.liveStateUtilsService.getUserIdsToResolveFromLiveStates(i));break}case"allSelections":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.selectionUtilsService.getUserIdsToResolveFromSelections(Object.values(i)));break}default:p=[]}p?.length&&(r?yield this.usersService.resolveUsers(p,a):this.usersService.resolveUsers(p,a))}if(this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable()){let p=[];switch(e){case"allDocNotifications":{if(i&&typeof i=="object"){let h=this.notificationUtilsService.getTargetAnnotationIdsFromNotifications(i);p=[...p,...h],p=p.filter(_=>!this.commentAnnotationsResolverService.getCommentAnnotationById(_))}break}case"allUserNotifications":{if(i&&typeof i=="object"&&!Array.isArray(i)){let h=this.notificationUtilsService.getTargetAnnotationIdsFromNotifications(i);p=[...p,...h],p=p.filter(_=>!this.commentAnnotationsResolverService.getCommentAnnotationById(_))}break}default:p=[]}p?.length&&(s?yield this.commentAnnotationsResolverService.resolveCommentAnnotations({commentAnnotationIds:p,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""}):this.commentAnnotationsResolverService.resolveCommentAnnotations({commentAnnotationIds:p,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""}))}return i}catch(p){return this.loggingService.catch("Error in CommonDbUtilsService formatResponse:",p),i}})}mergeCommentAnnotationsWithData({data:e,feature:i}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeCommentAnnotationsWithData","color: green;"),this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())switch(i){case"allComments":return e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).reduce((r,[a,s])=>(r[a]=this.commentUtilsService.mergeStrippedDataWithCommentAnnotations(s),r),{}):e;case"allDocNotifications":case"allUserNotifications":return e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).reduce((r,[a,s])=>(r[a]=this.notificationUtilsService.mergeStrippedDataWithNotification(s),r),{}):e;default:return e}return e}catch(r){return this.loggingService.catch("Error in CommonDbUtilsService mergeCommentAnnotationsWithData:",r),e}}mergeReactionAnnotationsWithData({data:e,feature:i}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeReactionAnnotationsWithData","color: green;"),this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable())switch(i){case"allReactions":return e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).reduce((r,[a,s])=>(r[a]=this.reactionUtilsService.mergeStrippedDataWithReactionAnnotations(s),r),{}):e;default:return e}return e}catch(r){return this.loggingService.catch("Error in CommonDbUtilsService mergeReactionAnnotationsWithData:",r),e}}mergeLocationMetadataWithData({data:e,feature:i,locationMetadata:r}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeLocationMetadataWithData","color: green;"),r&&typeof r=="object"&&!Array.isArray(r))switch(i){case"allComments":return e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).reduce((a,[s,c])=>(a[s]=this.commentUtilsService.mergeLocationWithCommentAnnotations(c,r),a),{}):e;case"allDocNotifications":case"allUserNotifications":return e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).reduce((a,[s,c])=>(a[s]=this.notificationUtilsService.mergeLocationWithNotification(c,r),a),{}):e;default:return e}return e}catch(a){return this.loggingService.catch("Error in CommonDbUtilsService mergeLocationMetadataWithData:",a),e}}mergeUsersWithData({feature:e,data:i}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeUsersWithData","color: green;"),this.usersService.userDataProviderAvailable())switch(e){case"allAreas":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.areaUtilsService.mergeAreaWithUser(s),r),{}):i;case"allArrows":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.arrowUtilsService.mergeArrowWithUser(s),r),{}):i;case"allCursors":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.cursorUtilsService.mergeCursorUserWithUser(s),r),{}):i;case"allComments":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.commentUtilsService.mergeCommentWithUser(s),r),{}):i;case"allDocumentUsers":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.contactUtilsService.mergeUserIamWithUser(s),r),{}):i;case"allFolderUsers":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.contactUtilsService.mergeUserIamWithUser(s),r),{}):i;case"allOrganizationUsers":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.contactUtilsService.mergeUserIamWithUser(s),r),{}):i;case"allMultiThreads":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.multiThreadUtilsService.mergeMultiThreadWithUser(s),r),{}):i;case"allDocNotifications":return i&&typeof i=="object"?i?.map(r=>this.notificationUtilsService.mergeNotificationWithUser(r)):i;case"allUserNotifications":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.notificationUtilsService.mergeNotificationWithUser(s),r),{}):i;case"allPresence":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.presenceUtilsService.mergePresenceUserWithUser(s),r),{}):i;case"allRecorders":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.recorderUtilsService.mergeRecorderWithUser(s),r),{}):i;case"allReactions":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.reactionUtilsService.mergeReactionWithUser(s),r),{}):i;case"allTags":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.tagUtilsService.mergeTagWithUser(s),r),{}):i;case"allHuddleAttendees":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.huddleUtilsService.mergeHuddleAttendeeWithUser(s),r),{}):i;case"liveStateCustom":return i&&typeof i=="object"&&!Array.isArray(i)?this.liveStateUtilsService.mergeLiveStateCustomWithUser(i):i;case"allLiveStateCustoms":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.liveStateUtilsService.mergeLiveStateCustomWithUser(s),r),{}):i;case"allLiveStates":return i&&typeof i=="object"?this.liveStateUtilsService.mergeLiveStateWithUser(i):i;case"allSelections":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.selectionUtilsService.mergeSelectionWithUser(s),r),{}):i;default:return i}return i}catch(r){return this.loggingService.catch("Error in CommonDbUtilsService mergeUsersWithData:",r),i}}mergeCommentAnnotationsWithData$({data:e,feature:i}){try{return this.commentAnnotationsResolverService.getCommentAnnotationsById$().pipe(ce(()=>{let r=this.mergeCommentAnnotationsWithData({data:e?.data??{},feature:i}),a=this.mergeUsersWithData({feature:i,data:r??{}});return typeof a=="object"?{data:JSON.parse(JSON.stringify(a)),operation:e?.operation??null}:{data:a,operation:e?.operation??null}}),Kt(_o))}catch(r){return this.loggingService.catch("Error in mergeCommentAnnotationsWithData:",r),re(e)}}mergeReactionAnnotationsWithData$({data:e,feature:i}){try{return this.reactionAnnotationsResolverService.getReactionAnnotationsById$().pipe(ce(()=>{let r=this.mergeReactionAnnotationsWithData({data:e?.data??{},feature:i}),a=this.mergeUsersWithData({feature:i,data:r??{}});return typeof a=="object"?{data:JSON.parse(JSON.stringify(a)),operation:e?.operation??null}:{data:a,operation:e?.operation??null}}),Kt(_o))}catch(r){return this.loggingService.catch("Error in mergeReactionAnnotationsWithData:",r),re(e)}}mergeUsersWithData$({feature:e,data:i}){try{return this.usersService.getUserById$().pipe(ce(()=>{let r=this.mergeUsersWithData({feature:e,data:i?.data??{}});return typeof r=="object"?{data:JSON.parse(JSON.stringify(r)),operation:i?.operation??null}:{data:r,operation:i?.operation??null}}),Kt(_o))}catch(r){return this.loggingService.catch(`Error in mergeUsersWithData for ${e}:`,r),re(i)}}mergeLocationMetadataWithData$({data:e,feature:i}){try{return this.docService.getLocationMetadata$().pipe(ce(r=>{let a=this.mergeLocationMetadataWithData({data:e?.data??{},feature:i,locationMetadata:r});return typeof a=="object"?{data:JSON.parse(JSON.stringify(a)),operation:e?.operation??null}:{data:a,operation:e?.operation??null}}),Kt(_o))}catch(r){return this.loggingService.catch(`Error in mergeLocationMetadataWithData for ${i}:`,r),re(e)}}handleDataStripping({feature:e,data:i,actionType:r}){try{switch(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: handleDataStripping","color: green;"),e){case"comment":return this.commentUtilsService.stripCommentAnnotationData({data:i,actionType:r});case"reaction":return this.reactionUtilsService.stripReactionAnnotationData(i);default:return{originalData:i,strippedData:null}}}catch(a){return this.loggingService.catch("Error in CommonDbUtilsService handleDataStripping:",a),{originalData:i,strippedData:null}}}formatData({feature:e,data:i,properties:r,offset:a,isRealtimeDb:s}){try{this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: formatData","color: green;"),typeof i=="object"&&(i=JSON.parse(JSON.stringify(i)));let c=new Date().getTime()+a;switch(e){case"documentAccessType":return delete i?.users,{docIamConfig:i};case"organizationMetadata":case"documentMetadata":return s?i:{metadata:i};case"cursor":return this.cursorUtilsService.formatCursorUserData(i);case"comment":return this.commentUtilsService.formatCommentData(i);case"area":return this.areaUtilsService.formatAreaData(i);case"arrow":return this.arrowUtilsService.formatArrowData(i);case"liveStateCustom":return this.liveStateUtilsService.formatLiveStateCustomData(i);case"liveStateSingleEditorMode":return this.liveStateUtilsService.formatLiveStateSingleEditorModeData(i);case"multiThread":return this.multiThreadUtilsService.formatMultiThreadData(i);case"reaction":return this.reactionUtilsService.formatReactionData(i);case"recorder":return this.recorderUtilsService.formatRecorderData(i,c);case"notificationViewsTimestamp":return{views:{[r.user??""]:i}};case"documentUsersViews":return s?i:{users:{[r.user??""]:{[r.date??""]:i}}};case"documentDayViews":return s?i:{day:{[r.date??""]:{[r.user??""]:i}}};case"documentMetadataViews":return s?i:{metadata:i};case"huddleMessage":return this.huddleUtilsService.formatHuddleMessageData(i);case"locationMetadataViews":return s?i:{metadata:i};case"locationUsersViews":return s?i:{users:{[r.user??""]:{[r.date??""]:i}}};case"locationDayViews":return s?i:{day:{[r.date??""]:{[r.user??""]:i}}};case"locationViews":return s?i:{location:i};case"docNotificationViews":return s?i:{views:i.views};case"userNotificationViews":return s?i:{views:i.views};case"presence":return this.presenceUtilsService.formatPresenceUserData(i);case"selection":return this.selectionUtilsService.formatSelectionData(i);case"tag":return this.tagUtilsService.formatTagData(i);default:return i}}catch(c){return this.loggingService.catch("Error in CommonDbUtilsService formatData:",c),i}}modifyAndSetData(s){return ee(this,arguments,function*({feature:e,data:i,subscriber:r,operation:a=null}){try{let c=yield this.modifyData({feature:e,data:i});r.next({data:c,operation:a})}catch(c){this.loggingService.catch("Error in CommonDbUtilsService modifyAndSetData:",c)}})}isDataAlreadyProcessedInLocalCache({feature:e,change:i,cache:r}){try{if(e==="allReactions"||e==="allComments"){if(i.type==="removed")return!Object.keys(r??{}).includes(i.doc.id);if(r?.[i.doc.id]){let a=i.doc.data(),s=r?.[i.doc.id];return a?.lastUpdated===s?.lastUpdated}}return!1}catch(a){return this.loggingService.catch("Error in CommonDbUtilsService isDataAlreadyProcessedInLocalCache:",a),!1}}modifyData(r){return ee(this,arguments,function*({feature:e,data:i}){try{return yield this.formatResponse({feature:e,data:i})}catch(a){return this.loggingService.catch("Error in CommonDbUtilsService modifyData:",a),i}})}addMetadata(e,i){try{return e&&typeof e=="object"&&!Array.isArray(e)?T(I({},e),{metadata:e?.metadata??{documentId:i?.documentId,organizationId:i?.organizationId,apiKey:i?.apiKey}}):e}catch(r){return this.loggingService.catch("Error in CommonDbUtilsService addMetadata:",r),e}}setDataInLocal(p){return ee(this,arguments,function*({feature:e,data:i,observablesCache:r,eventType:a,id:s,operation:c=null}){try{let _={comment:"allComments",reaction:"allReactions"}[e];if(!_)return null;let E=i?.metadata?.documentId,D=i?.metadata?.veltFolderId;return Object.keys(r).filter(B=>B.includes(_)&&(!E||B.includes(E)||D&&B.includes(D))).forEach(B=>{let G=r[B]?.subject?.getValue()??{};a==="DELETE"?s&&G?.data?.[s]&&(delete G?.data?.[s],r[B]?.subject&&r[B].subject.next({data:G?.data,operation:c})):r[B]?.subject?.next({data:T(I({},G?.data),{[i?.annotationId]:i}),operation:c})}),null}catch(h){return this.loggingService.catch("Error in CommonDbUtilsService setDataInLocal:",h),null}})}handleCommentEncryption(s){return ee(this,arguments,function*({data:e,firestorePath:i,extraData:r,eventType:a}){try{return yield this.commentUtilsService.handleCommentEncryption({data:e,firestorePath:i,extraData:r,eventType:a})}catch(c){return this.loggingService.catch("Error in CommonDbUtilsService handleCommentEncryption:",c),e}})}handleReactionEncryption(a){return ee(this,arguments,function*({data:e,firestorePath:i,eventType:r}){try{return yield this.reactionUtilsService.handleReactionEncryption({data:e,firestorePath:i,eventType:r})}catch(s){return this.loggingService.catch("Error in CommonDbUtilsService handleReactionEncryption:",s),e}})}};o.\u0275fac=function(i){return new(i||o)(J(ase),J(sse),J(Uv),J(lse),J(cse),J(xM),J(dse),J(y),J(pse),J(TM),J(use),J(hse),J(jv),J(fse),J(vse),J(Hn),J(lt),J(vs),J(um))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Cse=(()=>{let o=class o{constructor(e,i,r){this.configService=e,this.authService=i,this.loggingService=r,this.firestore$=new fe(null);try{Dn([this.authService.getFirebaseConfig$(),this.configService.getApiKey$()]).pipe(Ne(([a,s])=>!!a&&!!s),Je(1)).subscribe(([a,s])=>{a&&s&&a?.firebaseOptions?.storeDbId&&this.firestore$.next(Q6(Fp.getFirestoreProdDbName(s,a.firebaseOptions)))},a=>{})}catch{}}getFirestore(){return this.firestore$.asObservable()}getFirestoreValue(){return this.firestore$.value}generateFirestoreDocumentId(){try{let e=this.getFirestoreValue()||Q6("DocumentIdDb");if(e){let i=kS(e,"generateDocumentId");return kv(i).id}return}catch(e){this.loggingService.catch("Error in FirestoreService generateFirestoreDocumentId: ",e);return}}};o.\u0275fac=function(i){return new(i||o)(J($t),J(je),J(y))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var bn=(()=>{let o=class o{constructor(e,i,r,a,s,c,p,h,_,E){this.authService=e,this.commonDbUtilsService=i,this.loggingService=r,this.firestoreService=a,this.databaseService=s,this.configService=c,this.docService=p,this.usersService=h,this.commentAnnotationsResolverService=_,this.reactionAnnotationsResolverService=E,this.offset=0,this.db=null,this.firestore=null,this.subscriptions=[],this.offsetListener=null,this.observablesCache={},this.firestoreSubscriptions={},this.loggingService.log("%c[WB] Creating CLASS: CommonDbService","color: blue;"),this.docService.setCommonDbService(this),this.authService.setCommonDbService(this),this.subscriptions.push(this.databaseService.getDb().subscribe(D=>{if(D){this.db=D;let B=on(D,".info/serverTimeOffset");this.offsetListener=gu(B,G=>{let X=G.val();this.offset=X})}})),this.subscriptions.push(this.firestoreService.getFirestore().subscribe(D=>{D&&(this.firestore=D)}))}unsubscribeFromObservables(){try{Object.values(this.firestoreSubscriptions??{}).forEach(e=>{e?.unsubscribe()}),Object.entries(this.observablesCache??{}).forEach(([e,i])=>{i?.subject?.complete(),i?.subject?.unsubscribe()}),this.observablesCache={},this.firestoreSubscriptions={}}catch(e){this.loggingService.catch("Error in unsubscribeFromObservables:",e)}}ngOnDestroy(){this.subscriptions.forEach(e=>e.unsubscribe()),this.offsetListener&&this.offsetListener(),this.unsubscribeFromObservables()}getOffset(){return this.offset}getServerTimestamp(){return new Date().getTime()+this.getOffset()}subscribeToServices(e){Dn([this.databaseService.getDb(),this.firestoreService.getFirestore()]).pipe(Ne(([i,r])=>!!i),Je(1),In(([i,r])=>{e({db:i,firestore:r})})).subscribe({error:i=>{this.loggingService.catch("Error in CommonDbService subscription: ",i)}})}performDatabaseOperation(e,i,r,a,s,c){return ee(this,null,function*(){try{if(!i){this.loggingService.warn(`%c[WB] No properties found for ${e}`,"color: red;");return}return this.subscribeToServices(_=>ee(this,[_],function*({db:p,firestore:h}){let E;i?.skipFirestore||(E=this.commonDbUtilsService.getFirestorePath({feature:e,properties:i,documentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey()}));let D=this.commonDbUtilsService.getDocumentPath({feature:e,properties:i,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey(),useFirestore:this.shouldUseFirestore()});if(!p){this.loggingService.warn(`%c[WB] No database or firestore found for ${e}`,"color: red;");return}try{let B,G;try{D&&(B=on(p,`${D}`))}catch{this.loggingService.catch("Error in dbRef")}try{E?.includes("/organizations")&&h&&E&&(G=kv(h,`${E}`))}catch{this.loggingService.catch("Error in docRef")}yield r({dbRef:B,firestoreRef:G,data:a,firestorePath:E}),c&&c({firestoreAvailable:!!h})}catch(B){this.loggingService.catch(`Error in ${e} operation: `,B),s&&s(B)}}))}catch(p){this.loggingService.catch("Error in performDatabaseOperation:",p)}})}setData(p){return ee(this,arguments,function*({feature:e,data:i,properties:r,callback:a,errorCallback:s,extraData:c}){try{return this.loggingService.log(`%c[WB] Calling FUNCTION: setData for ${e}`,"color: green;"),this.shouldUseFirestore()&&i?.metadata&&!i?.metadata?.apiKey?void 0:(this.commonDbUtilsService.setDataInLocal({feature:e,data:i,observablesCache:this.observablesCache,operation:null}),this.performDatabaseOperation(e,r,h=>ee(this,null,function*(){if(h.dbRef){let _=this.commonDbUtilsService.formatData({feature:e,data:h.data,properties:r,offset:this.getOffset(),isRealtimeDb:!0});yield Of(h.dbRef,JSON.parse(JSON.stringify(_)))}try{if(h.firestoreRef&&h.data&&!r?.skipFirestore){let _=this.commonDbUtilsService.formatData({feature:e,data:h.data,properties:r,offset:this.getOffset()});typeof _=="object"&&(_=JSON.parse(JSON.stringify(_)));let{strippedData:E,originalData:D,eventType:B}=this.commonDbUtilsService.handleDataStripping({feature:e,data:_,actionType:c?.actionType});if(e==="comment"){let G=null;E&&(G=yield this.commentAnnotationsResolverService.saveCommentAnnotation({commentAnnotation:E,eventType:B,commentId:c?.targetAnnotationData?.commentId})),D&&(G?.isSuccess||G===null)&&(yield this.commonDbUtilsService.handleCommentEncryption({data:D,firestorePath:h.firestorePath??"",extraData:c}))}else if(e==="reaction"){let G=null;E&&(G=yield this.reactionAnnotationsResolverService.saveReactionAnnotation(E)),D&&(G?.isSuccess||G===null)&&(yield this.commonDbUtilsService.handleReactionEncryption({data:D,firestorePath:h.firestorePath??""}))}else yield Qj(h.firestoreRef,_)}}catch(_){this.loggingService.catch(`Error in setData for ${e}`,_)}}),i,s,a))}catch(h){this.loggingService.catch(`Error in setData for ${e}`,h)}})}updateData(p){return ee(this,arguments,function*({feature:e,data:i,properties:r,callback:a,errorCallback:s,extraData:c}){try{return this.loggingService.log(`%c[WB] Calling FUNCTION: updateData for ${e}`,"color: green;"),this.shouldUseFirestore()&&i?.metadata&&!i?.metadata?.apiKey?void 0:(this.commonDbUtilsService.setDataInLocal({feature:e,data:i,observablesCache:this.observablesCache,operation:null}),this.performDatabaseOperation(e,r,h=>ee(this,null,function*(){if(h.dbRef&&!r?.skipRtdb){let _=this.commonDbUtilsService.formatData({feature:e,data:h.data,properties:r,offset:this.getOffset(),isRealtimeDb:!0});yield jA(h.dbRef,JSON.parse(JSON.stringify(_)))}try{if(h.firestoreRef&&h.data&&!r?.skipFirestore){let _=this.commonDbUtilsService.formatData({feature:e,data:h.data,properties:r,offset:this.getOffset()});typeof _=="object"&&(_=JSON.parse(JSON.stringify(_)));let{strippedData:E,originalData:D,eventType:B}=this.commonDbUtilsService.handleDataStripping({feature:e,data:_,actionType:c?.actionType});if(e==="comment"){let G=null;E&&(G=yield this.commentAnnotationsResolverService.saveCommentAnnotation({commentAnnotation:E,eventType:B,commentId:c?.targetAnnotationData?.commentId})),D&&(G?.isSuccess||G===null)&&(yield this.commonDbUtilsService.handleCommentEncryption({data:D,firestorePath:h.firestorePath??"",extraData:c}))}else if(e==="reaction"){let G=null;E&&(G=yield this.reactionAnnotationsResolverService.saveReactionAnnotation(E)),D&&(G?.isSuccess||G===null)&&(yield this.commonDbUtilsService.handleReactionEncryption({data:D,firestorePath:h.firestorePath??""}))}else yield Qj(h.firestoreRef,_,{merge:!0})}}catch(_){this.loggingService.catch(`Error in updateDoc for ${e}`,_)}}),i,s,a))}catch(h){this.loggingService.catch(`Error in updateData for ${e}`,h)}})}deleteData(s){return ee(this,arguments,function*({feature:e,properties:i,callback:r,errorCallback:a}){try{return this.loggingService.log(`%c[WB] Calling FUNCTION: deleteData for ${e}`,"color: green;"),this.commonDbUtilsService.setDataInLocal({feature:e,observablesCache:this.observablesCache,eventType:"DELETE",id:i?.id,operation:{type:"removed",ids:[i?.id]}}),this.performDatabaseOperation(e,i,c=>ee(this,null,function*(){c.dbRef&&(yield VA(c.dbRef));try{if(c.firestoreRef&&!i?.skipFirestore)if(e==="comment"){let p=null;p=yield this.commentAnnotationsResolverService.deleteCommentAnnotation(i?.id??""),(p?.isSuccess||p===null)&&(yield this.commonDbUtilsService.handleCommentEncryption({firestorePath:c.firestorePath??"",eventType:"DELETE"}))}else if(e==="reaction"){let p=null;p=yield this.reactionAnnotationsResolverService.deleteReactionAnnotation(i?.id??""),(p?.isSuccess||p===null)&&(yield this.commonDbUtilsService.handleReactionEncryption({firestorePath:c.firestorePath??"",eventType:"DELETE"}))}else yield Lae(c.firestoreRef)}catch(p){this.loggingService.catch(`Error in deleteData for ${e}`,p)}}),void 0,a,r)}catch(c){this.loggingService.catch(`Error in deleteData for ${e}`,c)}})}shouldUseFirestore(){try{return this.authService.getAdvancedQueriesEnabled()}catch(e){return this.loggingService.catch("Error in shouldUseFirestore:",e),!1}}generateDocumentId(){try{let e=this.firestoreService.generateFirestoreDocumentId();return e||(e=xn()),e||"noDocumentId"}catch(e){return this.loggingService.catch("Error in generateFirestoreDocumentId:",e),xn()||"noDocumentId"}}queryData(r){return ee(this,arguments,function*({feature:e,properties:i}){try{let a=this.shouldUseFirestore();return!e||!i?(this.loggingService.warn("[WB] Missing required parameters in queryData"),[]):a?yield this.handleFirestoreQuery(e,i):yield this.handleRtdbQuery(e,i)}catch(a){return this.loggingService.catch(`Error in queryData for ${e}`,a),[]}})}handleFirestoreQuery(e,i){return ee(this,null,function*(){try{if(!this.firestore)return this.loggingService.warn("[WB] Firestore not initialized"),[];let r=i?.useCollectionGroup?this.commonDbUtilsService.getFirestoreCollectionGroupPath(e):this.commonDbUtilsService.getFirestorePath({feature:e,properties:i,documentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey()});if(!r)return this.loggingService.warn(`[WB] No firestore path found for ${e}`),[];try{let a=kS(this.firestore,r);i?.useCollectionGroup&&(a=Kj(this.firestore,r));let s=i?.firestoreQuery??[],c=Xj(a,...s);if(i?.getCount){let p=yield Vae(c).catch(h=>(this.loggingService.catch(`Error in getCountFromServer for ${e}`,h),null));return p?p.data().count:0}else{let p=yield jae(c).catch(E=>(this.loggingService.catch(`Error in getDocs for ${e}`,E),null));if(!p)return[];let h=p.docs.map(E=>E.data());return yield this.commonDbUtilsService.modifyData({feature:e,data:h})}}catch(a){return this.loggingService.catch(`Error in Firestore query for ${e}:`,a),[]}}catch(r){return this.loggingService.catch(`Error in Firestore query for ${e}:`,r),[]}})}handleRtdbQuery(e,i){return ee(this,null,function*(){if(!this.db)return this.loggingService.warn("[WB] Realtime Database not initialized"),[];let r=this.commonDbUtilsService.getDocumentPath({feature:e,properties:i,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey()});if(!r)return this.loggingService.warn(`[WB] No database path found for ${e}`),[];try{let a=on(this.db,r),s=i?.rtdbQuery??[],c=xL(a,...s),p=yield bL(c).catch(_=>(this.loggingService.catch(`Error in get for ${e}`,_),null));if(!p)return[];let h=p.val();return h?i?.skipObjectValues?h:Object.values(h??{}):[]}catch(a){return this.loggingService.catch(`Error in RTDB query for ${e}:`,a),[]}})}getData(r){return ee(this,arguments,function*({feature:e,properties:i}){try{let a=this.shouldUseFirestore();if(i?.skipFirestore&&(a=!1),!e||!i)return this.loggingService.warn("[WB] Missing required parameters in getData"),{};if(a&&this.firestore){let s=this.commonDbUtilsService.getFirestorePath({feature:e,properties:i,documentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey()});if(!s)return this.loggingService.warn(`[WB] No firestore path found for ${e}`),{};try{let c=yield Uae(kv(this.firestore,s)).catch(h=>(this.loggingService.catch(`Error in getDoc for ${e}`,h),null));if(!c)return this.loggingService.warn(`[WB] No document found at ${s}`),{};let p=c.data();return i?.field?p?.[i.field]??{}:p??{}}catch(c){return this.loggingService.catch(`Error fetching Firestore data for ${e}:`,c),{}}}if(this.db){let s=this.commonDbUtilsService.getDocumentPath({feature:e,properties:i,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey()});if(!s)return this.loggingService.warn(`[WB] No database path found for ${e}`),{};try{let c=yield bL(on(this.db,s)).catch(h=>(this.loggingService.catch(`Error in get for ${e}`,h),null));if(!c)return this.loggingService.warn(`[WB] No data found at ${s}`),{};let p=c.val();return i?.field?p?.[i.field]??{}:p??{}}catch(c){return this.loggingService.catch(`Error fetching RTDB data for ${e}:`,c),{}}}return this.loggingService.warn("[WB] No database connection available"),{}}catch(a){return this.loggingService.catch("Unexpected error in getData:",a),{}}})}dbListener({feature:e,properties:i}){let r=this.shouldUseFirestore();i?.skipFirestore&&(r=!1);let a=`${e}-${JSON.stringify(i)}`;return Dn([this.databaseService.getDb(),this.firestoreService.getFirestore()]).pipe(Ne(([s,c])=>s?r&&!c?(this.loggingService.warn(`[WB] Firestore requested but not available for ${e}`),!1):!0:(this.loggingService.warn(`[WB] No database found for ${e}`),!1)),ge(([s,c])=>{try{if(r&&c){if(!!!this.observablesCache[a]){this.observablesCache[a]={subject:new fe({}),count:0};let _=this.handleFirestoreListener(e,i,c).subscribe(E=>{this.observablesCache[a]?.subject?.next(E)},E=>this.observablesCache[a]?.subject?.error(E));this.firestoreSubscriptions[a]=_}return new Ft(h=>{let _=this.observablesCache[a]?.subject?.subscribe(E=>h.next(E),E=>h.error(E),()=>h.complete());return this.observablesCache[a].count+=1,()=>{_?.unsubscribe(),this.observablesCache[a]&&(this.observablesCache[a].count-=1,this.observablesCache[a].count<=0&&(this.firestoreSubscriptions[a]?.unsubscribe(),delete this.firestoreSubscriptions[a],this.observablesCache[a]?.subject?.complete(),delete this.observablesCache[a]))}})}else if(s)return this.handleRealtimeDbListener(e,i,s);return re({})}catch(p){return this.loggingService.catch(`Error setting up listener for ${e}:`,p),re({})}}),Ig(()=>{this.loggingService.log(`[WB] Cleaning up listener for ${e} and key ${a}`)}))}handleFirestoreListener(e,i,r){let a=i?.useCollectionGroup?this.commonDbUtilsService.getFirestoreCollectionGroupPath(e):this.commonDbUtilsService.getFirestorePath({feature:e,properties:i,documentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey()}),s=`${e}-${JSON.stringify(i)}`;return a?new Ft(c=>{let p=i.isCollection?this.setupCollectionListener(r,a,e,c,i):this.setupDocumentListener(r,a,e,c,i);return()=>{c.complete(),c.unsubscribe(),p(),this.observablesCache[s]?.subject?.complete(),this.observablesCache[s]?.subject?.unsubscribe(),delete this.observablesCache[s]}}).pipe(ge(c=>this.commonDbUtilsService.mergeUsersWithData$({feature:e,data:c})),ge(c=>["allComments","allUserNotifications"].includes(e)?this.commonDbUtilsService.mergeCommentAnnotationsWithData$({data:c,feature:e}):re(c)),ge(c=>["allReactions"].includes(e)?this.commonDbUtilsService.mergeReactionAnnotationsWithData$({data:c,feature:e}):re(c)),Kt(_o)):(this.loggingService.warn(`[WB] No firestore path found for ${e} and key ${s}`),re({}))}setupCollectionListener(e,i,r,a,s){let c=`${r}-${JSON.stringify(s)}`,p=kS(e,i);if(s?.useCollectionGroup&&(p=Kj(e,i)),s?.useQuery&&s?.firestoreQuery){let E=s?.firestoreQuery??[];p=Xj(p,...E)}let h=!0,_=[];return Zj(p,E=>{try{let D=JSON.parse(JSON.stringify(this.observablesCache[c]?.subject?.getValue()?.data??{})),B=null,G=!1;E?.docChanges()?.length?E.docChanges().forEach(X=>{["allComments","allReactions"].includes(r)&&!h&&X.type!=="removed"&&_.push(X.doc.id),this.commonDbUtilsService.isDataAlreadyProcessedInLocalCache({feature:r,change:X,cache:this.observablesCache[c]?.subject?.getValue()?.data??{}})||(G=!0,Object.assign(D,this.handleCollectionChange(X,D)),X.type==="removed"&&(B||(B={type:X.type,ids:[]}),B.ids.push(X.doc.id)))}):G=!0,G&&(["allComments","allReactions"].includes(r)&&_?.length&&(this.commonDbUtilsService.resolveAnnotations({data:_,feature:r}),_=[]),this.commonDbUtilsService.modifyAndSetData({feature:r,data:D,subscriber:a,operation:B})),h=!1}catch(D){this.handleListenerError(D,r,a)}},E=>this.handleListenerError(E,r,a))}handleCollectionChange(e,i){switch(e.type){case"added":case"modified":i[e.doc.id]=e.doc.data();break;case"removed":delete i?.[e.doc.id];break}return i}setupDocumentListener(e,i,r,a,s){let c=kv(e,i);return Zj(c,p=>{try{let h=p.data()||{};s?.field&&(h=h?.[s?.field]??{}),this.commonDbUtilsService.modifyAndSetData({feature:r,data:h,subscriber:a,operation:null})}catch(h){this.handleListenerError(h,r,a)}},p=>this.handleListenerError(p,r,a))}handleListenerError(e,i,r){this.loggingService.catch(`Firestore listener error for ${i}:`,e),r.error(e)}handleRealtimeDbListener(e,i,r){let a=this.commonDbUtilsService.getDocumentPath({feature:e,properties:i,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey()});if(!a)return this.loggingService.warn(`[WB] No database path found for ${e}`),re({});let s=on(r,a);if(i?.useQuery&&i?.rtdbQuery){let c=i?.rtdbQuery??[];s=xL(s,...c)}return Af(s).pipe(Ln(c=>(this.loggingService.catch(`RTDB listener error for ${e}:`,c),re({}))),ce(c=>(c===null&&(c={}),c&&typeof c=="object"?Object.entries(c??{}).reduce((h,[_,E])=>(h[_]=this.commonDbUtilsService.addMetadata(E,i),h),{}):this.commonDbUtilsService.addMetadata(c,i))),ge(c=>this.commonDbUtilsService.modifyData({feature:e,data:c})),ge(c=>this.usersService.getUserById$().pipe(ce(()=>({data:this.commonDbUtilsService.mergeUsersWithData({feature:e,data:c}),operation:null})))))}};o.\u0275fac=function(i){return new(i||o)(J(je),J($v),J(y),J(Cse),J(pn),J($t),J(lt),J(Hn),J(vs),J(um))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var gi=(()=>{let o=class o{constructor(e,i,r,a,s,c,p,h){this.analyticsService=e,this.authService=i,this.configService=r,this.databaseService=a,this.docService=s,this.loggingService=c,this.commonDbService=p,this.usersService=h,this.db=Ci(),this.internalUserContacts$=new fe([]),this.userGlobalContact$=new fe(!1),this.userGroupContact$=new fe(null),this.users$=new fe([]),this.userPersonalContacts=[],this.userGroupContacts=[],this.userGlobalContacts=[],this.users=[],this.documentPaths=null,this.userOrganizationContacts$=new fe([]),this.userFolderContacts$=new fe([]),this.userDocumentContacts$=new fe([]),this.userOrganizationGroups$=new fe([]),this.onContactSelectedSubject$=new et,this.documentAccessType=null,this.atHereEnabled$=new fe(!1),this.atHereLabel$=new fe("here"),this.atHereDescription$=new fe(null),this.contactListScopeForOrganizationUsers$=new fe([xi.ALL]),this.customUserContacts$=new fe(null),this.customUserContactsConfig$=new fe({merge:!1}),this.currentOrganizationUserIAM$=new fe(null),this.userContacts$=new fe([]),this.userSnippylyIdContacts$=new fe(null),this.usersByOrganizationId$=new fe({}),this.usersByOrganizationIdAndDocumentId$=new fe({}),this.usersByOrganizationIdAndFolderId$=new fe({}),this.userById$=new fe({}),this.authService.setContactService(this),this.authService.getUser$().pipe(ge(_=>this.docService.getDocumentPaths$().pipe(In(E=>{this.documentPaths=E}),ce(()=>_)))).subscribe(_=>ee(this,null,function*(){this.user=_,_&&this.documentPaths?_?.organizationId?(this.getOrganizationContactsFromDb$(),this.getFolderContactsFromDb$(),this.getDocumentContactsFromDb$(),this.getOrganizationGroupsFromDb$()):(this.getLoggedInUsers$().subscribe(),this.getUserContactsFromDb$(),yield this.migrateLoggedInUserFromEmailToUserIdPath(_),this.setLoggedInUser(_),yield this.moveGlobalContactUserFromEmailToUserIdPath(_),this.updateUserInGlobalContactsIfAvailable(_),_?.groupId&&(yield this.migrateGroupContactsFromEmailToUserIdPath(_?.groupId)),this.checkToSetLoggedInUserInGroupContacts()):(this.getUserContactSubscription?.unsubscribe(),this.getLoggedInUsersSubscription?.unsubscribe(),this.getOrganizationContactsSubscription?.unsubscribe(),this.getFolderContactsSubscription?.unsubscribe(),this.getDocumentContactsSubscription?.unsubscribe(),this.getOrganizationGroupsSubscription?.unsubscribe())}),_=>{this.loggingService.catch("Error in ContactService constructor getUser$: ",_)}),this.databaseService.getDb().pipe(Ne(_=>!!_),Je(1)).subscribe(_=>{_&&(this.db=_)},_=>{this.loggingService.catch("Error in ContactService constructor getDb: ",_)}),this.getOrganizationGroups$().subscribe(_=>{this.authService.setOrganizationUserGroups(_)}),Dn([this.getInternalUserContacts$(),this.getCustomUserContacts$(),this.getCustomUserContactsConfig$()]).subscribe(([_,E,D])=>{E?D?.merge?this.userContacts$.next([..._||[],...E||[]]):this.userContacts$.next(E||[]):this.userContacts$.next(_||[])}),this.getUserContacts$().subscribe(_=>{try{_?.forEach(E=>{let D=E?.userSnippylyId||ov(this.configService.getApiKey(),E.userId);D&&this.userSnippylyIdContacts$.next(T(I({},this.userSnippylyIdContacts$.value),{[D]:E}))})}catch{}})}clearCache(){this.loggingService.log("%c[WB] Calling FUNCTION: clearCache in ContactService","color: green;");try{this.documentPaths=null,this.usersByOrganizationId$.next({}),this.usersByOrganizationIdAndFolderId$.next({}),this.usersByOrganizationIdAndDocumentId$.next({}),this.userById$.next({}),this.userOrganizationContacts$.next([]),this.userFolderContacts$.next([]),this.userDocumentContacts$.next([]),this.userOrganizationGroups$.next([]),this.userContacts$.next([]),this.userSnippylyIdContacts$.next(null),this.userGlobalContact$.next(!1),this.userGroupContact$.next(null),this.users$.next([]),this.userPersonalContacts=[],this.userGroupContacts=[],this.userGlobalContacts=[],this.users=[]}catch(e){this.loggingService.catch("Error in ContactService clearCache: ",e)}}setDocumentAccessType(e){try{this.documentAccessType=e}catch(i){this.loggingService.catch("Error in ContactService setDocumentAccessType: ",i)}}checkIfUserGlobalContact(e){return ee(this,null,function*(){try{if(e?.userId&&this.documentPaths?.globalContacts){let i=yield this.commonDbService?.getData({feature:"globalContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Rt(e?.userId),skipFirestore:!0}});if(Object.keys(i??{}).length>0)return!0}if(e?.email&&this.documentPaths?.globalContacts){let i=yield this.commonDbService?.getData({feature:"globalContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Rt(e?.email),skipFirestore:!0}});if(Object.keys(i??{}).length>0)return!0}return!1}catch(i){return this.loggingService.catch("Error in ContactService isUserGlobalContact: ",i),!1}})}setLoggedInUser(e){try{e?.userId&&this.documentPaths?.logins&&(this.commonDbService.updateData({feature:"logins",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Rt(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(T(I({},e),{contacts:void 0})))}),this.setLoggedInUserPrivateContacts(e,e?.contacts))}catch(i){this.loggingService.catch("Error in ContactService setLoggedInUser: ",i)}}migrateLoggedInUserFromEmailToUserIdPath(e){return ee(this,null,function*(){try{if(e?.email&&this.documentPaths?.logins){let i=yield this.commonDbService?.getData({feature:"logins",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Rt(e?.email),skipFirestore:!0}});if(Object.keys(i??{}).length>0){let r=i;if(r){if(r?.contacts){let a={};Object.keys(r?.contacts??{})?.forEach(s=>{let c=r.contacts[s];if(c?.userId){let p=Rt(c?.userId);a[p]=c}}),r.contacts=a}yield this.commonDbService.updateData({feature:"logins",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Rt(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(r))}),yield this.commonDbService.deleteData({feature:"logins",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Rt(e?.email),skipFirestore:!0}})}}}}catch(i){this.loggingService.catch("Error in ContactService migrateLoggedInUserFromEmailToUserIdPath: ",i)}})}addGlobalContact(e){try{e?.userId&&this.documentPaths?.globalContacts&&this.commonDbService.updateData({feature:"globalContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Rt(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(e))})}catch(i){this.loggingService.catch("Error in ContactService addGlobalContact: ",i)}}updateUserInGlobalContactsIfAvailable(e){return ee(this,null,function*(){try{if(e?.userId&&this.documentPaths?.globalContacts&&(yield this.checkIfUserGlobalContact(e))){let r=new wo;r.userId=e?.userId,r.userSnippylyId=e?.userSnippylyId,r.email=e?.email,r.name=e?.name,r.photoUrl=e?.photoUrl,this.commonDbService.updateData({feature:"globalContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Rt(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(r))})}}catch(i){this.loggingService.catch("Error in ContactService updateUserInGlobalContactsIfAvailable: ",i)}})}moveGlobalContactUserFromEmailToUserIdPath(e){return ee(this,null,function*(){try{if(e?.email&&e?.userId&&this.documentPaths?.globalContacts){let i=yield this.commonDbService?.getData({feature:"globalContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Rt(e?.email),skipFirestore:!0}});if(Object.keys(i??{}).length>0){let r=i;r&&(yield this.commonDbService.updateData({feature:"globalContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Rt(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(r))}),yield this.commonDbService.deleteData({feature:"globalContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Rt(e?.email),skipFirestore:!0}}))}}}catch(i){this.loggingService.catch("Error in ContactService removeUserFromGlobalContactsByEmail: ",i)}})}setLoggedInUserPrivateContacts(e,i){try{if(e?.userId&&this.documentPaths?.logins){let r,a=i?.filter(c=>c?.visibility!=="group"),s=!1;this.authService.getUserOptions()&&(s=!!this.authService.getUserOptions()?.replaceContacts||!!this.authService.getUserOptions()?.replacePrivateContacts),a?.length?(r={},a?.forEach(c=>{if(c?.userId){let p=Rt(c?.userId);r[p]=c}}),s?this.commonDbService.setData({feature:"allLoginContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Rt(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(r))}):this.commonDbService.updateData({feature:"allLoginContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Rt(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(r))})):s&&this.commonDbService.deleteData({feature:"allLoginContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Rt(e?.userId),skipFirestore:!0}})}}catch(r){this.loggingService.catch("Error in ContactService setLoggedInUserPrivateContacts: ",r)}}migrateGroupContactsFromEmailToUserIdPath(e){return ee(this,null,function*(){try{if(this.documentPaths?.groupContacts&&e){let i=yield this.commonDbService?.getData({feature:"groupContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",groupId:e,skipFirestore:!0}});i&&Object.keys(i??{}).forEach(r=>ee(this,null,function*(){let a=i[r];a?.email&&a?.userId&&Rt(a?.email)===r&&(yield this.commonDbService.deleteData({feature:"groupContactsUser",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",groupId:e,userId:r,skipFirestore:!0}}),yield this.commonDbService.updateData({feature:"groupContactsUser",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",groupId:e,userId:Rt(a?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(a))}))}))}}catch(i){this.loggingService.catch("Error in ContactService migrateGroupContacts: ",i)}})}checkToSetLoggedInUserInGroupContacts(){return ee(this,null,function*(){try{this.user?.groupId&&this.user?.userId&&((yield this.checkIfUserGlobalContact(this.user))||this.docService.getDocumentIam$().pipe(Je(1)).subscribe(i=>ee(this,null,function*(){if(this.user?.groupId&&this.user?.userId){let r=!1,a=this.docService.getDocumentAccessType(i);if(!a||a===di.PUBLIC)r=!0;else if(a===di.RESTRICTED){let s=Rt(this.user?.userId);if(i?.users?.[s]&&(r=!0),this.user?.email){let c=Rt(this.user?.email);i?.users?.[c]&&(r=!0)}}if(r){let s=new Rp;s.email=this.user.email,s.visibility="group",s.name=this.user.name,s.photoUrl=this.user.photoUrl,s.userId=this.user.userId,(this.authService.getUserOptions()?.replaceContacts||this.authService.getUserOptions()?.replaceGroupContacts)&&(yield this.removeGroupContacts(this.user?.groupId)),this.setLoggedInUserGroupContacts(this.user?.groupId,[s]),this.user?.contacts&&this.user?.groupId&&this.setLoggedInUserGroupContacts(this.user?.groupId,this.user?.contacts)}}})))}catch(e){this.loggingService.catch("Error in ContactService checkToSetLoggedInUserInGroupContacts: ",e)}})}setLoggedInUserGroupContacts(e,i){try{let r=i?.filter(a=>a?.visibility==="group");r?.length&&r.forEach(a=>ee(this,null,function*(){if(a?.userId&&e&&this.documentPaths?.groupContacts){if(this.configService?.getSF()&&(yield this.checkIfUserGlobalContact(a)))return;yield this.commonDbService.updateData({feature:"groupContactsUser",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",groupId:e,userId:Rt(a?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(a))}),a?.email&&(yield this.commonDbService.deleteData({feature:"groupContactsUser",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",groupId:e,userId:Rt(a?.email),skipFirestore:!0}}))}}))}catch(r){this.loggingService.catch("Error in ContactService setLoggedInUserGroupContacts: ",r)}}removeGroupContacts(e){return ee(this,null,function*(){try{if(this.documentPaths?.groupContacts&&e)return this.commonDbService.deleteData({feature:"groupContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",groupId:e,skipFirestore:!0}})}catch(i){this.loggingService.catch("Error in ContactService removeGroupContacts: ",i)}})}mergeUserContacts(){try{let e=[];this.userPersonalContacts&&e.push(...this.userPersonalContacts),this.userGroupContacts&&e.push(...this.userGroupContacts),this.userGlobalContacts&&e.push(...this.userGlobalContacts);let i={};e.forEach(r=>{r?.userId?(!r?.email||!i[r.email])&&(i[r.userId]=r):r?.email&&(!r?.userId||!i[r.userId])&&(i[r.email]=r)}),e=Object.values(i??{}),this.internalUserContacts$.next(e)}catch(e){this.loggingService.catch("Error in ContactService mergeUserContacts: ",e)}}getInternalUserContacts(){return this.internalUserContacts$.value}getInternalUserContacts$(){return this.internalUserContacts$.asObservable()}getUserContacts$(e){try{let{organizationId:i,documentId:r,veltFolderId:a}=e||{};return i&&r?Dn([this.usersByOrganizationId$,this.usersByOrganizationIdAndFolderId$,this.usersByOrganizationIdAndDocumentId$,this.userById$,this.customUserContacts$,this.customUserContactsConfig$,this.getContactListScopeForOrganizationUsers$()]).pipe(ce(([s,c,p,h,_,E,D])=>{let B={},G=!1;E&&!E?.merge&&(G=!0);let X=We=>D.some(ke=>We.includes(ke)),he=X([xi.ALL,xi.ORGANIZATION])?Object.keys(s?.[i]||{}):[],Ie=a?X([xi.ALL,xi.FOLDER])?Object.keys(c?.[i]?.[a]||{}):[]:[],Me=X([xi.ALL,xi.DOCUMENT])?Object.keys(p?.[i]?.[r]||{}):[];if([...he,...Ie||[],...Me].forEach(We=>{let ke=h?.[We];ke&&(B[We]=ke)}),_){let{merge:We,options:ke}=E||{},{organizationId:we,documentId:Ee,folderId:Pe}=ke||{},Ce=Pe?hl(Pe):void 0;(!we||we===i)&&(!Ee||Ee===r)&&(!Ce||Ce===a)&&(We||(B={}),_.forEach(ue=>{ue?.userId&&(B[ue.userId]=ue)}))}return Object.values(B??{})})):this.userContacts$.asObservable().pipe(ce(s=>s))}catch(i){return this.loggingService.catch("Error in ContactService getUserContacts$ metadata: ",i),re([])}}getUserContactsBySnippylyId$(){return this.userSnippylyIdContacts$.asObservable()}getAtHereLabel(){return this.atHereLabel$.asObservable()}getAtHereDescription(){return this.atHereDescription$.asObservable()}getUserContactsFromDb$(){this.getUserContactSubscription||(this.getUserContactSubscription=this.authService.getUser$().pipe(Ne(e=>!!e),ge(e=>this.docService.getDocumentPaths$().pipe(Ne(i=>!!i),In(i=>{this.documentPaths=i}),ce(()=>e))),ge(e=>{if(this.userGroupContacts=[],this.userPersonalContacts=[],!e)return re();if(!this.documentPaths)return re();let i=[];return i.push(this.commonDbService.dbListener({feature:"allGlobalContacts",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,skipFirestore:!0}}).pipe(ce(r=>r?.data),In(r=>{r?(this.userGlobalContacts=Object.values(r??{}),this.userGlobalContacts?.find(a=>a.userId===this.user?.userId)?this.userGlobalContact$.next(!0):this.userGlobalContact$.next(!1)):(this.userGlobalContacts=[],this.userGlobalContact$.next(!1))}))),i.push(this.commonDbService.dbListener({feature:"groupContacts",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,skipFirestore:!0,groupId:e?.groupId}}).pipe(ce(r=>r?.data),In(r=>{r?(this.userGroupContacts=Object.values(r??{}),this.userGroupContacts?.find(a=>a?.userId===this.user?.userId)?this.userGroupContact$.next(!0):this.userGroupContact$.next(!1)):(this.userGroupContacts=[],this.userGroupContact$.next(!1))}))),i.push(this.commonDbService.dbListener({feature:"allLoginContacts",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,skipFirestore:!0,userId:Rt(e?.userId)}}).pipe(ce(r=>r?.data),In(r=>{r?this.userPersonalContacts=Object.values(r??{}):this.userPersonalContacts=[]}))),io(...i).pipe(oo(this.authService.getUser$().pipe(Ne(r=>!r))))})).subscribe(()=>{this.mergeUserContacts()},e=>{this.loggingService.catch("Error in ContactService getUserContacts$ subscription: ",e)}))}addUserContact(e){try{this.user?.organizationId||this.user?.groupId&&(e.visibility="group",this.setLoggedInUserGroupContacts(this.user?.groupId,[e]))}catch(i){this.loggingService.catch("Error in ContactService addUserContact: ",i)}}isUserGlobalContact$(){return this.userGlobalContact$.asObservable()}isUserGlobalContact(){return this.userGlobalContact$.value}isUserGroupContact$(){return this.userGroupContact$.asObservable()}isUserGroupContact(){return this.userGroupContact$.value}getLoggedInUsers$(){return this.getLoggedInUsersSubscription||(this.getLoggedInUsersSubscription=this.authService.getUser$().pipe(ge(e=>e?this.documentPaths?e?.userId&&this.documentPaths?.logins?this.commonDbService.dbListener({feature:"allLogins",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,skipFirestore:!0}}).pipe(ce(i=>i?.data),In(i=>{i?this.users=Object.values(i??{}):this.users=[]})):(this.users=[],re()):re():re())).subscribe(()=>{this.users$.next(this.users)},e=>{this.loggingService.catch("Error in ContactService getLoggedInUsers$ subscription: ",e)})),this.users$.asObservable()}getUsersMap$(){return this.authService.getUser$().pipe(ge(e=>e?.organizationId?this.userById$.pipe(ce(i=>{let r={};return Object.values(i||{}).forEach(a=>{a?.userSnippylyId&&(r[a?.userSnippylyId]=a)}),r})):this.users$.pipe(ce(i=>{let r={};return i.forEach(a=>{r[a.userSnippylyId]=a}),r}))))}getUserByEmail$(e){return this.users$.pipe(ce(i=>i.find(r=>r.email===e)))}getUserByEmail(e){return this.users?.find(i=>i.email===e)}getContactByEmail(e){return this.getInternalUserContacts().find(i=>i.email===e)}getUserByUserId$(e){return this.users$.pipe(ce(i=>i.find(r=>r.userId===e)))}getUserGroupContacts(){return this.userGroupContacts}getOrganizationContactsFromDb$(){try{this.getOrganizationContactsSubscription||(this.getOrganizationContactsSubscription=this.authService.getUser$().pipe(ge(e=>e?.organizationId?re(e).pipe(ge(i=>this.docService.getOrganizationConfig$().pipe(Ne(r=>!!r),ce(()=>i))),ge(i=>{let r=this.docService.getOrganizationConfig()?.organizationId;return this.setUserOrganizationContacts([],r),i?r?this.commonDbService.dbListener({feature:"allOrganizationUsers",properties:{organizationId:r,isCollection:!0}}).pipe(ce(a=>a?.data),ce(a=>{if(a){typeof a=="object"&&(a?.undefined&&delete a.undefined,a?.null&&delete a.null);let s=Object.values(a??{});this.setUserOrganizationContacts(s,r)}else this.setUserOrganizationContacts([],r)})):re():re()}),ge(()=>this.getContactListScopeForOrganizationUsers$())):(this.setUserOrganizationContacts([]),re()))).subscribe(()=>{this.mergeOrganizationAndDocumentContacts()},e=>{this.loggingService.catch("Error in ContactService getOrganizationContactsFromDb$ subscription: ",e)}))}catch{}}getFolderContactsFromDb$(){try{this.getFolderContactsSubscription||(this.getFolderContactsSubscription=this.authService.getUser$().pipe(ge(e=>e?re(e).pipe(ge(i=>this.docService.getOrganizationConfig$().pipe(Ne(r=>!!r),ce(()=>i))),ge(i=>this.docService.getFolderConfig$().pipe(ce(()=>i))),ge(i=>{let r=this.docService.getOrganizationConfig()?.organizationId;if(this.setUserFolderContacts([]),!i)return re();if(!this.commonDbService.shouldUseFirestore())return re();let a=this.docService.getFolderConfig();if(!a?.veltFolderId)return re();let s=re([]);return s=this.commonDbService.dbListener({feature:"allFolderUsers",properties:{organizationId:r,folderId:a?.veltFolderId,isCollection:!0}}).pipe(ce(c=>c?.data)),s.pipe(ce(c=>{if(c){typeof c=="object"&&(c?.undefined&&delete c.undefined,c?.null&&delete c.null);let p=Object.values(c??{});this.setUserFolderContacts(p)}else this.setUserFolderContacts([])}))}),ge(()=>this.getContactListScopeForOrganizationUsers$())):(this.setUserFolderContacts([]),re()))).subscribe(()=>{this.mergeOrganizationAndDocumentContacts()},e=>{this.loggingService.catch("Error in ContactService getFolderContactsFromDb$ subscription: ",e)}))}catch{}}getDocumentContactsFromDb$(){try{this.getDocumentContactsSubscription||(this.getDocumentContactsSubscription=this.authService.getUser$().pipe(ge(e=>e?re(e).pipe(ge(i=>this.docService.getDocumentPaths$().pipe(Ne(r=>!!r),In(r=>{this.documentPaths=r}),ce(()=>i))),ge(i=>(this.setUserDocumentContacts([]),i?this.documentPaths?this.docService.getDocumentIds$().pipe(ge(r=>{let a=r?.length>0?r.map(h=>h.documentId):[this.documentPaths?.documentId??""];if(a.some(h=>!h)||!this.documentPaths)return re();let s=this.docService.getFolderConfig(),c=re([]),p={useCollectionGroup:!0,isCollection:!0,useQuery:!0};if(this.commonDbService.shouldUseFirestore()||(p.documentId=a?.length?a[0]:void 0,p.organizationId=this.documentPaths?.organizationId),s?.veltFolderId&&s?.allDocuments)c=this.commonDbService.dbListener({feature:"allDocumentUsers",properties:T(I({},p),{firestoreQuery:[Fi(mt("metadata.apiKey","==",this.configService?.getApiKey()),mt("metadata.veltFolderId","==",s?.veltFolderId),mt("metadata.organizationId","==",this.documentPaths?.organizationId))]})}).pipe(ce(h=>h?.data));else{let h=[];for(let _=0;_<a.length;_+=U.LISTENER_BATCH_SIZE)h.push(a.slice(_,_+U.LISTENER_BATCH_SIZE));c=Dn(h.map(_=>this.commonDbService.dbListener({feature:"allDocumentUsers",properties:T(I({},p),{firestoreQuery:[Fi(mt("metadata.apiKey","==",this.configService?.getApiKey()),mt("metadata.documentId","in",_),mt("metadata.organizationId","==",this.documentPaths?.organizationId),...s?.veltFolderId?[mt("metadata.veltFolderId","==",s?.veltFolderId)]:[])]})}).pipe($r()))).pipe(ce(_=>ca(_)?.data))}return c.pipe(ce(h=>{if(h){typeof h=="object"&&(h?.undefined&&delete h.undefined,h?.null&&delete h.null);let _=Object.values(h??{});this.setUserDocumentContacts(_)}else this.setUserDocumentContacts([])}))})):re():re())),ge(()=>this.getContactListScopeForOrganizationUsers$())):(this.setUserDocumentContacts([]),re()))).subscribe(()=>{this.mergeOrganizationAndDocumentContacts()},e=>{this.loggingService.catch("Error in ContactService getDocumentContactsFromDb$ subscription: ",e)}))}catch{}}setUserOrganizationContacts(e,i){try{let r=e.find(s=>s.user.userId===this.user?.userId);r?this.currentOrganizationUserIAM$.next(r):this.currentOrganizationUserIAM$.next(null);let a=e.map(s=>s.user);if(this.userOrganizationContacts$.next(a),i){let s={};s[i]={},e.forEach(c=>{s[i][c.user.userId]=c,this.userById$.next(T(I({},this.userById$.value),{[c.user.userId]:c.user}))}),this.usersByOrganizationId$.next(T(I({},this.usersByOrganizationId$.value),{[i]:s[i]}))}else this.usersByOrganizationId$.next({})}catch(r){this.loggingService.catch("Error in ContactService setUserOrganizationContacts: ",r)}}getUserOrganizationContacts$(){return this.getContactListScopeForOrganizationUsers$().pipe(ge(()=>this.checkContactListScopeForOrganizationUsers([xi.ALL,xi.ORGANIZATION])?this.userOrganizationContacts$.asObservable():re([])))}getUserOrganizationContacts(){return this.checkContactListScopeForOrganizationUsers([xi.ALL,xi.ORGANIZATION])?this.userOrganizationContacts$.value:[]}setUserFolderContacts(e){try{this.userFolderContacts$.next(e?.map(r=>r?.user));let i={};e?.forEach(r=>{let{organizationId:a,veltFolderId:s}=r?.metadata||{};a&&s&&(i[a]||(i[a]={}),i[a][s]||(i[a][s]={}),i[a][s][r.user.userId]=r,this.userById$.next(T(I({},this.userById$.value),{[r.user.userId]:r.user})))}),this.usersByOrganizationIdAndFolderId$.next(i)}catch(i){this.loggingService.catch("Error in ContactService updateUserFolderContacts: ",i)}}getUserFolderContacts$(){return this.getContactListScopeForOrganizationUsers$().pipe(ge(()=>this.checkContactListScopeForOrganizationUsers([xi.ALL,xi.FOLDER])?this.userFolderContacts$.asObservable():re([])))}getUserFolderContacts(){return this.checkContactListScopeForOrganizationUsers([xi.ALL,xi.FOLDER])?this.userFolderContacts$.value:[]}setUserDocumentContacts(e){try{this.userDocumentContacts$.next(e?.map(r=>r?.user));let i={};e?.forEach(r=>{let{organizationId:a,documentId:s}=r?.metadata||{};a&&s&&(i[a]||(i[a]={}),i[a][s]||(i[a][s]={}),i[a][s][r.user.userId]=r,this.userById$.next(T(I({},this.userById$.value),{[r.user.userId]:r.user})))}),this.usersByOrganizationIdAndDocumentId$.next(i)}catch(i){this.loggingService.catch("Error in ContactService updateUserDocumentContacts: ",i)}}getUserDocumentContacts$(){return this.getContactListScopeForOrganizationUsers$().pipe(ge(()=>this.checkContactListScopeForOrganizationUsers([xi.ALL,xi.DOCUMENT])?this.userDocumentContacts$.asObservable():re([])))}getUserDocumentContacts(){return this.checkContactListScopeForOrganizationUsers([xi.ALL,xi.DOCUMENT])?this.userDocumentContacts$.value:[]}getCurrentOrganizationUserIAM$(){return this.currentOrganizationUserIAM$.asObservable()}getCurrentOrganizationUserIAM(){return this.currentOrganizationUserIAM$.value}mergeOrganizationAndDocumentContacts(){try{let e=[];this.getContactListScopeForOrganizationUsers().includes(xi.ALL)?e=[...this.getUserOrganizationContacts(),...this.getUserFolderContacts(),...this.getUserDocumentContacts()]:this.getContactListScopeForOrganizationUsers().includes(xi.ORGANIZATION)?e=[...this.getUserOrganizationContacts()]:this.getContactListScopeForOrganizationUsers().includes(xi.FOLDER)?e=[...this.getUserFolderContacts()]:this.getContactListScopeForOrganizationUsers().includes(xi.DOCUMENT)&&(e=[...this.getUserDocumentContacts()]);let i=[...new Map(e.filter(r=>r?.userId).map(r=>[r.userId,r])).values()];this.internalUserContacts$.next(i)}catch(e){this.loggingService.catch("Error in ContactService mergeOrganizationAndDocumentContacts: ",e)}}getOrganizationGroupsFromDb$(){try{this.getOrganizationGroupsSubscription||(this.getOrganizationGroupsSubscription=this.authService.getUser$().pipe(ge(e=>e?.organizationId?re(e).pipe(ge(i=>this.docService.getOrganizationConfig$().pipe(Ne(r=>!!r),ce(()=>i))),ge(i=>{if(this.setUserOrganizationGroups([]),!i)return re();let r=this.docService.getOrganizationConfig()?.organizationId;return r?this.commonDbService.dbListener({feature:"allOrganizationGroups",properties:{organizationId:r,isCollection:!0}}).pipe(ce(a=>a?.data),ce(a=>{a?(typeof a=="object"&&(a?.undefined&&delete a.undefined,a?.null&&delete a.null),this.setUserOrganizationGroups(Object.values(a??{}))):this.setUserOrganizationGroups([])})):re()})):(this.setUserOrganizationGroups([]),re()))).subscribe(()=>{},e=>{this.loggingService.catch("Error in ContactService getOrganizationGroupsFromDb$ subscription: ",e)}))}catch{}}setUserOrganizationGroups(e){try{this.userOrganizationGroups$.next(e)}catch(i){this.loggingService.catch("Error in ContactService setUserOrganizationGroups: ",i)}}onContactSelected(e){try{if(e?.userId){let i=!!this.getUserDocumentContacts().find(a=>a.userId===e.userId),r=!!this.getUserOrganizationContacts().find(a=>a.userId===e.userId);switch(this.documentAccessType){case di.RESTRICTED:if(!i){let a={contact:e,isOrganizationContact:r,isDocumentContact:i,documentAccessType:this.documentAccessType};this.onContactSelectedSubject$.next(a)}break}}else{let i={contact:e,isOrganizationContact:!1,isDocumentContact:!1,documentAccessType:this.documentAccessType};this.onContactSelectedSubject$.next(i)}}catch(i){this.loggingService.catch("Error in ContactService onContactSelected: ",i)}}onContactSelected$(){return this.onContactSelectedSubject$.asObservable()}getOrganizationGroups$(){return this.getContactListScopeForOrganizationUsers$().pipe(ge(()=>this.checkContactListScopeForOrganizationUsers([xi.ALL,xi.ORGANIZATION_USER_GROUP])?this.userOrganizationGroups$.asObservable():re([])))}enableAtHere(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{atHereEnabled:!0}}),this.atHereEnabled$.value===!0)return;this.atHereEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in ContactService enableAtHere: ",e)}}setAtHereLabel(e){try{this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{atHereLabel:e}}),e&&this.atHereLabel$.next(e)}catch(i){this.loggingService.catch("Error in ContactService setAtHereLabel: ",i)}}setAtHereDescription(e){try{this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{atHereDescription:e}}),e&&this.atHereDescription$.next(e)}catch(i){this.loggingService.catch("Error in ContactService setAtHereDescription: ",i)}}disableAtHere(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{atHereEnabled:!1}}),this.atHereEnabled$.value===!1)return;this.atHereEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in ContactService disableAtHere: ",e)}}getAtHereEnabled$(){return this.getContactListScopeForOrganizationUsers$().pipe(ge(()=>this.checkContactListScopeForOrganizationUsers([xi.ALL,xi.DOCUMENT])?this.atHereEnabled$.asObservable():re(!1)))}getAtHereEnabled(){return this.checkContactListScopeForOrganizationUsers([xi.ALL,xi.DOCUMENT])?this.atHereEnabled$.value:!1}updateContactListScopeForOrganizationUsers(e){try{this.contactListScopeForOrganizationUsers$.next(e)}catch(i){this.loggingService.catch("Error in ContactService updateContactListScopeForOrganizationUsers: ",i)}}getContactListScopeForOrganizationUsers$(){return this.contactListScopeForOrganizationUsers$.asObservable()}getContactListScopeForOrganizationUsers(){return this.contactListScopeForOrganizationUsers$.value}checkContactListScopeForOrganizationUsers(e){return this.getContactListScopeForOrganizationUsers().some(i=>e.includes(i))}updateContactList(e,i){return ee(this,null,function*(){try{if(this.analyticsService.trackEvent(Z.Events.Contact.UPDATE_CONTACT_LIST_TRIGGERED,{contactsCount:e?.length,config:i}),this.usersService?.userDataProviderAvailable()){let r=e.map(s=>s?.userId).filter(s=>s);yield this.usersService.resolveUsers(r);let a=r.map(s=>this.usersService.getUserById(s)).filter(s=>!!s);this.customUserContacts$.next(a)}else this.customUserContacts$.next(e);this.customUserContactsConfig$.next(i)}catch(r){this.loggingService.catch("Error in CommentService updateContactList: ",r)}})}convert(e){try{if(e?.options){let{documentId:i,organizationId:r}=this.docService.getServerId(e?.options);e.options=T(I({},e?.options),{documentId:i,organizationId:r})}return this}catch(i){return this.loggingService.catch("Error in ContactService convert: ",i),this}}getContactList$(){try{return this.authService.getUser$().pipe(ge(e=>e?Dn([this.userOrganizationContacts$.asObservable(),this.userFolderContacts$.asObservable(),this.userDocumentContacts$.asObservable(),this.userOrganizationGroups$.asObservable(),this.customUserContacts$.asObservable()]).pipe(ce(([i,r,a,s,c])=>{let p={};p.organizationUsers=i?.map(_=>this.convertToClientUser(_)),p.folderUsers=r?.map(_=>this.convertToClientUser(_)),p.documentUsers=a?.map(_=>this.convertToClientUser(_)),p.updatedContactList=c?.map(_=>this.convertToClientUser(_));let h=[];return s?.forEach(_=>{let E=this.convertToClientUserGroup(_,p.organizationUsers||[]);E&&h.push(E)}),p.userGroups=h,p}),Kt(_o)):re(null)),Ln(e=>(this.loggingService.catch("Error in ContactService getContactList$: ",e),re(null))))}catch(e){return this.loggingService.catch("Error in ContactService getContactList$: ",e),re(null)}}convertToClientUserGroup(e,i){try{let r={groupId:e?.metadata?.clientGroupId,groupName:e?.metadata?.groupName,users:[]},a={};return i?.forEach(s=>{if(s?.userId){let c=Rt(s.userId);a[c]=s}}),Object.keys(e?.users??{}).forEach(s=>{a[s]&&r.users?.push(a[s])}),r}catch(r){return this.loggingService.catch("Error in ContactService convertToClientUserGroup: ",r),null}}convertToClientUser(e){try{return e&&(e=JSON.parse(JSON.stringify(e)),e?.clientGroupId&&(e.groupId=e.clientGroupId,delete e.clientGroupId),e?.clientOrganizationId&&(e.organizationId=e.clientOrganizationId,delete e.clientOrganizationId),e?.userSnippylyId&&delete e.userSnippylyId),e}catch(i){return this.loggingService.catch("Error in ContactService convertToClientUser: ",i),e}}getCustomUserContacts(){return this.customUserContacts$.value}getCustomUserContacts$(){return this.customUserContacts$.asObservable()}getCustomUserContactsConfig(){return this.customUserContactsConfig$.value}getCustomUserContactsConfig$(){return this.customUserContactsConfig$.asObservable()}};o.\u0275fac=function(i){return new(i||o)(J(Qe),J(je),J($t),J(pn),J(lt),J(y),J(bn),J(Hn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var _se=n=>{try{return n.name.split(".").slice(0,-1).join(".")}catch(o){pt.catch("Error in File utils getFileName: ",o);return}},p$=n=>{try{return/(?:\.([^.]+))?$/.exec(n?.name)[1]}catch(o){pt.catch("Error in File utils getFileExtension: ",o);return}},yse=(n,o)=>{try{let t=n.slice(0,-1,n.type);return new File([t],o+"."+p$(n),{type:n.type})}catch(t){pt.catch("Error in File utils updateFile: ",t);return}},Sse=n=>new Promise((o,t)=>{let e=new FileReader;e.readAsDataURL(n),e.onload=()=>{o(e.result)},e.onerror=i=>{t(i)}}),bse={mp4:"video/mp4",mov:"video/quicktime",avi:"video/x-msvideo",wmv:"video/x-ms-wmv",flv:"video/x-flv",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",webm:"video/webm",mkv:"video/x-matroska",m4v:"video/x-m4v",m4a:"audio/x-m4a",aac:"audio/aac","3gp":"video/3gpp","3g2":"video/3gpp2",jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",bmp:"image/bmp",svg:"image/svg+xml",webp:"image/webp",pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",odt:"application/vnd.oasis.opendocument.text",ods:"application/vnd.oasis.opendocument.spreadsheet",zip:"application/zip",rar:"application/x-rar-compressed",txt:"text/plain",rtf:"application/rtf",html:"text/html",htm:"text/html",csv:"text/csv",ics:"text/calendar",vcf:"text/x-vcard",js:"application/javascript",css:"text/css",json:"application/json",xml:"application/xml",swf:"application/x-shockwave-flash"};var Bp=(()=>{let o=class o{constructor(e,i,r,a){this.authService=e,this.configService=i,this.loggingService=r,this.attachmentResolverService=a,this.storage=Ty();try{this.configService.getApiKey$().subscribe(s=>{this.apiKey=s}),this.authService.getFirebaseConfig$().subscribe(s=>{s&&s.firebaseOptions?.storageBucket&&(this.storage=Ty(void 0,s?.firebaseOptions?.storageBucket))},s=>{this.loggingService.catch("Error in StorageService constructor: ",s)})}catch(s){this.loggingService.catch("Error in StorageService constructor:",s)}}createAttachment({path:e,file:i}){try{let r=new Nv;r.name=i.name;let a=yse(i,`${r.attachmentId}_${_se(i)}`),s=`${this.apiKey}/${e}/${a?.name}`;return r.bucketPath=s,r.size=i.size,r.type=p$(i),r?.type&&(r.mimeType=bse[r?.type]),r}catch(r){return this.loggingService.catch("Error in StorageService createAttachment: ",r),null}}uploadAttachmentToStorage({attachment:e,file:i,resolve:r,reject:a}){try{let s=wy(this.storage,e.bucketPath),c=QL(s,i,{cacheControl:"public,max-age=3600"});c.on("state_changed",p=>{let h=p.bytesTransferred/p.totalBytes*100},p=>{a(p)},()=>{XL(c.snapshot.ref).then(p=>{e.url=p,r(e)})})}catch(s){this.loggingService.catch("Error in StorageService uploadAttachmentToStorage: ",s),a(s)}}uploadToResolver(c){return ee(this,arguments,function*({file:e,attachment:i,metadata:r,resolve:a,reject:s}){try{r.attachmentId=i.attachmentId;let p={attachmentId:i.attachmentId,name:i.name,file:e,metadata:r,mimeType:i.mimeType},h=yield this.attachmentResolverService.saveAttachment({attachment:p,eventType:Ha.ATTACHMENT_ADD});h&&h.data?.url?(i.url=h.data?.url,a(i)):s(new Error("Failed to upload attachment to resolver"))}catch(p){this.loggingService.catch("Error in StorageService uploadToResolver: ",p),s(p)}})}uploadFile({path:e,file:i,useAttachmentResolver:r,metadata:a}){return new Promise((s,c)=>{try{if(!this.apiKey)throw new Error("API key not configured");let p=this.createAttachment({path:e,file:i});if(!p)throw new Error("Attachment not created");r?this.uploadToResolver({file:i,attachment:p,metadata:a,resolve:s,reject:c}):this.uploadAttachmentToStorage({attachment:p,file:i,resolve:s,reject:c})}catch(p){this.loggingService.catch("Error in StorageService uploadFile:",p),c(p)}})}uploadChunk(e,i,r){return new Promise((a,s)=>{try{if(this.apiKey){let c=`${this.apiKey}/${e}/${i.name}`,p=wy(this.storage,c),h=QL(p,i,{cacheControl:"public,max-age=3600"});h.on("state_changed",_=>{let E=_.bytesTransferred/_.totalBytes*100},_=>{s(_)},()=>{XL(h.snapshot.ref).then(_=>{a(_)}).catch(_=>{this.loggingService.catch(`[uploadChunk] Error getting download URL for chunk ${r}:`,_),s(_)})})}else{let c=new Error("API key not available");this.loggingService.catch("[uploadChunk] API key not available",c),s(c)}}catch(c){this.loggingService.catch(`[uploadChunk] Error in StorageService uploadChunk for chunk ${r}: `,c),s(c)}})}downloadAttachment(e){try{if(e.url){let i=new XMLHttpRequest;i.responseType="blob",i.onload=()=>{let r=i.response,a=document.createElement("a"),s=window.URL.createObjectURL(r);a.setAttribute("type","hidden"),a.setAttribute(U.ATTRIBUTES.VELT_DOWNLOAD_BUTTON,"true"),a.classList.add("snippyly-overlay-panel"),a.href=s,e?.name&&(a.download=e?.name),document.body.appendChild(a);let c=new MouseEvent("click",{view:window,bubbles:!0,cancelable:!1});a.dispatchEvent(c),window.URL.revokeObjectURL(s),a.remove()},i.onerror=()=>{window.open(e.url,"_blank")},i.open("GET",e.url),i.send()}}catch(i){this.loggingService.catch("Error in StorageService downloadAttachment: ",i)}}deleteAttachment({attachment:e,metadata:i,useAttachmentResolver:r}){return new Promise((a,s)=>{if(r)this.attachmentResolverService.deleteAttachment({attachmentId:e.attachmentId,metadata:i}).then(()=>{a(null)}).catch(c=>{s(c)});else{let c=wy(this.storage,e.bucketPath);ZL(c).then(()=>{a(null)}).catch(p=>{a(null)})}})}deleteFileFromPath(e){return new Promise((i,r)=>{let a=wy(this.storage,e);ZL(a).then(()=>{i(null)}).catch(s=>{r(s)})})}};o.\u0275fac=function(i){return new(i||o)(J(je),J($t),J(y),J(Lp))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var gn=(()=>{let o=class o{constructor(e,i,r,a,s,c,p,h){this.analyticsService=e,this.authService=i,this.contactService=r,this.databaseService=a,this.docService=s,this.configService=c,this.loggingService=p,this.commonDbService=h,this.documentIAM$=new fe(null),this.workspaceIAM$=new fe(null),this.roles$=new fe([]),this.getDocumentIamSubscription=null,this.getOrganizationIamSubscription=null,this.getWorkspaceIamSubscription=null;try{this.authService.setIamService(this),this.databaseService.getDb().pipe(Ne(_=>!!_),Je(1)).subscribe(_=>{_&&(this.db=_,this.getUser(),this.getDocumentPaths())},_=>{this.loggingService.catch("Error in CommentService getDb subscription: ",_)}),this.getRole$().pipe(Je(1)).subscribe(_=>{this.authService?.getUser()&&!_&&this.analyticsService.trackEvent(Z.Events.Iam.USER_ACCESS_DENIED)}),this.documentIAM$.subscribe(_=>{_?.accessType&&this.contactService.setDocumentAccessType(_.accessType)})}catch(_){this.loggingService.catch("Error in IamService constructor: ",_)}}clearCache(){this.loggingService.log("%c[WB] Calling FUNCTION: clearCache in IamService","color: green;");try{this.documentIAM$.next(null),this.workspaceIAM$.next(null),this.roles$.next([]),this.documentPaths=null}catch(e){this.loggingService.catch("Error in IamService clearCache: ",e)}}getUser(){try{this.authService.getUser$().pipe(Ne(e=>!!e)).subscribe(e=>{this.user=e,this.user?this.getDocumentIam():(this.getDocumentIamSubscription?.unsubscribe(),this.getOrganizationIamSubscription?.unsubscribe(),this.getWorkspaceIamSubscription?.unsubscribe())},e=>{this.loggingService.catch("Error in IamService getUser$ subscription: ",e)})}catch(e){this.loggingService.catch("Error in IamService getUser: ",e)}}getDocumentPaths(){try{this.docService.getDocumentPaths$().pipe(Ne(e=>!!e)).subscribe(e=>{this.documentPaths=e,this.getDocumentIam(),this.getWorkspaceIam()},e=>{this.loggingService.catch("Error in IamService getDocumentPaths$ subscription: ",e)})}catch(e){this.loggingService.catch("Error in IamService getDocumentPaths: ",e)}}getDocumentIam(){try{this.getDocumentIamSubscription&&(this.getDocumentIamSubscription.unsubscribe(),this.getDocumentIamSubscription=null),this.user?this.getDocumentIamSubscription=this.docService.getDocumentIam$().subscribe(e=>{let i=e||new oM;this.documentIAM$.next(i)},e=>{this.loggingService.catch("Error in IamService getDocumentIam$ subscription: ",e)}):this.documentIAM$.next(null)}catch(e){this.loggingService.catch("Error in IamService getDocumentIam: ",e)}}getWorkspaceIam(){try{this.getWorkspaceIamSubscription||(this.getWorkspaceIamSubscription=this.commonDbService.dbListener({feature:"workspaceIam",properties:{skipFirestore:!0}}).pipe(Ln(e=>re(null))).subscribe(e=>{this.workspaceIAM$.next(e?.data),this.roles$.next(e?.data?.roles||[])}))}catch(e){this.loggingService.catch("Error in IamService getWorkspaceIam: ",e)}}isUserAllowed$(){return this.getRole$().pipe(ce(e=>!!e),Kt())}getDocumentIAM$(){return this.documentIAM$.asObservable()}getRoles$(){return this.roles$.asObservable().pipe(ce(e=>e?.length?e:U.WorkspaceRoles))}getFeaturesAccessLevel$(){return this.documentIAM$.asObservable().pipe(ce(e=>e?.features),ge(e=>this.getRole$().pipe(ce(i=>(i===mo.ADMIN&&(e=e&&JSON.parse(JSON.stringify(e||{})),e?.all?.disabled&&(e.all.disabled=!1)),e)))))}hasRole(e){try{return e===this.getRole()}catch(i){return this.loggingService.catch("Error in IamService hasRole: ",i),!1}}hasRoleAny(e=[]){try{return e?.includes(this.getRole()||"")}catch(i){return this.loggingService.catch("Error in IamService hasRoleAny: ",i),!1}}hasRole$(e){try{return this.authService.getUser$().pipe(ge(()=>this.documentIAM$.pipe(Ne(i=>!!i),ge(()=>this.workspaceIAM$.pipe(ce(()=>e===this.getRole()))))))}catch(i){return this.loggingService.catch("Error in IamService hasRole$: ",i),re(!1)}}getRole$(){try{return this.authService.getUser$().pipe(ge(()=>this.configService.getSF$()),ge(()=>this.configService.getSF()?this.contactService.isUserGlobalContact$():re(null)),ge(()=>this.documentIAM$.pipe(Ne(e=>!!e))),ge(()=>this.workspaceIAM$),ce(()=>this.getRole()))}catch(e){return this.loggingService.catch("Error in IamService getRole$: ",e),re(null)}}getRole(){try{let e=this.configService.getSF();if(e&&this.contactService.isUserGlobalContact())return mo.ADMIN;if(!e&&this.user?.isAdmin)return mo.ADMIN;let i=null,r;if(this.user)switch((this.documentIAM$.value?this.documentIAM$.value?.features?.all?.restricted:!1)?di.RESTRICTED:this.documentIAM$.value?this.documentIAM$.value?.documentAccessType||di.PUBLIC:null){case di.PUBLIC:r=this.getUserFromDocumentIAM(this.user?.email,this.user?.userId),r||(r=this.getUserFromWorkspaceIAM(this.user?.email,this.user?.userId)),i=r?.role?.name||mo.COMMENTER;break;case di.RESTRICTED:r=this.getUserFromDocumentIAM(this.user?.email,this.user?.userId),r||(r=this.getUserFromWorkspaceIAM(this.user?.email,this.user?.userId)),i=r?.role?.name||null;break;default:break}return i}catch(e){this.loggingService.catch("Error in IamService getRole: ",e)}return null}isUserAdmin$(){return this.getRole$().pipe(ce(e=>e===mo.ADMIN),Kt())}isUserAdmin(){try{return this.getRole()===mo.ADMIN}catch(e){return this.loggingService.catch("Error in IamService isUserAdmin: ",e),!1}}getUserFromDocumentIAM(e,i){try{if(e||i){let r;return e&&(r=this.documentIAM$.value?.users?.[Rt(e)]),!r&&i&&(r=this.documentIAM$.value?.users?.[Rt(i)]),r}else return}catch(r){this.loggingService.catch("Error in IamService getUserFromDocumentIAM: ",r)}}getUserFromWorkspaceIAM(e,i){try{if(e||i){let r;return e&&(r=this.workspaceIAM$.value?.users?.[Rt(e)]),!r&&i&&(r=this.workspaceIAM$.value?.users?.[Rt(i)]),r}else return}catch(r){this.loggingService.catch("Error in IamService getUserFromWorkspaceIAM: ",r)}}};o.\u0275fac=function(i){return new(i||o)(J(Qe),J(je),J(gi),J(pn),J(lt),J($t),J(y),J(bn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Vn=(()=>{let o=class o{constructor(e,i,r,a,s,c,p,h,_,E,D,B,G,X,he,Ie){this.afAuth=e,this.analyticsService=i,this.authService=r,this.configService=a,this.commonDbService=s,this.commonDbUtilsService=c,this.commentUtilsService=p,this.commentAnnotationsResolverService=h,this.databaseService=_,this.docService=E,this.domService=D,this.iamService=B,this.loggingService=G,this.notificationUtilsService=X,this.usersService=he,this.functions=Ie,this.db=Ci(),this.notificationsDb=Ci(void 0,Zn.firebaseNotificationsDatabaseURL),this.documentPaths=null,this.notifications$=new fe([]),this.rawNotificationsByIdMap$=new fe(new Map),this.processedNotifications$=new fe([]),this.readNotificationsOnForYouTab$=new fe(!1),this.notificationViews$=new fe({}),this.notificationsByIdMap$=new fe(new Map),this.historyPanelVisible$=new fe(!1),this.notificationsForYou$=new fe(null),this.notificationsByDocumentIdMap$=new fe(null),this.notificationsByDocumentIdSubscription={},this.allowedDocumentMetadataMap$=new fe(null),this.maxNotificationDays$=new fe(15),this.tabConfig$=new fe({people:{enable:!1}});try{this.subscribeNotificationsData().subscribe(),this.commentUtilsService.setNotificationService(this),this.databaseService.getDb().pipe(Ne(Me=>!!Me),Je(1)).subscribe(Me=>{Me&&(this.db=Me,this.getDocumentIds(),this.subscribeGetNotificationsForYou())},Me=>{this.loggingService.catch("Error in NotificationService getDb subscription: ",Me)}),this.authService.getUser$().subscribe(Me=>{Me?(this.subscribeGetNotificationsForYou(),this.getDocumentIds()):(Object.keys(this.notificationsByDocumentIdSubscription).forEach(Le=>{this.notificationsByDocumentIdSubscription[Le]?.unsubscribe()}),this.notificationForYouSubscription?.unsubscribe(),this.documentIdsSubscription?.unsubscribe(),this.resetCacheData())}),this.docService.getLocationMetadata$().subscribe(Me=>{if(Me){let Le=this.notificationsByDocumentIdMap$.getValue()?JSON.parse(JSON.stringify(this.notificationsByDocumentIdMap$.getValue())):null;Object.keys(Me||{}).forEach(We=>{let ke=Le?.[We]?.notifications;ke?.length&&ke.forEach(we=>{this.notificationUtilsService.mergeLocationWithNotification({notification:we},Me)?.notification})}),this.notificationsByDocumentIdMap$.next(Le)}})}catch(Me){this.loggingService.catch("Error in NotificationService constructor: ",Me)}}resetCacheData(){try{this.loggingService.log("%c[WB] Calling NotificationService FUNCTION: resetCacheData","color: green;"),this.notificationsByDocumentIdMap$.next(null),this.notificationsForYou$.next(null)}catch(e){this.loggingService.catch("Error in NotificationService resetCacheData: ",e)}}subscribeGetNotificationsForYou(){try{this.notificationForYouSubscription&&this.notificationForYouSubscription.unsubscribe(),this.notificationForYouSubscription=this.getNotificationsForYou().subscribe(()=>{},e=>{this.loggingService.catch("Error in NotificationService getNotificationsForYou subscription: ",e)})}catch(e){this.loggingService.catch("Error in NotificationService subscriveGetNotificationsForYou: ",e)}}setCommentService(e){try{this.commentService=e}catch(i){this.loggingService.catch("Error in NotificationService setCommentService: ",i)}}getDocumentIds(){try{this.documentIdsSubscription&&this.documentIdsSubscription.unsubscribe(),this.documentIdsSubscription=this.getDocumentIdsByLastNotificationTimestamp().pipe(Vi(),ce(([e,i])=>{let r=e?.map(h=>h.documentId),a=i?.map(h=>h.documentId),s=r?.filter(h=>!a?.includes(h)),c=a?.map(h=>({documentId:h,timestamp:i?.find(_=>_.documentId===h)?.timestamp})).filter(h=>!r?.includes(h.documentId)),p=a?.map(h=>{let _=i?.find(E=>E.documentId===h)?.timestamp;return{documentId:h,timestamp:_}}).filter(h=>{let _=e?.find(E=>E.documentId===h.documentId)?.timestamp;return _&&h.timestamp&&_!==h.timestamp});c?.length&&this.fetchNotificationsForDocumentIds(c),p?.length&&this.fetchNotificationsForDocumentIds(p,1),s?.forEach(h=>{this.removeNotificationsForDocumentId(h)}),i&&!i?.length&&!this.notificationsByDocumentIdMap$.getValue()&&this.notificationsByDocumentIdMap$.next({})})).subscribe(()=>{},e=>{this.loggingService.catch("Error in NotificationService getDocumentIds subscription: ",e)})}catch(e){this.loggingService.catch("Error in NotificationService getDocumentIds: ",e)}}getDocumentIdsByLastNotificationTimestamp(e=15){try{return this.authService.getUser$().pipe(ge(i=>this.docService.getOrganizationConfig$().pipe(ce(r=>{let a=null,s=this.configService.getApiKey(),c=r?.organizationId||i?.organizationId;return s&&c&&(a=new xd({apiKey:s,organizationId:c})),{user:i,documentPaths:a}}))),ge(i=>{let{user:r,documentPaths:a}=i;if(r&&a?.organizationNotificationsLastNotificationTimestamp){let s=new Date,c=this.maxNotificationDays$.getValue()>0?this.maxNotificationDays$.getValue():15;s.setDate(s.getDate()-c);let p=s.getTime();return this.commonDbService.dbListener({feature:"allLastNotificationTimestamp",properties:{organizationId:a?.organizationId,isCollection:!0,useQuery:!0,firestoreQuery:[Fi(mt("timestamp",">=",p)),Ga("timestamp","desc"),Rv(e)]}}).pipe(ce(h=>h?.data),ce(h=>{let _=[];return Object.keys(h||{}).forEach(E=>{let D=this.commonDbService.shouldUseFirestore()?h[E]?.timestamp??0:h[E],B=this.commonDbService.shouldUseFirestore()?h[E]?.deletedNotification??!1:!1;if(B&&B.id&&B?.timestamp===D){let G=B.id,X=h[E]?.metadata?.documentId,he=JSON.parse(JSON.stringify(this.notificationsByDocumentIdMap$.getValue()??{})),Ie=he?.[X]??{documentMetadata:null,notifications:[]},Me=Ie.notifications??[],Le=Me?.findIndex(We=>We.notificationId===G);Le!==-1&&(Me.splice(Le,1),this.notificationsByDocumentIdMap$.next(T(I({},he),{[X]:T(I({},Ie),{notifications:Me})})))}else _.push({documentId:E,timestamp:D})}),_}),Ln(h=>(this.loggingService.catch("Error in NotificationService getDocumentIdsByLastNotificationTimestamp: ",h),re([]))))}return re(null)}))}catch(i){return this.loggingService.catch("Error in NotificationService getDocumentIdsByLastNotificationTimestamp: ",i),re([])}}fetchNotificationsForDocumentIds(e,i=15){return ee(this,null,function*(){try{if(e?.length){let r=Cr(this.functions,Zn.cloudFunction.getNotificationsForDocuments,{timeout:12e5}),a=this.docService.getOrganizationConfig()?.organizationId??"",s=this.getStartAtTimestamp(),c={};e.forEach(B=>{if(B?.documentId){let G=this.getAllowedDocumentMetadataByDocumentId(B.documentId);G&&(c[B.documentId]=G)}});let p={organizationId:a,documentIds:e,timestamp:s,limitToLast:i,documentMetadataByDocumentId:c},h=yield this.notificationUtilsService.handleNotificationEncryption({data:p}),_=(yield r({veltData:h}))?.data?.data?.veltData||{},E="notificationwithdocumentidstoencryptanddecryptonsdk"+(this.authService.getUser()?.userId??""),D=yield Pie(_,E);if(D&&typeof D=="object"){let B=this.usersService.userDataProviderAvailable(),G=this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable(),X=[],he=[];Object.keys(D).forEach((Ie,Me)=>{let Le=D[Ie].documentMetadata;if(Le){let ke=this.allowedDocumentMetadataMap$.value||{};(!ke?.[Ie]||!Co(ke?.[Ie],Le))&&this.allowedDocumentMetadataMap$.next(T(I({},ke),{[Ie]:Le}))}let We=D[Ie].notifications||[];We.forEach(ke=>{ke.notification=this.getClientNotificationObject(ke)}),this.setNotificationForDocumentIdInCache(Ie,Le,We),B&&X.push(this.commonDbUtilsService.formatResponse({feature:"allDocNotifications",data:We,shouldAwait:!0,forceResolve:!0})),G&&he.push(this.commonDbUtilsService.formatResponse({feature:"allDocNotifications",data:We,shouldCommentAnnotationsResolverAwait:!0}))}),B&&Promise.all(X).then(()=>{Object.keys(D).forEach(Ie=>{let Me=D?.[Ie]?.documentMetadata||{},Le=this.commonDbUtilsService.mergeUsersWithData({feature:"allDocNotifications",data:D?.[Ie]?.notifications||[]});Le.forEach(We=>{We.notification=this.getClientNotificationObject(We)}),this.setNotificationForDocumentIdInCache(Ie,Me,Le)})}),G&&Promise.all(he).then(()=>{Object.keys(D).forEach(Ie=>{let Me=D?.[Ie]?.documentMetadata||{},Le=D?.[Ie]?.notifications?.reduce((We,ke)=>(We[ke.notificationId]=ke,We),{});Le=this.commonDbUtilsService.mergeCommentAnnotationsWithData({feature:"allDocNotifications",data:Le}),Le=Object.values(Le??{}),Le.forEach(We=>{We.notification=this.getClientNotificationObject(We)}),this.setNotificationForDocumentIdInCache(Ie,Me,Le)})})}}}catch(r){return this.loggingService.catch("Error in NotificationService fetchNotificationsForDocumentIds: ",r),[]}})}setNotificationForDocumentIdInCache(e,i,r,a){try{let s=this.docService.getOrganizationConfig()?.organizationId??"",c=this.docService.getOrganizationMetadata(s);i||(i=JSON.parse(JSON.stringify(this.docService.getDocumentMetadata()||{}))),c||(c=JSON.parse(JSON.stringify(this.docService.getOrganizationMetadata(s)||{})));let p=this.notificationsByDocumentIdMap$.getValue(),h=p?.[e]?.notifications||[],_=this.docService.getLocationMetadatas(),E=r?.map(G=>{let X=G.notification;return X.metadata&&(X.metadata.documentName=i?.documentName||X.metadata.documentName,X.metadata.organizationMetadata=c||X.metadata.organizationMetadata,X.metadata.documentMetadata=i||X.metadata.documentMetadata),_&&(X=this.notificationUtilsService.mergeLocationWithNotification({notification:X},_)?.notification),X})?.filter(G=>!!G)||[],D=new Map(h.map(G=>[G.id,G]));E.forEach(G=>{D.set(G.id,G)});let B=Array.from(D.values()).sort((G,X)=>(X.timestamp||0)-(G.timestamp||0));this.notificationsByDocumentIdMap$.next(T(I({},p),{[e]:{notifications:B,documentMetadata:i}}))}catch(s){this.loggingService.catch("Error in NotificationService setNotificationForDocumentIdInCache: ",s)}}removeNotificationsForDocumentId(e){try{this.notificationsByDocumentIdSubscription[e]&&this.notificationsByDocumentIdSubscription[e].unsubscribe();let i=this.notificationsByDocumentIdMap$.getValue();delete i?.[e],this.notificationsByDocumentIdMap$.next(i)}catch(i){this.loggingService.catch("Error in NotificationService removeNotificationsForDocumentId: ",i)}}getNotificationsForDocumentId$(e,i=50){try{return this.authService.getUser$().pipe(ce(r=>({user:r})),ge(r=>this.maxNotificationDays$.pipe(ce(()=>r))),ge(r=>{let{user:a}=r,s=this.configService.getApiKey();if(a&&s){let c=new Date,p=this.maxNotificationDays$.getValue()>0?this.maxNotificationDays$.getValue():15;c.setDate(c.getDate()-p);let h=c.getTime();return bo(this.commonDbService.queryData({feature:"allDocNotifications",properties:{rtdbQuery:[EL("timestamp"),TL(h),IL(i)],firestoreQuery:[Ga("timestamp","desc"),mt("timestamp",">=",h),mt("notification.actionUser.userId","!=",a.userId),Rv(i)],apiKey:s,organizationId:this.docService?.getDocumentPaths()?.organizationId||a?.organizationId,documentId:e}})).pipe(ge(_=>this.commonDbUtilsService.mergeUsersWithData$({feature:"allDocNotifications",data:{data:_,operation:null}})),ce(_=>_?.data??[]),ce(_=>(_.sort((E,D)=>D.timestamp-E.timestamp),_)),Ln(_=>(this.loggingService.catch("Error in NotificationService getNotificationsForDocumentId: ",_),re([]))),ce(_=>(_.forEach(E=>{E.notification=this.getClientNotificationObject(E)}),_)))}return re([])}))}catch(r){return this.loggingService.catch("Error in NotificationService getNotificationsForDocumentId: ",r),re([])}}getStartAtTimestamp(){try{let e=new Date,i=this.maxNotificationDays$.getValue()>0?this.maxNotificationDays$.getValue():15;return e.setDate(e.getDate()-i),e.getTime()}catch(e){return this.loggingService.catch("Error in NotificationService getStartAtTimestamp: ",e),0}}getNotificationsForYou(){try{return this.databaseService.getDb().pipe(ge(e=>this.authService.getUser$().pipe(ce(i=>({db:e,user:i})))),ge(e=>this.maxNotificationDays$.pipe(ce(()=>e))),ge(e=>{let{db:i,user:r}=e,a=this.configService.getApiKey();if(i&&r?.organizationId&&a){let s=Rt(r?.userId),c=new Date,p=this.maxNotificationDays$.getValue()>0?this.maxNotificationDays$.getValue():15;c.setDate(c.getDate()-p);let h=c.getTime();return this.commonDbService.dbListener({feature:"allUserNotifications",properties:{useQuery:!0,isCollection:!0,rtdbQuery:[EL("timestamp"),TL(h),IL(50)],firestoreQuery:[Ga("timestamp","desc"),mt("timestamp",">=",h),mt("notification.actionUser.userId","!=",r.userId),Rv(50)],apiKey:a,organizationId:this.docService?.getDocumentPaths()?.organizationId||r?.organizationId,documentId:this.docService.getDocumentPaths()?.documentId,userId:s}}).pipe(ge(_=>_?.data?re(_).pipe(ce(E=>E?.data),ce(E=>{let D=Object.values(E||{});return D.forEach(G=>{G.notification=this.getClientNotificationObject(G)}),D.sort((G,X)=>X.timestamp-G.timestamp),D.map(G=>G.notification).filter(G=>!!G)}),ge(E=>{let D={data:E?.reduce((B,G)=>(B[G.id]={notification:G},B),{}),operation:null};return this.commonDbUtilsService.mergeLocationMetadataWithData$({data:D,feature:"allUserNotifications"}).pipe(ce(B=>Object.values(B?.data||{}).map(G=>G?.notification)))})):re(null)))}return re(null)}),ge(e=>{let i=this.docService.getOrganizationConfig()?.organizationId??"";return this.docService.getOrganizationMetadata$(i).pipe(ce(()=>e))}),ge(e=>this.allowedDocumentMetadataMap$.pipe(ce(()=>e))),ce(e=>(e?.length&&(e=e.map(i=>{if(i?.metadata){let r=this.docService.getOrganizationConfig()?.organizationId??"",a=this.getAllowedDocumentMetadataByDocumentId(i.metadata.documentId),s=this.docService.getOrganizationMetadata(r);a||(a=JSON.parse(JSON.stringify(this.docService.getDocumentMetadata()||{}))),s||(s=JSON.parse(JSON.stringify(this.docService.getOrganizationMetadata(r)||{}))),i.metadata.documentName=a?.documentName||i.metadata.documentName,i.metadata.organizationMetadata=s||i.metadata.organizationMetadata,i.metadata.documentMetadata=a||i.metadata.documentMetadata}return i})),e===null?this.notificationsForYou$.next(null):e?.length?this.notificationsForYou$.next(e):this.notificationsForYou$.next([]),re(e))))}catch(e){return this.loggingService.catch("Error in NotificationService getNotificationsForYou: ",e),re({})}}subscribeNotificationsData(e,i){this.loggingService.log("%c[WB] Calling FUNCTION: subscribeViewsData","color: green;");let r,a;try{if(e&&(a=fn(e)),i&&typeof i=="object"){let s=Xo(i);r=fn(JSON.stringify(s))}}catch(s){this.loggingService.catch("Error in ViewsService subscribeViewsData: ",s)}return Wn(this.afAuth).pipe(Ne(s=>!!s),ge(s=>this.isFeatureAllowed({firebaseUser:s})),ge(s=>s.featureAllowed?this.iamService.isUserAllowed$().pipe(ce(c=>(s.featureAllowed=c,s))):re(s)),ge(s=>!s.featureAllowed||s?.user?.organizationId?(this.notifications$.next([]),this.rawNotificationsByIdMap$.next(new Map),this.processedNotifications$.next([]),this.notificationsByIdMap$.next(new Map),this.notificationViews$.next({}),this.setNotificationsByIdMap(),re([])):re(s).pipe(ge(c=>this.docService.getDocumentPaths$().pipe(ce(p=>(this.documentPaths=p,c.documentPaths=p,c)))),ge(c=>this.getDataFromDocumentId(a)))))}isFeatureAllowed(e){return this.configService.getConfig$().pipe(Ne(i=>!!i),ce(i=>T(I({},e),{config:i})),ge(i=>this.authService.getUser$().pipe(ce(r=>T(I({},i),{user:r})))),ge(i=>Xi(i.config,i.user,Re.NOTIFICATION)?re(T(I({},i),{featureAllowed:!0})):(this.loggingService.warn("Notification feature is not allowed."),re(T(I({},i),{featureAllowed:!1})))))}getDataFromDocumentId(e){return this.databaseService.getDb().pipe(Ne(i=>!!i),ge(i=>{if(this.db=i,this.loggingService.log(this.db),this.configService?.getApiKey()&&this.documentPaths?.views){let r=`${this.configService.getApiKey()}`;this.documentPaths?.organizationId&&(r+=`/${U.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${this.documentPaths.organizationId}`);let a=on(this.db,`${e?r+"/"+U.FIREBASE_PARTIAL_PATH_DOCS+"/"+e+"/"+U.FIREBASE_PARTIAL_PATH_VIEWS+"/":this.documentPaths?.notifications}`);return Af(a).pipe(Ln(s=>(this.loggingService.catch("Error in NotificationService getDataFromDocumentId: ",s),re(null))),ce(s=>{let c=[],p=new Map;s?.raw&&(Object.keys(s?.raw||{}).forEach(_=>{let E=s?.raw[_];E?.id&&c.push(E)}),c.forEach(_=>{_.id&&p.set(_.id,_)})),this.notifications$.next(c),this.rawNotificationsByIdMap$.next(p);let h=[];s?.processed&&Object.keys(s?.processed||{}).forEach(_=>{let E=s?.processed[_];E?.id&&h.push(E)}),this.processedNotifications$.next(h),this.setNotificationsByIdMap()}))}else return re(null)}))}setNotificationsByIdMap(){try{let e=this.authService.getUser();if(e){let i=this.notificationViews$.getValue(),r;e?.email&&(r=Rt(e?.email));let a;e?.userId&&(a=Rt(e?.userId));let s=new Map;this.processedNotifications$.getValue().forEach(p=>{if(p.id&&p?.displayHeadlineMessageTemplate){let h=!1;(r&&p.notifyUsers?.[r]||a&&p.notifyUsers?.[a])&&(h=!0);let _={id:p.id,notificationSource:p.notificationSource,actionType:p.actionType,actionUser:p.actionUser,timestamp:p.timestamp,targetAnnotationId:p.targetAnnotationId,displayHeadlineMessage:this.getNotificationHeadlineMessage(p),displayBodyMessage:this.getNotificationBodyMessage(p),forYou:h,notificationSourceData:p.notificationSourceData},E=this.getRawNotificationById(_.id);if(E?.metadata&&(_.metadata={apiKey:E.metadata.apiKey,organizationId:E.metadata.organizationId,clientOrganizationId:E.metadata.clientOrganizationId,documentId:E.metadata.documentId,clientDocumentId:E.metadata.clientDocumentId,location:E?.location,locationId:E?.locationId}),_?.notificationSource==="comment"&&_?.targetAnnotationId){let D=this.commentService?.getAnnotationById(_.targetAnnotationId);D||E?.annotationData&&(D=E.annotationData),D&&(_.notificationSourceData=$n(D))}s.set(p.id,_)}}),s.forEach((p,h)=>{p.isUnread=p?.actionUser?.userSnippylyId!==e?.userSnippylyId&&!i?.notification?.[h]?.views?.[e?.userSnippylyId],s.set(h,p)}),this.notificationsByIdMap$.next(s)}}catch(e){this.loggingService.catch("Error in NotificationService setNotificationsByIdMap: ",e)}}getClientNotificationObject({processed:e,raw:i,metadata:r,views:a,notification:s}){try{let c=this.authService.getUser(),p=s||e;if(p.id&&p?.displayHeadlineMessageTemplate&&c){let h=null;c?.email&&(h=Rt(c?.email));let _=null;c?.userId&&(_=Rt(c?.userId));let E=!1,D=!0;(h&&p.notifyUsers?.[h]||_&&p.notifyUsersByUserId?.[_])&&(E=!0),_&&a?.[_]&&(D=!1);let B={id:p.id};if(s?B=T(I(I({},B),s),{displayHeadlineMessage:this.getNotificationHeadlineMessage(s),displayBodyMessage:this.getNotificationBodyMessage(s),forYou:E,isUnread:D}):B={id:e.id,notificationSource:e.notificationSource,actionType:e.actionType,actionUser:e.actionUser,timestamp:e.timestamp,targetAnnotationId:e.targetAnnotationId,displayHeadlineMessage:this.getNotificationHeadlineMessage(e),displayBodyMessage:this.getNotificationBodyMessage(e),forYou:E,isUnread:D,metadata:r},B?.notificationSource==="comment"&&B?.targetAnnotationId){let G=this.commentService?.getAnnotationById(B.targetAnnotationId);G||s?.notificationSourceData&&(G=s?.notificationSourceData),G||i?.annotationData&&(G=i.annotationData),G&&(B.notificationSourceData=$n(G))}return i?.targetAnnotationData?.isCommentResolverUsed&&(B.isCommentResolverUsed=i?.targetAnnotationData?.isCommentResolverUsed),B}return}catch(c){this.loggingService.catch("Error in NotificationService getClientNotificationObject: ",c);return}}getNotificationsForYou$(){return this.notificationsForYou$.asObservable()}getNotificationsByDocumentId$(){return this.notificationsByDocumentIdMap$.asObservable().pipe(ce(e=>e?Object.keys(e??{}).map(i=>{let r=e[i].notifications||[],a=r.filter(c=>c.isUnread).length,s=r.length>0&&r[0]?.timestamp||0;return{documentId:i,notifications:e[i]?.notifications,unreadNotificationsCount:a,latestNotificationTimestamp:s,documentMetadata:e[i]?.documentMetadata}}).filter(i=>i.notifications?.length>0).sort((i,r)=>r.latestNotificationTimestamp-i.latestNotificationTimestamp):null))}getAllNotifications$(){return this.getNotificationsByDocumentId$().pipe(ce(e=>{let i=null;return e?(i=[],e.forEach(r=>{r.notifications.forEach(a=>{i?.push(a)})}),i?.sort((r,a)=>a.timestamp-r.timestamp)):null}))}processNotificationData(e){try{let i=e?.annotationData?.metadata,r=this.docService.getOrganizationConfig()?.organizationId;e.metadata=JSON.parse(JSON.stringify(this.docService.getDocumentMetadata(i?.documentId)||{})),e.metadata||(e.metadata={},this.loggingService.catch("Warning in NotificationService updateNotificationDatabase: ","Document metadata not found")),delete e.metadata.locations,e.metadata.documentMetadata=JSON.parse(JSON.stringify(this.docService.getDocumentMetadata(i?.documentId)||{})),e?.metadata?.documentMetadata?.clientDocumentId&&e?.metadata?.documentMetadata?.documentId&&(e.metadata.documentMetadata.documentId=e?.metadata?.documentMetadata?.clientDocumentId),delete e.metadata.documentMetadata.locations,e.metadata.organizationMetadata=JSON.parse(JSON.stringify(r?this.docService.getOrganizationMetadata(r)||{}:{})),e?.metadata?.organizationMetadata?.clientOrganizationId&&e?.metadata?.organizationMetadata?.organizationId&&(e.metadata.organizationMetadata.organizationId=e?.metadata?.organizationMetadata?.clientOrganizationId);let a=this.configService.getApiKey();e.metadata.apiKey=a,e.platform=this.configService.getSF()?"sf":"sdk",e.actionUser=this.authService.getUser();let s=i?.documentId?new xd({apiKey:a,documentId:i.documentId,organizationId:i?.organizationId}):this.docService.getDocumentPaths();e?.actionUser?.organizationId&&(e.metadata.organizationId=s?.organizationId||e.actionUser.organizationId,e.metadata.clientOrganizationId=s?.clientOrganizationId||e.actionUser.clientOrganizationId);let c=this.docService.getLocation();c&&(e.location=c?.location,e.locationId=c?.locationId),this.loggingService.log(`[NOTIFICATION] ${e?.notificationSource} ${e?.actionType}`,e);let p=this.commonDbService.getServerTimestamp(),h=this.notificationUtilsService.formatNotification(e,p);return JSON.parse(JSON.stringify(h))}catch(i){return this.loggingService.catch("Error in NotificationService processNotificationData: ",i),null}}updateNotificationDatabase(e){try{let i=on(this.notificationsDb),r=this.processNotificationData(e);RA(i,JSON.parse(JSON.stringify(r)))}catch(i){this.loggingService.catch("Error in NotificationService updateNotificationDatabase: ",i)}}getRawNotifications$(){return this.notifications$.asObservable()}getProcessedNotifications$(){return this.processedNotifications$.asObservable()}getNotifications$(){return this.authService.getUser$().pipe(ge(e=>e?e.organizationId?this.getAllNotifications$().pipe(ge(i=>this.notificationsForYou$.pipe(ce(r=>{let a=new Map;return(i||[]).forEach(s=>{s.id&&a.set(s.id,s)}),(r||[]).forEach(s=>{s.id&&!a.has(s.id)&&a.set(s.id,s)}),Array.from(a.values()).sort((s,c)=>(c.timestamp||0)-(s.timestamp||0))})))):this.notificationsByIdMap$.asObservable().pipe(ce(i=>Array.from(i.values())),ce(i=>i.sort((r,a)=>a.timestamp-r.timestamp)),Eg()):re(null)))}getRawNotificationById(e){try{return this.rawNotificationsByIdMap$.getValue()?.get(e)}catch(i){this.loggingService.catch("Error in NotificationService getRawNotificationById: ",i);return}}setNotificationViews(e){try{this.notificationViews$.next(e),this.setNotificationsByIdMap()}catch(i){this.loggingService.catch("Error in NotificationService setNotificationViews: ",i)}}getNotificationHeadlineMessage(e){try{let i=this.authService.getUser();if(e?.displayHeadlineMessageTemplate&&e?.displayHeadlineMessageTemplateData){let r=e.displayHeadlineMessageTemplate,a=e.displayHeadlineMessageTemplateData,s=/\{(\w+)\}/g,c=r.replace(s,(p,h)=>(h==="actionUser"||h==="recipientUser")&&a[h]?i?.email&&a[h].email===i?.email||i?.userId&&a[h]?.userId===i?.userId?"You":a[h].name||a[h].email||' <velt-skeleton-loader width="50px" height="20px" border-radius="4px"></velt-skeleton-loader> ':a[h]?a[h]:p);return this.domService.sanitizeHtml(c)}return this.domService.sanitizeHtml(e.displayHeadlineMessageTemplate||"")}catch(i){return this.loggingService.catch("Error in NotificationService getNotificationHeadlineMessage: ",i),""}}getNotificationBodyMessage(e){try{if(e?.displayBodyMessageTemplate&&e?.displayBodyMessageTemplateData){let i=e?.displayBodyMessageTemplate;return e?.displayBodyMessageTemplateData&&e?.displayBodyMessageTemplateData?.users?.forEach(r=>{if(r?.userId){let a=this.usersService.getUserById(r?.userId);i=i?.replaceAll(`{{${r.userId}}}`,a?.name||a?.email||'<velt-skeleton-loader width="50px" height="20px" border-radius="4px"></velt-skeleton-loader>')}}),this.domService.sanitizeHtml(i)}return this.domService.sanitizeHtml(e.displayBodyMessage||"")}catch(i){return this.loggingService.catch("Error in NotificationService getNotificationBodyMessage: ",i),""}}setHistoryPanelVisibility(e,i=!1,r=!1){try{e?document.querySelector(U.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL)?this.historyPanelVisible$.next(e):this.loggingService.catch("Error in NotificationService setHistoryPanelVisibility: ",`<${U.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`):this.historyPanelVisible$.next(e),e?this.analyticsService.trackEvent(Z.Events.Notifications.NOTIFICATION_HISTORY_PANEL_OPENED):this.analyticsService.trackEvent(Z.Events.Notifications.NOTIFICATION_HISTORY_PANEL_CLOSED)}catch{this.loggingService.catch("Error in NotificationService setHistoryPanelVisibility: ",`<${U.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`)}}toggleHistoryPanelVisibility(e=!1,i=!1){try{this.historyPanelVisible$.value?this.historyPanelVisible$.next(!this.historyPanelVisible$.value):document.querySelector(U.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL)?(this.historyPanelVisible$.next(!this.historyPanelVisible$.value),this.historyPanelVisible$.value?this.analyticsService.trackEvent(Z.Events.Notifications.NOTIFICATION_HISTORY_PANEL_TOGGLED,{action:"closed"}):this.analyticsService.trackEvent(Z.Events.Notifications.NOTIFICATION_HISTORY_PANEL_TOGGLED,{action:"opened"})):this.loggingService.catch("Error in NotificationService toggleHistoryPanelVisibility: ",`<${U.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`)}catch{this.loggingService.catch("Error in NotificationService toggleHistoryPanelVisibility: ",`<${U.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`)}}getHistoryPanelVisibility$(){return this.historyPanelVisible$.asObservable()}setNotificationsAsRead(e){return ee(this,null,function*(){try{if(e?.length){for(let a=0;a<e.length;a+=50){let c=e.slice(a,a+50).filter(p=>p?.id).map(p=>this.setNotificationAsRead(p));yield Promise.all(c)}let r=JSON.parse(JSON.stringify(this.notificationsByDocumentIdMap$.getValue()||{}));e.forEach(a=>{let s=a.metadata?.documentId;if(s&&r?.[s]){let c=r?.[s]?.notifications||[],p=c.find(h=>h.id===a.id);p&&(p.isUnread=!1),r[s].notifications=c}}),this.notificationsByDocumentIdMap$.next(r)}}catch(i){this.loggingService.catch("Error in NotificationService setNotificationsAsRead: ",i)}})}setAllNotificationsAsRead(e){return ee(this,null,function*(){try{if(e?.tabId==="for-you"){let i=this.notificationsForYou$.value||[];this.setNotificationsAsRead(i)}else this.getAllNotifications$().pipe(Je(1)).subscribe(i=>{i&&this.setNotificationsAsRead(i)})}catch(i){this.loggingService.catch("Error in NotificationService setAllNotificationsAsRead: ",i)}})}getUnreadNotificationsCount$(){try{return this.notificationsForYou$.pipe(ce(e=>e?.filter(r=>r?.isUnread)?.length??null),ge(e=>this.getNotifications$().pipe(ce(i=>{let r=i?.filter(a=>a?.isUnread)?.length??null;return{forYou:e,all:r}}))))}catch(e){return this.loggingService.catch("Error in NotificationService getUnreadNotificationsCount$: ",e),re({forYou:null,all:null})}}setNotificationAsRead(e){return ee(this,null,function*(){try{let i=this.authService.getUser();if(i&&e?.id){let r=Rt(i?.userId),{metadata:a}=e;if(a){let{apiKey:s,organizationId:c,documentId:p}=a;if(s&&c&&p&&r){let h=yield this.commonDbService.getData({feature:"docNotification",properties:{id:e.id,organizationId:c,documentId:p,apiKey:s}});h?.notificationId&&(h?.views?.[r]||(h.views||(h.views={}),h.views[r]={timestamp:Date.now()},this.commonDbService.updateData({feature:"docNotificationViews",properties:{id:e.id,organizationId:c,documentId:p,apiKey:s},data:h})));let _=yield this.commonDbService.getData({feature:"userNotification",properties:{id:e.id,userId:r,documentId:p,organizationId:c}});_?.notificationId&&(this.getReadNotificationsOnForYouTab()?_?.views?.[r]||(_.views||(_.views={}),_.views[r]={timestamp:Date.now()},this.commonDbService.updateData({feature:"userNotificationViews",properties:{id:e.id,userId:r,documentId:p,organizationId:c},data:_})):yield this.commonDbService.deleteData({feature:"userNotification",properties:{id:e.id,userId:r,documentId:p,organizationId:c}}))}}}}catch(i){this.loggingService.catch("Error in NotificationService setNotificationAsRead: ",i)}})}setMaxDays(e){try{e>0?this.maxNotificationDays$.next(e):this.maxNotificationDays$.next(15)}catch(i){this.loggingService.catch("Error in NotificationService setMaxDays: ",i)}}setTabConfig(e){try{e&&this.tabConfig$.next(e)}catch(i){this.loggingService.catch("Error in NotificationService setTabConfig: ",i)}}getTabConfig$(){return this.tabConfig$.asObservable()}getTabConfig(){return this.tabConfig$.value}enableReadNotificationsOnForYouTab(){this.readNotificationsOnForYouTab$.next(!0)}disableReadNotificationsOnForYouTab(){this.readNotificationsOnForYouTab$.next(!1)}getReadNotificationsOnForYouTab$(){return this.readNotificationsOnForYouTab$.asObservable()}getReadNotificationsOnForYouTab(){return this.readNotificationsOnForYouTab$.value}markNotificationAsReadById(e){return ee(this,null,function*(){try{this.getAllNotifications$().pipe(Je(1)).subscribe(i=>{if(i){let r=i.filter(a=>a.id===e);this.setNotificationsAsRead(r)}})}catch(i){this.loggingService.catch("Error in NotificationService markNotificationAsReadById: ",i)}})}getAllowedDocumentMetadataByDocumentId(e){try{return this.allowedDocumentMetadataMap$.value?.[e]||null}catch(i){return this.loggingService.catch("Error in NotificationService getAllowedDocumentMetadataByDocumentId: ",i),null}}};o.\u0275fac=function(i){return new(i||o)(J(vi),J(Qe),J(je),J($t),J(bn),J($v),J(Uv),J(vs),J(pn),J(lt),J(Fe),J(gn),J(y),J(TM),J(Hn),J(Vo))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var $o=(()=>{let o=class o{constructor(e){this.loggingService=e,this._customStatusMap=new fe(U.CommentAnnotationStatusMap),this._customPriorityMap=new fe(U.CommentAnnotationPriorityMap),this._customCategoryMap=new fe(U.CommentCategoryMap);try{let i=sessionStorage.getItem(U.SESSION_STORAGE.VELT_CUSTOM_PRIORITY_MAP);i&&this._customPriorityMap.next(JSON.parse(i));let r=sessionStorage.getItem(U.SESSION_STORAGE.VELT_CUSTOM_STATUS_MAP);r&&this._customStatusMap.next(JSON.parse(r));let a=sessionStorage.getItem(U.SESSION_STORAGE.VELT_CUSTOM_CATEGORY_MAP);a&&this._customCategoryMap.next(JSON.parse(a))}catch(i){this.loggingService.catch("Error in CustomFilterService constructor: ",i)}}setCustomStatusFilters(e){try{if(e.length<2){this._customStatusMap.next(U.CommentAnnotationStatusMap),sessionStorage.setItem(U.SESSION_STORAGE.VELT_CUSTOM_STATUS_MAP,JSON.stringify(U.CommentAnnotationStatusMap)),this.loggingService.catch("Custom status filters must have at least 2 filters");return}let i={};e.forEach(r=>{i[r.id]=r,r.type||(r.type="ongoing")}),this._customStatusMap.next(i),sessionStorage.setItem(U.SESSION_STORAGE.VELT_CUSTOM_STATUS_MAP,JSON.stringify(i))}catch(i){this.loggingService.catch("Error in CustomFilterService setCustomStatusFilters: ",i)}}setCustomPriorityFilters(e){try{if(e.length<2){this._customPriorityMap.next(U.CommentAnnotationPriorityMap),sessionStorage.setItem(U.SESSION_STORAGE.VELT_CUSTOM_PRIORITY_MAP,JSON.stringify(U.CommentAnnotationPriorityMap)),this.loggingService.catch("Custom priority filters must have at least 2 filters");return}let i={};e.forEach(r=>{i[r.id]=r}),this._customPriorityMap.next(i),sessionStorage.setItem(U.SESSION_STORAGE.VELT_CUSTOM_PRIORITY_MAP,JSON.stringify(i))}catch(i){this.loggingService.catch("Error in CustomFilterService setCustomPriorityFilters: ",i)}}setCustomCategories(e){try{let i={};e.forEach(r=>{i[r.id]=r}),this._customCategoryMap.next(i),sessionStorage.setItem(U.SESSION_STORAGE.VELT_CUSTOM_CATEGORY_MAP,JSON.stringify(i))}catch(i){this.loggingService.catch("Error in CustomFilterService setCustomCategories: ",i)}}get customStatusMap$(){return this._customStatusMap.asObservable()}get customPriorityMap$(){return this._customPriorityMap.asObservable()}get customCategoryMap$(){return this._customCategoryMap.asObservable()}get defaultStatus(){try{let i=Object.entries(this._customStatusMap.value).find(([r,a])=>a.type==="default");if(i)return i[1]}catch(e){this.loggingService.catch("Error in CustomFilterService defaultStatus: ",e)}return U.CommentAnnotationStatusMap.OPEN}get resolvedStatus(){try{let i=Object.entries(this._customStatusMap.value).find(([r,a])=>a.type==="terminal");if(i)return i[1]}catch(e){this.loggingService.catch("Error in CustomFilterService resolvedStatus: ",e)}return U.CommentAnnotationStatusMap.OPEN}get ongoingStatuses(){try{let i=Object.entries(this._customStatusMap.value).filter(([r,a])=>a.type==="ongoing");if(i)return i.map(r=>r[1])}catch(e){this.loggingService.catch("Error in CustomFilterService ongoingStatuses: ",e)}return[U.CommentAnnotationStatusMap.IN_PROGRESS]}convertLegacyAnnotationStatus(e){try{if(typeof e.status=="string"||e.status===void 0){let i=Object.entries(this._customStatusMap.value),r=i.find(([a,s])=>s.type==="default");switch(e.status){case"open":r&&(e.status=r[1]);break;case"inProgress":let a=i.find(([c,p])=>p.type==="ongoing");a&&(e.status=a[1]);break;case"resolved":let s=i.find(([c,p])=>p.type==="terminal");s&&(e.status=s[1]);break;default:r&&(e.status=r[1]);break}}return e}catch(i){return this.loggingService.catch("Error in CustomFilterService convertLegacyAnnotation: ",i),e}}convertLegacyPriority(e){try{typeof e.priority=="string"&&(e.priority=U.CommentAnnotationPriorityMap[e.priority])}catch(i){this.loggingService.catch("Error in CustomFilterService convertLegacyPriority: ",i)}return e}convertLegacyCategory(e){try{if(e.commentCategories===void 0||e.commentCategories===null||!Array.isArray(e.commentCategories)||e.commentCategories.length===0)return e;typeof e.commentCategories[0]=="string"&&(e.commentCategories=e.commentCategories.map(i=>U.CommentCategoryMap[i]))}catch(i){this.loggingService.catch("Error in CustomFilterService convertLegacyCategory: ",i)}return e}};o.\u0275fac=function(i){return new(i||o)(J(y))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var hc=(()=>{let o=class o{constructor(e,i,r){this.domService=e,this.loggingService=i,this.sanitizer=r,this.emojis={};try{this.loggingService.log("%c[WB] Creating CLASS: EmojiService","color: blue;"),Object.keys(o.Icons).forEach(a=>{let s=o.Icons[a];this.emojis[a]=this.sanitizer.bypassSecurityTrustHtml(this.domService.sanitizeSvg(s))}),Object.keys(o.GIF_PATHS).forEach(a=>{let s=`<img src="${o.GIF_PATHS[a]}" alt="${a}" />`;this.emojis[a]=this.sanitizer.bypassSecurityTrustHtml(this.domService.sanitizeHtml(s))})}catch(a){this.loggingService.catch("Error in EmojiService constructor: ",a)}}getEmoji(e){try{return this.emojis[e]}catch{return""}}getEmojiFromIconUrl(e){try{return this.sanitizer.bypassSecurityTrustHtml(this.domService.sanitizeHtml(`<img src="${e}" alt="emoji" />`))}catch{return""}}getEmojiFromIconEmoji(e,i){try{let r=`<span class="velt-emoji-icon velt-emoji-icon--emoji">${e}</span>`;return i&&(r=`<span class="velt-emoji-icon velt-emoji-icon--emoji" emoji-id=${i}>${e}</span>`),this.sanitizer.bypassSecurityTrustHtml(this.domService.sanitizeHtml(r))}catch{return""}}setEmojiList(e){try{this.emojis={},Object.keys(e).forEach(i=>{let r=e[i];if(r.svg)this.emojis[i]=this.sanitizer.bypassSecurityTrustHtml(this.domService.sanitizeSvg(r.svg));else if(r.url){let a=`<img src="${r.url}" alt="${i}" />`;this.emojis[i]=this.sanitizer.bypassSecurityTrustHtml(this.domService.sanitizeHtml(a))}else r.emoji&&(this.emojis[i]=this.getEmojiFromIconEmoji(this.domService.sanitizeHtml(r.emoji)))})}catch(i){this.loggingService.catch("Error in EmojiService setEmojiList: ",i)}}};o.Icons={RAISED_HANDS:`<svg width="58" height="57" viewBox="0 0 58 57" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
195
|
+
`+wr),_c&&_M([Be,Se,Ut],Is=>{wr=jS(wr,Is," ")}),Le&&ag?Le.createHTML(wr):wr},o.setConfig=function(){let Yt=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Rm(Yt),rg=!0},o.clearConfig=function(){km=null,rg=!1},o.isValidAttribute=function(Yt,Ve,yt){km||Rm({});let Wt=uo(Yt),to=uo(Ve);return e_(Wt,to,yt)},o.addHook=function(Yt,Ve){typeof Ve=="function"&&US(ue[Yt],Ve)},o.removeHook=function(Yt,Ve){if(Ve!==void 0){let yt=_Pe(ue[Yt],Ve);return yt===-1?void 0:yPe(ue[Yt],yt,1)[0]}return Wae(ue[Yt])},o.removeHooks=function(Yt){ue[Yt]=[]},o.removeAllHooks=function(){ue=Jae()},o}var s$=ose();var rse={ADD_TAGS:["velt-skeleton-loader"],ADD_ATTR:["border-radius"]},Fe=(()=>{let o=class o{constructor(e,i,r){this.rendererFactory2=e,this.loggingService=i,this.sanitizer=r,this.isVideoEditorHandlingDelete=!1,this.pageScrollHeight=0,this.enableRectSelectionSubject$=new fe(!1),this.enableRectSelection$=this.enableRectSelectionSubject$.asObservable(),this.scrollableElementsIds$=new fe([]),this.mousedown=!1,this.windowMouseDown$=new et,this.windowPointerMove$=new fe(null),this.windowPointerUp$=new fe(null),this.documentSelectionChange$=new fe(null),this.windowClick$=new fe(null),this.windowScroll$=new fe(null),this.windowResize$=new fe(null),this.windowKeyupBackspace$=new fe(null),this.windowKeyupDelete$=new fe(null),this.windowKeyupEsc$=new fe(null),this.windowPopState$=new fe(null),this.documentClick$=new fe(null),this.documentClickSubject$=new et,this.documentFocus$=new fe(null),this.windowKeydownShift$=new fe(null),this.windowKeyupShift$=new fe(null),this.mutation$=new fe(null),this.childListMutation$=new fe(null),this.networkStatus$=new fe(!1),this.xpathCache=new Map,this.xpathCacheId=new Map,this.selectedAnnotationsMap$=new fe({}),this.selectedAnnotationsLocationMap$=new fe({}),this.recordingInProgress$=new fe({}),this.deleteAnnotations$=new fe([]),this.pinHighlighterClass$=new fe(null),this.dialogOpenedInSidebar$=new fe(!1),this.textHighlighterClass$=new fe(null),this.commentPinHighlighter$=new fe(!1),this.deviceInfo$=new fe(new Jn),this.customCss$=new fe(null),this.mutationObserver=null,this.previousMousePosition={pageX:0,pageY:0,clientX:0,clientY:0},this.currentMousePosition={pageX:0,pageY:0,clientX:0,clientY:0,element:{xpath:"",topPercentage:0,leftPercentage:0}},this.nodeMap={},this.unlistenElementScroll={},this.filterSnippylyNodes=a=>{try{let s=[];return a.forEach(c=>{if(!ji(c))if(c instanceof HTMLElement){if(c.className.includes("cdk-overlay-container")||c.className.includes("cdk-overlay-connected-position-bounding-box"))return;if(c.className.includes("cdk-overlay")){let p=!1;c.childNodes.forEach(h=>{ji(h)&&(p=!0)}),p||s.push(c)}else s.push(c)}else s.push(c)}),s}catch(s){return this.loggingService.catch("Error in DomService filterSnippylyNodes: ",s),[]}},this.loggingService.log("%c[WB] Creating CLASS: DomService","color: blue;");try{this.renderer=this.rendererFactory2.createRenderer(null,null);let a=this.calculateScreenSize();this.currentScreenSize$=new fe(a),this.currentMousePosition$=new fe(this.currentMousePosition),this.detectNetworkStatusChange(),this.getScrollableElementsIds$().pipe(Vi(),In(([s,c])=>{try{let p=c.filter(_=>!s.includes(_)),h=s.filter(_=>!c.includes(_));h.length&&h.map(E=>document.getElementById(E)).filter(E=>E).forEach(E=>{this.unlistenElementScroll&&this.unlistenElementScroll[E.id]&&this.unlistenElementScroll[E.id]()}),p.length&&p.map(E=>document.getElementById(E)).filter(E=>E).forEach(E=>{this.unlistenElementScroll[E.id]=this.renderer.listen(E,"scroll",D=>{let B=this.calculateScreenSize();this.currentScreenSize$.next(B)})})}catch(p){this.loggingService.catch("Error in DomService getScrollableElementsIds subscription: ",p)}})).subscribe(()=>{},s=>{this.loggingService.catch("Error in DomService getScrollableElementsIds subscription: ",s)}),this.getSelectedAnnotationsMap$().subscribe(s=>{Object.keys(s||{})?.length?Hie("snippylyUserScalableNo","viewport","width=device-width, user-scalable=no"):zie("snippylyUserScalableNo")},s=>{this.loggingService.catch("Error in DomService getSelectedAnnotationsMap$ subscription: ",s)})}catch(a){this.loggingService.catch("Error in DomService constructor: ",a)}}setDocService(e){try{this.docService=e,this.subscribeToDomEvents()}catch(i){this.loggingService.catch("Error in DomService setDocService: ",i)}}subscribeToDomEvents(){try{this.docService?.getDocumentPaths$().pipe(ce(e=>{e?(this.onWindowResize(),this.onWindowScroll(),this.onPointerDown(),this.onWindowClick(),this.onWindowKeyupBackspace(),this.onWindowKeyupDelete(),this.onWindowKeyupEsc(),this.onWindowPopState(),this.onWindowKeydownShift(),this.onWindowKeyupShift(),this.addPointerMoveListener(),this.addPointerUpListener(),this.addSelectionChangeListener(),this.onDocumentClick(),this.onDocumentFocus()):(this.unsubscribeFromWindowResize(),this.unsubscribeFromWindowScroll(),this.unsubscribeFromPointerDown(),this.unsubscribeFromWindowClick(),this.unsubscribeFromWindowKeyupBackspace(),this.unsubscribeFromWindowKeyupDelete(),this.unsubscribeFromWindowKeyupEsc(),this.unsubscribeFromWindowPopState(),this.unsubscribeFromWindowKeydownShift(),this.unsubscribeFromWindowKeyupShift(),this.unsubscribeFromPointerMoveListener(),this.unsubscribeFromPointerUpListener(),this.unsubscribeFromSelectionChangeListener(),this.unsubscribeFromDocumentClick(),this.unsubscribeFromDocumentFocus(),this.unsetMutationObserver())})).subscribe()}catch(e){this.loggingService.catch("Error in DomService subscribeToDomEvents: ",e)}}setScrollableElementsIds(e){try{e&&e.length&&this.scrollableElementsIds$.next(Array.from(new Set(e)))}catch(i){this.loggingService.catch("Error in DomService setScrollableElementsIds: ",i)}}getScrollableElementsIds$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getScrollableElementsIds$","color: green;"),this.scrollableElementsIds$.asObservable()}removeScrollableElementsIds(){this.scrollableElementsIds$.next([])}setMutationObserver(e){try{this.mutationObserver||(this.loggingService.log("%c[WB] Calling DomService FUNCTION: setMutationObserver","color: green;"),this.loggingService.log("%c[WB] setMutationObserver from: "+e,"color: green;"),this.mutationObserver=new MutationObserver(i=>{try{if(i?.find(a=>a?.attributeName===U.VELT_IGNORE_CHANGE_DETECTION))return;let r=i.filter(a=>a.type==="childList").filter(a=>{let s=a.target;return a.removedNodes.forEach(c=>{let p=c;if(typeof p.getAttribute=="function"){let h=p.getAttribute(U.ATTRIBUTES.VELT_ELEMENT_CACHE_ID);if(h!==null&&h!==""){let _=this.xpathCacheId.get(h);_!==void 0&&(this.xpathCacheId.delete(h),this.xpathCache.delete(_))}}}),ji(s)?!1:!!(this.filterSnippylyNodes(a.addedNodes).length||this.filterSnippylyNodes(a.removedNodes).length)});this.childListMutation$.next(r),r.push(...i.filter(a=>a.type==="attributes").filter(a=>!ji(a.target)).filter(a=>this.filterSnippylyNodes([a.target]).length).filter(a=>{if(a){let s=a.target;return s?.classList?.contains("snippyly-sidebar-panel")?!1:s?!s.getAttribute(U.VELT_IGNORE_CHANGE_DETECTION):!0}return!0})),r=r.filter(a=>{let s=!0;return Object.keys(U.INGNORE_MUTATION_OBSERVER_CHANGE_TAGS).forEach(c=>{a.target?.closest(c)&&(s=!1)}),s}),r=r.filter(a=>a.target&&xo(a.target)),r.length&&this.mutation$.next(r)}catch(r){this.loggingService.catch("Error in DomService change detection: ",r)}}),this.mutationObserver.observe(document.body,{childList:!0,subtree:!0,attributes:!0}))}catch(i){this.loggingService.catch("Error in DomService change detection: ",i)}}unsetMutationObserver(){try{this.mutationObserver&&(this.mutationObserver.disconnect(),this.mutationObserver=null)}catch(e){this.loggingService.catch("Error in DomService unsetMutationObserver: ",e)}}detectNetworkStatusChange(){this.loggingService.log("%c[WB] Calling FUNCTION: detectNetworkStatusChange","color: green;");try{io(oi(window,"offline").pipe(ce(()=>!1)),oi(window,"online").pipe(ce(()=>!0)),new Ft(e=>{e.next(navigator.onLine),e.complete()})).subscribe(e=>{this.networkStatus$.next(e)})}catch(e){this.loggingService.catch("Error in DomService detectNetworkStatusChange: ",e)}}onWindowResize(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowResize","color: green;");try{this.unsubscribeFromWindowResize(),this.unlistenWindowResize=this.renderer.listen("window","resize",e=>{this.windowResize$.next(e);let i=this.calculateScreenSize();this.deviceInfo$.next(new Jn),this.currentScreenSize$.next(i)})}catch(e){this.loggingService.catch("Error in DomService onWindowResize: ",e)}}unsubscribeFromWindowResize(){try{this.unlistenWindowResize&&typeof this.unlistenWindowResize=="function"&&(this.unlistenWindowResize(),this.unlistenWindowResize=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromWindowResize: ",e)}}onWindowScroll(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowScroll","color: green;");try{this.unsubscribeFromWindowScroll(),this.unlistenWindowScroll=this.renderer.listen("window","scroll",e=>{this.windowScroll$.next(e);let i=this.calculateScreenSize();this.currentScreenSize$.next(i)})}catch(e){this.loggingService.catch("Error in DomService onWindowScroll: ",e)}}unsubscribeFromWindowScroll(){try{this.unlistenWindowScroll&&typeof this.unlistenWindowScroll=="function"&&(this.unlistenWindowScroll(),this.unlistenWindowScroll=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromWindowScroll: ",e)}}onPointerDown(){this.loggingService.log("%c[WB] Calling FUNCTION: onPointerDown","color: green;");try{this.unsubscribeFromPointerDown(),this.unlistenPointerDown=this.renderer.listen("window","pointerdown",e=>{this.mousedown=!0,this.windowMouseDown$.next(e),this.setPointerPosition(e)})}catch(e){this.loggingService.catch("Error in DomService onPointerDown: ",e)}}unsubscribeFromPointerDown(){try{this.unlistenPointerDown&&typeof this.unlistenPointerDown=="function"&&(this.unlistenPointerDown(),this.unlistenPointerDown=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromPointerDown: ",e)}}onWindowClick(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowKeyupBackspace","color: green;");try{this.unsubscribeFromWindowClick(),this.unlistenWindowClick=this.renderer.listen("window","click",e=>{this.windowClick$.next(e)})}catch(e){this.loggingService.catch("Error in DomService onWindowClick: ",e)}}unsubscribeFromWindowClick(){try{this.unlistenWindowClick&&typeof this.unlistenWindowClick=="function"&&(this.unlistenWindowClick(),this.unlistenWindowClick=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromWindowClick: ",e)}}onWindowKeyupBackspace(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowKeyupBackspace","color: green;");try{this.unsubscribeFromWindowKeyupBackspace(),this.unlistenWindowKeyupBackspace=this.renderer.listen("window","keyup.backspace",e=>{this.isVideoEditorHandlingDelete||this.windowKeyupBackspace$.next(e)})}catch(e){this.loggingService.catch("Error in DomService onWindowKeyupBackspace: ",e)}}unsubscribeFromWindowKeyupBackspace(){try{this.unlistenWindowKeyupBackspace&&typeof this.unlistenWindowKeyupBackspace=="function"&&(this.unlistenWindowKeyupBackspace(),this.unlistenWindowKeyupBackspace=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromWindowKeyupBackspace: ",e)}}onWindowKeyupDelete(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowKeyupDelete","color: green;");try{this.unsubscribeFromWindowKeyupDelete(),this.unlistenWindowKeyupDelete=this.renderer.listen("window","keyup.delete",e=>{this.isVideoEditorHandlingDelete||this.windowKeyupDelete$.next(e)})}catch(e){this.loggingService.catch("Error in DomService onWindowKeyupDelete: ",e)}}unsubscribeFromWindowKeyupDelete(){try{this.unlistenWindowKeyupDelete&&typeof this.unlistenWindowKeyupDelete=="function"&&(this.unlistenWindowKeyupDelete(),this.unlistenWindowKeyupDelete=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromWindowKeyupDelete: ",e)}}onWindowKeyupEsc(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowKeyupEsc","color: green;");try{this.unsubscribeFromWindowKeyupEsc(),this.unlistenWindowKeyupEsc=this.renderer.listen("window","keyup.esc",e=>{this.windowKeyupEsc$.next(e)})}catch(e){this.loggingService.catch("Error in DomService onWindowKeyupEsc: ",e)}}unsubscribeFromWindowKeyupEsc(){try{this.unlistenWindowKeyupEsc&&typeof this.unlistenWindowKeyupEsc=="function"&&(this.unlistenWindowKeyupEsc(),this.unlistenWindowKeyupEsc=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromWindowKeyupEsc: ",e)}}onWindowPopState(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowPopState","color: green;");try{this.unsubscribeFromWindowPopState(),this.unlistenWindowPopState=this.renderer.listen("window","popstate",e=>{this.windowPopState$.next(e)})}catch(e){this.loggingService.catch("Error in DomService onWindowPopState: ",e)}}unsubscribeFromWindowPopState(){try{this.unlistenWindowPopState&&typeof this.unlistenWindowPopState=="function"&&(this.unlistenWindowPopState(),this.unlistenWindowPopState=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromWindowPopState: ",e)}}onDocumentClick(){this.loggingService.log("%c[WB] Calling FUNCTION: onDocumentClick","color: green;");try{this.unsubscribeFromDocumentClick(),this.documentClickListener=e=>{e?.target?.tagName?.toLowerCase()!==U.TAGS.SUPERFLOW_TOOLBAR&&(this.documentClick$.next(e),this.documentClickSubject$.next(e))},document.addEventListener("click",this.documentClickListener,!0)}catch(e){this.loggingService.catch("Error in DomService onDocumentClick: ",e)}}unsubscribeFromDocumentClick(){try{this.documentClickListener&&typeof this.documentClickListener=="function"&&(document.removeEventListener("click",this.documentClickListener,!0),this.documentClickListener=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromDocumentClick: ",e)}}onDocumentFocus(){this.loggingService.log("%c[WB] Calling FUNCTION: onDocumentFocus","color: green;");try{this.unsubscribeFromDocumentFocus(),this.documentFocusListener=e=>{this.documentFocus$.next(e)},document.addEventListener("focus",this.documentFocusListener,!0)}catch(e){this.loggingService.catch("Error in DomService onDocumentFocus: ",e)}}unsubscribeFromDocumentFocus(){try{this.documentFocusListener&&typeof this.documentFocusListener=="function"&&(document.removeEventListener("focus",this.documentFocusListener,!0),this.documentFocusListener=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromDocumentFocus: ",e)}}onWindowKeydownShift(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowKeydownShift","color: green;");try{this.unsubscribeFromWindowKeydownShift(),this.unlistenWindowKeydownShift=this.renderer.listen("window","keydown.shift",e=>{this.windowKeydownShift$.next(e),this.windowKeyupShift$.next(null)})}catch(e){this.loggingService.catch("Error in DomService onWindowKeydownShift: ",e)}}unsubscribeFromWindowKeydownShift(){try{this.unlistenWindowKeydownShift&&typeof this.unlistenWindowKeydownShift=="function"&&(this.unlistenWindowKeydownShift(),this.unlistenWindowKeydownShift=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromWindowKeydownShift: ",e)}}onWindowKeyupShift(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowKeyupShift","color: green;");try{this.unsubscribeFromWindowKeyupShift(),this.unlistenWindowKeyupShift=this.renderer.listen("window","keyup.shift",e=>{this.windowKeyupShift$.next(e),this.windowKeydownShift$.next(null)})}catch(e){this.loggingService.catch("Error in DomService onWindowKeyupShift: ",e)}}unsubscribeFromWindowKeyupShift(){try{this.unlistenWindowKeyupShift&&typeof this.unlistenWindowKeyupShift=="function"&&(this.unlistenWindowKeyupShift(),this.unlistenWindowKeyupShift=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromWindowKeyupShift: ",e)}}onWindowKeydown$(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowKeydown$","color: green;");try{return oi(window,"keydown")}catch(e){return this.loggingService.catch("Error in DomService onWindowKeydown$: ",e),_g}}addPointerMoveListener(){this.loggingService.log("%c[WB] Calling FUNCTION: addPointerMoveListener","color: green;");try{this.unsubscribeFromPointerMoveListener(),this.unlistenPointerMoveListener=this.renderer.listen("document","pointermove",e=>{this.windowPointerMove$.next(e),this.mouseMoveEvent=e})}catch(e){this.loggingService.catch("Error in DomService addPointerMoveListener: ",e)}}unsubscribeFromPointerMoveListener(){try{this.unlistenPointerMoveListener&&typeof this.unlistenPointerMoveListener=="function"&&(this.unlistenPointerMoveListener(),this.unlistenPointerMoveListener=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromPointerMoveListener: ",e)}}addPointerUpListener(){this.loggingService.log("%c[WB] Calling FUNCTION: addPointerUpListener","color: green;");try{this.unsubscribeFromPointerUpListener(),this.unlistenPointerUpListener=this.renderer.listen("document","pointerup",e=>{this.windowPointerUp$.next(e)})}catch(e){this.loggingService.catch("Error in DomService addPointerUpListener: ",e)}}unsubscribeFromPointerUpListener(){try{this.unlistenPointerUpListener&&typeof this.unlistenPointerUpListener=="function"&&(this.unlistenPointerUpListener(),this.unlistenPointerUpListener=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromPointerUpListener: ",e)}}addSelectionChangeListener(){this.loggingService.log("%c[WB] Calling FUNCTION: addPointerUpListener","color: green;");try{this.unsubscribeFromSelectionChangeListener(),this.unlistenSelectionChangeListener=this.renderer.listen("document","selectionchange",e=>{this.documentSelectionChange$.next(e)})}catch(e){this.loggingService.catch("Error in DomService addPointerUpListener: ",e)}}unsubscribeFromSelectionChangeListener(){try{this.unlistenSelectionChangeListener&&typeof this.unlistenSelectionChangeListener=="function"&&(this.unlistenSelectionChangeListener(),this.unlistenSelectionChangeListener=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromSelectionChangeListener: ",e)}}updateCurrentMousePosition(e){try{if(this.currentMousePosition.pageX=e.pageX,this.currentMousePosition.pageY=e.pageY,this.currentMousePosition.clientX=e.clientX,this.currentMousePosition.clientY=e.clientY,e.target){let i=this.getXPath(e.target),r=e.target;if(i?.includes("name()='svg'")){let _=this.getXPath(i);_&&(r=_.iterateNext()||e.target)}let a=r.getBoundingClientRect(),s=e.clientX-a.x,c=e.clientY-a.y,p=s*100/(a.width||1),h=c*100/(a.height||1);this.currentMousePosition.element={xpath:i,topPercentage:h,leftPercentage:p}}else this.currentMousePosition.element=null;this.currentMousePosition$.next(this.currentMousePosition)}catch(i){this.loggingService.catch("Error in DomService updateCurrentMousePosition: ",i)}}getTargetElementForCursorPosition(e,i=!0,r=!1,a=!0,s){try{let c=e,p=c?.touches?.length?c.touches[0]?.clientX:c.clientX,h=c?.touches?.length?c.touches[0]?.clientY:c.clientY,_=this.getBackgroundElement(p,h,i,r);if(_&&s&&typeof s=="function"&&(_=s(_)),_){let E=this.getXPath(_),D=this.getXPath(_,!0),B=_.getBoundingClientRect(),G=p-B.x,X=h-B.y,he=G*100/(B.width||1),Ie=X*100/(B.height||1),Me={xpath:E,fXpath:D,leftPercentage:he,topPercentage:Ie};if(a){let Le=this.getXPath(_,!0,!0);Me.cfXpath=Le}return Me}else return null}catch(c){return this.loggingService.catch("Error in DomService getTargetElementForCommentPinAnnotation: ",c),null}}getBackgroundElement(e,i,r=!0,a=!1){try{let s=document.elementsFromPoint(e,i),c=[];s.forEach(h=>{ji(h)?c=[]:xo(h)&&c.push(h)}),a&&(c=c.filter(h=>this.isElementVisibleOnScreen(h)));let p=0;return r||c?.forEach((h,_)=>{h.tagName.toLowerCase()==="svg"&&(p=_)}),c[p]}catch(s){return this.loggingService.catch("Error in DomService getBackgroundElement: ",s),null}}getBackgroundVeltElement(e,i){try{let r=document.elementsFromPoint(e,i),a=[];return r.forEach(s=>{ji(s)&&xo(s)&&a.push(s)}),a[0]}catch(r){return this.loggingService.catch("Error in DomService getBackgroundSnippylyElement: ",r),null}}setPointerPosition(e){this.loggingService.log("%c[WB] Calling FUNCTION: setPointerPosition","color: green;");try{this.previousMousePosition.pageX=e.pageX,this.previousMousePosition.pageY=e.pageY,this.currentMousePosition.pageX=e.pageX,this.currentMousePosition.pageY=e.pageY}catch(i){this.loggingService.catch("Error in DomService setPointerPosition: ",i)}}getCurrentWindowSize$(e){return this.loggingService.log("%c[WB] Calling FUNCTION: getCurrentWindowSize","color: green;"),this.currentScreenSize$.asObservable()}getCurrentMousePosition$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getCurrentMousePosition","color: green;"),this.currentMousePosition$.asObservable()}getCurrentWindowSizeValue(){return this.loggingService.log("%c[WB] Calling FUNCTION: getCurrentWindowSizeValue","color: green;"),this.currentScreenSize$.value}getTopLeftPosition(){this.loggingService.log("%c[WB] Calling FUNCTION: getTopLeftPosition","color: green;");try{let e=document?.body?.getBoundingClientRect()||document?.documentElement?.getBoundingClientRect(),i=this.currentMousePosition?.pageX||e.x+200,r=Math.min(i,e.width/2),a=Math.abs(e.y),s=e.y-20;return a>50&&(s=Math.abs(e.y)+180),this.loggingService.log(e),this.loggingService.log(r),this.loggingService.log(s),{topPositionX:r,topPositionY:s}}catch(e){return this.loggingService.catch("Error in DomService getTopLeftPosition: ",e),{topPositionX:0,topPositionY:0}}}toggleSelection(){this.enableRectSelectionSubject$.next(!this.enableRectSelectionSubject$.value)}enableSelection(){this.enableRectSelectionSubject$.next(!0)}disableSelection(){this.enableRectSelectionSubject$.next(!1)}setPinHighlighterClass(e){this.pinHighlighterClass$.next(e)}setTextHighlighterClass(e){this.textHighlighterClass$.next(e)}getTextHighlighterClass(){return this.textHighlighterClass$.asObservable()}enableCommentPinHighlighter(){this.commentPinHighlighter$.next(!0)}disableCommentPinHighlighter(){this.commentPinHighlighter$.next(!1)}getCommentPinHighlighter$(){return this.commentPinHighlighter$.asObservable()}getCommentPinHighlighter(){return this.commentPinHighlighter$?.value}highlightElement(e,i,r){if(e){if(!r&&this.getCommentPinHighlighter()&&(this.pinHighlighterClass$.value?this.addClassToElement(e,this.pinHighlighterClass$.value):this.addClassToElement(e,U.SNIPPYLY_HIGHLIGHT)),i&&!e.hasAttribute(U.ATTRIBUTES.DEFAULT_CURSOR)){let a=e.style.getPropertyValue("cursor"),s=e.style.getPropertyPriority("cursor"),c=a?{defaultCursorValue:a,defaultCursorPriority:s}:"";e.setAttribute(U.ATTRIBUTES.DEFAULT_CURSOR,c?JSON.stringify(c):""),e.style.setProperty("cursor",i,"important")}e.setAttribute(U.SNIPPYLY_HIGHLIGHT,"true"),e.setAttribute(U.VELT_IGNORE_CHANGE_DETECTION,"true")}}removeHighlightFromElement(e){if(e&&(this.pinHighlighterClass$.value&&this.removeClassFromElement(e,this.pinHighlighterClass$.value),this.removeClassFromElement(e,U.SNIPPYLY_HIGHLIGHT),e.removeAttribute(U.SNIPPYLY_HIGHLIGHT),e.removeAttribute(U.VELT_IGNORE_CHANGE_DETECTION),e.hasAttribute(U.ATTRIBUTES.DEFAULT_CURSOR))){try{if(e.style.removeProperty("cursor"),e.getAttribute(U.ATTRIBUTES.DEFAULT_CURSOR)){let i=JSON.parse(e.getAttribute(U.ATTRIBUTES.DEFAULT_CURSOR));e.style.setProperty("cursor",i.defaultCursorValue,i.defaultCursorPriority)}}catch{}e.removeAttribute(U.ATTRIBUTES.DEFAULT_CURSOR)}}highlightUserElement(e,i,r,a=!1){try{e&&(this.addClassToElement(e,U.VELT_LIVE_SELECTION_ON_ELEMENT),a&&this.addClassToElement(e,U.VELT_LIVE_SELECTION_ON_ELEMENT_DEFAULT),e.setAttribute(U.SNIPPYLY_HIGHLIGHT,"true"),e.setAttribute(U.VELT_IGNORE_CHANGE_DETECTION,"true"),i&&!e.style.getPropertyValue(U.VELT_SELECTION_COLOR)&&e.style.setProperty(U.VELT_SELECTION_COLOR,i),r&&e.setAttribute(U.SNIPPYLY_HIGHLIGHT_USER_NAME,r))}catch(s){this.loggingService.catch("Error in DomService highlightUserElement: ",s)}}removeHighlightUserFromElement(e){try{e&&(this.removeClassFromElement(e,U.VELT_LIVE_SELECTION_ON_ELEMENT),this.removeClassFromElement(e,U.VELT_LIVE_SELECTION_ON_ELEMENT_DEFAULT),e.removeAttribute(U.SNIPPYLY_HIGHLIGHT),e.removeAttribute(U.VELT_IGNORE_CHANGE_DETECTION),e.removeAttribute(U.VELT_SELECTION_COLOR),e.removeAttribute(U.SNIPPYLY_HIGHLIGHT_USER_NAME),e.style.removeProperty(U.VELT_SELECTION_COLOR))}catch(i){this.loggingService.catch("Error in DomService removeHighlightUserFromElement: ",i)}}previewHighlightElement(e){e&&e.setAttribute(U.SNIPPYLY_HIGHLIGHT_PREVIEW,"true")}removePreviewHighlightFromElement(e){e&&e.removeAttribute(U.SNIPPYLY_HIGHLIGHT_PREVIEW)}getXPath(e,i=!1,r=!1,a){try{let s=this.calculateXPath(e,i,r,a);if(s&&typeof s=="string"&&s.includes("/svg")){let c=s.split("/"),p=!1;c.forEach((h,_)=>{h.includes("svg")&&(p=!0),p&&(c[_]="svg:"+h)}),s=c.join("/")}return s}catch(s){this.loggingService.catch("Error in DomService getXPath:",s)}}namespaceResolver(e){return e==="svg"?"http://www.w3.org/2000/svg":null}calculateXPath(e,i,r,a){try{if(e){if(typeof e=="string")return document.evaluate(e,a||document,this.namespaceResolver,XPathResult.ANY_TYPE,null);if(!e||e.nodeType!=1)return"";if(e.id&&document.querySelectorAll(`[id='${e.id}']`)?.length===1&&!i)return"//*[@id='"+e.id+"']";if(r&&e.className&&e.className.split){let c=e.className?.split(" ")?.filter(p=>!p?.includes("snippyly")&&!p?.includes("velt")&&!["show-pin-cursor"].includes(p))[0];if(c){let p=this.calculateXPath(e.parentNode,i,r,a)+"/"+e.tagName.toLowerCase(),h=Array.from(e.parentNode?.children||[]).filter(_=>_.nodeType===1&&_.tagName===e.tagName?_.className?.split(" ")?.filter(D=>D?.includes("snippyly")||D?.includes("velt")||["show-pin-cursor"].includes(D))[0]===c:!1);if(h.length>1){let _=h.indexOf(e)+1;p+=`[contains(concat(' ', normalize-space(@class), ' '), ' ${c} ')][${_}]`}else p+=`[contains(concat(' ', normalize-space(@class), ' '), ' ${c} ')]`;return p}}let s=[].filter.call(e.parentNode?.children?e.parentNode?.children:[],function(c){return c.tagName==e.tagName});return this.calculateXPath(e.parentNode,i,r)+"/"+e.tagName.toLowerCase()+(s.length>1?"["+([].indexOf.call(s,e)+1)+"]":"")}}catch(s){this.loggingService.catch("Error in DomService calculateXPath:",s)}}getElementFromXPath(e,i=document){try{if(this.xpathCache.has(e)){let a=this.xpathCache.get(e);if(a!==void 0&&document.contains(a))return a;this.xpathCache.delete(e)}let r=this.getXPath(e,!1,!1,i);if(r){let a=r?.iterateNext();if(a!==null&&typeof a.setAttribute=="function"){let s=xn();a.setAttribute(U.ATTRIBUTES.VELT_ELEMENT_CACHE_ID,s),this.xpathCacheId.set(s,e)}return this.xpathCache.set(e,a),a}return null}catch(r){return this.loggingService.catch("Error in DomService getElementFromXPath:",r),null}}calculateScreenSize(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowResize","color: green;");try{let e=[document?.body?.clientHeight||0,document?.documentElement?.clientHeight||0,window?.innerHeight||0],i=[document?.body?.clientWidth||0,document?.documentElement?.clientWidth||0,window?.innerWidth||0];this.calculatePageScrollHeight(),this.loggingService.log(this.pageScrollHeight),this.loggingService.log(this.nodeMap),this.highestNode=this.nodeMap[this.pageScrollHeight];let r=new NS;return r.screenWidth=Math.max(...i),r.screenHeight=Math.max(...e),r.screenScrollHeight=this.pageScrollHeight,r}catch(e){return this.loggingService.catch("Error in DomService calculateScreenSize:",e),new NS}}calculatePageScrollHeight(){this.loggingService.log("%c[WB] Calling FUNCTION: calculatePageScrollHeight","color: green;");try{this.pageScrollHeight=0,this.findLongestNode(document?.documentElement?.childNodes)}catch(e){this.loggingService.catch("Error in DomService calculatePageScrollHeight: ",e)}}removeSnippylyContent(e){this.loggingService.log("%c[WB] Calling FUNCTION: removeSnippylyContent","color: green;");try{let r=new DOMParser().parseFromString(e,"text/html");r.querySelectorAll("[data-snippyly-cache-id]").forEach(E=>{E.removeAttribute("data-snippyly-cache-id")}),r.querySelectorAll("[data-velt-cache-id]").forEach(E=>{E.removeAttribute("data-velt-cache-id")}),r.querySelectorAll(".comment-text-highlight").forEach(E=>{E?.parentNode?.insertBefore(document.createTextNode(E?.textContent),E),E.remove()});let p=document.createNodeIterator(r,NodeFilter.SHOW_COMMENT),h;for(;h=p.nextNode();)h?.remove();return this.mergeAdjacentTextNodes(r.body),this.sanitizeHtml(r.body.innerHTML)}catch(i){return this.loggingService.catch("Error in DomService removeSnippylyContent: ",i),e}}mergeAdjacentTextNodes(e){try{let i=e.firstChild;for(;i;){if(i.nodeType===Node.TEXT_NODE){let r=i.nextSibling;for(;r&&r.nodeType===Node.TEXT_NODE;)i.textContent+=r.textContent,r.remove(),r=i.nextSibling}i=i.nextSibling}}catch(i){this.loggingService.catch("Error in DomService mergeAdjacentTextNodes: ",i)}}findLongestNode(e){try{for(let i=e.length-1;i>=0;i--){if(e[i]?.scrollHeight&&e[i]?.clientHeight){let r=Math.max(e[i]?.scrollHeight,e[i]?.clientHeight);this.pageScrollHeight=Math.max(r,this.pageScrollHeight),this.nodeMap[r]=e[i]}e[i]?.childNodes?.length&&this.findLongestNode(e[i]?.childNodes)}}catch(i){this.loggingService.catch("Error in DomService findLongestNode: ",i)}}resetSelectedAnnotationsMap(e=!0,i){try{let r=Array.from(document.querySelectorAll(`[${U.ATTRIBUTES.VELT_ANNOTATION_DRAFT}]`)),a=this.getDraftCommentAnnotationDialogs()||[];r.push(...a),r=Array.from(new Set(r));let s=r.map(_=>_.classList.contains("velt-annotation-draft-checked")?(_.classList.remove("velt-annotation-draft-checked"),null):(this.removeClassFromElement(_,"velt-comment-dialog-shake"),setTimeout(()=>{this.addClassToElement(_,"velt-comment-dialog-shake"),_.getAttribute(U.ATTRIBUTES.VELT_ANNOTATION_EDIT_COMMENT)||_.classList.contains("velt-annotation-draft-checked")||this.addClassToElement(_,"velt-annotation-draft-checked")},100),_.getAttribute(U.ATTRIBUTES.VELT_ANNOTATION_DRAFT))).filter(_=>_),c=Object.keys(this.getRecordingInProgress()||{});s=[...s,...c];let p=this.selectedAnnotationsMap$.value;if(e&&this.selectedAnnotationsMap$.value&&Object.keys(this.selectedAnnotationsMap$.value).length){let _=[];Object.keys(p).forEach(E=>{if(p[E]?.type==="tag"){let D=p[E];D?.to?.length||s.includes(E)||_.push(D)}else p[E]?.comments?.length||s.includes(E)||_.push(p[E])}),this.deleteAnnotations$.next(_),this.deleteAnnotations$.next([])}let h={};Object.keys(p).forEach(_=>{if(s.includes(_)&&(h[_]=p[_]),i)switch(i){case"comment":["comment","videoPin"].includes(p[_]?.type)||(h[_]=p[_]);break;default:p[_]?.type!==i&&(h[_]=p[_]);break}}),Object.keys(h).forEach(_=>{let E=h[_]?.multiThreadAnnotationId;E&&!h[E]&&(h[E]={annotationId:E,type:"multiThread"})}),JSON.stringify(this.selectedAnnotationsMap$.value)!==JSON.stringify(h)&&this.selectedAnnotationsMap$.next(h),this.setDialogOpenedInSidebar(!1)}catch(r){this.loggingService.catch("Error in DomService resetSelectedAnnotationsMap: ",r)}}setRecordingInProgress(e,i){try{if(i)this.recordingInProgress$.next(T(I({},this.recordingInProgress$.value),{[e]:i}));else{let r=this.recordingInProgress$.value;delete r[e],this.recordingInProgress$.next(r)}}catch(r){this.loggingService.catch("Error in DomService setRecordingInProgress: ",r)}}resetRecordingInProgress(){try{this.recordingInProgress$.next({})}catch(e){this.loggingService.catch("Error in DomService resetRecordingInProgress: ",e)}}getRecordingInProgress(){try{return this.recordingInProgress$.value}catch(e){return this.loggingService.catch("Error in DomService getRecordingInProgress: ",e),{}}}getDraftCommentAnnotationDialogs(){try{let e=[];return Array.from(document.querySelectorAll(`${U.TAGS.SNIPPYLY_COMMENT_DIALOG}`)).forEach(r=>{if(r?.shadowRoot){let a=r.shadowRoot.querySelector(`[${U.ATTRIBUTES.VELT_ANNOTATION_DRAFT}]`);a&&e.push(a)}else{let a=r.querySelector(`${U.TAGS.VELT_SHADOW_DOM_INTERNAL}`);if(a?.shadowRoot){let s=a.shadowRoot?.querySelector(`[${U.ATTRIBUTES.VELT_ANNOTATION_DRAFT}]`);s&&e.push(s)}else{let s=r.querySelector(`[${U.ATTRIBUTES.VELT_ANNOTATION_DRAFT}]`);s&&e.push(s)}}}),e}catch(e){return this.loggingService.catch("Error in DomService getDraftCommentAnnotationDialogs: ",e),[]}}getSelectedAnnotationsMap(e){try{let i=this.selectedAnnotationsMap$.value;if(e){let r={};return Object.keys(i).forEach(a=>{switch(e){case"comment":["comment","videoPin"].includes(i[a].type)&&(r[a]=i[a]);break;default:i[a].type===e&&(r[a]=i[a]);break}}),r}else return i}catch(i){return this.loggingService.catch("Error in DomService getSelectedAnnotationsMap: ",i),{}}}getSelectedAnnotationsMap$(e){return this.selectedAnnotationsMap$.asObservable().pipe(ce(i=>{if(e){let r={};return Object.keys(i).forEach(a=>{i[a].type===e&&(r[a]=i[a])}),r}else return i}))}getSelectedComments$(){return this.selectedAnnotationsMap$.asObservable().pipe(ce(e=>Object.values(e)))}getSelectedAnnotationsLocationMap(){try{return this.selectedAnnotationsLocationMap$.value}catch(e){return this.loggingService.catch("Error in DomService getSelectedAnnotationsLocationMap: ",e),{}}}getSelectedAnnotationsLocationMap$(){return this.selectedAnnotationsLocationMap$.asObservable()}toggleAnnotationSelection(e,i,r,a=!1){try{r==="sidebarShowReplies"?this.setDialogOpenedInSidebar(!0):this.setDialogOpenedInSidebar(!1);let s=JSON.parse(JSON.stringify(this.selectedAnnotationsMap$.value||{})),c=JSON.parse(JSON.stringify(this.selectedAnnotationsLocationMap$.value||{}));if(s[e.annotationId]&&!a)delete s[e.annotationId];else{(!this.windowKeydownShift$.value||a)&&(s={}),s[e.annotationId]=e,c[e.annotationId]=i;let p=e?.multiThreadAnnotationId;p&&(s[p]={annotationId:p,type:"multiThread"},c[p]=i)}this.selectedAnnotationsMap$.next(s),Object.keys(c).forEach(p=>{s[p]||delete c[p]}),this.selectedAnnotationsLocationMap$.next(c)}catch(s){this.loggingService.catch("Error in DomService toggleAnnotationSelection: ",s)}}setSelectedAnnotationLocation(e,i){try{let r=JSON.parse(JSON.stringify(this.getSelectedAnnotationsLocationMap()||{}));r?.[e]!==i&&(r[e]=i,this.selectedAnnotationsLocationMap$.next(r))}catch(r){this.loggingService.catch("Error in DomService setSelectedAnnotationLocation: ",r)}}updateSelectedAnnotationInMap(e){try{let i=this.selectedAnnotationsMap$.value;e.forEach(r=>{i[r.annotationId]&&(i[r.annotationId]=r)}),this.selectedAnnotationsMap$.next(i)}catch(i){this.loggingService.catch("Error in DomService updateSelectedAnnotationInMap: ",i)}}getDeleteCommmentAnnotations$(){try{return this.deleteAnnotations$.asObservable()}catch(e){return this.loggingService.catch("Error in DomService getDeleteCommmentAnnotations$: ",e),re([])}}getHighestNode(){return this.loggingService.log("%c[WB] Calling FUNCTION: getHighestNode","color: green;"),this.highestNode}onWindowMouseDown$(){return this.windowMouseDown$.asObservable()}onWindowPointerMove$(){return this.windowPointerMove$.asObservable()}onWindowPointerMove(){return this.windowPointerMove$.value}onWindowPointerUp$(){return this.windowPointerUp$.asObservable()}onSelectionChange$(){return this.documentSelectionChange$.asObservable()}onWindowClick$(){return this.windowClick$.asObservable()}onWindowScroll$(){return this.windowScroll$.asObservable()}onWindowResize$(){return this.windowResize$.asObservable()}onWindowKeyupBackspace$(){return this.windowKeyupBackspace$.asObservable()}onWindowKeyupDelete$(){return this.windowKeyupDelete$.asObservable()}onWindowKeyupEsc$(){return this.windowKeyupEsc$.asObservable()}onWindowPopState$(){return this.windowPopState$.asObservable()}onDocumentClick$(){return this.documentClick$.asObservable()}getLastDocumentClick(){return this.documentClick$.value}onDocumentClickSubject$(){return this.documentClickSubject$.asObservable()}onDocumentFocus$(){return this.documentFocus$.asObservable()}onDomChange$(e){try{return this.mutationObserver||this.setMutationObserver(e),this.mutation$.asObservable()}catch(i){return this.loggingService.catch("Error in DomService onDomChange$: ",i),re([])}}getChildListMutation$(){return this.childListMutation$.asObservable()}onNetworkStatusChange$(){return this.networkStatus$.asObservable()}getElementOffset(e,i){try{let r={offsetTop:0,offsetLeft:0},a=e;if(a===i){let s=window.getComputedStyle(e);s.position==="static"&&s.transformStyle!="preserve-3d"&&s.transform=="none"&&(r.offsetLeft=e?.offsetLeft||0,r.offsetTop=e?.offsetTop||0)}if(a!==i)if(e?.closest("svg"))for(;a&&a!==i;){let c=window.getComputedStyle(a);if(a.tagName.toLowerCase()==="svg"||a instanceof SVGElement){let p=a.parentElement;if(p){let h=p.getBoundingClientRect(),_=a.getBoundingClientRect();r.offsetLeft+=_.left-h.left,r.offsetTop+=_.top-h.top}}else c.position==="static"?c.transformStyle!="preserve-3d"&&c.transform=="none"&&(r.offsetLeft+=a?.offsetLeft||0,r.offsetTop+=a?.offsetTop||0):(r.offsetLeft+=a.offsetLeft,r.offsetTop+=a.offsetTop);if(a=a.parentElement,e instanceof SVGElement&&a===i){let p=window.getComputedStyle(a);p.position==="static"&&p.transformStyle!="preserve-3d"&&p.transform=="none"&&(r.offsetLeft+=a?.offsetLeft||0,r.offsetTop+=a?.offsetTop||0)}}else{let c=window.getComputedStyle(a);c.position==="static"?c.transformStyle!="preserve-3d"&&c.transform=="none"&&(r.offsetLeft+=a?.offsetLeft||0,r.offsetTop+=a?.offsetTop||0):(r.offsetLeft+=a.offsetLeft,r.offsetTop+=a.offsetTop)}return r}catch(r){return this.loggingService.catch("Error in DomService getElementOffset: ",r),{offsetTop:0,offsetLeft:0}}}isElementVisible(e){try{if(typeof e?.getBoundingClientRect=="function"){let{width:i,height:r,top:a,bottom:s}=e?.getBoundingClientRect();return i>0||r>0||a<window.innerHeight&&s>0}else return!1}catch(i){return this.loggingService.catch("Error in DomService isElementVisible: ",i),!1}}isElementVisibleOnScreen(e){try{if(e){if(!(e instanceof Element))return!1;let i=e,r=window.getComputedStyle(i);return!(r.display==="none"||r.visibility==="hidden"||parseFloat(r.opacity)===0)}return!1}catch(i){return this.loggingService.catch("Error in DomService isElementVisibleOnScreen: ",i),!1}}getClickAndDragPointsObservable(){return new Ft(e=>{let i=oi(document,"mousedown").pipe(ce(p=>({type:p.type,x:p.clientX+window.scrollX,y:p.clientY+window.scrollY,event:p}))),r=oi(document,"mousemove").pipe(ce(p=>({type:p.type,x:p.clientX+window.scrollX,y:p.clientY+window.scrollY,event:p}))),a=oi(document,"mouseup").pipe(ce(p=>({type:p.type,x:p.clientX+window.scrollX,y:p.clientY+window.scrollY,event:p}))),c=i.pipe(ge(p=>r.pipe(Vi(),ce(([h,_])=>({startPoint:p,prevPoint:h,curPoint:_})),oo(a)))).subscribe(e);return()=>c.unsubscribe()})}drawRectangle(e,i){let r=document.querySelector(".rectangle");r||(r=document.createElement("div"),this.addClassToElement(r,"rectangle"),r.setAttribute(U.ATTRIBUTES.VELT_COMMENT_DISABLED,"true"),r.setAttribute(U.VELT_IGNORE_CHANGE_DETECTION,"true"),document.body.appendChild(r));let a=Math.abs(i.x-e.x),s=Math.abs(i.y-e.y),c=Math.min(e.x,i.x),p=Math.min(e.y,i.y);return r.style.width=`${a}px`,r.style.height=`${s}px`,r.style.left=`${c}px`,r.style.top=`${p}px`,r.style.position="absolute",r.style.border="2px dashed #f00",r.style.pointerEvents="none",r.style.zIndex="2147483577",r}getRange(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: getRange","color: green;"),window.getSelection()?.toString()){let e=window.getSelection();if(e?.rangeCount)return e.getRangeAt(0)}return null}catch(e){return this.loggingService.catch("Error in DomService getRange: ",e),null}}clearTextSelection(){try{this.loggingService.log("%c[WB] Calling FUNCTION: clearTextSelection","color: green;"),window.getSelection&&(window.getSelection()?.empty?window.getSelection()?.empty():window.getSelection()?.removeAllRanges&&window.getSelection()?.removeAllRanges())}catch(e){this.loggingService.catch("Error in DomService clearTextSelection: ",e)}}getTargetTextRangeFromSelectionRange(e){try{let i={},r=e.commonAncestorContainer;r?.nodeType===Node.TEXT_NODE&&(r=r.parentElement);let a=document.body;if(r){let c=this.getTextXPath(r);this.isXpathWithId(c)&&(a=r)}let s=this.getAdditionalLocationContainer(r);if(s&&(a=s),i.commonAncestorContainer=this.getTextXPath(a),i.commonAncestorContainer){let c=this.getElementFromXPath(i.commonAncestorContainer);c&&(i.commonAncestorContainerFXpath=this.getXPath(c,!0),i.commonAncestorContainerCFXpath=this.getXPath(c,!0,!0))}return i.text=e.toString(),i.occurrence=Au(a,0,e.startContainer,e.startOffset,e.toString())+1,i}catch(i){this.loggingService.catch("Error in DomService getTargetTextRangeFromSelectionRange: ",i);return}}getTextXPath(e){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: getTextXPath","color: green;"),e.nodeType===Node.TEXT_NODE){let i=1,r=e.previousSibling;for(;r;)r.nodeType===Node.TEXT_NODE&&i++,r=r.previousSibling;return this.getXPath(e.parentElement)}else return this.getXPath(e)}catch(i){this.loggingService.catch("Error in DomService getTextXPath: ",i);return}}getHostElement(e){try{if(U.NON_NESTABLE_ELEMENTS[e?.tagName?.toLowerCase()]){let r=e?.closest("picture");return r?r?.parentElement:e.parentElement}let i=e.closest("svg");return i?i?.parentElement:e}catch(i){return this.loggingService.catch("Error in DomService getHostElement: ",i),e}}isElementInsideAdditionalLocationContainer(e){try{return!!e?.closest(`[${U.ATTRIBUTES.VELT_LOCATION}], [${U.ATTRIBUTES.VELT_LOCATION_ID}]`)}catch(i){return this.loggingService.catch("Error in DomService isElementInsideAdditionalLocationContainer: ",i),!1}}getAdditionalLocationContainer(e){try{return e?.closest(`[${U.ATTRIBUTES.VELT_LOCATION}], [${U.ATTRIBUTES.VELT_LOCATION_ID}]`)||null}catch(i){return this.loggingService.catch("Error in DomService getAdditionalLocationContainer: ",i),null}}isXpathWithId(e){try{return typeof e=="string"?!!e?.includes("[@id="):!1}catch(i){return this.loggingService.catch("Error in DomService isXpathWithId: ",i),!1}}getListedElements({elementIds:e,elementClassNames:i,elementQuerySelectors:r}){try{let a=[];if(e?.length)for(let s=0;s<e.length;s++){let c=document.getElementById(e[s]);c&&a.push(c)}if(i?.length)for(let s=0;s<i.length;s++){let c=document.getElementsByClassName(i[s]);for(let p=0;p<c.length;p++){let h=c[p];h&&h instanceof HTMLElement&&a.push(h)}}if(r?.length)for(let s=0;s<r.length;s++){let c=document.querySelectorAll(r[s]);for(let p=0;p<c.length;p++){let h=c[p];h&&h instanceof HTMLElement&&a.push(h)}}return a}catch(a){return this.loggingService.catch("Error in DomService getListedElements: ",a),[]}}isElementInsideListedElementIds(e,i){try{if(i?.length){for(let r=0;r<i.length;r++){let a=document.getElementById(i[r]);if(a&&a.contains(e))return!0}return!1}return!0}catch(r){return this.loggingService.catch("Error in DomService isElementInsideListedElementIds: ",r),!1}}isElementInsideListedElementClassNames(e,i){try{if(i?.length){for(let r=0;r<i.length;r++){let a=document.getElementsByClassName(i[r]);for(let s=0;s<a.length;s++)if(a[s].contains(e))return!0}return!1}return!0}catch(r){return this.loggingService.catch("Error in DomService isElementInsideListedElementClassNames: ",r),!1}}isElementInsideListedElementQuerySelectors(e,i){try{if(i?.length){for(let r=0;r<i.length;r++){let a=document.querySelectorAll(i[r]);for(let s=0;s<a.length;s++)if(a[s].contains(e))return!0}return!1}return!0}catch(r){return this.loggingService.catch("Error in DomService isElementInsideListedElementQuerySelectors: ",r),!1}}addClassToElement(e,i){try{this.loggingService.log("%c[WB] Calling FUNCTION: addClassToElement","color: green;"),e&&(e.classList?.contains(i)||e.classList?.add(i))}catch(r){this.loggingService.catch("Error in DomService addClassToElement: ",r)}}removeClassFromElement(e,i){try{this.loggingService.log("%c[WB] Calling FUNCTION: removeClassFromElement","color: green;"),e&&e.classList?.contains(i)&&e.classList?.remove(i)}catch(r){this.loggingService.catch("Error in DomService removeClassFromElement: ",r)}}isElementInsideParentWithAttribute(e,i,r){try{let a=e;for(;a&&a!==document.body;){if(a?.getAttribute&&a?.getAttribute(i)===r)return!0;a=a.parentElement}return!1}catch(a){return this.loggingService.catch("Error in DomService isElementInsideParentWithAttribute: ",a),!1}}setVideoEditorHandlingDelete(e){try{this.isVideoEditorHandlingDelete=e}catch(i){this.loggingService.catch("Error in DomService setVideoEditorHandlingDelete: ",i)}}isVideoEditorHandlingDeleteKey(){try{return this.isVideoEditorHandlingDelete}catch(e){return this.loggingService.catch("Error in DomService isVideoEditorHandlingDeleteKey: ",e),!1}}setCustomCss(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setCustomCss","color: green;"),this.customCss$.next(e)}catch(i){this.loggingService.catch("Error in DomService setCustomCss: ",i)}}getCustomCss$(){try{return this.loggingService.log("%c[WB] Calling FUNCTION: getCustomCss$","color: green;"),this.customCss$.asObservable()}catch(e){return this.loggingService.catch("Error in DomService getCustomCss$: ",e),re(null)}}injectCustomCss(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: injectCustomCss","color: green;");let i=this.customCss$.value;if(i){let r=e?.shadowRoot?.querySelector(`[${U.VELT_CUSTOM_CSS}]`);if(r&&r.remove(),i?.type==="link"){let a=document.createElement("link");a.href=i?.value,a.rel="stylesheet",a.setAttribute(U.VELT_CUSTOM_CSS,"true"),e?.shadowRoot?.appendChild(a)}else{let a=document.createElement("style");a.innerHTML=this.sanitizeHtml(i?.value),a.setAttribute(U.VELT_CUSTOM_CSS,"true"),e?.shadowRoot?.appendChild(a)}}}catch(i){this.loggingService.catch("Error in DomService injectCustomCss: ",i)}}trimCommentHtml(e){try{let i=document.createElement("div");i.innerHTML=e,this.removeEmptyElements(i);let r=i.innerHTML;return r=r.replace(o.MULTIPLE_NBSP_REGEX," ").replace(o.TRIM_NBSP_REGEX,"").trim(),r}catch(i){return this.loggingService.catch("Error in DomService trimCommentHtml: ",i),e}}removeEmptyElements(e){try{let a=function(s){return r.test(s.innerHTML)};var i=a;let r=/^\s*(<br\s*\/?>)?\s*$/;for(;e.firstChild&&a(e.firstChild);)e.removeChild(e.firstChild);for(;e.lastChild&&a(e.lastChild);)e.removeChild(e.lastChild)}catch(r){this.loggingService.catch("Error in DomService removeEmptyElements: ",r)}}normalizeWhitespace(e){try{e.childNodes.forEach(i=>{i.nodeType===Node.TEXT_NODE?i.nodeValue=i.nodeValue?.replace(/\s+/g," ").trim()??"":i.nodeType===Node.ELEMENT_NODE&&this.normalizeWhitespace(i)})}catch(i){this.loggingService.catch("Error in DomService normalizeWhitespace: ",i)}}sanitizeHtml(e){try{return this.loggingService.log("%c[WB] Calling FUNCTION: sanitizeHtml","color: green;"),s$.sanitize(e,rse)}catch(i){return this.loggingService.catch("Error in DomService sanitizeHtml: ",i),""}}sanitizeSvg(e){try{return s$.sanitize(e,rse)}catch(i){return this.loggingService.catch("Error in DomService sanitizeSvg: ",i),e}}setDeviceInfo(){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDeviceInfo","color: green;");let e=new Jn;this.deviceInfo$.next(e)}catch(e){this.loggingService.catch("Error in DomService setDeviceInfo: ",e)}}getDeviceInfo$(){try{return this.loggingService.log("%c[WB] Calling FUNCTION: getDeviceInfo$","color: green;"),this.deviceInfo$.asObservable()}catch(e){return this.loggingService.catch("Error in DomService getDeviceInfo$: ",e),re(new Jn)}}getTabId(){try{let e=sessionStorage.getItem(U.SESSION_STORAGE.VELT_TAB_ID),i=this.getTabIdFromWindowName();return(!e||e!==i)&&(e=xn(),sessionStorage.setItem(U.SESSION_STORAGE.VELT_TAB_ID,e),this.setTabIdToWindowName(e)),e}catch(e){return this.loggingService.catch("Error in DomService getTabId: ",e),null}}getTabIdFromWindowName(){try{return window.name}catch(e){return this.loggingService.catch("Error in DomService getTabIdFromWindowName: ",e),null}}setTabIdToWindowName(e){try{window.name=e}catch(i){this.loggingService.catch("Error in DomService setTabIdToWindowName: ",i)}}getDeviceInfo(){try{return this.loggingService.log("%c[WB] Calling FUNCTION: getDeviceInfo","color: green;"),this.deviceInfo$.value}catch(e){return this.loggingService.catch("Error in DomService getDeviceInfo: ",e),new Jn}}isMobileDevice(){try{return new Jn().getDeviceType()===Zo.MOBILE}catch(e){return this.loggingService.catch("Error in DomService isMobileDevice: ",e),!1}}isTabletDevice(){try{return new Jn().getDeviceType()===Zo.TABLET}catch(e){return this.loggingService.catch("Error in DomService isTabletDevice: ",e),!1}}isDesktopDevice(){try{return new Jn().getDeviceType()===Zo.DESKTOP}catch(e){return this.loggingService.catch("Error in DomService isDesktopDevice: ",e),!1}}deepCloneElement(e){try{var i=document.createElement(e?.tagName);return Array.from(e.attributes).forEach(r=>{i.setAttribute(r.nodeName,r.nodeValue)}),e.childNodes.forEach(r=>{r.nodeType===Node.ELEMENT_NODE?i.appendChild(this.deepCloneElement(r)):r.nodeType===Node.TEXT_NODE&&i.appendChild(document.createTextNode(r.nodeValue))}),i}catch(r){return this.loggingService.catch("Error in DomService deepCloneElement: ",r),e}}setRandomNumberToElementRecursive(e){try{if(!e)return;let i=Math.random().toString(36).substring(7);e&&e.setAttribute&&typeof e.setAttribute=="function"&&(e.getAttribute("velt-wireframe-id")||e.setAttribute("velt-wireframe-id",i)),Array.from(e.children).forEach(a=>{this.setRandomNumberToElementRecursive(a)})}catch(i){this.loggingService.catch("Error in DomService setRandomNumberToElementRecursive: ",i)}}setDialogOpenedInSidebar(e){this.dialogOpenedInSidebar$.next(e)}getDialogOpenedInSidebar(){return this.dialogOpenedInSidebar$.asObservable()}removeWireframeSuffixFromTags(e){if(!e)return;Array.from(e.children).forEach(r=>{if(this.removeWireframeSuffixFromTags(r),r.tagName.toLowerCase().endsWith("-wireframe")){let a=r.tagName.toLowerCase().replace("-wireframe",""),s=document.createElement(a);for(Array.from(r.attributes).forEach(c=>{s.setAttribute(c.name,c.value)});r.firstChild;)s.appendChild(r.firstChild);r.parentNode.replaceChild(s,r)}})}isMonitorDevice(){try{return new Jn().getDeviceType()===Zo.MONITOR}catch(e){return this.loggingService.catch("Error in DomService isMonitorDevice: ",e),!1}}};o.MULTIPLE_NBSP_REGEX=/(?: \s*){2,}/g,o.TRIM_NBSP_REGEX=/^(?: \s*)+|(?: \s*)+$/g,o.\u0275fac=function(i){return new(i||o)(J(qo),J(y),J(Ms))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var je=(()=>{let o=class o{constructor(e,i,r,a,s,c,p,h){this.afAuth=e,this.configService=i,this.avatarService=r,this.coreActionsService=a,this.domService=s,this.functions=c,this.analyticsService=p,this.loggingService=h,this.user$=new fe(null),this.userOptions$=new fe(null),this.userContacts$=new fe(null),this.userOrganization$=new fe(null),this.providedUser=new wo,this.firebaseConfig$=new fe(null),this.advancedQueries$=new fe(null),this.planDetails$=new fe(null),this.signOutPreviousUser$=new fe(null),this.preSignOutFunctions=new Map,this.autoLoginCalled=!1,this.autoLoginRequired=!0,this.config=null,this.getPlanDetailsCalled=!1,this.forceReLoggedIn=!1,this.lastLoggedInUserData=null,this.sessionReLoginCount=0,this.SESSION_RE_LOGIN_COUNT_LIMIT=10,this.sessionReLoginSubscription=null,this.TOKEN_EXPIRED_ERROR_COUNT_LIMIT=3,this.tokenExpiredErrorCount=0,this.loggingService.log("%c[WB] Creating CLASS: AuthService","color: blue;");try{this.analyticsService.setAuthService(this),this.configService.getConfig$().subscribe(_=>{this.config=_}),this.forceReLoggedIn=localStorage.getItem(U.LOCAL_STORAGE.VELT_USER_FORCE_RE_LOGGED_IN)==="true",this.sessionReLoginSubscription=Wn(this.afAuth).pipe(Go(this.afAuth.currentUser),Vi(),ge(([_,E])=>this.domService.onNetworkStatusChange$().pipe(Ne(D=>D),Je(1),ce(()=>({previousUser:_,currentUser:E}))))).subscribe(D=>ee(this,[D],function*({previousUser:_,currentUser:E}){if(!E&&_){let B=_?.stsTokenManager?.expirationTime,G=new Date().getTime(),X=B-G;G>B&&(this.analyticsService.trackEvent(Z.Events.Core.SDK_SESSION_TOKEN_EXPIRED,{apiKey:this.apiKey,user:this.user$.value,lastLoggedInUserData:this.lastLoggedInUserData,timeLeft:X,forceReset:this.userOptions$.value?.forceReset,sessionReLoginCount:this.sessionReLoginCount},!0,this.user$.value?.userSnippylyId),this.user$.value&&_?.uid===this.user$.value?.userSnippylyId&&this.lastLoggedInUserData?.user?.userSnippylyId===this.user$.value?.userSnippylyId&&(this.sessionReLoginCount>this.SESSION_RE_LOGIN_COUNT_LIMIT?(this.analyticsService.trackEvent(Z.Events.Core.SDK_SESSION_RE_LOGIN_COUNT_EXCEEDED,{apiKey:this.apiKey,clientUserId:this.lastLoggedInUserData.user.userId,snippylyUserId:this.lastLoggedInUserData.user.userSnippylyId,timeLeft:X,forceReset:this.userOptions$.value?.forceReset,sessionReLoginCount:this.sessionReLoginCount},!0,this.user$.value?.userSnippylyId),this.sessionReLoginSubscription?.unsubscribe()):(this.sessionReLoginCount++,this.analyticsService.trackEvent(Z.Events.Core.SDK_SESSION_RE_LOGIN_TRIGGERED,{apiKey:this.apiKey,clientUserId:this.lastLoggedInUserData.user.userId,snippylyUserId:this.lastLoggedInUserData.user.userSnippylyId,user:this.getUserWithoutContacts(this.lastLoggedInUserData.user),timeLeft:X,forceReset:this.userOptions$.value?.forceReset,sessionReLoginCount:this.sessionReLoginCount},!0,this.lastLoggedInUserData.user.userSnippylyId),this.initializeClient(this.lastLoggedInUserData.user,this.lastLoggedInUserData.userOptions,this.lastLoggedInUserData.initializeClientToken,this.lastLoggedInUserData.autoLogin,"internal-sessionReLogin"))))}}),_=>{this.loggingService.catch("Error in AuthService sessionReLoginSubscription: ",_)}),this.getUser$().pipe(Kt(_o)).subscribe(_=>{let E=aS(_);this.coreActionsService.triggerAction(gd.USER_UPDATE,E)})}catch(_){this.loggingService.catch("Error in AuthService constructor: ",_)}}setApiKey(e,i){this.loggingService.log("%c[WB] Calling FUNCTION: setApiKey","color: green;",e);try{if(this.apiKey){this.loggingService.log("API key is already set");return}this.apiKey=e,this.configService.setApiKey(this.apiKey),i||(i=new iM),this.configService.initConfig(i),i.debugMode?sessionStorage.setItem("debugMode","true"):sessionStorage.removeItem("debugMode"),this.autoLoginCalled||Wn(this.afAuth).pipe(Je(1)).subscribe(r=>ee(this,null,function*(){if(this.autoLoginCalled=!0,r){let a=yield ad(r,!0).catch(s=>null);if(a){let{user:s}=a?.claims;this.autoLoginRequired&&this.initializeClient(s,this.userOptions$?.value?T(I({},this.userOptions$?.value),{replaceContacts:!1,replaceGroupContacts:!1,replacePrivateContacts:!1}):{},new Date().getTime(),!0,"internal-autoLogin")}}}))}catch(r){this.loggingService.catch("Error in setApiKey: ",r)}}setUsersService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setUsersService","color: green;"),this.usersService=e}catch(i){this.loggingService.catch("Error in setUsersService: ",i)}}setDocService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocService","color: green;"),this.docService=e}catch(i){this.loggingService.catch("Error in setDocService: ",i)}}setContactService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setContactService","color: green;"),this.contactService=e}catch(i){this.loggingService.catch("Error in setContactService: ",i)}}setIamService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setIamService","color: green;"),this.iamService=e}catch(i){this.loggingService.catch("Error in setIamService: ",i)}}setAreaService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setAreaService","color: green;"),this.areaService=e}catch(i){this.loggingService.catch("Error in setAreaService: ",i)}}setCommentService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setCommentService","color: green;"),this.commentService=e}catch(i){this.loggingService.catch("Error in setCommentService: ",i)}}setReactionService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setReactionService","color: green;"),this.reactionService=e}catch(i){this.loggingService.catch("Error in setReactionService: ",i)}}setRecorderAnnotationService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setRecorderAnnotationService","color: green;"),this.recorderAnnotationService=e}catch(i){this.loggingService.catch("Error in setRecorderAnnotationService: ",i)}}setViewsService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setViewsService","color: green;"),this.viewsService=e}catch(i){this.loggingService.catch("Error in setViewsService: ",i)}}setCommonDbService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setCommonDbService","color: green;"),this.commonDbService=e}catch(i){this.loggingService.catch("Error in setCommonDbService: ",i)}}validateOrganizationId(e){if(this.isVersionGreaterThanOrEqualTo4()&&!e?.organizationId)if(this.analyticsService.trackEvent(Z.Events.Core.SDK_VALIDATE_CLIENT_FAILED,{apiKey:this.apiKey,clientUserId:e.userId,snippylyUserId:e.userSnippylyId,message:"Organization Id is not set",forceReset:this.userOptions$.value?.forceReset,user:this.getUserWithoutContacts(e)},!0,e.userSnippylyId),this.configService.getSF())this.loggingService.catch("OrganizationId is not set in Identify method",void 0,void 0,!0);else throw new Error("OrganizationId is not set in Identify method")}initializeClient(e,i,r,a,s){return ee(this,null,function*(){try{if(this.autoLoginRequired=!1,this.userOptions$.next(i),this.initializeClientToken)this.pendingUserLogin=e,this.pendingUserLoginSource=s;else{e.userSnippylyId=ov(this.configService.getApiKey(),e.userId),this.pendingUserLogin=void 0,this.pendingUserLoginSource=void 0,this.initializeClientToken=r;let c=yield Wn(this.afAuth).pipe(Je(1)).toPromise().catch(h=>null),p=!0;if(this.providedUser=JSON.parse(JSON.stringify(e)),c){let h=yield ad(c,!0).catch(D=>null);if(!h)return;let{user:_,firebaseConfig:E}=h.claims;if(c?.uid!==e?.userSnippylyId||e?.groupId!==_?.groupId||e?.organizationId!==_?.organizationId||i?.forceReset||!a&&e?.organizationId&&!this.forceReLoggedIn||this.forceReLoginRequiredForAdvancedQueries(e)||this.forceReLoginRequiredForRegion(e,E))localStorage.setItem(U.LOCAL_STORAGE.VELT_USER_FORCE_RE_LOGGED_IN,"true"),this.forceReLoggedIn=!0,yield this.signOutUser("internal");else{this.loggingService.log("%c[WB] Calling FUNCTION: reinitializeCurrentUser","color: green;"),this.loggingService.log("Keeping user");let D=yield ad(c,!0).catch(he=>null);if(!D)return;let{firebaseConfig:B,user:G,advancedQueries:X}=D.claims;this.validateOrganizationId(e),this.setFirebaseConfig(B),this.setAdvancedQueries(X),G&&(this.providedUser.isAdmin=!!G.isAdmin),this.initializeSignedInUser(c,a),p=!1,this.analyticsService.trackEvent(Z.Events.Core.SDK_USER_AUTH_SUCCESS,{apiKey:this.apiKey,clientUserId:e.userId,snippylyUserId:e.userSnippylyId,authType:"auto",forceReset:this.userOptions$.value?.forceReset,user:this.getUserWithoutContacts(e),source:s})}}if(p){this.analyticsService.trackEvent(Z.Events.Core.SDK_VALIDATE_CLIENT_TRIGGERED,{apiKey:this.apiKey,clientUserId:e.userId,snippylyUserId:e.userSnippylyId,forceReset:this.userOptions$.value?.forceReset,user:this.getUserWithoutContacts(e),source:s},!0,e.userSnippylyId);let h=Cr(this.functions,Zn.cloudFunction.validateClient,{timeout:20*60*1e3}),_=Ta(),E=(yield h({apiKey:this.apiKey,user:e,version:_,authToken:i?.authToken}))?.data;if(E.error){if(this.analyticsService.trackEvent(Z.Events.Core.SDK_VALIDATE_CLIENT_FAILED,{apiKey:this.apiKey,clientUserId:e.userId,snippylyUserId:e.userSnippylyId,message:E.error,forceReset:this.userOptions$.value?.forceReset,user:this.getUserWithoutContacts(e),source:s},!0,e.userSnippylyId),E.error&&typeof E.error=="string"&&E.error?.toLowerCase()?.includes("token expired"))if(this.tokenExpiredErrorCount++,this.tokenExpiredErrorCount<=this.TOKEN_EXPIRED_ERROR_COUNT_LIMIT){let D={code:"token_expired",message:"Token expired"};this.coreActionsService.triggerAction(gd.ERROR,D)}else{let D={code:"too_many_retries",message:"Token expired. Too many retries."};this.coreActionsService.triggerAction(gd.ERROR,D),this.analyticsService.trackEvent(Z.Events.Core.SDK_JWT_EXPIRED_RETRY_EXCEEDED,{apiKey:this.apiKey,clientUserId:e.userId,snippylyUserId:e.userSnippylyId,forceReset:this.userOptions$.value?.forceReset,source:s},!0,e.userSnippylyId)}throw E.error}else this.tokenExpiredErrorCount=0;if(this.analyticsService.trackEvent(Z.Events.Core.SDK_VALIDATE_CLIENT_SUCCESS,{apiKey:this.apiKey,clientUserId:e.userId,snippylyUserId:e.userSnippylyId,forceReset:this.userOptions$.value?.forceReset,user:this.getUserWithoutContacts(e),source:s},!0,e.userSnippylyId),this.validateOrganizationId(e),E.firebaseConfig){this.setFirebaseConfig(E.firebaseConfig),yield this.signInWithCustomToken(e,E.token),this.loggingService.log("new signed in user",this.afAuth.currentUser);let D=yield ad(this.afAuth.currentUser,!0).catch(X=>null);if(!D)return;let{user:B,advancedQueries:G}=D.claims;this.setAdvancedQueries(G),this.providedUser.isAdmin=!!B?.isAdmin,this.initializeSignedInUser(this.afAuth.currentUser,a)}}this.initializeClientToken=0,this.lastLoggedInUserData={user:e,userOptions:i,initializeClientToken:r,autoLogin:a},this.checkForPendingLogin()}return e}catch(c){return this.initializeClientToken=0,this.checkForPendingLogin(),this.loggingService.catch("Error in initializeClient: ",c),Promise.resolve(null)}})}isVersionGreaterThanOrEqualTo4(){try{let e=Ta();return(e?parseInt(e.split(".")?.[0]||"0"):0)>=4}catch(e){return this.loggingService.catch("Error in isVersionGreaterThanOrEqualTo4: ",e),!1}}forceReLoginRequiredForAdvancedQueries(e){try{let i=this.isVersionGreaterThanOrEqualTo4(),r=!1;try{let a=localStorage.getItem(U.LOCAL_STORAGE.VELT_ADVANCED_QUERIES);a&&(r=JSON.parse(a)?.advancedQueriesEnabled)}catch(a){this.loggingService.catch("Error in forceReLoginRequiredForAdvancedQueries: ",a)}return!!(i&&e.organizationId&&!r)}catch(i){return this.loggingService.catch("Error in forceReLoginRequiredForAdvancedQueries: ",i),!1}}forceReLoginRequiredForRegion(e,i){try{return!!(this.isVersionGreaterThanOrEqualTo4()&&e.organizationId&&!i?.region)}catch(r){return this.loggingService.catch("Error in forceReLoginRequiredForRegion: ",r),!1}}checkForPendingLogin(){this.pendingUserLogin&&this.initializeClient(this.pendingUserLogin,this.userOptions$?.value||{},new Date().getTime(),void 0,this.pendingUserLoginSource)}setFirebaseConfig(e){this.loggingService.log("%c[WB] Calling FUNCTION: setFirebaseConfig","color: green;");try{this.firebaseConfig$.value||this.firebaseConfig$.next({firebaseOptions:I(I({},Zn.firebaseConfig),e)})}catch(i){this.loggingService.catch("Error in setFirebaseConfig: ",i)}}getFirebaseConfig$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getFirebaseConfig","color: green;"),this.firebaseConfig$.asObservable()}getFirebaseConfig(){return this.loggingService.log("%c[WB] Calling FUNCTION: getFirebaseConfig","color: green;"),this.firebaseConfig$.value}setAdvancedQueries(e){this.loggingService.log("%c[WB] Calling FUNCTION: setAdvancedQueries","color: green;");try{e&&typeof e=="object"&&localStorage.setItem(U.LOCAL_STORAGE.VELT_ADVANCED_QUERIES,JSON.stringify(e)),this.advancedQueries$.next(e)}catch(i){this.loggingService.catch("Error in setAdvancedQueries: ",i)}}getAdvancedQueries$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getAdvancedQueries$","color: green;"),this.advancedQueries$.asObservable()}getAdvancedQueries(){return this.loggingService.log("%c[WB] Calling FUNCTION: getAdvancedQueries","color: green;"),this.advancedQueries$.value}getAdvancedQueriesEnabled$(){return Dn([this.configService.getConfig$(),this.getAdvancedQueries$()]).pipe(ce(()=>this.getAdvancedQueriesEnabled()),Ln(()=>re(!1)))}getAdvancedQueriesEnabled(){try{return!this.configService.getConfig()?.advancedQueriesDisabled&&!!this.getAdvancedQueries()?.advancedQueriesEnabled}catch(e){return this.loggingService.catch("Error in getAdvancedQueriesEnabled: ",e),!1}}signOutPreviousUser(){return this.signOutPreviousUser$.asObservable()}getUser(){return this.loggingService.log("%c[WB] Calling FUNCTION: getUser","color: green;"),this.afAuth?.currentUser?this.user$.value:null}getUser$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getUser$","color: green;"),Wn(this.afAuth).pipe(ge(e=>e?this.user$.asObservable():re(null)))}getAuthUser(){return this.loggingService.log("%c[WB] Calling FUNCTION: getAuthUser","color: green;"),this.afAuth?.currentUser}getUserOptions(){return this.loggingService.log("%c[WB] Calling FUNCTION: getUserOptions","color: green;"),this.userOptions$.value}getUserOptions$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getUserOptions$","color: green;"),this.userOptions$.asObservable()}updateUser(e){this.loggingService.log("%c[WB] Calling FUNCTION: updateUser","color: green;");try{let i=this.user$.value;if(e.userId&&e.userId!==i?.userId||e?.groupId&&e?.groupId!==i?.groupId||e?.organizationId&&e?.organizationId!==i?.organizationId)this.providedUser=e,this.initializeClient(e,this.userOptions$?.value||{},new Date().getTime(),void 0,"internal-updateUser");else if(this.providedUser=I(I({},this.providedUser),e),i){let r=I(I({},i),e);this.updateUserInternally(r)}}catch(i){this.loggingService.catch("Error in updateUser: ",i)}}signInWithCustomToken(e,i,r="manual"){this.loggingService.log("%c[WB] Calling FUNCTION: signInWithCustomToken","color: green;");try{return gQ(this.afAuth,i).then(a=>(this.analyticsService.trackEvent(Z.Events.Core.SDK_USER_AUTH_SUCCESS,{apiKey:this.apiKey,clientUserId:e.userId,snippylyUserId:e.userSnippylyId,authType:r,forceReset:this.userOptions$.value?.forceReset,user:this.getUserWithoutContacts(e)}),a)).catch(a=>(this.analyticsService.trackEvent(Z.Events.Core.SDK_USER_AUTH_FAILED,{apiKey:this.apiKey,clientUserId:e.userId,snippylyUserId:e.userSnippylyId,authType:r,forceReset:this.userOptions$.value?.forceReset,message:a.message,user:this.getUserWithoutContacts(e)}),a))}catch(a){return this.loggingService.catch("Error in signInWithCustomToken: ",a),Promise.reject(a)}}resetServicesCache(){this.loggingService.log("%c[WB] Calling FUNCTION: resetServicesCache in AuthService","color: green;");try{this.commonDbService?.unsubscribeFromObservables(),this.docService?.clearCache(),this.contactService?.clearCache(),this.iamService?.clearCache(),this.areaService?.clearCache(),this.commentService?.clearCache(),this.reactionService?.clearCache(),this.recorderAnnotationService?.clearCache(),this.viewsService?.clearCache()}catch(e){this.loggingService.catch("Error in resetServicesCache: ",e)}}initializeSignedInUser(e,i){this.loggingService.log("%c[WB] Calling FUNCTION: initializeSignedInUser","color: green;");try{let r=new wo;r.userSnippylyId=e.uid,r.type="signedIn",this.mergeUserWithProvidedUserData(r,i)}catch(r){this.loggingService.catch("Error in initializeSignedInUser: ",r)}}mergeUserWithProvidedUserData(e,i){return ee(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: mergeUserWithProvidedUserData","color: green;");try{e.userId=this.providedUser?.userId||e.userId;let r=null;if(this.usersService?.userDataProviderAvailable()){let a=yield this.usersService.resolveUsers([e.userId]);a&&a[e.userId]&&(r=JSON.parse(JSON.stringify(a[e.userId]||{}))),e=I(I({},e),r||{})}e.name=r?r?.name:this.providedUser?.name||e.name,e.clientUserName=r?r?.clientUserName:this.providedUser?.clientUserName||e.clientUserName,e.photoUrl=r?r?.photoUrl:this.providedUser?.photoUrl||e.photoUrl,e?.photoUrl===void 0&&(e.photoUrl=null),e.email=r?r?.email:this.providedUser?.email||e.email,e.color=r?r?.color:this.providedUser?.color||this.avatarService.generateUserColor(fn(e.userId)),e.textColor=r?r?.textColor:this.providedUser?.textColor||"#FFFFFF",e.initial=r?r?.initial:this.providedUser?.initial||e.initial||e.name?.charAt(0).toUpperCase()||e.email?.charAt(0).toUpperCase(),e.contacts=this.providedUser?.contacts||e.contacts,e.plan=this.providedUser?.plan||e.plan,e.groupId=this.providedUser?.groupId||e.groupId,e.clientGroupId=this.providedUser?.clientGroupId||e.clientGroupId,e.clientOrganizationId=this.providedUser?.clientOrganizationId||e.clientOrganizationId,e.organizationId=this.providedUser?.organizationId||e.organizationId,e.isAdmin=this.providedUser?.isAdmin,e.isReadOnly=this.providedUser?.isReadOnly,e.isAnonymous=this.providedUser?.isAnonymous,e.isGuest=this.providedUser?.isGuest,this.updateUserInternally(e)}catch(r){this.loggingService.catch("Error in mergeUserWithProvidedUserData: ",r)}})}updateUserInternally(e){return ee(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: updateUserInternally","color: green;");try{let i=Object.assign({},e);delete i.contacts,this.analyticsService.identifyUser(e.userSnippylyId,i,{forceReset:this.userOptions$.value?.forceReset}),this.getPlanDetailsCalled||(yield this.getPlanDetailsFromDb()),this.afAuth.currentUser&&(this.user$.next(e),this.updateUserToFirebase(e))}catch(i){this.loggingService.catch("Error in updateUserInternally: ",i)}})}updateUserToFirebase(e){this.loggingService.log("%c[WB] Calling FUNCTION: updateUserToFirebase","color: green;");try{let i=JSON.parse(JSON.stringify(e)),r=T(I({},i),{lastUpdated:new Date})}catch(i){this.loggingService.catch("Error in updateUserToFirebase: ",i)}}getPlanDetailsFromDb(){return ee(this,null,function*(){try{this.getPlanDetailsCalled=!0;let i=yield Cr(this.functions,Zn.cloudFunction.getPlanDetails,{timeout:20*60*1e3})({apiKey:this.configService.getApiKey(),sdkVersion:Ta(),sdkType:this.configService.getSdkType()});return i?.data?.isPlanExpired&&(this.analyticsService.trackEvent(Z.Events.Core.SDK_PLAN_EXPIRED),this.configService.getSF()||console.warn("Velt SDK plan has expired.")),this.planDetails$.next(i?.data||{planInfo:null,isPlanExpired:!1}),i}catch(e){return this.loggingService.catch("Error in getPlanDetailsFromDb: ",e),this.planDetails$.next({planInfo:null,isPlanExpired:!1}),Promise.resolve(null)}})}isPlanExpired$(){return this.planDetails$.pipe(Ne(e=>!!e),ce(e=>!!e?.isPlanExpired))}isPlanExpired(){return this.planDetails$.getValue()?.isPlanExpired}addPreSignOutFuction(e,i){try{this.preSignOutFunctions.set(e,i)}catch(r){this.loggingService.catch("Error in addPreSignOutFuction: ",r)}}setUserOrganization(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setUserOrganization","color: green;");let i=JSON.parse(JSON.stringify(this.userOrganization$.value||{}));this.getUser()?.organizationId===e?.organizationId?(i.metadata=e,this.userOrganization$.next(i)):this.userOrganization$.next(null)}catch(i){this.loggingService.catch("Error in setUserOrganization: ",i)}}setOrganizationUserGroups(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setUserOrganizationGroups","color: green;");let i=JSON.parse(JSON.stringify(this.userOrganization$.value||{}));this.getUser()?.organizationId===i?.metadata?.organizationId&&(i.groups=e,this.userOrganization$.next(i))}catch(i){this.loggingService.catch("Error in setUserOrganizationGroups: ",i)}}getUserOrganization$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getUserOrganization$","color: green;"),this.getUser$().pipe(ge(e=>e?this.userOrganization$.asObservable().pipe(ce(i=>i?.metadata?.organizationId===e.organizationId?i:null)):re(null)))}signOutUser(e="internal"){return ee(this,null,function*(){try{yield this.analyticsService.trackEvent(Z.Events.Core.SDK_USER_SIGN_OUT,{apiKey:this.apiKey,clientUserId:this.user$?.value?.userId,snippylyUserId:this.user$?.value?.userSnippylyId,message:e==="external"?"User Sign out":"System Sign out",user:this.user$?.value?this.getUserWithoutContacts(this.user$?.value):null,forceReset:this.userOptions$.value?.forceReset,source:e});let i=yield Wn(this.afAuth).pipe(Je(1)).toPromise().catch(r=>null);if(i){this.user$.next(null);for(let[r,a]of this.preSignOutFunctions)try{yield a(i)}catch(s){this.loggingService.catch(`Error in signOutUser ${r} function: `,s)}return this.resetServicesCache(),this.user$.next(null),uQ(this.afAuth).catch(r=>{this.loggingService.catch("Error in signOutUser:",r)})}else return Promise.resolve()}catch(i){this.loggingService.catch("Error in signOutUser: ",i)}})}isFeatureAllowed(e){return Xi(this.config,this.user$.value,e)}getUserWithoutContacts(e){try{if(e){let i=JSON.parse(JSON.stringify(e));return delete i.contacts,i}else return null}catch(i){return this.loggingService.catch("Error in getUserWithoutContacts: ",i),null}}getUserForClient(e){try{return aS(e)}catch(i){return this.loggingService.catch("Error in getUserForClient: ",i),null}}};o.\u0275fac=function(i){return new(i||o)(J(vi),J($t),J(gm),J(Np),J(Fe),J(Vo),J(Qe),J(y))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var xd=class{constructor({apiKey:o,documentId:t,organizationId:e,clientDocumentId:i,clientOrganizationId:r}){this.paths={},this.apiKey=o,this.documentId=t,this.organizationId=e,this.clientDocumentId=i,this.clientOrganizationId=r,i&&(this.documentId=ud(i)),r&&(this.organizationId=hd(r)),this.generateDocumentPaths()}generateDocumentPaths(){try{if(this.paths.clientDocumentId=this.clientDocumentId,this.paths.documentId=this.documentId,this.organizationId&&(this.paths.organizationId=this.organizationId,this.paths.clientOrganizationId=this.clientOrganizationId),this.apiKey){let o=`${this.apiKey}`;this.organizationId&&(o=`${o}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${this.paths.organizationId}`),this.documentId&&(this.paths.docs=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/`,this.paths.presence=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_PRESENCE}/`,this.paths.cursor=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_CURSOR}/`,this.paths.comment=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_COMMENT}/`,this.paths.multiThread=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_MULTI_THREAD}/`,this.paths.tag=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_TAG}/`,this.paths.area=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_AREA}/`,this.paths.arrow=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_ARROW}/`,this.paths.selection=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_SELECTION}/`,this.paths.audioHuddle=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_AUDIO_HUDDLE}/`,this.paths.huddle=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_HUDDLE}/`,this.paths.recorder=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_RECORDER}/`,this.paths.flock=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_FOLLOW_ALONG}/`,this.paths.syncVideoPlayer=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_SYNC_VIDEO_PLAYER}/`,this.paths.liveState=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_LIVE_STATE}/`,this.paths.liveStateSingleEditorMode=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_LIVE_STATE}/default/singleEditorMode`,this.paths.reaction=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_REACTION}/`,this.paths.views=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_VIEWS}/`,this.paths.notifications=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_NOTIFICATIONS}/`,this.paths.metadata=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_METADATA}/`,this.paths.users=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_USERS}/`,this.paths.documentIam=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_IAM}/`),this.paths.customerMetadata=`${o}/${U.FIREBASE_PARTIAL_PATH_CUSTOMER_METADATA}/`,this.paths.groupContacts=`${o}/${U.FIREBASE_PARTIAL_PATH_CONTACTS}/${U.FIREBASE_PARTIAL_PATH_GROUPS}/`,this.paths.globalContacts=`${o}/${U.FIREBASE_PARTIAL_PATH_CONTACTS}/${U.FIREBASE_PARTIAL_PATH_GLOBAL}/`,this.paths.logins=`${o}/${U.FIREBASE_PARTIAL_PATH_CONTACTS}/${U.FIREBASE_PARTIAL_PATH_LOGINS}/`,this.paths.userFeedback=`${o}/${U.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${U.FIREBASE_PARTIAL_PATH_FEEDBACK}/`,this.paths.userReportBugs=`${o}/${U.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${U.FIREBASE_PARTIAL_PATH_BUGS}/`,this.paths.userContactUs=`${o}/${U.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${U.FIREBASE_PARTIAL_PATH_CONTACT_US}/`,this.organizationId&&(this.paths.organizationMetadata=`${o}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_METADATA}/`,this.paths.organizationIam=`${o}/${U.FIREBASE_PARTIAL_PATH_IAM}/`,this.paths.organizationGroups=`${o}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_GROUPS}/`,this.paths.organizationNotifications=`${o}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/`,this.documentId&&(this.paths.organizationNotificationsWithDocumentId=`${o}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/`),this.paths.organizationNotificationsLastNotificationTimestamp=`${o}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${U.FIREBASE_PARTIAL_PATH_LAST_NOTIFICATION_TIMESTAMP}/${U.FIREBASE_PARTIAL_PATH_DOCS}/`,this.paths.organizationNotificationsUsers=`${o}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${U.FIREBASE_PARTIAL_PATH_USERS}/`),this.paths.workspaceIam=`${this.apiKey}/${U.FIREBASE_PARTIAL_PATH_IAM}/`}}catch{}}get workspaceIam(){return this.paths.workspaceIam?this.paths.workspaceIam:this.throwError("Workspace IAM path is not available.")}get docs(){return this.paths.docs?this.paths.docs:this.throwError("Docs path is not available.")}get presence(){return this.paths.presence?this.paths.presence:this.throwError("Presence path is not available.")}get cursor(){return this.paths.cursor?this.paths.cursor:this.throwError("Cursor path is not available.")}get area(){return this.paths.area?this.paths.area:this.throwError("Area path is not available.")}get arrow(){return this.paths.arrow?this.paths.arrow:this.throwError("Arrow path is not available.")}get comment(){return this.paths.comment?this.paths.comment:this.throwError("Comment path is not available.")}get multiThread(){return this.paths.multiThread?this.paths.multiThread:this.throwError("Multi thread path is not available.")}get tag(){return this.paths.tag?this.paths.tag:this.throwError("Tag path is not available.")}get selection(){return this.paths.selection?this.paths.selection:this.throwError("Selection path is not available.")}get audioHuddle(){return this.paths.audioHuddle?this.paths.audioHuddle:this.throwError("Audio huddle path is not available.")}get huddle(){return this.paths.huddle?this.paths.huddle:this.throwError("Huddle path is not available.")}get recorder(){return this.paths.recorder?this.paths.recorder:this.throwError("Recorder path is not available.")}get flock(){return this.paths.flock?this.paths.flock:this.throwError("Flock path is not available.")}get syncVideoPlayer(){return this.paths.syncVideoPlayer?this.paths.syncVideoPlayer:this.throwError("Sync video player path is not available.")}get liveState(){return this.paths.liveState?this.paths.liveState:this.throwError("Live state path is not available.")}get liveStateSingleEditorMode(){return this.paths.liveStateSingleEditorMode?this.paths.liveStateSingleEditorMode:this.throwError("Live state single editor mode path is not available.")}get reaction(){return this.paths.reaction?this.paths.reaction:this.throwError("Reaction path is not available.")}get views(){return this.paths.views?this.paths.views:this.throwError("Views path is not available.")}get notifications(){return this.paths.notifications?this.paths.notifications:this.throwError("Notifications path is not available.")}get metadata(){return this.paths.metadata?this.paths.metadata:this.throwError("Metadata path is not available.")}get users(){return this.paths.users?this.paths.users:this.throwError("Users path is not available.")}get documentIam(){return this.paths.documentIam?this.paths.documentIam:this.throwError("Document IAM path is not available.")}get organizationMetadata(){return this.paths.organizationMetadata?this.paths.organizationMetadata:this.throwError("Organization metadata path is not available.")}get organizationIam(){return this.paths.organizationIam?this.paths.organizationIam:this.throwError("Organization IAM path is not available.")}get customerMetadata(){return this.paths.customerMetadata?this.paths.customerMetadata:this.throwError("Customer metadata path is not available.")}get groupContacts(){return this.paths.groupContacts?this.paths.groupContacts:this.throwError("Group contacts path is not available.")}get globalContacts(){return this.paths.globalContacts?this.paths.globalContacts:this.throwError("Global contacts path is not available.")}get logins(){return this.paths.logins?this.paths.logins:this.throwError("Logins path is not available.")}get userFeedback(){return this.paths.userFeedback?this.paths.userFeedback:this.throwError("User feedback path is not available.")}get userReportBugs(){return this.paths.userReportBugs?this.paths.userReportBugs:this.throwError("User report bugs path is not available.")}get userContactUs(){return this.paths.userContactUs?this.paths.userContactUs:this.throwError("User contact us path is not available.")}get organizationGroups(){return this.paths.organizationGroups?this.paths.organizationGroups:this.throwError("Organization groups path is not available.")}get organizationNotifications(){return this.paths.organizationNotifications?this.paths.organizationNotifications:this.throwError("Organization notifications path is not available.")}get organizationNotificationsWithDocumentId(){return this.paths.organizationNotificationsWithDocumentId?this.paths.organizationNotificationsWithDocumentId:this.throwError("Organization notifications with document id path is not available.")}get organizationNotificationsUsers(){return this.paths.organizationNotificationsUsers?this.paths.organizationNotificationsUsers:this.throwError("Organization notifications users path is not available.")}get organizationNotificationsLastNotificationTimestamp(){return this.paths.organizationNotificationsLastNotificationTimestamp?this.paths.organizationNotificationsLastNotificationTimestamp:this.throwError("Organization notifications last notification timestamp path is not available.")}throwError(o){throw{type:"DocumentPaths",message:o,metadata:{apiKey:this.apiKey,documentId:this.documentId,organizationId:this.organizationId}}}};var bM=class{constructor({apiKey:o,documentId:t,organizationId:e,clientDocumentId:i,clientOrganizationId:r,folderId:a,veltFolderId:s}){this.paths={},this.apiKey=o,this.documentId=t,this.organizationId=e,this.veltFolderId=s,i&&(this.documentId=ud(i)),r&&(this.organizationId=hd(r)),a&&(this.folderId=a,this.veltFolderId=hl(a)),this.generateDocumentPaths()}generateDocumentPaths(){try{if(this.paths.clientDocumentId=this.clientDocumentId,this.paths.documentId=this.documentId,this.organizationId&&(this.paths.organizationId=this.organizationId,this.paths.clientOrganizationId=this.clientOrganizationId),this.veltFolderId&&(this.paths.folderId=this.folderId,this.paths.veltFolderId=this.veltFolderId),this.apiKey){let o=`apiKey/${this.apiKey}`;this.organizationId&&(o=`${o}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${this.paths.organizationId}`,this.paths.organization=o,this.paths.folder=`${o}/${U.FIREBASE_PARTIAL_PATH_FOLDERS}`,this.paths.organizationUsers=`${o}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_USERS}`,this.paths.notificationDocs=`${o}/${U.FIREBASE_PARTIAL_PATH_NOTIFICATION_DOCS}`,this.paths.notificationUsers=`${o}/${U.FIREBASE_PARTIAL_PATH_NOTIFICATION_USERS}`,this.paths.organizationGroups=`${o}/${U.FIREBASE_PARTIAL_PATH_GROUPS}`,this.paths.lastNotificationTimestamp=`${o}/${U.FIREBASE_PARTIAL_PATH_LAST_NOTIFICATION_TIMESTAMP}`),this.veltFolderId&&(this.paths.folderUsers=`${o}/${U.FIREBASE_PARTIAL_PATH_FOLDERS}/${this.veltFolderId}/${U.FIREBASE_PARTIAL_PATH_FOLDER_USERS}`),this.documentId&&(this.paths.document=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}`,this.paths.comment=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_COMMENT}`,this.paths.location=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_LOCATION}`,this.paths.multiThread=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_MULTI_THREAD}`,this.paths.area=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_AREA}`,this.paths.recorder=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_RECORDER}`,this.paths.reaction=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_REACTION}`,this.paths.commentViews=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_COMMENT_VIEWS}`,this.paths.notificationViews=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_NOTIFICATION_VIEWS}`,this.paths.documentViews=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_DOCUMENT_VIEWS}`,this.paths.locationViews=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_LOCATION_VIEWS}`,this.paths.documentUsers=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_DOCUMENT_USERS}`,this.paths.docNotification=`${this.paths.notificationDocs}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_DOC_NOTIFICATION}`)}}catch{}}get folder(){return this.paths.folder?this.paths.folder:this.throwError("Folder path is not available.")}get lastNotificationTimestamp(){return this.paths.lastNotificationTimestamp?this.paths.lastNotificationTimestamp:this.throwError("LastNotificationTimestamp path is not available.")}get organizationGroups(){return this.paths.organizationGroups?this.paths.organizationGroups:this.throwError("organizationGroups path is not available.")}get docNotification(){return this.paths.docNotification?this.paths.docNotification:this.throwError("DocNotification path is not available.")}get organization(){return this.paths.organization?this.paths.organization:this.throwError("Organization path is not available.")}get document(){return this.paths.document?this.paths.document:this.throwError("Document path is not available.")}get location(){return this.paths.location?this.paths.location:this.throwError("Location path is not available.")}get area(){return this.paths.area?this.paths.area:this.throwError("Area path is not available.")}get comment(){return this.paths.comment?this.paths.comment:this.throwError("Comment path is not available.")}get commentViews(){return this.paths.commentViews?this.paths.commentViews:this.throwError("CommentViews path is not available.")}get documentViews(){return this.paths.documentViews?this.paths.documentViews:this.throwError("DocumentViews path is not available.")}get locationViews(){return this.paths.locationViews?this.paths.locationViews:this.throwError("LocationViews path is not available.")}get notificationViews(){return this.paths.notificationViews?this.paths.notificationViews:this.throwError("NotificationViews path is not available.")}get documentUsers(){return this.paths.documentUsers?this.paths.documentUsers:this.throwError("DocumentUsers path is not available.")}get folderUsers(){return this.paths.folderUsers?this.paths.folderUsers:this.throwError("FolderUsers path is not available.")}get organizationUsers(){return this.paths.organizationUsers?this.paths.organizationUsers:this.throwError("OrganizationUsers path is not available.")}get notificationDocs(){return this.paths.notificationDocs?this.paths.notificationDocs:this.throwError("NotificationDocs path is not available.")}get notificationUsers(){return this.paths.notificationUsers?this.paths.notificationUsers:this.throwError("NotificationUsers path is not available.")}get multiThread(){return this.paths.multiThread?this.paths.multiThread:this.throwError("Multi thread path is not available.")}get recorder(){return this.paths.recorder?this.paths.recorder:this.throwError("Recorder path is not available.")}get reaction(){return this.paths.reaction?this.paths.reaction:this.throwError("Reaction path is not available.")}throwError(o){throw{type:"DocumentPaths",message:o,metadata:{apiKey:this.apiKey,documentId:this.documentId,organizationId:this.organizationId}}}};var IM=class{};var pn=(()=>{let o=class o{constructor(e,i){this.authService=e,this.loggingService=i,this.db$=new fe(null);try{this.authService.getFirebaseConfig$().subscribe(r=>{r&&this.db$.next(Df(void 0,r.firebaseOptions.databaseURL))},r=>{this.loggingService.catch("Error in DatabaseService constructor: ",r)})}catch(r){this.loggingService.catch("Error in DatabaseService constructor:",r)}}getDb(){return this.db$.asObservable()}};o.\u0275fac=function(i){return new(i||o)(J(je),J(y))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var vs=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.analyticsService=i,this.resolveTimeout=1*60*1e3,this.retrySaveConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.retryDeleteConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.retryGetConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.commentAnnotationDataProvider$=new fe(null),this.commentAnnotationById$=new fe({}),this.getCommentAnnotationById=r=>{try{return this.commentAnnotationDataProviderAvailable()?this.commentAnnotationById$.value?.[r]:void 0}catch(a){this.loggingService.catch("Error in CommentAnnotationsResolverService getCommentAnnotationById:",a);return}};try{this.loggingService.log("CommentAnnotationsResolverService initialized"),this.commentAnnotationDataProvider$.subscribe(r=>{r&&(r.config?.resolveTimeout&&(this.resolveTimeout=r.config.resolveTimeout),r.config?.saveRetryConfig&&(this.retrySaveConfig=r.config.saveRetryConfig),r.config?.deleteRetryConfig&&(this.retryDeleteConfig=r.config.deleteRetryConfig),r.config?.getRetryConfig&&(this.retryGetConfig=r.config.getRetryConfig))})}catch(r){this.loggingService.catch("Error in CommentAnnotationsResolverService constructor:",r)}}getProvider(){try{let e=this.commentAnnotationDataProvider$.getValue();return e||void 0}catch(e){this.loggingService.catch("Error in CommentAnnotationsResolverService getProvider:",e);return}}ngOnDestroy(){try{this.commentAnnotationById$.next({})}catch(e){this.loggingService.catch("Error in CommentAnnotationsResolverService ngOnDestroy:",e)}}resolveCommentAnnotations(e){return ee(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling CommentAnnotationsResolverService FUNCTION: resolveCommentAnnotations","color: green;"),!this.commentAnnotationDataProviderAvailable())return{};let i,r=!1,a=!1,s=()=>{i&&(clearTimeout(i),i=void 0,a=!0)};return new Promise((c,p)=>{i=setTimeout(()=>{a||(r=!0,s(),p(new Error("Comment annotation resolution timeout")))},this.commentAnnotationDataProvider$.value?.config?.resolveTimeout||this.resolveTimeout);let h=this.getProvider();if(!h)return s(),c({});let _={},E=[...new Set(e.commentAnnotationIds||[])],D=T(I({},e),{commentAnnotationIds:E});ee(this,null,function*(){try{if(E.length>0||e.documentIds?.length||e.folderId){let G=sc(()=>h?.get(D)||Promise.resolve(void 0),"getCommentAnnotations",this.retryGetConfig).then(X=>r?{}:(s(),X&&X.statusCode!==200?(this.loggingService.catch(X?.message??"Error in CommentAnnotationsResolverService resolveCommentAnnotations:"),{}):X?.data)).catch(X=>{throw s(),X});try{_=(yield G)||{},this.analyticsService.trackEvent(Z.Events.Resolver.COMMENT_RESOLVER_GET,{sourceMethod:"resolveCommentAnnotations",source:"sdk",commentAnnotationIds:E});let X={};Object.entries(_).forEach(([he,Ie])=>{let Me=this.commentAnnotationById$.value?.[he];Me?Me&&JSON.stringify(Me)!==JSON.stringify(Ie)&&(X[he]=Ie):X[he]=Ie}),Object.keys(X).length>0&&this.commentAnnotationById$.next(I(I({},this.commentAnnotationById$.getValue()),X)),c(X)}catch(X){r||p(X),c(_)}}else s(),c({})}catch(G){s(),p(G)}})})}catch(i){return this.loggingService.catch("Error in CommentAnnotationsResolverService resolveCommentAnnotations:",i),{}}})}saveCommentAnnotation(e){return ee(this,null,function*(){try{this.loggingService.log("%c[WB] Calling CommentAnnotationsResolverService FUNCTION: saveCommentAnnotation","color: green;");let i=this.getProvider();if(!this.commentAnnotationDataProviderAvailable())throw new Error("Comment annotation save data provider not available");let r=JSON.parse(JSON.stringify(this.commentAnnotationById$.getValue()));this.commentAnnotationById$._value=I(I({},r),e.commentAnnotation);let a=yield sc(()=>i?.save({commentAnnotation:e.commentAnnotation,event:e.eventType,commentId:e.commentId,metadata:Object.values(e.commentAnnotation??{})?.[0]?.metadata})||Promise.resolve(void 0),"saveCommentAnnotation",this.retrySaveConfig);return a&&a.statusCode!==200?(this.retrySaveConfig.revertOnFailure&&(this.commentAnnotationById$._value=r),this.loggingService.catch(a?.message??"Error in CommentAnnotationsResolverService saveCommentAnnotation:"),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(Z.Events.Resolver.COMMENT_RESOLVER_SAVE,{sourceMethod:"saveCommentAnnotation",source:"sdk",commentAnnotationIds:Object.keys(e.commentAnnotation),eventType:e.eventType,commentId:e.commentId}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0})}catch(i){return this.loggingService.warn("Error in CommentAnnotationsResolverService saveCommentAnnotation:",i),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0}}})}deleteCommentAnnotation(e,i){return ee(this,null,function*(){try{this.loggingService.log("%c[WB] Calling CommentAnnotationsResolverService FUNCTION: deleteCommentAnnotation","color: green;");let r=this.getProvider();if(!this.commentAnnotationDataProviderAvailable())throw new Error("Comment annotation delete data provider not available");let a=this.commentAnnotationById$.getValue(),s=I({},a);delete s?.[e],this.commentAnnotationById$._value=s;let c=yield sc(()=>r?.delete({commentAnnotationId:e.toString(),metadata:i,event:Ha.COMMENT_ANNOTATION_DELETE})||Promise.resolve(void 0),"deleteCommentAnnotation",this.retryDeleteConfig);return c&&c.statusCode!==200?(this.retryDeleteConfig.revertOnFailure&&(this.commentAnnotationById$._value=a),this.loggingService.catch(c?.message??"Error in CommentAnnotationsResolverService deleteCommentAnnotation:"),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(Z.Events.Resolver.COMMENT_RESOLVER_DELETE,{sourceMethod:"deleteCommentAnnotation",source:"sdk",commentAnnotationId:e.toString()}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0})}catch(r){return this.loggingService.warn("Error in CommentAnnotationsResolverService deleteCommentAnnotation:",r),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0}}})}getCommentAnnotationsById$(){try{return this.commentAnnotationDataProviderAvailable()?(this.loggingService.log("%c[WB] Calling CommentAnnotationsResolverService FUNCTION: getCommentAnnotationsById$","color: green;"),this.commentAnnotationById$.asObservable()):re(void 0)}catch(e){return this.loggingService.catch("Error in CommentAnnotationsResolverService getCommentAnnotationsById$:",e),re(void 0)}}getAnnotationById(e){try{return this.commentAnnotationDataProviderAvailable()?this.commentAnnotationById$.getValue()?.[e]:void 0}catch(i){this.loggingService.catch("Error in CommentAnnotationsResolverService getAnnotationById:",i);return}}setCommentAnnotationDataProvider(e){try{if(e){this.loggingService.log("Setting comment annotation data provider");let r=["get","save","delete"].filter(a=>!(a in e)||typeof e[a]!="function");if(r.length>0){let a=`DataProviders.comment is invalid. The following methods are missing or are not functions: ${r.join(", ")}.`;this.loggingService.catch(a);return}else this.commentAnnotationDataProvider$.next(e)}}catch(i){this.loggingService.catch("Error in CommentAnnotationsResolverService setCommentAnnotationDataProvider:",i)}}commentAnnotationDataProviderAvailable(){try{return!!this.commentAnnotationDataProvider$.getValue()}catch(e){return this.loggingService.catch("Error in CommentAnnotationsResolverService commentAnnotationDataProviderAvailable:",e),!1}}};o.\u0275fac=function(i){return new(i||o)(J(y),J(Qe))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var um=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.analyticsService=i,this.resolveTimeout=1*60*1e3,this.retrySaveConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.retryDeleteConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.retryGetConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.reactionAnnotationDataProvider$=new fe(null),this.reactionAnnotationById$=new fe({}),this.getReactionAnnotationById=r=>{try{return this.reactionAnnotationDataProviderAvailable()?this.reactionAnnotationById$.value?.[r]:void 0}catch(a){this.loggingService.catch("Error in ReactionAnnotationsResolverService getReactionAnnotationById:",a);return}};try{this.loggingService.log("ReactionAnnotationsResolverService initialized"),this.reactionAnnotationDataProvider$.subscribe(r=>{r&&(r.config?.resolveTimeout&&(this.resolveTimeout=r.config.resolveTimeout),r.config?.saveRetryConfig&&(this.retrySaveConfig=r.config.saveRetryConfig),r.config?.deleteRetryConfig&&(this.retryDeleteConfig=r.config.deleteRetryConfig),r.config?.getRetryConfig&&(this.retryGetConfig=r.config.getRetryConfig))})}catch(r){this.loggingService.catch("Error in ReactionAnnotationsResolverService constructor:",r)}}getProvider(){try{let e=this.reactionAnnotationDataProvider$.getValue();return e||void 0}catch(e){this.loggingService.catch("Error in ReactionAnnotationsResolverService getProvider:",e);return}}ngOnDestroy(){try{this.reactionAnnotationById$.next({})}catch(e){this.loggingService.catch("Error in ReactionAnnotationsResolverService ngOnDestroy:",e)}}resolveReactionAnnotations(e){return ee(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling ReactionAnnotationsResolverService FUNCTION: resolveReactionAnnotations","color: green;"),!this.reactionAnnotationDataProviderAvailable())return{};let i,r=!1,a=!1,s=()=>{i&&(clearTimeout(i),i=void 0,a=!0)};return new Promise((c,p)=>{i=setTimeout(()=>{a||(r=!0,s(),p(new Error("Reaction annotation resolution timeout")))},this.reactionAnnotationDataProvider$.value?.config?.resolveTimeout||this.resolveTimeout);let h=this.getProvider();if(!h)return s(),c({});let _={},E=[...new Set(e.reactionAnnotationIds||[])],D=T(I({},e),{reactionAnnotationIds:E});ee(this,null,function*(){try{if(E.length>0||e.documentIds?.length||e.folderId){let G=sc(()=>h?.get(D)||Promise.resolve(void 0),"getReactionAnnotations",this.retryGetConfig).then(X=>r?{}:(s(),X&&X.statusCode!==200?(this.loggingService.catch(X?.message??"Error in ReactionAnnotationsResolverService resolveReactionAnnotations:"),{}):X?.data)).catch(X=>{throw s(),X});try{_=(yield G)||{},this.analyticsService.trackEvent(Z.Events.Resolver.REACTION_RESOLVER_GET,{sourceMethod:"resolveReactionAnnotations",source:"sdk",reactionAnnotationIds:E});let X={};Object.entries(_).forEach(([he,Ie])=>{let Me=this.reactionAnnotationById$.value?.[he];Me?Me&&JSON.stringify(Me)!==JSON.stringify(Ie)&&(X[he]=Ie):X[he]=Ie}),Object.keys(X).length>0&&this.reactionAnnotationById$.next(I(I({},this.reactionAnnotationById$.getValue()),X)),c(X)}catch(X){r||p(X),c(_)}}else s(),c({})}catch(G){s(),p(G)}})})}catch(i){return this.loggingService.catch("Error in ReactionAnnotationsResolverService resolveReactionAnnotations:",i),{}}})}saveReactionAnnotation(e){return ee(this,null,function*(){try{this.loggingService.log("%c[WB] Calling ReactionAnnotationsResolverService FUNCTION: saveReactionAnnotation","color: green;");let i=this.getProvider();if(!this.reactionAnnotationDataProviderAvailable())throw new Error("Reaction annotation save data provider not available");let r=JSON.parse(JSON.stringify(this.reactionAnnotationById$.getValue()));this.reactionAnnotationById$._value=I(I({},r),e);let a={reactionAnnotation:e,event:Ha.REACTION_ADD,metadata:Object.values(e??{})?.[0]?.metadata},s=yield sc(()=>i?.save(a)||Promise.resolve(void 0),"saveReactionAnnotation",this.retrySaveConfig);return s&&s.statusCode!==200?(this.retrySaveConfig.revertOnFailure&&(this.reactionAnnotationById$._value=r),this.loggingService.catch(s?.message??"Error in ReactionAnnotationsResolverService saveReactionAnnotation:"),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(Z.Events.Resolver.REACTION_RESOLVER_SAVE,{sourceMethod:"saveReactionAnnotation",source:"sdk",reactionAnnotationIds:Object.keys(e),eventType:a.event}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0})}catch(i){return this.loggingService.warn("Error in ReactionAnnotationsResolverService saveReactionAnnotation:",i),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0}}})}deleteReactionAnnotation(e,i){return ee(this,null,function*(){try{this.loggingService.log("%c[WB] Calling ReactionAnnotationsResolverService FUNCTION: deleteReactionAnnotation","color: green;");let r=this.getProvider();if(!this.reactionAnnotationDataProviderAvailable())throw new Error("Reaction annotation delete data provider not available");let a=JSON.parse(JSON.stringify(this.reactionAnnotationById$.getValue())),s=I({},a);delete s?.[e],this.reactionAnnotationById$._value=s;let c=yield sc(()=>r?.delete({reactionAnnotationId:e.toString(),metadata:i,event:Ha.REACTION_DELETE})||Promise.resolve(void 0),"deleteReactionAnnotation",this.retryDeleteConfig);return c&&c.statusCode!==200?(this.retryDeleteConfig.revertOnFailure&&(this.reactionAnnotationById$._value=a),this.loggingService.catch(c?.message??"Error in ReactionAnnotationsResolverService deleteReactionAnnotation:"),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(Z.Events.Resolver.REACTION_RESOLVER_DELETE,{sourceMethod:"deleteReactionAnnotation",source:"sdk",reactionAnnotationId:e.toString()}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0})}catch(r){return this.loggingService.warn("Error in ReactionAnnotationsResolverService deleteReactionAnnotation:",r),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0}}})}getReactionAnnotationsById$(){try{return this.reactionAnnotationDataProviderAvailable()?(this.loggingService.log("%c[WB] Calling ReactionAnnotationsResolverService FUNCTION: getReactionAnnotationsById$","color: green;"),this.reactionAnnotationById$.asObservable()):re(void 0)}catch(e){return this.loggingService.catch("Error in ReactionAnnotationsResolverService getReactionAnnotationsById$:",e),re(void 0)}}getAnnotationById(e){try{return this.reactionAnnotationDataProviderAvailable()?this.reactionAnnotationById$.getValue()?.[e]:void 0}catch(i){this.loggingService.catch("Error in ReactionAnnotationsResolverService getAnnotationById:",i);return}}setReactionAnnotationDataProvider(e){try{if(e){this.loggingService.log("Setting reaction annotation data provider");let r=["get","save","delete"].filter(a=>!(a in e)||typeof e[a]!="function");if(r.length>0){let a=`DataProviders.reaction is invalid. The following methods are missing or are not functions: ${r.join(", ")}.`;this.loggingService.catch(a);return}else this.reactionAnnotationDataProvider$.next(e)}}catch(i){this.loggingService.catch("Error in ReactionAnnotationsResolverService setReactionAnnotationDataProvider:",i)}}reactionAnnotationDataProviderAvailable(){try{return!!this.reactionAnnotationDataProvider$.getValue()}catch(e){return this.loggingService.catch("Error in ReactionAnnotationsResolverService reactionAnnotationDataProviderAvailable:",e),!1}}};o.\u0275fac=function(i){return new(i||o)(J(y),J(Qe))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var lt=(()=>{let o=class o{constructor(e,i,r,a,s,c,p,h){this.analyticsService=e,this.authService=i,this.databaseService=r,this.domService=a,this.configService=s,this.loggingService=c,this.commentResolverService=p,this.reactionResolverService=h,this.documentPaths$=new fe(null),this.documentIds$=new fe([]),this.folderConfig$=new fe(null),this.organizationConfig$=new fe(null),this.firestorePaths$=new fe(null),this.location$=new fe(null),this.excludedLocationIds$=new fe([]),this.organizationMetadata$=new fe(null),this.documentMetadata$=new fe(null),this.locationMetadata$=new fe(null),this.customerMetadata$=new fe(null),this.currentDocumentId=null,this.isCustomDocId=!1,this.locations$=new fe({}),this.preDocumentIdChangeFunctions=new Map,this.draftDocumentId=null,this.clientDocumentMetadataMap={},this.uiState=new fe({}),this.lastSetDocumentIdExecutionTime=0,this.lastSetDocumentIdCallTime=0,this.setDocumentIdSubject=new et,this.DEBOUNCE_TIME=5e3,this.MAX_QUEUE_SIZE=100,this.queueSize=0,this.isDocumentIdInDebounceQueue=!1,this.draftLocationMap={location:null,locations:[]};try{this.loggingService.log("%c[WB] Creating CLASS: DocService","color: blue;"),this.domService.setDocService(this),this.authService.setDocService(this),this.setDocumentIdSubject.pipe(jr(this.DEBOUNCE_TIME)).subscribe({next:_=>{try{this.setDocumentIdImpl(_.documentId,_.clientOrganizationId,_.auto,_.avoidAnalytics,_.options),this.lastSetDocumentIdExecutionTime=Date.now(),this.isDocumentIdInDebounceQueue=!1,this.draftLocationMap.location&&this.setLocation(this.draftLocationMap.location),this.draftLocationMap.locations.length>0&&this.draftLocationMap.locations.forEach(E=>{this.addLocation(E)}),this.draftLocationMap={location:null,locations:[]}}finally{this.queueSize--}},error:_=>{this.loggingService.catch("Error in setDocumentId subscription:",_),this.queueSize--}}),this.databaseService.getDb().pipe(Ne(_=>!!_),Je(1)).subscribe(_=>{_&&(this.db=_)}),this.configService.getApiKey$().subscribe(_=>{if(this.apiKey=_,this.apiKey){if(!this.isCustomDocId){let E=qO(window.location.href);this.currentUrl=E}this.analyticsService.updateDefaultProperties({apiKey:_})}}),this.authService.getUser$().subscribe(_=>{_?(this.analyticsService.updateDefaultProperties({organizationId:_?.organizationId,clientOrganizationId:_?.clientOrganizationId}),this.draftDocumentId?(this.setDocumentId(this.draftDocumentId,this.draftOrganizationId,!1,!1,this.draftFolderConfig),this.draftDocumentId=null,this.draftLocationMap.location&&this.setLocation(this.draftLocationMap.location),this.draftLocationMap.locations.length>0&&this.draftLocationMap.locations.forEach(E=>{this.addLocation(E)}),this.draftLocationMap={location:null,locations:[]},this.draftOrganizationId=void 0,this.draftFolderConfig=void 0):this.documentPaths$?.value&&_?.organizationId&&this.documentPaths$.value?.organizationId!==_?.organizationId&&this.setDocumentId(this.documentPaths$.value?.clientDocumentId),this.updateDocumentLocationMetadata(),setTimeout(()=>{this.documentPaths$.value||this.loggingService.catch("Error in DocService constructor:","Please set document id to continue.")},1e4),_?.organizationId&&_?.clientOrganizationId&&this.organizationConfig$.next({organizationId:_?.organizationId,clientOrganizationId:_?.clientOrganizationId})):(this.organizationMetadataSubscription?.unsubscribe(),this.documentMetadataSubscription?.unsubscribe(),this.customerMetadataSubscription?.unsubscribe(),this.documentPaths$.value&&(this.draftDocumentId=this.documentPaths$.value?.clientDocumentId??null,this.draftFolderConfig=this.folderConfig$.value,this.draftLocationMap={location:this.location$.value?.location??null,locations:Object.values(this.locations$.value||{}).map(E=>E.location)},this.currentDocumentId=null,this.location$.next(null),this.documentPaths$.next(null),this.firestorePaths$.next(null)))}),this.documentPaths$.subscribe(_=>{let E={documentId:_?.documentId,clientDocumentId:_?.clientDocumentId};_?.organizationId&&(E.organizationId=_.organizationId,E.clientOrganizationId=_.clientOrganizationId),this.analyticsService.updateDefaultProperties(E),this.domService.resetSelectedAnnotationsMap()}),this.folderConfig$.subscribe(_=>{this.analyticsService.updateDefaultProperties({folderId:_?.folderId,veltFolderId:_?.veltFolderId,allDocuments:_?.allDocuments})}),this.location$.subscribe(_=>{this.analyticsService.updateDefaultProperties({clientLocation:_?.location,locationId:_?.locationId})}),this.organizationMetadata$.subscribe(_=>{this.authService.setUserOrganization(_?.[this.documentPaths$.value?.organizationId])}),this.organizationConfig$.subscribe(_=>{_&&this.updateOrganizationMetadata()}),this.documentPaths$.pipe(Ne(_=>!!_),Je(1)).subscribe(()=>{try{this.subscribeToCustomerMetadata()}catch(_){this.loggingService.catch("Error in DocService subscribeToCustomerMetadata:",_)}},_=>{this.loggingService.catch("Error in DocService subscribeToCustomerMetadata:",_)}),this.loggingService.log("%c[WB] Creating CLASS: DocService 2","color: blue;"),this.onWindowPopstate(),this.onWindowClick()}catch(_){this.loggingService.catch("Error in DocService constructor:",_)}}clearCache(){this.loggingService.log("%c[WB] Calling FUNCTION: clearCache in DocService","color: green;");try{this.folderConfig$.next(null),this.organizationConfig$.next(null),this.organizationMetadata$.next(null),this.documentMetadata$.next(null),this.locationMetadata$.next(null),this.customerMetadata$.next(null)}catch(e){this.loggingService.catch("Error in DocService clearCache: ",e)}}setCommonDbService(e){try{this.commonDbService=e}catch(i){this.loggingService.catch("Error in setCommonDbService:",i)}}setCommentService(e){try{this.commentService=e}catch(i){this.loggingService.catch("Error in setCommentService:",i)}}onWindowPopstate(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowPopstate","color: green;");try{this.domService.onWindowPopState$().subscribe(()=>{this.loggingService.log("location",location.href);let e=qO(location.href);this.currentUrl!==e&&(this.currentUrl=e,!this.isCustomDocId&&this.apiKey&&this.loggingService.log("current url in doc service",this.currentUrl))},e=>{this.loggingService.catch("Error in DocService onWindowPopstate subscription: ",e)})}catch(e){this.loggingService.catch("Error in onWindowPopstate: ",e)}}onWindowClick(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowClick","color: green;");try{this.domService.onWindowClick$().subscribe(()=>{let e=qO(location.href);this.currentUrl!==e&&(this.currentUrl=e,this.isCustomDocId||this.loggingService.log("current url in doc service",this.currentUrl))},e=>{this.loggingService.catch("Error in DocService onWindowClick subscription: ",e)})}catch(e){this.loggingService.catch("Error in onWindowClick: ",e)}}setDocument(e,i){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocument","color: green;"),this.documentIds$.value?.length&&this.documentIds$.next([]);let r=i?.organizationId;this.setDocumentId(e,r,!1,!0),i&&(i.organizationId&&delete i.organizationId,this.clientDocumentMetadata={clientDocumentId:e,documentMetadata:i},this.updateDocumentMetadata()),this.analyticsService.trackEvent(Z.Events.Doc.DOCUMENT_SET,{documentId:e,documentMetadata:i},!0,this.getUserIdForAnalytics())}catch(r){this.loggingService.catch("Error in DocService setDocument:",r)}}shouldSetDocumentsAgain(e,i={}){try{this.loggingService.log("%c[WB] Calling FUNCTION: shouldSetDocumentsAgain","color: green;");let r=this.documentIds$.value.map(c=>c.clientDocumentId),a=this.folderConfig$.value??{};return!e.every(c=>r.includes(c.id))||!Co(a,i)}catch(r){return this.loggingService.catch("Error in DocService shouldSetDocumentsAgain:",r),!0}}setDocuments(e,i){try{if(!this.shouldSetDocumentsAgain(e,i)){this.loggingService.warn("setDocuments called with previous request");return}let r=[];if(e.forEach(a=>{let s=a.id,c=`${fn(s)}`;a?.metadata&&typeof a.metadata=="object"&&(this.clientDocumentMetadataMap[s]=a.metadata),r.push({documentId:c,clientDocumentId:s})}),r?.length===0){this.loggingService.warn("Minimum one document must be set in setDocuments");return}this.documentIds$.next(r),e?.length&&this.setDocumentId(e[0]?.id,i?.organizationId,!1,!1,i),this.analyticsService.trackEvent(Z.Events.Doc.DOCUMENTS_SET,{documentIds:r,options:i},!0,this.getUserIdForAnalytics())}catch(r){this.loggingService.catch("Error in DocService setDocuments:",r)}}setDocumentId(e,i,r=!1,a=!1,s){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocumentId","color: green;"),this.folderConfig$.value&&this.folderConfig$.next(null);let c=Date.now(),p=c-this.lastSetDocumentIdCallTime,h=c-this.lastSetDocumentIdExecutionTime;if(this.lastSetDocumentIdCallTime=c,this.queueSize>=this.MAX_QUEUE_SIZE){this.loggingService.warn("SetDocumentId queue size exceeded limit");return}if(!this.documentPaths$.value&&!this.isDocumentIdInDebounceQueue||p>this.DEBOUNCE_TIME&&h>this.DEBOUNCE_TIME){this.setDocumentIdImpl(e,i,r,a,s),this.lastSetDocumentIdExecutionTime=c;return}this.documentPaths$.next(null),this.isDocumentIdInDebounceQueue=!0,this.draftLocationMap={location:null,locations:[]},this.queueSize++,this.setDocumentIdSubject.next({documentId:e,clientOrganizationId:i,auto:r,avoidAnalytics:a})}catch(c){this.loggingService.catch("Error in setDocumentId:",c)}}setDocumentIdImpl(e,i,r=!1,a=!1,s){this.loggingService.log("%c[WB] Calling FUNCTION: setDocumentIdImpl","color: green;");try{r||(this.isCustomDocId=!0);let c=this.authService.getUser();if(!c){this.draftDocumentId=e,this.draftOrganizationId=i,this.draftFolderConfig=s;return}(s?.folderId||s?.locationId)&&this.folderConfig$.next({folderId:s?.folderId,allDocuments:s?.allDocuments,locationId:s?.locationId,veltFolderId:s?.folderId?hl(s?.folderId):void 0}),this.currentDocumentId&&this.documentPaths$.value&&this.callPreDocumentIdChangeFunctions(this.documentPaths$.value);let p=this.currentDocumentId;if(this.apiKey){let h=`${fn(e)}`,_=c?.organizationId?i?Rt(i):c?.organizationId:void 0;if(this.commentResolverService.resolveCommentAnnotations({documentIds:this.documentIds$.value.map(E=>E.clientDocumentId),organizationId:i??c?.clientOrganizationId??""}),this.reactionResolverService.resolveReactionAnnotations({documentIds:this.documentIds$.value.map(E=>E.clientDocumentId),organizationId:i??c?.clientOrganizationId??""}),_&&this.documentPaths$.value?.organizationId&&_!==this.documentPaths$.value?.organizationId){let E=this.getFolderConfig();this.authService.resetServicesCache(),E&&this.folderConfig$.next(E)}if(this.currentDocumentId!==h||this.documentPaths$.value?.organizationId!==_){this.loggingService.log("setting new docid"),this.currentDocumentId=h;let E=new aM,D=new IM;E.clientDocumentId=e,D.clientDocumentId=e,E.documentId=h,D.documentId=h,_&&(E.organizationId=_,E.clientOrganizationId=i??c?.clientOrganizationId,D.organizationId=_,D.clientOrganizationId=i??c?.clientOrganizationId);let B=`${this.apiKey}`,G=`apiKey/${this.apiKey}`;_&&(B=`${B}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${E.organizationId}`,G=`${G}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${E.organizationId}`),D.organization=`apiKey/${this.apiKey}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}`,D.document=`${G}/${U.FIREBASE_PARTIAL_PATH_DOCS}`,E.presence=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_PRESENCE}/`,E.cursor=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_CURSOR}/`,E.comment=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_COMMENT}/`,D.comment=`${G}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_COMMENT}`,E.multiThread=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_MULTI_THREAD}/`,D.multiThread=`${G}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_MULTI_THREAD}`,E.tag=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_TAG}/`,E.area=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_AREA}/`,D.area=`${G}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_AREA}`,E.arrow=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_ARROW}/`,E.selection=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_SELECTION}/`,E.audioHuddle=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_AUDIO_HUDDLE}/`,E.huddle=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_HUDDLE}/`,E.recorder=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_RECORDER}/`,D.recorder=`${G}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_RECORDER}`,E.flock=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_FOLLOW_ALONG}/`,E.syncVideoPlayer=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_SYNC_VIDEO_PLAYER}/`,E.liveState=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_LIVE_STATE}/`,E.liveStateSingleEditorMode=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_LIVE_STATE}/default/singleEditorMode`,E.reaction=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_REACTION}/`,D.reaction=`${G}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_REACTION}`,E.customerMetadata=`${this.apiKey}/${U.FIREBASE_PARTIAL_PATH_CUSTOMER_METADATA}/`,E.views=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_VIEWS}/`,D.commentViews=`${G}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_COMMENT_VIEWS}`,D.notificationViews=`${G}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_NOTIFICATION_VIEWS}`,D.documentViews=`${G}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_DOCUMENT_VIEWS}`,D.locationViews=`${G}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_LOCATION_VIEWS}`,E.notifications=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_NOTIFICATIONS}/`,E.metadata=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_METADATA}/`,E.users=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_USERS}/`,E.documentIam=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_IAM}/`,E.workspaceIam=`${this.apiKey}/${U.FIREBASE_PARTIAL_PATH_IAM}/`,E.groupContacts=`${B}/${U.FIREBASE_PARTIAL_PATH_CONTACTS}/${U.FIREBASE_PARTIAL_PATH_GROUPS}/`,E.globalContacts=`${B}/${U.FIREBASE_PARTIAL_PATH_CONTACTS}/${U.FIREBASE_PARTIAL_PATH_GLOBAL}/`,E.logins=`${B}/${U.FIREBASE_PARTIAL_PATH_CONTACTS}/${U.FIREBASE_PARTIAL_PATH_LOGINS}/`,E.userFeedback=`${B}/${U.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${U.FIREBASE_PARTIAL_PATH_FEEDBACK}/`,E.userReportBugs=`${B}/${U.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${U.FIREBASE_PARTIAL_PATH_BUGS}/`,E.userContactUs=`${B}/${U.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${U.FIREBASE_PARTIAL_PATH_CONTACT_US}/`,_&&(E.organizationMetadata=`${B}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_METADATA}/`,E.organizationIam=`${B}/${U.FIREBASE_PARTIAL_PATH_IAM}/`,E.organizationGroups=`${B}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_GROUPS}/`,E.organizationNotifications=`${B}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/`,h&&(E.organizationNotificationsWithDocumentId=`${B}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/`),E.organizationNotificationsLastNotificationTimestamp=`${B}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${U.FIREBASE_PARTIAL_PATH_LAST_NOTIFICATION_TIMESTAMP}/${U.FIREBASE_PARTIAL_PATH_DOCS}/`,E.organizationNotificationsUsers=`${B}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${U.FIREBASE_PARTIAL_PATH_USERS}/`),D.organizationUsers=`${G}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_USERS}`,D.documentUsers=`${G}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_DOCUMENT_USERS}`,D.notificationDocs=`${G}/${U.FIREBASE_PARTIAL_PATH_NOTIFICATION_DOCS}`,D.notificationUsers=`${G}/${U.FIREBASE_PARTIAL_PATH_NOTIFICATION_USERS}`,this.documentPaths$.next(E),this.firestorePaths$.next(D),E?.clientOrganizationId&&E?.organizationId&&!(E?.clientOrganizationId===this.organizationConfig$?.value?.clientOrganizationId&&E?.organizationId===this.organizationConfig$?.value?.organizationId)&&this.organizationConfig$.next({organizationId:E?.organizationId,clientOrganizationId:E?.clientOrganizationId}),this.updateFolderMetadata(),this.updateDocumentMetadata(),this.getLocationMetadata(),p&&this.location$.value&&this.removeLocation(),a||this.analyticsService.trackEvent(Z.Events.Doc.DOCUMENT_ID_SET,{documentId:h,clientDocumentId:e},!0,this.getUserIdForAnalytics())}return h}else this.loggingService.catch("Error in setDocumentIdImpl: API key is not provided.")}catch(c){this.loggingService.catch("Error in setDocumentIdImpl: ",c)}}unsetDocumentId(e="internal"){this.loggingService.log("%c[WB] Calling FUNCTION: unsetDocumentId","color: green;");try{this.analyticsService.trackEvent(Z.Events.Doc.DOCUMENT_UNSET,{documentId:this.currentDocumentId,documentMetadata:this.documentMetadata$.value?.[this.currentDocumentId??""],message:e==="external"?"User unset document id":"System unset document id",source:e},!0,this.getUserIdForAnalytics()),this.currentDocumentId&&this.documentPaths$.value&&this.callPreDocumentIdChangeFunctions(this.documentPaths$.value),this.currentDocumentId=null,this.documentPaths$.next(null),this.firestorePaths$.next(null),this.location$.next(null),this.excludedLocationIds$.next([]),this.documentMetadata$.next(null),this.locationMetadata$.next(null),this.customerMetadata$.next(null),this.locations$.next({})}catch(i){this.loggingService.catch("Error in unsetDocumentId: ",i)}}unsetDocuments(e="internal"){this.loggingService.log("%c[WB] Calling FUNCTION: unsetDocuments","color: green;");try{this.unsetDocumentId(e),this.documentIds$.next([])}catch(i){this.loggingService.catch("Error in unsetDocuments: ",i)}}addPreDocumentIdChangeFunction(e,i){try{this.loggingService.log("%c[WB] Calling FUNCTION: addPreDocumentIdChangeFunction","color: green;"),this.preDocumentIdChangeFunctions.set(e,i)}catch(r){this.loggingService.catch("Error in addPreDocumentIdChangeFunction: ",r)}}callPreDocumentIdChangeFunctions(e){return ee(this,null,function*(){try{this.loggingService.log("%c[WB] Calling FUNCTION: callPreDocumentIdChangeFunctions","color: green;");for(let[i,r]of this.preDocumentIdChangeFunctions)try{yield r(e)}catch(a){this.loggingService.catch("Error in callPreDocumentIdChangeFunctions: ",a)}}catch(i){this.loggingService.catch("Error in callPreDocumentIdChangeFunctions: ",i)}})}subscribeToOrganizationMetadata(){this.loggingService.log("%c[WB] Calling FUNCTION: subscribeToOrganizationMetadata","color: green;");try{if(this.organizationMetadataSubscription&&this.organizationMetadataSubscription.unsubscribe(),this.db&&this.authService.getUser()?.organizationId){let e=this.organizationConfig$.value?.organizationId;this.commonDbService?.getData({feature:"organizationMetadata",properties:{apiKey:this.apiKey??"",organizationId:e,field:"metadata"}}).then(i=>{i&&this.organizationMetadata$.next(T(I({},this.organizationMetadata$.value),{[e]:i}))}).catch(i=>{this.loggingService.catch("Error in subscribeToOrganizationMetadata: ",i)})}}catch(e){this.loggingService.catch("Error in subscribeToOrganizationMetadata: ",e)}}subscribeToDocumentMetadata(e){try{if(this.documentMetadataSubscription&&this.documentMetadataSubscription.unsubscribe(),this.db&&this.authService.getUser()){let i=this.documentPaths$.value,r=this.documentMetadata$.value;if(e=e.filter(a=>!r?.[a.documentId]),e?.some(a=>!a?.documentId||!a?.clientDocumentId)||!i)return;if(this.commonDbService?.shouldUseFirestore()){let a=this.getFolderConfig()?.folderId,s=this.getFolderConfig()?.allDocuments,c=[],p={organizationId:i?.clientOrganizationId,folderId:a,allDocuments:s};if(a&&s)c.push(this.fetchDocuments(p));else{let _=[];for(let D=0;D<e.length;D+=20)_.push(e.slice(D,D+20));_.forEach(D=>{let B=JSON.parse(JSON.stringify(p));B.documentIds=D.map(G=>G.clientDocumentId),c.push(this.fetchDocuments(B))})}let h={};c.length>0&&Promise.all(c).then(_=>{_?.forEach(E=>{E?.forEach(D=>{D?.metadata?.documentId&&(h[D.metadata.documentId]=D.metadata)})}),this.documentMetadata$.next(I(I({},this.documentMetadata$.value),h))}).catch(_=>{this.loggingService.catch("Error in subscribeToDocumentMetadata: ",_)})}else r?.[i?.documentId??e?.[0]?.documentId]||this.commonDbService?.queryData({feature:"allDocuments",properties:{apiKey:this.apiKey??"",organizationId:i?.organizationId,documentId:i?.documentId??e?.[0]?.documentId,skipObjectValues:!0}}).then(a=>{a?.documentId&&this.documentMetadata$.next({[a.documentId]:a})}).catch(a=>{this.loggingService.catch("Error in subscribeToDocumentMetadata: ",a)})}}catch(i){this.loggingService.catch("Error in subscribeToDocumentMetadata: ",i)}}getLocationMetadata(){try{if(this.db&&this.authService.getUser()){let e=this.documentPaths$.value,i=this.documentIds$.value,r=this.getFolderConfig()?.folderId,a=this.getFolderConfig()?.allDocuments,s=[],c={organizationId:e?.clientOrganizationId,folderId:r,allDocuments:a};if(r&&a)s.push(this.fetchLocations(c));else{let h=[];for(let E=0;E<i.length;E+=20)h.push(i.slice(E,E+20));h.forEach(E=>{let D=JSON.parse(JSON.stringify(c));D.documentIds=E.map(B=>B.clientDocumentId),s.push(this.fetchLocations(D))})}let p=this.locationMetadata$.value??{};s.length>0&&Promise.all(s).then(h=>{h?.forEach(_=>{_?.forEach(E=>{E?.metadata?.documentId&&(p[E.metadata.documentId]=T(I({},p?.[E.metadata.documentId]??{}),{[E.location.id]:E}))})}),Object.keys(p||{}).length>0&&this.locationMetadata$.next(p)}).catch(h=>{this.loggingService.catch("Error in getLocationMetadata: ",h)})}}catch(e){this.loggingService.catch("Error in getLocationMetadata: ",e)}}getLocationMetadatas(){return this.locationMetadata$.value}subscribeToCustomerMetadata(){this.loggingService.log("%c[WB] Calling FUNCTION: subscribeToCustomerMetadata","color: green;");try{if(this.customerMetadataSubscription)return;this.db&&this.authService.getUser()&&this.documentPaths$.value&&(this.customerMetadataSubscription=this.commonDbService?.dbListener({feature:"customerMetadata",properties:{skipFirestore:!0}}).pipe(Ln(i=>re(null))).subscribe(i=>{this.customerMetadata$.next(i?.data)}))}catch(e){this.loggingService.catch("Error in subscribeToCustomerMetadata: ",e)}}getDocumentId(){return this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentId","color: green;"),this.documentPaths$.value?.documentId}getClientDocumentId(){return this.loggingService.log("%c[WB] Calling FUNCTION: getClientDocumentId","color: green;"),this.documentPaths$.value?.clientDocumentId}getDocumentIds$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentIds$","color: green;"),this.documentIds$.asObservable().pipe(ce(e=>e?.slice()))}getFolderConfig$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getFolderConfig$","color: green;"),this.folderConfig$.asObservable()}getDocumentIds(){return this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentIds","color: green;"),this.documentIds$.value?.slice()}getFolderConfig(){return this.loggingService.log("%c[WB] Calling FUNCTION: getFolderConfig","color: green;"),this.folderConfig$.value}getLocationMetadata$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getLocationMetadata$","color: green;"),this.locationMetadata$.asObservable().pipe()}getDocumentPaths$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentPaths$","color: green;"),this.documentPaths$.asObservable()}getFirestorePaths$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getFirestorePaths$","color: green;"),this.firestorePaths$.asObservable()}getDocumentPaths(){return this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentPaths","color: green;"),this.documentPaths$.value}generateDocumentId(e){try{return`${fn(e)}`}catch(i){return this.loggingService.catch("Error in generateDocumentId: ",i),""}}generateOrganizationId(e){try{return`${Rt(e)}`}catch(i){return this.loggingService.catch("Error in generateOrganizationId: ",i),""}}getFirestorePaths(){return this.loggingService.log("%c[WB] Calling FUNCTION: getFirestorePaths","color: green;"),this.firestorePaths$.value}setLocation(e){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: setLocationImpl","color: green;"),e&&typeof e=="object"){if(e?.version&&(!e?.version?.id||!e?.version?.name)){this.loggingService.catch("Error in setLocationImpl: ","If you're setting version then add id and name fields to version object.");return}let i=Xo(e),r=fn(JSON.stringify(i));this.location$.next({locationId:r,location:i}),this.isDocumentIdInDebounceQueue&&(this.draftLocationMap.location=e),this.updateDocumentLocationMetadata().then(()=>{this.analyticsService.trackEvent(Z.Events.Doc.LOCATION_SET,{location:i,locationId:r},!0,this.getUserIdForAnalytics())})}}catch(i){this.loggingService.catch("Error in setLocationImpl: ",i)}}removeLocation(e,i="internal"){try{if(this.analyticsService.trackEvent(Z.Events.Doc.LOCATION_UNSET,{location:this.location$.value?.location,locationId:this.location$.value?.locationId,message:i==="external"?"User removed location":"System removed location",source:i},!0,this.getUserIdForAnalytics()),e){let r=this.genarateLocationId(e);this.getLocation()?.locationId===r&&(this.location$.next(null),i!=="internal"&&(this.draftLocationMap.location=null)),this.removeCustomLocation(e)}else this.location$.next(null),this.locations$.next({}),i!=="internal"&&(this.draftLocationMap.location=null,this.draftLocationMap.locations=[])}catch(r){this.loggingService.catch("Error in removeLocation: ",r)}}getLocation$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getLocation$","color: green;"),this.location$.asObservable()}getLocation(){return this.loggingService.log("%c[WB] Calling FUNCTION: getLocation$","color: green;"),this.location$.value?JSON.parse(JSON.stringify(this.location$.value)):null}excludeLocationIds(e){try{this.excludedLocationIds$.next([...e])}catch(i){this.loggingService.catch("Error in excludeLocationIds: ",i)}}getExcludedLocationIds$(){try{return this.excludedLocationIds$.asObservable()}catch(e){return this.loggingService.catch("Error in getExcludedLocationIds$: ",e),re([])}}updateOrganizationMetadata(){try{if(this.db&&this.authService.getUser()?.organizationId){let e=this.documentPaths$.value,i=this.organizationConfig$.value?.organizationId;if(!this.organizationMetadata$.value?.[i]){let a=new CM;a.apiKey=this.configService?.getApiKey()??"",a.organizationId=i,a.clientOrganizationId=this.organizationConfig$.value?.clientOrganizationId,this.commonDbService?.updateData({feature:"organizationMetadata",data:JSON.parse(JSON.stringify(a)),properties:{organizationId:i,documentId:e?.documentId??""}}),this.subscribeToOrganizationMetadata()}}}catch(e){this.loggingService.catch("Error in updateOrganizationMetadata: ",e)}}updateFolderMetadata(){return ee(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: updateFolderMetadata","color: green;"),this.db&&this.authService.getUser()&&this.folderConfig$.value){let e=this.documentPaths$.value,i=this.folderConfig$.value;if(!(yield this.commonDbService?.getData({feature:"folderMetadata",properties:{organizationId:e?.organizationId??"",folderId:i?.veltFolderId??""}}))?.metadata){let a={folderId:i?.folderId,veltFolderId:i?.veltFolderId,apiKey:this.configService?.getApiKey()??"",organizationId:e?.organizationId,clientOrganizationId:e?.clientOrganizationId,createdAt:Date.now(),lastUpdated:Date.now(),parentFolderId:"root",veltParentFolderId:"root"};this.commonDbService?.updateData({feature:"folderMetadata",data:JSON.parse(JSON.stringify({metadata:a})),properties:{organizationId:e?.organizationId??"",folderId:i?.veltFolderId??""}})}}}catch(e){this.loggingService.catch("Error in updateFolderMetadata: ",e)}})}updateDocumentMetadata(){return ee(this,null,function*(){try{if(this.db&&this.authService.getUser()){let e=this.documentPaths$.value;if(e){let i=this.getDocumentIds();i.find(a=>a.documentId===e.documentId)||i.push({documentId:e.documentId??"",clientDocumentId:e.clientDocumentId??""});let r=i.map(a=>ee(this,null,function*(){let s=new rM;this.clientDocumentMetadata&&(this.clientDocumentMetadata?.clientDocumentId===e.clientDocumentId&&this.clientDocumentMetadata?.documentMetadata&&(s=I(I({},this.clientDocumentMetadata.documentMetadata),s)),this.clientDocumentMetadata=void 0),this.clientDocumentMetadataMap?.[a.clientDocumentId]&&(s=I(I({},this.clientDocumentMetadataMap[a.clientDocumentId]),s)),s.apiKey=this.configService?.getApiKey()??"",s.documentId=a.documentId,s.clientDocumentId=a.clientDocumentId,s.organizationId=e.organizationId,s.clientOrganizationId=e.clientOrganizationId,s.pageInfo=_i();let c=this.getFolderConfig();s?.pageInfo?.deviceInfo&&delete s?.pageInfo?.deviceInfo;let p=!0,h=this.documentMetadata$.value?.[a.documentId];if(c){let _=yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:a?.documentId??"",organizationId:e?.organizationId??"",field:"metadata"}});_?.clientDocumentId?_?.folderId&&(_?.folderId!==c?.folderId||_?.veltFolderId!==c?.veltFolderId)?(this.loggingService.catch(`Folder id mismatch for document ${a?.clientDocumentId??""}`),p=!1):_?.folderId===c?.folderId?(c?.folderId&&(s.folderId=c.folderId),c?.veltFolderId&&(s.veltFolderId=c.veltFolderId)):(this.loggingService.catch(`Document ${a?.clientDocumentId??""} is not in the folder ${c?.folderId??""}`),p=!1):(c?.folderId&&(s.folderId=c.folderId),c?.veltFolderId&&(s.veltFolderId=c.veltFolderId))}if(h){let _={};Object.entries(s).forEach(([E,D])=>{_[E]=D}),Co(_,h)&&(p=!1)}p&&(yield this.commonDbService?.updateData({feature:"documentMetadata",data:JSON.parse(JSON.stringify(s)),properties:{organizationId:e?.organizationId??"",documentId:a?.documentId??""}}))}));yield Promise.all(r),this.subscribeToDocumentMetadata(i)}}}catch(e){this.loggingService.catch("Error in updateDocumentMetadata: ",e)}})}updateDocumentLocationMetadata(){return ee(this,null,function*(){try{if(this.db&&this.authService.getUser()){let e=this.documentPaths$.value,i=this.location$.value;if(e&&i){let r=this.getDocumentIds();r.find(a=>a.documentId===e.documentId)||r.push({documentId:e.documentId??"",clientDocumentId:e.clientDocumentId??""});for(let a of r){let s=yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:a?.documentId??"",organizationId:e?.organizationId??"",field:"metadata"}}),c=new mM;c.locationId=i?.locationId,c.veltLocationId=uV(i?.location?.id??""),c.location=i?.location,c.pageInfo=_i(),c?.pageInfo?.deviceInfo&&delete c?.pageInfo?.deviceInfo;let p=T(I({},s),{[U.FIREBASE_PARTIAL_PATH_LOCATIONS]:T(I({},s[U.FIREBASE_PARTIAL_PATH_LOCATIONS]??{}),{[i?.locationId]:c})}),h=T(I({},c),{metadata:I({},this.getBaseMetadata()??{})});this.commonDbService?.updateData({feature:"documentMetadata",data:JSON.parse(JSON.stringify(p)),properties:{documentId:a?.documentId??"",organizationId:e?.organizationId??""}}),this.commonDbService?.updateData({feature:"locationMetadata",data:JSON.parse(JSON.stringify(h)),properties:{documentId:a?.documentId??"",organizationId:e?.organizationId??"",id:c.veltLocationId}});let _=this.locationMetadata$.value;if(_||(_={}),i?.location?.id){let E=_?.[a.documentId],D=E?.[i?.location?.id??""];_&&(E||(_[a.documentId]={}),D||(_[a.documentId][i?.location?.id??""]={}),_[a.documentId][i?.location?.id??""]=T(I({},D),{location:i?.location})),Object.keys(_||{}).length>0&&this.locationMetadata$.next(_)}}}}}catch(e){this.loggingService.catch("Error in updateDocumentLocationMetadata: ",e)}})}genarateLocationId(e){try{return e&&typeof e=="object"?fn(JSON.stringify(Xo(e))):0}catch(i){return this.loggingService.catch("Error in genarateLocationId: ",i),0}}addLocation(e){try{let i=null;if(e&&typeof e=="object"){if(e?.version&&(!e?.version?.id||!e?.version?.name)){this.loggingService.catch("Error in setLocation: ","If you're setting version then add id and name fields to version object.");return}let r=I({},e),a=this.locations$.value;e?.id&&Object.keys(a).forEach(p=>{let h=a[p];h.location?.id===e.id&&(r=I(I({},h.location),e),delete a[p])});let s=this.genarateLocationId(r),c={locationId:s,location:r};i=c,this.locations$.next(T(I({},a),{[s]:c})),this.isDocumentIdInDebounceQueue&&this.draftLocationMap.locations.push(r),this.analyticsService.trackEvent(Z.Events.Doc.LOCATION_ADDED,{addedLocation:e,addedLocationId:s},!0,this.getUserIdForAnalytics())}return i}catch(i){return this.loggingService.catch("Error in DocService addLocation:",i),null}}removeCustomLocation(e,i="internal"){try{let r=this.genarateLocationId(e),a=this.locations$.value;a[r]&&(delete a[r],this.locations$.next(I({},a)),i!=="internal"&&this.isDocumentIdInDebounceQueue&&(this.draftLocationMap.locations=this.draftLocationMap.locations.filter(s=>s.id!==e.id)))}catch(r){this.loggingService.catch("Error in DocService removeLocation:",r)}}getLocationByClientLocationId(e){try{let i=this.getLocation()?.location;if(i?.id===e)return i;{let r=this.getLocations();Object.keys(r).forEach(a=>{let s=r[a];s.location?.id===e&&(i=s.location)})}return i}catch(i){this.loggingService.catch("Error in DocService getLocationByClientLocationId:",i);return}}removeLocationIfNotInDom(){try{let e=this.locations$.value,i=document.querySelectorAll(`[${U.ATTRIBUTES.VELT_LOCATION}]`),r=[];i.forEach(a=>{let s=a.getAttribute(U.ATTRIBUTES.VELT_LOCATION);if(s){let c=JSON.parse(s),p=this.genarateLocationId(c);r.push(p)}}),Object.keys(e).forEach(a=>{let s=e[a];r.includes(s.locationId)||delete e[a]}),this.locations$.next(I({},e))}catch(e){this.loggingService.catch("Error in DocService removeLocationIfNotInDom:",e)}}getLocations$(){try{return this.locations$.asObservable()}catch(e){return this.loggingService.catch("Error in DocService getLocations$:",e),re({})}}getLocations(){try{return this.locations$.value}catch(e){return this.loggingService.catch("Error in DocService getLocations:",e),{}}}getLocationFromElement(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: getLocationFromElement","color: green;");let i=null;if(e?.getAttribute(U.ATTRIBUTES.VELT_LOCATION)?i=e:i=e.closest(`[${U.ATTRIBUTES.VELT_LOCATION}]`),i){let r=i?.getAttribute(U.ATTRIBUTES.VELT_LOCATION);if(r){let a=JSON.parse(r);return{locationId:this.genarateLocationId(a),location:a}}}return null}catch(i){return this.loggingService.catch("Error in DocService getLocationFromElement:",i),null}}getElementMapWithLocation(){try{this.loggingService.log("%c[WB] Calling FUNCTION: getElementMapWithLocation","color: green;");let e={};return document.querySelectorAll(`[${U.ATTRIBUTES.VELT_LOCATION}], [${U.ATTRIBUTES.VELT_LOCATION_ID}]`).forEach(r=>{if(r.getAttribute(U.ATTRIBUTES.VELT_LOCATION)){let a=this.getLocationFromElement(r);a?.locationId&&(e[a.locationId]={element:r,location:a})}else if(r.getAttribute(U.ATTRIBUTES.VELT_LOCATION_ID)){let a=r.getAttribute(U.ATTRIBUTES.VELT_LOCATION_ID);if(a){let s=this.getLocationByClientLocationId(a);s?.locationId&&(e[s.locationId]={element:r,location:s});let c={id:a},p=this.genarateLocationId(c);e[a]={element:r,location:{locationId:p,location:c}}}}}),e}catch(e){return this.loggingService.catch("Error in DocService getElementMapWithLocation:",e),{}}}getAdditionLocationFromElement(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: getAdditionLocationFromElement","color: green;");let i;if(i=e?.closest(`[${U.ATTRIBUTES.VELT_LOCATION}], [${U.ATTRIBUTES.VELT_LOCATION_ID}]`),i){if(i?.getAttribute(U.ATTRIBUTES.VELT_LOCATION)){let r=i?.getAttribute(U.ATTRIBUTES.VELT_LOCATION);if(r)return JSON.parse(r)}else if(i?.getAttribute(U.ATTRIBUTES.VELT_LOCATION_ID)){let r=i?.getAttribute(U.ATTRIBUTES.VELT_LOCATION_ID);if(r)return{id:r}}}return null}catch(i){return this.loggingService.catch("Error in DocService getAdditionLocationFromElement:",i),null}}getAdditionalDocumentIdFromElement(e){try{return e?.closest(`[${U.ATTRIBUTES.VELT_DOCUMENT_ID}]`)?.getAttribute(U.ATTRIBUTES.VELT_DOCUMENT_ID)||null}catch(i){return this.loggingService.catch("Error in DocService getAdditionalDocumentIdFromElement:",i),null}}getDocumentMetadata(e){try{return e?this.documentMetadata$.value?.[e]||null:this.documentMetadata$.value?.[this.documentPaths$.value?.documentId??""]||null}catch(i){return this.loggingService.catch("Error in DocService getDocumentMetadata:",i),null}}getAllDocumentMetadata(){try{return Object.values(this.documentMetadata$.value||{})}catch(e){return this.loggingService.catch("Error in DocService getAllDocumentMetadata:",e),[]}}getDocumentMetadataOfAvailableDocuments(){try{this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentMetadataOfAvailableDocuments","color: green;");let e=this.documentMetadata$.value||{},i={},r=this.getFolderConfig();if(r?.veltFolderId&&r?.allDocuments)Object.values(e).forEach(a=>{a?.documentId&&a?.veltFolderId===r?.veltFolderId&&(i[a.documentId]=a)});else{let a=this.documentIds$.value;if(a?.length)a.forEach(s=>{let c=e?.[s.documentId];c&&(i[s.documentId]=c)});else if(this.documentPaths$.value?.documentId){let s=e?.[this.documentPaths$.value?.documentId];s&&(i[this.documentPaths$.value?.documentId]=s)}}return Object.values(i)}catch(e){return this.loggingService.catch("Error in DocService getDocumentMetadataOfAvailableDocuments:",e),[]}}getDocumentMetadata$(e){return this.documentMetadata$.asObservable().pipe(ce(i=>i?.[e??this.documentPaths$.value?.documentId??""]||null))}getOrganizationMetadata(e){return this.organizationMetadata$.value?.[e]||null}getOrganizationMetadata$(e){return this.organizationMetadata$.asObservable().pipe(ce(i=>i?.[e]||null))}getCustomerMetadata(){return this.customerMetadata$.value}getCustomerMetadata$(){return this.customerMetadata$.asObservable()}getOrganizationConfig$(){return this.organizationConfig$.asObservable()}getOrganizationConfig(){return this.organizationConfig$.value}getMetadataFromType(e,i){try{switch(e){case"area":return;case"comment":return i?.multiThreadAnnotationId?this.commentService?.getMultiThreadAnnotationById(i.multiThreadAnnotationId)?.metadata:void 0;case"reaction":case"recorder":return i?.commentAnnotationId?this.commentService?.getAnnotationById(i.commentAnnotationId)?.metadata:void 0;default:return}}catch(r){this.loggingService.catch("Error in DocService getMetadataFromType:",r);return}}getDefaultMetadata({clientDocumentId:e,documentId:i}){try{let r=this.documentPaths$.value;if(!r)return;let a=e||r.clientDocumentId,s=i||r.documentId,c=this.getDocumentMetadata(s);if(!c)return;let p=c?.folderId,h=c?.veltFolderId;return I(I({apiKey:this.configService.getApiKey()??void 0,clientDocumentId:a,clientOrganizationId:r.clientOrganizationId,documentId:s,organizationId:r.organizationId},p?{folderId:p}:{}),h?{veltFolderId:h}:{})}catch(r){this.loggingService.catch("Error in DocService getDefaultMetadata:",r);return}}getBaseMetadata(e,i){try{let r,a;i?.element?r=this.getAdditionalDocumentIdFromElement(i.element)||void 0:i?.clientDocumentId&&(r=i.clientDocumentId),r&&(a=this.generateDocumentId(r));let s=this.getMetadataFromType(e,i),c=this.getDefaultMetadata({clientDocumentId:r,documentId:a});return s||c||{}}catch(r){return this.loggingService.catch("Error in DocService getBaseMetadata:",r),{}}}getServerId({documentId:e,organizationId:i}){try{return e&&(e=this.generateDocumentId(e)),i&&(i=this.generateOrganizationId(i)),{documentId:e,organizationId:i}}catch(r){return this.loggingService.catch("Error in DocService getServerId:",r),null}}fetchDocuments(e){return ee(this,null,function*(){try{if(!this.authService.getUser())return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),[];let r=[];if(!e?.organizationId)return this.loggingService.catch("Error in fetchDocuments: organizationId is required"),[];if(e?.folderId){let s=hl(e?.folderId);r.push(mt("metadata.veltFolderId","==",s))}return e?.documentIds?.length&&!e?.allDocuments&&r.push(mt("metadata.documentId","in",e?.documentIds?.map(s=>this.generateDocumentId(s)).slice(0,30))),yield this.commonDbService?.queryData({feature:"allDocuments",properties:{firestoreQuery:r,apiKey:this.apiKey??"",organizationId:this.generateOrganizationId(e?.organizationId)??this.documentPaths$.value?.organizationId,documentId:this.documentPaths$.value?.documentId}})}catch(i){return this.loggingService.catch("Error in DocService fetchDocuments:",i),[]}})}fetchLocations(e){return ee(this,null,function*(){try{if(!this.authService.getUser())return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),[];let r=[];if(!e?.organizationId)return this.loggingService.catch("Error in fetchLocations: organizationId is required"),[];if(e?.folderId){let s=hl(e?.folderId);r.push(mt("metadata.veltFolderId","==",s))}return e?.documentIds?.length&&!e?.allDocuments&&r.push(mt("metadata.documentId","in",e?.documentIds?.map(s=>this.generateDocumentId(s)).slice(0,30))),yield this.commonDbService?.queryData({feature:"allLocations",properties:{firestoreQuery:r,apiKey:this.apiKey??"",organizationId:this.generateOrganizationId(e?.organizationId)??this.documentPaths$.value?.organizationId,documentId:this.documentPaths$.value?.documentId}})}catch(i){return this.loggingService.catch("Error in DocService fetchLocations:",i),[]}})}updateDocuments(e){return ee(this,null,function*(){try{if(!this.authService.getUser())return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),[];let{organizationId:r,documents:a}=e;if(!r&&(r=this.documentPaths$.value?.clientOrganizationId,!r))return this.loggingService.catch("Error in updateDocuments: organizationId is required"),[];if(!a||a.length===0)return this.loggingService.catch("Error in updateDocuments: documents is required"),[];let s=[],c=this.documentMetadata$.value;a.forEach(p=>{delete p?.organizationId,delete p?.clientDocumentId,delete p?.clientOrganizationId,delete p?.apiKey;let h=ud(p.documentId),_=c?.[h];_&&(c[h]=I(I({},_),p)),p&&this.commonDbService&&s.push(this.commonDbService.updateData({feature:"documentMetadata",data:JSON.parse(JSON.stringify(p)),properties:{organizationId:hd(r),documentId:h}}))}),yield Promise.all(s),this.documentMetadata$.next(c)}catch(i){return this.loggingService.catch("Error in DocService updateDocuments:",i),[]}})}updateLocations(e){return ee(this,null,function*(){try{if(!this.authService.getUser())return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),[];let{organizationId:r,locations:a,documentIds:s}=e;if((!s||s.length===0)&&(s=this.documentIds$.value.map(_=>_.clientDocumentId)??[],s.length===0))return this.loggingService.catch("Error in updateLocations: documentId is required"),[];if(!r&&(r=this.documentPaths$.value?.clientOrganizationId,!r))return this.loggingService.catch("Error in updateLocations: organizationId is required"),[];if(!a||a.length===0)return this.loggingService.catch("Error in updateLocations: locations is required"),[];let c=s.map(_=>ud(_)),p=[],h=this.locationMetadata$.value;h||(h={}),c.forEach(_=>{a.forEach(E=>{let D=this.location$.value;if(E?.id===D?.location?.id&&this.location$.next({locationId:D?.locationId,location:E}),E?.id){delete E?.metadata;let B=uV(E.id),G=h?.[_],X=G?.[E.id];h&&(G||(h[_]={}),X||(h[_][E.id]={}),h[_][E.id]=T(I({},X),{location:E})),E&&this.commonDbService&&p.push(this.commonDbService.updateData({feature:"locationMetadata",data:JSON.parse(JSON.stringify({location:E})),properties:{organizationId:hd(r),documentId:_,id:B}}))}})}),yield Promise.all(p),Object.keys(h||{}).length>0&&this.locationMetadata$.next(h)}catch(i){return this.loggingService.catch("Error in DocService updateLocations:",i),[]}})}fetchFolders(e){return ee(this,null,function*(){try{if(!this.authService.getUser())return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),[];let r=[];if(!e?.organizationId)return this.loggingService.catch("Error in fetchFolders: organizationId is required"),{data:[],parentFolders:[]};let a=[],s=this.generateOrganizationId(e?.organizationId);if(e?.folderId){let c=hl(e?.folderId);r=yield this.commonDbService?.getData({feature:"folder",properties:{folderId:c,apiKey:this.apiKey??"",organizationId:s,documentId:this.documentPaths$.value?.documentId}}),r&&(r=[r]),a=yield this.commonDbService?.queryData({feature:"allFolders",properties:{firestoreQuery:[mt("metadata.veltParentFolderId","==",c)],folderId:c,apiKey:this.apiKey??"",organizationId:s,documentId:this.documentPaths$.value?.documentId}})}else r=yield this.commonDbService?.queryData({feature:"allFolders",properties:{apiKey:this.apiKey??"",organizationId:s,documentId:this.documentPaths$.value?.documentId}});return{data:r,parentFolders:a}}catch(i){return this.loggingService.catch("Error in DocService getFoldersRequest:",i),{data:[],parentFolders:[]}}})}getDocumentIam$(){return this.authService.getUser$().pipe(ge(e=>e?this.documentPaths$.pipe(ge(i=>i?.documentIam?this.commonDbService?.dbListener({feature:"documentIam",properties:{documentId:i.documentId,organizationId:i.organizationId,isCollection:!1}}).pipe(ce(r=>r?.data?.docIamConfig??r?.data),Kt((r,a)=>JSON.stringify(r??{})===JSON.stringify(a??{}))):re(null))):re(null)))}getDocumentAccessType(e){try{return e&&e.features&&e.features.all?e.features.all.restricted?di.RESTRICTED:di.PUBLIC:e&&e.documentAccessType?e.documentAccessType:di.PUBLIC}catch(i){return this.loggingService.catch("Error in DocService getDocumentAccessType:",i),di.PUBLIC}}changeDocumentAccessType(e){return ee(this,null,function*(){try{let i=this.documentPaths$.value;if(i){let r=yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:i?.documentId??"",organizationId:i?.organizationId??"",field:"docIamConfig"}});switch(delete r.documentAccessType,r.features||(r.features={}),r.features.all||(r.features.all={}),e){case di.PUBLIC:r.features.all.restricted=!1;break;case di.RESTRICTED:r.features.all.restricted=!0,r.features.all.guestMode=!1;break;default:break}this.commonDbService?.updateData({feature:"documentAccessType",data:JSON.parse(JSON.stringify(r)),properties:{documentId:i?.documentId??"",organizationId:i?.organizationId??""}})}}catch(i){this.loggingService.catch("Error in DocService changeDocumentAccessType:",i)}})}getUserIdForAnalytics(){try{return this.authService?.getAuthUser()?.uid||this.configService?.getApiKey()||""}catch(e){return this.loggingService.catch("Error in DocService getUserIdForAnalytics:",e),""}}setUIState(e){try{this.uiState.next(I(I({},this.uiState.value),e))}catch(i){this.loggingService.catch("Error in DocService setUIState:",i)}}getUIState$(){return this.uiState.asObservable()}};o.\u0275fac=function(i){return new(i||o)(J(Qe),J(je),J(pn),J(Fe),J($t),J(y),J(vs),J(um))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Hn=(()=>{let o=class o{constructor(e,i,r,a){this.analyticsService=e,this.authService=i,this.docService=r,this.loggingService=a,this.defaultUserDataProvider={get:s=>ee(this,null,function*(){return{}})},this.resolveTimeout=1*60*1e3,this.maxResolveAttempts=1,this.resolveAttempts=new Map,this.subscriptions=new ln,this.userDataProvider$=new fe(null),this.userById$=new fe({}),this.userByIdCalled$=new fe({}),this.pendingResolutions=new Set,this.getUserById=s=>{try{return this.userById$.value?.[s]}catch(c){this.loggingService.catch("Error in UsersService getUserById:",c);return}};try{this.analyticsService.setUserService(this),this.authService.setUsersService(this)}catch(s){this.loggingService.catch("Error in UsersService constructor:",s)}}ngOnDestroy(){try{this.subscriptions.unsubscribe(),this.pendingResolutions.clear(),this.resolveAttempts.clear()}catch(e){this.loggingService.catch("Error in UsersService ngOnDestroy:",e)}}resolveUsers(e,i=!1){return ee(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling UsersService FUNCTION: resolveUsers","color: green;"),this.userDataProvider$.getValue()){let r={},a=[],s={};if(e?.forEach(c=>{let p=this.getUserById(c);p?r[c]=p:this.userByIdCalled$.getValue()[c]?i&&a.push(c):(a.push(c),this.userByIdCalled$.next(T(I({},this.userByIdCalled$.getValue()),{[c]:!0})))}),a.length>0){let c=this.userDataProvider$.getValue();if(c){let p={};try{let h,_=new Promise((E,D)=>{h=setTimeout(()=>{D(new Error("User resolution timeout"))},this.userDataProvider$.getValue()?.resolveTimeout||this.resolveTimeout)});p=yield Promise.race([c.get(a).finally(()=>{clearTimeout(h)}),_]),this.analyticsService.trackEvent(Z.Events.Resolver.USER_RESOLVER_GET,{sourceMethod:"resolveUsers",source:"sdk",userIds:a})}catch(h){this.loggingService.catch("Error in UsersService resolveUsers getUsers:",h,{userIds:a})}finally{a?.forEach(h=>{p[h]||(p[h]={userId:h,name:`User ${h}`})})}Object.entries(p).forEach(([h,_])=>{_&&(r[h]=p?.[h],s[h]=p?.[h])})}}return Object.keys(s).length>0&&this.userById$.next(I(I({},this.userById$.getValue()),s)),r}else return{}}catch(r){return this.loggingService.catch("Error in UsersService resolveUsers:",r),{}}})}subscribeToDocuments(){return this.docService.getDocumentIds$().pipe(In(e=>ee(this,null,function*(){let i=yield this.getUsersFromCentralDb({documentIds:e?.map(r=>r.documentId)});this.resolveUsers(i)})))}getUsersFromCentralDb(i){return ee(this,arguments,function*({documentIds:e}){try{return new Promise(r=>{r(["customuser1","customuser2","customuser3"])})}catch{return[]}})}getUserById$(){try{return this.loggingService.log("%c[WB] Calling UsersService FUNCTION: getUserById$","color: green;"),this.userById$.asObservable()}catch(e){return this.loggingService.catch("Error in UsersService getUserById$:",e),re({})}}setUserDataProvider(e){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setUserDataProvider","color: green;"),this.userDataProvider$.next(e)}catch(i){this.loggingService.catch("Error in UsersService setUserDataProvider:",i)}}userDataProviderAvailable(){try{return this.loggingService.log("%c[WB] Calling UsersService FUNCTION: userDataProviderAvailable","color: green;"),!!this.userDataProvider$.getValue()}catch(e){return this.loggingService.catch("Error in UsersService userDataProviderAvailable:",e),!1}}};o.\u0275fac=function(i){return new(i||o)(J(Qe),J(je),J(lt),J(y))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var ase=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.usersService=i}getUserIdsToResolveFromAreaAnnotations(e){try{this.loggingService.log("%c[WB] Calling AreaUtilsService FUNCTION: getUserIdsToResolveFromAreaAnnotations","color: green;");let i=new Set;for(let r of e)r?.from?.userId&&i.add(r?.from?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in AreaUtilsService getUserIdsToResolveFromAreaAnnotations:",i),[]}}mergeAreaWithUser(e){try{if(this.loggingService.log("%c[WB] Calling AreaUtilsService FUNCTION: mergeAreaWithUser","color: green;"),e?.from?.userId){let i=this.usersService.getUserById(e?.from?.userId);i&&(e.from=i)}return e}catch(i){return this.loggingService.catch("Error in AreaUtilsService mergeAreaWithUser:",i),e}}formatAreaData(e){try{return this.loggingService.log("%c[WB] Calling AreaUtilsService FUNCTION: formatAreaData","color: green;"),this.usersService.userDataProviderAvailable()&&e?.from?.userId&&(e.from={userId:e.from.userId}),e}catch(i){return this.loggingService.catch("Error in AreaUtilsService formatAreaData:",i),e}}};o.\u0275fac=function(i){return new(i||o)(J(y),J(Hn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var sse=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.usersService=i}getUserIdsToResolveFromArrowAnnotations(e){try{this.loggingService.log("%c[WB] Calling ArrowUtilsService FUNCTION: getUserIdsToResolveFromArrowAnnotations","color: green;");let i=new Set;for(let r of e)r?.from?.userId&&i.add(r?.from?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in ArrowUtilsService getUserIdsToResolveFromArrowAnnotations:",i),[]}}mergeArrowWithUser(e){try{if(this.loggingService.log("%c[WB] Calling ArrowUtilsService FUNCTION: mergeArrowWithUser","color: green;"),e?.from?.userId){let i=this.usersService.getUserById(e?.from?.userId);i&&(e.from=i)}return e}catch(i){return this.loggingService.catch("Error in ArrowUtilsService mergeArrowWithUser:",i),e}}formatArrowData(e){try{return this.loggingService.log("%c[WB] Calling ArrowUtilsService FUNCTION: formatArrowData","color: green;"),this.usersService.userDataProviderAvailable()&&e?.from?.userId&&(e.from={userId:e.from.userId}),e}catch(i){return this.loggingService.catch("Error in ArrowUtilsService formatArrowData:",i),e}}};o.\u0275fac=function(i){return new(i||o)(J(y),J(Hn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Fp=class{static getFirestoreProdDbName(o,t){return t?.storeDbId??(this.isTestingDb(t?.databaseURL??"")?"sdktest":`apikey${o.toLowerCase()}`)}static isTestingDb(o){try{return o.includes("-test")}catch(t){return pt.error("Error in isTestingDb:",t),!1}}};var Lp=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.analyticsService=i,this.retrySaveConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.retryDeleteConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.attachmentDataProvider$=new fe(null);try{this.loggingService.log("AttachmentResolverService initialized"),this.attachmentDataProvider$.subscribe(r=>{r&&(r.config?.saveRetryConfig&&(this.retrySaveConfig=r.config.saveRetryConfig),r.config?.deleteRetryConfig&&(this.retryDeleteConfig=r.config.deleteRetryConfig))})}catch(r){this.loggingService.catch("Error in AttachmentResolverService constructor:",r)}}getProvider(){try{let e=this.attachmentDataProvider$.getValue();return e||void 0}catch(e){this.loggingService.catch("Error in AttachmentResolverService getProvider:",e);return}}saveAttachment(e){return ee(this,null,function*(){try{this.loggingService.log("%c[WB] Calling AttachmentResolverService FUNCTION: saveAttachment","color: green;");let i=this.getProvider();if(!this.attachmentDataProviderAvailable())throw new Error("Attachment save data provider not available");let r=yield sc(()=>i?.save({attachment:e.attachment,event:e.eventType,metadata:e.attachment.metadata})||Promise.resolve(void 0),"saveAttachment",this.retrySaveConfig);if(r?.statusCode!==200){this.loggingService.catch(r?.message??"Error in AttachmentResolverService saveAttachment:");return}return this.analyticsService.trackEvent(Z.Events.Resolver.ATTACHMENT_RESOLVER_SAVE,{sourceMethod:"saveAttachment",source:"sdk",attachmentId:e.attachment.attachmentId,eventType:e.eventType}),r}catch(i){this.loggingService.warn("Error in AttachmentResolverService saveAttachment:",i);return}})}deleteAttachment(r){return ee(this,arguments,function*({attachmentId:e,metadata:i}){try{this.loggingService.log("%c[WB] Calling AttachmentResolverService FUNCTION: deleteAttachment","color: green;");let a=this.getProvider();if(!this.attachmentDataProviderAvailable())throw new Error("Attachment delete data provider not available");let s=yield sc(()=>a?.delete({attachmentId:e,metadata:i,event:Ha.ATTACHMENT_DELETE})||Promise.resolve(void 0),"deleteAttachment",this.retryDeleteConfig);return s?.statusCode!==200?(this.loggingService.catch(s?.message??"Error in AttachmentResolverService deleteAttachment:"),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(Z.Events.Resolver.ATTACHMENT_RESOLVER_DELETE,{sourceMethod:"deleteAttachment",source:"sdk",attachmentId:e}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0})}catch(a){return this.loggingService.warn("Error in AttachmentResolverService deleteAttachment:",a),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0}}})}setAttachmentDataProvider(e){try{if(e){this.loggingService.log("Setting attachment data provider");let r=["save","delete"].filter(a=>!(a in e)||typeof e[a]!="function");if(r.length>0){let a=`DataProviders.attachment is invalid. The following methods are missing or are not functions: ${r.join(", ")}.`;this.loggingService.catch(a);return}else this.attachmentDataProvider$.next(e)}}catch(i){this.loggingService.catch("Error in AttachmentResolverService setAttachmentDataProvider:",i)}}attachmentDataProviderAvailable(){try{return!!this.attachmentDataProvider$.getValue()}catch(e){return this.loggingService.catch("Error in AttachmentResolverService attachmentDataProviderAvailable:",e),!1}}};o.\u0275fac=function(i){return new(i||o)(J(y),J(Qe))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Uv=(()=>{let o=class o{constructor(e,i,r,a,s,c,p){this.loggingService=e,this.usersService=i,this.authService=r,this.functions=a,this.configService=s,this.commentAnnotationsResolverService=c,this.attachmentResolverService=p,this.notificationActionTypeMap={[jt.NEWLY_ADDED]:Ha.COMMENT_ANNOTATION_ADD,[jt.ADDED]:Ha.COMMENT_ADD,[jt.UPDATED]:Ha.COMMENT_UPDATE,[jt.DELETED]:Ha.COMMENT_DELETE}}setNotificationService(e){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: setNotificationService","color: green;"),this.notificationService=e}catch(i){this.loggingService.catch("Error in CommentUtilsService setNotificationService: ",i)}}getUserIdsToResolveFromComments(e){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: getUserIdsToResolveFromComments","color: green;");let i=new Set;for(let r of e){if(r?.from?.userId&&i.add(r?.from?.userId),r?.comments)for(let a of r?.comments){if(a?.from?.userId&&i.add(a?.from?.userId),a?.to)for(let s of a?.to)s?.userId&&i.add(s?.userId);if(a?.taggedUserContacts)for(let s of a?.taggedUserContacts)s?.userId&&i.add(s?.userId)}if(r?.assignedTo?.userId&&i.add(r?.assignedTo?.userId),r?.subscribedUsers)for(let a of Object.values(r?.subscribedUsers))a.user.userId&&i.add(a.user.userId);if(r?.unsubscribedUsers)for(let a of Object.values(r?.unsubscribedUsers))a.user.userId&&i.add(a.user.userId)}return Array.from(i)}catch(i){return this.loggingService.catch("Error in CommentUtilsService getUserIdsToResolveFromComments:",i),[]}}mergeCommentWithUser(e){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: mergeCommentWithUser","color: green;"),e?.from?.userId){let i=this.usersService.getUserById(e?.from?.userId);i&&(e.from=i)}if(e?.comments)for(let i of e?.comments){if(i?.from?.userId){let a=this.usersService.getUserById(i?.from?.userId);a&&(i.from=a)}i?.to&&(i.to=i?.to?.map(a=>{if(a?.userId){let s=this.usersService.getUserById(a?.userId);if(s)return I(I({},a),s)}return a})),i?.taggedUserContacts&&(i.taggedUserContacts=i?.taggedUserContacts?.map(a=>{if(a?.contact){let s=this.usersService.getUserById(a?.contact?.userId);s&&(a.contact=s,(s?.name||s?.email)&&(a.text=`@${s?.name||s?.email}`))}return a})),(i?.taggedUserContacts?.filter((a,s,c)=>c.findIndex(p=>p.text===a.text)===s)||[]).forEach(a=>{if(a?.text){let s=new RegExp(im(`{{${a.userId}}}`),"g");i.commentText=i.commentText?.replaceAll(s,a.text),i.commentHtml=i.commentHtml?.replaceAll(s,a.text)}})}if(e?.assignedTo?.userId){let i=this.usersService.getUserById(e?.assignedTo?.userId);i&&(e.assignedTo=i)}if(e?.subscribedUsers)for(let i of Object.values(e?.subscribedUsers)){let r=this.usersService.getUserById(i.user.userId);r&&e?.subscribedUsers?.id?.user&&(e.subscribedUsers.id.user=r)}if(e?.unsubscribedUsers)for(let i of Object.values(e?.unsubscribedUsers)){let r=this.usersService.getUserById(i.user.userId);r&&e?.unsubscribedUsers?.id?.user&&(e.unsubscribedUsers.id.user=r)}return e}catch(i){return this.loggingService.catch("Error in CommentUtilsService mergeCommentWithUser:",i),e}}formatCommentData(e){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: formatCommentData","color: green;"),e?.comments?.forEach(i=>{i?.commentText&&i?.commentText?.length>0&&(i.isCommentTextAvailable=!0)}),this.usersService.userDataProviderAvailable()){if(e?.from?.userId&&(e.from={userId:e.from.userId}),e?.assignedTo?.userId&&(e.assignedTo={userId:e.assignedTo.userId}),e?.subscribedUsers)for(let i of Object.keys(e?.subscribedUsers))e.subscribedUsers[i].user={userId:e?.subscribedUsers[i].user.userId};if(e?.unsubscribedUsers)for(let i of Object.keys(e?.unsubscribedUsers))e.unsubscribedUsers[i].user={userId:e?.unsubscribedUsers[i].user.userId}}return e?.comments&&(e.comments=e?.comments?.map(i=>this.formatCommentThreadData(i))),e}catch(i){return this.loggingService.catch("Error in CommentUtilsService formatCommentData:",i),e}}mergeStrippedDataWithCommentAnnotations(e){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: mergeStrippedDataWithCommentAnnotations","color: green;"),!this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())return e;let i=this.commentAnnotationsResolverService.getAnnotationById(e?.annotationId),r=this.attachmentResolverService.attachmentDataProviderAvailable();return i&&e?.comments?.forEach(a=>{let s=i?.comments?.[a?.commentId];if(s){a.commentHtml=s?.commentHtml,a.commentText=s?.commentText;let c=s?.attachments;r&&c&&a.attachments?.forEach(p=>{let h=p?.attachmentId;c?.[h]&&(p.name=c?.[h]?.name,p.url=c?.[h]?.url)})}}),e}catch(i){return this.loggingService.catch("Error in CommentUtilsService mergeStrippedDataWithCommentAnnotations:",i),e}}mergeLocationWithCommentAnnotations(e,i){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: mergeLocationWithCommentAnnotations","color: green;");let r=e?.location?.id,a=e?.metadata?.documentId;if(!r||!a)return e;let s=i?.[a]?.[r];return s&&(e.location=s?.location),e}catch(r){return this.loggingService.catch("Error in CommentUtilsService mergeLocationWithCommentAnnotations:",r),e}}isCommentsDataChanged(e,i){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: isCommentsDataChanged","color: green;");let r=this.commentAnnotationsResolverService.getCommentAnnotationById(i);return r?!Co(e,r):!0}catch(r){return this.loggingService.catch("Error in CommentUtilsService isCommentsDataChanged:",r),!0}}stripCommentAnnotationData({data:e,actionType:i}){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: stripCommentAnnotationData","color: green;"),!this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable()||!i)return{originalData:e,strippedData:null};let r=this.attachmentResolverService.attachmentDataProviderAvailable(),a=this.notificationActionTypeMap?.[i];if(!a)return{originalData:e,strippedData:null};let s={},c=null;if(e&&e.annotationId){let p=e.annotationId;if(s[p]={annotationId:p,metadata:sv(e.metadata??{}),comments:{}},e.comments?.forEach(E=>{if(E.commentId){let D;r&&(D={},E.attachments?.forEach(B=>{D[B.attachmentId]={attachmentId:B.attachmentId,name:B.name,url:B.url}})),s[p].comments[E.commentId]=I(I(I({commentId:E.commentId},E?.commentHtml&&{commentHtml:E?.commentHtml}),E?.commentText&&{commentText:E?.commentText}),D&&{attachments:D})}}),!this.isCommentsDataChanged(s[p],p))return{strippedData:null,originalData:e};let _=new ko;Object.assign(_,e),_.comments=e.comments?.map(E=>{let D=new pc;if(Object.assign(D,E),D.isCommentResolverUsed=!0,r){let B=D.attachments?.map(G=>(G.isAttachmentResolverUsed=!0,delete G?.name,delete G?.url,G));D.attachments=B}return delete D?.commentHtml,delete D?.commentText,D})||[],c=_}return{strippedData:s,originalData:c,eventType:a}}catch(r){return this.loggingService.catch("Error in CommentAnnotationsResolverService stripCommentAnnotationData:",r),{strippedData:null,originalData:null}}}formatCommentThreadData(e){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: formatCommentThreadData","color: green;"),this.usersService.userDataProviderAvailable()){e?.from?.userId&&(e.from={userId:e.from.userId}),e?.to&&(e.to=e?.to?.map(r=>r?.userId?{userId:r.userId}:r)),e?.taggedUserContacts&&(e.taggedUserContacts=e?.taggedUserContacts?.map(r=>r?.contact?T(I({},r),{contact:{userId:r.userId}}):r));let i=e?.taggedUserContacts?.filter((r,a,s)=>s.findIndex(c=>c.text===r.text)===a)||[];i.forEach(r=>{if(r?.text){let a=new RegExp(im(r.text),"g");e.commentText=e.commentText?.replaceAll(a,s=>`{{${r.userId}}}`),e.commentHtml=e.commentHtml?.replaceAll(a,s=>`{{${r.userId}}}`)}}),i.forEach(r=>{r?.text&&(r.text="")})}return e}catch(i){return this.loggingService.catch("Error in CommentUtilsService formatCommentThreadData:",i),e}}handleCommentEncryption(s){return ee(this,arguments,function*({data:e,firestorePath:i,extraData:r,eventType:a}){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: handleCommentEncryption","color: green;");let c=$O(this.authService.getFirebaseConfig()?.firebaseOptions),p=Cr(this.functions,Zn.cloudFunction?.[c]?.setEncryptedData,{timeout:20*60*1e3});if(r){r=this.notificationService?.processNotificationData(r),r.annotationData=e;let D=r?.targetAnnotationData?.commentId;if(D){let B=e?.comments?.find(G=>G?.commentId===D);B&&(r.targetAnnotationData=B)}}let h=Fp.getFirestoreProdDbName(this.configService.getApiKey()??"",this.authService.getFirebaseConfig()?.firebaseOptions),_={path:i??"",data:e??{},dbId:h??"",notificationData:r||void 0,notificationURL:Zn.firebaseNotificationsDatabaseURL,feature:"comment",eventType:a??"PATCH",sdkVersion:Ta()},E=yield bp(_,this.authService.getUser()?.userId??"");yield p({veltData:E})}catch(c){this.loggingService.catch("Error in CommentUtilsService handleCommentEncryption:",c)}})}};o.\u0275fac=function(i){return new(i||o)(J(y),J(Hn),J(je),J(Vo),J($t),J(vs),J(Lp))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var lse=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.usersService=i}getUserIdsToResolveFromUserIamData(e){try{this.loggingService.log("%c[WB] Calling ContactUtilsService FUNCTION: getUserIdsToResolveFromUserIamData","color: green;");let i=new Set;if(e?.length)for(let r of e)r?.user?.userId&&i.add(r?.user?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in ContactUtilsService getUserIdsToResolveFromUserIamData: ",i),[]}}mergeUserIamWithUser(e){try{if(this.loggingService.log("%c[WB] Calling ContactUtilsService FUNCTION: mergeUserIamWithUser","color: green;"),e?.user?.userId){let i=this.usersService.getUserById(e?.user?.userId);i&&(e=T(I({},e),{user:i}))}return e}catch(i){return this.loggingService.catch("Error in ContactUtilsService mergeUserIamWithUser: ",i),e}}};o.\u0275fac=function(i){return new(i||o)(J(y),J(Hn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var cse=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.usersService=i}getUserIdsToResolveFromCursorUsers(e){try{this.loggingService.log("%c[WB] Calling CursorUtilsService FUNCTION: getUserIdsToResolveFromCursorUsers","color: green;");let i=new Set;for(let r of e)r?.userId&&i.add(r?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in CursorUtilsService getUserIdsToResolveFromCursorUsers:",i),[]}}mergeCursorUserWithUser(e){try{if(this.loggingService.log("%c[WB] Calling CursorUtilsService FUNCTION: mergeCursorUserWithUser","color: green;"),this.usersService.userDataProviderAvailable()&&e?.userId){let i=this.usersService.getUserById(e?.userId);i&&(e=I(I({},e),i))}return e}catch(i){return this.loggingService.catch("Error in CursorUtilsService mergeCursorUserWithUser:",i),e}}formatCursorUserData(e){try{if(this.loggingService.log("%c[WB] Calling CursorUtilsService FUNCTION: formatCursorUserData","color: green;"),this.usersService.userDataProviderAvailable()){let i=["userId","comment","positionX","positionY","screenWidth","screenHeight","screenScrollHeight","onlineStatus","userSnippylyId","color","textColor","timestamp","type","selections","documentParamsId","documentParams","locationId","location","targetElement","position","isReadOnly","isAnonymous","pageInfo"];Object.keys(e).forEach(r=>{i.includes(r)||(e[r]=null)})}return e}catch(i){return this.loggingService.catch("Error in CursorUtilsService formatCursorUserData:",i),e}}};o.\u0275fac=function(i){return new(i||o)(J(y),J(Hn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var xM=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.usersService=i}getUserIdsToResolveFromHuddleAttendees(e){try{this.loggingService.log("%c[WB] Calling HuddleUtilsService FUNCTION: getUserIdsToResolveFromHuddleAttendees","color: green;");let i=new Set;for(let r of e)r?.userId&&i.add(r?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in HuddleUtilsService getUserIdsToResolveFromHuddleAttendees:",i),[]}}mergeHuddleAttendeeWithUser(e){try{if(this.loggingService.log("%c[WB] Calling HuddleUtilsService FUNCTION: mergeHuddleAttendeeWithUser","color: green;"),e?.userId){let i=this.usersService.getUserById(e?.userId);i&&(e=I(I({},e),i))}return e}catch(i){return this.loggingService.catch("Error in HuddleUtilsService mergeHuddleAttendeeWithUser:",i),e}}formatHuddleAttendeeData(e){try{if(this.usersService.userDataProviderAvailable()){let i=["userId","userSnippylyId","state","timestamp","initialHuddleMode","streamMetadata","initialHuddleType","huddleOnCursorMode"];Object.keys(e).forEach(r=>{i.includes(r)||(e[r]=null)})}return e}catch(i){return this.loggingService.catch("Error in HuddleUtilsService formatHuddleAttendeeData:",i),e}}getUserIdsToResolveFromHuddleMessages(e){try{this.loggingService.log("%c[WB] Calling HuddleUtilsService FUNCTION: getUserIdsToResolveFromHuddleMessages","color: green;");let i=new Set;for(let r of e)r?.from?.userId&&i.add(r?.from?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in HuddleUtilsService getUserIdsToResolveFromHuddleMessages:",i),[]}}mergeHuddleMessageWithUser(e){try{if(this.loggingService.log("%c[WB] Calling HuddleUtilsService FUNCTION: mergeHuddleMessageWithUser","color: green;"),e?.from?.userId){let i=this.usersService.getUserById(e?.from?.userId);i&&(e.from=i)}return e}catch(i){return this.loggingService.catch("Error in HuddleUtilsService mergeHuddleMessageWithUser:",i),e}}resolveUsersFromHuddleMessages(e){return ee(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling HuddleUtilsService FUNCTION: resolveUsersFromHuddleMessages","color: green;"),this.usersService.userDataProviderAvailable()){let i=this.getUserIdsToResolveFromHuddleMessages(e),r=yield this.usersService.resolveUsers(i);for(let a of e)a?.from?.userId&&r[a.from.userId]&&(a.from=r[a.from.userId])}return e}catch(i){return this.loggingService.catch("Error in HuddleUtilsService resolveUsersFromHuddleMessages:",i),e}})}formatHuddleMessageData(e){try{return this.loggingService.log("%c[WB] Calling HuddleUtilsService FUNCTION: formatHuddleMessageData","color: green;"),this.usersService.userDataProviderAvailable()&&e?.from?.userId&&(e.from={userId:e.from.userId}),e}catch(i){return this.loggingService.catch("Error in HuddleUtilsService formatHuddleMessageData:",i),e}}};o.\u0275fac=function(i){return new(i||o)(J(y),J(Hn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var dse=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.usersService=i}getUserIdsToResolveFromLiveStateCustom(e){try{let i=new Set;return e?.updatedBy&&i.add(e?.updatedBy?.userId),Array.from(i)}catch(i){return this.loggingService.catch("Error in LiveStateUtilsService getUserIdsToResolveFromLiveStateCustom:",i),[]}}mergeLiveStateCustomWithUser(e){try{if(e?.updatedBy?.userId){let i=this.usersService.getUserById(e?.updatedBy?.userId);i&&(e.updatedBy=i)}return e}catch(i){return this.loggingService.catch("Error in LiveStateUtilsService mergeLiveStateCustomWithUser:",i),e}}formatLiveStateCustomData(e){try{return this.usersService.userDataProviderAvailable()&&e?.updatedBy&&(e.updatedBy={userId:e.updatedBy.userId}),e}catch(i){return this.loggingService.catch("Error in LiveStateUtilsService formatLiveStateCustomData:",i),e}}getUserIdsToResolveFromLiveStateCustoms(e){try{let i=new Set;for(let r of e)r?.updatedBy?.userId&&i.add(r?.updatedBy?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in LiveStateUtilsService getUserIdsToResolveFromLiveStateCustoms:",i),[]}}getUserIdsToResolveFromLiveStates(e){try{let i=new Set;return e?.default?.singleEditorMode?.editor?.userId&&i.add(e?.default?.singleEditorMode?.editor?.userId),Array.from(i)}catch(i){return this.loggingService.catch("Error in LiveStateUtilsService getUserIdsToResolveFromLiveStates:",i),[]}}mergeLiveStateWithUser(e){try{if(e?.default?.singleEditorMode?.editor?.userId){let i=this.usersService.getUserById(e?.default?.singleEditorMode?.editor?.userId);i&&(e.default.singleEditorMode.editor=i)}if(e?.default?.singleEditorMode?.requestEditorAccess?.user?.userId){let i=this.usersService.getUserById(e?.default?.singleEditorMode?.requestEditorAccess?.user?.userId);i&&(e.default.singleEditorMode.requestEditorAccess.user=i)}return e}catch(i){return this.loggingService.catch("Error in LiveStateUtilsService mergeLiveStateWithUser:",i),e}}formatLiveStateSingleEditorModeData(e){try{return this.usersService.userDataProviderAvailable()&&(e?.editor?.userId&&(e.editor={userId:e.editor.userId}),e?.requestEditorAccess?.user?.userId&&(e.requestEditorAccess.user={userId:e.requestEditorAccess.user.userId})),e}catch(i){return this.loggingService.catch("Error in LiveStateUtilsService formatLiveStateSingleEditorModeData:",i),e}}mergeLiveStateCustomsWithUsers(e){try{for(let i of e)if(i?.updatedBy?.userId){let r=this.usersService.getUserById(i?.updatedBy?.userId);r&&(i.updatedBy=r)}return e}catch(i){return this.loggingService.catch("Error in mergeLiveStateCustomsWithUsers:",i),e}}};o.\u0275fac=function(i){return new(i||o)(J(y),J(Hn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var pse=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.usersService=i}getUserIdsToResolveFromMultiThreads(e){try{let i=new Set;for(let r of e)r?.from?.userId&&i.add(r?.from?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in MultiThreadUtilsService getUserIdsToResolveFromMultiThreads:",i),[]}}mergeMultiThreadWithUser(e){try{if(e?.from?.userId){let i=this.usersService.getUserById(e?.from?.userId);i&&(e.from=i)}return e}catch(i){return this.loggingService.catch("Error in MultiThreadUtilsService mergeMultiThreadWithUser:",i),e}}formatMultiThreadData(e){try{return this.usersService.userDataProviderAvailable()&&(e?.from?.userId&&(e.from={userId:e.from.userId}),e?.commentAnnotationsMap&&(e.commentAnnotationsMap=null)),e}catch(i){return this.loggingService.catch("Error in MultiThreadUtilsService formatMultiThreadData:",i),e}}};o.\u0275fac=function(i){return new(i||o)(J(y),J(Hn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var jv=(()=>{let o=class o{constructor(e,i,r){this.authService=e,this.loggingService=i,this.usersService=r}getUserIdsToResolveFromRecorders(e){try{let i=new Set;for(let r of e)r?.from?.userId&&i.add(r?.from?.userId),r?.transcription?.from?.userId&&i.add(r?.transcription?.from?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in RecorderUtilsService getUserIdsToResolveFromRecorders:",i),[]}}mergeRecorderWithUser(e){try{if(e?.from?.userId){let i=this.usersService.getUserById(e?.from?.userId);i&&(e.from=i)}if(e?.transcription?.from?.userId){let i=this.usersService.getUserById(e?.transcription?.from?.userId);i&&(e.transcription.from=i)}return e}catch(i){return this.loggingService.catch("Error in RecorderUtilsService mergeRecorderWithUser:",i),e}}formatRecorderData(e,i){try{return e.transcription=e?.transcription?T(I({},e.transcription),{lastUpdated:i}):void 0,this.usersService.userDataProviderAvailable()&&(e?.from?.userId&&(e.from={userId:e.from.userId}),e?.transcription?.from?.userId&&(e.transcription.from={userId:e.transcription.from.userId})),e}catch(r){return this.loggingService.catch("Error in RecorderUtilsService formatRecorderData:",r),e}}formatRecorderDataForWhisperTranscription(e){try{return this.usersService.userDataProviderAvailable()&&e?.fromUser?.userId&&(e.fromUser={userId:e.fromUser?.userId}),e}catch(i){return this.loggingService.catch("Error in RecorderUtilsService formatRecorderDataForWhisperTranscription:",i),e}}encryptRecorderAnnotation(e){return ee(this,null,function*(){try{return yield bp(e,this.authService.getUser()?.userId??"")}catch(i){this.loggingService.catch("Error in RecorderUtilsService encryptRecorderAnnotation:",i);return}})}};o.\u0275fac=function(i){return new(i||o)(J(je),J(y),J(Hn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var TM=(()=>{let o=class o{constructor(e,i,r,a,s,c){this.commentUtilsService=e,this.recorderUtilsService=i,this.loggingService=r,this.usersService=a,this.authService=s,this.commentAnnotationsResolverService=c}getUserIdsToResolveFromNotifications(e){try{let i=new Set;for(let r of e){let{notification:a}=r;switch(a?.actionUser?.userId&&i.add(a?.actionUser?.userId),a?.displayHeadlineMessageTemplateData?.actionUser?.userId&&i.add(a?.displayHeadlineMessageTemplateData?.actionUser?.userId),a?.displayHeadlineMessageTemplateData?.recipientUser?.userId&&i.add(a?.displayHeadlineMessageTemplateData?.recipientUser?.userId),a?.notificationSource){case"comment":if(a?.notificationSourceData){let s=this.commentUtilsService.getUserIdsToResolveFromComments([a?.notificationSourceData]);for(let c of s)i.add(c)}break}}return Array.from(i)}catch(i){return this.loggingService.catch("Error in ReactionUtilsService getUserIdsToResolveFromRecorders:",i),[]}}mergeStrippedDataWithNotification(e){try{if(this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: mergeStrippedDataWithNotification","color: green;"),!this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())return e;let i=this.commentAnnotationsResolverService.getAnnotationById(e?.notification?.targetAnnotationId),r=e?.raw?.targetAnnotationData?.commentId,a=i?.comments?.[r]?.commentText,s=i?.comments?.[r]?.commentHtml;return a&&s&&e?.raw?.notificationSource==="comment"&&(e.notification.displayBodyMessageTemplate=a,e.raw.targetAnnotationData.commentText=a,e.raw.targetAnnotationData.commentHtml=s),e}catch(i){return this.loggingService.catch("Error in NotificationUtilsService mergeStrippedDataWithNotification:",i),e}}mergeLocationWithNotification(e,i){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: mergeLocationWithNotification","color: green;");let r=e?.notification?.notificationSourceData?.location?.id,a=e?.notification?.notificationSourceData?.metadata?.documentId;if(!r||!a)return e;let s=i?.[a]?.[r];return s&&(e.notification.notificationSourceData.location=s?.location,e?.raw?.annotationData?.location&&(e.raw.annotationData.location=s?.location)),e}catch(r){return this.loggingService.catch("Error in NotificationUtilsService mergeLocationWithNotification:",r),e}}mergeNotificationWithUser(e){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: mergeNotificationWithUser","color: green;");let{notification:i}=e;if(i?.actionUser?.userId){let r=this.usersService.getUserById(i?.actionUser?.userId);r&&(i.actionUser=r)}if(i?.displayHeadlineMessageTemplateData?.actionUser?.userId){let r=this.usersService.getUserById(i?.displayHeadlineMessageTemplateData?.actionUser?.userId);r&&(i.displayHeadlineMessageTemplateData.actionUser=r)}if(i?.displayHeadlineMessageTemplateData?.recipientUser?.userId){let r=this.usersService.getUserById(i?.displayHeadlineMessageTemplateData?.recipientUser?.userId);r&&(i.displayHeadlineMessageTemplateData.recipientUser=r)}switch(i?.notificationSource){case"comment":i?.notificationSourceData&&this.commentUtilsService.mergeCommentWithUser(i?.notificationSourceData);break}return e}catch(i){return this.loggingService.catch("Error in NotificationUtilsService mergeNotificationWithUser:",i),e}}formatNotification(e,i){try{switch(typeof e=="object"&&(e=JSON.parse(JSON.stringify(e))),this.usersService.userDataProviderAvailable()&&e?.actionUser&&(e.actionUser={userId:e.actionUser.userId}),e.notificationSource){case"comment":this.commentUtilsService.formatCommentData(e.annotationData),this.commentUtilsService.formatCommentThreadData(e.targetAnnotationData);break;case"recorder":this.recorderUtilsService.formatRecorderData(e.annotationData,i);break}return e}catch(r){return this.loggingService.catch("Error in NotificationUtilsService formatNotification: ",r),e}}getTargetAnnotationIdsFromNotifications(e){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: getTargetAnnotationIdsFromNotifications","color: green;");let i=[];return Object.values(e).forEach(r=>{r?.notification?.targetAnnotationId&&r?.raw?.notificationSource==="comment"&&i.push(r.notification.targetAnnotationId)}),i}catch(i){return this.loggingService.catch("Error in NotificationUtilsService getTargetAnnotationIdsFromNotifications:",i),[]}}handleNotificationEncryption(i){return ee(this,arguments,function*({data:e}){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: handleNotificationEncryption","color: green;");let r="notificationwithdocumentidstoencryptanddecryptonsdk"+(this.authService.getUser()?.userId??"");return yield bp(e,r)}catch(r){return this.loggingService.catch("Error in NotificationUtilsService handleNotificationEncryption:",r),e}})}};o.\u0275fac=function(i){return new(i||o)(J(Uv),J(jv),J(y),J(Hn),J(je),J(vs))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var use=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.usersService=i}getUserIdsToResolveFromPresenceUsers(e){try{let i=new Set;for(let r of e)r?.userId&&i.add(r?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in PresenceUtilsService getUserIdsToResolveFromPresenceUsers:",i),[]}}mergePresenceUserWithUser(e){try{if(this.usersService.userDataProviderAvailable()&&e?.userId){let i=this.usersService.getUserById(e?.userId);i&&(e=I(I({},e),i))}return e}catch(i){return this.loggingService.catch("Error in PresenceUtilsService mergePresenceUserWithUser:",i),e}}formatPresenceUserData(e){try{if(this.usersService.userDataProviderAvailable()){let i=["userId","onlineStatus","userSnippylyId","color","textColor","timestamp","type","selections","documentParamsId","documentParams","locationId","location","isReadOnly","isAnonymous","pageInfo"];Object.keys(e).forEach(r=>{i.includes(r)||(e[r]=null)})}return e}catch(i){return this.loggingService.catch("Error in PresenceUtilsService formatPresenceUserData:",i),e}}};o.\u0275fac=function(i){return new(i||o)(J(y),J(Hn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var hse=(()=>{let o=class o{constructor(e,i,r,a,s,c){this.loggingService=e,this.usersService=i,this.authService=r,this.functions=a,this.configService=s,this.reactionAnnotationsResolverService=c}getUserIdsToResolveFromReactions(e){try{let i=new Set;for(let r of e)if(r?.from?.userId&&i.add(r?.from?.userId),r?.reactions?.length)for(let a of r?.reactions)a?.from?.userId&&i.add(a?.from?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in ReactionUtilsService getUserIdsToResolveFromRecorders:",i),[]}}handleReactionEncryption(a){return ee(this,arguments,function*({data:e,firestorePath:i,eventType:r}){try{let s=$O(this.authService.getFirebaseConfig()?.firebaseOptions),c=Cr(this.functions,Zn.cloudFunction?.[s]?.setEncryptedData,{timeout:20*60*1e3}),p=Fp.getFirestoreProdDbName(this.configService.getApiKey()??"",this.authService.getFirebaseConfig()?.firebaseOptions),h=this.authService.getUser()?.userId??"",_={path:i??"",data:e??{},dbId:p??"",feature:"reaction",eventType:r??"PATCH",sdkVersion:Ta()},E=yield bp(_,h);yield c({veltData:E})}catch(s){this.loggingService.catch("Error in handleReactionEncryption:",s)}})}mergeReactionWithUser(e){try{if(this.usersService.userDataProviderAvailable()){if(e?.from?.userId){let i=this.usersService.getUserById(e?.from?.userId);i&&(e.from=i)}if(e?.reactions?.length){for(let i of e?.reactions)if(i?.from?.userId){let r=this.usersService.getUserById(i?.from?.userId);r&&(i.from=r)}}}return e}catch(i){return this.loggingService.catch("Error in ReactionUtilsService mergeReactionWithUser:",i),e}}formatReactionData(e){try{return this.usersService.userDataProviderAvailable()&&e?.from?.userId&&(e.from={userId:e.from.userId}),e.reactions=e?.reactions?.map(i=>(this.usersService.userDataProviderAvailable()&&i?.from?.userId&&(i.from={userId:i.from.userId}),i)),e}catch(i){return this.loggingService.catch("Error in ReactionUtilsService formatReactionData:",i),e}}isReactionDataChanged(e,i){try{this.loggingService.log("%c[WB] Calling ReactionUtilsService FUNCTION: isReactionDataChanged","color: green;");let r=this.reactionAnnotationsResolverService.getReactionAnnotationById(i);return r?!Co(e,r):!0}catch(r){return this.loggingService.catch("Error in ReactionUtilsService isReactionDataChanged:",r),!0}}stripReactionAnnotationData(e){try{if(this.loggingService.log("%c[WB] Calling ReactionUtilsService FUNCTION: stripReactionAnnotationData","color: green;"),!this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable())return{originalData:e,strippedData:null};let i={};if(e&&e.annotationId){let r=e.annotationId;if(i[r]={annotationId:r,metadata:sv(e.metadata??{}),icon:e.icon},!this.isReactionDataChanged(i[r],r))return{strippedData:null,originalData:e};delete e?.icon,e.isReactionResolverUsed=!0}return{strippedData:i,originalData:e}}catch(i){return this.loggingService.catch("Error in ReactionUtilsService stripReactionAnnotationData:",i),{strippedData:null,originalData:null}}}mergeStrippedDataWithReactionAnnotations(e){try{if(this.loggingService.log("%c[WB] Calling ReactionUtilsService FUNCTION: mergeStrippedDataWithReactionAnnotations","color: green;"),!this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable())return e;let i=this.reactionAnnotationsResolverService.getReactionAnnotationById(e?.annotationId);return i&&i.icon&&(e.icon=i.icon),e}catch(i){return this.loggingService.catch("Error in ReactionUtilsService mergeStrippedDataWithReactionAnnotations:",i),e}}};o.\u0275fac=function(i){return new(i||o)(J(y),J(Hn),J(je),J(Vo),J($t),J(um))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var fse=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.usersService=i}getUserIdsToResolveFromSelections(e){try{let i=new Set;for(let r of e)r?.user?.userId&&i.add(r.user.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in SelectionUtilsService getUserIdsToResolveFromSelections:",i),[]}}mergeSelectionWithUser(e){try{if(e?.user?.userId){let i=this.usersService.getUserById(e?.user?.userId);i&&(e.user=i)}return e}catch(i){return this.loggingService.catch("Error in SelectionUtilsService mergeSelectionWithUser:",i),e}}formatSelectionData(e){try{return this.usersService.userDataProviderAvailable()&&e?.user?.userId&&(e.user={userId:e.user.userId}),e}catch(i){return this.loggingService.catch("Error in SelectionUtilsService formatSelectionData:",i),e}}};o.\u0275fac=function(i){return new(i||o)(J(y),J(Hn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var vse=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.usersService=i}getUserIdsToResolveFromTags(e){try{let i=new Set;for(let r of e)if(r?.from?.userId&&i.add(r.from.userId),r?.to?.length)for(let a of r.to)a?.userId&&i.add(a.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in TagUtilsService getUserIdsToResolveFromTags:",i),[]}}mergeTagWithUser(e){try{if(e?.from?.userId){let i=this.usersService.getUserById(e?.from?.userId);i&&(e.from=i)}return e?.to?.length&&(e.to=e.to.map(i=>{if(i?.userId){let r=this.usersService.getUserById(i?.userId);r&&(i=r)}return i})),e}catch(i){return this.loggingService.catch("Error in TagUtilsService mergeTagWithUser:",i),e}}formatTagData(e){try{return this.usersService.userDataProviderAvailable()&&(e?.from?.userId&&(e.from={userId:e.from.userId}),e?.to?.length&&(e.to=e.to.map(i=>(i?.userId&&(i={userId:i.userId}),i)))),e}catch(i){return this.loggingService.catch("Error in TagUtilsService formatTagData:",i),e}}};o.\u0275fac=function(i){return new(i||o)(J(y),J(Hn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var $v=(()=>{let o=class o{constructor(e,i,r,a,s,c,p,h,_,E,D,B,G,X,he,Ie,Me,Le,We){this.areaUtilsService=e,this.arrowUtilsService=i,this.commentUtilsService=r,this.contactUtilsService=a,this.cursorUtilsService=s,this.huddleUtilsService=c,this.liveStateUtilsService=p,this.loggingService=h,this.multiThreadUtilsService=_,this.notificationUtilsService=E,this.presenceUtilsService=D,this.reactionUtilsService=B,this.recorderUtilsService=G,this.selectionUtilsService=X,this.tagUtilsService=he,this.usersService=Ie,this.docService=Me,this.commentAnnotationsResolverService=Le,this.reactionAnnotationsResolverService=We}getFirestorePath({feature:e,properties:i,documentPaths:r,apiKey:a}){try{if(!a)return;let{documentId:s,organizationId:c,folderId:p}=i;c||(c=r?.organizationId);let h=new bM({apiKey:a,documentId:s?`${s}`:"",organizationId:c?`${c}`:"",veltFolderId:p?`${p}`:void 0});switch(e){case"comment":return i?.documentId&&i?.id&&h?.comment?`${h?.comment}/${i?.id}`:void 0;case"allComments":return i?.documentId&&h?.comment?`${h?.comment}`:void 0;case"multiThread":return i?.documentId&&i?.id&&h?.multiThread?`${h?.multiThread}/${i?.id}`:void 0;case"allMultiThreads":return i?.documentId&&h?.multiThread?`${h?.multiThread}`:void 0;case"allLastNotificationTimestamp":return h?.lastNotificationTimestamp?`${h?.lastNotificationTimestamp}`:void 0;case"lastNotificationTimestamp":return i?.id&&h?.lastNotificationTimestamp?`${h?.lastNotificationTimestamp}/${i?.id}`:void 0;case"area":return i?.documentId&&i?.id&&h?.area?`${h?.area}/${i?.id}`:void 0;case"allAreas":return i?.documentId&&h?.area?`${h?.area}`:void 0;case"allDocuments":return h?.document?`${h?.document}`:void 0;case"allLocations":return h?.location?`${h?.location}`:void 0;case"allFolders":return h?.folder?`${h?.folder}`:void 0;case"folder":return h?.folder&&i.folderId?`${h?.folder}/${i.folderId}`:void 0;case"documentUserAccess":return i?.documentId&&i?.id&&h?.documentUsers?`${h?.documentUsers}/${i?.id}`:void 0;case"reaction":return i?.documentId&&i?.id&&h?.reaction?`${h?.reaction}/${i?.id}`:void 0;case"allReactions":return i?.documentId&&h?.reaction?`${h?.reaction}`:void 0;case"recorder":return i?.documentId&&i?.id&&h?.recorder?`${h?.recorder}/${i?.id}`:void 0;case"allRecorders":return i?.documentId&&h?.recorder?`${h?.recorder}`:void 0;case"documentAccessType":return i?.documentId&&h?.document?`${h?.document}/${i?.documentId}`:void 0;case"organizationMetadata":return h?.organization?`${h?.organization}`:void 0;case"documentIam":case"documentMetadata":return i?.documentId&&h?.document?`${h?.document}/${i?.documentId}`:void 0;case"folderMetadata":return i?.folderId&&h?.folder?`${h?.folder}/${i?.folderId}`:void 0;case"locationMetadata":return i?.documentId&&h?.location&&i?.id?`${h?.location}/${i?.id}`:void 0;case"documentUser":return i?.documentId&&i?.id&&h?.documentUsers?`${h?.documentUsers}/${i?.id}`:void 0;case"allDocumentUsers":return i?.documentId&&h?.documentUsers?`${h?.documentUsers}`:void 0;case"allFolderUsers":return i?.folderId&&h?.folderUsers?`${h?.folderUsers}`:void 0;case"allOrganizationGroups":return h?.organizationGroups?`${h?.organizationGroups}`:void 0;case"allOrganizationUsers":return h?.organizationUsers?`${h?.organizationUsers}`:void 0;case"commentViews":return i?.documentId&&i?.id&&h?.commentViews?`${h?.commentViews}/${i?.id}`:void 0;case"allCommentViews":return i?.documentId&&h?.commentViews?`${h?.commentViews}`:void 0;case"notificationViewsTimestamp":return i?.documentId&&i?.id&&h?.notificationViews?`${h?.notificationViews}/${i?.id}`:void 0;case"allDocumentViews":return i?.documentId&&h?.documentViews?`${h?.documentViews}`:void 0;case"documentViews":case"documentMetadataViews":case"documentDayViews":case"documentUsersViews":return i?.documentId&&i?.id&&h?.documentViews?`${h?.documentViews}/${i?.id}`:void 0;case"locationDayViews":case"locationUsersViews":case"locationViews":case"locationMetadataViews":case"location":return i?.documentId&&i?.id&&h?.locationViews?`${h?.locationViews}/${i?.id}`:void 0;case"allLocationViews":return i?.documentId&&h?.locationViews?`${h?.locationViews}`:void 0;case"allDocNotifications":return i?.documentId&&h?.docNotification?`${h?.docNotification}`:void 0;case"docNotificationViews":case"docNotification":return i?.documentId&&i?.id&&h?.docNotification?`${h?.docNotification}/${i?.id}`:void 0;case"userNotificationViews":case"userNotification":return i?.userId&&i?.id&&h?.notificationUsers?`${h?.notificationUsers}/${i?.userId}/${U.FIREBASE_PARTIAL_PATH_USER_NOTIFICATION}/${i?.id}`:void 0;case"allDocNotifications":return i?.documentId&&h?.docNotification?`${h?.docNotification}`:void 0;case"allUserNotifications":return i?.userId&&h?.notificationUsers?`${h?.notificationUsers}/${i?.userId}/${U.FIREBASE_PARTIAL_PATH_USER_NOTIFICATION}`:void 0;default:throw new Error(`Unknown feature: ${e}`)}}catch(s){this.loggingService.catch("Error in CommonDbUtilsService getFirestorePath:",s);return}}getFirestoreCollectionGroupPath(e){try{switch(e){case"allComments":return U.FIREBASE_PARTIAL_PATH_COMMENT;case"allDocuments":return U.FIREBASE_PARTIAL_PATH_DOCS;case"allLocations":return U.FIREBASE_PARTIAL_PATH_LOCATION;case"allMultiThreads":return U.FIREBASE_PARTIAL_PATH_MULTI_THREAD;case"allAreas":return U.FIREBASE_PARTIAL_PATH_AREA;case"allReactions":return U.FIREBASE_PARTIAL_PATH_REACTION;case"allRecorders":return U.FIREBASE_PARTIAL_PATH_RECORDER;case"allDocumentViews":return U.FIREBASE_PARTIAL_PATH_DOCUMENT_VIEWS;case"allCommentViews":return U.FIREBASE_PARTIAL_PATH_COMMENT_VIEWS;case"allLocationViews":return U.FIREBASE_PARTIAL_PATH_LOCATION_VIEWS;case"allDocumentUsers":return U.FIREBASE_PARTIAL_PATH_DOCUMENT_USERS;case"allFolderUsers":return U.FIREBASE_PARTIAL_PATH_FOLDER_USERS;default:throw new Error(`Unknown feature: ${e}`)}}catch(i){this.loggingService.catch("Error in CommonDbUtilsService getFirestoreCollectionGroupPath:",i);return}}getDocumentPath({feature:e,properties:i,defaultDocumentPaths:r,apiKey:a,useFirestore:s}){try{if(!a)return;let{documentId:c,organizationId:p}=i;p||(p=r?.organizationId);let h=new xd({apiKey:a,documentId:c?`${c}`:"",organizationId:p?`${p}`:""});switch(e){case"allComments":return!s&&i?.documentId&&h?.comment?`${h?.comment}`:void 0;case"allGlobalContacts":return i?.documentId&&h?.globalContacts?`${h?.globalContacts}`:void 0;case"globalContacts":return i?.documentId&&i?.userId&&h?.globalContacts?`${h?.globalContacts}${i?.userId}`:void 0;case"groupContacts":return i?.documentId&&i?.groupId&&h?.groupContacts?`${h?.groupContacts}${i?.groupId}`:void 0;case"groupContactsUser":return i?.documentId&&i?.groupId&&i?.userId&&h?.groupContacts?`${h?.groupContacts}${i?.groupId}/${i?.userId}`:void 0;case"allLoginContacts":return i?.documentId&&i?.userId&&h?.logins?`${h?.logins}${i?.userId}/contacts`:void 0;case"allLogins":return i?.documentId&&h?.logins?`${h?.logins}`:void 0;case"logins":return i?.documentId&&i?.userId&&h?.logins?`${h?.logins}${i?.userId}`:void 0;case"customerMetadata":return h?.customerMetadata?`${h?.customerMetadata}`:void 0;case"allArrows":return i?.documentId&&h?.arrow?`${h?.arrow}`:void 0;case"arrow":return i?.documentId&&h?.arrow&&i.id?`${h?.arrow}${i.id}`:void 0;case"allCursors":return i?.documentId&&h?.cursor?`${h?.cursor}`:void 0;case"cursor":return i?.documentId&&h?.cursor&&i.id?`${h?.cursor}${i.id}`:void 0;case"flockUser":return i?.documentId&&h?.flock&&i.id?`${h?.flock}users/${i.id}`:void 0;case"flockSession":return i?.documentId&&h?.flock&&i.id?`${h?.flock}sessions/${i.id}`:void 0;case"allHuddleAttendees":return i?.documentId&&h?.huddle?`${h?.huddle}attendees`:void 0;case"huddleAttendee":return i?.documentId&&h?.huddle&&i.id?`${h?.huddle}attendees/${i.id}`:void 0;case"huddleAttendeeState":return i?.documentId&&h?.huddle&&i.id?`${h?.huddle}attendees/${i.id}/state`:void 0;case"allHuddleInvitees":return i?.documentId&&h?.huddle?`${h?.huddle}invitees`:void 0;case"huddleConnection":return i?.documentId&&h?.huddle&&i.id?`${h?.huddle}connections/${i.id}`:void 0;case"huddleIceCandidate":return i?.documentId&&h?.huddle&&i.id?`${h?.huddle}iceCandidates/${i.id}`:void 0;case"allHuddleIceCandidates":return i?.documentId&&h?.huddle?`${h?.huddle}iceCandidates`:void 0;case"allHuddleMessages":return i?.documentId&&h?.huddle?`${h?.huddle}messages`:void 0;case"huddleMessage":return i?.documentId&&h?.huddle&&i.id?`${h?.huddle}messages/${i.id}`:void 0;case"allLiveStates":return i?.documentId&&h?.liveState?`${h?.liveState}`:void 0;case"allLiveStateCustoms":return i?.documentId&&h?.liveState?`${h?.liveState}custom`:void 0;case"liveStateCustom":return i?.documentId&&h?.liveState&&i?.id?`${h?.liveState}custom/${i.id}`:void 0;case"liveStateSingleEditorMode":return i?.documentId&&h?.liveStateSingleEditorMode?`${h?.liveStateSingleEditorMode}`:void 0;case"liveStateAutoSyncStateCurrent":return i?.documentId&&h?.liveState?`${h?.liveState}default/autoSyncState/current`:void 0;case"liveStateAutoSyncStateHistoryId":return i?.documentId&&h?.liveState&&i?.id?`${h?.liveState}default/autoSyncState/history/${i.id}`:void 0;case"presence":return i?.documentId&&h?.presence&&i?.userId?`${h?.presence}${i?.userId}`:void 0;case"allPresence":return i?.documentId&&h?.presence?`${h?.presence}`:void 0;case"workspaceIam":return h?.workspaceIam?`${h?.workspaceIam}`:void 0;case"selection":return i?.documentId&&h?.selection&&i?.userId?`${h?.selection}${i?.userId}`:void 0;case"allSelections":return i?.documentId&&h?.selection?`${h?.selection}`:void 0;case"syncVideoPlayer":return i?.documentId&&h?.syncVideoPlayer?`${h?.syncVideoPlayer}`:void 0;case"allTags":return i?.documentId&&h?.tag?`${h?.tag}`:void 0;case"tag":return i?.documentId&&h?.tag&&i?.id?`${h?.tag}${i?.id}`:void 0;case"userContactUs":return i?.documentId&&h?.userContactUs?`${h?.userContactUs}`:void 0;case"userFeedback":return i?.documentId&&h?.userFeedback?`${h?.userFeedback}`:void 0;case"userReportBug":return i?.documentId&&h?.userReportBugs?`${h?.userReportBugs}`:void 0;case"comment":return!s&&i?.documentId&&i?.id&&h?.comment?`${h?.comment}${i?.id}`:void 0;case"allMultiThreads":return!s&&i?.documentId&&h?.multiThread?`${h?.multiThread}`:void 0;case"multiThread":return!s&&i?.documentId&&i?.id&&h?.multiThread?`${h?.multiThread}${i?.id}`:void 0;case"allLastNotificationTimestamp":return!s&&h?.organizationNotificationsLastNotificationTimestamp?`${h?.organizationNotificationsLastNotificationTimestamp}`:void 0;case"lastNotificationTimestamp":return!s&&i?.id&&h?.organizationNotificationsLastNotificationTimestamp?`${h?.organizationNotificationsLastNotificationTimestamp}${i?.id}`:void 0;case"documentIam":return!s&&i?.documentId&&h?.documentIam?`${h?.documentIam}`:void 0;case"documentMetadata":return!s&&i?.documentId&&h?.metadata?`${h?.metadata}`:void 0;case"allDocuments":return!s&&h?.docs&&i?.documentId?`${h?.docs}/${i?.documentId}/${U.FIREBASE_PARTIAL_PATH_METADATA}`:void 0;case"allAreas":return!s&&i?.documentId&&h?.area?`${h?.area}`:void 0;case"area":return!s&&i?.id&&h?.area?`${h?.area}${i?.id}`:void 0;case"documentUserAccess":return!s&&i?.id&&h?.documentIam?`${h?.documentIam}users/${i?.id}`:void 0;case"documentUser":return!s&&i?.documentId&&i?.id&&h?.documentIam?`${h?.documentIam}users/${i?.id}`:void 0;case"allDocumentUsers":return!s&&i?.documentId&&h?.documentIam?`${h?.documentIam}users/`:void 0;case"allOrganizationGroups":return!s&&h?.organizationGroups?`${h?.organizationGroups}`:void 0;case"allOrganizationUsers":return!s&&h?.organizationIam?`${h?.organizationIam}users/`:void 0;case"reaction":return!s&&i?.id&&h?.reaction?`${h?.reaction}${i?.id}`:void 0;case"allReactions":return!s&&i?.documentId&&h?.reaction?`${h?.reaction}`:void 0;case"recorder":return!s&&i?.documentId&&i?.id&&h?.recorder?`${h?.recorder}${i?.id}`:void 0;case"allRecorders":return!s&&i?.documentId&&h?.recorder?`${h?.recorder}`:void 0;case"organizationMetadata":return!s&&h?.organizationMetadata?`${h?.organizationMetadata}`:void 0;case"documentAccessType":return!s&&h?.documentIam?`${h?.documentIam}`:void 0;case"documentIam":return!s&&h?.documentIam?`${h?.documentIam}`:void 0;case"documentMetadata":return!s&&i?.documentId&&h?.metadata?`${h?.metadata}`:void 0;case"commentViews":return!s&&i?.documentId&&i?.id&&h?.views?`${h?.views}comment/${i?.id}`:void 0;case"allDocumentViews":return!s&&i?.documentId&&h?.views?`${h?.views}documentViews/`:void 0;case"documentViews":return!s&&i?.documentId&&i?.id&&h?.views?`${h?.views}documentViews/${i?.id}`:void 0;case"allCommentViews":return!s&&i?.documentId&&h?.views?`${h?.views}comment/`:void 0;case"allLocationViews":return!s&&i?.documentId&&h?.views?`${h?.views}locationViews/`:void 0;case"notificationViewsTimestamp":return!s&&i?.id&&i?.user&&h?.views?`${h?.views}notification/${i?.id}/views/${i?.user}`:void 0;case"documentUsersViews":return!s&&i?.id&&i?.user&&i?.date&&h?.views?`${h?.views}documentViews/${i?.id}/users/${i?.user}/${i?.date}`:void 0;case"documentMetadataViews":return!s&&i?.id&&h?.views?`${h?.views}documentViews/${i?.id}/metadata`:void 0;case"documentDayViews":return!s&&i?.id&&i?.date&&i?.user&&h?.views?`${h?.views}documentViews/${i?.id}/day/${i?.date}/${i?.user}`:void 0;case"locationViews":return!s&&i?.id&&h?.views?`${h?.views}locationViews/${i?.id}/location`:void 0;case"location":return!s&&i?.id&&h?.views?`${h?.views}locationViews/${i?.id}`:void 0;case"locationUsersViews":return!s&&i?.id&&i?.user&&i?.date&&h?.views?`${h?.views}locationViews/${i?.id}/users/${i?.user}/${i?.date}`:void 0;case"locationMetadataViews":return!s&&i?.id&&h?.views?`${h?.views}locationViews/${i?.id}/metadata`:void 0;case"locationDayViews":return!s&&i?.id&&i?.date&&i?.user&&h?.views?`${h?.views}locationViews/${i?.id}/day/${i?.date}/${i?.user}`:void 0;case"docNotificationViews":case"docNotification":return i?.documentId&&i?.id&&h?.organizationNotificationsWithDocumentId?`${h?.organizationNotificationsWithDocumentId}${i?.id}`:void 0;case"allDocNotifications":return i?.documentId&&h?.organizationNotificationsWithDocumentId?`${h?.organizationNotificationsWithDocumentId}`:void 0;case"allUserNotifications":return i?.userId&&h?.organizationNotificationsUsers?`${h?.organizationNotificationsUsers}${i?.userId}`:void 0;case"userNotificationViews":case"userNotification":return i?.userId&&i?.id&&h?.organizationNotificationsUsers?`${h?.organizationNotificationsUsers}${i?.userId}/${i?.id}`:void 0;case"locationMetadata":return;case"allLocations":return;case"folderMetadata":return;default:throw new Error(`Unknown feature: ${e}`)}}catch(c){this.loggingService.catch("Error in CommonDbUtilsService getDocumentPath:",c);return}}resolveAnnotations(r){return ee(this,arguments,function*({data:e,feature:i}){try{if(e&&e?.length>0)switch(i){case"allComments":{this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable()&&this.commentAnnotationsResolverService.resolveCommentAnnotations({commentAnnotationIds:e,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""});break}case"allReactions":{this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable()&&this.reactionAnnotationsResolverService.resolveReactionAnnotations({reactionAnnotationIds:e,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""});break}default:break}}catch(a){this.loggingService.catch(`Error in CommonDbUtilsService resolveAnnotations: ${i}`,a)}})}formatResponse(c){return ee(this,arguments,function*({feature:e,data:i,shouldAwait:r=!1,forceResolve:a=!1,shouldCommentAnnotationsResolverAwait:s=!1}){try{if(this.usersService.userDataProviderAvailable()){let p=[];switch(e){case"allAreas":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.areaUtilsService.getUserIdsToResolveFromAreaAnnotations(Object.values(i)));break}case"allArrows":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.arrowUtilsService.getUserIdsToResolveFromArrowAnnotations(Object.values(i)));break}case"allCursors":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.cursorUtilsService.getUserIdsToResolveFromCursorUsers(Object.values(i)));break}case"allComments":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.commentUtilsService.getUserIdsToResolveFromComments(Object.values(i)));break}case"allDocumentUsers":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.contactUtilsService.getUserIdsToResolveFromUserIamData(Object.values(i)));break}case"allFolderUsers":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.contactUtilsService.getUserIdsToResolveFromUserIamData(Object.values(i)));break}case"allOrganizationUsers":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.contactUtilsService.getUserIdsToResolveFromUserIamData(Object.values(i)));break}case"allMultiThreads":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.multiThreadUtilsService.getUserIdsToResolveFromMultiThreads(Object.values(i)));break}case"allDocNotifications":{i&&typeof i=="object"&&(p=this.notificationUtilsService.getUserIdsToResolveFromNotifications(Array.isArray(i)?i:Object.values(i)));break}case"allUserNotifications":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.notificationUtilsService.getUserIdsToResolveFromNotifications(Object.values(i)));break}case"allPresence":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.presenceUtilsService.getUserIdsToResolveFromPresenceUsers(Object.values(i)));break}case"allRecorders":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.recorderUtilsService.getUserIdsToResolveFromRecorders(Object.values(i)));break}case"allReactions":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.reactionUtilsService.getUserIdsToResolveFromReactions(Object.values(i)));break}case"allTags":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.tagUtilsService.getUserIdsToResolveFromTags(Object.values(i)));break}case"allHuddleAttendees":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.huddleUtilsService.getUserIdsToResolveFromHuddleAttendees(Object.values(i)));break}case"liveStateCustom":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.liveStateUtilsService.getUserIdsToResolveFromLiveStateCustom(i));break}case"allLiveStateCustoms":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.liveStateUtilsService.getUserIdsToResolveFromLiveStateCustoms(Object.values(i)));break}case"allLiveStates":{i&&typeof i=="object"&&(p=this.liveStateUtilsService.getUserIdsToResolveFromLiveStates(i));break}case"allSelections":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.selectionUtilsService.getUserIdsToResolveFromSelections(Object.values(i)));break}default:p=[]}p?.length&&(r?yield this.usersService.resolveUsers(p,a):this.usersService.resolveUsers(p,a))}if(this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable()){let p=[];switch(e){case"allDocNotifications":{if(i&&typeof i=="object"){let h=this.notificationUtilsService.getTargetAnnotationIdsFromNotifications(i);p=[...p,...h],p=p.filter(_=>!this.commentAnnotationsResolverService.getCommentAnnotationById(_))}break}case"allUserNotifications":{if(i&&typeof i=="object"&&!Array.isArray(i)){let h=this.notificationUtilsService.getTargetAnnotationIdsFromNotifications(i);p=[...p,...h],p=p.filter(_=>!this.commentAnnotationsResolverService.getCommentAnnotationById(_))}break}default:p=[]}p?.length&&(s?yield this.commentAnnotationsResolverService.resolveCommentAnnotations({commentAnnotationIds:p,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""}):this.commentAnnotationsResolverService.resolveCommentAnnotations({commentAnnotationIds:p,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""}))}return i}catch(p){return this.loggingService.catch("Error in CommonDbUtilsService formatResponse:",p),i}})}mergeCommentAnnotationsWithData({data:e,feature:i}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeCommentAnnotationsWithData","color: green;"),this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())switch(i){case"allComments":return e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).reduce((r,[a,s])=>(r[a]=this.commentUtilsService.mergeStrippedDataWithCommentAnnotations(s),r),{}):e;case"allDocNotifications":case"allUserNotifications":return e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).reduce((r,[a,s])=>(r[a]=this.notificationUtilsService.mergeStrippedDataWithNotification(s),r),{}):e;default:return e}return e}catch(r){return this.loggingService.catch("Error in CommonDbUtilsService mergeCommentAnnotationsWithData:",r),e}}mergeReactionAnnotationsWithData({data:e,feature:i}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeReactionAnnotationsWithData","color: green;"),this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable())switch(i){case"allReactions":return e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).reduce((r,[a,s])=>(r[a]=this.reactionUtilsService.mergeStrippedDataWithReactionAnnotations(s),r),{}):e;default:return e}return e}catch(r){return this.loggingService.catch("Error in CommonDbUtilsService mergeReactionAnnotationsWithData:",r),e}}mergeLocationMetadataWithData({data:e,feature:i,locationMetadata:r}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeLocationMetadataWithData","color: green;"),r&&typeof r=="object"&&!Array.isArray(r))switch(i){case"allComments":return e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).reduce((a,[s,c])=>(a[s]=this.commentUtilsService.mergeLocationWithCommentAnnotations(c,r),a),{}):e;case"allDocNotifications":case"allUserNotifications":return e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).reduce((a,[s,c])=>(a[s]=this.notificationUtilsService.mergeLocationWithNotification(c,r),a),{}):e;default:return e}return e}catch(a){return this.loggingService.catch("Error in CommonDbUtilsService mergeLocationMetadataWithData:",a),e}}mergeUsersWithData({feature:e,data:i}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeUsersWithData","color: green;"),this.usersService.userDataProviderAvailable())switch(e){case"allAreas":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.areaUtilsService.mergeAreaWithUser(s),r),{}):i;case"allArrows":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.arrowUtilsService.mergeArrowWithUser(s),r),{}):i;case"allCursors":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.cursorUtilsService.mergeCursorUserWithUser(s),r),{}):i;case"allComments":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.commentUtilsService.mergeCommentWithUser(s),r),{}):i;case"allDocumentUsers":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.contactUtilsService.mergeUserIamWithUser(s),r),{}):i;case"allFolderUsers":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.contactUtilsService.mergeUserIamWithUser(s),r),{}):i;case"allOrganizationUsers":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.contactUtilsService.mergeUserIamWithUser(s),r),{}):i;case"allMultiThreads":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.multiThreadUtilsService.mergeMultiThreadWithUser(s),r),{}):i;case"allDocNotifications":return i&&typeof i=="object"?i?.map(r=>this.notificationUtilsService.mergeNotificationWithUser(r)):i;case"allUserNotifications":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.notificationUtilsService.mergeNotificationWithUser(s),r),{}):i;case"allPresence":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.presenceUtilsService.mergePresenceUserWithUser(s),r),{}):i;case"allRecorders":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.recorderUtilsService.mergeRecorderWithUser(s),r),{}):i;case"allReactions":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.reactionUtilsService.mergeReactionWithUser(s),r),{}):i;case"allTags":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.tagUtilsService.mergeTagWithUser(s),r),{}):i;case"allHuddleAttendees":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.huddleUtilsService.mergeHuddleAttendeeWithUser(s),r),{}):i;case"liveStateCustom":return i&&typeof i=="object"&&!Array.isArray(i)?this.liveStateUtilsService.mergeLiveStateCustomWithUser(i):i;case"allLiveStateCustoms":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.liveStateUtilsService.mergeLiveStateCustomWithUser(s),r),{}):i;case"allLiveStates":return i&&typeof i=="object"?this.liveStateUtilsService.mergeLiveStateWithUser(i):i;case"allSelections":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.selectionUtilsService.mergeSelectionWithUser(s),r),{}):i;default:return i}return i}catch(r){return this.loggingService.catch("Error in CommonDbUtilsService mergeUsersWithData:",r),i}}mergeCommentAnnotationsWithData$({data:e,feature:i}){try{return this.commentAnnotationsResolverService.getCommentAnnotationsById$().pipe(ce(()=>{let r=this.mergeCommentAnnotationsWithData({data:e?.data??{},feature:i}),a=this.mergeUsersWithData({feature:i,data:r??{}});return typeof a=="object"?{data:JSON.parse(JSON.stringify(a)),operation:e?.operation??null}:{data:a,operation:e?.operation??null}}),Kt(_o))}catch(r){return this.loggingService.catch("Error in mergeCommentAnnotationsWithData:",r),re(e)}}mergeReactionAnnotationsWithData$({data:e,feature:i}){try{return this.reactionAnnotationsResolverService.getReactionAnnotationsById$().pipe(ce(()=>{let r=this.mergeReactionAnnotationsWithData({data:e?.data??{},feature:i}),a=this.mergeUsersWithData({feature:i,data:r??{}});return typeof a=="object"?{data:JSON.parse(JSON.stringify(a)),operation:e?.operation??null}:{data:a,operation:e?.operation??null}}),Kt(_o))}catch(r){return this.loggingService.catch("Error in mergeReactionAnnotationsWithData:",r),re(e)}}mergeUsersWithData$({feature:e,data:i}){try{return this.usersService.getUserById$().pipe(ce(()=>{let r=this.mergeUsersWithData({feature:e,data:i?.data??{}});return typeof r=="object"?{data:JSON.parse(JSON.stringify(r)),operation:i?.operation??null}:{data:r,operation:i?.operation??null}}),Kt(_o))}catch(r){return this.loggingService.catch(`Error in mergeUsersWithData for ${e}:`,r),re(i)}}mergeLocationMetadataWithData$({data:e,feature:i}){try{return this.docService.getLocationMetadata$().pipe(ce(r=>{let a=this.mergeLocationMetadataWithData({data:e?.data??{},feature:i,locationMetadata:r});return typeof a=="object"?{data:JSON.parse(JSON.stringify(a)),operation:e?.operation??null}:{data:a,operation:e?.operation??null}}),Kt(_o))}catch(r){return this.loggingService.catch(`Error in mergeLocationMetadataWithData for ${i}:`,r),re(e)}}handleDataStripping({feature:e,data:i,actionType:r}){try{switch(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: handleDataStripping","color: green;"),e){case"comment":return this.commentUtilsService.stripCommentAnnotationData({data:i,actionType:r});case"reaction":return this.reactionUtilsService.stripReactionAnnotationData(i);default:return{originalData:i,strippedData:null}}}catch(a){return this.loggingService.catch("Error in CommonDbUtilsService handleDataStripping:",a),{originalData:i,strippedData:null}}}formatData({feature:e,data:i,properties:r,offset:a,isRealtimeDb:s}){try{this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: formatData","color: green;"),typeof i=="object"&&(i=JSON.parse(JSON.stringify(i)));let c=new Date().getTime()+a;switch(e){case"documentAccessType":return delete i?.users,{docIamConfig:i};case"organizationMetadata":case"documentMetadata":return s?i:{metadata:i};case"cursor":return this.cursorUtilsService.formatCursorUserData(i);case"comment":return this.commentUtilsService.formatCommentData(i);case"area":return this.areaUtilsService.formatAreaData(i);case"arrow":return this.arrowUtilsService.formatArrowData(i);case"liveStateCustom":return this.liveStateUtilsService.formatLiveStateCustomData(i);case"liveStateSingleEditorMode":return this.liveStateUtilsService.formatLiveStateSingleEditorModeData(i);case"multiThread":return this.multiThreadUtilsService.formatMultiThreadData(i);case"reaction":return this.reactionUtilsService.formatReactionData(i);case"recorder":return this.recorderUtilsService.formatRecorderData(i,c);case"notificationViewsTimestamp":return{views:{[r.user??""]:i}};case"documentUsersViews":return s?i:{users:{[r.user??""]:{[r.date??""]:i}}};case"documentDayViews":return s?i:{day:{[r.date??""]:{[r.user??""]:i}}};case"documentMetadataViews":return s?i:{metadata:i};case"huddleMessage":return this.huddleUtilsService.formatHuddleMessageData(i);case"locationMetadataViews":return s?i:{metadata:i};case"locationUsersViews":return s?i:{users:{[r.user??""]:{[r.date??""]:i}}};case"locationDayViews":return s?i:{day:{[r.date??""]:{[r.user??""]:i}}};case"locationViews":return s?i:{location:i};case"docNotificationViews":return s?i:{views:i.views};case"userNotificationViews":return s?i:{views:i.views};case"presence":return this.presenceUtilsService.formatPresenceUserData(i);case"selection":return this.selectionUtilsService.formatSelectionData(i);case"tag":return this.tagUtilsService.formatTagData(i);default:return i}}catch(c){return this.loggingService.catch("Error in CommonDbUtilsService formatData:",c),i}}modifyAndSetData(s){return ee(this,arguments,function*({feature:e,data:i,subscriber:r,operation:a=null}){try{let c=yield this.modifyData({feature:e,data:i});r.next({data:c,operation:a})}catch(c){this.loggingService.catch("Error in CommonDbUtilsService modifyAndSetData:",c)}})}isDataAlreadyProcessedInLocalCache({feature:e,change:i,cache:r}){try{if(e==="allReactions"||e==="allComments"){if(i.type==="removed")return!Object.keys(r??{}).includes(i.doc.id);if(r?.[i.doc.id]){let a=i.doc.data(),s=r?.[i.doc.id];return a?.lastUpdated===s?.lastUpdated}}return!1}catch(a){return this.loggingService.catch("Error in CommonDbUtilsService isDataAlreadyProcessedInLocalCache:",a),!1}}modifyData(r){return ee(this,arguments,function*({feature:e,data:i}){try{return yield this.formatResponse({feature:e,data:i})}catch(a){return this.loggingService.catch("Error in CommonDbUtilsService modifyData:",a),i}})}addMetadata(e,i){try{return e&&typeof e=="object"&&!Array.isArray(e)?T(I({},e),{metadata:e?.metadata??{documentId:i?.documentId,organizationId:i?.organizationId,apiKey:i?.apiKey}}):e}catch(r){return this.loggingService.catch("Error in CommonDbUtilsService addMetadata:",r),e}}setDataInLocal(p){return ee(this,arguments,function*({feature:e,data:i,observablesCache:r,eventType:a,id:s,operation:c=null}){try{let _={comment:"allComments",reaction:"allReactions"}[e];if(!_)return null;let E=i?.metadata?.documentId,D=i?.metadata?.veltFolderId;return Object.keys(r).filter(B=>B.includes(_)&&(!E||B.includes(E)||D&&B.includes(D))).forEach(B=>{let G=r[B]?.subject?.getValue()??{};a==="DELETE"?s&&G?.data?.[s]&&(delete G?.data?.[s],r[B]?.subject&&r[B].subject.next({data:G?.data,operation:c})):r[B]?.subject?.next({data:T(I({},G?.data),{[i?.annotationId]:i}),operation:c})}),null}catch(h){return this.loggingService.catch("Error in CommonDbUtilsService setDataInLocal:",h),null}})}handleCommentEncryption(s){return ee(this,arguments,function*({data:e,firestorePath:i,extraData:r,eventType:a}){try{return yield this.commentUtilsService.handleCommentEncryption({data:e,firestorePath:i,extraData:r,eventType:a})}catch(c){return this.loggingService.catch("Error in CommonDbUtilsService handleCommentEncryption:",c),e}})}handleReactionEncryption(a){return ee(this,arguments,function*({data:e,firestorePath:i,eventType:r}){try{return yield this.reactionUtilsService.handleReactionEncryption({data:e,firestorePath:i,eventType:r})}catch(s){return this.loggingService.catch("Error in CommonDbUtilsService handleReactionEncryption:",s),e}})}};o.\u0275fac=function(i){return new(i||o)(J(ase),J(sse),J(Uv),J(lse),J(cse),J(xM),J(dse),J(y),J(pse),J(TM),J(use),J(hse),J(jv),J(fse),J(vse),J(Hn),J(lt),J(vs),J(um))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Cse=(()=>{let o=class o{constructor(e,i,r){this.configService=e,this.authService=i,this.loggingService=r,this.firestore$=new fe(null);try{Dn([this.authService.getFirebaseConfig$(),this.configService.getApiKey$()]).pipe(Ne(([a,s])=>!!a&&!!s),Je(1)).subscribe(([a,s])=>{a&&s&&a?.firebaseOptions?.storeDbId&&this.firestore$.next(Q6(Fp.getFirestoreProdDbName(s,a.firebaseOptions)))},a=>{})}catch{}}getFirestore(){return this.firestore$.asObservable()}getFirestoreValue(){return this.firestore$.value}generateFirestoreDocumentId(){try{let e=this.getFirestoreValue()||Q6("DocumentIdDb");if(e){let i=kS(e,"generateDocumentId");return kv(i).id}return}catch(e){this.loggingService.catch("Error in FirestoreService generateFirestoreDocumentId: ",e);return}}};o.\u0275fac=function(i){return new(i||o)(J($t),J(je),J(y))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var bn=(()=>{let o=class o{constructor(e,i,r,a,s,c,p,h,_,E){this.authService=e,this.commonDbUtilsService=i,this.loggingService=r,this.firestoreService=a,this.databaseService=s,this.configService=c,this.docService=p,this.usersService=h,this.commentAnnotationsResolverService=_,this.reactionAnnotationsResolverService=E,this.offset=0,this.db=null,this.firestore=null,this.subscriptions=[],this.offsetListener=null,this.observablesCache={},this.firestoreSubscriptions={},this.loggingService.log("%c[WB] Creating CLASS: CommonDbService","color: blue;"),this.docService.setCommonDbService(this),this.authService.setCommonDbService(this),this.subscriptions.push(this.databaseService.getDb().subscribe(D=>{if(D){this.db=D;let B=on(D,".info/serverTimeOffset");this.offsetListener=gu(B,G=>{let X=G.val();this.offset=X})}})),this.subscriptions.push(this.firestoreService.getFirestore().subscribe(D=>{D&&(this.firestore=D)}))}unsubscribeFromObservables(){try{Object.values(this.firestoreSubscriptions??{}).forEach(e=>{e?.unsubscribe()}),Object.entries(this.observablesCache??{}).forEach(([e,i])=>{i?.subject?.complete(),i?.subject?.unsubscribe()}),this.observablesCache={},this.firestoreSubscriptions={}}catch(e){this.loggingService.catch("Error in unsubscribeFromObservables:",e)}}ngOnDestroy(){this.subscriptions.forEach(e=>e.unsubscribe()),this.offsetListener&&this.offsetListener(),this.unsubscribeFromObservables()}getOffset(){return this.offset}getServerTimestamp(){return new Date().getTime()+this.getOffset()}subscribeToServices(e){Dn([this.databaseService.getDb(),this.firestoreService.getFirestore()]).pipe(Ne(([i,r])=>!!i),Je(1),In(([i,r])=>{e({db:i,firestore:r})})).subscribe({error:i=>{this.loggingService.catch("Error in CommonDbService subscription: ",i)}})}performDatabaseOperation(e,i,r,a,s,c){return ee(this,null,function*(){try{if(!i){this.loggingService.warn(`%c[WB] No properties found for ${e}`,"color: red;");return}return this.subscribeToServices(_=>ee(this,[_],function*({db:p,firestore:h}){let E;i?.skipFirestore||(E=this.commonDbUtilsService.getFirestorePath({feature:e,properties:i,documentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey()}));let D=this.commonDbUtilsService.getDocumentPath({feature:e,properties:i,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey(),useFirestore:this.shouldUseFirestore()});if(!p){this.loggingService.warn(`%c[WB] No database or firestore found for ${e}`,"color: red;");return}try{let B,G;try{D&&(B=on(p,`${D}`))}catch{this.loggingService.catch("Error in dbRef")}try{E?.includes("/organizations")&&h&&E&&(G=kv(h,`${E}`))}catch{this.loggingService.catch("Error in docRef")}yield r({dbRef:B,firestoreRef:G,data:a,firestorePath:E}),c&&c({firestoreAvailable:!!h})}catch(B){this.loggingService.catch(`Error in ${e} operation: `,B),s&&s(B)}}))}catch(p){this.loggingService.catch("Error in performDatabaseOperation:",p)}})}setData(p){return ee(this,arguments,function*({feature:e,data:i,properties:r,callback:a,errorCallback:s,extraData:c}){try{return this.loggingService.log(`%c[WB] Calling FUNCTION: setData for ${e}`,"color: green;"),this.shouldUseFirestore()&&i?.metadata&&!i?.metadata?.apiKey?void 0:(this.commonDbUtilsService.setDataInLocal({feature:e,data:i,observablesCache:this.observablesCache,operation:null}),this.performDatabaseOperation(e,r,h=>ee(this,null,function*(){if(h.dbRef){let _=this.commonDbUtilsService.formatData({feature:e,data:h.data,properties:r,offset:this.getOffset(),isRealtimeDb:!0});yield Of(h.dbRef,JSON.parse(JSON.stringify(_)))}try{if(h.firestoreRef&&h.data&&!r?.skipFirestore){let _=this.commonDbUtilsService.formatData({feature:e,data:h.data,properties:r,offset:this.getOffset()});typeof _=="object"&&(_=JSON.parse(JSON.stringify(_)));let{strippedData:E,originalData:D,eventType:B}=this.commonDbUtilsService.handleDataStripping({feature:e,data:_,actionType:c?.actionType});if(e==="comment"){let G=null;E&&(G=yield this.commentAnnotationsResolverService.saveCommentAnnotation({commentAnnotation:E,eventType:B,commentId:c?.targetAnnotationData?.commentId})),D&&(G?.isSuccess||G===null)&&(yield this.commonDbUtilsService.handleCommentEncryption({data:D,firestorePath:h.firestorePath??"",extraData:c}))}else if(e==="reaction"){let G=null;E&&(G=yield this.reactionAnnotationsResolverService.saveReactionAnnotation(E)),D&&(G?.isSuccess||G===null)&&(yield this.commonDbUtilsService.handleReactionEncryption({data:D,firestorePath:h.firestorePath??""}))}else yield Qj(h.firestoreRef,_)}}catch(_){this.loggingService.catch(`Error in setData for ${e}`,_)}}),i,s,a))}catch(h){this.loggingService.catch(`Error in setData for ${e}`,h)}})}updateData(p){return ee(this,arguments,function*({feature:e,data:i,properties:r,callback:a,errorCallback:s,extraData:c}){try{return this.loggingService.log(`%c[WB] Calling FUNCTION: updateData for ${e}`,"color: green;"),this.shouldUseFirestore()&&i?.metadata&&!i?.metadata?.apiKey?void 0:(this.commonDbUtilsService.setDataInLocal({feature:e,data:i,observablesCache:this.observablesCache,operation:null}),this.performDatabaseOperation(e,r,h=>ee(this,null,function*(){if(h.dbRef&&!r?.skipRtdb){let _=this.commonDbUtilsService.formatData({feature:e,data:h.data,properties:r,offset:this.getOffset(),isRealtimeDb:!0});yield jA(h.dbRef,JSON.parse(JSON.stringify(_)))}try{if(h.firestoreRef&&h.data&&!r?.skipFirestore){let _=this.commonDbUtilsService.formatData({feature:e,data:h.data,properties:r,offset:this.getOffset()});typeof _=="object"&&(_=JSON.parse(JSON.stringify(_)));let{strippedData:E,originalData:D,eventType:B}=this.commonDbUtilsService.handleDataStripping({feature:e,data:_,actionType:c?.actionType});if(e==="comment"){let G=null;E&&(G=yield this.commentAnnotationsResolverService.saveCommentAnnotation({commentAnnotation:E,eventType:B,commentId:c?.targetAnnotationData?.commentId})),D&&(G?.isSuccess||G===null)&&(yield this.commonDbUtilsService.handleCommentEncryption({data:D,firestorePath:h.firestorePath??"",extraData:c}))}else if(e==="reaction"){let G=null;E&&(G=yield this.reactionAnnotationsResolverService.saveReactionAnnotation(E)),D&&(G?.isSuccess||G===null)&&(yield this.commonDbUtilsService.handleReactionEncryption({data:D,firestorePath:h.firestorePath??""}))}else yield Qj(h.firestoreRef,_,{merge:!0})}}catch(_){this.loggingService.catch(`Error in updateDoc for ${e}`,_)}}),i,s,a))}catch(h){this.loggingService.catch(`Error in updateData for ${e}`,h)}})}deleteData(s){return ee(this,arguments,function*({feature:e,properties:i,callback:r,errorCallback:a}){try{return this.loggingService.log(`%c[WB] Calling FUNCTION: deleteData for ${e}`,"color: green;"),this.commonDbUtilsService.setDataInLocal({feature:e,observablesCache:this.observablesCache,eventType:"DELETE",id:i?.id,operation:{type:"removed",ids:[i?.id]}}),this.performDatabaseOperation(e,i,c=>ee(this,null,function*(){c.dbRef&&(yield VA(c.dbRef));try{if(c.firestoreRef&&!i?.skipFirestore)if(e==="comment"){let p=null;p=yield this.commentAnnotationsResolverService.deleteCommentAnnotation(i?.id??""),(p?.isSuccess||p===null)&&(yield this.commonDbUtilsService.handleCommentEncryption({firestorePath:c.firestorePath??"",eventType:"DELETE"}))}else if(e==="reaction"){let p=null;p=yield this.reactionAnnotationsResolverService.deleteReactionAnnotation(i?.id??""),(p?.isSuccess||p===null)&&(yield this.commonDbUtilsService.handleReactionEncryption({firestorePath:c.firestorePath??"",eventType:"DELETE"}))}else yield Lae(c.firestoreRef)}catch(p){this.loggingService.catch(`Error in deleteData for ${e}`,p)}}),void 0,a,r)}catch(c){this.loggingService.catch(`Error in deleteData for ${e}`,c)}})}shouldUseFirestore(){try{return this.authService.getAdvancedQueriesEnabled()}catch(e){return this.loggingService.catch("Error in shouldUseFirestore:",e),!1}}generateDocumentId(){try{let e=this.firestoreService.generateFirestoreDocumentId();return e||(e=xn()),e||"noDocumentId"}catch(e){return this.loggingService.catch("Error in generateFirestoreDocumentId:",e),xn()||"noDocumentId"}}queryData(r){return ee(this,arguments,function*({feature:e,properties:i}){try{let a=this.shouldUseFirestore();return!e||!i?(this.loggingService.warn("[WB] Missing required parameters in queryData"),[]):a?yield this.handleFirestoreQuery(e,i):yield this.handleRtdbQuery(e,i)}catch(a){return this.loggingService.catch(`Error in queryData for ${e}`,a),[]}})}handleFirestoreQuery(e,i){return ee(this,null,function*(){try{if(!this.firestore)return this.loggingService.warn("[WB] Firestore not initialized"),[];let r=i?.useCollectionGroup?this.commonDbUtilsService.getFirestoreCollectionGroupPath(e):this.commonDbUtilsService.getFirestorePath({feature:e,properties:i,documentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey()});if(!r)return this.loggingService.warn(`[WB] No firestore path found for ${e}`),[];try{let a=kS(this.firestore,r);i?.useCollectionGroup&&(a=Kj(this.firestore,r));let s=i?.firestoreQuery??[],c=Xj(a,...s);if(i?.getCount){let p=yield Vae(c).catch(h=>(this.loggingService.catch(`Error in getCountFromServer for ${e}`,h),null));return p?p.data().count:0}else{let p=yield jae(c).catch(E=>(this.loggingService.catch(`Error in getDocs for ${e}`,E),null));if(!p)return[];let h=p.docs.map(E=>E.data());return yield this.commonDbUtilsService.modifyData({feature:e,data:h})}}catch(a){return this.loggingService.catch(`Error in Firestore query for ${e}:`,a),[]}}catch(r){return this.loggingService.catch(`Error in Firestore query for ${e}:`,r),[]}})}handleRtdbQuery(e,i){return ee(this,null,function*(){if(!this.db)return this.loggingService.warn("[WB] Realtime Database not initialized"),[];let r=this.commonDbUtilsService.getDocumentPath({feature:e,properties:i,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey()});if(!r)return this.loggingService.warn(`[WB] No database path found for ${e}`),[];try{let a=on(this.db,r),s=i?.rtdbQuery??[],c=xL(a,...s),p=yield bL(c).catch(_=>(this.loggingService.catch(`Error in get for ${e}`,_),null));if(!p)return[];let h=p.val();return h?i?.skipObjectValues?h:Object.values(h??{}):[]}catch(a){return this.loggingService.catch(`Error in RTDB query for ${e}:`,a),[]}})}getData(r){return ee(this,arguments,function*({feature:e,properties:i}){try{let a=this.shouldUseFirestore();if(i?.skipFirestore&&(a=!1),!e||!i)return this.loggingService.warn("[WB] Missing required parameters in getData"),{};if(a&&this.firestore){let s=this.commonDbUtilsService.getFirestorePath({feature:e,properties:i,documentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey()});if(!s)return this.loggingService.warn(`[WB] No firestore path found for ${e}`),{};try{let c=yield Uae(kv(this.firestore,s)).catch(h=>(this.loggingService.catch(`Error in getDoc for ${e}`,h),null));if(!c)return this.loggingService.warn(`[WB] No document found at ${s}`),{};let p=c.data();return i?.field?p?.[i.field]??{}:p??{}}catch(c){return this.loggingService.catch(`Error fetching Firestore data for ${e}:`,c),{}}}if(this.db){let s=this.commonDbUtilsService.getDocumentPath({feature:e,properties:i,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey()});if(!s)return this.loggingService.warn(`[WB] No database path found for ${e}`),{};try{let c=yield bL(on(this.db,s)).catch(h=>(this.loggingService.catch(`Error in get for ${e}`,h),null));if(!c)return this.loggingService.warn(`[WB] No data found at ${s}`),{};let p=c.val();return i?.field?p?.[i.field]??{}:p??{}}catch(c){return this.loggingService.catch(`Error fetching RTDB data for ${e}:`,c),{}}}return this.loggingService.warn("[WB] No database connection available"),{}}catch(a){return this.loggingService.catch("Unexpected error in getData:",a),{}}})}dbListener({feature:e,properties:i}){let r=this.shouldUseFirestore();i?.skipFirestore&&(r=!1);let a=`${e}-${JSON.stringify(i)}`;return Dn([this.databaseService.getDb(),this.firestoreService.getFirestore()]).pipe(Ne(([s,c])=>s?r&&!c?(this.loggingService.warn(`[WB] Firestore requested but not available for ${e}`),!1):!0:(this.loggingService.warn(`[WB] No database found for ${e}`),!1)),ge(([s,c])=>{try{if(r&&c){if(!!!this.observablesCache[a]){this.observablesCache[a]={subject:new fe({}),count:0};let _=this.handleFirestoreListener(e,i,c).subscribe(E=>{this.observablesCache[a]?.subject?.next(E)},E=>this.observablesCache[a]?.subject?.error(E));this.firestoreSubscriptions[a]=_}return new Ft(h=>{let _=this.observablesCache[a]?.subject?.subscribe(E=>h.next(E),E=>h.error(E),()=>h.complete());return this.observablesCache[a].count+=1,()=>{_?.unsubscribe(),this.observablesCache[a]&&(this.observablesCache[a].count-=1,this.observablesCache[a].count<=0&&(this.firestoreSubscriptions[a]?.unsubscribe(),delete this.firestoreSubscriptions[a],this.observablesCache[a]?.subject?.complete(),delete this.observablesCache[a]))}})}else if(s)return this.handleRealtimeDbListener(e,i,s);return re({})}catch(p){return this.loggingService.catch(`Error setting up listener for ${e}:`,p),re({})}}),Ig(()=>{this.loggingService.log(`[WB] Cleaning up listener for ${e} and key ${a}`)}))}handleFirestoreListener(e,i,r){let a=i?.useCollectionGroup?this.commonDbUtilsService.getFirestoreCollectionGroupPath(e):this.commonDbUtilsService.getFirestorePath({feature:e,properties:i,documentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey()}),s=`${e}-${JSON.stringify(i)}`;return a?new Ft(c=>{let p=i.isCollection?this.setupCollectionListener(r,a,e,c,i):this.setupDocumentListener(r,a,e,c,i);return()=>{c.complete(),c.unsubscribe(),p(),this.observablesCache[s]?.subject?.complete(),this.observablesCache[s]?.subject?.unsubscribe(),delete this.observablesCache[s]}}).pipe(ge(c=>this.commonDbUtilsService.mergeUsersWithData$({feature:e,data:c})),ge(c=>["allComments","allUserNotifications"].includes(e)?this.commonDbUtilsService.mergeCommentAnnotationsWithData$({data:c,feature:e}):re(c)),ge(c=>["allReactions"].includes(e)?this.commonDbUtilsService.mergeReactionAnnotationsWithData$({data:c,feature:e}):re(c)),Kt(_o)):(this.loggingService.warn(`[WB] No firestore path found for ${e} and key ${s}`),re({}))}setupCollectionListener(e,i,r,a,s){let c=`${r}-${JSON.stringify(s)}`,p=kS(e,i);if(s?.useCollectionGroup&&(p=Kj(e,i)),s?.useQuery&&s?.firestoreQuery){let E=s?.firestoreQuery??[];p=Xj(p,...E)}let h=!0,_=[];return Zj(p,E=>{try{let D=JSON.parse(JSON.stringify(this.observablesCache[c]?.subject?.getValue()?.data??{})),B=null,G=!1;E?.docChanges()?.length?E.docChanges().forEach(X=>{["allComments","allReactions"].includes(r)&&!h&&X.type!=="removed"&&_.push(X.doc.id),this.commonDbUtilsService.isDataAlreadyProcessedInLocalCache({feature:r,change:X,cache:this.observablesCache[c]?.subject?.getValue()?.data??{}})||(G=!0,Object.assign(D,this.handleCollectionChange(X,D)),X.type==="removed"&&(B||(B={type:X.type,ids:[]}),B.ids.push(X.doc.id)))}):G=!0,G&&(["allComments","allReactions"].includes(r)&&_?.length&&(this.commonDbUtilsService.resolveAnnotations({data:_,feature:r}),_=[]),this.commonDbUtilsService.modifyAndSetData({feature:r,data:D,subscriber:a,operation:B})),h=!1}catch(D){this.handleListenerError(D,r,a)}},E=>this.handleListenerError(E,r,a))}handleCollectionChange(e,i){switch(e.type){case"added":case"modified":i[e.doc.id]=e.doc.data();break;case"removed":delete i?.[e.doc.id];break}return i}setupDocumentListener(e,i,r,a,s){let c=kv(e,i);return Zj(c,p=>{try{let h=p.data()||{};s?.field&&(h=h?.[s?.field]??{}),this.commonDbUtilsService.modifyAndSetData({feature:r,data:h,subscriber:a,operation:null})}catch(h){this.handleListenerError(h,r,a)}},p=>this.handleListenerError(p,r,a))}handleListenerError(e,i,r){this.loggingService.catch(`Firestore listener error for ${i}:`,e),r.error(e)}handleRealtimeDbListener(e,i,r){let a=this.commonDbUtilsService.getDocumentPath({feature:e,properties:i,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey()});if(!a)return this.loggingService.warn(`[WB] No database path found for ${e}`),re({});let s=on(r,a);if(i?.useQuery&&i?.rtdbQuery){let c=i?.rtdbQuery??[];s=xL(s,...c)}return Af(s).pipe(Ln(c=>(this.loggingService.catch(`RTDB listener error for ${e}:`,c),re({}))),ce(c=>(c===null&&(c={}),c&&typeof c=="object"?Object.entries(c??{}).reduce((h,[_,E])=>(h[_]=this.commonDbUtilsService.addMetadata(E,i),h),{}):this.commonDbUtilsService.addMetadata(c,i))),ge(c=>this.commonDbUtilsService.modifyData({feature:e,data:c})),ge(c=>this.usersService.getUserById$().pipe(ce(()=>({data:this.commonDbUtilsService.mergeUsersWithData({feature:e,data:c}),operation:null})))))}};o.\u0275fac=function(i){return new(i||o)(J(je),J($v),J(y),J(Cse),J(pn),J($t),J(lt),J(Hn),J(vs),J(um))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var gi=(()=>{let o=class o{constructor(e,i,r,a,s,c,p,h){this.analyticsService=e,this.authService=i,this.configService=r,this.databaseService=a,this.docService=s,this.loggingService=c,this.commonDbService=p,this.usersService=h,this.db=Ci(),this.internalUserContacts$=new fe([]),this.userGlobalContact$=new fe(!1),this.userGroupContact$=new fe(null),this.users$=new fe([]),this.userPersonalContacts=[],this.userGroupContacts=[],this.userGlobalContacts=[],this.users=[],this.documentPaths=null,this.userOrganizationContacts$=new fe([]),this.userFolderContacts$=new fe([]),this.userDocumentContacts$=new fe([]),this.userOrganizationGroups$=new fe([]),this.onContactSelectedSubject$=new et,this.documentAccessType=null,this.atHereEnabled$=new fe(!1),this.atHereLabel$=new fe("here"),this.atHereDescription$=new fe(null),this.contactListScopeForOrganizationUsers$=new fe([xi.ALL]),this.customUserContacts$=new fe(null),this.customUserContactsConfig$=new fe({merge:!1}),this.currentOrganizationUserIAM$=new fe(null),this.userContacts$=new fe([]),this.userSnippylyIdContacts$=new fe(null),this.usersByOrganizationId$=new fe({}),this.usersByOrganizationIdAndDocumentId$=new fe({}),this.usersByOrganizationIdAndFolderId$=new fe({}),this.userById$=new fe({}),this.authService.setContactService(this),this.authService.getUser$().pipe(ge(_=>this.docService.getDocumentPaths$().pipe(In(E=>{this.documentPaths=E}),ce(()=>_)))).subscribe(_=>ee(this,null,function*(){this.user=_,_&&this.documentPaths?_?.organizationId?(this.getOrganizationContactsFromDb$(),this.getFolderContactsFromDb$(),this.getDocumentContactsFromDb$(),this.getOrganizationGroupsFromDb$()):(this.getLoggedInUsers$().subscribe(),this.getUserContactsFromDb$(),yield this.migrateLoggedInUserFromEmailToUserIdPath(_),this.setLoggedInUser(_),yield this.moveGlobalContactUserFromEmailToUserIdPath(_),this.updateUserInGlobalContactsIfAvailable(_),_?.groupId&&(yield this.migrateGroupContactsFromEmailToUserIdPath(_?.groupId)),this.checkToSetLoggedInUserInGroupContacts()):(this.getUserContactSubscription?.unsubscribe(),this.getLoggedInUsersSubscription?.unsubscribe(),this.getOrganizationContactsSubscription?.unsubscribe(),this.getFolderContactsSubscription?.unsubscribe(),this.getDocumentContactsSubscription?.unsubscribe(),this.getOrganizationGroupsSubscription?.unsubscribe())}),_=>{this.loggingService.catch("Error in ContactService constructor getUser$: ",_)}),this.databaseService.getDb().pipe(Ne(_=>!!_),Je(1)).subscribe(_=>{_&&(this.db=_)},_=>{this.loggingService.catch("Error in ContactService constructor getDb: ",_)}),this.getOrganizationGroups$().subscribe(_=>{this.authService.setOrganizationUserGroups(_)}),Dn([this.getInternalUserContacts$(),this.getCustomUserContacts$(),this.getCustomUserContactsConfig$()]).subscribe(([_,E,D])=>{E?D?.merge?this.userContacts$.next([..._||[],...E||[]]):this.userContacts$.next(E||[]):this.userContacts$.next(_||[])}),this.getUserContacts$().subscribe(_=>{try{_?.forEach(E=>{let D=E?.userSnippylyId||ov(this.configService.getApiKey(),E.userId);D&&this.userSnippylyIdContacts$.next(T(I({},this.userSnippylyIdContacts$.value),{[D]:E}))})}catch{}})}clearCache(){this.loggingService.log("%c[WB] Calling FUNCTION: clearCache in ContactService","color: green;");try{this.documentPaths=null,this.usersByOrganizationId$.next({}),this.usersByOrganizationIdAndFolderId$.next({}),this.usersByOrganizationIdAndDocumentId$.next({}),this.userById$.next({}),this.userOrganizationContacts$.next([]),this.userFolderContacts$.next([]),this.userDocumentContacts$.next([]),this.userOrganizationGroups$.next([]),this.userContacts$.next([]),this.userSnippylyIdContacts$.next(null),this.userGlobalContact$.next(!1),this.userGroupContact$.next(null),this.users$.next([]),this.userPersonalContacts=[],this.userGroupContacts=[],this.userGlobalContacts=[],this.users=[]}catch(e){this.loggingService.catch("Error in ContactService clearCache: ",e)}}setDocumentAccessType(e){try{this.documentAccessType=e}catch(i){this.loggingService.catch("Error in ContactService setDocumentAccessType: ",i)}}checkIfUserGlobalContact(e){return ee(this,null,function*(){try{if(e?.userId&&this.documentPaths?.globalContacts){let i=yield this.commonDbService?.getData({feature:"globalContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Rt(e?.userId),skipFirestore:!0}});if(Object.keys(i??{}).length>0)return!0}if(e?.email&&this.documentPaths?.globalContacts){let i=yield this.commonDbService?.getData({feature:"globalContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Rt(e?.email),skipFirestore:!0}});if(Object.keys(i??{}).length>0)return!0}return!1}catch(i){return this.loggingService.catch("Error in ContactService isUserGlobalContact: ",i),!1}})}setLoggedInUser(e){try{e?.userId&&this.documentPaths?.logins&&(this.commonDbService.updateData({feature:"logins",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Rt(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(T(I({},e),{contacts:void 0})))}),this.setLoggedInUserPrivateContacts(e,e?.contacts))}catch(i){this.loggingService.catch("Error in ContactService setLoggedInUser: ",i)}}migrateLoggedInUserFromEmailToUserIdPath(e){return ee(this,null,function*(){try{if(e?.email&&this.documentPaths?.logins){let i=yield this.commonDbService?.getData({feature:"logins",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Rt(e?.email),skipFirestore:!0}});if(Object.keys(i??{}).length>0){let r=i;if(r){if(r?.contacts){let a={};Object.keys(r?.contacts??{})?.forEach(s=>{let c=r.contacts[s];if(c?.userId){let p=Rt(c?.userId);a[p]=c}}),r.contacts=a}yield this.commonDbService.updateData({feature:"logins",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Rt(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(r))}),yield this.commonDbService.deleteData({feature:"logins",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Rt(e?.email),skipFirestore:!0}})}}}}catch(i){this.loggingService.catch("Error in ContactService migrateLoggedInUserFromEmailToUserIdPath: ",i)}})}addGlobalContact(e){try{e?.userId&&this.documentPaths?.globalContacts&&this.commonDbService.updateData({feature:"globalContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Rt(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(e))})}catch(i){this.loggingService.catch("Error in ContactService addGlobalContact: ",i)}}updateUserInGlobalContactsIfAvailable(e){return ee(this,null,function*(){try{if(e?.userId&&this.documentPaths?.globalContacts&&(yield this.checkIfUserGlobalContact(e))){let r=new wo;r.userId=e?.userId,r.userSnippylyId=e?.userSnippylyId,r.email=e?.email,r.name=e?.name,r.photoUrl=e?.photoUrl,this.commonDbService.updateData({feature:"globalContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Rt(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(r))})}}catch(i){this.loggingService.catch("Error in ContactService updateUserInGlobalContactsIfAvailable: ",i)}})}moveGlobalContactUserFromEmailToUserIdPath(e){return ee(this,null,function*(){try{if(e?.email&&e?.userId&&this.documentPaths?.globalContacts){let i=yield this.commonDbService?.getData({feature:"globalContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Rt(e?.email),skipFirestore:!0}});if(Object.keys(i??{}).length>0){let r=i;r&&(yield this.commonDbService.updateData({feature:"globalContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Rt(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(r))}),yield this.commonDbService.deleteData({feature:"globalContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Rt(e?.email),skipFirestore:!0}}))}}}catch(i){this.loggingService.catch("Error in ContactService removeUserFromGlobalContactsByEmail: ",i)}})}setLoggedInUserPrivateContacts(e,i){try{if(e?.userId&&this.documentPaths?.logins){let r,a=i?.filter(c=>c?.visibility!=="group"),s=!1;this.authService.getUserOptions()&&(s=!!this.authService.getUserOptions()?.replaceContacts||!!this.authService.getUserOptions()?.replacePrivateContacts),a?.length?(r={},a?.forEach(c=>{if(c?.userId){let p=Rt(c?.userId);r[p]=c}}),s?this.commonDbService.setData({feature:"allLoginContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Rt(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(r))}):this.commonDbService.updateData({feature:"allLoginContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Rt(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(r))})):s&&this.commonDbService.deleteData({feature:"allLoginContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Rt(e?.userId),skipFirestore:!0}})}}catch(r){this.loggingService.catch("Error in ContactService setLoggedInUserPrivateContacts: ",r)}}migrateGroupContactsFromEmailToUserIdPath(e){return ee(this,null,function*(){try{if(this.documentPaths?.groupContacts&&e){let i=yield this.commonDbService?.getData({feature:"groupContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",groupId:e,skipFirestore:!0}});i&&Object.keys(i??{}).forEach(r=>ee(this,null,function*(){let a=i[r];a?.email&&a?.userId&&Rt(a?.email)===r&&(yield this.commonDbService.deleteData({feature:"groupContactsUser",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",groupId:e,userId:r,skipFirestore:!0}}),yield this.commonDbService.updateData({feature:"groupContactsUser",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",groupId:e,userId:Rt(a?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(a))}))}))}}catch(i){this.loggingService.catch("Error in ContactService migrateGroupContacts: ",i)}})}checkToSetLoggedInUserInGroupContacts(){return ee(this,null,function*(){try{this.user?.groupId&&this.user?.userId&&((yield this.checkIfUserGlobalContact(this.user))||this.docService.getDocumentIam$().pipe(Je(1)).subscribe(i=>ee(this,null,function*(){if(this.user?.groupId&&this.user?.userId){let r=!1,a=this.docService.getDocumentAccessType(i);if(!a||a===di.PUBLIC)r=!0;else if(a===di.RESTRICTED){let s=Rt(this.user?.userId);if(i?.users?.[s]&&(r=!0),this.user?.email){let c=Rt(this.user?.email);i?.users?.[c]&&(r=!0)}}if(r){let s=new Rp;s.email=this.user.email,s.visibility="group",s.name=this.user.name,s.photoUrl=this.user.photoUrl,s.userId=this.user.userId,(this.authService.getUserOptions()?.replaceContacts||this.authService.getUserOptions()?.replaceGroupContacts)&&(yield this.removeGroupContacts(this.user?.groupId)),this.setLoggedInUserGroupContacts(this.user?.groupId,[s]),this.user?.contacts&&this.user?.groupId&&this.setLoggedInUserGroupContacts(this.user?.groupId,this.user?.contacts)}}})))}catch(e){this.loggingService.catch("Error in ContactService checkToSetLoggedInUserInGroupContacts: ",e)}})}setLoggedInUserGroupContacts(e,i){try{let r=i?.filter(a=>a?.visibility==="group");r?.length&&r.forEach(a=>ee(this,null,function*(){if(a?.userId&&e&&this.documentPaths?.groupContacts){if(this.configService?.getSF()&&(yield this.checkIfUserGlobalContact(a)))return;yield this.commonDbService.updateData({feature:"groupContactsUser",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",groupId:e,userId:Rt(a?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(a))}),a?.email&&(yield this.commonDbService.deleteData({feature:"groupContactsUser",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",groupId:e,userId:Rt(a?.email),skipFirestore:!0}}))}}))}catch(r){this.loggingService.catch("Error in ContactService setLoggedInUserGroupContacts: ",r)}}removeGroupContacts(e){return ee(this,null,function*(){try{if(this.documentPaths?.groupContacts&&e)return this.commonDbService.deleteData({feature:"groupContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",groupId:e,skipFirestore:!0}})}catch(i){this.loggingService.catch("Error in ContactService removeGroupContacts: ",i)}})}mergeUserContacts(){try{let e=[];this.userPersonalContacts&&e.push(...this.userPersonalContacts),this.userGroupContacts&&e.push(...this.userGroupContacts),this.userGlobalContacts&&e.push(...this.userGlobalContacts);let i={};e.forEach(r=>{r?.userId?(!r?.email||!i[r.email])&&(i[r.userId]=r):r?.email&&(!r?.userId||!i[r.userId])&&(i[r.email]=r)}),e=Object.values(i??{}),this.internalUserContacts$.next(e)}catch(e){this.loggingService.catch("Error in ContactService mergeUserContacts: ",e)}}getInternalUserContacts(){return this.internalUserContacts$.value}getInternalUserContacts$(){return this.internalUserContacts$.asObservable()}getUserContacts$(e){try{let{organizationId:i,documentId:r,veltFolderId:a}=e||{};return i&&r?Dn([this.usersByOrganizationId$,this.usersByOrganizationIdAndFolderId$,this.usersByOrganizationIdAndDocumentId$,this.userById$,this.customUserContacts$,this.customUserContactsConfig$,this.getContactListScopeForOrganizationUsers$()]).pipe(ce(([s,c,p,h,_,E,D])=>{let B={},G=!1;E&&!E?.merge&&(G=!0);let X=We=>D.some(ke=>We.includes(ke)),he=X([xi.ALL,xi.ORGANIZATION])?Object.keys(s?.[i]||{}):[],Ie=a?X([xi.ALL,xi.FOLDER])?Object.keys(c?.[i]?.[a]||{}):[]:[],Me=X([xi.ALL,xi.DOCUMENT])?Object.keys(p?.[i]?.[r]||{}):[];if([...he,...Ie||[],...Me].forEach(We=>{let ke=h?.[We];ke&&(B[We]=ke)}),_){let{merge:We,options:ke}=E||{},{organizationId:we,documentId:Ee,folderId:Pe}=ke||{},Ce=Pe?hl(Pe):void 0;(!we||we===i)&&(!Ee||Ee===r)&&(!Ce||Ce===a)&&(We||(B={}),_.forEach(ue=>{ue?.userId&&(B[ue.userId]=ue)}))}return Object.values(B??{})})):this.userContacts$.asObservable().pipe(ce(s=>s))}catch(i){return this.loggingService.catch("Error in ContactService getUserContacts$ metadata: ",i),re([])}}getUserContactsBySnippylyId$(){return this.userSnippylyIdContacts$.asObservable()}getAtHereLabel(){return this.atHereLabel$.asObservable()}getAtHereDescription(){return this.atHereDescription$.asObservable()}getUserContactsFromDb$(){this.getUserContactSubscription||(this.getUserContactSubscription=this.authService.getUser$().pipe(Ne(e=>!!e),ge(e=>this.docService.getDocumentPaths$().pipe(Ne(i=>!!i),In(i=>{this.documentPaths=i}),ce(()=>e))),ge(e=>{if(this.userGroupContacts=[],this.userPersonalContacts=[],!e)return re();if(!this.documentPaths)return re();let i=[];return i.push(this.commonDbService.dbListener({feature:"allGlobalContacts",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,skipFirestore:!0}}).pipe(ce(r=>r?.data),In(r=>{r?(this.userGlobalContacts=Object.values(r??{}),this.userGlobalContacts?.find(a=>a.userId===this.user?.userId)?this.userGlobalContact$.next(!0):this.userGlobalContact$.next(!1)):(this.userGlobalContacts=[],this.userGlobalContact$.next(!1))}))),i.push(this.commonDbService.dbListener({feature:"groupContacts",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,skipFirestore:!0,groupId:e?.groupId}}).pipe(ce(r=>r?.data),In(r=>{r?(this.userGroupContacts=Object.values(r??{}),this.userGroupContacts?.find(a=>a?.userId===this.user?.userId)?this.userGroupContact$.next(!0):this.userGroupContact$.next(!1)):(this.userGroupContacts=[],this.userGroupContact$.next(!1))}))),i.push(this.commonDbService.dbListener({feature:"allLoginContacts",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,skipFirestore:!0,userId:Rt(e?.userId)}}).pipe(ce(r=>r?.data),In(r=>{r?this.userPersonalContacts=Object.values(r??{}):this.userPersonalContacts=[]}))),io(...i).pipe(oo(this.authService.getUser$().pipe(Ne(r=>!r))))})).subscribe(()=>{this.mergeUserContacts()},e=>{this.loggingService.catch("Error in ContactService getUserContacts$ subscription: ",e)}))}addUserContact(e){try{this.user?.organizationId||this.user?.groupId&&(e.visibility="group",this.setLoggedInUserGroupContacts(this.user?.groupId,[e]))}catch(i){this.loggingService.catch("Error in ContactService addUserContact: ",i)}}isUserGlobalContact$(){return this.userGlobalContact$.asObservable()}isUserGlobalContact(){return this.userGlobalContact$.value}isUserGroupContact$(){return this.userGroupContact$.asObservable()}isUserGroupContact(){return this.userGroupContact$.value}getLoggedInUsers$(){return this.getLoggedInUsersSubscription||(this.getLoggedInUsersSubscription=this.authService.getUser$().pipe(ge(e=>e?this.documentPaths?e?.userId&&this.documentPaths?.logins?this.commonDbService.dbListener({feature:"allLogins",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,skipFirestore:!0}}).pipe(ce(i=>i?.data),In(i=>{i?this.users=Object.values(i??{}):this.users=[]})):(this.users=[],re()):re():re())).subscribe(()=>{this.users$.next(this.users)},e=>{this.loggingService.catch("Error in ContactService getLoggedInUsers$ subscription: ",e)})),this.users$.asObservable()}getUsersMap$(){return this.authService.getUser$().pipe(ge(e=>e?.organizationId?this.userById$.pipe(ce(i=>{let r={};return Object.values(i||{}).forEach(a=>{a?.userSnippylyId&&(r[a?.userSnippylyId]=a)}),r})):this.users$.pipe(ce(i=>{let r={};return i.forEach(a=>{r[a.userSnippylyId]=a}),r}))))}getUserByEmail$(e){return this.users$.pipe(ce(i=>i.find(r=>r.email===e)))}getUserByEmail(e){return this.users?.find(i=>i.email===e)}getContactByEmail(e){return this.getInternalUserContacts().find(i=>i.email===e)}getUserByUserId$(e){return this.users$.pipe(ce(i=>i.find(r=>r.userId===e)))}getUserGroupContacts(){return this.userGroupContacts}getOrganizationContactsFromDb$(){try{this.getOrganizationContactsSubscription||(this.getOrganizationContactsSubscription=this.authService.getUser$().pipe(ge(e=>e?.organizationId?re(e).pipe(ge(i=>this.docService.getOrganizationConfig$().pipe(Ne(r=>!!r),ce(()=>i))),ge(i=>{let r=this.docService.getOrganizationConfig()?.organizationId;return this.setUserOrganizationContacts([],r),i?r?this.commonDbService.dbListener({feature:"allOrganizationUsers",properties:{organizationId:r,isCollection:!0}}).pipe(ce(a=>a?.data),ce(a=>{if(a){typeof a=="object"&&(a?.undefined&&delete a.undefined,a?.null&&delete a.null);let s=Object.values(a??{});this.setUserOrganizationContacts(s,r)}else this.setUserOrganizationContacts([],r)})):re():re()}),ge(()=>this.getContactListScopeForOrganizationUsers$())):(this.setUserOrganizationContacts([]),re()))).subscribe(()=>{this.mergeOrganizationAndDocumentContacts()},e=>{this.loggingService.catch("Error in ContactService getOrganizationContactsFromDb$ subscription: ",e)}))}catch{}}getFolderContactsFromDb$(){try{this.getFolderContactsSubscription||(this.getFolderContactsSubscription=this.authService.getUser$().pipe(ge(e=>e?re(e).pipe(ge(i=>this.docService.getOrganizationConfig$().pipe(Ne(r=>!!r),ce(()=>i))),ge(i=>this.docService.getFolderConfig$().pipe(ce(()=>i))),ge(i=>{let r=this.docService.getOrganizationConfig()?.organizationId;if(this.setUserFolderContacts([]),!i)return re();if(!this.commonDbService.shouldUseFirestore())return re();let a=this.docService.getFolderConfig();if(!a?.veltFolderId)return re();let s=re([]);return s=this.commonDbService.dbListener({feature:"allFolderUsers",properties:{organizationId:r,folderId:a?.veltFolderId,isCollection:!0}}).pipe(ce(c=>c?.data)),s.pipe(ce(c=>{if(c){typeof c=="object"&&(c?.undefined&&delete c.undefined,c?.null&&delete c.null);let p=Object.values(c??{});this.setUserFolderContacts(p)}else this.setUserFolderContacts([])}))}),ge(()=>this.getContactListScopeForOrganizationUsers$())):(this.setUserFolderContacts([]),re()))).subscribe(()=>{this.mergeOrganizationAndDocumentContacts()},e=>{this.loggingService.catch("Error in ContactService getFolderContactsFromDb$ subscription: ",e)}))}catch{}}getDocumentContactsFromDb$(){try{this.getDocumentContactsSubscription||(this.getDocumentContactsSubscription=this.authService.getUser$().pipe(ge(e=>e?re(e).pipe(ge(i=>this.docService.getDocumentPaths$().pipe(Ne(r=>!!r),In(r=>{this.documentPaths=r}),ce(()=>i))),ge(i=>(this.setUserDocumentContacts([]),i?this.documentPaths?this.docService.getDocumentIds$().pipe(ge(r=>{let a=r?.length>0?r.map(h=>h.documentId):[this.documentPaths?.documentId??""];if(a.some(h=>!h)||!this.documentPaths)return re();let s=this.docService.getFolderConfig(),c=re([]),p={useCollectionGroup:!0,isCollection:!0,useQuery:!0};if(this.commonDbService.shouldUseFirestore()||(p.documentId=a?.length?a[0]:void 0,p.organizationId=this.documentPaths?.organizationId),s?.veltFolderId&&s?.allDocuments)c=this.commonDbService.dbListener({feature:"allDocumentUsers",properties:T(I({},p),{firestoreQuery:[Fi(mt("metadata.apiKey","==",this.configService?.getApiKey()),mt("metadata.veltFolderId","==",s?.veltFolderId),mt("metadata.organizationId","==",this.documentPaths?.organizationId))]})}).pipe(ce(h=>h?.data));else{let h=[];for(let _=0;_<a.length;_+=U.LISTENER_BATCH_SIZE)h.push(a.slice(_,_+U.LISTENER_BATCH_SIZE));c=Dn(h.map(_=>this.commonDbService.dbListener({feature:"allDocumentUsers",properties:T(I({},p),{firestoreQuery:[Fi(mt("metadata.apiKey","==",this.configService?.getApiKey()),mt("metadata.documentId","in",_),mt("metadata.organizationId","==",this.documentPaths?.organizationId),...s?.veltFolderId?[mt("metadata.veltFolderId","==",s?.veltFolderId)]:[])]})}).pipe($r()))).pipe(ce(_=>ca(_)?.data))}return c.pipe(ce(h=>{if(h){typeof h=="object"&&(h?.undefined&&delete h.undefined,h?.null&&delete h.null);let _=Object.values(h??{});this.setUserDocumentContacts(_)}else this.setUserDocumentContacts([])}))})):re():re())),ge(()=>this.getContactListScopeForOrganizationUsers$())):(this.setUserDocumentContacts([]),re()))).subscribe(()=>{this.mergeOrganizationAndDocumentContacts()},e=>{this.loggingService.catch("Error in ContactService getDocumentContactsFromDb$ subscription: ",e)}))}catch{}}setUserOrganizationContacts(e,i){try{let r=e.find(s=>s.user.userId===this.user?.userId);r?this.currentOrganizationUserIAM$.next(r):this.currentOrganizationUserIAM$.next(null);let a=e.map(s=>s.user);if(this.userOrganizationContacts$.next(a),i){let s={};s[i]={},e.forEach(c=>{s[i][c.user.userId]=c,this.userById$.next(T(I({},this.userById$.value),{[c.user.userId]:c.user}))}),this.usersByOrganizationId$.next(T(I({},this.usersByOrganizationId$.value),{[i]:s[i]}))}else this.usersByOrganizationId$.next({})}catch(r){this.loggingService.catch("Error in ContactService setUserOrganizationContacts: ",r)}}getUserOrganizationContacts$(){return this.getContactListScopeForOrganizationUsers$().pipe(ge(()=>this.checkContactListScopeForOrganizationUsers([xi.ALL,xi.ORGANIZATION])?this.userOrganizationContacts$.asObservable():re([])))}getUserOrganizationContacts(){return this.checkContactListScopeForOrganizationUsers([xi.ALL,xi.ORGANIZATION])?this.userOrganizationContacts$.value:[]}setUserFolderContacts(e){try{this.userFolderContacts$.next(e?.map(r=>r?.user));let i={};e?.forEach(r=>{let{organizationId:a,veltFolderId:s}=r?.metadata||{};a&&s&&(i[a]||(i[a]={}),i[a][s]||(i[a][s]={}),i[a][s][r.user.userId]=r,this.userById$.next(T(I({},this.userById$.value),{[r.user.userId]:r.user})))}),this.usersByOrganizationIdAndFolderId$.next(i)}catch(i){this.loggingService.catch("Error in ContactService updateUserFolderContacts: ",i)}}getUserFolderContacts$(){return this.getContactListScopeForOrganizationUsers$().pipe(ge(()=>this.checkContactListScopeForOrganizationUsers([xi.ALL,xi.FOLDER])?this.userFolderContacts$.asObservable():re([])))}getUserFolderContacts(){return this.checkContactListScopeForOrganizationUsers([xi.ALL,xi.FOLDER])?this.userFolderContacts$.value:[]}setUserDocumentContacts(e){try{this.userDocumentContacts$.next(e?.map(r=>r?.user));let i={};e?.forEach(r=>{let{organizationId:a,documentId:s}=r?.metadata||{};a&&s&&(i[a]||(i[a]={}),i[a][s]||(i[a][s]={}),i[a][s][r.user.userId]=r,this.userById$.next(T(I({},this.userById$.value),{[r.user.userId]:r.user})))}),this.usersByOrganizationIdAndDocumentId$.next(i)}catch(i){this.loggingService.catch("Error in ContactService updateUserDocumentContacts: ",i)}}getUserDocumentContacts$(){return this.getContactListScopeForOrganizationUsers$().pipe(ge(()=>this.checkContactListScopeForOrganizationUsers([xi.ALL,xi.DOCUMENT])?this.userDocumentContacts$.asObservable():re([])))}getUserDocumentContacts(){return this.checkContactListScopeForOrganizationUsers([xi.ALL,xi.DOCUMENT])?this.userDocumentContacts$.value:[]}getCurrentOrganizationUserIAM$(){return this.currentOrganizationUserIAM$.asObservable()}getCurrentOrganizationUserIAM(){return this.currentOrganizationUserIAM$.value}mergeOrganizationAndDocumentContacts(){try{let e=[];this.getContactListScopeForOrganizationUsers().includes(xi.ALL)?e=[...this.getUserOrganizationContacts(),...this.getUserFolderContacts(),...this.getUserDocumentContacts()]:this.getContactListScopeForOrganizationUsers().includes(xi.ORGANIZATION)?e=[...this.getUserOrganizationContacts()]:this.getContactListScopeForOrganizationUsers().includes(xi.FOLDER)?e=[...this.getUserFolderContacts()]:this.getContactListScopeForOrganizationUsers().includes(xi.DOCUMENT)&&(e=[...this.getUserDocumentContacts()]);let i=[...new Map(e.filter(r=>r?.userId).map(r=>[r.userId,r])).values()];this.internalUserContacts$.next(i)}catch(e){this.loggingService.catch("Error in ContactService mergeOrganizationAndDocumentContacts: ",e)}}getOrganizationGroupsFromDb$(){try{this.getOrganizationGroupsSubscription||(this.getOrganizationGroupsSubscription=this.authService.getUser$().pipe(ge(e=>e?.organizationId?re(e).pipe(ge(i=>this.docService.getOrganizationConfig$().pipe(Ne(r=>!!r),ce(()=>i))),ge(i=>{if(this.setUserOrganizationGroups([]),!i)return re();let r=this.docService.getOrganizationConfig()?.organizationId;return r?this.commonDbService.dbListener({feature:"allOrganizationGroups",properties:{organizationId:r,isCollection:!0}}).pipe(ce(a=>a?.data),ce(a=>{a?(typeof a=="object"&&(a?.undefined&&delete a.undefined,a?.null&&delete a.null),this.setUserOrganizationGroups(Object.values(a??{}))):this.setUserOrganizationGroups([])})):re()})):(this.setUserOrganizationGroups([]),re()))).subscribe(()=>{},e=>{this.loggingService.catch("Error in ContactService getOrganizationGroupsFromDb$ subscription: ",e)}))}catch{}}setUserOrganizationGroups(e){try{this.userOrganizationGroups$.next(e)}catch(i){this.loggingService.catch("Error in ContactService setUserOrganizationGroups: ",i)}}onContactSelected(e){try{if(e?.userId){let i=!!this.getUserDocumentContacts().find(a=>a.userId===e.userId),r=!!this.getUserOrganizationContacts().find(a=>a.userId===e.userId);switch(this.documentAccessType){case di.RESTRICTED:if(!i){let a={contact:e,isOrganizationContact:r,isDocumentContact:i,documentAccessType:this.documentAccessType};this.onContactSelectedSubject$.next(a)}break}}else{let i={contact:e,isOrganizationContact:!1,isDocumentContact:!1,documentAccessType:this.documentAccessType};this.onContactSelectedSubject$.next(i)}}catch(i){this.loggingService.catch("Error in ContactService onContactSelected: ",i)}}onContactSelected$(){return this.onContactSelectedSubject$.asObservable()}getOrganizationGroups$(){return this.getContactListScopeForOrganizationUsers$().pipe(ge(()=>this.checkContactListScopeForOrganizationUsers([xi.ALL,xi.ORGANIZATION_USER_GROUP])?this.userOrganizationGroups$.asObservable():re([])))}enableAtHere(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{atHereEnabled:!0}}),this.atHereEnabled$.value===!0)return;this.atHereEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in ContactService enableAtHere: ",e)}}setAtHereLabel(e){try{this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{atHereLabel:e}}),e&&this.atHereLabel$.next(e)}catch(i){this.loggingService.catch("Error in ContactService setAtHereLabel: ",i)}}setAtHereDescription(e){try{this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{atHereDescription:e}}),e&&this.atHereDescription$.next(e)}catch(i){this.loggingService.catch("Error in ContactService setAtHereDescription: ",i)}}disableAtHere(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{atHereEnabled:!1}}),this.atHereEnabled$.value===!1)return;this.atHereEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in ContactService disableAtHere: ",e)}}getAtHereEnabled$(){return this.getContactListScopeForOrganizationUsers$().pipe(ge(()=>this.checkContactListScopeForOrganizationUsers([xi.ALL,xi.DOCUMENT])?this.atHereEnabled$.asObservable():re(!1)))}getAtHereEnabled(){return this.checkContactListScopeForOrganizationUsers([xi.ALL,xi.DOCUMENT])?this.atHereEnabled$.value:!1}updateContactListScopeForOrganizationUsers(e){try{this.contactListScopeForOrganizationUsers$.next(e)}catch(i){this.loggingService.catch("Error in ContactService updateContactListScopeForOrganizationUsers: ",i)}}getContactListScopeForOrganizationUsers$(){return this.contactListScopeForOrganizationUsers$.asObservable()}getContactListScopeForOrganizationUsers(){return this.contactListScopeForOrganizationUsers$.value}checkContactListScopeForOrganizationUsers(e){return this.getContactListScopeForOrganizationUsers().some(i=>e.includes(i))}updateContactList(e,i){return ee(this,null,function*(){try{if(this.analyticsService.trackEvent(Z.Events.Contact.UPDATE_CONTACT_LIST_TRIGGERED,{contactsCount:e?.length,config:i}),this.usersService?.userDataProviderAvailable()){let r=e.map(s=>s?.userId).filter(s=>s);yield this.usersService.resolveUsers(r);let a=r.map(s=>this.usersService.getUserById(s)).filter(s=>!!s);this.customUserContacts$.next(a)}else this.customUserContacts$.next(e);this.customUserContactsConfig$.next(i)}catch(r){this.loggingService.catch("Error in CommentService updateContactList: ",r)}})}convert(e){try{if(e?.options){let{documentId:i,organizationId:r}=this.docService.getServerId(e?.options);e.options=T(I({},e?.options),{documentId:i,organizationId:r})}return this}catch(i){return this.loggingService.catch("Error in ContactService convert: ",i),this}}getContactList$(){try{return this.authService.getUser$().pipe(ge(e=>e?Dn([this.userOrganizationContacts$.asObservable(),this.userFolderContacts$.asObservable(),this.userDocumentContacts$.asObservable(),this.userOrganizationGroups$.asObservable(),this.customUserContacts$.asObservable()]).pipe(ce(([i,r,a,s,c])=>{let p={};p.organizationUsers=i?.map(_=>this.convertToClientUser(_)),p.folderUsers=r?.map(_=>this.convertToClientUser(_)),p.documentUsers=a?.map(_=>this.convertToClientUser(_)),p.updatedContactList=c?.map(_=>this.convertToClientUser(_));let h=[];return s?.forEach(_=>{let E=this.convertToClientUserGroup(_,p.organizationUsers||[]);E&&h.push(E)}),p.userGroups=h,p}),Kt(_o)):re(null)),Ln(e=>(this.loggingService.catch("Error in ContactService getContactList$: ",e),re(null))))}catch(e){return this.loggingService.catch("Error in ContactService getContactList$: ",e),re(null)}}convertToClientUserGroup(e,i){try{let r={groupId:e?.metadata?.clientGroupId,groupName:e?.metadata?.groupName,users:[]},a={};return i?.forEach(s=>{if(s?.userId){let c=Rt(s.userId);a[c]=s}}),Object.keys(e?.users??{}).forEach(s=>{a[s]&&r.users?.push(a[s])}),r}catch(r){return this.loggingService.catch("Error in ContactService convertToClientUserGroup: ",r),null}}convertToClientUser(e){try{return e&&(e=JSON.parse(JSON.stringify(e)),e?.clientGroupId&&(e.groupId=e.clientGroupId,delete e.clientGroupId),e?.clientOrganizationId&&(e.organizationId=e.clientOrganizationId,delete e.clientOrganizationId),e?.userSnippylyId&&delete e.userSnippylyId),e}catch(i){return this.loggingService.catch("Error in ContactService convertToClientUser: ",i),e}}getCustomUserContacts(){return this.customUserContacts$.value}getCustomUserContacts$(){return this.customUserContacts$.asObservable()}getCustomUserContactsConfig(){return this.customUserContactsConfig$.value}getCustomUserContactsConfig$(){return this.customUserContactsConfig$.asObservable()}};o.\u0275fac=function(i){return new(i||o)(J(Qe),J(je),J($t),J(pn),J(lt),J(y),J(bn),J(Hn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var _se=n=>{try{return n.name.split(".").slice(0,-1).join(".")}catch(o){pt.catch("Error in File utils getFileName: ",o);return}},p$=n=>{try{return/(?:\.([^.]+))?$/.exec(n?.name)[1]}catch(o){pt.catch("Error in File utils getFileExtension: ",o);return}},yse=(n,o)=>{try{let t=n.slice(0,-1,n.type);return new File([t],o+"."+p$(n),{type:n.type})}catch(t){pt.catch("Error in File utils updateFile: ",t);return}},Sse=n=>new Promise((o,t)=>{let e=new FileReader;e.readAsDataURL(n),e.onload=()=>{o(e.result)},e.onerror=i=>{t(i)}}),bse={mp4:"video/mp4",mov:"video/quicktime",avi:"video/x-msvideo",wmv:"video/x-ms-wmv",flv:"video/x-flv",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",webm:"video/webm",mkv:"video/x-matroska",m4v:"video/x-m4v",m4a:"audio/x-m4a",aac:"audio/aac","3gp":"video/3gpp","3g2":"video/3gpp2",jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",bmp:"image/bmp",svg:"image/svg+xml",webp:"image/webp",pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",odt:"application/vnd.oasis.opendocument.text",ods:"application/vnd.oasis.opendocument.spreadsheet",zip:"application/zip",rar:"application/x-rar-compressed",txt:"text/plain",rtf:"application/rtf",html:"text/html",htm:"text/html",csv:"text/csv",ics:"text/calendar",vcf:"text/x-vcard",js:"application/javascript",css:"text/css",json:"application/json",xml:"application/xml",swf:"application/x-shockwave-flash"};var Bp=(()=>{let o=class o{constructor(e,i,r,a){this.authService=e,this.configService=i,this.loggingService=r,this.attachmentResolverService=a,this.storage=Ty();try{this.configService.getApiKey$().subscribe(s=>{this.apiKey=s}),this.authService.getFirebaseConfig$().subscribe(s=>{s&&s.firebaseOptions?.storageBucket&&(this.storage=Ty(void 0,s?.firebaseOptions?.storageBucket))},s=>{this.loggingService.catch("Error in StorageService constructor: ",s)})}catch(s){this.loggingService.catch("Error in StorageService constructor:",s)}}createAttachment({path:e,file:i}){try{let r=new Nv;r.name=i.name;let a=yse(i,`${r.attachmentId}_${_se(i)}`),s=`${this.apiKey}/${e}/${a?.name}`;return r.bucketPath=s,r.size=i.size,r.type=p$(i),r?.type&&(r.mimeType=bse[r?.type]),r}catch(r){return this.loggingService.catch("Error in StorageService createAttachment: ",r),null}}uploadAttachmentToStorage({attachment:e,file:i,resolve:r,reject:a}){try{let s=wy(this.storage,e.bucketPath),c=QL(s,i,{cacheControl:"public,max-age=3600"});c.on("state_changed",p=>{let h=p.bytesTransferred/p.totalBytes*100},p=>{a(p)},()=>{XL(c.snapshot.ref).then(p=>{e.url=p,r(e)})})}catch(s){this.loggingService.catch("Error in StorageService uploadAttachmentToStorage: ",s),a(s)}}uploadToResolver(c){return ee(this,arguments,function*({file:e,attachment:i,metadata:r,resolve:a,reject:s}){try{r.attachmentId=i.attachmentId;let p={attachmentId:i.attachmentId,name:i.name,file:e,metadata:r,mimeType:i.mimeType},h=yield this.attachmentResolverService.saveAttachment({attachment:p,eventType:Ha.ATTACHMENT_ADD});h&&h.data?.url?(i.url=h.data?.url,a(i)):s(new Error("Failed to upload attachment to resolver"))}catch(p){this.loggingService.catch("Error in StorageService uploadToResolver: ",p),s(p)}})}uploadFile({path:e,file:i,useAttachmentResolver:r,metadata:a}){return new Promise((s,c)=>{try{if(!this.apiKey)throw new Error("API key not configured");let p=this.createAttachment({path:e,file:i});if(!p)throw new Error("Attachment not created");r?this.uploadToResolver({file:i,attachment:p,metadata:a,resolve:s,reject:c}):this.uploadAttachmentToStorage({attachment:p,file:i,resolve:s,reject:c})}catch(p){this.loggingService.catch("Error in StorageService uploadFile:",p),c(p)}})}uploadChunk(e,i,r){return new Promise((a,s)=>{try{if(this.apiKey){let c=`${this.apiKey}/${e}/${i.name}`,p=wy(this.storage,c),h=QL(p,i,{cacheControl:"public,max-age=3600"});h.on("state_changed",_=>{let E=_.bytesTransferred/_.totalBytes*100},_=>{s(_)},()=>{XL(h.snapshot.ref).then(_=>{a(_)}).catch(_=>{this.loggingService.catch(`[uploadChunk] Error getting download URL for chunk ${r}:`,_),s(_)})})}else{let c=new Error("API key not available");this.loggingService.catch("[uploadChunk] API key not available",c),s(c)}}catch(c){this.loggingService.catch(`[uploadChunk] Error in StorageService uploadChunk for chunk ${r}: `,c),s(c)}})}downloadAttachment(e){try{if(e.url){let i=new XMLHttpRequest;i.responseType="blob",i.onload=()=>{let r=i.response,a=document.createElement("a"),s=window.URL.createObjectURL(r);a.setAttribute("type","hidden"),a.setAttribute(U.ATTRIBUTES.VELT_DOWNLOAD_BUTTON,"true"),a.classList.add("snippyly-overlay-panel"),a.href=s,e?.name&&(a.download=e?.name),document.body.appendChild(a);let c=new MouseEvent("click",{view:window,bubbles:!0,cancelable:!1});a.dispatchEvent(c),window.URL.revokeObjectURL(s),a.remove()},i.onerror=()=>{window.open(e.url,"_blank")},i.open("GET",e.url),i.send()}}catch(i){this.loggingService.catch("Error in StorageService downloadAttachment: ",i)}}deleteAttachment({attachment:e,metadata:i,useAttachmentResolver:r}){return new Promise((a,s)=>{if(r)this.attachmentResolverService.deleteAttachment({attachmentId:e.attachmentId,metadata:i}).then(()=>{a(null)}).catch(c=>{s(c)});else{let c=wy(this.storage,e.bucketPath);ZL(c).then(()=>{a(null)}).catch(p=>{a(null)})}})}deleteFileFromPath(e){return new Promise((i,r)=>{let a=wy(this.storage,e);ZL(a).then(()=>{i(null)}).catch(s=>{r(s)})})}};o.\u0275fac=function(i){return new(i||o)(J(je),J($t),J(y),J(Lp))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var gn=(()=>{let o=class o{constructor(e,i,r,a,s,c,p,h){this.analyticsService=e,this.authService=i,this.contactService=r,this.databaseService=a,this.docService=s,this.configService=c,this.loggingService=p,this.commonDbService=h,this.documentIAM$=new fe(null),this.workspaceIAM$=new fe(null),this.roles$=new fe([]),this.getDocumentIamSubscription=null,this.getOrganizationIamSubscription=null,this.getWorkspaceIamSubscription=null;try{this.authService.setIamService(this),this.databaseService.getDb().pipe(Ne(_=>!!_),Je(1)).subscribe(_=>{_&&(this.db=_,this.getUser(),this.getDocumentPaths())},_=>{this.loggingService.catch("Error in CommentService getDb subscription: ",_)}),this.getRole$().pipe(Je(1)).subscribe(_=>{this.authService?.getUser()&&!_&&this.analyticsService.trackEvent(Z.Events.Iam.USER_ACCESS_DENIED)}),this.documentIAM$.subscribe(_=>{_?.accessType&&this.contactService.setDocumentAccessType(_.accessType)})}catch(_){this.loggingService.catch("Error in IamService constructor: ",_)}}clearCache(){this.loggingService.log("%c[WB] Calling FUNCTION: clearCache in IamService","color: green;");try{this.documentIAM$.next(null),this.workspaceIAM$.next(null),this.roles$.next([]),this.documentPaths=null}catch(e){this.loggingService.catch("Error in IamService clearCache: ",e)}}getUser(){try{this.authService.getUser$().pipe(Ne(e=>!!e)).subscribe(e=>{this.user=e,this.user?this.getDocumentIam():(this.getDocumentIamSubscription?.unsubscribe(),this.getOrganizationIamSubscription?.unsubscribe(),this.getWorkspaceIamSubscription?.unsubscribe())},e=>{this.loggingService.catch("Error in IamService getUser$ subscription: ",e)})}catch(e){this.loggingService.catch("Error in IamService getUser: ",e)}}getDocumentPaths(){try{this.docService.getDocumentPaths$().pipe(Ne(e=>!!e)).subscribe(e=>{this.documentPaths=e,this.getDocumentIam(),this.getWorkspaceIam()},e=>{this.loggingService.catch("Error in IamService getDocumentPaths$ subscription: ",e)})}catch(e){this.loggingService.catch("Error in IamService getDocumentPaths: ",e)}}getDocumentIam(){try{this.getDocumentIamSubscription&&(this.getDocumentIamSubscription.unsubscribe(),this.getDocumentIamSubscription=null),this.user?this.getDocumentIamSubscription=this.docService.getDocumentIam$().subscribe(e=>{let i=e||new oM;this.documentIAM$.next(i)},e=>{this.loggingService.catch("Error in IamService getDocumentIam$ subscription: ",e)}):this.documentIAM$.next(null)}catch(e){this.loggingService.catch("Error in IamService getDocumentIam: ",e)}}getWorkspaceIam(){try{this.getWorkspaceIamSubscription||(this.getWorkspaceIamSubscription=this.commonDbService.dbListener({feature:"workspaceIam",properties:{skipFirestore:!0}}).pipe(Ln(e=>re(null))).subscribe(e=>{this.workspaceIAM$.next(e?.data),this.roles$.next(e?.data?.roles||[])}))}catch(e){this.loggingService.catch("Error in IamService getWorkspaceIam: ",e)}}isUserAllowed$(){return this.getRole$().pipe(ce(e=>!!e),Kt())}getDocumentIAM$(){return this.documentIAM$.asObservable()}getRoles$(){return this.roles$.asObservable().pipe(ce(e=>e?.length?e:U.WorkspaceRoles))}getFeaturesAccessLevel$(){return this.documentIAM$.asObservable().pipe(ce(e=>e?.features),ge(e=>this.getRole$().pipe(ce(i=>(i===mo.ADMIN&&(e=e&&JSON.parse(JSON.stringify(e||{})),e?.all?.disabled&&(e.all.disabled=!1)),e)))))}hasRole(e){try{return e===this.getRole()}catch(i){return this.loggingService.catch("Error in IamService hasRole: ",i),!1}}hasRoleAny(e=[]){try{return e?.includes(this.getRole()||"")}catch(i){return this.loggingService.catch("Error in IamService hasRoleAny: ",i),!1}}hasRole$(e){try{return this.authService.getUser$().pipe(ge(()=>this.documentIAM$.pipe(Ne(i=>!!i),ge(()=>this.workspaceIAM$.pipe(ce(()=>e===this.getRole()))))))}catch(i){return this.loggingService.catch("Error in IamService hasRole$: ",i),re(!1)}}getRole$(){try{return this.authService.getUser$().pipe(ge(()=>this.configService.getSF$()),ge(()=>this.configService.getSF()?this.contactService.isUserGlobalContact$():re(null)),ge(()=>this.documentIAM$.pipe(Ne(e=>!!e))),ge(()=>this.workspaceIAM$),ce(()=>this.getRole()))}catch(e){return this.loggingService.catch("Error in IamService getRole$: ",e),re(null)}}getRole(){try{let e=this.configService.getSF();if(e&&this.contactService.isUserGlobalContact())return mo.ADMIN;if(!e&&this.user?.isAdmin)return mo.ADMIN;let i=null,r;if(this.user)switch((this.documentIAM$.value?this.documentIAM$.value?.features?.all?.restricted:!1)?di.RESTRICTED:this.documentIAM$.value?this.documentIAM$.value?.documentAccessType||di.PUBLIC:null){case di.PUBLIC:r=this.getUserFromDocumentIAM(this.user?.email,this.user?.userId),r||(r=this.getUserFromWorkspaceIAM(this.user?.email,this.user?.userId)),i=r?.role?.name||mo.COMMENTER;break;case di.RESTRICTED:r=this.getUserFromDocumentIAM(this.user?.email,this.user?.userId),r||(r=this.getUserFromWorkspaceIAM(this.user?.email,this.user?.userId)),i=r?.role?.name||null;break;default:break}return i}catch(e){this.loggingService.catch("Error in IamService getRole: ",e)}return null}isUserAdmin$(){return this.getRole$().pipe(ce(e=>e===mo.ADMIN),Kt())}isUserAdmin(){try{return this.getRole()===mo.ADMIN}catch(e){return this.loggingService.catch("Error in IamService isUserAdmin: ",e),!1}}getUserFromDocumentIAM(e,i){try{if(e||i){let r;return e&&(r=this.documentIAM$.value?.users?.[Rt(e)]),!r&&i&&(r=this.documentIAM$.value?.users?.[Rt(i)]),r}else return}catch(r){this.loggingService.catch("Error in IamService getUserFromDocumentIAM: ",r)}}getUserFromWorkspaceIAM(e,i){try{if(e||i){let r;return e&&(r=this.workspaceIAM$.value?.users?.[Rt(e)]),!r&&i&&(r=this.workspaceIAM$.value?.users?.[Rt(i)]),r}else return}catch(r){this.loggingService.catch("Error in IamService getUserFromWorkspaceIAM: ",r)}}};o.\u0275fac=function(i){return new(i||o)(J(Qe),J(je),J(gi),J(pn),J(lt),J($t),J(y),J(bn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Vn=(()=>{let o=class o{constructor(e,i,r,a,s,c,p,h,_,E,D,B,G,X,he,Ie){this.afAuth=e,this.analyticsService=i,this.authService=r,this.configService=a,this.commonDbService=s,this.commonDbUtilsService=c,this.commentUtilsService=p,this.commentAnnotationsResolverService=h,this.databaseService=_,this.docService=E,this.domService=D,this.iamService=B,this.loggingService=G,this.notificationUtilsService=X,this.usersService=he,this.functions=Ie,this.db=Ci(),this.notificationsDb=Ci(void 0,Zn.firebaseNotificationsDatabaseURL),this.documentPaths=null,this.notifications$=new fe([]),this.rawNotificationsByIdMap$=new fe(new Map),this.processedNotifications$=new fe([]),this.readNotificationsOnForYouTab$=new fe(!1),this.notificationViews$=new fe({}),this.notificationsByIdMap$=new fe(new Map),this.historyPanelVisible$=new fe(!1),this.notificationsForYou$=new fe(null),this.notificationsByDocumentIdMap$=new fe(null),this.notificationsByDocumentIdSubscription={},this.allowedDocumentMetadataMap$=new fe(null),this.maxNotificationDays$=new fe(15),this.tabConfig$=new fe({people:{enable:!1}});try{this.subscribeNotificationsData().subscribe(),this.commentUtilsService.setNotificationService(this),this.databaseService.getDb().pipe(Ne(Me=>!!Me),Je(1)).subscribe(Me=>{Me&&(this.db=Me,this.getDocumentIds(),this.subscribeGetNotificationsForYou())},Me=>{this.loggingService.catch("Error in NotificationService getDb subscription: ",Me)}),this.authService.getUser$().subscribe(Me=>{Me?(this.subscribeGetNotificationsForYou(),this.getDocumentIds()):(Object.keys(this.notificationsByDocumentIdSubscription).forEach(Le=>{this.notificationsByDocumentIdSubscription[Le]?.unsubscribe()}),this.notificationForYouSubscription?.unsubscribe(),this.documentIdsSubscription?.unsubscribe(),this.resetCacheData())}),this.docService.getLocationMetadata$().subscribe(Me=>{if(Me){let Le=this.notificationsByDocumentIdMap$.getValue()?JSON.parse(JSON.stringify(this.notificationsByDocumentIdMap$.getValue())):null;Object.keys(Me||{}).forEach(We=>{let ke=Le?.[We]?.notifications;ke?.length&&ke.forEach(we=>{this.notificationUtilsService.mergeLocationWithNotification({notification:we},Me)?.notification})}),this.notificationsByDocumentIdMap$.next(Le)}})}catch(Me){this.loggingService.catch("Error in NotificationService constructor: ",Me)}}resetCacheData(){try{this.loggingService.log("%c[WB] Calling NotificationService FUNCTION: resetCacheData","color: green;"),this.notificationsByDocumentIdMap$.next(null),this.notificationsForYou$.next(null)}catch(e){this.loggingService.catch("Error in NotificationService resetCacheData: ",e)}}subscribeGetNotificationsForYou(){try{this.notificationForYouSubscription&&this.notificationForYouSubscription.unsubscribe(),this.notificationForYouSubscription=this.getNotificationsForYou().subscribe(()=>{},e=>{this.loggingService.catch("Error in NotificationService getNotificationsForYou subscription: ",e)})}catch(e){this.loggingService.catch("Error in NotificationService subscriveGetNotificationsForYou: ",e)}}setCommentService(e){try{this.commentService=e}catch(i){this.loggingService.catch("Error in NotificationService setCommentService: ",i)}}getDocumentIds(){try{this.documentIdsSubscription&&this.documentIdsSubscription.unsubscribe(),this.documentIdsSubscription=this.getDocumentIdsByLastNotificationTimestamp().pipe(Vi(),ce(([e,i])=>{let r=e?.map(h=>h.documentId),a=i?.map(h=>h.documentId),s=r?.filter(h=>!a?.includes(h)),c=a?.map(h=>({documentId:h,timestamp:i?.find(_=>_.documentId===h)?.timestamp})).filter(h=>!r?.includes(h.documentId)),p=a?.map(h=>{let _=i?.find(E=>E.documentId===h)?.timestamp;return{documentId:h,timestamp:_}}).filter(h=>{let _=e?.find(E=>E.documentId===h.documentId)?.timestamp;return _&&h.timestamp&&_!==h.timestamp});c?.length&&this.fetchNotificationsForDocumentIds(c),p?.length&&this.fetchNotificationsForDocumentIds(p,1),s?.forEach(h=>{this.removeNotificationsForDocumentId(h)}),i&&!i?.length&&!this.notificationsByDocumentIdMap$.getValue()&&this.notificationsByDocumentIdMap$.next({})})).subscribe(()=>{},e=>{this.loggingService.catch("Error in NotificationService getDocumentIds subscription: ",e)})}catch(e){this.loggingService.catch("Error in NotificationService getDocumentIds: ",e)}}getDocumentIdsByLastNotificationTimestamp(e=15){try{return this.authService.getUser$().pipe(ge(i=>this.docService.getOrganizationConfig$().pipe(ce(r=>{let a=null,s=this.configService.getApiKey(),c=r?.organizationId||i?.organizationId;return s&&c&&(a=new xd({apiKey:s,organizationId:c})),{user:i,documentPaths:a}}))),ge(i=>{let{user:r,documentPaths:a}=i;if(r&&a?.organizationNotificationsLastNotificationTimestamp){let s=new Date,c=this.maxNotificationDays$.getValue()>0?this.maxNotificationDays$.getValue():15;s.setDate(s.getDate()-c);let p=s.getTime();return this.commonDbService.dbListener({feature:"allLastNotificationTimestamp",properties:{organizationId:a?.organizationId,isCollection:!0,useQuery:!0,firestoreQuery:[Fi(mt("timestamp",">=",p)),Ga("timestamp","desc"),Rv(e)]}}).pipe(ce(h=>h?.data),ce(h=>{let _=[];return Object.keys(h||{}).forEach(E=>{let D=this.commonDbService.shouldUseFirestore()?h[E]?.timestamp??0:h[E],B=this.commonDbService.shouldUseFirestore()?h[E]?.deletedNotification??!1:!1;if(B&&B.id&&B?.timestamp===D){let G=B.id,X=h[E]?.metadata?.documentId,he=JSON.parse(JSON.stringify(this.notificationsByDocumentIdMap$.getValue()??{})),Ie=he?.[X]??{documentMetadata:null,notifications:[]},Me=Ie.notifications??[],Le=Me?.findIndex(We=>We.notificationId===G);Le!==-1&&(Me.splice(Le,1),this.notificationsByDocumentIdMap$.next(T(I({},he),{[X]:T(I({},Ie),{notifications:Me})})))}else _.push({documentId:E,timestamp:D})}),_}),Ln(h=>(this.loggingService.catch("Error in NotificationService getDocumentIdsByLastNotificationTimestamp: ",h),re([]))))}return re(null)}))}catch(i){return this.loggingService.catch("Error in NotificationService getDocumentIdsByLastNotificationTimestamp: ",i),re([])}}fetchNotificationsForDocumentIds(e,i=15){return ee(this,null,function*(){try{if(e?.length){let r=Cr(this.functions,Zn.cloudFunction.getNotificationsForDocuments,{timeout:12e5}),a=this.docService.getOrganizationConfig()?.organizationId??"",s=this.getStartAtTimestamp(),c={};e.forEach(B=>{if(B?.documentId){let G=this.getAllowedDocumentMetadataByDocumentId(B.documentId);G&&(c[B.documentId]=G)}});let p={organizationId:a,documentIds:e,timestamp:s,limitToLast:i,documentMetadataByDocumentId:c},h=yield this.notificationUtilsService.handleNotificationEncryption({data:p}),_=(yield r({veltData:h}))?.data?.data?.veltData||{},E="notificationwithdocumentidstoencryptanddecryptonsdk"+(this.authService.getUser()?.userId??""),D=yield Pie(_,E);if(D&&typeof D=="object"){let B=this.usersService.userDataProviderAvailable(),G=this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable(),X=[],he=[];Object.keys(D).forEach((Ie,Me)=>{let Le=D[Ie].documentMetadata;if(Le){let ke=this.allowedDocumentMetadataMap$.value||{};(!ke?.[Ie]||!Co(ke?.[Ie],Le))&&this.allowedDocumentMetadataMap$.next(T(I({},ke),{[Ie]:Le}))}let We=D[Ie].notifications||[];We.forEach(ke=>{ke.notification=this.getClientNotificationObject(ke)}),this.setNotificationForDocumentIdInCache(Ie,Le,We),B&&X.push(this.commonDbUtilsService.formatResponse({feature:"allDocNotifications",data:We,shouldAwait:!0,forceResolve:!0})),G&&he.push(this.commonDbUtilsService.formatResponse({feature:"allDocNotifications",data:We,shouldCommentAnnotationsResolverAwait:!0}))}),B&&Promise.all(X).then(()=>{Object.keys(D).forEach(Ie=>{let Me=D?.[Ie]?.documentMetadata||{},Le=this.commonDbUtilsService.mergeUsersWithData({feature:"allDocNotifications",data:D?.[Ie]?.notifications||[]});Le.forEach(We=>{We.notification=this.getClientNotificationObject(We)}),this.setNotificationForDocumentIdInCache(Ie,Me,Le)})}),G&&Promise.all(he).then(()=>{Object.keys(D).forEach(Ie=>{let Me=D?.[Ie]?.documentMetadata||{},Le=D?.[Ie]?.notifications?.reduce((We,ke)=>(We[ke.notificationId]=ke,We),{});Le=this.commonDbUtilsService.mergeCommentAnnotationsWithData({feature:"allDocNotifications",data:Le}),Le=Object.values(Le??{}),Le.forEach(We=>{We.notification=this.getClientNotificationObject(We)}),this.setNotificationForDocumentIdInCache(Ie,Me,Le)})})}}}catch(r){return this.loggingService.catch("Error in NotificationService fetchNotificationsForDocumentIds: ",r),[]}})}setNotificationForDocumentIdInCache(e,i,r,a){try{let s=this.docService.getOrganizationConfig()?.organizationId??"",c=this.docService.getOrganizationMetadata(s);i||(i=JSON.parse(JSON.stringify(this.docService.getDocumentMetadata()||{}))),c||(c=JSON.parse(JSON.stringify(this.docService.getOrganizationMetadata(s)||{})));let p=this.notificationsByDocumentIdMap$.getValue(),h=p?.[e]?.notifications||[],_=this.docService.getLocationMetadatas(),E=r?.map(G=>{let X=G.notification;return X.metadata&&(X.metadata.documentName=i?.documentName||X.metadata.documentName,X.metadata.organizationMetadata=c||X.metadata.organizationMetadata,X.metadata.documentMetadata=i||X.metadata.documentMetadata),_&&(X=this.notificationUtilsService.mergeLocationWithNotification({notification:X},_)?.notification),X})?.filter(G=>!!G)||[],D=new Map(h.map(G=>[G.id,G]));E.forEach(G=>{D.set(G.id,G)});let B=Array.from(D.values()).sort((G,X)=>(X.timestamp||0)-(G.timestamp||0));this.notificationsByDocumentIdMap$.next(T(I({},p),{[e]:{notifications:B,documentMetadata:i}}))}catch(s){this.loggingService.catch("Error in NotificationService setNotificationForDocumentIdInCache: ",s)}}removeNotificationsForDocumentId(e){try{this.notificationsByDocumentIdSubscription[e]&&this.notificationsByDocumentIdSubscription[e].unsubscribe();let i=this.notificationsByDocumentIdMap$.getValue();delete i?.[e],this.notificationsByDocumentIdMap$.next(i)}catch(i){this.loggingService.catch("Error in NotificationService removeNotificationsForDocumentId: ",i)}}getNotificationsForDocumentId$(e,i=50){try{return this.authService.getUser$().pipe(ce(r=>({user:r})),ge(r=>this.maxNotificationDays$.pipe(ce(()=>r))),ge(r=>{let{user:a}=r,s=this.configService.getApiKey();if(a&&s){let c=new Date,p=this.maxNotificationDays$.getValue()>0?this.maxNotificationDays$.getValue():15;c.setDate(c.getDate()-p);let h=c.getTime();return bo(this.commonDbService.queryData({feature:"allDocNotifications",properties:{rtdbQuery:[EL("timestamp"),TL(h),IL(i)],firestoreQuery:[Ga("timestamp","desc"),mt("timestamp",">=",h),mt("notification.actionUser.userId","!=",a.userId),Rv(i)],apiKey:s,organizationId:this.docService?.getDocumentPaths()?.organizationId||a?.organizationId,documentId:e}})).pipe(ge(_=>this.commonDbUtilsService.mergeUsersWithData$({feature:"allDocNotifications",data:{data:_,operation:null}})),ce(_=>_?.data??[]),ce(_=>(_.sort((E,D)=>D.timestamp-E.timestamp),_)),Ln(_=>(this.loggingService.catch("Error in NotificationService getNotificationsForDocumentId: ",_),re([]))),ce(_=>(_.forEach(E=>{E.notification=this.getClientNotificationObject(E)}),_)))}return re([])}))}catch(r){return this.loggingService.catch("Error in NotificationService getNotificationsForDocumentId: ",r),re([])}}getStartAtTimestamp(){try{let e=new Date,i=this.maxNotificationDays$.getValue()>0?this.maxNotificationDays$.getValue():15;return e.setDate(e.getDate()-i),e.getTime()}catch(e){return this.loggingService.catch("Error in NotificationService getStartAtTimestamp: ",e),0}}getNotificationsForYou(){try{return this.databaseService.getDb().pipe(ge(e=>this.authService.getUser$().pipe(ce(i=>({db:e,user:i})))),ge(e=>this.maxNotificationDays$.pipe(ce(()=>e))),ge(e=>{let{db:i,user:r}=e,a=this.configService.getApiKey();if(i&&r?.organizationId&&a){let s=Rt(r?.userId),c=new Date,p=this.maxNotificationDays$.getValue()>0?this.maxNotificationDays$.getValue():15;c.setDate(c.getDate()-p);let h=c.getTime();return this.commonDbService.dbListener({feature:"allUserNotifications",properties:{useQuery:!0,isCollection:!0,rtdbQuery:[EL("timestamp"),TL(h),IL(50)],firestoreQuery:[Ga("timestamp","desc"),mt("timestamp",">=",h),mt("notification.actionUser.userId","!=",r.userId),Rv(50)],apiKey:a,organizationId:this.docService?.getDocumentPaths()?.organizationId||r?.organizationId,documentId:this.docService.getDocumentPaths()?.documentId,userId:s}}).pipe(ge(_=>_?.data?re(_).pipe(ce(E=>E?.data),ce(E=>{let D=Object.values(E||{});return D.forEach(G=>{G.notification=this.getClientNotificationObject(G)}),D.sort((G,X)=>X.timestamp-G.timestamp),D.map(G=>G.notification).filter(G=>!!G)}),ge(E=>{let D={data:E?.reduce((B,G)=>(B[G.id]={notification:G},B),{}),operation:null};return this.commonDbUtilsService.mergeLocationMetadataWithData$({data:D,feature:"allUserNotifications"}).pipe(ce(B=>Object.values(B?.data||{}).map(G=>G?.notification)))})):re(null)))}return re(null)}),ge(e=>{let i=this.docService.getOrganizationConfig()?.organizationId??"";return this.docService.getOrganizationMetadata$(i).pipe(ce(()=>e))}),ge(e=>this.allowedDocumentMetadataMap$.pipe(ce(()=>e))),ce(e=>(e?.length&&(e=e.map(i=>{if(i?.metadata){let r=this.docService.getOrganizationConfig()?.organizationId??"",a=this.getAllowedDocumentMetadataByDocumentId(i.metadata.documentId),s=this.docService.getOrganizationMetadata(r);a||(a=JSON.parse(JSON.stringify(this.docService.getDocumentMetadata()||{}))),s||(s=JSON.parse(JSON.stringify(this.docService.getOrganizationMetadata(r)||{}))),i.metadata.documentName=a?.documentName||i.metadata.documentName,i.metadata.organizationMetadata=s||i.metadata.organizationMetadata,i.metadata.documentMetadata=a||i.metadata.documentMetadata}return i})),e===null?this.notificationsForYou$.next(null):e?.length?this.notificationsForYou$.next(e):this.notificationsForYou$.next([]),re(e))))}catch(e){return this.loggingService.catch("Error in NotificationService getNotificationsForYou: ",e),re({})}}subscribeNotificationsData(e,i){this.loggingService.log("%c[WB] Calling FUNCTION: subscribeViewsData","color: green;");let r,a;try{if(e&&(a=fn(e)),i&&typeof i=="object"){let s=Xo(i);r=fn(JSON.stringify(s))}}catch(s){this.loggingService.catch("Error in ViewsService subscribeViewsData: ",s)}return Wn(this.afAuth).pipe(Ne(s=>!!s),ge(s=>this.isFeatureAllowed({firebaseUser:s})),ge(s=>s.featureAllowed?this.iamService.isUserAllowed$().pipe(ce(c=>(s.featureAllowed=c,s))):re(s)),ge(s=>!s.featureAllowed||s?.user?.organizationId?(this.notifications$.next([]),this.rawNotificationsByIdMap$.next(new Map),this.processedNotifications$.next([]),this.notificationsByIdMap$.next(new Map),this.notificationViews$.next({}),this.setNotificationsByIdMap(),re([])):re(s).pipe(ge(c=>this.docService.getDocumentPaths$().pipe(ce(p=>(this.documentPaths=p,c.documentPaths=p,c)))),ge(c=>this.getDataFromDocumentId(a)))))}isFeatureAllowed(e){return this.configService.getConfig$().pipe(Ne(i=>!!i),ce(i=>T(I({},e),{config:i})),ge(i=>this.authService.getUser$().pipe(ce(r=>T(I({},i),{user:r})))),ge(i=>Xi(i.config,i.user,Re.NOTIFICATION)?re(T(I({},i),{featureAllowed:!0})):(this.loggingService.warn("Notification feature is not allowed."),re(T(I({},i),{featureAllowed:!1})))))}getDataFromDocumentId(e){return this.databaseService.getDb().pipe(Ne(i=>!!i),ge(i=>{if(this.db=i,this.loggingService.log(this.db),this.configService?.getApiKey()&&this.documentPaths?.views){let r=`${this.configService.getApiKey()}`;this.documentPaths?.organizationId&&(r+=`/${U.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${this.documentPaths.organizationId}`);let a=on(this.db,`${e?r+"/"+U.FIREBASE_PARTIAL_PATH_DOCS+"/"+e+"/"+U.FIREBASE_PARTIAL_PATH_VIEWS+"/":this.documentPaths?.notifications}`);return Af(a).pipe(Ln(s=>(this.loggingService.catch("Error in NotificationService getDataFromDocumentId: ",s),re(null))),ce(s=>{let c=[],p=new Map;s?.raw&&(Object.keys(s?.raw||{}).forEach(_=>{let E=s?.raw[_];E?.id&&c.push(E)}),c.forEach(_=>{_.id&&p.set(_.id,_)})),this.notifications$.next(c),this.rawNotificationsByIdMap$.next(p);let h=[];s?.processed&&Object.keys(s?.processed||{}).forEach(_=>{let E=s?.processed[_];E?.id&&h.push(E)}),this.processedNotifications$.next(h),this.setNotificationsByIdMap()}))}else return re(null)}))}setNotificationsByIdMap(){try{let e=this.authService.getUser();if(e){let i=this.notificationViews$.getValue(),r;e?.email&&(r=Rt(e?.email));let a;e?.userId&&(a=Rt(e?.userId));let s=new Map;this.processedNotifications$.getValue().forEach(p=>{if(p.id&&p?.displayHeadlineMessageTemplate){let h=!1;(r&&p.notifyUsers?.[r]||a&&p.notifyUsers?.[a])&&(h=!0);let _={id:p.id,notificationSource:p.notificationSource,actionType:p.actionType,actionUser:p.actionUser,timestamp:p.timestamp,targetAnnotationId:p.targetAnnotationId,displayHeadlineMessage:this.getNotificationHeadlineMessage(p),displayBodyMessage:this.getNotificationBodyMessage(p),forYou:h,notificationSourceData:p.notificationSourceData},E=this.getRawNotificationById(_.id);if(E?.metadata&&(_.metadata={apiKey:E.metadata.apiKey,organizationId:E.metadata.organizationId,clientOrganizationId:E.metadata.clientOrganizationId,documentId:E.metadata.documentId,clientDocumentId:E.metadata.clientDocumentId,location:E?.location,locationId:E?.locationId}),_?.notificationSource==="comment"&&_?.targetAnnotationId){let D=this.commentService?.getAnnotationById(_.targetAnnotationId);D||E?.annotationData&&(D=E.annotationData),D&&(_.notificationSourceData=$n(D))}s.set(p.id,_)}}),s.forEach((p,h)=>{p.isUnread=p?.actionUser?.userSnippylyId!==e?.userSnippylyId&&!i?.notification?.[h]?.views?.[e?.userSnippylyId],s.set(h,p)}),this.notificationsByIdMap$.next(s)}}catch(e){this.loggingService.catch("Error in NotificationService setNotificationsByIdMap: ",e)}}getClientNotificationObject({processed:e,raw:i,metadata:r,views:a,notification:s}){try{let c=this.authService.getUser(),p=s||e;if(p.id&&p?.displayHeadlineMessageTemplate&&c){let h=null;c?.email&&(h=Rt(c?.email));let _=null;c?.userId&&(_=Rt(c?.userId));let E=!1,D=!0;(h&&p.notifyUsers?.[h]||_&&p.notifyUsersByUserId?.[_])&&(E=!0),_&&a?.[_]&&(D=!1);let B={id:p.id};if(s?B=T(I(I({},B),s),{displayHeadlineMessage:this.getNotificationHeadlineMessage(s),displayBodyMessage:this.getNotificationBodyMessage(s),forYou:E,isUnread:D}):B={id:e.id,notificationSource:e.notificationSource,actionType:e.actionType,actionUser:e.actionUser,timestamp:e.timestamp,targetAnnotationId:e.targetAnnotationId,displayHeadlineMessage:this.getNotificationHeadlineMessage(e),displayBodyMessage:this.getNotificationBodyMessage(e),forYou:E,isUnread:D,metadata:r},B?.notificationSource==="comment"&&B?.targetAnnotationId){let G=this.commentService?.getAnnotationById(B.targetAnnotationId);G||s?.notificationSourceData&&(G=s?.notificationSourceData),G||i?.annotationData&&(G=i.annotationData),G&&(B.notificationSourceData=$n(G))}return i?.targetAnnotationData?.isCommentResolverUsed&&(B.isCommentResolverUsed=i?.targetAnnotationData?.isCommentResolverUsed),B}return}catch(c){this.loggingService.catch("Error in NotificationService getClientNotificationObject: ",c);return}}getNotificationsForYou$(){return this.notificationsForYou$.asObservable()}getNotificationsByDocumentId$(){return this.notificationsByDocumentIdMap$.asObservable().pipe(ce(e=>e?Object.keys(e??{}).map(i=>{let r=e[i].notifications||[],a=r.filter(c=>c.isUnread).length,s=r.length>0&&r[0]?.timestamp||0;return{documentId:i,notifications:e[i]?.notifications,unreadNotificationsCount:a,latestNotificationTimestamp:s,documentMetadata:e[i]?.documentMetadata}}).filter(i=>i.notifications?.length>0).sort((i,r)=>r.latestNotificationTimestamp-i.latestNotificationTimestamp):null))}getAllNotifications$(){return this.getNotificationsByDocumentId$().pipe(ce(e=>{let i=null;return e?(i=[],e.forEach(r=>{r.notifications.forEach(a=>{i?.push(a)})}),i?.sort((r,a)=>a.timestamp-r.timestamp)):null}))}processNotificationData(e){try{let i=e?.annotationData?.metadata,r=this.docService.getOrganizationConfig()?.organizationId;e.metadata=JSON.parse(JSON.stringify(this.docService.getDocumentMetadata(i?.documentId)||{})),e.metadata||(e.metadata={},this.loggingService.catch("Warning in NotificationService updateNotificationDatabase: ","Document metadata not found")),delete e.metadata.locations,e.metadata.documentMetadata=JSON.parse(JSON.stringify(this.docService.getDocumentMetadata(i?.documentId)||{})),e?.metadata?.documentMetadata?.clientDocumentId&&e?.metadata?.documentMetadata?.documentId&&(e.metadata.documentMetadata.documentId=e?.metadata?.documentMetadata?.clientDocumentId),delete e.metadata.documentMetadata.locations,e.metadata.organizationMetadata=JSON.parse(JSON.stringify(r?this.docService.getOrganizationMetadata(r)||{}:{})),e?.metadata?.organizationMetadata?.clientOrganizationId&&e?.metadata?.organizationMetadata?.organizationId&&(e.metadata.organizationMetadata.organizationId=e?.metadata?.organizationMetadata?.clientOrganizationId);let a=this.configService.getApiKey();e.metadata.apiKey=a,e.platform=this.configService.getSF()?"sf":"sdk",e.actionUser=this.authService.getUser();let s=i?.documentId?new xd({apiKey:a,documentId:i.documentId,organizationId:i?.organizationId}):this.docService.getDocumentPaths();e?.actionUser?.organizationId&&(e.metadata.organizationId=s?.organizationId||e.actionUser.organizationId,e.metadata.clientOrganizationId=s?.clientOrganizationId||e.actionUser.clientOrganizationId);let c=this.docService.getLocation();c&&(e.location=c?.location,e.locationId=c?.locationId),this.loggingService.log(`[NOTIFICATION] ${e?.notificationSource} ${e?.actionType}`,e);let p=this.commonDbService.getServerTimestamp(),h=this.notificationUtilsService.formatNotification(e,p);return JSON.parse(JSON.stringify(h))}catch(i){return this.loggingService.catch("Error in NotificationService processNotificationData: ",i),null}}updateNotificationDatabase(e){try{let i=on(this.notificationsDb),r=this.processNotificationData(e);RA(i,JSON.parse(JSON.stringify(r)))}catch(i){this.loggingService.catch("Error in NotificationService updateNotificationDatabase: ",i)}}getRawNotifications$(){return this.notifications$.asObservable()}getProcessedNotifications$(){return this.processedNotifications$.asObservable()}getNotifications$(){return this.authService.getUser$().pipe(ge(e=>e?e.organizationId?this.getAllNotifications$().pipe(ge(i=>this.notificationsForYou$.pipe(ce(r=>{let a=new Map;return(i||[]).forEach(s=>{s.id&&a.set(s.id,s)}),(r||[]).forEach(s=>{s.id&&!a.has(s.id)&&a.set(s.id,s)}),Array.from(a.values()).sort((s,c)=>(c.timestamp||0)-(s.timestamp||0))})))):this.notificationsByIdMap$.asObservable().pipe(ce(i=>Array.from(i.values())),ce(i=>i.sort((r,a)=>a.timestamp-r.timestamp)),Eg()):re(null)))}getRawNotificationById(e){try{return this.rawNotificationsByIdMap$.getValue()?.get(e)}catch(i){this.loggingService.catch("Error in NotificationService getRawNotificationById: ",i);return}}setNotificationViews(e){try{this.notificationViews$.next(e),this.setNotificationsByIdMap()}catch(i){this.loggingService.catch("Error in NotificationService setNotificationViews: ",i)}}getNotificationHeadlineMessage(e){try{let i=this.authService.getUser();if(e?.displayHeadlineMessageTemplate&&e?.displayHeadlineMessageTemplateData){let r=e.displayHeadlineMessageTemplate,a=e.displayHeadlineMessageTemplateData,s=/\{(\w+)\}/g,c=r.replace(s,(p,h)=>(h==="actionUser"||h==="recipientUser")&&a[h]?i?.email&&a[h].email===i?.email||i?.userId&&a[h]?.userId===i?.userId?"You":a[h].name||a[h].email||' <velt-skeleton-loader width="50px" height="20px" border-radius="4px"></velt-skeleton-loader> ':a[h]?a[h]:p);return this.domService.sanitizeHtml(c)}return this.domService.sanitizeHtml(e.displayHeadlineMessageTemplate||"")}catch(i){return this.loggingService.catch("Error in NotificationService getNotificationHeadlineMessage: ",i),""}}getNotificationBodyMessage(e){try{if(e?.displayBodyMessageTemplate&&e?.displayBodyMessageTemplateData){let i=e?.displayBodyMessageTemplate;return e?.displayBodyMessageTemplateData&&e?.displayBodyMessageTemplateData?.users?.forEach(r=>{if(r?.userId){let a=this.usersService.getUserById(r?.userId);i=i?.replaceAll(`{{${r.userId}}}`,a?.name||a?.email||'<velt-skeleton-loader width="50px" height="20px" border-radius="4px"></velt-skeleton-loader>')}}),this.domService.sanitizeHtml(i)}return this.domService.sanitizeHtml(e.displayBodyMessage||"")}catch(i){return this.loggingService.catch("Error in NotificationService getNotificationBodyMessage: ",i),""}}setHistoryPanelVisibility(e,i=!1,r=!1){try{e?document.querySelector(U.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL)?this.historyPanelVisible$.next(e):this.loggingService.catch("Error in NotificationService setHistoryPanelVisibility: ",`<${U.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`):this.historyPanelVisible$.next(e),e?this.analyticsService.trackEvent(Z.Events.Notifications.NOTIFICATION_HISTORY_PANEL_OPENED):this.analyticsService.trackEvent(Z.Events.Notifications.NOTIFICATION_HISTORY_PANEL_CLOSED)}catch{this.loggingService.catch("Error in NotificationService setHistoryPanelVisibility: ",`<${U.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`)}}toggleHistoryPanelVisibility(e=!1,i=!1){try{this.historyPanelVisible$.value?this.historyPanelVisible$.next(!this.historyPanelVisible$.value):document.querySelector(U.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL)?(this.historyPanelVisible$.next(!this.historyPanelVisible$.value),this.historyPanelVisible$.value?this.analyticsService.trackEvent(Z.Events.Notifications.NOTIFICATION_HISTORY_PANEL_TOGGLED,{action:"closed"}):this.analyticsService.trackEvent(Z.Events.Notifications.NOTIFICATION_HISTORY_PANEL_TOGGLED,{action:"opened"})):this.loggingService.catch("Error in NotificationService toggleHistoryPanelVisibility: ",`<${U.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`)}catch{this.loggingService.catch("Error in NotificationService toggleHistoryPanelVisibility: ",`<${U.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`)}}getHistoryPanelVisibility$(){return this.historyPanelVisible$.asObservable()}setNotificationsAsRead(e){return ee(this,null,function*(){try{if(e?.length){for(let a=0;a<e.length;a+=50){let c=e.slice(a,a+50).filter(p=>p?.id).map(p=>this.setNotificationAsRead(p));yield Promise.all(c)}let r=JSON.parse(JSON.stringify(this.notificationsByDocumentIdMap$.getValue()||{}));e.forEach(a=>{let s=a.metadata?.documentId;if(s&&r?.[s]){let c=r?.[s]?.notifications||[],p=c.find(h=>h.id===a.id);p&&(p.isUnread=!1),r[s].notifications=c}}),this.notificationsByDocumentIdMap$.next(r)}}catch(i){this.loggingService.catch("Error in NotificationService setNotificationsAsRead: ",i)}})}setAllNotificationsAsRead(e){return ee(this,null,function*(){try{if(e?.tabId==="for-you"){let i=this.notificationsForYou$.value||[];this.setNotificationsAsRead(i)}else this.getNotifications$().pipe(Je(1)).subscribe(i=>{i&&this.setNotificationsAsRead(i)})}catch(i){this.loggingService.catch("Error in NotificationService setAllNotificationsAsRead: ",i)}})}getUnreadNotificationsCount$(){try{return this.notificationsForYou$.pipe(ce(e=>e?.filter(r=>r?.isUnread)?.length??null),ge(e=>this.getNotifications$().pipe(ce(i=>{let r=i?.filter(a=>a?.isUnread)?.length??null;return{forYou:e,all:r}}))))}catch(e){return this.loggingService.catch("Error in NotificationService getUnreadNotificationsCount$: ",e),re({forYou:null,all:null})}}setNotificationAsRead(e){return ee(this,null,function*(){try{let i=this.authService.getUser();if(i&&e?.id){let r=Rt(i?.userId),{metadata:a}=e;if(a){let{apiKey:s,organizationId:c,documentId:p}=a;if(s&&c&&p&&r){let h=yield this.commonDbService.getData({feature:"docNotification",properties:{id:e.id,organizationId:c,documentId:p,apiKey:s}});h?.notificationId&&(h?.views?.[r]||(h.views||(h.views={}),h.views[r]={timestamp:Date.now()},this.commonDbService.updateData({feature:"docNotificationViews",properties:{id:e.id,organizationId:c,documentId:p,apiKey:s},data:h})));let _=yield this.commonDbService.getData({feature:"userNotification",properties:{id:e.id,userId:r,documentId:p,organizationId:c}});_?.notificationId&&(this.getReadNotificationsOnForYouTab()?_?.views?.[r]||(_.views||(_.views={}),_.views[r]={timestamp:Date.now()},this.commonDbService.updateData({feature:"userNotificationViews",properties:{id:e.id,userId:r,documentId:p,organizationId:c},data:_})):yield this.commonDbService.deleteData({feature:"userNotification",properties:{id:e.id,userId:r,documentId:p,organizationId:c}}))}}}}catch(i){this.loggingService.catch("Error in NotificationService setNotificationAsRead: ",i)}})}setMaxDays(e){try{e>0?this.maxNotificationDays$.next(e):this.maxNotificationDays$.next(15)}catch(i){this.loggingService.catch("Error in NotificationService setMaxDays: ",i)}}setTabConfig(e){try{e&&this.tabConfig$.next(e)}catch(i){this.loggingService.catch("Error in NotificationService setTabConfig: ",i)}}getTabConfig$(){return this.tabConfig$.asObservable()}getTabConfig(){return this.tabConfig$.value}enableReadNotificationsOnForYouTab(){this.readNotificationsOnForYouTab$.next(!0)}disableReadNotificationsOnForYouTab(){this.readNotificationsOnForYouTab$.next(!1)}getReadNotificationsOnForYouTab$(){return this.readNotificationsOnForYouTab$.asObservable()}getReadNotificationsOnForYouTab(){return this.readNotificationsOnForYouTab$.value}markNotificationAsReadById(e){return ee(this,null,function*(){try{this.getAllNotifications$().pipe(Je(1)).subscribe(i=>{if(i){let r=i.filter(a=>a.id===e);this.setNotificationsAsRead(r)}})}catch(i){this.loggingService.catch("Error in NotificationService markNotificationAsReadById: ",i)}})}getAllowedDocumentMetadataByDocumentId(e){try{return this.allowedDocumentMetadataMap$.value?.[e]||null}catch(i){return this.loggingService.catch("Error in NotificationService getAllowedDocumentMetadataByDocumentId: ",i),null}}};o.\u0275fac=function(i){return new(i||o)(J(vi),J(Qe),J(je),J($t),J(bn),J($v),J(Uv),J(vs),J(pn),J(lt),J(Fe),J(gn),J(y),J(TM),J(Hn),J(Vo))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var $o=(()=>{let o=class o{constructor(e){this.loggingService=e,this._customStatusMap=new fe(U.CommentAnnotationStatusMap),this._customPriorityMap=new fe(U.CommentAnnotationPriorityMap),this._customCategoryMap=new fe(U.CommentCategoryMap);try{let i=sessionStorage.getItem(U.SESSION_STORAGE.VELT_CUSTOM_PRIORITY_MAP);i&&this._customPriorityMap.next(JSON.parse(i));let r=sessionStorage.getItem(U.SESSION_STORAGE.VELT_CUSTOM_STATUS_MAP);r&&this._customStatusMap.next(JSON.parse(r));let a=sessionStorage.getItem(U.SESSION_STORAGE.VELT_CUSTOM_CATEGORY_MAP);a&&this._customCategoryMap.next(JSON.parse(a))}catch(i){this.loggingService.catch("Error in CustomFilterService constructor: ",i)}}setCustomStatusFilters(e){try{if(e.length<2){this._customStatusMap.next(U.CommentAnnotationStatusMap),sessionStorage.setItem(U.SESSION_STORAGE.VELT_CUSTOM_STATUS_MAP,JSON.stringify(U.CommentAnnotationStatusMap)),this.loggingService.catch("Custom status filters must have at least 2 filters");return}let i={};e.forEach(r=>{i[r.id]=r,r.type||(r.type="ongoing")}),this._customStatusMap.next(i),sessionStorage.setItem(U.SESSION_STORAGE.VELT_CUSTOM_STATUS_MAP,JSON.stringify(i))}catch(i){this.loggingService.catch("Error in CustomFilterService setCustomStatusFilters: ",i)}}setCustomPriorityFilters(e){try{if(e.length<2){this._customPriorityMap.next(U.CommentAnnotationPriorityMap),sessionStorage.setItem(U.SESSION_STORAGE.VELT_CUSTOM_PRIORITY_MAP,JSON.stringify(U.CommentAnnotationPriorityMap)),this.loggingService.catch("Custom priority filters must have at least 2 filters");return}let i={};e.forEach(r=>{i[r.id]=r}),this._customPriorityMap.next(i),sessionStorage.setItem(U.SESSION_STORAGE.VELT_CUSTOM_PRIORITY_MAP,JSON.stringify(i))}catch(i){this.loggingService.catch("Error in CustomFilterService setCustomPriorityFilters: ",i)}}setCustomCategories(e){try{let i={};e.forEach(r=>{i[r.id]=r}),this._customCategoryMap.next(i),sessionStorage.setItem(U.SESSION_STORAGE.VELT_CUSTOM_CATEGORY_MAP,JSON.stringify(i))}catch(i){this.loggingService.catch("Error in CustomFilterService setCustomCategories: ",i)}}get customStatusMap$(){return this._customStatusMap.asObservable()}get customPriorityMap$(){return this._customPriorityMap.asObservable()}get customCategoryMap$(){return this._customCategoryMap.asObservable()}get defaultStatus(){try{let i=Object.entries(this._customStatusMap.value).find(([r,a])=>a.type==="default");if(i)return i[1]}catch(e){this.loggingService.catch("Error in CustomFilterService defaultStatus: ",e)}return U.CommentAnnotationStatusMap.OPEN}get resolvedStatus(){try{let i=Object.entries(this._customStatusMap.value).find(([r,a])=>a.type==="terminal");if(i)return i[1]}catch(e){this.loggingService.catch("Error in CustomFilterService resolvedStatus: ",e)}return U.CommentAnnotationStatusMap.OPEN}get ongoingStatuses(){try{let i=Object.entries(this._customStatusMap.value).filter(([r,a])=>a.type==="ongoing");if(i)return i.map(r=>r[1])}catch(e){this.loggingService.catch("Error in CustomFilterService ongoingStatuses: ",e)}return[U.CommentAnnotationStatusMap.IN_PROGRESS]}convertLegacyAnnotationStatus(e){try{if(typeof e.status=="string"||e.status===void 0){let i=Object.entries(this._customStatusMap.value),r=i.find(([a,s])=>s.type==="default");switch(e.status){case"open":r&&(e.status=r[1]);break;case"inProgress":let a=i.find(([c,p])=>p.type==="ongoing");a&&(e.status=a[1]);break;case"resolved":let s=i.find(([c,p])=>p.type==="terminal");s&&(e.status=s[1]);break;default:r&&(e.status=r[1]);break}}return e}catch(i){return this.loggingService.catch("Error in CustomFilterService convertLegacyAnnotation: ",i),e}}convertLegacyPriority(e){try{typeof e.priority=="string"&&(e.priority=U.CommentAnnotationPriorityMap[e.priority])}catch(i){this.loggingService.catch("Error in CustomFilterService convertLegacyPriority: ",i)}return e}convertLegacyCategory(e){try{if(e.commentCategories===void 0||e.commentCategories===null||!Array.isArray(e.commentCategories)||e.commentCategories.length===0)return e;typeof e.commentCategories[0]=="string"&&(e.commentCategories=e.commentCategories.map(i=>U.CommentCategoryMap[i]))}catch(i){this.loggingService.catch("Error in CustomFilterService convertLegacyCategory: ",i)}return e}};o.\u0275fac=function(i){return new(i||o)(J(y))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var hc=(()=>{let o=class o{constructor(e,i,r){this.domService=e,this.loggingService=i,this.sanitizer=r,this.emojis={};try{this.loggingService.log("%c[WB] Creating CLASS: EmojiService","color: blue;"),Object.keys(o.Icons).forEach(a=>{let s=o.Icons[a];this.emojis[a]=this.sanitizer.bypassSecurityTrustHtml(this.domService.sanitizeSvg(s))}),Object.keys(o.GIF_PATHS).forEach(a=>{let s=`<img src="${o.GIF_PATHS[a]}" alt="${a}" />`;this.emojis[a]=this.sanitizer.bypassSecurityTrustHtml(this.domService.sanitizeHtml(s))})}catch(a){this.loggingService.catch("Error in EmojiService constructor: ",a)}}getEmoji(e){try{return this.emojis[e]}catch{return""}}getEmojiFromIconUrl(e){try{return this.sanitizer.bypassSecurityTrustHtml(this.domService.sanitizeHtml(`<img src="${e}" alt="emoji" />`))}catch{return""}}getEmojiFromIconEmoji(e,i){try{let r=`<span class="velt-emoji-icon velt-emoji-icon--emoji">${e}</span>`;return i&&(r=`<span class="velt-emoji-icon velt-emoji-icon--emoji" emoji-id=${i}>${e}</span>`),this.sanitizer.bypassSecurityTrustHtml(this.domService.sanitizeHtml(r))}catch{return""}}setEmojiList(e){try{this.emojis={},Object.keys(e).forEach(i=>{let r=e[i];if(r.svg)this.emojis[i]=this.sanitizer.bypassSecurityTrustHtml(this.domService.sanitizeSvg(r.svg));else if(r.url){let a=`<img src="${r.url}" alt="${i}" />`;this.emojis[i]=this.sanitizer.bypassSecurityTrustHtml(this.domService.sanitizeHtml(a))}else r.emoji&&(this.emojis[i]=this.getEmojiFromIconEmoji(this.domService.sanitizeHtml(r.emoji)))})}catch(i){this.loggingService.catch("Error in EmojiService setEmojiList: ",i)}}};o.Icons={RAISED_HANDS:`<svg width="58" height="57" viewBox="0 0 58 57" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
196
196
|
<path d="M35.8477 11.6603L40.4962 5.23427" stroke="#B0BEC5" stroke-width="1.92685" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/>
|
|
197
197
|
<path d="M21.8298 11.617L17.4655 6.02428" stroke="#B0BEC5" stroke-width="1.92685" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/>
|
|
198
198
|
<path d="M28.7568 9.77682L28.7761 1" stroke="#B0BEC5" stroke-width="1.92685" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/>
|
|
@@ -380,7 +380,7 @@ This typically indicates that your device does not have a healthy Internet conne
|
|
|
380
380
|
</svg>
|
|
381
381
|
`},o.GIF_PATHS={CAT_JAM:"https://firebasestorage.googleapis.com/v0/b/snippyly-sdk-external/o/emojis%2Fcatjam.gif?alt=media&token=9868b4ec-0031-4751-bb2e-47bf0f9d9583"},o.\u0275fac=function(i){return new(i||o)(J(Fe),J(y),J(Ms))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var er=(()=>{let o=class o{constructor(e,i,r,a,s,c,p,h,_,E,D){this.afAuth=e,this.analyticsService=i,this.authService=r,this.configService=a,this.databaseService=s,this.commonDbService=c,this.docService=p,this.domService=h,this.emojiService=_,this.iamService=E,this.loggingService=D,this.documentPaths=null,this.db=Ci(),this.reactionAnnotationById$=new fe({}),this.customReactions$=new fe({}),this.darkMode$=new fe(null),this.loggingService.log("%c[WB] Creating CLASS: ReactionService","color: blue;"),this.analyticsService.setReactionService(this),this.authService.setReactionService(this),this.databaseService.getDb().pipe(Ne(B=>!!B),Je(1)).subscribe(B=>{B&&(this.db=B,this.getAllReactionAnnotations(void 0,void 0,!0).subscribe())},B=>{this.loggingService.catch("Error in ReactionService getDb subscription: ",B)})}clearCache(){this.loggingService.log("%c[WB] Calling FUNCTION: clearCache in ReactionService","color: green;");try{this.reactionAnnotationById$.next({}),this.customReactions$.next({}),this.documentPaths=null}catch(e){this.loggingService.catch("Error in ReactionService clearCache: ",e)}}getAllReactionAnnotations(e,i,r,a,s){this.loggingService.log("%c[WB] Calling FUNCTION: getAllReactionAnnotations","color: green;");let c,p;try{if(e&&(p=`${fn(e)}`),i&&typeof i=="object"){let h=Xo(i);c=fn(JSON.stringify(h))}}catch(h){this.loggingService.catch("Error in ReactionService getAllReactionAnnotations: ",h)}return Wn(this.afAuth).pipe(Ne(h=>!!h),ge(h=>this.isFeatureAllowed({firebaseUser:h,annotations:[],filteredAnnotations:[]})),ge(h=>h.featureAllowed?this.iamService.isUserAllowed$().pipe(ce(_=>(h.featureAllowed=_,h))):re(h)),ge(h=>h.featureAllowed?re(h).pipe(ge(_=>this.docService.getDocumentPaths$().pipe(ce(E=>(this.documentPaths=E,_.documentPaths=E,_)))),ge(_=>p?this.getDataFromDocumentIds([p]).pipe(ce(E=>(_.annotations=E||[],I({},_)))):this.docService.getDocumentIds$().pipe(ge(E=>{let D=E?.length>0?E.map(B=>B.documentId):[this.documentPaths?.documentId??""];return this.getDataFromDocumentIds(D).pipe(ce(B=>(_.annotations=B||[],I({},_))))}))),ge(_=>this.docService.getLocation$().pipe(ce(E=>(_.location=E,_)))),ge(_=>this.docService.getLocations$().pipe(ce(E=>(_.customLocations=E,_)))),ce(_=>{if(_.filteredAnnotations=[],p&&!c)return _.filteredAnnotations=_.annotations?.slice(),_;{let E=[];return c?E.push(c):(E.push(_?.location?.locationId),E.push(...Object.values(_?.customLocations||[]).map(D=>D.locationId))),_.filteredAnnotations=this.filterAnnotationsByLocationIds(_?.annotations,E),_}}),ge(_=>r?re(_):_?.annotations?.length?this.domService.onWindowResize$().pipe(ce(()=>_)):re(_)),ge(_=>r?re(_):re(_)),ce(_=>_),ge(_=>_?.filteredAnnotations?re(_?.filteredAnnotations||[]):re([]))):re([])),Kt(_o))}isFeatureAllowed(e){return this.configService.getConfig$().pipe(Ne(i=>!!i),ce(i=>T(I({},e),{config:i})),ge(i=>this.authService.getUser$().pipe(ce(r=>T(I({},i),{user:r})))),ge(i=>Xi(i.config,i.user,Re.REACTION)?re(T(I({},i),{featureAllowed:!0})):(this.loggingService.warn("Reaction feature is not allowed."),re(T(I({},i),{featureAllowed:!1})))))}getDataFromDocumentIds(e,i){return this.getDataFromDocuments({documentIds:e,filters:i})}getDataFromDocuments(e){if(this.configService?.getApiKey()){let{documentIds:i,filters:r}=e;if(i?.some(p=>!p)||!this.documentPaths)return re([]);let a=this.docService.getFolderConfig(),s=re([]),c={useCollectionGroup:!0,isCollection:!0,useQuery:!0};if(this.commonDbService.shouldUseFirestore()||(c.documentId=i?.length?i[0]:void 0,c.organizationId=this.documentPaths?.organizationId),a?.veltFolderId&&a?.allDocuments)s=this.commonDbService.dbListener({feature:"allReactions",properties:T(I({},c),{firestoreQuery:[Fi(mt("metadata.apiKey","==",this.configService?.getApiKey()),mt("metadata.veltFolderId","==",a?.veltFolderId),mt("metadata.organizationId","==",this.documentPaths?.organizationId))]})});else{let p=[];for(let h=0;h<(i?.length??0);h+=U.LISTENER_BATCH_SIZE)p.push(i?.slice(h,h+U.LISTENER_BATCH_SIZE)??[]);s=Dn(p.map(h=>this.commonDbService.dbListener({feature:"allReactions",properties:T(I({},c),{firestoreQuery:[Fi(mt("metadata.apiKey","==",this.configService?.getApiKey()),mt("metadata.documentId","in",h),mt("metadata.organizationId","==",this.documentPaths?.organizationId),...a?.veltFolderId?[mt("metadata.veltFolderId","==",a?.veltFolderId)]:[])]})}).pipe($r()))).pipe(ce(h=>ca(h)))}return s.pipe(ce(p=>({data:p?.data,operation:p?.operation})),ce(({data:p,operation:h})=>{let _=[];return p&&(_=Object.values(p??{}).filter(E=>typeof E=="object")),_?.forEach(E=>{this.sanitizeReactionAnnotation(E)}),{data:_,operation:h}}),ce(({data:p,operation:h})=>{if(!i)return{data:p,documentMap:{},operation:h};let _=p.reduce((E,D)=>{let B=D.metadata?.documentId;return B&&(E[B]||(E[B]=[]),E[B].push(D)),E},{});return{data:p,documentMap:_,operation:h}}),ce(({data:p,documentMap:h,operation:_})=>{if(!r)if(_?.type==="removed"){if(_?.ids?.length){let E=this.reactionAnnotationById$.value;_?.ids?.forEach(D=>{delete E?.[D]}),this.reactionAnnotationById$.next(E)}}else Object.entries(h??{}).forEach(([E,D])=>{this.setReactionAnnotationsByOrganizationIdAndDocumentId({organizationId:this.documentPaths?.organizationId,documentId:E,annotations:D})});return p}),Ln(p=>(this.loggingService.catch("Error in ReactionService getDataFromDocumentId: ",p),re([]))))}else return re([])}setReactionAnnotationsByOrganizationIdAndDocumentId({organizationId:e,documentId:i,annotations:r,queryHash:a}){try{if(i){e||(e=U.NO_ORGANIZATION_ID),a||(a=U.DEFAULT_QUERY_HASH);let s={};r?.forEach(p=>{p?.annotationId&&(s[p?.annotationId]=p)});let c=I(I({},this.reactionAnnotationById$.value),s);this.reactionAnnotationById$.next(c)}}catch(s){this.loggingService.catch("Error in ReactionService setReactionAnnotationsByOrganizationIdAndDocumentId:",s)}}getReactionAnnotationsByOrganizationIdAndDocumentId({organizationId:e,documentId:i}){try{let r={};return Object.values(this.reactionAnnotationById$.value??{}).forEach(a=>{a?.metadata?.documentId==i&&a?.metadata?.organizationId==e&&(r[a?.annotationId]=a)}),Object.values(r)}catch(r){return this.loggingService.catch("Error in ReactionService getReactionAnnotationsByOrganizationIdAndDocumentId:",r),[]}}getLocations$(){return this.docService.getLocation$().pipe(ge(e=>this.docService.getLocations$().pipe(ce(i=>({location:e,locations:i})))),ce(e=>{let i=[];return i.push(e?.location?.locationId),i.push(...Object.values(e.locations||[]).map(r=>r.locationId)),i||[]}))}filterAnnotationsByLocationIds(e,i){try{return e.filter(r=>i.includes(r.locationId))}catch(r){return this.loggingService.catch("Error in ReactionService filterAnnotationsByLocations:",r),[]}}getAnnotationById(e,i){try{let r=this.reactionAnnotationById$.value?.[e];if(r){let{documentId:a,organizationId:s}=i||{};if(a&&r.metadata?.documentId!==a||s&&r.metadata?.organizationId!==s)return}return r}catch(r){this.loggingService.catch("Error in ReactionService getAnnotationById: ",r);return}}getBaseMetadataFromReactionAnnotationId(e){try{let i=this.reactionAnnotationById$.value?.[e];return i?i.metadata:void 0}catch(i){this.loggingService.catch("Error in ReactionService getBaseMetadataFromReactionAnnotationId: ",i);return}}getReactionAnnotationByAnnotationId(e,i){try{return this.reactionAnnotationById$.pipe(ce(()=>this.getAnnotationById(e,i)),ge(r=>r?re(r):re(r)))}catch(r){return this.loggingService.catch("Error in ReactionService getReactionAnnotationByAnnotationId: ",r),re(void 0)}}getReactionAnnotationsBySectionId(e){try{return this.reactionAnnotationById$.pipe(ge(i=>this.docService.getDocumentPaths$().pipe(ce(r=>({documentPaths:r,sectionId:e,reactionAnnotationsMap:i})))),ge(i=>{let r=cr(e,["id","data-id"]);if(r){let a=this.docService.getAdditionLocationFromElement(r);if(a){let s=this.docService.genarateLocationId(a);return this.docService.getLocations$().pipe(ce(c=>{let h=Object.values(c||{}).find(_=>_.locationId===s||a?.id&&_.location.id===a.id);return T(I({},i),{additionalLocation:h,locationOnElement:!!a})}))}}return re(T(I({},i),{additionalLocation:null,element:r}))}),ge(i=>i?.locationOnElement?re(i):this.docService.getLocation$().pipe(ce(r=>T(I({},i),{location:r})))),ce(({documentPaths:i,location:r,additionalLocation:a,locationOnElement:s,element:c})=>{let p=null,h=this.docService.getAdditionalDocumentIdFromElement(c),_=h?this.docService.generateDocumentId(h):i?.documentId,E=i?.organizationId;if(_){let D=this.getReactionAnnotationsByOrganizationIdAndDocumentId({organizationId:E,documentId:_});if(D){p=[];for(let B of D)B?.targetElementId===e&&(s?a&&Ou({location:a?.location,locationId:a?.locationId},{location:B.location,locationId:B.locationId})&&p.push(B):r?Ou({location:r?.location,locationId:r?.locationId},{location:B.location,locationId:B.locationId})&&p.push(B):B?.locationId||p.push(B))}}return p}))}catch(i){return this.loggingService.catch("Error in ReactionService getReactionAnnotationsBySectionId: ",i),re(null)}}addOrUpdateReaction(e,i,r,a,s,c,p,h){return ee(this,null,function*(){try{let _=i?.map(E=>this.getAnnotationById(E)).find(E=>E?.icon===e);if(_){if(!p||p==="delete")return yield this.updateUserInReaction(_)}else if(!p||p==="add")return yield this.addReaction(void 0,e,r,a,s,c,h)}catch(_){this.loggingService.catch("Error in ReactionService addOrUpdateReaction: ",_)}})}addReaction(e,i,r,a,s,c,p){return ee(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: addReaction","color: green;");try{let h=this.authService.getUser();if(h)if(h.isReadOnly||h.isAnonymous)this.loggingService.catch("Anonymous/Readonly users cannot add reactions.");else{let _=new vM;if(_.from=h,_.lastUpdated=this.timestamp,_.reactions=[],_.reactions.push({from:h,lastUpdated:this.timestamp}),a&&(_.targetElementId=a),s&&(_.commentAnnotationId=s),this.setLocationToReactionAnnotation(_),_.pageInfo=_i(),_.pageInfo&&(_.pageInfo.screenWidth=this.domService.getCurrentWindowSizeValue()?.screenWidth),i)if(_.icon=i,c)_.iconUrl=c?.url,_.iconEmoji=c?.emoji;else{let E=this.customReactions$.value;if(E){let D=E[i];D?.url&&(_.iconUrl=D?.url),D?.emoji&&(_.iconEmoji=D?.emoji)}}return r&&(_.location={},_.location=I({},r),_.locationId=this.docService.genarateLocationId(_.location)),yield this.saveReactionToDb(_)}}catch(h){this.loggingService.catch("Error in ReactionService addReaction: ",h)}})}setLocationToReactionAnnotation(e){try{let i=this.docService.getLocation();i?(e.locationId=i.locationId,e.location=i.location):(delete e.locationId,delete e.location);try{let r;e.targetElement?.xpath?r=this.domService.getElementFromXPath(e.targetElement.xpath):e.targetElementId&&(r=cr(e.targetElementId,["id","data-id"]));let a=this.docService.getAdditionLocationFromElement(r);if(a){let s=this.docService.addLocation(a);s&&(e.locationId=s.locationId,e.location=s.location)}}catch{}}catch(i){this.loggingService.catch("Error in ReactionService setLocationToReactionAnnotation:",i)}}getElementForReactionAnnotation(e){try{let i;return e.targetElementId&&(i=cr(e.targetElementId,["id","data-id"])),i}catch(i){return this.loggingService.catch("Error in ReactionService getElementForReactionAnnotation: ",i),null}}saveReactionToDb(e){return ee(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: saveReactionToDb","color: green;");try{if(this.authService.getUser()){let i=yield this.docService.getDocumentPaths$().pipe(Ne(a=>!!a),Je(1)).toPromise();if(!i)throw new Error("Document paths not found.");this.documentPaths=i,this.loggingService.log(this.documentPaths);let r=yield this.databaseService.getDb().pipe(Ne(a=>!!a),Je(1)).toPromise();if(!r)throw new Error("Database not found.");if(this.db=r,this.loggingService.log(this.db),this.documentPaths?.reaction){let a=on(this.db,`${this.documentPaths.reaction}`);if(e.annotationId=this.commonDbService.generateDocumentId(),e.pageInfo,!e?.metadata?.documentId){e?.metadata||(e.metadata={});let h=this.getElementForReactionAnnotation(e),_=this.docService.getBaseMetadata("reaction",{commentAnnotationId:e.commentAnnotationId,element:h});e.metadata=I(I({},e?.metadata),_)}let s=JSON.parse(JSON.stringify(e));s.position=null;let{documentId:c,organizationId:p}=this.getDocumentIdAndOrganizationIdFromReactionAnnotation(e);return yield this.commonDbService.setData({feature:"reaction",properties:{id:e.annotationId,documentId:c,organizationId:p},data:s}),s}else return}}catch(i){this.loggingService.catch("Error in ReactionService saveReactionToDb: ",i)}})}getDocumentIdAndOrganizationIdFromReactionAnnotation(e){try{return{documentId:e?.metadata?.documentId,organizationId:e?.metadata?.organizationId}}catch(i){return this.loggingService.catch("Error in ReactionService getDocumentIdAndOrganizationIdFromReactionAnnotation: ",i),{}}}updateUserInReaction(e){return ee(this,null,function*(){try{let i=this.authService.getUser();if(i)return e?.reactions||(e.reactions=[]),e?.reactions?.find(a=>a?.from?.userId===i?.userId)?e.reactions=e?.reactions?.filter(a=>a?.from?.userId!==i?.userId):e.reactions.push({from:i,lastUpdated:this.timestamp}),e.reactions.length?yield this.updateReaction(e):yield this.deleteReactionPinAnnotation(e?.annotationId),e}catch(i){this.loggingService.catch("Error in ReactionService updateUserInReaction: ",i)}})}removeUserFromReaction(e){this.loggingService.log("%c[WB] Calling FUNCTION: removeUserFromReaction","color: green;");try{let i=this.authService.getUser();i&&(e?.reactions||(e.reactions=[]),e.reactions=e?.reactions?.filter(r=>r?.from?.userId!==i?.userId),this.updateReaction(e))}catch(i){this.loggingService.catch("Error in ReactionService removeUserFromReaction: ",i)}}updateReaction(e,i,r){return ee(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: updateReaction","color: green;");try{if(this.authService.getUser()){if(e?.targetElement?.xpath){let p=this.domService.getXPath(e.targetElement.xpath);if(p){let h=p.iterateNext();h&&(xo(h)||(e.targetElement=null))}}let a=JSON.parse(JSON.stringify(e));if(a.position=null,a.lastUpdated=this.timestamp,!a?.metadata?.documentId){a?.metadata||(a.metadata={});let p=this.docService.getBaseMetadata("reaction",{commentAnnotationId:e.commentAnnotationId});a.metadata=I(I({},a?.metadata),p)}let{documentId:s,organizationId:c}=a?.metadata||{};return r?yield this.commonDbService.updateData({feature:"reaction",properties:{id:e.annotationId,documentId:s,organizationId:c},data:JSON.parse(JSON.stringify(a))}):yield this.commonDbService.setData({feature:"reaction",properties:{id:e.annotationId,documentId:s,organizationId:c},data:JSON.parse(JSON.stringify(a))}),a}}catch(a){this.loggingService.catch("Error in ReactionService updateReaction: ",a)}})}deleteReactionPinAnnotation(e,i){return ee(this,null,function*(){try{let r=this.getAnnotationById(e),{documentId:a,organizationId:s}=this.getDocumentIdAndOrganizationIdFromReactionAnnotation(r);yield this.commonDbService.deleteData({feature:"reaction",properties:{id:e,documentId:a,organizationId:s}})}catch(r){this.loggingService.catch("Error in ReactionService deleteReactionPinAnnotation: ",r)}})}setCustomReactions(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setCustomReactions","color: green;"),this.customReactions$.next(e),this.emojiService.setEmojiList(e)}catch(i){this.loggingService.catch("Error in ReactionService setCustomReactions: ",i)}}enableDarkMode(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableDarkMode","color: green;"),this.darkMode$.value===!0)return;this.darkMode$.next(!0)}catch(e){this.loggingService.catch("Error in ReactionService enableDarkMode: ",e)}}disableDarkMode(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableDarkMode","color: green;"),this.darkMode$.value===!1)return;this.darkMode$.next(!1)}catch(e){this.loggingService.catch("Error in ReactionService disableDarkMode: ",e)}}getDarkMode(){return this.darkMode$.value}getDarkMode$(){return this.darkMode$.asObservable()}sanitizeReactionAnnotation(e){try{e&&(e.iconUrl&&(e.iconUrl=this.domService.sanitizeHtml(e.iconUrl)),e.iconEmoji&&(e.iconEmoji=this.domService.sanitizeHtml(e.iconEmoji)),e.icon&&(e.icon=this.domService.sanitizeHtml(e.icon)))}catch(i){this.loggingService.catch("Error in ReactionService sanitizeReactionAnnotation: ",i)}}get timestamp(){return this.commonDbService.getServerTimestamp()}};o.\u0275fac=function(i){return new(i||o)(J(vi),J(Qe),J(je),J($t),J(pn),J(bn),J(lt),J(Fe),J(hc),J(gn),J(y))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Ise=(()=>{let o=class o{constructor(e,i){this.domService=e,this.loggingService=i,this.keyEventSubject$=new et;try{this.loggingService.log("%c[WB] Creating CLASS: HotkeyService","color: blue;"),this.keyEvent$=this.keyEventSubject$.asObservable().pipe(Eg()),this.domService.onWindowKeydown$().subscribe(r=>{this.keyEventSubject$.next(r)})}catch(r){this.loggingService.catch("Error in HotkeyService constructor: ",r)}}getKeyPressEvent(e,i={}){try{return this.loggingService.log("%c[WB] Calling FUNCTION: getKeyPressEvent","color: green;"),this.keyEvent$.pipe(Ne(r=>r?.key===e),Ne(r=>!(!!i?.includeCtrl!==r.ctrlKey||!!i?.includeAlt!==r.altKey||!!i?.includeShift!==r.shiftKey||!!i?.includeMeta!==r.metaKey)),Ne(()=>this.isNoInputFocused()))}catch(r){return this.loggingService.catch("Error in HotkeyService getKeyPressEvent: ",r),new Ft}}isNoInputFocused(){try{let e=document.activeElement;for(;e&&e?.tagName!=="BODY";){if(e.tagName==="INPUT"||e.tagName==="TEXTAREA"||e?.isContentEditable)return!1;e=e?.parentElement}return!0}catch(e){return this.loggingService.catch("Error in HotkeyService isNoInputFocused: ",e),!1}}};o.\u0275fac=function(i){return new(i||o)(J(Fe),J(y))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Ye=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.configService=i,this.darkMode$=new fe(!1)}setDarkMode(e){try{let i=document.documentElement;if(!i)return;e?i.setAttribute(U.ATTRIBUTES.VELT_THEME,"dark"):i.removeAttribute(U.ATTRIBUTES.VELT_THEME),this.darkMode$.next(e)}catch(i){this.loggingService.catch("Error in theme service setDarkMode: ",i)}}getDarkMode$(){return this.darkMode$.asObservable()}updateListenerOnConfigChange(){try{this.configService.getConfig$().subscribe(e=>{if(e&&e.usePrefersColorScheme){this.enablePrefersColorScheme();return}this.disablePrefersColorScheme()})}catch(e){this.loggingService.catch("Error in theme service updateListenerOnConfigChange: ",e)}}enablePrefersColorScheme(){try{if(this.disablePrefersColorScheme(),!window.matchMedia)return;this.darkModeQuery=window.matchMedia("(prefers-color-scheme: dark)"),this.setDarkMode(this.darkModeQuery.matches),this.darkModeQueryListener=e=>{this.setDarkMode(e.matches)},this.darkModeQuery.addEventListener("change",this.darkModeQueryListener)}catch(e){this.loggingService.catch("Error in theme service enablePrefersColorScheme: ",e)}}disablePrefersColorScheme(){try{this.darkModeQuery&&this.darkModeQueryListener&&this.darkModeQuery.removeEventListener("change",this.darkModeQueryListener)}catch(e){this.loggingService.catch("Error in theme service disablePrefersColorScheme: ",e)}}};o.\u0275fac=function(i){return new(i||o)(J(y),J($t))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();function KPe(n,o){n&1&&(oe(),C(0,"svg",16),w(1,"rect",17)(2,"path",18)(3,"path",19)(4,"rect",20)(5,"path",21),S())}function ZPe(n,o){n&1&&(oe(),C(0,"svg",16),w(1,"rect",22)(2,"path",23)(3,"path",19)(4,"rect",20)(5,"path",21),S())}function XPe(n,o){if(n&1&&(f(0),C(1,"div",6)(2,"div",7),g(3,KPe,6,0,"svg",8)(4,ZPe,6,0,"ng-template",null,1,xe),S(),C(6,"div",9),te(7),A(8,"translate"),w(9,"br"),te(10),A(11,"translate"),S(),C(12,"div",10)(13,"p"),te(14),A(15,"translate"),oe(),C(16,"svg",11),w(17,"path",12)(18,"path",13)(19,"path",14)(20,"path",15),S(),te(21),A(22,"translate"),S(),ct(),C(23,"p"),te(24),A(25,"translate"),S()()(),v()),n&2){let t=de(5),e=l();d(3),m("ngIf",e.darkMode)("ngIfElse",t),d(4),ve(" ",O(8,7,"Allow mic permission to"),""),d(3),ve("",O(11,9,"enable your audio")," "),d(4),ve(" ",O(15,11,"1. Click the")," "),d(7),ve(" ",O(22,13,"page info icon in your browser\u2019s address bar")," "),d(3),ve(" ",O(25,15,"2. Turn on Microphone")," ")}}function QPe(n,o){n&1&&(oe(),C(0,"svg",16),w(1,"rect",17)(2,"path",24)(3,"path",19)(4,"rect",20)(5,"path",21),S())}function JPe(n,o){n&1&&(oe(),C(0,"svg",16),w(1,"rect",22)(2,"path",25)(3,"path",19)(4,"rect",20)(5,"path",21),S())}function e9e(n,o){if(n&1&&(f(0),C(1,"div",6)(2,"div",7),g(3,QPe,6,0,"svg",8)(4,JPe,6,0,"ng-template",null,2,xe),S(),C(6,"div",9),te(7),A(8,"translate"),w(9,"br"),te(10),A(11,"translate"),S(),C(12,"div",10)(13,"p"),te(14),A(15,"translate"),oe(),C(16,"svg",11),w(17,"path",12)(18,"path",13)(19,"path",14)(20,"path",15),S(),te(21),A(22,"translate"),S(),ct(),C(23,"p"),te(24),A(25,"translate"),S()()(),v()),n&2){let t=de(5),e=l();d(3),m("ngIf",e.darkMode)("ngIfElse",t),d(4),ve(" ",O(8,7,"Allow camera permission"),""),d(3),ve("",O(11,9,"to enable your video")," "),d(4),ve(" ",O(15,11,"1. Click the")," "),d(7),ve(" ",O(22,13,"page info icon in your browser\u2019s address bar")," "),d(3),ve(" ",O(25,15,"2. Turn on Camera")," ")}}var DM=(()=>{let o=class o{constructor(e,i,r,a,s){this.loggingService=e,this.themeService=i,this.elementRef=r,this.matDialogRef=a,this.data=s,this.veltElement=!0,this.darkMode=!0;try{this.loggingService.log("%c[WB] Creating CLASS: DevicePermissionDeniedDialogComponent","color: blue;"),this.type=this.data?.type,[!0,!1].includes(this.data?.darkMode)&&(this.darkMode=this.data?.darkMode)}catch(c){this.loggingService.catch("Error in DevicePermissionDeniedDialogComponent constructor: ",c)}}ngOnDestroy(){}};o.\u0275fac=function(i){return new(i||o)(u(y),u(Ye),u(N),u(Ko,8),u(ml,8))},o.\u0275cmp=M({type:o,selectors:[["velt-device-permission-denied-dialog-internal"]],hostVars:1,hostBindings:function(i,r){i&2&&x("data-velt-element",r.veltElement)},inputs:{type:"type"},standalone:!1,decls:5,vars:5,consts:[["devicePermissionDialogRef",""],["defaultAudioIcon",""],["defaultVideoIcon",""],[1,"velt-device-permission-denied-dialog--container",3,"snippylyOverlay","snippylyOverlayZIndex"],[3,"ngSwitch"],[4,"ngSwitchCase"],[1,"velt-device-permission-denied-dialog"],[1,"velt-device-permission-denied-dialog--icon"],["width","61","height","60","viewBox","0 0 61 60","fill","none","xmlns","http://www.w3.org/2000/svg",4,"ngIf","ngIfElse"],[1,"velt-device-permission-denied-dialog--header"],[1,"velt-device-permission-denied-dialog--content"],["width","13","height","12","viewBox","0 0 13 12","fill","none","xmlns","http://www.w3.org/2000/svg",1,"velt-device-permission-denied-dialog--page-info-icon"],["d","M4.375 2.5C4.375 3.53553 3.53553 4.375 2.5 4.375C1.46447 4.375 0.625 3.53553 0.625 2.5C0.625 1.46447 1.46447 0.625 2.5 0.625C3.53553 0.625 4.375 1.46447 4.375 2.5Z","stroke","currentColor","stroke-opacity","0.6","stroke-width","1.25"],["d","M5 2.5H12.5","stroke","currentColor","stroke-opacity","0.6","stroke-width","1.25"],["d","M0 8.75H7.5","stroke","currentColor","stroke-opacity","0.6","stroke-width","1.25"],["d","M11.875 8.75C11.875 9.78553 11.0355 10.625 10 10.625C8.96447 10.625 8.125 9.78553 8.125 8.75C8.125 7.71447 8.96447 6.875 10 6.875C11.0355 6.875 11.875 7.71447 11.875 8.75Z","stroke","currentColor","stroke-opacity","0.6","stroke-width","1.25"],["width","61","height","60","viewBox","0 0 61 60","fill","none","xmlns","http://www.w3.org/2000/svg"],["x","0.5","y","4","width","56","height","56","rx","28","fill","white","fill-opacity","0.04"],["d","M23.5026 20.333C23.5026 19.0069 24.0294 17.7352 24.9671 16.7975C25.9048 15.8598 27.1765 15.333 28.5026 15.333C29.8287 15.333 31.1005 15.8598 32.0381 16.7975C32.9758 17.7352 33.5026 19.0069 33.5026 20.333V28.6663C33.5027 29.1599 33.4297 29.6508 33.2859 30.123M29.9526 33.4563C29.2054 33.6828 28.4155 33.7311 27.6463 33.5973C26.8771 33.4636 26.1499 33.1516 25.5229 32.6863C24.8959 32.2211 24.3866 31.6154 24.0358 30.9179C23.685 30.2204 23.5024 29.4504 23.5026 28.6697V27.003M16.8359 28.6663C16.8356 30.7719 17.405 32.8383 18.484 34.6465C19.5629 36.4546 21.111 37.9371 22.9642 38.9366C24.8174 39.9362 26.9066 40.4156 29.0102 40.324C31.1137 40.2324 33.1533 39.5732 34.9126 38.4163M38.2459 35.083C39.5023 33.1791 40.1701 30.9474 40.1659 28.6663M21.8359 46.9997H35.1693M28.5026 40.333V46.9997","stroke","white","stroke-opacity","0.52","stroke-width","2.5","stroke-linecap","round","stroke-linejoin","round"],["d","M13.5 17L43.5 47","stroke","currentColor","stroke-width","2.5","stroke-linecap","round","stroke-linejoin","round"],["x","36.5","width","24","height","24","rx","12","fill","currentColor"],["d","M48.5 18.99V19M48.5 14V5","stroke","white","stroke-width","2.5","stroke-linecap","round","stroke-linejoin","round"],["x","0.5","y","4","width","56","height","56","rx","28","fill","black","fill-opacity","0.04"],["d","M23.5026 20.333C23.5026 19.0069 24.0294 17.7352 24.9671 16.7975C25.9048 15.8598 27.1765 15.333 28.5026 15.333C29.8287 15.333 31.1005 15.8598 32.0381 16.7975C32.9758 17.7352 33.5026 19.0069 33.5026 20.333V28.6663C33.5027 29.1599 33.4297 29.6508 33.2859 30.123M29.9526 33.4563C29.2054 33.6828 28.4155 33.7311 27.6463 33.5973C26.8771 33.4636 26.1499 33.1516 25.5229 32.6863C24.8959 32.2211 24.3866 31.6154 24.0358 30.9179C23.685 30.2204 23.5024 29.4504 23.5026 28.6697V27.003M16.8359 28.6663C16.8356 30.7719 17.405 32.8383 18.484 34.6465C19.5629 36.4546 21.111 37.9371 22.9642 38.9366C24.8174 39.9362 26.9066 40.4156 29.0102 40.324C31.1137 40.2324 33.1533 39.5732 34.9126 38.4163M38.2459 35.083C39.5023 33.1791 40.1701 30.9474 40.1659 28.6663M21.8359 46.9997H35.1693M28.5026 40.333V46.9997","stroke","black","stroke-opacity","0.52","stroke-width","2.5","stroke-linecap","round","stroke-linejoin","round"],["d","M42.375 39.2135C42.7034 39.1007 42.9883 38.8881 43.19 38.6054C43.3917 38.3227 43.5001 37.9841 43.5 37.6369V26.3635C43.4998 26.0795 43.4271 25.8003 43.2888 25.5523C43.1504 25.3043 42.9509 25.0958 42.7093 24.9465C42.4677 24.7973 42.192 24.7122 41.9083 24.6994C41.6246 24.6867 41.3424 24.7466 41.0883 24.8735L33.5 28.6669V30.3335V25.3333C33.5 24.4493 33.1488 23.6014 32.5237 22.9763C31.8986 22.3512 31.0507 22 30.1667 22H25.1667M33.5 37V38.6667C33.5 39.5507 33.1488 40.3986 32.5237 41.0237C31.8986 41.6488 31.0507 42 30.1667 42H16.8333C15.9493 42 15.1014 41.6488 14.4763 41.0237C13.8512 40.3986 13.5 39.5507 13.5 38.6667V25.3333C13.5 24.4493 13.8512 23.6014 14.4763 22.9763C15.1014 22.3512 15.9493 22 16.8333 22H18.5","stroke","white","stroke-opacity","0.52","stroke-width","2.5","stroke-linecap","round","stroke-linejoin","round"],["d","M42.375 39.2135C42.7034 39.1007 42.9883 38.8881 43.19 38.6054C43.3917 38.3227 43.5001 37.9841 43.5 37.6369V26.3635C43.4998 26.0795 43.4271 25.8003 43.2888 25.5523C43.1504 25.3043 42.9509 25.0958 42.7093 24.9465C42.4677 24.7973 42.192 24.7122 41.9083 24.6994C41.6246 24.6867 41.3424 24.7466 41.0883 24.8735L33.5 28.6669V30.3335V25.3333C33.5 24.4493 33.1488 23.6014 32.5237 22.9763C31.8986 22.3512 31.0507 22 30.1667 22H25.1667M33.5 37V38.6667C33.5 39.5507 33.1488 40.3986 32.5237 41.0237C31.8986 41.6488 31.0507 42 30.1667 42H16.8333C15.9493 42 15.1014 41.6488 14.4763 41.0237C13.8512 40.3986 13.5 39.5507 13.5 38.6667V25.3333C13.5 24.4493 13.8512 23.6014 14.4763 22.9763C15.1014 22.3512 15.9493 22 16.8333 22H18.5","stroke","currentColor","stroke-opacity","0.52","stroke-width","2.5","stroke-linecap","round","stroke-linejoin","round"]],template:function(i,r){if(i&1&&(C(0,"div",3,0),f(2,4),g(3,XPe,26,17,"ng-container",5)(4,e9e,26,17,"ng-container",5),v(),S()),i&2){let a=de(1);m("snippylyOverlay",a)("snippylyOverlayZIndex",3e3),d(2),m("ngSwitch",r.type),d(),m("ngSwitchCase","audio"),d(),m("ngSwitchCase","video")}},styles:["html[_ngcontent-%COMP%]{--velt-base-rem-unit: 1}*[data-snippyly-element=true][_ngcontent-%COMP%], *[data-velt-element=true][_ngcontent-%COMP%]{font-family:var(--velt-default-font-family)}velt-wireframe[_ngcontent-%COMP%]{display:none!important}[_nghost-%COMP%]{--velt-green: var(--velt-light-mode-green);--velt-magenta: var(--velt-light-mode-magenta);--velt-amber: var(--velt-light-mode-amber);--velt-purple: var(--velt-light-mode-purple);--velt-cyan: var(--velt-light-mode-cyan);--velt-orange: var(--velt-light-mode-orange);--velt-black: var(--velt-light-mode-black);--velt-white: var(--velt-light-mode-white);--velt-gray: var(--velt-light-mode-gray);--velt-error: var(--velt-light-mode-error);--velt-error-hover: var(--velt-light-mode-error-hover);--velt-error-foreground: var(--velt-light-mode-error-foreground);--velt-error-light: var(--velt-light-mode-error-light);--velt-error-transparent: var(--velt-light-mode-error-transparent);--velt-warning: var(--velt-light-mode-warning);--velt-warning-hover: var(--velt-light-mode-warning-hover);--velt-warning-foreground: var(--velt-light-mode-warning-foreground);--velt-warning-light: var(--velt-light-mode-warning-light);--velt-warning-transparent: var(--velt-light-mode-warning-transparent);--velt-success: var(--velt-light-mode-success);--velt-success-hover: var(--velt-light-mode-success-hover);--velt-success-foreground: var(--velt-light-mode-success-foreground);--velt-success-light: var(--velt-light-mode-success-light);--velt-success-transparent: var(--velt-light-mode-success-transparent);--velt-accent: var(--velt-light-mode-accent);--velt-accent-text: var(--velt-light-mode-accent-text);--velt-accent-hover: var(--velt-light-mode-accent-hover);--velt-accent-foreground: var(--velt-light-mode-accent-foreground);--velt-accent-light: var(--velt-light-mode-accent-light);--velt-accent-transparent: var(--velt-light-mode-accent-transparent);--velt-text-0: var(--velt-light-mode-text-0);--velt-text-1: var(--velt-light-mode-text-1);--velt-text-2: var(--velt-light-mode-text-2);--velt-text-3: var(--velt-light-mode-text-3);--velt-text-4: var(--velt-light-mode-text-4);--velt-text-5: var(--velt-light-mode-text-5);--velt-text-6: var(--velt-light-mode-text-6);--velt-text-7: var(--velt-light-mode-text-7);--velt-text-8: var(--velt-light-mode-text-8);--velt-text-9: var(--velt-light-mode-text-9);--velt-text-10: var(--velt-light-mode-text-10);--velt-text-11: var(--velt-light-mode-text-11);--velt-text-12: var(--velt-light-mode-text-12);--velt-background-0: var(--velt-light-mode-background-0);--velt-background-1: var(--velt-light-mode-background-1);--velt-background-2: var(--velt-light-mode-background-2);--velt-background-3: var(--velt-light-mode-background-3);--velt-background-4: var(--velt-light-mode-background-4);--velt-background-5: var(--velt-light-mode-background-5);--velt-background-6: var(--velt-light-mode-background-6);--velt-background-7: var(--velt-light-mode-background-7);--velt-background-8: var(--velt-light-mode-background-8);--velt-background-9: var(--velt-light-mode-background-9);--velt-background-10: var(--velt-light-mode-background-10);--velt-border-0: var(--velt-light-mode-border-0);--velt-border-1: var(--velt-light-mode-border-1);--velt-border-2: var(--velt-light-mode-border-2);--velt-border-3: var(--velt-light-mode-border-3);--velt-border-4: var(--velt-light-mode-border-4);--velt-border-5: var(--velt-light-mode-border-5);--velt-border-6: var(--velt-light-mode-border-6);--velt-border-7: var(--velt-light-mode-border-7);--velt-border-8: var(--velt-light-mode-border-8);--velt-border-9: var(--velt-light-mode-border-9);--velt-border-10: var(--velt-light-mode-border-10);--velt-background-transparent: var(--velt-light-mode-background-transparent);--velt-border-transparent: var(--velt-light-mode-border-transparent);--velt-animation-transparent: var(--velt-light-mode-animation-transparent)}[dark][_nghost-%COMP%]{--velt-green: var(--velt-dark-mode-green);--velt-magenta: var(--velt-dark-mode-magenta);--velt-amber: var(--velt-dark-mode-amber);--velt-purple: var(--velt-dark-mode-purple);--velt-cyan: var(--velt-dark-mode-cyan);--velt-orange: var(--velt-dark-mode-orange);--velt-black: var(--velt-dark-mode-black);--velt-white: var(--velt-dark-mode-white);--velt-gray: var(--velt-dark-mode-gray);--velt-error: var(--velt-dark-mode-error);--velt-error-hover: var(--velt-dark-mode-error-hover);--velt-error-foreground: var(--velt-dark-mode-error-foreground);--velt-error-light: var(--velt-dark-mode-error-light);--velt-error-transparent: var(--velt-dark-mode-error-transparent);--velt-warning: var(--velt-dark-mode-warning);--velt-warning-hover: var(--velt-dark-mode-warning-hover);--velt-warning-foreground: var(--velt-dark-mode-warning-foreground);--velt-warning-light: var(--velt-dark-mode-warning-light);--velt-warning-transparent: var(--velt-dark-mode-warning-transparent);--velt-success: var(--velt-dark-mode-success);--velt-success-hover: var(--velt-dark-mode-success-hover);--velt-success-foreground: var(--velt-dark-mode-success-foreground);--velt-success-light: var(--velt-dark-mode-success-light);--velt-success-transparent: var(--velt-dark-mode-success-transparent);--velt-accent: var(--velt-dark-mode-accent);--velt-accent-text: var(--velt-dark-mode-accent-text);--velt-accent-hover: var(--velt-dark-mode-accent-hover);--velt-accent-foreground: var(--velt-dark-mode-accent-foreground);--velt-accent-light: var(--velt-dark-mode-accent-light);--velt-accent-transparent: var(--velt-dark-mode-accent-transparent);--velt-text-0: var(--velt-dark-mode-text-0);--velt-text-1: var(--velt-dark-mode-text-1);--velt-text-2: var(--velt-dark-mode-text-2);--velt-text-3: var(--velt-dark-mode-text-3);--velt-text-4: var(--velt-dark-mode-text-4);--velt-text-5: var(--velt-dark-mode-text-5);--velt-text-6: var(--velt-dark-mode-text-6);--velt-text-7: var(--velt-dark-mode-text-7);--velt-text-8: var(--velt-dark-mode-text-8);--velt-text-9: var(--velt-dark-mode-text-9);--velt-text-10: var(--velt-dark-mode-text-10);--velt-text-11: var(--velt-dark-mode-text-11);--velt-text-12: var(--velt-dark-mode-text-12);--velt-background-0: var(--velt-dark-mode-background-0);--velt-background-1: var(--velt-dark-mode-background-1);--velt-background-2: var(--velt-dark-mode-background-2);--velt-background-3: var(--velt-dark-mode-background-3);--velt-background-4: var(--velt-dark-mode-background-4);--velt-background-5: var(--velt-dark-mode-background-5);--velt-background-6: var(--velt-dark-mode-background-6);--velt-background-7: var(--velt-dark-mode-background-7);--velt-background-8: var(--velt-dark-mode-background-8);--velt-background-9: var(--velt-dark-mode-background-9);--velt-background-10: var(--velt-dark-mode-background-10);--velt-border-0: var(--velt-dark-mode-border-0);--velt-border-1: var(--velt-dark-mode-border-1);--velt-border-2: var(--velt-dark-mode-border-2);--velt-border-3: var(--velt-dark-mode-border-3);--velt-border-4: var(--velt-dark-mode-border-4);--velt-border-5: var(--velt-dark-mode-border-5);--velt-border-6: var(--velt-dark-mode-border-6);--velt-border-7: var(--velt-dark-mode-border-7);--velt-border-8: var(--velt-dark-mode-border-8);--velt-border-9: var(--velt-dark-mode-border-9);--velt-border-10: var(--velt-dark-mode-border-10);--velt-background-transparent: var(--velt-dark-mode-background-transparent);--velt-border-transparent: var(--velt-dark-mode-border-transparent);--velt-animation-transparent: var(--velt-dark-mode-animation-transparent)} .velt-device-permission-denied-dialog--panel mat-dialog-container .mat-mdc-dialog-surface.mdc-dialog__surface{padding:0;background-color:transparent;box-shadow:none;overflow:unset}.velt-device-permission-denied-dialog[_ngcontent-%COMP%]{display:flex;flex-direction:column;gap:var(--velt-spacing-lg);align-items:center;justify-content:center;padding:4rem;box-sizing:border-box;word-break:break-word;max-width:600px;max-height:400px;text-align:center;background-color:var(--velt-background-0);border-radius:var(--velt-border-radius-2xl);box-shadow:0 calc((4rem + 0px) * var(--velt-base-rem-unit)) calc((4rem + 0px) * var(--velt-base-rem-unit)) calc((-3rem + 0px) * var(--velt-base-rem-unit)) #1f2f461f}.velt-device-permission-denied-dialog[_ngcontent-%COMP%] .velt-device-permission-denied-dialog--icon[_ngcontent-%COMP%]{color:var(--velt-error)}.velt-device-permission-denied-dialog[_ngcontent-%COMP%] .velt-device-permission-denied-dialog--header[_ngcontent-%COMP%]{font-size:var(--velt-font-size-lg);font-weight:600;line-height:36px;letter-spacing:-.02em;text-align:center;color:var(--velt-text-0)}.velt-device-permission-denied-dialog[_ngcontent-%COMP%] .velt-device-permission-denied-dialog--content[_ngcontent-%COMP%]{font-size:var(--velt-font-size-sm);font-weight:400;line-height:21px;text-align:center;color:var(--velt-text-0)}.velt-device-permission-denied-dialog[_ngcontent-%COMP%] .velt-device-permission-denied-dialog--content[_ngcontent-%COMP%] .velt-device-permission-denied-dialog--page-info-icon[_ngcontent-%COMP%]{margin-left:var(--velt-spacing-sm);margin-right:var(--velt-spacing-sm);color:var(--velt-error)}"],changeDetection:0});let n=o;return n})();var hm=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.matDialog=i,this.audioPermissionState$=new fe(null),this.videoPermissionState$=new fe(null);try{this.loggingService.log("%c[WB] Creating CLASS: DevicePermissionService","color: blue;"),this.checkPermissions()}catch(r){this.loggingService.catch("Error in DevicePermissionService constructor: ",r)}}checkPermissions(){try{this.loggingService.log("%c[WB] Calling DevicePermissionService FUNCTION: checkPermissions","color: green;"),new Jn().browserName!=="Firefox"&&(navigator.permissions.query({name:"microphone"}).then(i=>{this.audioPermissionState$.next(i.state),i.onchange=()=>{this.audioPermissionState$.next(i.state)}}).catch(i=>{}),navigator.permissions.query({name:"camera"}).then(i=>{this.videoPermissionState$.next(i.state),i.onchange=()=>{this.videoPermissionState$.next(i.state)}}).catch(i=>{}))}catch(e){this.loggingService.catch("Error in DevicePermissionService checkPermissions: ",e)}}getPermissionState$(e){try{switch(this.loggingService.log("%c[WB] Calling DevicePermissionService FUNCTION: getPermissionState$","color: green;"),e){case"audio":return this.getAudioPermissionState$();case"video":return this.getVideoPermissionState$();default:return re(null)}}catch(i){return this.loggingService.catch("Error in DevicePermissionService getPermissionState$: ",i),re(null)}}getAudioPermissionState$(){return this.audioPermissionState$.asObservable()}getVideoPermissionState$(){return this.videoPermissionState$.asObservable()}openDevicePermissionDeniedDialog(e,i){try{this.loggingService.log("%c[WB] Calling DevicePermissionService FUNCTION: openDevicePermissionDeniedDialog","color: green;"),this.matDialog.open(DM,{panelClass:"velt-device-permission-denied-dialog--panel",backdropClass:["velt-device-permission-denied-dialog--backdrop","s-background-blur-1"],data:I({type:e},i||{})})}catch(r){this.loggingService.catch("Error in DevicePermissionService openDevicePermissionDeniedDialog: ",r)}}};o.\u0275fac=function(i){return new(i||o)(J(y),J(qi))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var t9e=()=>["video","screen"];function n9e(n,o){if(n&1&&w(0,"app-recording-preview-steps-dialog-video",4),n&2){let t=l(2);m("componentConfigSignal",t.componentConfigSignal)}}function i9e(n,o){if(n&1&&w(0,"app-recording-preview-steps-dialog-audio",4),n&2){let t=l(2);m("componentConfigSignal",t.componentConfigSignal)}}function o9e(n,o){if(n&1&&(f(0),C(1,"div",2,0),g(3,n9e,1,1,"app-recording-preview-steps-dialog-video",3)(4,i9e,1,1,"app-recording-preview-steps-dialog-audio",3),S(),v()),n&2){let t=o.ngIf,e=de(2),i=l();d(),m("snippylyOverlay",e)("snippylyOverlayZIndex",2e3),x("aria-label","Recording preview - "+t.type+" mode")("data-testid",i.componentId),d(2),m("ngIf",kt(6,t9e).includes(t.type)),d(),m("ngIf",t.type==="audio")}}var AM=(()=>{let o=class o{constructor(e,i,r,a,s,c,p){this.loggingService=e,this.recorderService=i,this.dialog=r,this.devicePermissionService=a,this.dialogRef=s,this.elementRef=c,this.data=p,this.darkMode=!1,this.shadowDom=!0,this.startCountdownFrom=3,this.defaultMediaSourceOptions=ac(),this.recordingCountdownEnabled=!1,this.subscriptions=[],this.veltElement=!0,this.componentId="velt-recording-preview-steps-dialog",this.componentConfigSignal=be({closeDialog:this.closeDialog.bind(this),startCountdown:this.startCountdown.bind(this),toggleAudio:this.toggleAudio.bind(this),toggleVideo:this.toggleVideo.bind(this),toggleSettings:this.toggleSettings.bind(this),cancelCountdown:this.cancelCountdown.bind(this),updateMediaConfig:this.updateMediaConfig.bind(this),handleOverlayClick:this.handleOverlayClick.bind(this),countdownStarted:!1,mediaConfig:{audio:{enabled:!1},video:{enabled:!1}},mediaState:{audio:{enabled:!1},video:{enabled:!1}},type:"video",countdown:this.startCountdownFrom,mediaStream:void 0,isSettingsOpen:!1,darkMode:this.darkMode,shadowDom:this.shadowDom});try{this.devicePermissionService.getPermissionState$("video").subscribe(h=>{this.componentConfigSignal.update(_=>(_=T(I({},_),{mediaState:T(I({},_.mediaState),{video:{enabled:h!=="denied"}})}),_))}),this.devicePermissionService.getPermissionState$("audio").subscribe(h=>{this.componentConfigSignal.update(_=>(_=T(I({},_),{mediaState:T(I({},_.mediaState),{audio:{enabled:h!=="denied"}})}),_))}),this.subscriptions.push(this.recorderService.getRecordingCountdownEnabled$().subscribe(h=>{this.recordingCountdownEnabled=h})),p&&(p.type&&this.componentConfigSignal.update(h=>(h=T(I({},h),{type:p.type}),h)),p.recordingCountdown!==void 0&&(this.recordingCountdownEnabled=!!p.recordingCountdown),p.mediaConfig&&(p.mediaConfig?.audio?.enabled&&!p.mediaConfig?.audio?.deviceId&&(p.mediaConfig.audio.deviceId=this.defaultMediaSourceOptions?.selectedAudioDevice?.deviceId),p.mediaConfig?.video?.enabled&&!p.mediaConfig?.video?.deviceId&&(p.mediaConfig.video.deviceId=this.defaultMediaSourceOptions?.selectedVideoDevice?.deviceId),p?.darkMode?this.elementRef.nativeElement.setAttribute("dark",""):this.elementRef.nativeElement.removeAttribute("dark"),this.componentConfigSignal.update(h=>(h=T(I({},h),{shadowDom:p?.shadowDom!==!1,darkMode:p.darkMode||!1}),h)),this.updateMediaConfig(p.mediaConfig)))}catch(h){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent constructor: ",h)}}ngOnInit(){try{this.setupA11yAttributes()}catch(e){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent ngOnInit:",e)}}setupA11yAttributes(){try{let e=this.elementRef.nativeElement;e.setAttribute("data-testid",this.componentId+"-container"),e.setAttribute("role","dialog"),e.setAttribute("aria-label","Recording preview steps dialog")}catch(e){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent setupA11yAttributes:",e)}}ngOnChanges(e){try{e&&Object.keys(e).forEach(i=>{this.componentConfigSignal.update(r=>(r=T(I({},r),{[i]:e[i].currentValue}),r))})}catch(i){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent ngOnChanges: ",i)}}ngAfterViewInit(){try{this.dialogRef.addPanelClass("snippyly-recording-preview-steps-dialog"),this.dialogRef.disableClose=!0}catch(e){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent ngAfterViewInit: ",e)}}toggleSettings(e){try{e.stopPropagation(),this.componentConfigSignal.update(i=>(i=T(I({},i),{isSettingsOpen:!i.isSettingsOpen}),i))}catch(i){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent toggleSettings: ",i)}}toggleAudio(){try{this.componentConfigSignal().mediaConfig.audio||this.componentConfigSignal.update(r=>(r=T(I({},r),{mediaConfig:T(I({},r.mediaConfig),{audio:{enabled:!0}})}),r));let e=!this.componentConfigSignal().mediaConfig.audio?.enabled;this.componentConfigSignal.update(r=>(r=T(I({},r),{mediaConfig:T(I({},r.mediaConfig),{audio:{enabled:e}})}),r));let i=this.componentConfigSignal().mediaStream?.getAudioTracks()[0];i?i.enabled=e:e&&(this.componentConfigSignal.update(r=>(r=T(I({},r),{mediaConfig:T(I({},r.mediaConfig),{audio:T(I({},r.mediaConfig.audio),{deviceId:this.defaultMediaSourceOptions?.selectedAudioDevice?.deviceId})})}),r)),this.updateMediaConfig(this.componentConfigSignal().mediaConfig))}catch(e){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent toggleAudio: ",e)}}toggleVideo(){try{this.componentConfigSignal.update(e=>(e=I({},e),e.mediaConfig.video||(e.mediaConfig.video={enabled:!0}),e.mediaConfig.video.enabled=!e.mediaConfig.video.enabled,e.mediaConfig.video.deviceId=this.defaultMediaSourceOptions?.selectedVideoDevice?.deviceId,e)),this.updateMediaConfig(this.componentConfigSignal().mediaConfig)}catch(e){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent toggleVideo: ",e)}}updateMediaConfig(e){try{this.stopMediaStream(),this.getMediaStream(e)}catch(i){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent updateMediaConfig: ",i)}}getMediaStream(e){try{if(!navigator.mediaDevices){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent getMediaStream: ","No media devices");return}if(!navigator.mediaDevices.getUserMedia){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent getMediaStream: ","No getUserMedia");return}if(e.audio?.enabled||e.video?.enabled){let i={};e.audio?.enabled&&(i.audio={deviceId:e.audio.deviceId}),e.video?.enabled&&(i.video={deviceId:e.video.deviceId}),navigator.mediaDevices.getUserMedia(i).then(r=>{this.componentConfigSignal.update(a=>(a=T(I({},a),{mediaConfig:e,mediaStream:r}),a))}).catch(r=>{this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent getMediaStream catch: ",r)})}else this.componentConfigSignal.update(i=>(i=T(I({},i),{mediaStream:void 0,mediaConfig:e}),i))}catch(i){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent getMediaStream: ",i)}}stopMediaStream(){try{this.componentConfigSignal.update(e=>(e=I({},e),e.mediaStream?.getTracks().forEach(i=>{i.stop()}),e.mediaStream=void 0,e))}catch(e){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent stopMediaStream: ",e)}}startCountdown(){return ee(this,null,function*(){try{if(this.componentConfigSignal().type==="screen"){let e=yield navigator.mediaDevices.getDisplayMedia();this.componentConfigSignal.update(i=>(i=I({},i),i.mediaConfig.screen={enabled:!0,stream:e},i)),e?.getTracks().forEach(i=>{i&&(i.onended=()=>{this.cancelCountdown()})})}this.recordingCountdownEnabled?(this.componentConfigSignal.update(e=>(e=T(I({},e),{countdownStarted:!0}),e)),this.countdownInterval=setInterval(()=>{this.componentConfigSignal().countdown>1?this.componentConfigSignal.update(e=>(e=T(I({},e),{countdown:e.countdown-1}),e)):this.closeDialog(this.componentConfigSignal().mediaConfig)},1e3)):this.closeDialog(this.componentConfigSignal().mediaConfig)}catch(e){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent startCountdown: ",e)}})}cancelCountdown(){try{if(this.componentConfigSignal.update(e=>(e=T(I({},e),{countdownStarted:!1,countdown:this.startCountdownFrom}),e)),this.clearInterval(),this.componentConfigSignal().type==="screen"){let e=this.componentConfigSignal().mediaConfig.screen?.stream;e&&e.getTracks().forEach(i=>{i.stop()}),this.componentConfigSignal.update(i=>(i=I({},i),i.mediaConfig.screen=void 0,i))}}catch(e){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent cancelCountdown: ",e)}}closeDialog(e){return ee(this,null,function*(){try{this.clearInterval(),this.stopMediaStream(),this.dialogRef.close(e)}catch(i){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent closeDialog: ",i)}})}handleOverlayClick(e){try{this.componentConfigSignal.update(i=>(i=T(I({},i),{isSettingsOpen:!1}),i)),e.stopPropagation()}catch(i){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent handleOverlayClick: ",i)}}clearInterval(){try{this.countdownInterval&&(clearInterval(this.countdownInterval),this.countdownInterval=void 0)}catch(e){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent clearInterval: ",e)}}ngOnDestroy(){try{this.clearInterval(),this.stopMediaStream(),this.subscriptions.forEach(e=>{e?.unsubscribe()})}catch(e){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent ngOnDestroy: ",e)}}};o.\u0275fac=function(i){return new(i||o)(u(y),u(yi),u(qi),u(hm),u(Ko),u(N),u(ml,8))},o.\u0275cmp=M({type:o,selectors:[["snippyly-recording-preview-steps-dialog"]],hostVars:1,hostBindings:function(i,r){i&2&&x("data-velt-element",r.veltElement)},inputs:{darkMode:"darkMode",shadowDom:"shadowDom"},standalone:!1,features:[qe],decls:1,vars:1,consts:[["recordingPreviewDialogRef",""],[4,"ngIf"],["role","dialog","aria-modal","true",3,"snippylyOverlay","snippylyOverlayZIndex"],[3,"componentConfigSignal",4,"ngIf"],[3,"componentConfigSignal"]],template:function(i,r){i&1&&g(0,o9e,5,7,"ng-container",1),i&2&&m("ngIf",r.componentConfigSignal())},styles:["html[_ngcontent-%COMP%]{--velt-base-rem-unit: 1}*[data-snippyly-element=true][_ngcontent-%COMP%], *[data-velt-element=true][_ngcontent-%COMP%]{font-family:var(--velt-default-font-family)}velt-wireframe[_ngcontent-%COMP%]{display:none!important}[_nghost-%COMP%]{--velt-green: var(--velt-light-mode-green);--velt-magenta: var(--velt-light-mode-magenta);--velt-amber: var(--velt-light-mode-amber);--velt-purple: var(--velt-light-mode-purple);--velt-cyan: var(--velt-light-mode-cyan);--velt-orange: var(--velt-light-mode-orange);--velt-black: var(--velt-light-mode-black);--velt-white: var(--velt-light-mode-white);--velt-gray: var(--velt-light-mode-gray);--velt-error: var(--velt-light-mode-error);--velt-error-hover: var(--velt-light-mode-error-hover);--velt-error-foreground: var(--velt-light-mode-error-foreground);--velt-error-light: var(--velt-light-mode-error-light);--velt-error-transparent: var(--velt-light-mode-error-transparent);--velt-warning: var(--velt-light-mode-warning);--velt-warning-hover: var(--velt-light-mode-warning-hover);--velt-warning-foreground: var(--velt-light-mode-warning-foreground);--velt-warning-light: var(--velt-light-mode-warning-light);--velt-warning-transparent: var(--velt-light-mode-warning-transparent);--velt-success: var(--velt-light-mode-success);--velt-success-hover: var(--velt-light-mode-success-hover);--velt-success-foreground: var(--velt-light-mode-success-foreground);--velt-success-light: var(--velt-light-mode-success-light);--velt-success-transparent: var(--velt-light-mode-success-transparent);--velt-accent: var(--velt-light-mode-accent);--velt-accent-text: var(--velt-light-mode-accent-text);--velt-accent-hover: var(--velt-light-mode-accent-hover);--velt-accent-foreground: var(--velt-light-mode-accent-foreground);--velt-accent-light: var(--velt-light-mode-accent-light);--velt-accent-transparent: var(--velt-light-mode-accent-transparent);--velt-text-0: var(--velt-light-mode-text-0);--velt-text-1: var(--velt-light-mode-text-1);--velt-text-2: var(--velt-light-mode-text-2);--velt-text-3: var(--velt-light-mode-text-3);--velt-text-4: var(--velt-light-mode-text-4);--velt-text-5: var(--velt-light-mode-text-5);--velt-text-6: var(--velt-light-mode-text-6);--velt-text-7: var(--velt-light-mode-text-7);--velt-text-8: var(--velt-light-mode-text-8);--velt-text-9: var(--velt-light-mode-text-9);--velt-text-10: var(--velt-light-mode-text-10);--velt-text-11: var(--velt-light-mode-text-11);--velt-text-12: var(--velt-light-mode-text-12);--velt-background-0: var(--velt-light-mode-background-0);--velt-background-1: var(--velt-light-mode-background-1);--velt-background-2: var(--velt-light-mode-background-2);--velt-background-3: var(--velt-light-mode-background-3);--velt-background-4: var(--velt-light-mode-background-4);--velt-background-5: var(--velt-light-mode-background-5);--velt-background-6: var(--velt-light-mode-background-6);--velt-background-7: var(--velt-light-mode-background-7);--velt-background-8: var(--velt-light-mode-background-8);--velt-background-9: var(--velt-light-mode-background-9);--velt-background-10: var(--velt-light-mode-background-10);--velt-border-0: var(--velt-light-mode-border-0);--velt-border-1: var(--velt-light-mode-border-1);--velt-border-2: var(--velt-light-mode-border-2);--velt-border-3: var(--velt-light-mode-border-3);--velt-border-4: var(--velt-light-mode-border-4);--velt-border-5: var(--velt-light-mode-border-5);--velt-border-6: var(--velt-light-mode-border-6);--velt-border-7: var(--velt-light-mode-border-7);--velt-border-8: var(--velt-light-mode-border-8);--velt-border-9: var(--velt-light-mode-border-9);--velt-border-10: var(--velt-light-mode-border-10);--velt-background-transparent: var(--velt-light-mode-background-transparent);--velt-border-transparent: var(--velt-light-mode-border-transparent);--velt-animation-transparent: var(--velt-light-mode-animation-transparent)}[dark][_nghost-%COMP%]{--velt-green: var(--velt-dark-mode-green);--velt-magenta: var(--velt-dark-mode-magenta);--velt-amber: var(--velt-dark-mode-amber);--velt-purple: var(--velt-dark-mode-purple);--velt-cyan: var(--velt-dark-mode-cyan);--velt-orange: var(--velt-dark-mode-orange);--velt-black: var(--velt-dark-mode-black);--velt-white: var(--velt-dark-mode-white);--velt-gray: var(--velt-dark-mode-gray);--velt-error: var(--velt-dark-mode-error);--velt-error-hover: var(--velt-dark-mode-error-hover);--velt-error-foreground: var(--velt-dark-mode-error-foreground);--velt-error-light: var(--velt-dark-mode-error-light);--velt-error-transparent: var(--velt-dark-mode-error-transparent);--velt-warning: var(--velt-dark-mode-warning);--velt-warning-hover: var(--velt-dark-mode-warning-hover);--velt-warning-foreground: var(--velt-dark-mode-warning-foreground);--velt-warning-light: var(--velt-dark-mode-warning-light);--velt-warning-transparent: var(--velt-dark-mode-warning-transparent);--velt-success: var(--velt-dark-mode-success);--velt-success-hover: var(--velt-dark-mode-success-hover);--velt-success-foreground: var(--velt-dark-mode-success-foreground);--velt-success-light: var(--velt-dark-mode-success-light);--velt-success-transparent: var(--velt-dark-mode-success-transparent);--velt-accent: var(--velt-dark-mode-accent);--velt-accent-text: var(--velt-dark-mode-accent-text);--velt-accent-hover: var(--velt-dark-mode-accent-hover);--velt-accent-foreground: var(--velt-dark-mode-accent-foreground);--velt-accent-light: var(--velt-dark-mode-accent-light);--velt-accent-transparent: var(--velt-dark-mode-accent-transparent);--velt-text-0: var(--velt-dark-mode-text-0);--velt-text-1: var(--velt-dark-mode-text-1);--velt-text-2: var(--velt-dark-mode-text-2);--velt-text-3: var(--velt-dark-mode-text-3);--velt-text-4: var(--velt-dark-mode-text-4);--velt-text-5: var(--velt-dark-mode-text-5);--velt-text-6: var(--velt-dark-mode-text-6);--velt-text-7: var(--velt-dark-mode-text-7);--velt-text-8: var(--velt-dark-mode-text-8);--velt-text-9: var(--velt-dark-mode-text-9);--velt-text-10: var(--velt-dark-mode-text-10);--velt-text-11: var(--velt-dark-mode-text-11);--velt-text-12: var(--velt-dark-mode-text-12);--velt-background-0: var(--velt-dark-mode-background-0);--velt-background-1: var(--velt-dark-mode-background-1);--velt-background-2: var(--velt-dark-mode-background-2);--velt-background-3: var(--velt-dark-mode-background-3);--velt-background-4: var(--velt-dark-mode-background-4);--velt-background-5: var(--velt-dark-mode-background-5);--velt-background-6: var(--velt-dark-mode-background-6);--velt-background-7: var(--velt-dark-mode-background-7);--velt-background-8: var(--velt-dark-mode-background-8);--velt-background-9: var(--velt-dark-mode-background-9);--velt-background-10: var(--velt-dark-mode-background-10);--velt-border-0: var(--velt-dark-mode-border-0);--velt-border-1: var(--velt-dark-mode-border-1);--velt-border-2: var(--velt-dark-mode-border-2);--velt-border-3: var(--velt-dark-mode-border-3);--velt-border-4: var(--velt-dark-mode-border-4);--velt-border-5: var(--velt-dark-mode-border-5);--velt-border-6: var(--velt-dark-mode-border-6);--velt-border-7: var(--velt-dark-mode-border-7);--velt-border-8: var(--velt-dark-mode-border-8);--velt-border-9: var(--velt-dark-mode-border-9);--velt-border-10: var(--velt-dark-mode-border-10);--velt-background-transparent: var(--velt-dark-mode-background-transparent);--velt-border-transparent: var(--velt-dark-mode-border-transparent);--velt-animation-transparent: var(--velt-dark-mode-animation-transparent)} .snippyly-recording-preview-steps-dialog mat-dialog-container .mat-mdc-dialog-surface.mdc-dialog__surface{background:transparent;padding:0;margin:0;border-radius:var(--velt-border-radius-lg)}"],changeDetection:0});let n=o;return n})();var yi=(()=>{let o=class o{constructor(e,i,r,a,s,c,p){this.analyticsService=e,this.loggingService=i,this.matDialog=r,this.storageService=a,this.docService=s,this.databaseService=c,this.domService=p,this.recorderStatusSubject$=new fe(null),this.recorderDurationSubject$=new fe(null),this.darkMode$=new fe(null),this.shadowDom$=new fe(null),this.recordingDurations=[],this.chunks=[],this.recordingCountdownEnabled$=new fe(!0),this.recorderInitData$=new et,this.recordedRawData$=new et,this.recordedData$=new et,this.onInitRecording$=new fe(null),this.onRecordingAttributeRemovedFromBodySubject$=new et,this.videoEditor$=new fe(!1),this.settingsEmbedded$=new fe(!1),this.autoOpenVideoEditor$=new fe(!1),this.playVideoInFullScreen$=new fe(void 0),this.recordedDataStream=[],this.documentPaths=null,this.db=Ci(),this.uploadPromises=[],this.chunkUrls$=new fe({}),this.onInitRecording$.subscribe(h=>{h?this.setRecordingAttributeAtBody():this.removeRecordingAttributeFromBody()}),this.databaseService.getDb().pipe(Ne(h=>!!h),Je(1)).subscribe(h=>{h&&(this.db=h,this.getDocumentPaths())},h=>{this.loggingService.catch("Error in RecorderAnnotationService getDb subscription: ",h)})}getDocumentPaths(){this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentPaths","color: green;");try{this.docService.getDocumentPaths$().pipe(In(e=>{this.documentPaths=e})).subscribe(()=>{},e=>{this.loggingService.catch("Error in getDocumentPaths subscription: ",e)})}catch(e){this.loggingService.catch("Error in CursorService getDocumentPaths: ",e)}}setRecordedDataStream(e){this.recordedDataStream=e}getRecordedDataStream(){return this.recordedDataStream}setRecordingAttributeAtBody(){try{let e=this.onInitRecording$.getValue();e&&(document.body.setAttribute(U.ATTRIBUTES.VELT_ONGOING_RECORDING,e.type),e?.isCommentRecording&&document.body.setAttribute(U.ATTRIBUTES.VELT_COMMENT_RECORDING,"true"))}catch(e){this.loggingService.catch("Error in RecorderService setRecordingAttributeAtBody: ",e)}}removeRecordingAttributeFromBody(){try{document.body.removeAttribute(U.ATTRIBUTES.VELT_ONGOING_RECORDING),document.body.removeAttribute(U.ATTRIBUTES.VELT_COMMENT_RECORDING),this.onRecordingAttributeRemovedFromBodySubject$.next()}catch(e){this.loggingService.catch("Error in RecorderService removeRecordingAttributeFromBody: ",e)}}onRecordingAttributeRemovedFromBody$(){return this.onRecordingAttributeRemovedFromBodySubject$.asObservable()}getRecorderInitData(){return this.recorderInitData$.asObservable()}onInitRecording(){return this.onInitRecording$.asObservable()}onRecordedData(){return this.recordedData$.asObservable()}setRecordedData(e){this.recordedData$.next(e)}initRecording(e,i,r,a,s,c,p,h){return ee(this,null,function*(){try{let _={};switch(e){case"audio":_.audio={enabled:!0};break;case"video":_.video={enabled:!0},_.audio={enabled:!0};break;case"screen":_.screen={enabled:!0},_.video={enabled:!1},_.audio={enabled:!1};break;default:break}this.matDialog.open(AM,{data:{type:e,mediaConfig:_,darkMode:[!0,!1].includes(a)?a:this.darkMode$.value,shadowDom:s,recordingCountdown:h}}).afterClosed().subscribe(E=>{if(E){let D={};switch(e){case"audio":D.audio={enabled:!0,deviceId:E.audio?.deviceId},D.audio=E.audio;break;case"video":D.video={enabled:!0,deviceId:E.video?.deviceId},D.audio={enabled:!0,deviceId:E.audio?.deviceId},D.video=E.video,D.audio=E.audio;break;case"screen":D.screen={enabled:!0},D.audio=E.audio,D.video=E.video,D.screen=E.screen;break;default:break}this.onInitRecording$.next({type:e,panelId:i,mediaConfig:D,isCommentRecording:r,darkMode:[!0,!1].includes(a)?a:!!this.darkMode$.value,shadowDom:s,commentAnnotationId:c,clientDocumentId:p})}},E=>{this.loggingService.catch("Error in RecorderService initRecording afterClosed: ",E)})}catch(_){this.loggingService.catch("Error in RecorderService initRecording: ",_)}})}startRecording(e,i){return ee(this,null,function*(){try{this.loggingService.log("[startRecording] Starting with config:",e,"mediaConfig:",i);let r=new MediaStream,a=yield this.getBrowserSpecificOptions();return yield this.collectMediaTracks(r,e,i),yield this.initializeMediaRecorder(r,a),this.setupRecorderData(e,r),r}catch(r){return this.loggingService.catch("Error in RecorderService startRecording: ",r),Promise.reject(r)}})}getBrowserSpecificOptions(){return ee(this,null,function*(){try{let e={},i=this.getSupportedMimeTypes();if(i.length>0){let r=i.find(a=>a.includes("mp4")&&a.includes("h264"))||i.find(a=>a.includes("mp4"))||i[0];e.mimeType=r}return this.isSafari()?(e.videoBitsPerSecond=25e5,e.audioBitsPerSecond=128e3):(e.videoBitsPerSecond=1e6,e.audioBitsPerSecond=128e3),e}catch(e){return this.loggingService.catch("Error in RecorderService getBrowserSpecificOptions: ",e),{}}})}collectMediaTracks(e,i,r){return ee(this,null,function*(){try{if(i.type.screen&&r?.screen?.stream&&r.screen.stream.getTracks().forEach(a=>{e.addTrack(a),a.onended=()=>this.stopRecording()}),i?.type.audio||i?.type.video){let a=this.buildMediaConstraints(i,r),s=yield navigator.mediaDevices.getUserMedia(a);if(s)if(this.isSafari()){if(i?.type.audio&&(yield this.adjustSafariAudioTrack(e,s)),i?.type.video){let c=s.getVideoTracks();if(c.length>0){let p=c[0];p.enabled=!0;let h=p.clone();e.addTrack(h),r&&r.video&&(r.video.track=p)}}}else s.getTracks().forEach(c=>e.addTrack(c))}}catch(a){this.loggingService.catch("Error in RecorderService collectMediaTracks: ",a);return}})}buildMediaConstraints(e,i){try{let r={audio:e.type.audio?{deviceId:i?.audio?.deviceId?{ideal:i.audio.deviceId}:void 0,sampleRate:48e3,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}:!1,video:e.type.video?{deviceId:i?.video?.deviceId?{ideal:i.video.deviceId}:void 0,width:{ideal:1280},height:{ideal:720},frameRate:{ideal:20},aspectRatio:{ideal:1.777777778},facingMode:"user"}:!1};if(this.isSafari()&&e.type.video){let a=r.video;a.width={min:640,ideal:1280,max:1920},a.height={min:360,ideal:720,max:1080},a.frameRate={min:15,ideal:20,max:30}}return r}catch(r){return this.loggingService.catch("Error in RecorderService buildMediaConstraints: ",r),{}}}adjustSafariAudioTrack(e,i){return ee(this,null,function*(){try{let r=i.getAudioTracks()[0];if(r.getSettings().sampleRate!==48e3){this.loggingService.log("[startRecording] Adjusting audio sample rate for Safari");let s=yield navigator.mediaDevices.getUserMedia({audio:{sampleRate:48e3}});e.addTrack(s.getAudioTracks()[0])}else e.addTrack(r)}catch(r){this.loggingService.catch("Error in RecorderService adjustSafariAudioTrack: ",r);return}})}initializeMediaRecorder(e,i){return ee(this,null,function*(){try{this.mediaRecorder=new MediaRecorder(e,i),this.chunks=[],this.chunkUrls$.next({}),this.uploadPromises=[];let r=0;if(this.isSafari()){let s=e.getVideoTracks();s.length>0&&s.forEach(c=>{c.contentHint="detail",c.enabled=!0})}this.mediaRecorder.addEventListener("dataavailable",s=>{if(s.data?.size>0){let c=r++;this.chunks.push(s.data);let p=`recording_${new Date().getTime()}_${Math.random().toString(36).substring(2,9)}`,h=s.data,_=this.uploadChunk(h,p,c);this.uploadPromises||(this.uploadPromises=[]),this.uploadPromises.push({promise:_,index:c}),_.then(E=>{this.chunkUrls$.next(T(I({},this.chunkUrls$.value),{[c]:E}))}).catch(E=>{console.error("Chunk upload failed",E)})}}),this.mediaRecorder.addEventListener("stop",()=>this.onStopRecording()),this.mediaRecorder.start(4e3)}catch(r){this.loggingService.catch("Error in RecorderService initializeMediaRecorder: ",r);return}})}uploadChunk(e,i,r){return ee(this,null,function*(){try{let a="video/mp4",c=`chunk_${r}_${new Date().getTime()}.mp4`,p=new File([e],c,{type:a});return yield this.uploadChunkToStorage(p,i,r)}catch(a){throw this.loggingService.catch("Error in RecorderService uploadChunk: ",a),a}})}uploadChunkToStorage(e,i,r){try{if(!this.documentPaths?.documentId)throw new Error("Document ID is required for chunk upload");let a=this.documentPaths?.organizationId,s=this.documentPaths?.documentId,c=`${U.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${U.FIREBASE_PARTIAL_PATH_RECORDER}/${i}`;return a&&(c=`${U.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${a}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${U.FIREBASE_PARTIAL_PATH_RECORDER}/${i}`),this.storageService.uploadChunk(c,e,r)}catch(a){throw this.loggingService.catch("Error in RecorderService uploadChunkToStorage: ",a),a}}setupRecorderData(e,i){try{return this.recorderInitData=new pM,this.recorderStatusSubject$.next("started"),this.isSafari()&&e.type.video&&(this.loggingService.log("[setupRecorderData] Applying Safari-specific stream handling"),i.getVideoTracks().forEach(r=>{r.enabled=!0;try{r.applyConstraints({width:{ideal:1280},height:{ideal:720},frameRate:{min:15,ideal:20}})}catch(a){this.loggingService.catch("Error applying constraints to video track in Safari:",a)}})),this.recorderInitData.stream=i,this.recorderInitData.status=this.recorderStatusSubject$.asObservable(),this.recorderInitData.type=this.determineRecorderType(e),this.recorderInitData.recordedTime=this.recorderDurationSubject$.asObservable(),this.recorderInitData.recordedRawData$=this.recordedRawData$.asObservable(),this.recordingDurations=[{start:new Date().getTime()}],this.startTimer(),this.recorderInitData$.next(this.recorderInitData),this.recorderInitData}catch(r){return this.loggingService.catch("Error in RecorderService setupRecorderData: ",r),null}}determineRecorderType(e){try{return e.type.video?"video":e.type.screen?"screen":(e.type.audio,"audio")}catch(i){return this.loggingService.catch("Error in RecorderService determineRecorderType: ",i),"audio"}}timeout(e){return new Promise(i=>setTimeout(i,e))}pauseRecording(){try{this.recorderStatusSubject$.next("paused"),this.mediaRecorder.pause(),this.recordingDurations?.length&&(this.recordingDurations[this.recordingDurations.length-1].end=new Date().getTime()),this.stopTimer()}catch(e){this.loggingService.catch("Error in RecorderService pauseRecording: ",e)}}resumeRecording(){try{this.recorderStatusSubject$.next("resumed"),this.mediaRecorder.resume(),this.recordingDurations.push({start:new Date().getTime()}),this.startTimer()}catch(e){this.loggingService.catch("Error in RecorderService resumeRecording: ",e)}}stopRecording(){try{this.mediaRecorder?.state!=="inactive"?(this.mediaRecorder.stop(),this.removeRecordingAttributeFromBody()):this.clearRecording()}catch(e){this.loggingService.catch("Error in RecorderService stopRecording: ",e)}}onStopRecording(){return ee(this,null,function*(){try{this.loggingService.log("[onStopRecording] Starting, current chunks:",this.chunks.length),this.recordingDurations?.length&&(this.recordingDurations[this.recordingDurations?.length-1].end=new Date().getTime()),this.stopTimer(),this.recorderStatusSubject$.next("stopped"),this.recorderInitData?.stream?.getTracks().forEach(i=>{i.stop()}),yield this.timeout(100);let e=new gM;if(this.chunks.length>0){let i=this.recorderInitData?.type==="audio"?"audio/mp4":"video/mp4";if(this.loggingService.log("[onStopRecording] Creating blob with type:",i),e.blob=new Blob(this.chunks,{type:i}),this.loggingService.log("[onStopRecording] Blob created, size:",e.blob.size),e.blob.size===0)throw new Error("Recorded blob has zero size");if(e.url=URL.createObjectURL(e.blob),e.type=this.recorderInitData?.type,e.recordedTime=this.recorderDurationSubject$.value,e?.type!=="audio")try{yield this.timeout(200);let r=yield Lie(e.blob,3);r&&(e.thumbnail=yield Bie(r))}catch(r){this.loggingService.catch("Error in RecorderService onStopRecording getVideoCover: ",r)}this.recordedRawData$.next(e)}else throw new Error("No data chunks recorded")}catch(e){this.loggingService.catch("Error in RecorderService onStopRecording: ",e),this.recordedRawData$.error(e)}})}clearRecording(){return ee(this,null,function*(){try{this.loggingService.log("%c[WB] Calling RecorderService FUNCTION: clearRecording","color: green;"),this.recorderStatusSubject$.next(null),this.recorderDurationSubject$.next(null),this.onInitRecording$.next(null),this.recordingDurations=[],this.domService.resetRecordingInProgress(),this.mediaRecorder=null,this.recorderInitData?.stream?.getTracks()?.forEach(e=>{e.stop()}),this.recorderInitData=null,this.recorderInitData$.next(null),this.chunks=[],this.chunkUrls$.next({}),this.stopTimer()}catch(e){this.loggingService.catch("Error in RecorderService clearRecording: ",e)}})}startTimer(){try{this.stopTimer(),this.durationInterval=setInterval(()=>{this.calculateRecordedTime()},1e3)}catch(e){this.loggingService.catch("Error in RecorderService startTimer: ",e)}}stopTimer(){try{this.durationInterval&&clearInterval(this.durationInterval)}catch(e){this.loggingService.catch("Error in RecorderService stopTimer: ",e)}}calculateRecordedTime(){try{if(this?.recordingDurations?.length){let e=0;this.recordingDurations.forEach(i=>{i.end?e+=i?.end-i.start:e+=new Date().getTime()-i.start;let r={};r.duration=e,r.display=this.convertMillisecondsToTime(e),this.recorderDurationSubject$.next(r)})}else this.recorderDurationSubject$.next(null)}catch(e){this.loggingService.catch("Error in RecorderService calculateRecordedTime: ",e)}}convertMillisecondsToTime(e){try{let i=Math.floor(e/1e3),r=Math.floor(i/60),a=Math.floor(r/60);return i=i%60,r=r%60,`${a?a.toString().padStart(2,"0")+":":""}${r.toString().padStart(2,"0")}:${i.toString().padStart(2,"0")}`}catch(i){return this.loggingService.catch("Error in RecorderService convertMillisecondsToTime: ",i),""}}getRecorderStatus$(){return this.recorderDurationSubject$.asObservable()}enableRecordingCountdown(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableRecordingCountdown","color: green;"),this.recordingCountdownEnabled$.value===!0)return;this.recordingCountdownEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in RecorderService enableRecordingCountdown: ",e)}}disableRecordingCountdown(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableRecordingCountdown","color: green;"),this.recordingCountdownEnabled$.value===!1)return;this.recordingCountdownEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in RecorderService disableRecordingCountdown: ",e)}}getRecordingCountdownEnabled$(){return this.recordingCountdownEnabled$.asObservable()}enableDarkMode(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableDarkMode","color: green;"),this.darkMode$.value===!0)return;this.darkMode$.next(!0)}catch(e){this.loggingService.catch("Error in RecorderService enableDarkMode: ",e)}}disableDarkMode(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableDarkMode","color: green;"),this.darkMode$.value===!1)return;this.darkMode$.next(!1)}catch(e){this.loggingService.catch("Error in RecorderService disableDarkMode: ",e)}}getDarkMode(){return this.darkMode$.value}getDarkMode$(){return this.darkMode$.asObservable()}enableShadowDom(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableShadowDom","color: green;"),this.shadowDom$.value===!0)return;this.shadowDom$.next(!0)}catch(e){this.loggingService.catch("Error in RecorderService enableShadowDom: ",e)}}disableShadowDom(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableShadowDom","color: green;"),this.shadowDom$.value===!1)return;this.shadowDom$.next(!1)}catch(e){this.loggingService.catch("Error in RecorderService disableShadowDom: ",e)}}getShadowDom(){return this.shadowDom$.value}getShadowDom$(){return this.shadowDom$.asObservable()}isSafari(){try{this.loggingService.log("%c[WB] Calling FUNCTION: isSafari","color: green;");let e=navigator.userAgent.toLowerCase();return e.includes("safari")&&!e.includes("chrome")&&!e.includes("android")}catch(e){return this.loggingService.catch("Error in RecorderService isSafari: ",e),!1}}getSupportedMimeTypes(){try{return this.loggingService.log("%c[WB] Calling FUNCTION: getSupportedMimeTypes","color: green;"),["video/mp4;codecs=h264,aac","video/mp4","audio/mp4","video/webm;codecs=vp9,opus","video/webm;codecs=vp8,opus","video/webm;codecs=h264,opus","video/webm"].filter(i=>MediaRecorder.isTypeSupported(i))}catch(e){return this.loggingService.catch("Error in RecorderService getSupportedMimeTypes: ",e),[]}}enableVideoEditor(){try{if(this.videoEditor$.value===!0)return;this.videoEditor$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableVideoEditor: ",e)}}disableVideoEditor(){try{if(this.videoEditor$.value===!1)return;this.videoEditor$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableVideoEditor: ",e)}}getVideoEditor$(){return this.videoEditor$.asObservable()}getVideoEditor(){return this.videoEditor$.value}waitForChunksUpload(){return ee(this,null,function*(){try{if(this.uploadPromises.length===0)return{};let e=this.uploadPromises.map(i=>i.promise);return yield Promise.all(e),this.chunkUrls$.value}catch(e){return this.loggingService.catch("Error in RecorderService waitForChunksUpload: ",e),this.chunkUrls$.value}})}getChunkUrls$(){return this.chunkUrls$.asObservable()}getChunkUrls(){return this.chunkUrls$.value}setRecorderActionsService(e){try{this.recorderActionsService=e}catch(i){this.loggingService.catch("Error in RecorderAnnotationService setRecorderActionsService: ",i)}}enableSettingsEmbedded(){try{if(this.settingsEmbedded$.value===!0)return;this.settingsEmbedded$.next(!0)}catch(e){this.loggingService.catch("Error in RecorderService enableSettingsEmbedded: ",e)}}disableSettingsEmbedded(){try{if(this.settingsEmbedded$.value===!1)return;this.settingsEmbedded$.next(!1)}catch(e){this.loggingService.catch("Error in RecorderService disableSettingsEmbedded: ",e)}}getSettingsEmbedded$(){return this.settingsEmbedded$.asObservable()}getSettingsEmbedded(){return this.settingsEmbedded$.value}enableAutoOpenVideoEditor(){try{if(this.autoOpenVideoEditor$.value===!0)return;this.autoOpenVideoEditor$.next(!0)}catch(e){this.loggingService.catch("Error in RecorderService enableAutoOpenVideoEditor: ",e)}}disableAutoOpenVideoEditor(){try{if(this.autoOpenVideoEditor$.value===!1)return;this.autoOpenVideoEditor$.next(!1)}catch(e){this.loggingService.catch("Error in RecorderService disableAutoOpenVideoEditor: ",e)}}getAutoOpenVideoEditor$(){return this.autoOpenVideoEditor$.asObservable()}getAutoOpenVideoEditor(){return this.autoOpenVideoEditor$.value}enablePlayVideoInFullScreen(){try{if(this.playVideoInFullScreen$.value===!0)return;this.playVideoInFullScreen$.next(!0)}catch(e){this.loggingService.catch("Error in RecorderService enablePlayVideoInFullScreen: ",e)}}disablePlayVideoInFullScreen(){try{if(this.playVideoInFullScreen$.value===!1)return;this.playVideoInFullScreen$.next(!1)}catch(e){this.loggingService.catch("Error in RecorderService disablePlayVideoInFullScreen: ",e)}}getPlayVideoInFullScreen$(){return this.playVideoInFullScreen$.asObservable()}getPlayVideoInFullScreen(){return this.playVideoInFullScreen$.value}};o.\u0275fac=function(i){return new(i||o)(J(Qe),J(y),J(qi),J(Bp),J(lt),J(pn),J(Fe))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Za=(()=>{let o=class o{constructor(e,i,r,a,s,c,p,h,_){this.afAuth=e,this.authService=i,this.configService=r,this.databaseService=a,this.docService=s,this.commonDbService=c,this.iamService=p,this.loggingService=h,this.notificationService=_,this.documentPaths=null,this.db=Ci(),this.views$=new fe({}),this.commentViews$=new fe({}),this.documentViews$=new fe({}),this.locationViews$=new fe({}),this.commentViewsByOrganizationIdAndDocumentId$=new fe({}),this.documentViewsByOrganizationIdAndDocumentId$=new fe({}),this.locationViewsByOrganizationIdAndLocationId$=new fe({}),this.documentViewsEnabled$=new fe(!1),this.documentViewsSetByDocumentId={},this.loggingService.log("%c[WB] Creating CLASS: ViewsService","color: blue;");try{this.authService.setViewsService(this),this.databaseService.getDb().pipe(Ne(E=>!!E),Je(1)).subscribe(E=>{E&&(this.db=E,this.subscribeViewsData().subscribe(),this.getNotificationFeatureViews$().subscribe(D=>{this.notificationService.setNotificationViews(D)}),this.authService.getUser$().pipe(Ne(D=>!!D),ge(D=>this.documentViewsEnabled$.pipe(Ne(B=>B),ce(()=>D))),ge(D=>this.docService.getDocumentPaths$().pipe(Go(null),Vi(),ce(([B,G])=>(B?.documentId!==G?.documentId&&this.views$.next({}),G)),ce(B=>(this.documentPaths=B,this.setDocumentAsRead({documentId:this.documentPaths?.documentId??"",clientDocumentId:this.documentPaths?.clientDocumentId??""}),{_user:D,_documentPaths:B})),ge(B=>this.docService.getDocumentIds$().pipe(ge(G=>(G?.length&&(G.find(X=>X.documentId===this.documentPaths?.documentId)||G.push({documentId:this.documentPaths?.documentId??"",clientDocumentId:this.documentPaths?.clientDocumentId??""}),G.forEach(X=>{this.setDocumentAsRead({documentId:X.documentId,clientDocumentId:X.clientDocumentId})})),re(B))))))),ge(D=>this.docService.getDocumentMetadata$().pipe(Ne(B=>!!B),ce(B=>T(I({},D),{_documentMetadata:B}))))).subscribe(),this.authService.getUser$().pipe(Ne(D=>!!D),ge(D=>this.documentViewsEnabled$.pipe(Ne(B=>B),ce(()=>D))),ge(D=>this.docService.getLocation$().pipe(Ne(B=>!!B))),ge(D=>this.docService.getDocumentIds$().pipe(ge(B=>(B.find(G=>G.documentId===this.documentPaths?.documentId)||B.push({documentId:this.documentPaths?.documentId??"",clientDocumentId:this.documentPaths?.clientDocumentId??""}),B.forEach(G=>{this.setLocationAsRead({documentId:G.documentId,clientDocumentId:G.clientDocumentId})}),re(D)))))).subscribe())},E=>{this.loggingService.catch("Error in ViewsService getDb subscription: ",E)})}catch(E){this.loggingService.catch("Error in ViewsService constructor: ",E)}}clearCache(){this.loggingService.log("%c[WB] Calling FUNCTION: clearCache in ViewsService","color: green;");try{this.documentPaths=null,this.documentViews$.next({}),this.views$.next({}),this.commentViews$.next({}),this.locationViews$.next({}),this.commentViewsByOrganizationIdAndDocumentId$.next({}),this.documentViewsByOrganizationIdAndDocumentId$.next({}),this.locationViewsByOrganizationIdAndLocationId$.next({})}catch(e){this.loggingService.catch("Error in ViewsService clearCache: ",e)}}subscribeViewsData(e,i){this.loggingService.log("%c[WB] Calling FUNCTION: subscribeViewsData","color: green;");let r,a;try{if(e&&(a=fn(e)),i&&typeof i=="object"){let s=Xo(i);r=fn(JSON.stringify(s))}}catch(s){this.loggingService.catch("Error in ViewsService subscribeViewsData: ",s)}return Wn(this.afAuth).pipe(Ne(s=>!!s),ge(s=>this.isFeatureAllowed({firebaseUser:s})),ge(s=>s.featureAllowed?this.iamService.isUserAllowed$().pipe(ce(c=>(s.featureAllowed=c,s))):re(s)),ge(s=>s.featureAllowed?re(s).pipe(ge(c=>this.docService.getDocumentPaths$().pipe(ce(p=>(this.documentPaths=p,c.documentPaths=p,c)))),ge(c=>a?this.getDataFromDocumentIds([a]):this.docService.getDocumentIds$().pipe(ge(p=>{let h=p?.length>0?p.map(_=>_.documentId):[this.documentPaths?.documentId??""];return this.getDataFromDocumentIds(h)})))):re([])))}isFeatureAllowed(e){return this.configService.getConfig$().pipe(Ne(i=>!!i),ce(i=>T(I({},e),{config:i})),ge(i=>this.authService.getUser$().pipe(ce(r=>T(I({},i),{user:r})))),ge(i=>i.user?re(T(I({},i),{featureAllowed:!0})):re(T(I({},i),{featureAllowed:!1}))))}getDataFromDocumentIds(e,i){return this.getDataFromDocuments({documentIds:e,filters:i})}getCommentViewsById(e){try{return this.commentViews$.value?.[e]?this.commentViews$.value?.[e]:void 0}catch(i){this.loggingService.catch("Error in ViewsService getCommentViewsById: ",i);return}}getDocumentViewsById(e){try{return this.documentViews$.value?.[e]}catch(i){this.loggingService.catch("Error in ViewsService getDocumentViewsById: ",i);return}}getLocationViewsById(e){try{return this.locationViews$.value?.[e]}catch(i){this.loggingService.catch("Error in ViewsService getLocationViewsById: ",i);return}}getDataFromDocuments(e){if(this.configService?.getApiKey()){let{documentIds:i,filters:r}=e;return i?.some(a=>!a)||!this.documentPaths?re([]):this.documentViewsEnabled$.pipe(ge(a=>a?Dn([this.getCommentViewsDataFromDocuments(i),this.getDocumentViewsDataFromDocuments(i),this.getLocationViewsDataFromDocuments(i)]):Dn([this.getCommentViewsDataFromDocuments(i)])))}else return re(null)}getCommentViewsDataFromDocuments(e){let i=this.docService.getFolderConfig(),r=re([]),a={useCollectionGroup:!0,isCollection:!0,useQuery:!0};if(this.commonDbService.shouldUseFirestore()||(a.documentId=e?.length?e[0]:void 0,a.organizationId=this.documentPaths?.organizationId),i?.veltFolderId&&i?.allDocuments)r=this.commonDbService.dbListener({feature:"allCommentViews",properties:T(I({},a),{firestoreQuery:[Fi(mt("metadata.apiKey","==",this.configService?.getApiKey()),mt("metadata.veltFolderId","==",i?.veltFolderId),mt("metadata.organizationId","==",this.documentPaths?.organizationId))]})});else{let s=[];for(let c=0;c<(e?.length??0);c+=U.LISTENER_BATCH_SIZE)s.push(e?.slice(c,c+U.LISTENER_BATCH_SIZE)??[]);r=Dn(s.map(c=>this.commonDbService.dbListener({feature:"allCommentViews",properties:T(I({},a),{firestoreQuery:[Fi(mt("metadata.apiKey","==",this.configService?.getApiKey()),mt("metadata.documentId","in",c),mt("metadata.organizationId","==",this.documentPaths?.organizationId),...i?.veltFolderId?[mt("metadata.veltFolderId","==",i?.veltFolderId)]:[])]})}).pipe($r()))).pipe(ce(c=>ca(c)))}return r.pipe(ce(s=>({data:s?.data,operation:s?.operation})),ce(({data:s,operation:c})=>{let p={};return e?(Object.entries(s??{}).forEach(([h,_])=>{let E=_.metadata?.documentId;E&&(p[E]||(p[E]={}),p[E][h]=_)}),{data:s,documentMap:p,operation:c}):{data:s,documentMap:p,operation:c}}),ce(({data:s,documentMap:c,operation:p})=>{if(p?.type==="removed"){if(p?.ids?.length){let h=this.commentViews$.value;p?.ids?.forEach(_=>{delete h?.[_]}),this.commentViews$.next(h)}}else Object.entries(c??{}).forEach(([h,_])=>{this.setCommentViewsByOrganizationIdAndDocumentId({organizationId:this.documentPaths?.organizationId,documentId:h,commentViews:_})})}))}getDocumentViewsDataFromDocuments(e){let i=this.docService.getFolderConfig(),r=re([]),a={useCollectionGroup:!0,isCollection:!0,useQuery:!0};if(this.commonDbService.shouldUseFirestore()||(a.documentId=e?.length?e[0]:void 0,a.organizationId=this.documentPaths?.organizationId),i?.veltFolderId&&i?.allDocuments)r=this.commonDbService.dbListener({feature:"allDocumentViews",properties:T(I({},a),{firestoreQuery:[Fi(mt("metadata.apiKey","==",this.configService?.getApiKey()),mt("metadata.veltFolderId","==",i?.veltFolderId),mt("metadata.organizationId","==",this.documentPaths?.organizationId))]})});else{let s=[];for(let c=0;c<(e?.length??0);c+=U.LISTENER_BATCH_SIZE)s.push(e?.slice(c,c+U.LISTENER_BATCH_SIZE)??[]);r=Dn(s.map(c=>this.commonDbService.dbListener({feature:"allDocumentViews",properties:T(I({},a),{firestoreQuery:[Fi(mt("metadata.apiKey","==",this.configService?.getApiKey()),mt("metadata.documentId","in",c),mt("metadata.organizationId","==",this.documentPaths?.organizationId),...i?.veltFolderId?[mt("metadata.veltFolderId","==",i?.veltFolderId)]:[])]})}).pipe($r()))).pipe(ce(c=>ca(c)))}return r.pipe(ce(s=>({data:s?.data,operation:s?.operation})),ce(({data:s,operation:c})=>{let p={};return e?(Object.entries(s??{}).forEach(([h,_])=>{let E=_.metadata?.documentId;E&&(p[E]||(p[E]={}),p[E][h]=_)}),{data:s,documentMap:p,operation:c}):{data:s,documentMap:p,operation:c}}),ce(({data:s,documentMap:c,operation:p})=>{if(p?.type==="removed"){if(p?.ids?.length){let h=this.documentViews$.value;p?.ids?.forEach(_=>{delete h?.[_]}),this.documentViews$.next(h)}}else Object.entries(c??{}).forEach(([h,_])=>{this.setDocumentViewsByOrganizationIdAndDocumentId({organizationId:this.documentPaths?.organizationId,documentId:h,documentViews:_})})}))}getLocationViewsDataFromDocuments(e){let i=this.docService.getFolderConfig(),r=re([]),a={useCollectionGroup:!0,isCollection:!0,useQuery:!0};if(this.commonDbService.shouldUseFirestore()||(a.documentId=e?.length?e[0]:void 0,a.organizationId=this.documentPaths?.organizationId),i?.veltFolderId&&i?.allDocuments)r=this.commonDbService.dbListener({feature:"allLocationViews",properties:T(I({},a),{firestoreQuery:[Fi(mt("metadata.apiKey","==",this.configService?.getApiKey()),mt("metadata.veltFolderId","==",i?.veltFolderId),mt("metadata.organizationId","==",this.documentPaths?.organizationId))]})});else{let s=[];for(let c=0;c<(e?.length??0);c+=U.LISTENER_BATCH_SIZE)s.push(e?.slice(c,c+U.LISTENER_BATCH_SIZE)??[]);r=Dn(s.map(c=>this.commonDbService.dbListener({feature:"allLocationViews",properties:T(I({},a),{firestoreQuery:[Fi(mt("metadata.apiKey","==",this.configService?.getApiKey()),mt("metadata.documentId","in",c),mt("metadata.organizationId","==",this.documentPaths?.organizationId),...i?.veltFolderId?[mt("metadata.veltFolderId","==",i?.veltFolderId)]:[])]})}).pipe($r()))).pipe(ce(c=>ca(c)))}return r.pipe(ce(s=>({data:s?.data,operation:s?.operation})),ce(({data:s,operation:c})=>{let p={};return e?(Object.entries(s??{}).forEach(([h,_])=>{let E=_.metadata?.documentId;E&&(p[E]||(p[E]={}),p[E][h]=_)}),{data:s,documentMap:p,operation:c}):{data:s,documentMap:p,operation:c}}),ce(({data:s,documentMap:c,operation:p})=>{if(p?.type==="removed"){if(p?.ids?.length){let h=this.locationViews$.value;p?.ids?.forEach(_=>{delete h?.[_]}),this.locationViews$.next(h)}}else Object.entries(c??{}).forEach(([h,_])=>{this.setLocationViewsByOrganizationIdAndDocumentId({organizationId:this.documentPaths?.organizationId,documentId:h,locationViews:_})})}))}setViewsData(e){try{this.views$.next(I(I({},this.views$.getValue()),e||{}))}catch(i){this.loggingService.catch("Error in ViewsService setViewsData:",i)}}setCommentViewsByOrganizationIdAndDocumentId({organizationId:e,documentId:i,commentViews:r,queryHash:a}){try{if(r||(r={}),i){e||(e=U.NO_ORGANIZATION_ID),a||(a=U.DEFAULT_QUERY_HASH);let s=I(I({},this.commentViews$.value),r);this.commentViews$.next(s),this.commentViewsByOrganizationIdAndDocumentId$.next(T(I({},this.commentViewsByOrganizationIdAndDocumentId$.value),{[e]:T(I({},this.commentViewsByOrganizationIdAndDocumentId$.value[e]),{[i]:T(I({},this.commentViewsByOrganizationIdAndDocumentId$.value[e]?.[i]),{[a]:r})})}))}}catch(s){this.loggingService.catch("Error in CommentService setCommentAnnotationsByOrganizationIdAndDocumentId:",s)}}setDocumentViewsByOrganizationIdAndDocumentId({organizationId:e,documentId:i,documentViews:r,queryHash:a}){try{if(r||(r={}),i){e||(e=U.NO_ORGANIZATION_ID),a||(a=U.DEFAULT_QUERY_HASH);let s=I(I({},this.documentViews$.value),r);this.documentViews$.next(s),this.documentViewsByOrganizationIdAndDocumentId$.next(T(I({},this.documentViewsByOrganizationIdAndDocumentId$.value),{[e]:T(I({},this.documentViewsByOrganizationIdAndDocumentId$.value[e]),{[i]:T(I({},this.documentViewsByOrganizationIdAndDocumentId$.value[e]?.[i]),{[a]:r})})}))}}catch(s){this.loggingService.catch("Error in CommentService setCommentAnnotationsByOrganizationIdAndDocumentId:",s)}}setLocationViewsByOrganizationIdAndDocumentId({organizationId:e,documentId:i,locationViews:r,queryHash:a}){try{if(r||(r={}),i){e||(e=U.NO_ORGANIZATION_ID),a||(a=U.DEFAULT_QUERY_HASH);let s=I(I({},this.locationViews$.value),r);this.locationViews$.next(s),this.locationViewsByOrganizationIdAndLocationId$.next(T(I({},this.locationViewsByOrganizationIdAndLocationId$.value),{[e]:T(I({},this.locationViewsByOrganizationIdAndLocationId$.value[e]),{[i]:T(I({},this.locationViewsByOrganizationIdAndLocationId$.value[e]?.[i]),{[a]:r})})}))}}catch(s){this.loggingService.catch("Error in CommentService setCommentAnnotationsByOrganizationIdAndDocumentId:",s)}}getCommentFeatureViews$(){return this.commentViews$.pipe(Kt((e,i)=>JSON.stringify(e||{})===JSON.stringify(i||{})))}setCommentAnnotationAsRead(e){return ee(this,null,function*(){try{if(this.authService.getUser()&&e?.annotationId){let r=this.getCommentViewsById(e.annotationId)??(yield this.commonDbService?.getData({feature:"commentViews",properties:{id:e.annotationId,documentId:e.metadata?.documentId??this.documentPaths?.documentId??"",organizationId:e?.metadata?.organizationId??this.documentPaths?.organizationId??""}})),a=this.updateCommentAnnotationViews(e,r||{});this.commonDbService.setData({feature:"commentViews",properties:{id:e.annotationId,documentId:e.metadata?.documentId??this.documentPaths?.documentId??"",organizationId:e?.metadata?.organizationId??this.documentPaths?.organizationId??""},data:a})}}catch(i){this.loggingService.catch("Error in ViewsService setCommentAnnotationAsRead:",i)}})}updateCommentAnnotationViews(e,i){try{let r=this.authService.getUser(),a={views:{},comments:{}};if(r){let s={},c=i?.comments||{},p=new Date().getTime()+this.commonDbService.getOffset();e.comments?.forEach(_=>{c[_.commentId]||(c[_.commentId]={views:{}}),c[_.commentId].views||(c[_.commentId].views={}),c[_.commentId].views[r.userSnippylyId]||(c[_.commentId].views[r.userSnippylyId]={},c[_.commentId].views[r.userSnippylyId].timestamp=p)});let h=new Set(e.comments?.map(_=>_.commentId+""));if(Object.keys(c??{}).forEach(_=>{h.has(_)||delete c[_]}),e.comments?.length){let _=c[e.comments[0].commentId]?.views||{};Object.keys(_??{}).filter(D=>e.comments?.every(B=>c[B.commentId]?.views?.[D])).forEach(D=>{s[D]={timestamp:_[D].timestamp}})}a.views=s,a.comments=c}return e?.metadata?a.metadata=e.metadata:a.metadata=this.docService.getBaseMetadata(),a}catch(r){return this.loggingService.catch("Error in ViewsService updateCommentAnnotationViews:",r),{views:{},comments:{}}}}deleteCommentAnnotationViews(a,s){return ee(this,arguments,function*(e,{documentId:i,organizationId:r}){try{yield this.commonDbService.deleteData({feature:"commentViews",properties:{id:e.annotationId,documentId:i,organizationId:r}})}catch(c){this.loggingService.catch("Error in ViewsService deleteCommentAnnotationViews:",c)}})}getNotificationFeatureViews$(){return this.views$.pipe(Kt((e,i)=>JSON.stringify(e?.notification||{})===JSON.stringify(i?.notification||{})))}setNotificationsAsRead(e){try{let i=this.authService.getUser();if(i){let r=new Date().getTime()+this.commonDbService.getOffset();e.forEach(a=>{this.commonDbService.updateData({feature:"notificationViewsTimestamp",properties:{id:a,user:i.userSnippylyId,documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??""},data:{timestamp:r}})})}}catch(i){this.loggingService.catch("Error in ViewsService setNotificationAsRead:",i)}}getDocumentViews$(){return this.views$.pipe(Kt((e,i)=>JSON.stringify(e?.documentViews||{})===JSON.stringify(i?.documentViews||{})))}getUniqueViewsByUser(e){try{return this.enableDocumentViews(),this.docService.getDocumentPaths$().pipe(ge(i=>(this.documentPaths=i,e?this.locationViews$.pipe(ce(r=>{let a=Object.keys(r||{}).find(s=>r?.[s]?.location?.id===e);return a?r?.[a]?.users||{}:{}})):this.documentViews$.pipe(ce(r=>{let a=this.documentPaths?.documentId;return a?r?.[a]?.users||{}:{}})))),Kt(_o))}catch(i){return this.loggingService.catch("Error in ViewsService getUniqueViewsByUser:",i),re({})}}getUniqueViewsByDate(e){try{return this.enableDocumentViews(),this.docService.getDocumentPaths$().pipe(ge(i=>(this.documentPaths=i,e?this.locationViews$.pipe(ce(r=>{let a=Object.keys(r||{}).find(s=>r?.[s]?.location?.id===e);return a?r?.[a]?.day||{}:{}})):this.documentViews$.pipe(ce(r=>{let a=this.documentPaths?.documentId;return a?r?.[a]?.day||{}:{}})))))}catch(i){return this.loggingService.catch("Error in ViewsService getUniqueViewsByDate:",i),re({})}}enableDocumentViews(){try{if(this.documentViewsEnabled$.value===!0)return;this.documentViewsEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in ViewsService enableDocumentViews:",e)}}disableDocumentViews(){try{if(this.documentViewsEnabled$.value===!1)return;this.documentViewsEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in ViewsService disableDocumentViews:",e)}}setDocumentAsRead(r){return ee(this,arguments,function*({documentId:e,clientDocumentId:i}){try{let a=this.authService.getUser();if(a&&e){if(this.documentViewsSetByDocumentId[e])return;this.documentViewsSetByDocumentId[e]=!0;let s=new Date().getTime()+this.commonDbService.getOffset(),c=new Date().toISOString().split("T")[0],p=this.getDocumentViewsById(e);if(p){let h=new Date().toISOString().split("T")[0];p?.users[a.userSnippylyId]||(p.users[a.userSnippylyId]={}),p.users[a.userSnippylyId][h]={timestamp:this.timestamp},p?.day[h]||(p.day[h]={}),p.day[h][a.userSnippylyId]={timestamp:this.timestamp},p.metadata=this.docService.getBaseMetadata("documentViews",{clientDocumentId:i}),this.commonDbService.updateData({feature:"documentViews",properties:{id:e,date:h,user:a.userSnippylyId,documentId:e,organizationId:this.documentPaths?.organizationId??""},data:p})}else this.commonDbService.updateData({feature:"documentDayViews",properties:{id:e,date:c,user:a.userSnippylyId,documentId:e,organizationId:this.documentPaths?.organizationId??"",skipFirestore:!0},data:{timestamp:s}}),this.commonDbService.updateData({feature:"documentUsersViews",properties:{id:e,user:a.userSnippylyId,date:c,documentId:e,organizationId:this.documentPaths?.organizationId??"",skipFirestore:!0},data:{timestamp:s}}),this.commonDbService.updateData({feature:"documentMetadataViews",properties:{id:e,documentId:e,organizationId:this.documentPaths?.organizationId??"",skipFirestore:!0},data:this.docService.getBaseMetadata("documentViews",{clientDocumentId:i})}),this.docService.getDocumentMetadata$(e).pipe(Ne(h=>h!==null),Je(1)).subscribe(()=>{let h={day:{[c]:{[a.userSnippylyId]:{timestamp:s}}},users:{[a.userSnippylyId]:{[c]:{timestamp:s}}},metadata:this.docService.getBaseMetadata("documentViews",{clientDocumentId:i})};this.commonDbService.updateData({feature:"documentViews",properties:{id:e,date:c,user:a.userSnippylyId,documentId:e,organizationId:this.documentPaths?.organizationId??"",skipRtdb:!0},data:h})});this.checkAndTriggerNotification(a)}}catch(a){this.loggingService.catch("Error in ViewsService setDocumentAsRead:",a)}})}checkAndTriggerNotification(e){try{this.getUniqueViewsByUser().pipe(Je(1)).subscribe(i=>{if(Object.keys(i??{}).length===2){let r=this.docService.getDocumentMetadata();if(r?.creator?.email&&r?.creator?.email!==e.email){let a=[r.creator.email];this.updateNotificationsDatabase(pV.FIRST_VIEWED,{documentViews:{emails:a}})}}})}catch(i){this.loggingService.catch("Error in checkAndTriggerNotification:",i)}}setLocationAsRead(r){return ee(this,arguments,function*({documentId:e,clientDocumentId:i}){try{let a=this.authService.getUser(),s=this.docService.getLocation(),c=s?.locationId,p=s?.location;if(a&&c&&p){let h=new Date().getTime()+this.commonDbService.getOffset(),_=new Date().toISOString().split("T")[0],E=this.getLocationViewsById(c);if(E){let D=new Date().toISOString().split("T")[0];E?.users[a.userSnippylyId]||(E.users[a.userSnippylyId]={}),E.users[a.userSnippylyId][D]={timestamp:this.timestamp},E?.day[D]||(E.day[D]={}),E.day[D][a.userSnippylyId]={timestamp:this.timestamp},E.metadata=this.docService.getBaseMetadata("locationViews",{clientDocumentId:i}),this.commonDbService.updateData({feature:"location",data:E,properties:{id:c,documentId:e,organizationId:this.documentPaths?.organizationId??""}})}else{this.commonDbService.updateData({feature:"locationViews",data:p,properties:{id:c,documentId:e,organizationId:this.documentPaths?.organizationId??"",skipFirestore:!0}}),this.commonDbService.updateData({feature:"locationUsersViews",properties:{id:c,user:a.userSnippylyId,date:_,documentId:e,organizationId:this.documentPaths?.organizationId??"",skipFirestore:!0},data:{timestamp:h}}),this.commonDbService.updateData({feature:"locationDayViews",properties:{id:c,date:_,user:a.userSnippylyId,documentId:e,organizationId:this.documentPaths?.organizationId??"",skipFirestore:!0},data:{timestamp:h}}),this.commonDbService.updateData({feature:"locationMetadataViews",properties:{id:c,documentId:e,organizationId:this.documentPaths?.organizationId??"",skipFirestore:!0},data:this.docService.getBaseMetadata("locationViews",{clientDocumentId:i})});let D={day:{[_]:{[a.userSnippylyId]:{timestamp:h}}},users:{[a.userSnippylyId]:{[_]:{timestamp:h}}},metadata:this.docService.getBaseMetadata("locationViews",{clientDocumentId:i}),location:p};this.commonDbService.updateData({feature:"location",data:D,properties:{id:c,documentId:e,organizationId:this.documentPaths?.organizationId??"",skipRtdb:!0}})}}}catch(a){this.loggingService.catch("Error in ViewsService setLocationAsRead:",a)}})}updateNotificationsDatabase(e,i={}){try{let r=I({actionType:e,notificationSource:"documentViews"},i);this.notificationService.updateNotificationDatabase(r)}catch(r){this.loggingService.catch("Error in CommentService updateNotificationsDatabase: ",r)}}get timestamp(){return this.commonDbService.getServerTimestamp()}};o.\u0275fac=function(i){return new(i||o)(J(vi),J(je),J($t),J(pn),J(lt),J(bn),J(gn),J(y),J(Vn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var fm=(()=>{let o=class o{constructor(e,i,r){this.docService=e,this.loggingService=i,this.authService=r;try{this.loggingService.log("%c[WB] Creating CLASS: MetadataService","color: blue;")}catch(a){this.loggingService.catch("Error in MetadataService constructor: ",a)}}getGlobalMetadata(){return ee(this,null,function*(){try{if(!this.authService.getUser())return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),{};let i=this.docService.getOrganizationMetadata(this.docService.getOrganizationConfig()?.organizationId),r=this.docService.getDocumentMetadataOfAvailableDocuments(),a=this.docService.getLocation();i&&(i=JSON.parse(JSON.stringify(i)),delete i?.organizationId,i.organizationId=i?.clientOrganizationId,delete i?.clientOrganizationId,delete i?.pageInfo),r&&(r=JSON.parse(JSON.stringify(r)),r.forEach(_=>{delete _?.locations,delete _?.location,delete _?.locationId,delete _?.pageInfo,delete _?.documentId,_.documentId=_?.clientDocumentId,delete _?.clientDocumentId,delete _?.veltFolderId,_?.clientOrganizationId&&(_.organizationId=_?.clientOrganizationId,delete _?.clientOrganizationId)}));let s=[];a&&(a=JSON.parse(JSON.stringify(a)),a?.location&&s.push(a?.location));let c=this.docService.getLocations();c&&Object.values(c).forEach(_=>{_?.location&&s.push(_?.location)});let p=this.docService.getFolderConfig()?.folderId;return{organization:i,documents:r,locations:s,folderId:p}}catch(e){return this.loggingService.catch("Error in MetadataService getGlobalMetadata: ",e),{}}})}};o.\u0275fac=function(i){return new(i||o)(J(lt),J(y),J(je))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Gv=(()=>{let o=class o{constructor(e,i,r){this.coreActionsService=e,this.loggingService=i,this.metadataService=r,this.buttonClickSubject$=new et,this.buttonToggleMap$=new fe({}),this.contextDataMapping={commentAnnotation:{source:["componentConfigSignal","annotation"],target:"commentAnnotation"},unreadCommentsMap:{source:["componentConfigSignal","unreadCommentsMap"],target:"unreadCommentAnnotationsMap"},comment:{source:["commentObj"],target:"comment"},index:{source:["i"],target:"index"},allAnnotations:{source:["componentConfigSignal","annotations"],target:"commentAnnotations"},systemFilteredAnnotations:{source:["componentConfigSignal","filteredCommentPinAnnotations"],target:"systemFilteredAnnotations"},notification:{source:["notification"],target:"notification"},allNotifications:{source:["componentConfigSignal","notificationsInSession"],target:"notifications"}}}buttonClick(s){return ee(this,arguments,function*({id:e,type:i,groupId:r,contextData:a}){try{this.buttonToggle(e,void 0,i,r);let c=this.extractButtonData(a),p=this.createButtonContext(e,i,r),h=yield this.metadataService.getGlobalMetadata(),_=T(I({buttonContext:p},c),{metadata:h});this.buttonClickSubject$.next(_),this.coreActionsService.triggerAction(gd.VELT_BUTTON_CLICK,_)}catch(c){this.loggingService.catch("Error in ButtonService buttonClick: ",c)}})}buttonActive({id:e,type:i,groupId:r,contextData:a}){try{let s=this.buttonToggleMap$.value?.[r||"ungrouped"]?.[e]||!0;this.buttonToggle(e,s,i,r)}catch(s){this.loggingService.catch("Error in ButtonService buttonClick: ",s)}}buttonToggle(e,i,r,a){try{let s=this.buttonToggleMap$.value,c=this.createNewToggleMap(s,e,i,r,a);this.buttonToggleMap$.next(c)}catch(s){this.loggingService.catch("Error in ButtonService buttonToggle: ",s)}}extractButtonData(e){try{let i={};return Object.entries(this.contextDataMapping).forEach(([r,a])=>{let s=this.getNestedValue(e,a.source);s!==void 0&&(i[a.target]=s)}),i}catch(i){return this.loggingService.catch("Error in ButtonService extractContextData: ",i),{}}}getNestedValue(e,i){try{let r=e;for(let a of i){if(r?.[a]===void 0)return;Pi(r[a])?r=r[a]():r=r[a]}return r}catch(r){this.loggingService.catch("Error in ButtonService getNestedValue: ",r);return}}createButtonContext(e,i,r){try{let a={type:i,selections:this.buttonToggleMap$.value,clickedButtonId:e};return(i==="single-select"||i==="multi-select")&&r?T(I({},a),{groupId:r}):a}catch(a){return this.loggingService.catch("Error in ButtonService createButtonMetadata: ",a),{}}}createNewToggleMap(e,i,r,a,s){try{let c=I({},e);return a==="button-toggle"?T(I({},c),{ungrouped:T(I({},c.ungrouped),{[i]:r??!c.ungrouped?.[i]})}):a==="single-select"&&s?T(I({},c),{[s]:{[i]:r??!0}}):a==="multi-select"&&s?T(I({},c),{[s]:T(I({},c[s]),{[i]:r??!c[s]?.[i]})}):c}catch(c){return this.loggingService.catch("Error in ButtonService createNewToggleMap: ",c),{}}}buttonClickSubject(){return this.buttonClickSubject$.asObservable()}buttonToggleMap(){return this.buttonToggleMap$.asObservable()}resetVeltButtonState(e){return ee(this,null,function*(){try{if(e){let{id:s,group:c}=e,p=JSON.parse(JSON.stringify(this.buttonToggleMap$.value||{}));c&&s?delete p?.[c]?.[s]:c?delete p?.[c]:s&&Object.keys(p).forEach(h=>{Object.keys(p[h]).forEach(_=>{_===s&&delete p?.[h]?.[_]})}),this.buttonToggleMap$.next(p)}else this.buttonToggleMap$.next({});let i={selections:this.buttonToggleMap$.value},r=yield this.metadataService.getGlobalMetadata(),a={buttonContext:i,metadata:r};this.coreActionsService.triggerAction(gd.VELT_BUTTON_CLICK,a)}catch(i){this.loggingService.catch("Error in ButtonService resetVeltButtonState: ",i)}})}buttonToggleMapValue(){return this.buttonToggleMap$.value}};o.\u0275fac=function(i){return new(i||o)(J(Np),J(y),J(fm))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Te=(()=>{let o=class o{constructor(e,i,r,a,s,c,p,h,_,E,D,B,G,X,he,Ie,Me,Le,We,ke,we,Ee,Pe,Ce,ue,Be){this.analyticsService=e,this.areaService=i,this.commonDbService=r,this.configService=a,this.docService=s,this.databaseService=c,this.authService=p,this.domService=h,this.afAuth=_,this.avatarService=E,this.contactService=D,this.storageService=B,this.functions=G,this.dialog=X,this.iamService=he,this.loggingService=Ie,this.notificationService=Me,this.customFilterService=Le,this.reactionService=We,this.hotkeyService=ke,this.recorderService=we,this.viewsService=Ee,this.buttonService=Pe,this.metadataService=Ce,this.commonDbUtilsService=ue,this.attachmentResolverService=Be,this.customPinsById=new Map,this.commentAdded$=new et,this.commentUpdated$=new et,this.commentAccepted$=new et,this.commentRejected$=new et,this.commentAnnotationDeleted$=new et,this.multiThreadCommentAnnotationDeleted$=new et,this.commentAnnotationById$=new fe(null),this.multiThreadCommentAnnotationById$=new fe(null),this.ghostCommentAnnotationMap$=new fe({}),this.unreadCommentsMap$=new fe(null),this.documentPaths=null,this.db=Ci(),this.user=null,this.customCategoryMap=U.CommentCategoryMap,this.allowedElementIds$=new fe([]),this.allowedElementClassNames$=new fe([]),this.allowedElementQuerySelectors$=new fe([]),this.addCommentMode$=new fe(!1),this.persistentCommentMode$=new fe(!1),this.seenByUsers$=new fe(!0),this.deleteReplyConfirmation$=new fe(!1),this.persistentModeBanner$=new fe(!0),this.commentAddedEmitter=null,this.commentContextProvider=null,this.textCommentMode$=new fe(!0),this.sidebarVisible$=new fe(!1),this.sidebarOpenedByCustomTrigger$=new fe(!1),this.floatingCommentsEnabled$=new fe(!0),this.moderatorMode$=new fe(!1),this.streamMode$=new fe(!1),this.enableSignInButton$=new fe(!1),this.enableUpgradeButton$=new fe(!1),this.onSignInClick$=new et,this.onUpgradeClick$=new et,this.enableAttachment$=new fe(!0),this.enableReactions$=new fe(!0),this.allowedRecordings$=new fe(["audio","video","screen"]),this.openSidebar$=new et,this.showScreenSizeInfo$=new fe(!1),this.showCommentIndex$=new fe(!1),this.popoverMode$=new fe(!1),this.popoverTriangleComponent$=new fe(!0),this.draftMode$=new fe(!0),this.enableDialogOnHover$=new fe(!0),this.enableDialogOnTargetElementClick$=new fe(!1),this.enablePriority$=new fe(!1),this.enableStatus$=new fe(!0),this.enableResolve$=new fe(!0),this.enableGhostComments$=new fe(!1),this.enableGhostCommentsMessage$=new fe(!0),this.inboxMode$=new fe(!1),this.enableAutoCategorize$=new fe(!1),this.commentContainerDarkMode$=new fe(!1),this.suggestionMode$=new fe(!1),this.mobileMode$=new fe(!0),this.inlineCommentMode$=new fe(!1),this.minimap$=new fe(!1),this.commentsOnDom$=new fe(!0),this.commentToolEnabled$=new fe(!0),this.totalMediaLength$=new fe(0),this.sidebarUrlNavigationEnabled$=new fe(!1),this.detectionStrategy$=new fe(jO.DEFAULT),this.sidebarButtonOnCommentDialogVisible$=new fe(!1),this.sidebarButtonOnCommentDialogClick$=new et,this.commentNavigationButtonClick$=new et,this.deviceIndicatorOnCommentPins$=new fe(!1),this.sidebarCommentClick$=new et,this.privateCommentMode$=new fe(!1),this.scrollToComment$=new fe(!0),this.userMentions$=new fe(!0),this.deleteOnBackspace$=new fe(!0),this.hotkeyEnabled$=new fe(!1),this.recordingSummaryEnabled$=new fe(!0),this.unreadIndicatorMode$=new fe(wu.MINIMAL),this.composerMode$=new fe(Du.DEFAULT),this.enterKeyToSubmit$=new fe(!1),this.resolvedCommentsOnDom$=new fe(!1),this.bubbleOnPinEnabled$=new fe(!1),this.bubbleOnPinHoverEnabled$=new fe(!0),this.excludeLocationIdsFromSidebar$=new fe([]),this.multiThread$=new fe(!1),this.shortUserName$=new fe(!0),this.collapsedComments$=new fe(!1),this.fullExpanded$=new fe(!1),this.queryParamsComments$=new fe(!1),this.resolveStatusAccessAdminOnly$=new fe(!1),this.svgAsImg$=new fe(!1),this.commentToNearestAllowedElement$=new fe(!1),this.pinShadowDOM$=new fe(!0),this.dialogShadowDOM$=new fe(!0),this.textCommentToolShadowDOM$=new fe(!0),this.pinDarkMode$=new fe(null),this.textCommentToolDarkMode$=new fe(null),this.textCommentToolbarDarkMode$=new fe(null),this.textCommentToolbarShadowDOM$=new fe(!0),this.sidebarShadowDOM$=new fe(!0),this.changeDetectionInCommentMode$=new fe(!1),this.commentSelectionChange$=new et,this.commentSidebarFilters$=new fe({}),this.bubbleCommentAnnotationIds$=new fe([]),this.updateCommentDialogPositionTriggerSubject$=new fe(void 0),this.areaCommentEnabled$=new fe(!0),this.commentPinCursorImage$=new fe(""),this.commentAnnotationsFromCommentsContainer$=new fe([]),this.customChipDropdownData$=new fe(null),this.originalCommentAnnotationsByDocumentId$=new fe({}),this.draftCommentAnnotationsByAnnotationId$=new fe(null),this.draftMultiThreadCommentAnnotationsByAnnotationId$=new fe({}),this.copyLink$=new fe(""),this.addCommentDragMode=!1,this.dragSubscriptions=[],this.hotkeySubscriptions=[],this.sidebarData$=new fe(null),this.sidebarCustomActionEventData$=new fe(null),this.sidebarCustomActionEventDataAllChanges$=new fe(null),this.sidebarCustomActionEventDataOnInit$=new fe(null),this.customActions$=new fe(!1),this.focusedThreadMode$=new fe(!1),this.customStatusesShown$=new fe(!1),this.readOnly$=new fe(!1),this.customAutocompleteSearch$=new fe(!1),this.deleteThreadWithFirstComment$=new fe(!0),this.transformContext$=new fe(null),this.expandMentionGroups$=new fe(!1),this.showMentionGroupsFirst$=new fe(!1),this.showMentionGroupsOnly$=new fe(!1),this.loggingService.log("%c[WB] Creating CLASS: CommentService","color: blue;"),this.analyticsService.setCommentService(this),this.notificationService.setCommentService(this),this.docService.setCommentService(this),this.authService.setCommentService(this),this.docService.getDocumentPaths$().pipe(Vi()).subscribe(([Se,Ut])=>{Se?.documentId!==Ut?.documentId&&this.unreadCommentsMap$.next(null)},Se=>{this.loggingService.catch("Error in CommentService getDocumentPaths$ subscription: ",Se)}),this.authService.getUser$().subscribe(Se=>{Se||this.resetCacheData()},Se=>{this.loggingService.catch("Error in CommentService getUser$ subscription: ",Se)}),this.databaseService.getDb().pipe(Ne(Se=>!!Se),Je(1)).subscribe(Se=>{Se&&(this.db=Se,this.getDocumentPaths())},Se=>{this.loggingService.catch("Error in CommentService getDb subscription: ",Se)}),this.domService.onWindowPointerMove$().subscribe(Se=>{if(this.addCommentMode$.value){let Ut=!0;if(this.addCommentDragMode)this.domService.removeClassFromElement(document.body,"show-pin-cursor");else{let Gt=this.domService.getBackgroundElement(Se.clientX,Se.clientY,!0,!0);if(Gt)if(this.isElementInsideAllowedElements(Gt))if(fd(Se.target))this.domService.removeClassFromElement(document.body,"show-pin-cursor");else{this.domService.addClassToElement(document.body,"show-pin-cursor"),this.hightlightElement&&this.hightlightElement!==Gt&&this.domService.removeHighlightFromElement(this.hightlightElement),this.hightlightElement=Gt;let Dt=this.domService.getSelectedAnnotationsMap("comment")||{},It=this.commentPinCursorImage$.value||U.CURSOR.COMMENT_PIN;this.domService.highlightElement(this.hightlightElement,It,!!Object.keys(Dt)?.length),Ut=!1}else this.domService.removeClassFromElement(document.body,"show-pin-cursor")}this.hightlightElement&&Ut&&(this.domService.removeHighlightFromElement(this.hightlightElement),this.hightlightElement=null)}},Se=>{this.loggingService.catch("Error in CommentService onWindowPointerMove$ subscription: ",Se)}),this.domService.onWindowKeyupEsc$().subscribe(Se=>{if(this.addCommentMode$.value){let Ut=this.domService.getSelectedAnnotationsMap("comment")||{};Object.keys(Ut)?.length?this.domService.resetSelectedAnnotationsMap():this.disableAddCommentMode()}},Se=>{this.loggingService.catch("Error in CommentService onWindowKeyupEsc$ subscription: ",Se)}),this.domService.onDocumentClick$().subscribe(Se=>{if(Se?.target&&!ji(Se?.target)){let Ut=this.domService.getSelectedAnnotationsMap("comment")||{};if(Ut=I(I({},Ut),this.domService.getSelectedAnnotationsMap("multiThread")||{}),Object.keys(Ut)?.length&&(this.domService.resetSelectedAnnotationsMap(),this.persistentCommentMode$?.value)){this.addCommentMode$.value&&this.detectToAddAreaComment(),Se.preventDefault(),Se.stopPropagation();return}}if(Se&&this.addCommentMode$.value&&!fd(Se.target)){let Ut=!1;if(this.addCommentDragMode)Se.preventDefault(),Se.stopPropagation(),this.addCommentDragMode=!1;else if(!this.domService.getDraftCommentAnnotationDialogs()?.length){let Gt=this.domService.getBackgroundElement(Se.clientX,Se.clientY);(this.persistentCommentMode$?.value&&this.domService.getBackgroundVeltElement(Se.clientX,Se.clientY)||Se?.target&&ji(Se?.target))&&(Gt=null),Gt&&(this.isElementInsideAllowedElements(Gt)||this.getCommentToNearestAllowedElement()&&this.getNearestAllowedElement(Gt))&&(Ut=this.isElementInsideManualCommentContainer(Gt),Ut||(Se.preventDefault(),Se.stopPropagation(),this.addComment(Se)))}this.persistentCommentMode$?.value?this.detectToAddAreaComment():Ut||this.disableAddCommentMode()}},Se=>{this.loggingService.catch("Error in CommentService onDocumentClick$ subscription: ",Se)}),this.addCommentMode$.subscribe(Se=>{this.hightlightElement&&this.domService.removeHighlightFromElement(this.hightlightElement),Se?(this.domService.addClassToElement(document.body,"snippyly-add-comment-mode"),this.detectToAddAreaComment(),this.addIframeContainerStaticAttribute()):(this.removeIframeContainerStaticAttribute(),this.domService.removeClassFromElement(document.body,"snippyly-add-comment-mode"),this.domService.removeClassFromElement(document.body,"show-pin-cursor"),this.dragSubscriptions.forEach(Ut=>Ut.unsubscribe()))},Se=>{this.loggingService.catch("Error in CommentService addCommentMode$ subscription: ",Se)}),this.domService.onWindowKeyupBackspace$().subscribe(Se=>{this.getDeleteOnBackspace()&&this.deleteCommentPinAnnotations("keyupBackspace")},Se=>{this.loggingService.catch("Error in CommentService onWindowKeyupBackspace$ subscription: ",Se)}),this.domService.onWindowKeyupDelete$().subscribe(Se=>{this.deleteCommentPinAnnotations("keyupDelete")},Se=>{this.loggingService.catch("Error in CommentService onWindowKeyupDelete$ subscription: ",Se)}),this.domService.getDeleteCommmentAnnotations$().subscribe(Se=>{Se?.length&&(Se?.filter(Gt=>!["tag","recorder","rewriter","arrow","area","multiThread"].includes(Gt.type))).forEach(Gt=>ee(this,null,function*(){yield this.deleteCommentPinAnnotation(Gt)}))},Se=>{this.loggingService.catch("Error in CommentService onWindowKeyupDelete$ subscription: ",Se)}),this.getPopoverMode$().subscribe(Se=>{Se?document?.body?.setAttribute(U.ATTRIBUTES.VELT_POPOVER_MODE,"true"):document?.body?.removeAttribute(U.ATTRIBUTES.VELT_POPOVER_MODE)},Se=>{this.loggingService.catch("Error in CommentService getPopoverMode subscription: ",Se)}),this.customFilterService.customCategoryMap$.subscribe(Se=>{this.customCategoryMap=Se},Se=>{this.loggingService.catch("Error in CommentService customCategoryMap$ subscription: ",Se)}),this.hotkeyEnabled$.subscribe(Se=>{Se?this.subscribeHotkeyEvents():this.unsubscribeHotkeyEvents()},Se=>{this.loggingService.catch("Error in CommentService hotkeyEnabled$ subscription: ",Se)}),this.domService.getSelectedAnnotationsMap$().pipe(Vi()).subscribe(([Se,Ut])=>{try{let Gt=Object.values(Se||{}).filter(It=>!["tag","recorder","rewriter","arrow","area"].includes(It.type)),Dt=Object.values(Ut||{}).filter(It=>!["tag","recorder","rewriter","arrow","area"].includes(It.type));Gt?.forEach(It=>{Dt?.find(Nt=>Nt.annotationId===It.annotationId)||this.commentSelectionChange$.next({annotation:$n(It),selected:!1})}),Dt?.forEach(It=>{Gt?.find(Nt=>Nt.annotationId===It.annotationId)||this.commentSelectionChange$.next({annotation:$n(It),selected:!0})})}catch(Gt){this.loggingService.catch("Error in CommentService getSelectedAnnotationsMap$: ",Gt)}},Se=>{this.loggingService.catch("Error in CommentService getSelectedAnnotationsMap$ subscription: ",Se)})}clearCache(){try{this.loggingService.log("%c[WB] Calling FUNCTION: clearCache in CommentService","color: green;"),this.commentAnnotationById$.next(null),this.draftCommentAnnotationsByAnnotationId$.next(null),this.multiThreadCommentAnnotationById$.next({}),this.draftMultiThreadCommentAnnotationsByAnnotationId$.next({}),this.customAutocompleteSearch$.next(!1),this.hightlightElement=null,this.addCommentMode$.next(!1),this.unreadCommentsMap$.next(null),this.documentPaths=null}catch(e){this.loggingService.catch("Error in CommentService clearCache: ",e)}}setCommentActionsService(e){try{this.commentActionsService=e}catch(i){this.loggingService.catch("Error in CommentService setCommentActionsService: ",i)}}detectToAddAreaComment(){try{let e=this.areaService.getAreaEnabled(),i=this.getAreaCommentEnabled();if(e&&i){let r,a,s,c=null,p=null;this.dragSubscriptions.forEach(h=>h.unsubscribe()),this.dragSubscriptions.push(this.domService.onWindowMouseDown$().pipe(Ne(h=>!ji(h?.target)),Je(1)).subscribe(h=>{c=null,p=null,this.dragSubscriptions.push(this.domService.getClickAndDragPointsObservable().subscribe(_=>{if(c===null){let E=_?.startPoint?.event?.target,D=ji(E),B=fd(E),G=this.isElementInsideAllowedElements(E);c=!D&&!B&&G}if(c){this.addCommentDragMode=!0,r=_.startPoint,a=_.curPoint;let E=_?.curPoint?.event?.target,D=ji(E),B=fd(E),G=this.isElementInsideAllowedElements(E);p=!D&&!B&&G,p?s=this.domService.drawRectangle(r,a):s?.remove()}})),this.domService.onWindowPointerUp$().pipe(xs(1),Je(1)).subscribe(_=>{if(a={x:_.clientX,y:_.clientY},r&&a&&(s?.remove(),c&&p)){let E=[{x:r.x-window.scrollX,y:r.y-window.scrollY},{x:a.x,y:a.y}];this.addComment(_,void 0,E)}this.dragSubscriptions.forEach(E=>E.unsubscribe())})}))}}catch(e){this.loggingService.catch("Error in CommentService detectToAddAreaComment: ",e)}}resetCacheData(){try{this.loggingService.log("%c[WB] Calling CommentService FUNCTION: resetCacheData","color: green;"),this.commentAnnotationById$.next(null),this.draftCommentAnnotationsByAnnotationId$.next(null),this.multiThreadCommentAnnotationById$.next({}),this.draftMultiThreadCommentAnnotationsByAnnotationId$.next({})}catch(e){this.loggingService.catch("Error in CommentService resetCacheData: ",e)}}addAreaContainerTag(){try{if(!(document.querySelector(U.TAGS.VELT_AREAS)||document.querySelector(U.TAGS.SNIPPYLY_AREAS))){let i=document.createElement(U.TAGS.VELT_AREAS);document.body.appendChild(i)}}catch(e){this.loggingService.catch("Error in CommentService addAreaContainerTag: ",e)}}addIframeContainerStaticAttribute(){try{document.querySelectorAll(`[${U.ATTRIBUTES.VELT_IFRAME_CONTAINER}]`).forEach(i=>{window.getComputedStyle(i).position==="static"&&i.setAttribute(U.ATTRIBUTES.VELT_IFRAME_CONTAINER_STATIC,"true")})}catch(e){this.loggingService.catch("Error in CommentService addIframeContainerStaticAttribute: ",e)}}removeIframeContainerStaticAttribute(){try{document.querySelectorAll(`[${U.ATTRIBUTES.VELT_IFRAME_CONTAINER_STATIC}]`).forEach(i=>{i.removeAttribute(U.ATTRIBUTES.VELT_IFRAME_CONTAINER_STATIC)})}catch(e){this.loggingService.catch("Error in CommentService removeIframeContainerStaticAttribute: ",e)}}subscribeHotkeyEvents(){try{this.loggingService.log("%c[WB] Calling FUNCTION: subscribeHotkeyEvents","color: green;"),this.unsubscribeHotkeyEvents(),this.hotkeySubscriptions.push(this.hotkeyService.getKeyPressEvent("c").subscribe(e=>{e&&!this.addCommentMode$.value&&this.enableAddCommentMode()},e=>{this.loggingService.catch("Error in CommentService hotkeyService.getKeyPressEvent subscription: ",e)}))}catch(e){this.loggingService.catch("Error in CommentService subscribeHotkeyEvents: ",e)}}unsubscribeHotkeyEvents(){try{this.loggingService.log("%c[WB] Calling FUNCTION: unsubscribeHotkeyEvents","color: green;"),this.hotkeySubscriptions.forEach(e=>e?.unsubscribe())}catch(e){this.loggingService.catch("Error in CommentService unsubscribeHotkeyEvents: ",e)}}setCommentAddedEmitter(e){try{this.commentAddedEmitter=e}catch(i){this.loggingService.catch("Error in CommentService setCommentAddedEmitter: ",i)}}setContextProvider(e){try{this.commentContextProvider=e}catch(i){this.loggingService.catch("Error in CommentService setContextProvider: ",i)}}getDocumentPaths(){this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentPaths","color: green;"),this.docService.getDocumentPaths$()}getAnonymousAvatarImage(){return this.loggingService.log("%c[WB] Calling FUNCTION: getAnonymousAvatarImage","color: green;"),this.avatarService.generateUserImage()}setAllowedElementIds(e){try{this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{allowedElementIds:e}}),this.allowedElementIds$.next(e||[])}catch(i){this.loggingService.catch("Error in CommentService setAllowedElementIds: ",i)}}getAllowedElementIds(){return this.allowedElementIds$.asObservable()}setAllowedElementClassNames(e){try{this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{allowedElementClassNames:e}}),this.allowedElementClassNames$.next(e||[])}catch(i){this.loggingService.catch("Error in CommentService setAllowedElementClassNames: ",i)}}getAllowedElementClassNames(){return this.allowedElementClassNames$.asObservable()}setAllowedElementQuerySelectors(e){try{this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{allowedElementQuerySelectors:e}}),this.allowedElementQuerySelectors$.next(e||[])}catch(i){this.loggingService.catch("Error in CommentService setAllowedElementQuerySelectors: ",i)}}getAllowedElementQuerySelectors(){return this.allowedElementQuerySelectors$.asObservable()}getAnnotationsCount(e){try{return Wn(this.afAuth).pipe(Ne(i=>!!i),ge(i=>this.isFeatureAllowed({firebaseUser:i,annotations:[],filteredAnnotations:[]})),ge(i=>i.featureAllowed?this.iamService.isUserAllowed$().pipe(ce(r=>(i.featureAllowed=r,i))):re(i)),ge(i=>i.featureAllowed?re(i).pipe(ge(r=>this.docService.getDocumentPaths$().pipe(ce(a=>(this.documentPaths=a,r.documentPaths=a,r)))),ge(()=>e?.documentIds?.length?re(e?.documentIds.map(r=>({clientDocumentId:r,documentId:`${fn(r)}`}))):this.docService.getDocumentIds$().pipe(ce(r=>r?.length>0?r:[{documentId:this.documentPaths?.documentId??"",clientDocumentId:this.documentPaths?.clientDocumentId||""}]))),ge(r=>{let a=this.authService.getUser()?.userSnippylyId,s=this.documentPaths?.organizationId,c=r?.length>0?r.map(D=>D.documentId):[this.documentPaths?.documentId??""];if(c.some(D=>!D)||!this.documentPaths)return re();let p=this.docService.getFolderConfig(),h=re(),_=re(),E={useCollectionGroup:!0,isCollection:!0,useQuery:!0};if(p?.veltFolderId&&p?.allDocuments)h=this.commonDbService.dbListener({feature:"allComments",properties:T(I({},E),{firestoreQuery:[Fi(mt("metadata.apiKey","==",this.configService?.getApiKey()),mt("metadata.organizationId","==",s),mt("metadata.veltFolderId","==",p?.veltFolderId),...e?.statusIds?[mt("status.id","in",e.statusIds)]:[]),Ga("lastUpdated","desc"),Ga("createdAt","desc")]})}).pipe(ce(D=>D?.data)),_=this.commonDbService.dbListener({feature:"allCommentViews",properties:T(I({},E),{firestoreQuery:[Fi(mt("metadata.apiKey","==",this.configService?.getApiKey()),mt("metadata.organizationId","==",s),mt("metadata.veltFolderId","==",p?.veltFolderId))]})}).pipe(ce(D=>D?.data));else{let D=[];for(let B=0;B<(c?.length??0);B+=U.LISTENER_BATCH_SIZE)D.push(c?.slice(B,B+U.LISTENER_BATCH_SIZE)??[]);h=Dn(D.map(B=>this.commonDbService.dbListener({feature:"allComments",properties:T(I({},E),{firestoreQuery:[Fi(mt("metadata.apiKey","==",this.configService?.getApiKey()),mt("metadata.organizationId","==",s),mt("metadata.documentId","in",B),...e?.statusIds?[mt("status.id","in",e.statusIds)]:[],...p?.veltFolderId?[mt("metadata.veltFolderId","==",p?.veltFolderId)]:[]),Ga("lastUpdated","desc"),Ga("createdAt","desc")]})}).pipe($r()))).pipe(ce(B=>ca(B)?.data)),_=Dn(D.map(B=>this.commonDbService.dbListener({feature:"allCommentViews",properties:T(I({},E),{firestoreQuery:[Fi(mt("metadata.apiKey","==",this.configService?.getApiKey()),mt("metadata.organizationId","==",s),mt("metadata.documentId","in",B),...p?.veltFolderId?[mt("metadata.veltFolderId","==",p?.veltFolderId)]:[])]})}).pipe($r()))).pipe(ce(B=>ca(B)?.data))}return Dn([h,_]).pipe(ge(([D,B])=>!D||!B?re(null):re([D,B]).pipe(ce(([G,X])=>{let he=Object.values(G||{});e?.locationIds?.length&&(he=he.filter(ke=>e.locationIds?.includes(ke.location?.id??"")));let Ie={};he.forEach(ke=>{Ie[ke.annotationId]=ke});let Me={};Object.entries(X||{}).forEach(([ke,we])=>{Ie[ke]&&(we?.views?.[a]||(Me[ke]=we))});let Le=he.reduce((ke,we)=>{let Ee=we?.metadata?.clientDocumentId;return Ee&&(ke[Ee]||(ke[Ee]=[]),ke[Ee].push(we)),ke},{}),We=Object.values(Me).reduce((ke,we)=>{let Ee=we?.metadata?.clientDocumentId;return Ee&&(ke[Ee]||(ke[Ee]=[]),ke[Ee].push(we)),ke},{});return r.reduce((ke,{clientDocumentId:we})=>{ke?.data||(ke.data={});let Ee=Le[we]?.length??0,Pe=We[we]?.length??0;return ke.data[we]={total:Ee,unread:Pe},ke},{data:{}})}),Ln(G=>(this.loggingService.catch("Error in CommentService getAnnotationsCount: ",G),re(null))))))})):re(null)),ce(i=>i||{data:null}),Kt(_o))}catch(i){return this.loggingService.catch("Error in CommentService getAnnotationsCount: ",i),re({data:null})}}getAllCommentAnnotations({customClientDocumentId:e,params:i,excludeDomChanges:r,detectGhostComments:a,skipPositionCalculation:s,query:c,fromCommentSidebar:p,analytics:h}){this.loggingService.log("%c[WB] Calling FUNCTION: getAllCommentAnnotations","color: green;");let _,E,D;h?.enabled&&this.analyticsService.trackEvent(h?.eventName||Z.Events.Comments.GET_ALL_COMMENT_ANNOTATIONS_TRIGGERED_INTERNAL,h?.properties);try{if(e&&(D=`${fn(e)}`),i&&typeof i=="object"){let B=Xo(i);E=B?.id,_=fn(JSON.stringify(B))}}catch(B){this.loggingService.catch("Error in CommentService getAllCommentAnnotations: ",B)}return Wn(this.afAuth).pipe(Ne(B=>!!B),ge(B=>this.isFeatureAllowed({firebaseUser:B,annotations:[],filteredAnnotations:[]})),ge(B=>B.featureAllowed?this.iamService.isUserAllowed$().pipe(ce(G=>(B.featureAllowed=G,B))):re(B)),ge(B=>B.featureAllowed?re(B).pipe(ge(G=>this.docService.getDocumentPaths$().pipe(ce(X=>(this.documentPaths=X,G.documentPaths=X,G)))),ge(G=>c?.documentIds?.length||D?this.getDataFromDocumentIds({documentIds:D?[D]:c?.documentIds?.map(X=>`${fn(X)}`),organizationId:this.documentPaths?.organizationId,query:c}).pipe(ce(X=>({res:G,data:X}))):this.docService.getDocumentIds$().pipe(ge(X=>{let he=X?.length>0?X.map(Ie=>Ie.documentId):[this.documentPaths?.documentId??""];return this.getDataFromDocumentIds({documentIds:he.length>0?he:[D??""],organizationId:this.documentPaths?.organizationId,query:c}).pipe(ce(Ie=>({res:G,data:Ie})))}))),ge(G=>G?.data?(G.res.annotations=G.data||[],re(G.res).pipe(ge(X=>this.docService.getLocation$().pipe(ce(he=>(X.location=he,X)))),ge(X=>this.docService.getLocations$().pipe(ce(he=>(X.customLocations=he,X)))),ge(X=>this.docService.getExcludedLocationIds$().pipe(ce(he=>(X.excludedLocationIds=he,X)))),ce(X=>{if(X.filteredAnnotations=[],c)return X.filteredAnnotations=X.annotations?.slice(),X;if(D&&!_||p)return X.filteredAnnotations=X.annotations?.slice(),X?.excludedLocationIds?.length&&(X.filteredAnnotations=X.filteredAnnotations?.filter(he=>he?.location?.id?!X.excludedLocationIds.includes(he.location.id):!0)),X;{let he=[],Ie=[];return _?(he.push(_),E&&Ie.push(E)):(he.push(X?.location?.locationId),he.push(...Object.values(X?.customLocations||[]).map(Me=>Me.locationId)),X?.location?.location?.id&&Ie.push(X?.location?.location?.id),Ie.push(...Object.values(X?.customLocations||{}).map(Me=>Me.location?.id).filter(Me=>!!Me))),X.filteredAnnotations=this.filterAnnotationsByLocationIds(X?.annotations,he,Ie),X?.excludedLocationIds?.length&&(X.filteredAnnotations=X.filteredAnnotations?.filter(Me=>Me?.location?.id?!X.excludedLocationIds.includes(Me.location.id):!0)),X}}),ge(X=>this.iamService.isUserAdmin$().pipe(ce(he=>(he||(X.filteredAnnotations=X.filteredAnnotations?.filter(Ie=>Ie?.iam?.accessMode!==Ki.PRIVATE)),X)))),ge(X=>this.draftCommentAnnotationsByAnnotationId$.pipe(ce(he=>(X.filteredAnnotations=X.filteredAnnotations?.filter(Ie=>!Ie.isDraft),he&&X.filteredAnnotations.push(...Object.values(he)),X)))),ge(X=>r?re(X):X?.annotations?.length&&(!this.getPopoverMode()||this.getPopoverTriangleComponent())?this.domService.onWindowResize$().pipe(ce(()=>X)):re(X)),ge(X=>r?re(X):this.addCommentMode$.pipe(ge(he=>he&&!this.getChangeDetectionInCommentMode()?re(X):X?.annotations?.length&&(!this.getPopoverMode()||this.getPopoverTriangleComponent())?this.domService.onDomChange$("CommentService getAllCommentAnnotations").pipe(ce(()=>X)):re(X)))),ce(X=>(s||(!this.getPopoverMode()||this.getPopoverTriangleComponent())&&(X.filteredAnnotations=X.filteredAnnotations?.map(he=>{let Ie=Object.assign({},he);return this.calculateCommentAnnotationPosition(Ie,a),Ie})),X)),ge(X=>X?.annotations?.length?this.viewsService.getCommentFeatureViews$().pipe(ce(he=>(this.updateUnreadAnnotationsMap(X?.annotations,he),X))):re(X)),ge(X=>X?.filteredAnnotations?re(X?.filteredAnnotations||[]):re([])))):re(null))):re(null)),Kt((B,G)=>_o(B,G)))}getAllMultiThreadCommentAnnotations(e,i,r,a,s){this.loggingService.log("%c[WB] Calling FUNCTION: getAllMultiThreadCommentAnnotations","color: green;");let c,p;try{if(e&&(p=fn(e)),i&&typeof i=="object"){let h=Xo(i);c=fn(JSON.stringify(h))}}catch(h){this.loggingService.catch("Error in CommentService getAllMultiThreadCommentAnnotations: ",h)}return Wn(this.afAuth).pipe(Ne(h=>!!h),ge(h=>this.isFeatureAllowed({firebaseUser:h,annotations:[],filteredAnnotations:[]})),ge(h=>h.featureAllowed?this.iamService.isUserAllowed$().pipe(ce(_=>(h.featureAllowed=_,h))):re(h)),ge(h=>h.featureAllowed?re(h).pipe(ge(_=>this.docService.getDocumentPaths$().pipe(ce(E=>(this.documentPaths=E,_.documentPaths=E,_)))),ge(_=>p?this.getMultiThreadDataFromDocumentIds([p]).pipe(ce(E=>({res:_,data:E}))):this.docService.getDocumentIds$().pipe(ge(E=>{let D=E?.length>0?E.map(B=>B.documentId):[this.documentPaths?.documentId??""];return this.getMultiThreadDataFromDocumentIds(D.length>0?D:[`${p}`]).pipe(ce(B=>({res:_,data:B})))}))),ge(({res:_,data:E})=>E?(_.annotations=E||[],re(_).pipe(ge(D=>this.docService.getLocation$().pipe(ce(B=>(D.location=B,D)))),ge(D=>this.docService.getLocations$().pipe(ce(B=>(D.customLocations=B,D)))),ge(D=>this.docService.getExcludedLocationIds$().pipe(ce(B=>(D.excludedLocationIds=B,D)))),ce(D=>{if(D.filteredAnnotations=[],p&&!c)return D.filteredAnnotations=D.annotations?.slice(),D?.excludedLocationIds?.length&&(D.filteredAnnotations=D.filteredAnnotations?.filter(B=>B?.location?.id?!D.excludedLocationIds.includes(B.location.id):!0)),D;{let B=[],G=[];return c?B.push(c):(B.push(D?.location?.locationId),B.push(...Object.values(D?.customLocations||[]).map(X=>X.locationId)),D?.location?.location?.id&&G.push(D?.location?.location?.id),G.push(...Object.values(D?.customLocations||{}).map(X=>X.location?.id).filter(X=>!!X))),D.filteredAnnotations=this.filterAnnotationsByLocationIds(D?.annotations,B,G),D?.excludedLocationIds?.length&&(D.filteredAnnotations=D.filteredAnnotations?.filter(X=>X?.location?.id?!D.excludedLocationIds.includes(X.location.id):!0)),D}}),ge(D=>this.draftMultiThreadCommentAnnotationsByAnnotationId$.pipe(ce(B=>(D.filteredAnnotations=D.filteredAnnotations?.filter(G=>!G.isDraft),B&&D.filteredAnnotations.push(...Object.values(B)),D)))),ge(D=>r?re(D):D?.annotations?.length&&(!this.getPopoverMode()||this.getPopoverTriangleComponent())?this.domService.onWindowResize$().pipe(ce(()=>D)):re(D)),ge(D=>r?re(D):this.addCommentMode$.pipe(ge(B=>B&&!this.getChangeDetectionInCommentMode()?re(D):D?.annotations?.length&&(!this.getPopoverMode()||this.getPopoverTriangleComponent())?this.domService.onDomChange$("CommentService getAllMultiThreadCommentAnnotations").pipe(ce(()=>D)):re(D)))),ce(D=>(s||(!this.getPopoverMode()||this.getPopoverTriangleComponent())&&(D.filteredAnnotations=D.filteredAnnotations?.map(B=>{let G=Object.assign({},B);return this.calculateCommentAnnotationPosition(G,a),G})),D)),ge(D=>D?.filteredAnnotations?re(D?.filteredAnnotations||[]):re([])))):re(null))):re(null)),Kt(_o))}isFeatureAllowed(e){return this.configService.getConfig$().pipe(Ne(i=>!!i),ce(i=>T(I({},e),{config:i})),ge(i=>this.authService.getUser$().pipe(ce(r=>(this.user=r,T(I({},i),{user:r}))))),ge(i=>Xi(i.config,i.user,Re.COMMENT)?re(T(I({},i),{featureAllowed:!0})):(this.loggingService.warn("Comment feature is not allowed."),re(T(I({},i),{featureAllowed:!1})))))}getDataFromDocuments(e){let{documentIds:i,organizationId:r,query:a}=e;if(!this.configService?.getApiKey())return re([]);if(i?.some(D=>!D)||!this.documentPaths)return re([]);let s,c,p,h=[];if(a)a?.folderId&&(s=hl(a?.folderId)),c=a?.allDocuments,a?.locationId&&(h=[...h,a?.locationId]),a?.locationIds?.length&&(h=[...h,...a?.locationIds]),p=a?.statusIds;else{let D=this.docService.getFolderConfig();s=D?.veltFolderId,c=D?.allDocuments,D?.locationId&&(h=[...h,D?.locationId])}let _=re([]),E={useCollectionGroup:!0,isCollection:!0,useQuery:!0};if(this.commonDbService.shouldUseFirestore()||(E.documentId=i?.length?i[0]:void 0,E.organizationId=this.documentPaths?.organizationId),c)_=this.commonDbService.dbListener({feature:"allComments",properties:T(I({},E),{firestoreQuery:[Fi(mt("metadata.apiKey","==",this.configService?.getApiKey()),mt("metadata.organizationId","==",r??this.documentPaths?.organizationId),...s?[mt("metadata.veltFolderId","==",s)]:[],...p?[mt("status.id","in",p)]:[],...h?.length?[mt("location.id","in",h)]:[]),Ga("lastUpdated","desc"),Ga("createdAt","desc")]})});else{let D=[];for(let B=0;B<(i?.length??0);B+=U.LISTENER_BATCH_SIZE)D.push(i?.slice(B,B+U.LISTENER_BATCH_SIZE)??[]);_=Dn(D.map(B=>this.commonDbService.dbListener({feature:"allComments",properties:T(I({},E),{firestoreQuery:[Fi(mt("metadata.apiKey","==",this.configService?.getApiKey()),mt("metadata.organizationId","==",r??this.documentPaths?.organizationId),mt("metadata.documentId","in",B),...p?[mt("status.id","in",p)]:[],...s?[mt("metadata.veltFolderId","==",s)]:[],...h?.length?[mt("location.id","in",h)]:[]),Ga("lastUpdated","desc"),Ga("createdAt","desc")]})}).pipe($r()))).pipe(ce(B=>ca(JSON.parse(JSON.stringify(B)))))}return _.pipe(ge(D=>D?.data?re(D).pipe(ge(B=>this.commonDbUtilsService.mergeLocationMetadataWithData$({data:B,feature:"allComments"}).pipe(ce(G=>({data:Object.values(G?.data||{}).filter(X=>typeof X=="object"),operation:G?.operation})))),ce(({data:B,operation:G})=>{let X=B.reduce((he,Ie)=>{let Me=Ie.metadata?.documentId;return Me&&(he[Me]||(he[Me]=[]),he[Me].push(Ie)),he},{});return{data:B,documentMap:X,operation:G}}),ce(({data:B,documentMap:G,operation:X})=>p?{data:B,documentMap:G,operation:X}:(B?.length&&(B?.forEach(he=>{this.sanitizeCommentAnnotation(he)}),this.setAnnotationIndex(B),this.updateAnnotationsForSelectAllContentMode(B),B.forEach(he=>{this.customFilterService.convertLegacyAnnotationStatus(he),this.customFilterService.convertLegacyPriority(he),this.customFilterService.convertLegacyCategory(he)})),{data:B,documentMap:G,operation:X})),Ln(B=>(this.loggingService.catch("Error in CommentService getDataFromDocuments: ",B),re([]))),In(({documentMap:B})=>{p||Object.entries(B??{}).forEach(([G,X])=>{this.setOriginalCommentAnnotationsByAnnotationId(JSON.parse(JSON.stringify(X)))})}),ce(({data:B,documentMap:G,operation:X})=>({data:this.filterUserDraftComments(B),documentMap:G,operation:X})),ce(({data:B,documentMap:G,operation:X})=>({data:this.removeDraftFlags(B),documentMap:G,operation:X})),ge(({data:B,documentMap:G,operation:X})=>p?re({data:B,documentMap:G,operation:X}):this.mergeDraftAnnotations(B).pipe(ce(he=>({data:he,documentMap:G,operation:X})))),ce(({data:B,documentMap:G,operation:X})=>{if(!p)if(X?.type==="removed"){if(X?.ids?.length){let he=this.commentAnnotationById$.value??{};X?.ids?.forEach(Ie=>{delete he?.[Ie]}),this.commentAnnotationById$.next(he)}}else Object.entries(G??{}).length?Object.entries(G??{}).forEach(([Ie,Me])=>{this.setCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:this.documentPaths?.organizationId,documentId:Ie,annotations:Me})}):this.commentAnnotationById$.value||this.commentAnnotationById$.next({});return B})):re(null)))}fetchCommentAnnotations(e){return ee(this,null,function*(){try{let i=this.authService.getUser();if(!i)return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),{data:[],hasMore:!1};let r=this.configService?.getApiKey(),a=e?.organizationId??i?.clientOrganizationId,s=hd(a??""),c=[];e?.allDocuments||(c=e?.documentIds?.map(G=>ud(G??""))??this.docService.getDocumentIds()?.map(G=>G.documentId));let p=[];if(p.push(mt("metadata.organizationId","==",s)),p.push(mt("metadata.apiKey","==",r)),e?.folderId){let G=hl(e?.folderId);p.push(mt("metadata.veltFolderId","==",G))}if(e?.locationId&&p.push(mt("location.id","==",e?.locationId)),c?.length&&p.push(mt("metadata.documentId","in",c)),e?.resolvedBy){if(e?.order==="asc")throw new Error("Order by resolvedBy is not supported in ascending order.");p.push(mt("resolvedByUserId","==",e?.resolvedBy))}if(e?.mentionedUserIds?.length){if(e?.order==="asc")throw new Error("Order by mentionedUserIds is not supported in ascending order.");p.push(mt("mentionedUserIds","array-contains-any",e?.mentionedUserIds))}if(e?.userIds?.length){if(e?.order==="asc")throw new Error("Order by userIds is not supported in ascending order.");p.push(mt("from.userId","in",e?.userIds))}if(e?.statusIds?.length){if(e?.order==="asc")throw new Error("Order by status id is not supported in ascending order.");p.push(mt("status.id","in",e?.statusIds))}let h=new Date().getTime();if(e?.createdAfter&&p.push(mt("createdAt",">=",e?.createdAfter)),e?.createdBefore&&p.push(mt("createdAt","<=",e?.createdBefore??h)),e?.updatedAfter&&p.push(mt("lastUpdated",">=",e?.updatedAfter??h)),e?.updatedBefore&&p.push(mt("lastUpdated","<=",e?.updatedBefore??h)),p.push(Ga("lastUpdated",e?.order??"desc"),Ga("createdAt",e?.order??"desc")),e?.pageToken){let G=yield fV(e?.pageToken??"","veltencrypttoken","veltencrypttoken");p.push($ae(parseInt(G,10),"lastUpdated"))}let _=e?.pageSize??100;p.push(Rv(_+1));let E=yield this.commonDbService.queryData({feature:"allComments",properties:{useCollectionGroup:!0,isCollection:!0,useQuery:!0,firestoreQuery:p,apiKey:r??"",organizationId:s}}),D=E.length>_;E=E.slice(0,_);let B=E?.reduce((G,X)=>(G[X?.annotationId]=X,G),{});return B=yield this.commonDbUtilsService.formatResponse({feature:"allComments",data:B,shouldAwait:!0}),B=this.commonDbUtilsService.mergeUsersWithData({feature:"allComments",data:B}),{data:Object.values(B??{}),hasMore:D}}catch(i){throw this.loggingService.catch("Error in CommentService fetchCommentAnnotations:",i),i}})}filterUserDraftComments(e){let i=this.authService.getUser();return e.filter(r=>(r.comments=r?.comments?.filter(a=>a?.from?.userId===i?.userId||!a?.isDraft),!!r?.comments?.length))}removeDraftFlags(e){return e.forEach(i=>delete i.isDraft),e}mergeDraftAnnotations(e){return this.draftCommentAnnotationsByAnnotationId$.pipe(ce(i=>{let r=i||{};return e?.filter(a=>{r?.[a?.annotationId]&&delete r[a?.annotationId]}),r}),ce(i=>{if(i){let r=e.slice();return r.push(...Object.values(i)),r}return e}))}getDataFromDocumentIds({documentIds:e,organizationId:i,query:r}){return this.getDataFromDocuments({documentIds:e,organizationId:i,query:r})}getMultiThreadDataFromDocumentIds(e){return this.getMultiThreadDataFromDocuments({documentIds:e})}getMultiThreadDataFromDocuments(e){if(this.configService?.getApiKey()){let{documentIds:i}=e;if(i?.some(c=>!c)||!this.documentPaths)return re([]);let r=this.docService.getFolderConfig(),a=re([]),s={useCollectionGroup:!0,isCollection:!0,useQuery:!0};if(this.commonDbService.shouldUseFirestore()||(s.documentId=i?.length?i[0]:void 0,s.organizationId=this.documentPaths?.organizationId),r?.veltFolderId&&r?.allDocuments)a=this.commonDbService.dbListener({feature:"allMultiThreads",properties:T(I({},s),{firestoreQuery:[Fi(mt("metadata.apiKey","==",this.configService?.getApiKey()),mt("metadata.organizationId","==",this.documentPaths?.organizationId),mt("metadata.veltFolderId","==",r?.veltFolderId))]})});else{let c=[];for(let p=0;p<(i?.length??0);p+=U.LISTENER_BATCH_SIZE)c.push(i?.slice(p,p+U.LISTENER_BATCH_SIZE)??[]);a=Dn(c.map(p=>this.commonDbService.dbListener({feature:"allMultiThreads",properties:T(I({},s),{firestoreQuery:[Fi(mt("metadata.apiKey","==",this.configService?.getApiKey()),mt("metadata.organizationId","==",this.documentPaths?.organizationId),mt("metadata.documentId","in",p),...r?.veltFolderId?[mt("metadata.veltFolderId","==",r?.veltFolderId)]:[])]})}).pipe($r()))).pipe(ce(p=>ca(p)))}return a.pipe(ge(c=>c?.data?re(c).pipe(ce(p=>({data:p?.data,operation:p?.operation})),ce(({data:p,operation:h})=>{let _=[];return p&&(_=Object.values(p??{}).filter(E=>typeof E=="object")),{data:_,operation:h}}),Ln(p=>(this.loggingService.catch("Error in CommentService getMultiThreadDataFromDocumentId: ",p),re({data:[],operation:null}))),ce(({data:p,operation:h})=>{p.forEach(E=>{delete E.isDraft});let _=p.reduce((E,D)=>{let B=D.metadata?.documentId;return B&&(E[B]||(E[B]=[]),E[B].push(D)),E},{});return{data:p,documentMap:_,operation:h}}),ge(({data:p,documentMap:h,operation:_})=>{let E=[];return this.commentAnnotationById$.pipe(ge(()=>this.domService.getSelectedAnnotationsMap$().pipe(ce(D=>({selectedAnnotationsMap:D})))),ce(({selectedAnnotationsMap:D})=>{let B={};return Object.keys(h??{}).forEach(G=>{let X=this.getCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:this.documentPaths?.organizationId,documentId:G});X&&X?.forEach(he=>{B[he?.annotationId]=he})}),E=p.filter(G=>{let X=!1;if(G?.commentAnnotations){for(let he in G?.commentAnnotations)if(B?.[he]&&B?.[he]?.status?.id!==this.customFilterService.resolvedStatus.id){X=!0;break}}return X}),E.forEach(G=>{Object.keys(G?.commentAnnotations||{}).forEach(X=>{G.commentAnnotationsMap||(G.commentAnnotationsMap={}),G.commentAnnotationsMap[X]=B?.[X]})}),{data:E,operation:_}}))}),ge(({data:p,operation:h})=>this.draftMultiThreadCommentAnnotationsByAnnotationId$.pipe(ce(_=>{let E=_||{};return p?.filter(D=>{E?.[D?.annotationId]&&delete E[D?.annotationId]}),E}),ce(_=>{if(_){let E=p.slice();return E.push(...Object.values(_)),{data:E,operation:h}}return{data:p,operation:h}}))),ce(({data:p,operation:h})=>{let _=p.reduce((E,D)=>{let B=D.metadata?.documentId;return B&&(E[B]||(E[B]=[]),E[B].push(D)),E},{});if(h?.type==="removed"){if(h?.ids?.length){let E=this.multiThreadCommentAnnotationById$.value;h?.ids?.forEach(D=>{delete E?.[D]}),this.multiThreadCommentAnnotationById$.next(E)}}else Object.keys(_??{}).forEach(E=>{this.setMultiThreadCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:this.documentPaths?.organizationId,documentId:E,annotations:_[E]})});return p})):re(null)))}else return re([])}updateUnreadAnnotationsMap(e,i){try{let r=new Date(U.UNREAD_COMMENTS_CHECK_FROM_DATE)?.getTime(),a=e.filter(s=>s?.lastUpdated>r);if(i){let s={},c=!1;a.forEach(p=>{let h=0,_=i?.[p?.annotationId];if(_){let E=_?.comments;E&&p?.comments?.forEach(D=>{!E?.[D?.commentId]?.views?.[this.user?.userSnippylyId]&&this.user?.userSnippylyId!==D?.from?.userSnippylyId&&h++})}h?h!==s?.[p?.annotationId]&&(s[p?.annotationId]=h,c=!0):s?.[p?.annotationId]&&(delete s[p?.annotationId],c=!0)}),this.unreadCommentsMap$.next(s)}}catch(r){this.loggingService.catch("Error in CommentService updateUnreadAnnotationsMap:",r)}}updateAnnotationsForSelectAllContentMode(e){try{e.forEach(i=>{if(i?.selectAllContent&&i?.targetElementId){let r=cr(i.targetElementId,["id","data-id"]);if(r){let a=r.textContent;a&&(i.targetTextRange={commonAncestorContainer:this.domService.getXPath(r),text:a,occurrence:1},delete i?.targetElement)}}})}catch(i){this.loggingService.catch("Error in CommentService updateAnnotationsForSelectAllContentMode:",i)}}setCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:e,documentId:i,annotations:r,queryHash:a}){try{if(i){e||(e=U.NO_ORGANIZATION_ID),a||(a=U.DEFAULT_QUERY_HASH);let s={};r?.forEach(p=>{p?.annotationId&&(s[p?.annotationId]=p)});let c=I(I({},this.commentAnnotationById$.value??{}),s);this.commentAnnotationById$.next(c)}}catch(s){this.loggingService.catch("Error in CommentService setCommentAnnotationsByOrganizationIdAndDocumentId:",s)}}getCommentAnnotationsByOrganizationIdAndDocumentId$({organizationId:e,documentId:i}){try{return this.commentAnnotationById$.pipe(ce(()=>this.getCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:e,documentId:i})))}catch(r){return this.loggingService.catch("Error in CommentService getCommentAnnotationsByOrganizationIdAndDocumentId$:",r),re([])}}getCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:e,documentId:i}){try{let r=null;this.commentAnnotationById$.value&&(r={},Object.values(this.commentAnnotationById$.value).forEach(s=>{s?.metadata?.documentId==i&&s?.metadata?.organizationId==e&&(r[s?.annotationId]=s)}));let a=this.draftCommentAnnotationsByAnnotationId$.value;return a&&(r===null&&(r={}),Object.values(a).forEach(s=>{s?.metadata?.documentId===i&&s?.metadata?.organizationId===e&&!r[s?.annotationId]&&(r[s?.annotationId]=s)})),r?Object.values(r):null}catch(r){return this.loggingService.catch("Error in CommentService getCommentAnnotationsByOrganizationIdAndDocumentId:",r),[]}}getCommentAnnotationsOnCurrentOrganizationAndDocument$(){return this.docService.getDocumentPaths$().pipe(ge(e=>e?.documentId?this.getCommentAnnotationsByOrganizationIdAndDocumentId$({organizationId:e.organizationId,documentId:e.documentId}):re([])))}getCommentAnnotationsOnCurrentOrganizationAndDocument(){try{let e=this.docService.getDocumentPaths();return e?.documentId?this.getCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:e?.organizationId,documentId:e?.documentId}):[]}catch(e){return this.loggingService.catch("Error in CommentService getCommentAnnotationsOnCurrentOrganizationAndDocument:",e),[]}}setOriginalCommentAnnotationsByAnnotationId(e){try{let i={};e?.forEach(r=>{r?.annotationId&&(i[r?.annotationId]=r)}),this.originalCommentAnnotationsByDocumentId$.next(I(I({},this.originalCommentAnnotationsByDocumentId$.value),i))}catch(i){this.loggingService.catch("Error in CommentService setOriginalCommentAnnotationsByAnnotationId:",i)}}setMultiThreadCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:e,documentId:i,annotations:r,queryHash:a}){try{if(i){e||(e=U.NO_ORGANIZATION_ID),a||(a=U.DEFAULT_QUERY_HASH);let s={};r.forEach(p=>{p?.annotationId&&(s[p?.annotationId]=p)});let c=I(I({},this.multiThreadCommentAnnotationById$.value),s);this.multiThreadCommentAnnotationById$.next(c)}}catch(s){this.loggingService.catch("Error in CommentService setMultiThreadCommentAnnotationsByOrganizationIdAndDocumentId:",s)}}getMultiThreadCommentAnnotationsByOrganizationIdAndDocumentId$({organizationId:e,documentId:i}){return this.multiThreadCommentAnnotationById$.pipe(ce(()=>this.getMultiThreadCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:e,documentId:i})))}getMultiThreadCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:e,documentId:i}){try{let r={};Object.values(this.multiThreadCommentAnnotationById$.value??{}).forEach(s=>{s?.metadata?.documentId==i&&s?.metadata?.organizationId==e&&(r[s?.annotationId]=s)});let a=this.draftMultiThreadCommentAnnotationsByAnnotationId$.value;return a&&Object.values(a??{}).forEach(s=>{s?.metadata?.documentId===i&&s?.metadata?.organizationId===e&&!r[s?.annotationId]&&(r[s?.annotationId]=s)}),Object.values(r)}catch(r){return this.loggingService.catch("Error in CommentService getMultiThreadCommentAnnotationsByOrganizationIdAndDocumentId:",r),[]}}getMultiThreadCommentAnnotationsOnCurrentOrganizationAndDocument$(){return this.docService.getDocumentPaths$().pipe(ge(e=>e?.documentId?this.getMultiThreadCommentAnnotationsByOrganizationIdAndDocumentId$({organizationId:e.organizationId,documentId:e.documentId}):re([])))}getMultiThreadCommentAnnotationsOnCurrentOrganizationAndDocument(){try{let e=this.docService.getDocumentPaths();return this.getMultiThreadCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:e?.organizationId,documentId:e?.documentId})}catch(e){return this.loggingService.catch("Error in CommentService getMultiThreadCommentAnnotationsOnCurrentOrganizationAndDocument:",e),[]}}getLocations$(){return this.docService.getLocation$().pipe(ge(e=>this.docService.getLocations$().pipe(ce(i=>({location:e,locations:i})))),ce(e=>{let i=[];return i.push(e?.location?.locationId),i.push(...Object.values(e.locations||[]).map(r=>r.locationId)),i||[]}))}filterAnnotationsByLocationIds(e,i,r){try{return e.filter(a=>i.includes(a.locationId)||r?.includes(a?.location?.id)||i?.find(s=>s==a?.location?.id)||r?.find(s=>s==a?.locationId+""))}catch(a){return this.loggingService.catch("Error in CommentService filterAnnotationsByLocations:",a),[]}}setAnnotationIndex(e){try{e.forEach((i,r)=>{i?.annotationId&&(i.annotationIndex=r+1)})}catch(i){this.loggingService.catch("Error in CommentService setAnnotationIndex:",i)}}calculateCommentAnnotationPosition(e,i){try{if(e.multiThreadAnnotationId)return;if(e.targetElementId){let r=cr(e.targetElementId,["id","data-id"]);if(r&&this.domService.isElementVisible(r)){let a=r.getAttribute(U.ATTRIBUTES.VELT_COMMENT_TYPE),s=!0;if(a)switch(a){case"popover":s=!0;break;default:s=!1;break}else{let c=document.querySelector(`${U.TAGS.VELT_INLINE_COMMENTS_SECTION}[${U.ATTRIBUTES.TARGET_INLINE_COMMENT_ELEMENT_ID}="${e.targetElementId}"], ${U.TAGS.VELT_INLINE_COMMENTS_SECTION}[${U.ATTRIBUTES.TARGET_COMMENT_ELEMENT_ID}="${e.targetElementId}"], ${U.TAGS.VELT_INLINE_COMMENTS_SECTION}[${U.ATTRIBUTES.TARGET_ELEMENT_ID}="${e.targetElementId}"]`);c&&r?.contains(c)&&(s=!1)}s?e.targetElement={xpath:this.domService.getXPath(r),fXpath:this.domService.getXPath(r,!0),cfXpath:this.domService.getXPath(r,!0,!0),topPercentage:e.targetElement?.topPercentage||50,leftPercentage:e.targetElement?.leftPercentage||90}:e.targetElement=null}else e.targetElement=null}if(e.targetElement){e.position=null,e.ghostComment=null;let r=e.targetElement?.xpath;if(r){let a=this.domService.getElementFromXPath(r);this.domService.isXpathWithId(r)||((!a||!this.domService.isElementVisible(a))&&e.targetElement?.cfXpath&&(r=e.targetElement?.cfXpath,a=this.domService.getElementFromXPath(r)),this.getDetectionStrategy()===jO.DYNAMIC_ID&&(!a||!this.domService.isElementVisible(a))&&(r=e.targetElement?.fXpath,r&&(a=this.domService.getElementFromXPath(r)))),(!a||!this.domService.isElementVisible(a))&&i&&(e.ghostComment={},this.setGhostCommentMessage(e),e.ghostComment.targetElement=this.getGhostCommentTargetElement(e),e?.ghostComment?.targetElement?.xpath&&(a=this.domService.getElementFromXPath(e?.ghostComment?.targetElement?.xpath)));let c=!1;if(e?.locationId){let p=this.docService.getLocation();if(!Ou({location:p?.location,locationId:p?.locationId},{location:e?.location,locationId:e?.locationId})){let h=this.docService.getAdditionLocationFromElement(a),_=h?this.docService.genarateLocationId(h):void 0;e?.location?.id&&e?.location?.id===h?.id||_&&_===e?.locationId?c=!1:c=!0}}if(c&&(e.ghostComment=null),!c&&a&&xo(a)&&!a?.closest(".cdk-overlay-container")&&a?.getBoundingClientRect()){let h=this.popoverMode$?.value?0:e.targetElement?.topPercentage,_=this.popoverMode$?.value?100:e.targetElement?.leftPercentage,{height:E,width:D}=Ep(a);e.position={top:E*(h||0)/100,left:D*(_||0)/100};let B=window.getComputedStyle(a).transform;if(B&&B!=="none")try{let G=new DOMMatrixReadOnly(B),X=Math.sqrt(G.a*G.a+G.b*G.b)||1,he=Math.sqrt(G.c*G.c+G.d*G.d)||1;(Math.abs(X-1)>.01||Math.abs(he-1)>.01)&&(e.position.parentScaleX=X,e.position.parentScaleY=he)}catch{}if(this.transformContext$.value){let{containerSelector:G,transforms:X}=this.transformContext$.value,he=document.querySelector(G);he&&he.contains(a)&&(e.position.transformContext=X)}}!c&&i&&!e?.position&&!e?.ghostComment&&(e.ghostComment={},this.setGhostCommentMessage(e),e.ghostComment.targetElement=e.targetElement)}}i&&(e.ghostComment?this.addAnnotationToGhostCommentAnnotationMap(e):this.removeAnnotationFromGhostCommentAnnotationMap(e))}catch(r){this.loggingService.catch("Error in CommentService calculateCommentAnnotationPosition:",r)}}addComment(e,i,r,a,s,c=[],p,h,_,E,D,B,G,X,he,Ie,Me,Le){this.loggingService.log("%c[WB] Calling FUNCTION: addComment","color: green;");try{let We=this.authService.getUser();if(We)if(We.isReadOnly||We.isAnonymous)this.loggingService.catch("Anonymous/Readonly users cannot add comments.");else{let ke=new ko;Me&&(ke=I(I({},ke),Me)),ke.comments=[],Me?.comments?.length&&(ke.comments=Me.comments.map(Ut=>{let Gt=new pc;return Gt=I(I({},Gt),Ut),Gt.from=We,Gt.lastUpdated=new Date,Gt.createdAt=this.timestamp,Gt})),ke.from=We,ke.color=ke?.color||U.DEFAULT_ANNOTATION_COLOR,ke.lastUpdated=this.timestamp,ke.createdAt=this.timestamp,ke.sourceId=he,ke.assignedTo=Me?.assignedTo||Ie,ke.customList=Me?.customList||[];let{topPositionX:we,topPositionY:Ee}=this.domService.getTopLeftPosition();ke.positionX=we,ke.positionY=Ee;let Pe=this.domService.getCurrentWindowSizeValue();if(ke.screenWidth=Pe.screenWidth,ke.screenHeight=Pe.screenHeight,ke.screenScrollHeight=Pe.screenScrollHeight,ke.taggedElementPath="",e&&(ke.targetElement=this.domService.getTargetElementForCursorPosition(e,!0,!0,!0,Ut=>{if(this.getSvgAsImg()){let Gt=Ut?.closest(`[${U.ATTRIBUTES.VELT_COMMENT_CONTAINER}]`);Gt&&Gt instanceof HTMLElement&&(Ut=Gt)}if(this.getPopoverMode()){let Gt=Ut?.closest(`[${U.ATTRIBUTES.VELT_TARGET_COMMENT_ELEMENT_ID}]`);if(Gt&&Gt instanceof HTMLElement)return Gt}return Ut}),this.getCommentToNearestAllowedElement()&&ke.targetElement?.xpath)){let Ut=this.domService.getElementFromXPath(ke.targetElement.xpath);if(Ut&&!this.isElementInsideAllowedElements(Ut)){let Gt=this.getNearestAllowedElement(Ut);if(Gt)ke.targetElement.xpath=this.domService.getXPath(Gt),ke.targetElement.fXpath=this.domService.getXPath(Gt,!0),ke.targetElement.cfXpath=this.domService.getXPath(Gt,!0,!0);else return}}if(i&&(ke.targetTextRange=i),ke?.targetElement?.xpath){let Ut=this.domService.getXPath(ke.targetElement.xpath);if(Ut){let Gt=Ut.iterateNext();Gt&&(xo(Gt)||(ke.targetElement=null))}}this.customFilterService.defaultStatus&&!Me?.status&&(ke.status=this.customFilterService.defaultStatus),ke.pageInfo=_i(),ke.pageInfo&&(ke.pageInfo.screenWidth=this.domService.getCurrentWindowSizeValue()?.screenWidth);let Ce=this.docService.getClientDocumentId(),ue=this.docService.getLocation()?.location;if(this.commentContextProvider!==null){let Ut=this.commentContextProvider(Ce,ue);Ut&&(ke.context=Ut)}if(a){ke.sourceId=a?.sourceId;let Ut=a?.targetElement,Gt=a?.commentData;if(Ut?.targetText)ke.targetTextRange={commonAncestorContainer:"/html/body",text:Ut.targetText,occurrence:Ut?.occurrence||1};else if(Ut?.elementId)if(ke.targetElementId=Ut.elementId,Ut?.selectAllContent)ke.selectAllContent=!!Ut?.selectAllContent;else{let It=cr(Ut.elementId,["id","data-id"]);It?ke.targetElement={xpath:this.domService.getXPath(It),fXpath:this.domService.getXPath(It,!0),cfXpath:this.domService.getXPath(It,!0,!0),topPercentage:50,leftPercentage:90}:ke.targetElement={xpath:"/html/body",fXpath:"/html/body",cfXpath:"/html/body",topPercentage:50,leftPercentage:90}}a?.status&&(ke.status=a.status),a?.context&&(ke.context=a.context),ke.comments||(ke.comments=[]);let Dt=this.authService.getUser();Gt?.forEach(It=>{let Nt=new pc;Nt.commentText=It.commentText,Nt.commentHtml=It.commentHtml,Nt.replaceContentHtml=It.replaceContentHtml,Nt.replaceContentText=It.replaceContentText,Nt.from=Dt,ke.comments.push(Nt)})}if(s&&(ke.isPageAnnotation=!0),c?.length&&(ke.comments=c),p&&(ke.commentType="chart",ke.metadata=p),_?.sourceId&&(ke.sourceId=_.sourceId),ke?.targetElement?.xpath&&!_){let Ut=this.domService.getElementFromXPath(ke.targetElement.xpath);Ut&&(_=this.getInlineCommentSectionConfig(Ut))}_?.targetInlineCommentElementId&&(ke.targetInlineCommentElementId=_?.targetInlineCommentElementId,ke.targetElementId=_.targetInlineCommentElementId,_?.config?.id&&(ke.inlineCommentSectionConfig=_?.config));let Be=!ke?.comments?.length,Se=a?.openComment===!1;this.getPrivateCommentMode()&&(ke?.iam||(ke.iam=new RS),ke.iam.accessMode=Ki.PRIVATE),E&&(ke.context=E.context,ke.commentType="manual",delete ke.targetElement),D&&(ke.targetElementId=D.targetElementId,ke.targetElement=D.targetElement),this.saveCommentToDb(ke,r,Be,Se,h,B,G,Le,X)}}catch(We){this.loggingService.catch("Error in CommentService addComment: ",We)}}setLocationToCommentAnnotation(e){try{let i=this.docService.getLocation();i?(e.locationId=i.locationId,e.location=i.location):(delete e.locationId,delete e.location);try{let r;e.targetElement?.xpath?r=this.domService.getElementFromXPath(e.targetElement.xpath):e.targetElementId?r=cr(e.targetElementId,["id","data-id"]):e.targetTextRange?.commonAncestorContainer&&(r=this.domService.getElementFromXPath(e.targetTextRange.commonAncestorContainer));let a=this.docService.getAdditionLocationFromElement(r);if(a){let s=this.docService.addLocation(a);s&&(e.locationId=s.locationId,e.location=s.location)}}catch{}}catch(i){this.loggingService.catch("Error in CommentService setLocationToCommentAnnotation:",i)}}getElementForCommentAnnotation(e){try{let i;return e.targetElement?.xpath?i=this.domService.getElementFromXPath(e.targetElement.xpath):e.targetElementId?i=cr(e.targetElementId,["id","data-id"]):e.targetTextRange?.commonAncestorContainer&&(i=this.domService.getElementFromXPath(e.targetTextRange.commonAncestorContainer)),i}catch(i){return this.loggingService.catch("Error in CommentService getElementForCommentAnnotation: ",i),null}}saveCommentToDb(e,i,r=!1,a=!1,s,c,p,h,_){this.loggingService.log("%c[WB] Calling FUNCTION: saveCommentToDb","color: green;");try{this.authService.getUser()&&this.authService.isFeatureAllowed(Re.COMMENT)&&this.docService.getDocumentPaths$().pipe(Ne(E=>!!E),Je(1),ge(E=>(this.documentPaths=E,this.loggingService.log(this.documentPaths),this.databaseService.getDb().pipe(Ne(D=>!!D),Je(1),ge(D=>ee(this,null,function*(){if(this.db=D,this.loggingService.log(this.db),this.documentPaths?.comment){let B=on(this.db,`${this.documentPaths?.comment}`);e.annotationId=this.commonDbService.generateDocumentId();let G=this.docService.getClientDocumentId(),X=this.docService.getLocation()?.location;if(p)e.multiThreadAnnotationId=p;else if(this.getMultiThread()){let we=om();e.targetElementId&&(we=om(e.targetElementId),e?.location?.id?we=om([e?.location?.id,e.targetElementId]):e?.locationId&&(we=om([e?.locationId+"",e.targetElementId]))),e.multiThreadAnnotationId=we}let he={addContext:we=>{this.analyticsService.trackEvent(Z.Events.Comments.COMMENT_ADD_CONTEXT_TRIGGERED,{annotationId:e.annotationId,commentType:this.getCommentType(e),commentMode:this.getCommentMode(),context:we}),e.context=we,we?.commentType==="manual"&&(e.commentType="manual",delete e.targetElement),e?.annotationId&&this.updateCommentAnnotationContext(e.annotationId,we)},documentId:G,location:X,annotation:$n(e),targetAnnotationId:e?.annotationId,targetCommentId:e?.comments?.length?e?.comments[0]?.commentId:void 0};e?.targetElement?.xpath?he.elementRef={xpath:e.targetElement.xpath}:he.elementRef=void 0,this.commentAddedEmitter!==null&&"emit"in this.commentAddedEmitter&&this.commentAddedEmitter.emit(he),this.commentAdded$.next(he),_&&_(he);let Ie=yield this.commentActionsService?.getAddCommentAnnotationEventFromCommentAddEventData(he);Ie&&this.commentActionsService?.triggerAddCommentAnnotationEvent(Ie),this.setLocationToCommentAnnotation(e);let Me=this.getElementForCommentAnnotation(e),Le=this.docService.getBaseMetadata("comment",{element:Me,multiThreadAnnotationId:e.multiThreadAnnotationId});if(!Le?.apiKey)return;if(e?.metadata||(e.metadata={}),e.metadata=I(I({},e.metadata),Le),s&&typeof s=="object"&&(e.locationId=h||this.docService.genarateLocationId(s),e.location=s,this.docService.addLocation(s)),r)window.localStorage.setItem(U.LOCAL_STORAGE.SNIPPYLY_QUEUED_COMMENT,JSON.stringify(e));else{let we=window.localStorage.getItem(U.LOCAL_STORAGE.SNIPPYLY_QUEUED_COMMENT);we&&JSON.parse(we).annotationId===e.annotationId&&e.comments!==void 0&&e.comments.length>0&&window.localStorage.removeItem(U.LOCAL_STORAGE.SNIPPYLY_QUEUED_COMMENT)}e.pageInfo&&(e.pageInfo.commentUrl=this.generateCommentUrl(e));let We=e.comments,ke=JSON.parse(JSON.stringify(e));if(ke.position=null,i){ke.targetElement=null,ke.targetTextRange=null;let we={annotationId:e.multiThreadAnnotationId?e.multiThreadAnnotationId:e.annotationId,type:e.multiThreadAnnotationId?Re.MULTI_THREAD:Re.COMMENT},Ee=yield this.areaService.generateAreaAnnotationId();ke.areaAnnotationId=Ee;let Pe=this.areaService.addArea(void 0,i,we,Ee,{locationId:ke.locationId,location:ke.location});Pe&&(ke.metadata=I(I({},ke.metadata),Pe?.metadata||{}))}!a&&!ke?.targetInlineCommentElementId&&!ke?.isPageAnnotation&&this.domService.toggleAnnotationSelection(ke,c),e.targetTextRange&&sessionStorage.setItem(U.SESSION_STORAGE.SNIPPYLY_AUTO_SELECT_ANNOTATION_ID,e?.multiThreadAnnotationId?e?.multiThreadAnnotationId:e.annotationId),this.analyticsService.trackEvent(Z.Events.Comments.COMMENT_DRAFT_ADDED,{annotationId:e.annotationId,commentType:this.getCommentType(ke),commentMode:this.getCommentMode()}),ke?.comments?.length?ke.comments=[]:ke.isDraft=!0,ke?.multiThreadAnnotationId&&this.saveMultiThreadCommentAnnotation(ke),We?.length?this.saveComment(ke,{type:jt.NEWLY_ADDED,updatedComment:We[0]}):this.draftCommentAnnotationsByAnnotationId$.next(T(I({},this.draftCommentAnnotationsByAnnotationId$.value),{[e.annotationId]:ke}))}})))))).subscribe(()=>{},E=>{this.loggingService.catch("Error in CommentService saveCommentToDb subscription: ",E)})}catch(E){this.loggingService.catch("Error in CommentService saveCommentToDb: ",E)}}saveMultiThreadCommentAnnotation(e){return ee(this,null,function*(){try{if(e?.multiThreadAnnotationId){let i=this.docService.getDocumentPaths();if(this.db&&i?.multiThread){let r={annotationId:e.multiThreadAnnotationId,targetElement:e.targetElement,targetElementId:e.targetElementId,targetInlineCommentElementId:e.targetInlineCommentElementId,inlineCommentSectionConfig:e.inlineCommentSectionConfig,areaAnnotationId:e.areaAnnotationId,targetTextRange:e.targetTextRange,from:e.from,locationId:e.locationId,location:e.location,sourceId:e.sourceId,type:"multiThread",metadata:e.metadata};delete e?.targetElement,delete e?.areaAnnotationId,delete e?.targetTextRange;let a=this.getMultiThreadCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:i?.organizationId,documentId:i?.documentId})?.find(s=>s.annotationId===e.multiThreadAnnotationId);if(a||(a=yield this.commonDbService?.getData({feature:"multiThread",properties:{documentId:i?.documentId??"",organizationId:i?.organizationId??"",id:e.multiThreadAnnotationId}})),a&&(a=JSON.parse(JSON.stringify(a)),delete a.from,r=I(I({},a),r)),r?.commentAnnotations||(r.commentAnnotations={}),r.commentAnnotations[e.annotationId]=!0,e?.isDraft)this.draftMultiThreadCommentAnnotationsByAnnotationId$.next(T(I({},this.draftMultiThreadCommentAnnotationsByAnnotationId$.value),{[r.annotationId]:T(I({},r),{isDraft:!0})}));else{let c=this.draftMultiThreadCommentAnnotationsByAnnotationId$.value[r.annotationId];if(c&&(r=I(I({},r),c)),delete r.isDraft,r.commentAnnotationsMap={},!r?.metadata?.documentId){r?.metadata||(r.metadata={});let _=this.docService.getBaseMetadata();r.metadata=I(I({},r?.metadata),_)}let{documentId:p,organizationId:h}=r?.metadata||{};yield this.commonDbService.updateData({feature:"multiThread",properties:{id:r.annotationId,documentId:p,organizationId:h},data:JSON.parse(JSON.stringify(r)),callback:()=>{let _=this.draftMultiThreadCommentAnnotationsByAnnotationId$.value;_[e.annotationId]&&(delete _[e.annotationId],this.draftMultiThreadCommentAnnotationsByAnnotationId$.next(_))}})}return r}}return null}catch(i){return this.loggingService.catch("Error in CommentService saveMultiThreadCommentAnnotation: ",i),null}})}setCommentCategory(e){return ee(this,null,function*(){try{if(e?.comments?.length){let i=e.comments[0].commentText?.trim();if(i){let r=yield this.getCommentCategory(i).toPromise();if(r){let a=this.docService.getDocumentPaths();if(a?.comment&&e?.annotationId){let s=this.getCommentAnnotationsOnCurrentOrganizationAndDocument()?.find(c=>c.annotationId===e.annotationId);if(s||(s=yield this.commonDbService?.getData({feature:"comment",properties:{documentId:a?.documentId??"",organizationId:a?.organizationId??"",id:e.annotationId}})),s?.annotationId){let c=s;c.commentCategories=[r];let{documentId:p,organizationId:h}=this.getDocumentIdAndOrganizationIdFromCommentAnnotation(c);yield this.commonDbService.updateData({feature:"comment",properties:{id:e.annotationId,documentId:p,organizationId:h},data:JSON.parse(JSON.stringify(c))})}}}}}}catch(i){this.loggingService.catch("Error in CommentService setCommentCategory: ",i)}})}getCommentCategory(e){try{let i=Cr(this.functions,Zn.cloudFunction.chatgptCompletion,{timeout:12e5}),a=[{role:"system",content:`Identify category of this sentence from these categories, ${Object.keys(this.customCategoryMap)?.join(", ")}:`},{role:"user",content:e}];return bo(i({messages:a,apiKey:this.configService.getApiKey(),sdkVersion:Ta(),sdkType:this.configService.getSdkType(),numResponse:1})).pipe(ce(s=>{if(s?.data){let c=s.data,p=c?.length?c[0]?.content?.trim():void 0;return p&&Object.keys(this.customCategoryMap).includes(p)?this.customCategoryMap[p]:void 0}else return}))}catch(i){return this.loggingService.catch("Error in CommentService getCommentCategory: ",i),re(void 0)}}updateCommentAnnotationContext(e,i,r){return ee(this,null,function*(){try{this.analyticsService.trackEvent(Z.Events.Comments.COMMENT_UPDATE_CONTEXT_TRIGGERED,{annotationId:e,context:i,merge:r?.merge});let a=this.authService.getUser(),s=this.docService.getDocumentPaths();if(a&&s?.comment&&e){let c=this.getCommentAnnotationsOnCurrentOrganizationAndDocument()?.find(p=>p.annotationId===e);if(typeof c=="object"&&(c=JSON.parse(JSON.stringify(c))),c||(c=yield this.commonDbService?.getData({feature:"comment",properties:{documentId:s?.documentId??"",organizationId:s?.organizationId??"",id:e}})),c?.annotationId){let p=i,h=JSON.parse(JSON.stringify(c.context||{}));r?.merge&&(p=I(I({},h),i));let _={context:JSON.parse(JSON.stringify(p||{}))};if(_?.context?.commentType==="manual"&&(_.commentType="manual",_.targetElement=null),c.context=_.context,Co(h,p))return Promise.resolve("Comment annotation context is already updated.");{let{documentId:E,organizationId:D}=this.getDocumentIdAndOrganizationIdFromCommentAnnotation(c);return this.commonDbService.updateData({feature:"comment",properties:{id:e,documentId:E,organizationId:D},data:JSON.parse(JSON.stringify(c)),callback:()=>{this.analyticsService.trackEvent(Z.Events.Comments.COMMENT_UPDATE_CONTEXT_SUCCESS,{annotationId:e,context:_?.context,merge:r?.merge})}})}}else return this.analyticsService.trackEvent(Z.Events.Comments.COMMENT_UPDATE_CONTEXT_FAILED,{annotationId:e,context:i,merge:r?.merge,error:"Comment annotation not found in database."}),Promise.resolve("Comment annotation not found in database.")}}catch(a){return this.loggingService.catch("Error in CommentService updateCommentAnnotationContext: ",a),Promise.resolve("Error in CommentService updateCommentAnnotationContext.")}})}updateComment(e,i,r,a,s){this.loggingService.log("%c[WB] Calling FUNCTION: updateComment","color: green;");try{if(this.authService.getUser()&&this.authService.isFeatureAllowed(Re.COMMENT)){if(i&&this.setLocationToCommentAnnotation(e),e?.targetElement?.xpath){let c=this.domService.getXPath(e.targetElement.xpath);if(c){let p=c.iterateNext();p&&(xo(p)||(e.targetElement=null))}}if(e?.type==="multiThread"){let c=JSON.parse(JSON.stringify(e));if(c.position=null,c.ghostComment=null,!c?.metadata?.documentId){c?.metadata||(c.metadata={});let _=this.docService.getBaseMetadata();c.metadata=I(I({},c?.metadata),_)}let{documentId:p,organizationId:h}=c?.metadata||{};r?this.commonDbService.updateData({feature:"multiThread",properties:{id:c.annotationId,documentId:p,organizationId:h},data:JSON.parse(JSON.stringify(c))}):this.commonDbService.setData({feature:"multiThread",properties:{id:c.annotationId,documentId:p,organizationId:h},data:JSON.parse(JSON.stringify(c))})}else{this.setSubscribedUsersDataInCommentAnnotation(e);let c=JSON.parse(JSON.stringify(e));c.position=null,c.ghostComment=null,c.lastUpdated=this.timestamp,c.status||(c.status=this.customFilterService.defaultStatus),delete c.resolved,delete c.inProgress,this.setLocationFromDocumentParams(c);let p=window.localStorage.getItem(U.LOCAL_STORAGE.SNIPPYLY_QUEUED_COMMENT);if(p&&JSON.parse(p).annotationId===c.annotationId&&window.localStorage.removeItem(U.LOCAL_STORAGE.SNIPPYLY_QUEUED_COMMENT),c?.multiThreadAnnotationId&&!s&&this.saveMultiThreadCommentAnnotation(c).then(h=>{}),c?.comments?.length){if(delete c?.isDraft,c?.multiThreadAnnotationId&&this.draftMultiThreadCommentAnnotationsByAnnotationId$.value[c?.multiThreadAnnotationId]&&this.saveMultiThreadCommentAnnotation(c),!c?.metadata?.documentId){c?.metadata||(c.metadata={});let D=this.docService.getBaseMetadata();c.metadata=I(I({},c?.metadata),D)}let{documentId:h,organizationId:_}=c?.metadata||{},E=a?I({annotationData:a?.commentAnnotation,targetAnnotationData:a?.targetComment,actionType:a?.actionType,notificationSource:"comment"},a?.otherFields||{}):null;r?this.commonDbService.updateData({feature:"comment",properties:{id:c.annotationId,documentId:h,organizationId:_},extraData:E,data:JSON.parse(JSON.stringify(c)),callback:D=>{a&&!D?.firestoreAvailable&&this.updateNotificationsDatabase(a.commentAnnotation,a.targetComment,a.actionType,a.otherFields||{})}}):this.commonDbService.setData({feature:"comment",properties:{id:c.annotationId,documentId:h,organizationId:_},extraData:E,data:JSON.parse(JSON.stringify(c)),callback:D=>{a&&!D?.firestoreAvailable&&this.updateNotificationsDatabase(a.commentAnnotation,a.targetComment,a.actionType,a.otherFields||{})}}),this.viewsService.setCommentAnnotationAsRead(c)}else this.draftCommentAnnotationsByAnnotationId$.next(T(I({},this.draftCommentAnnotationsByAnnotationId$.value),{[e.annotationId]:c}))}}}catch(c){this.loggingService.catch("Error in CommentService updateComment: ",c)}}getDocumentIdAndOrganizationIdFromCommentAnnotation(e){try{return{documentId:e?.metadata?.documentId,organizationId:e?.metadata?.organizationId}}catch(i){return this.loggingService.catch("Error in CommentService getDocumentIdAndOrganizationIdFromCommentAnnotation: ",i),{}}}getDocumentIdAndOrganizationIdFromMultiThreadCommentAnnotation(e){try{return{documentId:e?.metadata?.documentId,organizationId:e?.metadata?.organizationId}}catch(i){return this.loggingService.catch("Error in CommentService getDocumentIdAndOrganizationIdFromMultiThreadCommentAnnotation: ",i),{}}}setLocationFromDocumentParams(e){e?.documentParams&&(e.location=e.documentParams,delete e.documentParams),e?.documentParamsId&&(e.locationId=e.documentParamsId,delete e.documentParamsId)}deleteCommentPinAnnotations(e){return new Promise((i,r)=>ee(this,null,function*(){try{let a=this.domService.getSelectedAnnotationsMap(),s=this.authService.getUser(),c=[];Object.keys(a).forEach(p=>{let h=a[p];["tag","recorder","rewriter","arrow","area","multiThread"].includes(h.type)||s&&h.from&&(s?.isAdmin||h.from.userId===s.userId)&&c.push(h)}),c?.length?(this.analyticsService.trackEvent(Z.Events.Comments.COMMENT_DELETE_TRIGGERED,{triggerType:e,annotationId:c.map(p=>p.annotationId).join(),commentMode:this.getCommentMode()}),this.dialog.open(da,{data:{title:"Delete thread?",message:"All replies to this thread will be lost.",yesButton:"Delete",noButton:"Cancel",darkMode:this.commentContainerDarkMode$.value,variant:"comment"}}).afterClosed().pipe(Je(1)).subscribe(p=>{try{p?(c.forEach(h=>ee(this,null,function*(){yield this.deleteCommentPinAnnotation(h)})),setTimeout(()=>{document.querySelectorAll(`[${U.SNIPPYLY_HIGHLIGHT}]`).forEach(_=>{this.domService.removeHighlightFromElement(_)}),i()},100)):i()}catch(h){r(h)}},p=>{r(p)})):i(),this.domService.resetSelectedAnnotationsMap(!0,"comment")}catch(a){this.loggingService.catch("Error in CommentService deleteCommentPinAnnotations: ",a),r(a)}}))}deleteCommentPinAnnotation(e,i){return ee(this,null,function*(){try{if(setTimeout(()=>{if(this.draftCommentAnnotationsByAnnotationId$?.value?.[e.annotationId]){let r=this.draftCommentAnnotationsByAnnotationId$.value;delete r[e.annotationId],this.draftCommentAnnotationsByAnnotationId$.next(r)}},50),this.authService.isFeatureAllowed(Re.COMMENT))if((i||e.comments?.length)&&this.updateNotificationsDatabase(e,null,jt.DELETED),e.comments?.forEach(r=>{r.reactionAnnotationIds&&r.reactionAnnotationIds.forEach(a=>{this.deleteReaction(a)})}),e?.annotationId){this.analyticsService.trackEvent(Z.Events.Comments.COMMENT_DELETED,{annotationId:e.annotationId,commentType:this.getCommentType(e),commentMode:this.getCommentMode()});let r=window.localStorage.getItem(U.LOCAL_STORAGE.SNIPPYLY_QUEUED_COMMENT);r&&JSON.parse(r).annotationId===e.annotationId&&window.localStorage.removeItem(U.LOCAL_STORAGE.SNIPPYLY_QUEUED_COMMENT),this.areaService.onDeleteTargetAnnotation(e?.annotationId,e?.areaAnnotationId);let a={type:"delete",annotation:null,targetAnnotationId:e.annotationId};this.commentUpdated$.next(a),e?.multiThreadAnnotationId&&(yield this.removeCommentAnnotationFromMultiThread(e)),this.commentAnnotationDeleted$.next(e);let{documentId:s,organizationId:c}=this.getDocumentIdAndOrganizationIdFromCommentAnnotation(e);return e?.isDraft?Promise.resolve():this.commonDbService.deleteData({feature:"comment",properties:{id:e.annotationId,documentId:s,organizationId:c}}).then(()=>{this.viewsService.deleteCommentAnnotationViews(e,{documentId:s,organizationId:c})})}else return Promise.resolve();return Promise.resolve()}catch(r){return this.loggingService.catch("Error in CommentService deleteCommentPinAnnotation: ",r),Promise.resolve()}})}removeCommentAnnotationFromMultiThread(e){return ee(this,null,function*(){try{let i=e?.multiThreadAnnotationId;if(i){let r=this.docService.getDocumentPaths(),a=this.getMultiThreadAnnotationById(i);if(!a){let h=e?.metadata?.documentId||r?.documentId,_=e?.metadata?.organizationId||r?.organizationId;a=yield this.commonDbService?.getData({feature:"multiThread",properties:{documentId:h,organizationId:_,id:i}})}let s=this.draftMultiThreadCommentAnnotationsByAnnotationId$.value?.[i];a&&delete a?.commentAnnotations?.[e.annotationId],s&&(delete s?.commentAnnotations?.[e.annotationId],Object.keys(s?.commentAnnotations||{}).length===0&&(delete this.draftMultiThreadCommentAnnotationsByAnnotationId$.value?.[i],this.draftMultiThreadCommentAnnotationsByAnnotationId$.next(this.draftMultiThreadCommentAnnotationsByAnnotationId$.value))),delete a.commentAnnotationsMap;let{documentId:c,organizationId:p}=this.getDocumentIdAndOrganizationIdFromMultiThreadCommentAnnotation(a);return Object.keys(a?.commentAnnotations||{}).length===0?(this.areaService.onDeleteTargetAnnotation(a?.annotationId,a?.areaAnnotationId),this.multiThreadCommentAnnotationDeleted$.next(a),this.commonDbService.deleteData({feature:"multiThread",properties:{id:a?.annotationId,documentId:c,organizationId:p}})):this.commonDbService.setData({feature:"multiThread",properties:{id:a?.annotationId,documentId:c,organizationId:p},data:JSON.parse(JSON.stringify(a))})}}catch(i){this.loggingService.catch("Error in CommentService removeCommentAnnotationFromMultiThread: ",i)}})}getAnnotationById(e,i){try{let r=this.commentAnnotationById$.value?.[e]||this.draftCommentAnnotationsByAnnotationId$?.value?.[e];if(r){let{documentId:a,organizationId:s}=i||{};if(a&&r.metadata?.documentId!==a||s&&r.metadata?.organizationId!==s)return}return r}catch(r){this.loggingService.catch("Error in CommentService getAnnotationById: ",r);return}}getBaseMetadataFromCommentAnnotationId(e){try{let i=this.commentAnnotationById$.value?.[e];if(i)return i.metadata}catch(i){this.loggingService.catch("Error in CommentService getBaseMetadataFromCommentAnnotationId: ",i)}}getMultiThreadAnnotationById(e,i){try{let r=this.multiThreadCommentAnnotationById$.value?.[e]||this.draftMultiThreadCommentAnnotationsByAnnotationId$?.value?.[e];if(r){let{documentId:a,organizationId:s}=i||{};if(a&&r.metadata?.documentId!==a||s&&r.metadata?.organizationId!==s)return}return r}catch(r){this.loggingService.catch("Error in CommentService getAnnotationById: ",r);return}}getBaseMetadataFromMultiThreadCommentAnnotationId(e){try{let i=this.multiThreadCommentAnnotationById$.value?.[e];if(i)return i.metadata}catch(i){this.loggingService.catch("Error in CommentService getBaseMetadataFromMultiThreadCommentAnnotationId: ",i)}}getElementRefByAnnotationId(e){try{let i=this.getAnnotationById(e);if(i){let r=i?.targetElement?.xpath;if(r)return{xpath:r}}return}catch(i){this.loggingService.catch("Error in CommentService getElementRefByAnnotationId: ",i);return}}scrollToCommentByAnnotationId(e){try{let i=this.getAnnotationById(e),r=document.getElementById(`comment-pin-container-${e}`);r||(r=document.querySelector(`[data-velt-id='${e}']`)),r||(r=document.querySelector(`${U.TAGS.VELT_COMMENT_TEXT}[${U.ATTRIBUTES.ANNOTATION_ID}="${e}"]`)),r&&(r.scrollIntoView({behavior:"smooth",block:"center",inline:"nearest"}),i&&(this.domService.getSelectedAnnotationsMap()[e]||this.domService.toggleAnnotationSelection(i)))}catch(i){this.loggingService.catch("Error in CommentService scrollToCommentByAnnotationId: ",i)}}selectCommentByAnnotationId(e,i){try{this.loggingService.log("%c[WB] Calling FUNCTION: selectCommentByAnnotationId","color: green;");let r=this.getAnnotationById(e);r&&this.domService.toggleAnnotationSelection(r,void 0,void 0,!0)}catch(r){this.loggingService.catch("Error in CommentService selectCommentByAnnotationId: ",r)}}enableAddCommentMode(){try{this.authService.isFeatureAllowed(Re.COMMENT)?!this.authService.isPlanExpired()&&this.iamService.hasRoleAny([mo.ADMIN,mo.COMMENTER])?(this.analyticsService.trackEvent(Z.Events.Comments.COMMENT_ADD_MODE_ENABLED,{commentMode:this.getCommentMode()}),this.addCommentMode$.next(!0)):this.loggingService.catch("Error in CommentService enableAddCommentMode: ","User is not allowed to add comment."):this.loggingService.catch("Error in CommentService enableAddCommentMode: ","Comment feature is not enabled.")}catch(e){this.loggingService.catch("Error in CommentService enableAddCommentMode: ",e)}}disableAddCommentMode(){this.analyticsService.trackEvent(Z.Events.Comments.COMMENT_ADD_MODE_DISABLED,{commentMode:this.getCommentMode()}),this.addCommentMode$.next(!1)}addCommentModeChange(){return this.addCommentMode$.asObservable()}enablePersistentCommentMode(){try{this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{persistentCommentMode:!0}}),this.persistentCommentMode$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enablePersistentCommentMode: ",e)}}enableDeleteReplyConfirmation(){try{this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{deleteReplyConfirmation:!0}}),this.deleteReplyConfirmation$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableDeleteReplyConfirmation: ",e)}}enableSeenByUsers(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{seenByUsers:!0}}),this.seenByUsers$.value===!0)return;this.seenByUsers$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableSeenByUsers: ",e)}}disableSeenByUsers(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{seenByUsers:!1}}),this.seenByUsers$.value===!1)return;this.seenByUsers$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableSeenByUsers: ",e)}}getSeenByUsers$(){return this.seenByUsers$.asObservable()}disableDeleteReplyConfirmation(){try{this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{deleteReplyConfirmation:!1}}),this.deleteReplyConfirmation$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableDeleteReplyConfirmation: ",e)}}disablePersistentCommentMode(){try{this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{persistentCommentMode:!1}}),this.persistentCommentMode$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disablePersistentCommentMode: ",e)}}persistentCommentModeChange(){return this.persistentCommentMode$.asObservable()}enablePersistentModeBanner(){this.persistentModeBanner$.next(!0)}disablePersistentModeBanner(){this.persistentModeBanner$.next(!1)}persistentModeBannerChange(){return this.persistentModeBanner$.asObservable()}showCommentIndex(e){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{commentIndex:e}}),this.showCommentIndex$.value===e)return;this.showCommentIndex$.next(e)}catch(i){this.loggingService.catch("Error in CommentService showCommentIndex: ",i)}}getShowCommentIndex(){return this.showCommentIndex$.asObservable()}enablePopoverMode(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{popoverMode:!0}}),this.popoverMode$.value===!0)return;this.popoverMode$.next(!0),this.analyticsService.trackEvent(Z.Events.Comments.COMMENT_POPOVER_MODE_ENABLED,{commentMode:this.getCommentMode()})}catch(e){this.loggingService.catch("Error in CommentService enablePopoverMode: ",e)}}disablePopoverMode(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{popoverMode:!1}}),this.popoverMode$.value===!1)return;this.popoverMode$.next(!1),this.analyticsService.trackEvent(Z.Events.Comments.COMMENT_POPOVER_MODE_DISABLED,{commentMode:this.getCommentMode()})}catch(e){this.loggingService.catch("Error in CommentService disablePopoverMode: ",e)}}getPopoverMode(){try{return this.popoverMode$.value}catch(e){return this.loggingService.catch("Error in CommentService getPopoverMode: ",e),!1}}getPopoverMode$(){return this.popoverMode$.asObservable()}enablePopoverTriangleComponent(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{popoverTriangleComponent:!0}}),this.popoverTriangleComponent$.value===!0)return;this.popoverTriangleComponent$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enablePopoverTriangleComponent: ",e)}}disablePopoverTriangleComponent(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{popoverTriangleComponent:!1}}),this.popoverTriangleComponent$.value===!1)return;this.popoverTriangleComponent$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disablePopoverTriangleComponent: ",e)}}getPopoverTriangleComponent(){try{return this.popoverTriangleComponent$.value}catch(e){return this.loggingService.catch("Error in CommentService getPopoverTriangleComponent: ",e),!1}}getPopoverTriangleComponent$(){return this.popoverTriangleComponent$.asObservable()}enableDraftMode(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{draftMode:!0}}),this.draftMode$.value===!0)return;this.draftMode$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableDraftMode: ",e)}}disableDraftMode(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{draftMode:!1}}),this.draftMode$.value===!1)return;this.draftMode$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableDraftMode: ",e)}}getDraftMode$(){return this.draftMode$.asObservable()}getDraftMode(){return this.draftMode$.value}enableTextComments(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{textMode:!0}}),this.analyticsService.trackEvent(Z.Events.Comments.COMMENT_TEXT_MODE_ENABLED,{commentMode:this.getCommentMode()}),this.textCommentMode$.value===!0)return;this.textCommentMode$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableTextComments: ",e)}}disableTextComments(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{textMode:!1}}),this.analyticsService.trackEvent(Z.Events.Comments.COMMENT_TEXT_MODE_DISABLED,{commentMode:this.getCommentMode()}),this.textCommentMode$.value===!1)return;this.textCommentMode$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableTextComments: ",e)}}getTextCommentMode$(){return this.textCommentMode$.asObservable()}isUserGlobalContact$(){return this.contactService.isUserGlobalContact$()}isSidebarOpenedByCustomTrigger(){try{return this.sidebarOpenedByCustomTrigger$.value}catch(e){return this.loggingService.catch("Error in CommentService isSidebarOpenedByCustomTrigger: ",e),!1}}setSidebarVisibility(e,i=!1,r=!1){try{this.domService.resetSelectedAnnotationsMap(),e?(document.querySelector(U.TAGS.VELT_COMMENTS_SIDEBAR)||document.querySelector(U.TAGS.SNIPPYLY_COMMENTS_SIDEBAR)?this.sidebarVisible$.next(e):this.loggingService.catch("Error in CommentService setSidebarVisibility: ",`<${U.TAGS.VELT_COMMENTS_SIDEBAR}> tag is not added.`),i&&this.sidebarOpenedByCustomTrigger$.next(!0)):(!this.sidebarOpenedByCustomTrigger$.value||i||r)&&(this.sidebarVisible$.next(e),this.sidebarOpenedByCustomTrigger$.next(!1)),e?this.analyticsService.trackEvent(Z.Events.Comments.COMMENT_SIDEBAR_OPENED,{commentMode:this.getCommentMode()}):this.analyticsService.trackEvent(Z.Events.Comments.COMMENT_SIDEBAR_CLOSED,{commentMode:this.getCommentMode()})}catch{this.loggingService.catch("Error in CommentService setSidebarVisibility: ",`<${U.TAGS.VELT_COMMENTS_SIDEBAR}> tag is not added.`)}}toggleSidebarVisibility(e=!1,i=!1){try{this.domService.resetSelectedAnnotationsMap(),this.sidebarVisible$.value?(!this.sidebarOpenedByCustomTrigger$.value||e||i)&&(this.sidebarVisible$.next(!this.sidebarVisible$.value),this.sidebarOpenedByCustomTrigger$.next(!1)):(document.querySelector(U.TAGS.VELT_COMMENTS_SIDEBAR)||document.querySelector(U.TAGS.SNIPPYLY_COMMENTS_SIDEBAR)?(this.sidebarVisible$.next(!this.sidebarVisible$.value),this.sidebarVisible$.value?this.analyticsService.trackEvent(Z.Events.Comments.COMMENT_SIDEBAR_TOGGLED,{commentMode:this.getCommentMode(),action:"closed"}):this.analyticsService.trackEvent(Z.Events.Comments.COMMENT_SIDEBAR_TOGGLED,{commentMode:this.getCommentMode(),action:"opened"})):this.loggingService.catch("Error in CommentService toggleSidebarVisibility: ",`<${U.TAGS.VELT_COMMENTS_SIDEBAR}> tag is not added.`),e&&this.sidebarOpenedByCustomTrigger$.next(!0))}catch{this.loggingService.catch("Error in CommentService toggleSidebarVisibility: ",`<${U.TAGS.VELT_COMMENTS_SIDEBAR}> tag is not added.`)}}getSidebarVisibility$(){return this.sidebarVisible$.asObservable()}disableFloatingComments(e){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{floatingCommentDialog:!e}}),this.floatingCommentsEnabled$.value===!e)return;this.floatingCommentsEnabled$.next(!e)}catch(i){this.loggingService.catch("Error in CommentService disableFloatingComments: ",i)}}showFloatingComments$(){return this.floatingCommentsEnabled$.asObservable()}showFloatingComments(){return this.floatingCommentsEnabled$.value}setModeratorMode(e){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{moderatorMode:e}}),this.moderatorMode$.value===e)return;this.moderatorMode$.next(e)}catch(i){this.loggingService.catch("Error in CommentService setModeratorMode: ",i)}}getModeratorMode(){return this.moderatorMode$.value}getModeratorMode$(){return this.moderatorMode$.asObservable()}setStreamMode(e){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{streamMode:e}}),this.streamMode$.value===e)return;this.streamMode$.next(e),e?this.analyticsService.trackEvent(Z.Events.Comments.COMMENT_STREAM_MODE_ENABLED,{commentMode:this.getCommentMode()}):this.analyticsService.trackEvent(Z.Events.Comments.COMMENT_STREAM_MODE_DISABLED,{commentMode:this.getCommentMode()})}catch(i){this.loggingService.catch("Error in CommentService setStreamMode: ",i)}}getStreamMode(){return this.streamMode$.value}getStreamMode$(){return this.streamMode$.asObservable()}getEnableDialogOnHover(){return this.enableDialogOnHover$.value}getEnableDialogOnHover$(){return this.enableDialogOnHover$.asObservable()}setEnableDialogOnHover(e){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{dialogOnHover:e}}),this.enableDialogOnHover$.value===e)return;this.enableDialogOnHover$.next(e)}catch(i){this.loggingService.catch("Error in CommentService setEnableDialogOnHover: ",i)}}getEnableDialogOnTargetElementClick(){return this.enableDialogOnTargetElementClick$.value}getEnableDialogOnTargetElementClick$(){return this.enableDialogOnTargetElementClick$.asObservable()}setEnableDialogOnTargetElementClick(e){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{dialogOnTargetElementClick:e}}),this.enableDialogOnTargetElementClick$.value===e)return;this.enableDialogOnTargetElementClick$.next(e)}catch(i){this.loggingService.catch("Error in CommentService setEnableDialogOnTargetElementClick: ",i)}}getEnablePriority(){return this.enablePriority$.value}getEnablePriority$(){return this.enablePriority$.asObservable()}setEnablePriority(e){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{priority:e}}),this.enablePriority$.value===e)return;this.enablePriority$.next(e)}catch(i){this.loggingService.catch("Error in CommentService setEnablePriority: ",i)}}getEnableStatus(){return this.enableStatus$.value}getEnableStatus$(){return this.enableStatus$.asObservable()}setEnableStatus(e){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{status:e}}),this.getEnableStatus()===e)return;this.enableStatus$.next(e)}catch(i){this.loggingService.catch("Error in CommentService setEnableStatus: ",i)}}getEnableResolve(){return this.enableResolve$.value}getEnableResolve$(){return this.enableResolve$.asObservable()}setEnableResolve(e){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{resolveButton:e}}),this.getEnableResolve()===e)return;this.enableResolve$.next(e)}catch(i){this.loggingService.catch("Error in CommentService setEnableResolve: ",i)}}getEnableGhostComments(){return this.enableGhostComments$.value}getEnableGhostComments$(){return this.enableGhostComments$.asObservable()}enableGhostComments(){try{this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{ghostComments:!0}}),this.enableGhostComments$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableGhostComments: ",e)}}disableGhostComments(){try{this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{ghostComments:!1}}),this.enableGhostComments$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableGhostComments: ",e)}}getEnableGhostCommentsMessage(){return this.enableGhostCommentsMessage$.value}getEnableGhostCommentsMessage$(){return this.enableGhostCommentsMessage$.asObservable()}enableGhostCommentsMessage(){try{this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{ghostCommentsIndicator:!0}}),this.enableGhostCommentsMessage$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableShowGhostCommentsMessage: ",e)}}disableGhostCommentsMessage(){try{this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{ghostCommentsIndicator:!1}}),this.enableGhostCommentsMessage$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableShowGhostCommentsMessage: ",e)}}enableInboxMode(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{inboxMode:!0}}),this.inboxMode$.value===!0)return;this.inboxMode$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableInboxMode: ",e)}}disableInboxMode(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{inboxMode:!1}}),this.inboxMode$.value===!1)return;this.inboxMode$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableInboxMode: ",e)}}getInboxMode(){return this.inboxMode$.value}getInboxMode$(){return this.inboxMode$.asObservable()}setEnableAutoCategorize(e){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{autoCategorize:e}}),this.enableAutoCategorize$.value===e)return;this.enableAutoCategorize$.next(e)}catch(i){this.loggingService.catch("Error in CommentService setEnableAutoCategorize: ",i)}}getEnableAutoCategorize(){return this.enableAutoCategorize$.value}getEnableAutoCategorize$(){return this.enableAutoCategorize$.asObservable()}setCommentContainerDarkMode(e){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{darkMode:e}}),this.commentContainerDarkMode$.value===e)return;this.commentContainerDarkMode$.next(e)}catch(i){this.loggingService.catch("Error in CommentService setCommentContainerDarkMode: ",i)}}getCommentContainerDarkMode(){return this.commentContainerDarkMode$.asObservable()}getSuggestionMode(){return this.suggestionMode$.value}getSuggestionMode$(){return this.suggestionMode$.asObservable()}setSuggestionMode(e){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{suggestionMode:e}}),this.getSuggestionMode()===e)return;this.suggestionMode$.next(e)}catch(i){this.loggingService.catch("Error in CommentService setSuggestionMode: ",i)}}getMobileMode(){return this.mobileMode$.value}getMobileMode$(){return this.mobileMode$.asObservable()}setMobileMode(e){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{mobileMode:e}}),this.getMobileMode()===e)return;this.mobileMode$.next(e)}catch(i){this.loggingService.catch("Error in CommentService setMobileMode: ",i)}}enableInlineCommentMode(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{inlineCommentMode:!0}}),this.inlineCommentMode$.value===!0)return;this.inlineCommentMode$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableInlineCommentMode: ",e)}}disableInlineCommentMode(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{inlineCommentMode:!1}}),this.inlineCommentMode$.value===!1)return;this.inlineCommentMode$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableInlineCommentMode: ",e)}}getInlineCommentMode(){return this.inlineCommentMode$.value}getInlineCommentMode$(){return this.inlineCommentMode$.asObservable()}enableMinimap(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{minimap:!0}}),this.minimap$.value===!0)return;this.minimap$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableMinimap: ",e)}}disableMinimap(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{minimap:!1}}),this.minimap$.value===!1)return;this.minimap$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableMinimap: ",e)}}getMinimap(){return this.minimap$.value}getMinimap$(){return this.minimap$.asObservable()}showCommentsOnDom(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{commentsOnDom:!0}}),this.commentsOnDom$.value===!0)return;this.commentsOnDom$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService showCommentsOnDom: ",e)}}hideCommentsOnDom(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{commentsOnDom:!1}}),this.commentsOnDom$.value===!1)return;this.commentsOnDom$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService hideCommentsOnDom: ",e)}}getCommentsOnDom(){return this.commentsOnDom$.value}getCommentsOnDom$(){return this.commentsOnDom$.asObservable()}enableCommentTool(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{commentTool:!0}}),this.commentToolEnabled$.value===!0)return;this.commentToolEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableCommentTool: ",e)}}disableCommentTool(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{commentTool:!1}}),this.commentToolEnabled$.value===!1)return;this.commentToolEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableCommentTool: ",e)}}getCommentTool(){return this.commentToolEnabled$.value}getCommentTool$(){return this.commentToolEnabled$.asObservable()}setTotalMediaLength(e){try{if(this.totalMediaLength$.value===e)return;this.totalMediaLength$.next(e)}catch(i){this.loggingService.catch("Error in CommentService setTotalMediaLength: ",i)}}getTotalMediaLength(){return this.totalMediaLength$.value}getTotalMediaLength$(){return this.totalMediaLength$.asObservable()}enableSidebarUrlNavigation(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{sidebarUrlNavigation:!0}}),this.sidebarUrlNavigationEnabled$.value===!0)return;this.sidebarUrlNavigationEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableSidebarUrlNavigation: ",e)}}disableSidebarUrlNavigation(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{sidebarUrlNavigation:!1}}),this.sidebarUrlNavigationEnabled$.value===!1)return;this.sidebarUrlNavigationEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableSidebarUrlNavigation: ",e)}}getSidebarUrlNavigation(){return this.sidebarUrlNavigationEnabled$.value}getSidebarUrlNavigation$(){return this.sidebarUrlNavigationEnabled$.asObservable()}setDetectionStrategy(e){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{detectionStrategy:e}}),this.detectionStrategy$.value===e)return;this.detectionStrategy$.next(e)}catch(i){this.loggingService.catch("Error in CommentService setDetectionStrategy: ",i)}}getDetectionStrategy(){return this.detectionStrategy$.value}getDetectionStrategy$(){return this.detectionStrategy$.asObservable()}enableSidebarButtonOnCommentDialog(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{sidebarButtonOnCommentDialog:!0}}),this.sidebarButtonOnCommentDialogVisible$.value===!0)return;this.sidebarButtonOnCommentDialogVisible$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableSidebarButtonOnCommentDialog: ",e)}}disableSidebarButtonOnCommentDialog(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{sidebarButtonOnCommentDialog:!1}}),this.sidebarButtonOnCommentDialogVisible$.value===!1)return;this.sidebarButtonOnCommentDialogVisible$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableSidebarButtonOnCommentDialog: ",e)}}getSidebarButtonOnCommentDialogVisibility(){return this.sidebarButtonOnCommentDialogVisible$.value}getSidebarButtonOnCommentDialogVisibility$(){return this.sidebarButtonOnCommentDialogVisible$.asObservable()}onSidebarButtonOnCommentDialogClick(){this.sidebarButtonOnCommentDialogClick$.next()}getSidebarButtonOnCommentDialogClick$(){return this.sidebarButtonOnCommentDialogClick$.asObservable()}enableDeviceIndicatorOnCommentPins(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{deviceIndicatorOnCommentPins:!0}}),this.deviceIndicatorOnCommentPins$.value===!0)return;this.deviceIndicatorOnCommentPins$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableDeviceIndicatorOnCommentPins: ",e)}}disableDeviceIndicatorOnCommentPins(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{deviceIndicatorOnCommentPins:!1}}),this.deviceIndicatorOnCommentPins$.value===!1)return;this.deviceIndicatorOnCommentPins$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableDeviceIndicatorOnCommentPins: ",e)}}getDeviceIndicatorOnCommentPins(){return this.deviceIndicatorOnCommentPins$.value}getDeviceIndicatorOnCommentPins$(){return this.deviceIndicatorOnCommentPins$.asObservable()}onSidebarCommentClick(e){this.sidebarCommentClick$.next(e)}getSidebarCommentClick$(){return this.sidebarCommentClick$.asObservable()}onCommentNavigationButtonClick(e){this.commentNavigationButtonClick$.next(e)}getCommentNavigationButtonClick$(){return this.commentNavigationButtonClick$.asObservable()}addBubbleCommentAnnotationIds(e){try{let r=[...this.bubbleCommentAnnotationIds$.value||[],...e],a=[...new Set(r)];this.bubbleCommentAnnotationIds$.next(a)}catch(i){this.loggingService.catch("Error in CommentService addBubbleCommentAnnotationIds: ",i)}}getBubbleCommentAnnotationIds(){return this.bubbleCommentAnnotationIds$.value}getBubbleCommentAnnotationIds$(){return this.bubbleCommentAnnotationIds$.asObservable()}removeBubbleCommentAnnotationIds(e){try{let r=(this.bubbleCommentAnnotationIds$.value||[]).filter(a=>!e.includes(a));this.bubbleCommentAnnotationIds$.next(r)}catch(i){this.loggingService.catch("Error in CommentService removeBubbleCommentAnnotationIds: ",i)}}enableSignInButton(e){try{this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{signInButton:e}}),this.enableSignInButton$.next(e)}catch(i){this.loggingService.catch("Error in CommentService enableSignInButton: ",i)}}getSignInButton(){return this.enableSignInButton$.value}getSignInButton$(){return this.enableSignInButton$.asObservable()}onSignInClick(){this.onSignInClick$.next()}getSignInButtonClick$(){return this.onSignInClick$.asObservable()}enableUpgradeButton(e){try{this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{upgradeButton:e}}),this.enableUpgradeButton$.next(e)}catch(i){this.loggingService.catch("Error in CommentService enableUpgradeButton: ",i)}}getUpgradeButton(){return this.enableUpgradeButton$.value}getUpgradeButton$(){return this.enableUpgradeButton$.asObservable()}onUpgradeClick(){this.onUpgradeClick$.next()}getUpgradeButtonClick$(){return this.onUpgradeClick$.asObservable()}openSidebar(){this.openSidebar$.next()}getOpenSidebar$(){return this.openSidebar$.asObservable()}enableAttachment(e){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{attachments:e}}),this.enableAttachment$.value===e)return;this.enableAttachment$.next(e)}catch(i){this.loggingService.catch("Error in CommentService enableAttachment: ",i)}}getEnableAttachment$(){return this.enableAttachment$.asObservable()}setAllowedRecordings(e){try{this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{recordings:e}}),e?.includes("all")?this.allowedRecordings$.next(["audio","video","screen"]):e?.includes("none")?this.allowedRecordings$.next([]):this.allowedRecordings$.next(e)}catch(i){this.loggingService.catch("Error in CommentService setAllowedRecordings: ",i)}}getAllowedRecordings(){return this.allowedRecordings$.value}getAllowedRecordings$(){return this.allowedRecordings$.asObservable()}enableReactions(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{reactions:!0}}),this.enableReactions$.value===!0)return;this.enableReactions$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableReactions: ",e)}}disableReactions(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{reactions:!1}}),this.enableReactions$.value===!1)return;this.enableReactions$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableReactions: ",e)}}getEnableReactions(){return this.enableReactions$.value}getEnableReactions$(){return this.enableReactions$.asObservable()}addCommentOnElement(e){this.addComment(void 0,void 0,void 0,e)}enablePrivateCommentMode(){return ee(this,null,function*(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{privateCommentMode:!0}}),this.privateCommentMode$.value===!0)return;this.iamService.isUserAdmin$().pipe(Je(1)).subscribe(e=>{e?(this.privateCommentMode$.next(!0),this.analyticsService.trackEvent(Z.Events.Comments.COMMENT_PRIVATE_COMMENT_MODE_ENABLED)):this.loggingService.logsEnabled&&console.warn("You are not allowed to enable private comment mode.")})}catch(e){this.loggingService.catch("Error in CommentService enablePrivateCommentMode: ",e)}})}disablePrivateCommentMode(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{privateCommentMode:!1}}),this.privateCommentMode$.value===!1)return;this.privateCommentMode$.next(!1),this.analyticsService.trackEvent(Z.Events.Comments.COMMENT_PRIVATE_COMMENT_MODE_DISABLED)}catch(e){this.loggingService.catch("Error in CommentService disablePrivateCommentMode: ",e)}}getPrivateCommentMode(){return this.privateCommentMode$.value}getPrivateCommentMode$(){return this.privateCommentMode$.asObservable()}enableScrollToComment(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{scrollToComment:!0}}),this.scrollToComment$.value===!0)return;this.scrollToComment$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableScrollToComment: ",e)}}disableScrollToComment(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{scrollToComment:!1}}),this.scrollToComment$.value===!1)return;this.scrollToComment$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableScrollToComment: ",e)}}getScrollToComment(){return this.scrollToComment$.value}getScrollToComment$(){return this.scrollToComment$.asObservable()}showScreenSizeInfo(e){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{deviceInfo:e}}),this.showScreenSizeInfo$.value===e)return;this.showScreenSizeInfo$.next(e)}catch(i){this.loggingService.catch("Error in CommentService showScreenSizeInfo: ",i)}}getShowScreenSizeInfo$(){return this.showScreenSizeInfo$.asObservable()}enableUserMentions(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableUserMentions","color: green;"),this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{userMentions:!0}}),this.userMentions$.value===!0)return;this.userMentions$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableUserMentions: ",e)}}disableUserMentions(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableUserMentions","color: green;"),this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{userMentions:!1}}),this.userMentions$.value===!1)return;this.userMentions$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableUserMentions: ",e)}}getUserMentions(){return this.userMentions$.value}getUserMentions$(){return this.userMentions$.asObservable()}enableDeleteOnBackspace(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableDeleteOnBackspace","color: green;"),this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{deleteOnBackspace:!0}}),this.deleteOnBackspace$.value===!0)return;this.deleteOnBackspace$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableDeleteOnBackspace: ",e)}}disableDeleteOnBackspace(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableDeleteOnBackspace","color: green;"),this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{deleteOnBackspace:!1}}),this.deleteOnBackspace$.value===!1)return;this.deleteOnBackspace$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableDeleteOnBackspace: ",e)}}getDeleteOnBackspace(){return this.deleteOnBackspace$.value}getDeleteOnBackspace$(){return this.deleteOnBackspace$.asObservable()}enableHotkey(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableHotkey","color: green;"),this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{hotkey:!0}}),this.hotkeyEnabled$.value===!0)return;this.hotkeyEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableHotkey: ",e)}}disableHotkey(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableHotkey","color: green;"),this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{hotkey:!1}}),this.hotkeyEnabled$.value===!1)return;this.hotkeyEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableHotkey: ",e)}}enableRecordingSummary(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableRecordingSummary","color: green;"),this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{recordingSummary:!0}}),this.recordingSummaryEnabled$.value===!0)return;this.recordingSummaryEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableRecordingSummary: ",e)}}disableRecordingSummary(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableRecordingSummary","color: green;"),this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{recordingSummary:!1}}),this.recordingSummaryEnabled$.value===!1)return;this.recordingSummaryEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableRecordingSummary: ",e)}}getRecordingSummaryEnabled(){return this.recordingSummaryEnabled$.value}getRecordingSummaryEnabled$(){return this.recordingSummaryEnabled$.asObservable()}setUnreadIndicatorMode(e){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: setUnreadIndicatorMode","color: green;"),this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{unreadIndicatorMode:e}}),this.unreadIndicatorMode$.value===e)return;this.unreadIndicatorMode$.next(e)}catch(i){this.loggingService.catch("Error in CommentService setUnreadIndicatorMode: ",i)}}getUnreadIndicatorMode(){return this.unreadIndicatorMode$.value}getUnreadIndicatorMode$(){return this.unreadIndicatorMode$.asObservable()}setComposerMode(e){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: setComposerMode","color: green;"),this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{composerMode:e}}),this.composerMode$.value===e)return;this.composerMode$.next(e)}catch(i){this.loggingService.catch("Error in CommentService setComposerMode: ",i)}}getComposerMode(){return this.composerMode$.value}getComposerMode$(){return this.composerMode$.asObservable()}enableEnterKeyToSubmit(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableEnterKeyToSubmit","color: green;"),this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{enterKeyToSubmit:!0}}),this.enterKeyToSubmit$.value===!0)return;this.enterKeyToSubmit$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableEnterKeyToSubmit: ",e)}}disableEnterKeyToSubmit(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableEnterKeyToSubmit","color: green;"),this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{enterKeyToSubmit:!1}}),this.enterKeyToSubmit$.value===!1)return;this.enterKeyToSubmit$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableEnterKeyToSubmit: ",e)}}getEnterKeyToSubmit(){return this.enterKeyToSubmit$.value}getEnterKeyToSubmit$(){return this.enterKeyToSubmit$.asObservable()}enablePinShadowDOM(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enablePinShadowDOM","color: green;"),this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{pinShadowDom:!0}}),this.pinShadowDOM$.value===!0)return;this.pinShadowDOM$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enablePinShadowDOM: ",e)}}disablePinShadowDOM(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disablePinShadowDOM","color: green;"),this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{pinShadowDom:!1}}),this.pinShadowDOM$.value===!1)return;this.pinShadowDOM$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disablePinShadowDOM: ",e)}}getPinShadowDOM(){return this.pinShadowDOM$.value}getPinDarkMode(){return this.pinDarkMode$.value}getPinDarkMode$(){return this.pinDarkMode$.asObservable()}getTextCommentToolDarkMode(){return this.textCommentToolDarkMode$.value}getTextCommentToolDarkMode$(){return this.textCommentToolDarkMode$.asObservable()}getTextCommentToolbarDarkMode(){return this.textCommentToolbarDarkMode$.value}getTextCommentToolbarDarkMode$(){return this.textCommentToolbarDarkMode$.asObservable()}getPinShadowDOM$(){return this.pinShadowDOM$.asObservable()}getTextCommentToolShadowDOM$(){return this.textCommentToolShadowDOM$.asObservable()}getTextCommentToolbarShadowDOM$(){return this.textCommentToolbarShadowDOM$.asObservable()}enableDialogShadowDOM(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableDialogShadowDOM","color: green;"),this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{dialogShadowDom:!0}}),this.dialogShadowDOM$.value===!0)return;this.dialogShadowDOM$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableDialogShadowDOM: ",e)}}enableTextCommentToolbarShadowDOM(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableTextCommentToolbarShadowDOM","color: green;"),this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{textCommentToolbarShadowDom:!0}}),this.textCommentToolbarShadowDOM$.value===!0)return;this.textCommentToolbarShadowDOM$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableTextCommentToolbarShadowDOM: ",e)}}disableTextCommentToolbarShadowDOM(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableTextCommentToolbarShadowDOM","color: green;"),this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{textCommentToolbarShadowDom:!1}}),this.textCommentToolbarShadowDOM$.value===!1)return;this.textCommentToolbarShadowDOM$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableTextCommentToolbarShadowDOM: ",e)}}enableTextCommentToolShadowDOM(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableTextCommentToolShadowDOM","color: green;"),this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{textCommentToolShadowDom:!0}}),this.textCommentToolShadowDOM$.value===!0)return;this.textCommentToolShadowDOM$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableTextCommentToolShadowDOM: ",e)}}disableTextCommentToolShadowDOM(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableTextCommentToolShadowDOM","color: green;"),this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{textCommentToolShadowDom:!1}}),this.textCommentToolShadowDOM$.value===!1)return;this.textCommentToolShadowDOM$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableTextCommentToolShadowDOM: ",e)}}enableTextCommentToolDarkMode(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableTextCommentToolDarkMode","color: green;"),this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{textCommentToolDarkMode:!0}}),this.textCommentToolDarkMode$.value===!0)return;this.textCommentToolDarkMode$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableTextCommentToolDarkMode: ",e)}}disableTextCommentToolDarkMode(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableTextCommentToolDarkMode","color: green;"),this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{textCommentToolDarkMode:!1}}),this.textCommentToolDarkMode$.value===!1)return;this.textCommentToolDarkMode$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableTextCommentToolDarkMode: ",e)}}enableTextCommentToolbarDarkMode(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableTextCommentToolbarDarkMode","color: green;"),this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{textCommentToolbarDarkMode:!0}}),this.textCommentToolbarDarkMode$.value===!0)return;this.textCommentToolbarDarkMode$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableTextCommentToolbarDarkMode: ",e)}}disableTextCommentToolbarDarkMode(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableTextCommentToolbarDarkMode","color: green;"),this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{textCommentToolbarDarkMode:!1}}),this.textCommentToolbarDarkMode$.value===!1)return;this.textCommentToolbarDarkMode$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableTextCommentToolbarDarkMode: ",e)}}enablePinDarkMode(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enablePinDarkMode","color: green;"),this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{pinDarkMode:!0}}),this.pinDarkMode$.value===!0)return;this.pinDarkMode$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enablePinDarkMode: ",e)}}disablePinDarkMode(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disablePinDarkMode","color: green;"),this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{pinDarkMode:!1}}),this.pinDarkMode$.value===!1)return;this.pinDarkMode$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disablePinDarkMode: ",e)}}disableDialogShadowDOM(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableDialogShadowDOM","color: green;"),this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{dialogShadowDom:!1}}),this.dialogShadowDOM$.value===!1)return;this.dialogShadowDOM$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableDialogShadowDOM: ",e)}}getDialogShadowDOM(){return this.dialogShadowDOM$.value}getDialogShadowDOM$(){return this.dialogShadowDOM$.asObservable()}enableSidebarShadowDOM(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableSidebarShadowDOM","color: green;"),this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{sidebarShadowDOM:!0}}),this.sidebarShadowDOM$.value===!0)return;this.sidebarShadowDOM$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableSidebarShadowDOM: ",e)}}disableSidebarShadowDOM(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableSidebarShadowDOM","color: green;"),this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{sidebarShadowDOM:!1}}),this.sidebarShadowDOM$.value===!1)return;this.sidebarShadowDOM$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableSidebarShadowDOM: ",e)}}getSidebarShadowDOM(){return this.sidebarShadowDOM$.value}getSidebarShadowDOM$(){return this.sidebarShadowDOM$.asObservable()}enableChangeDetectionInCommentMode(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableChangeDetectionInCommentMode","color: green;"),this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{changeDetectionInCommentMode:!0}}),this.changeDetectionInCommentMode$.value===!0)return;this.changeDetectionInCommentMode$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableChangeDetectionInCommentMode: ",e)}}disableChangeDetectionInCommentMode(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableChangeDetectionInCommentMode","color: green;"),this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{changeDetectionInCommentMode:!1}}),this.changeDetectionInCommentMode$.value===!1)return;this.changeDetectionInCommentMode$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableChangeDetectionInCommentMode: ",e)}}getChangeDetectionInCommentMode(){return this.changeDetectionInCommentMode$.value}getChangeDetectionInCommentMode$(){return this.changeDetectionInCommentMode$.asObservable()}showResolvedCommentsOnDom(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{resolvedCommentsOnDom:!0}}),this.resolvedCommentsOnDom$.value===!0)return;this.resolvedCommentsOnDom$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService showResolvedCommentsOnDom: ",e)}}hideResolvedCommentsOnDom(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{resolvedCommentsOnDom:!1}}),this.resolvedCommentsOnDom$.value===!1)return;this.resolvedCommentsOnDom$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService hideResolvedCommentsOnDom: ",e)}}getResolvedCommentsOnDom(){return this.resolvedCommentsOnDom$.value}getResolvedCommentsOnDom$(){return this.resolvedCommentsOnDom$.asObservable()}enableBubbleOnPin(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{bubbleOnPin:!0}}),this.bubbleOnPinEnabled$.value===!0)return;this.bubbleOnPinEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableBubbleOnPin: ",e)}}disableBubbleOnPin(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{bubbleOnPin:!1}}),this.bubbleOnPinEnabled$.value===!1)return;this.bubbleOnPinEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableBubbleOnPin: ",e)}}getBubbleOnPin(){return this.bubbleOnPinEnabled$.value}getBubbleOnPin$(){return this.bubbleOnPinEnabled$.asObservable()}enableBubbleOnPinHover(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{bubbleOnPinHover:!0}}),this.bubbleOnPinHoverEnabled$.value===!0)return;this.bubbleOnPinHoverEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableBubbleOnPinHover: ",e)}}disableBubbleOnPinHover(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{bubbleOnPinHover:!1}}),this.bubbleOnPinHoverEnabled$.value===!1)return;this.bubbleOnPinHoverEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableBubbleOnPinHover: ",e)}}getBubbleOnPinHover(){return this.bubbleOnPinHoverEnabled$.value}getBubbleOnPinHover$(){return this.bubbleOnPinHoverEnabled$.asObservable()}setExcludeLocationIdsFromSidebar(e){try{this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{excludeLocationIdsFromSidebar:e}}),this.excludeLocationIdsFromSidebar$.next(e)}catch(i){this.loggingService.catch("Error in CommentService setExcludeLocationIdsFromSidebar: ",i)}}getExcludeLocationIdsFromSidebar(){return this.excludeLocationIdsFromSidebar$.value}getExcludeLocationIdsFromSidebar$(){return this.excludeLocationIdsFromSidebar$.asObservable()}enableMultiThread(){try{this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{multiThread:!0}}),this.multiThread$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableMultiThread: ",e)}}disableMultiThread(){try{this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{multiThread:!1}}),this.multiThread$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableMultiThread: ",e)}}getMultiThread(){return this.multiThread$.value}getMultiThread$(){return this.multiThread$.asObservable()}enableShortUserName(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableShortUserName","color: green;"),this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{shortUserName:!0}}),this.shortUserName$.value===!0)return;this.shortUserName$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableShortUserName: ",e)}}disableShortUserName(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableShortUserName","color: green;"),this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{shortUserName:!1}}),this.shortUserName$.value===!1)return;this.shortUserName$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableShortUserName: ",e)}}getShortUserName(){return this.shortUserName$.value}getShortUserName$(){return this.shortUserName$.asObservable()}enableRecordingCountdown(){try{this.loggingService.log("%c[WB] Calling FUNCTION: enableRecordingCountdown","color: green;"),this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{recordingCountdown:!0}}),this.recorderService.enableRecordingCountdown()}catch(e){this.loggingService.catch("Error in CommentService enableRecordingCountdown: ",e)}}disableRecordingCountdown(){try{this.loggingService.log("%c[WB] Calling FUNCTION: disableRecordingCountdown","color: green;"),this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{recordingCountdown:!1}}),this.recorderService.disableRecordingCountdown()}catch(e){this.loggingService.catch("Error in CommentService disableRecordingCountdown: ",e)}}setCommentSidebarFilters(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setCommentSidebarFilters","color: green;"),this.commentSidebarFilters$.next(e)}catch(i){this.loggingService.catch("Error in CommentService setCommentSidebarFilters: ",i)}}getCommentSidebarFilters(){return this.commentSidebarFilters$.value}getCommentSidebarFilters$(){return this.commentSidebarFilters$.asObservable()}enableCommentPinHighlighter(){try{this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{commentPinHighlighter:!0}}),this.domService.enableCommentPinHighlighter()}catch(e){this.loggingService.catch("Error in CommentService enableCommentPinHighlighter: ",e)}}disableCommentPinHighlighter(){try{this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{commentPinHighlighter:!1}}),this.domService.disableCommentPinHighlighter()}catch(e){this.loggingService.catch("Error in CommentService disableCommentPinHighlighter: ",e)}}setCustomReactions(e){try{this.reactionService.setCustomReactions(e)}catch(i){this.loggingService.catch("Error in CommentService setCustomReactions: ",i)}}onCommentSelectionChange$(){return this.commentSelectionChange$.asObservable()}onCommentAdd$(){return this.commentAdded$.asObservable()}onCommentUpdate$(){return this.commentUpdated$.asObservable()}onCommentAnnotationDelete$(){return this.commentAnnotationDeleted$.asObservable()}onMultiThreadCommentAnnotationDelete$(){return this.multiThreadCommentAnnotationDeleted$.asObservable()}getCommentMode(){try{let e="freestyle";return this.getStreamMode()?e="stream":this.getPopoverMode()&&(e="popover"),e}catch(e){return this.loggingService.catch("Error in CommentService getCommentMode: ",e),"freestyle"}}getCommentType(e){try{return e.targetElement?"element":e.targetTextRange?"text":e.areaAnnotationId?"area":""}catch(i){return this.loggingService.catch("Error in CommentService getCommentType: ",i),""}}getCommentAnnotationAvailableOnXPath(e,i,r){try{return this.commentAnnotationById$.pipe(ge(()=>this.draftCommentAnnotationsByAnnotationId$),ge(a=>(!r&&i&&(r=cr(i,["id","data-id"])),re(T(I({},a),{element:r})))),ge(a=>this.getLocations$().pipe(ce(s=>T(I({},a),{locationIds:s})))),ce(({locationIds:a,element:s})=>{let c=[],p=this.docService.getDocumentPaths();if(p?.documentId){let h=this.docService.getAdditionalDocumentIdFromElement(s),_=h?this.docService.generateDocumentId(h):p?.documentId,E=this.getCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:p?.organizationId,documentId:_||""});if(E)for(let D of E)(i&&D?.targetElementId===i||D?.targetElement?.xpath===e)&&a?.includes(D?.locationId)&&c.push(D)}return c.length?c:null}))}catch(a){return this.loggingService.catch("Error in CommentService isCommentAnnotationAvailableOnXPath: ",a),re(null)}}getCommentAnnotationByAnnotationId(e){try{return this.commentAnnotationById$.pipe(ce(()=>this.getAnnotationById(e)),ge(i=>i?i?.iam?.accessMode===Ki.PRIVATE?this.iamService.isUserAdmin$().pipe(ce(r=>{if(r)return i})):re(i):re(i)))}catch(i){return this.loggingService.catch("Error in CommentService getCommentAnnotationByAnnotationId: ",i),re(void 0)}}getMultiThreadCommentAnnotationByAnnotationId(e){return this.multiThreadCommentAnnotationById$.pipe(ce(()=>this.getMultiThreadAnnotationById(e)))}getCommentBubbleElement(e){try{let i=document.querySelector(`${U.TAGS.VELT_COMMENT_BUBBLE}[${U.ATTRIBUTES.VELT_ANNOTATION_IDS}*="${e?.annotationId}"]`);return i||(i=document.querySelector(`${U.TAGS.SNIPPYLY_COMMENT_BUBBLE}[${U.ATTRIBUTES.VELT_ANNOTATION_IDS}*="${e?.annotationId}"]`)),i}catch(i){return this.loggingService.catch("Error in CommentService getCommentBubbleElement: ",i),null}}getCommentAnnotationsBySectionId(e){try{return this.commentAnnotationById$.pipe(ge(()=>this.docService.getDocumentPaths$().pipe(ce(i=>({documentPaths:i,sectionId:e})))),ge(i=>{let r=cr(e,["id","data-id"]);if(r){let a=this.docService.getAdditionLocationFromElement(r);if(a){let s=this.docService.genarateLocationId(a);return this.docService.getLocations$().pipe(ce(c=>{let h=Object.values(c||{}).find(_=>_.locationId===s||a?.id&&_.location.id===a.id);return T(I({},i),{additionalLocation:h,locationOnElement:!!a})}))}}return re(T(I({},i),{additionalLocation:null,element:r}))}),ge(i=>i?.locationOnElement?re(i):this.docService.getLocation$().pipe(ce(r=>T(I({},i),{location:r})))),ce(({documentPaths:i,location:r,additionalLocation:a,locationOnElement:s,element:c})=>{let p=null;if(this.authService.getUser()&&i?.documentId){let _=this.docService.getAdditionalDocumentIdFromElement(c),E=_?this.docService.generateDocumentId(_):i?.documentId,D=this.getCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:i?.organizationId,documentId:E||""});if(D){p=[];let B=om(e);s?a?.location?.id?B=om([a?.location?.id,e]):a?.locationId&&(B=om([a?.locationId+"",e])):r&&(r?.location?.id?B=om([r?.location?.id,e]):r?.locationId&&(B=om([r?.locationId+"",e])));for(let G of D)G?.multiThreadAnnotationId===B?p.push(G):(G?.targetInlineCommentElementId===e||G?.targetElementId===e)&&(s?a&&Ou({location:a?.location,locationId:a?.locationId},{location:G.location,locationId:G.locationId})&&p.push(G):r?Ou({location:r?.location,locationId:r?.locationId},{location:G.location,locationId:G.locationId})&&p.push(G):G?.locationId||p.push(G))}}return p}))}catch(i){return this.loggingService.catch("Error in CommentService getCommentAnnotationsBySectionId: ",i),re(null)}}getCommentAnnotationsByMultiThreadAnnotationId(e){try{return this.commentAnnotationById$.pipe(ge(()=>this.multiThreadCommentAnnotationById$),ge(()=>this.docService.getDocumentPaths$().pipe(ce(i=>({documentPaths:i,multiThreadAnnotationId:e})))),ce(({documentPaths:i,location:r,additionalLocation:a,locationOnElement:s})=>{let c=null;if(i?.documentId){let p=this.getMultiThreadAnnotationById(e),{documentId:h,organizationId:_}=p?.metadata||{documentId:i?.documentId,organizationId:i?.organizationId},E=this.getCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:_,documentId:h||""});if(E){c=[];for(let D of E)D?.multiThreadAnnotationId===e&&p?.commentAnnotations?.[D?.annotationId]&&c.push(D)}}return c}))}catch(i){return this.loggingService.catch("Error in CommentService getCommentAnnotationsBySectionId: ",i),re(null)}}get timestamp(){return this.commonDbService.getServerTimestamp()}isElementInsideAllowedElements(e){try{return this.allowedElementIds$.value?.length||this.allowedElementClassNames$.value?.length||this.allowedElementQuerySelectors$.value?.length?!!(this.allowedElementIds$.value?.length&&this.domService.isElementInsideListedElementIds(e,this.allowedElementIds$.value)||this.allowedElementClassNames$.value?.length&&this.domService.isElementInsideListedElementClassNames(e,this.allowedElementClassNames$.value)||this.allowedElementQuerySelectors$.value?.length&&this.domService.isElementInsideListedElementQuerySelectors(e,this.allowedElementQuerySelectors$.value)):!0}catch(i){return this.loggingService.catch("Error in CommentService isElementInsideAllowedElements: ",i),!1}}getNearestAllowedElement(e){try{let i=this.domService.getListedElements({elementIds:this.allowedElementIds$.value,elementClassNames:this.allowedElementClassNames$.value,elementQuerySelectors:this.allowedElementQuerySelectors$.value});if(i?.length){for(let r=0;r<i.length;r++){let a=i[r];if(e.contains(a))return a}return null}return null}catch(i){return this.loggingService.catch("Error in CommentService getNearestAllowedElement: ",i),null}}isElementInsideManualCommentContainer(e){try{return this.domService.isElementInsideParentWithAttribute(e,U.ATTRIBUTES.VELT_MANUAL_COMMENT_CONTAINER,"true")}catch(i){return this.loggingService.catch("Error in CommentService isElementInsideManualCommentContainer: ",i),!1}}saveComment(e,i){return ee(this,null,function*(){try{i?.annotation&&(e=i.annotation),e&&(e=JSON.parse(JSON.stringify(e)));let r=this.originalCommentAnnotationsByDocumentId$.value[e.annotationId];if(r?.comments?.length){let _=JSON.parse(JSON.stringify(e.comments||[]));e.comments=[],r.comments?.forEach(E=>{let D=_.find(B=>B.commentId===E.commentId);D?e.comments.push(D):e.comments.push(E)})}e.comments||(e.comments=[]);let a=!1,s=!1,c;switch(i.type){case jt.NEWLY_ADDED:case jt.ADDED:if(!i.updatedComment)break;e?.comments?.length||(s=!0),e.comments.push(i.updatedComment);let _=i?.assigned||void 0;c={commentAnnotation:e,targetComment:i.updatedComment,actionType:i.type,otherFields:{assigned:_}};break;case jt.APPROVED:e.approved=!0,c={commentAnnotation:e,targetComment:null,actionType:jt.APPROVED};break;case jt.ASSIGNED:e.assignedTo=i.assignedTo,c={commentAnnotation:e,targetComment:null,actionType:jt.ASSIGNED};break;case jt.UPDATED:if(!i.updatedComment)break;let E=e.comments.findIndex(Ie=>Ie.commentId===i.updatedComment.commentId);if(E>=0){e.comments[E]=i.updatedComment,e.comments[E].status=jt.UPDATED;let Ie=i?.assigned||void 0;c={commentAnnotation:e,targetComment:i.updatedComment,actionType:jt.UPDATED,otherFields:{assigned:Ie}}}break;case jt.REACTION_ADDED:if(!i.updatedComment)break;let D=e.comments.findIndex(Ie=>Ie.commentId===i.updatedComment.commentId);D>=0&&(e.comments[D]=i.updatedComment,e.comments[D].status=jt.UPDATED,c={commentAnnotation:e,targetComment:i.updatedComment,actionType:jt.REACTION_ADDED});break;case jt.REACTION_DELETED:if(!i.updatedComment)break;let B=e.comments.findIndex(Ie=>Ie.commentId===i.updatedComment.commentId);B>=0&&(e.comments[B]=i.updatedComment,e.comments[B].status=jt.UPDATED,c={commentAnnotation:e,targetComment:i.updatedComment,actionType:jt.REACTION_DELETED});break;case jt.STATUS_CHANGED:e.status.type==="terminal"&&(this.domService.resetSelectedAnnotationsMap(!1,"comment"),e.resolvedByUserId=this.authService.getUser()?.userId),c={commentAnnotation:e,targetComment:null,actionType:jt.STATUS_CHANGED,otherFields:{oldStatus:i.oldStatus,newStatus:i.newStatus}};break;case jt.PRIORITY_CHANGED:c={commentAnnotation:e,targetComment:null,actionType:jt.PRIORITY_CHANGED,otherFields:{oldPriority:i.oldPriority,newPriority:i.newPriority}};break;case jt.ACCESS_MODE_CHANGED:c={commentAnnotation:e,targetComment:null,actionType:jt.ACCESS_MODE_CHANGED,otherFields:{oldAccessMode:i.oldAccessMode,newAccessMode:i.newAccessMode}};break;case jt.CUSTOM_LIST_CHANGED:c={commentAnnotation:e,targetComment:null,actionType:jt.CUSTOM_LIST_CHANGED,otherFields:{oldCustomList:i.oldCustomList,newCustomList:i.newCustomList}};break;case jt.SUBSCRIBED:c={commentAnnotation:e,targetComment:null,actionType:jt.SUBSCRIBED};break;case jt.UNSUBSCRIBED:c={commentAnnotation:e,targetComment:null,actionType:jt.UNSUBSCRIBED};break;case jt.DELETED:if(!i.updatedComment)break;let G=e.comments.findIndex(Ie=>Ie.commentId===i.updatedComment.commentId);if(G>=0){if((G===0&&this.deleteThreadWithFirstComment$.value!==!1||this.deleteReplyConfirmation$.value)&&!i.skipDeleteThreadConfirmation){let Le={};if(this.deleteReplyConfirmation$.value&&(G!==0||this.deleteThreadWithFirstComment$.value===!1)?Le={title:"Delete comment?",message:"This selected comment will be deleted.",yesButton:"Delete",noButton:"Cancel",darkMode:this.commentContainerDarkMode$.value,variant:"reply"}:Le={title:"Delete thread?",message:"All replies to this thread will be lost.",yesButton:"Delete",noButton:"Cancel",darkMode:this.commentContainerDarkMode$.value,variant:"comment"},!(yield this.dialog.open(da,{data:Le}).afterClosed().toPromise()))return}let Ie=e.comments.splice(G,1),Me=e.metadata;Ie?.length&&Ie.forEach(Le=>{Le?.attachments&&Le.attachments.forEach(We=>{let ke={attachmentId:We.attachmentId,organizationId:Me?.organizationId??null,documentId:Me?.documentId??null,folderId:Me?.folderId??null,commentAnnotationId:e.annotationId,apiKey:Me?.apiKey??null};this.deleteAttachment({attachment:We,metadata:ke})}),Le?.reactionAnnotationIds&&Le.reactionAnnotationIds.forEach(We=>{this.deleteReaction(We)})})}e.status=this.customFilterService.defaultStatus,G===0&&this.deleteThreadWithFirstComment$.value!==!1||e.comments?.length===0?a=!0:(this.analyticsService.trackEvent(Z.Events.Comments.COMMENT_THREAD_DELETED,{annotationId:e.annotationId,commentThreadId:i.updatedComment.commentId,commentMode:this.getCommentMode()}),c={commentAnnotation:e,targetComment:i.updatedComment,actionType:jt.DELETED});break;case jt.ACCEPTED:let X={annotationId:e.annotationId,actionUser:this.authService.getUser(),actionType:jt.ACCEPTED,replaceContentHtml:e?.comments?.length?e?.comments[0]?.replaceContentHtml:void 0,replaceContentText:e?.comments?.length?e?.comments[0]?.replaceContentText:void 0,annotation:$n(e)};this.commentAccepted$.next(X),c={commentAnnotation:e,targetComment:null,actionType:jt.ACCEPTED};break;case jt.REJECTED:let he={annotationId:e.annotationId,actionUser:this.authService.getUser(),actionType:jt.REJECTED,replaceContentHtml:e?.comments?.length?e?.comments[0]?.replaceContentHtml:void 0,replaceContentText:e?.comments?.length?e?.comments[0]?.replaceContentText:void 0,annotation:$n(e)};this.commentRejected$.next(he),this.domService.resetSelectedAnnotationsMap(),c={commentAnnotation:e,targetComment:null,actionType:jt.REJECTED};break;default:break}e.resolvedByUserId&&e.status.type!=="terminal"&&(e.resolvedByUserId=null),i?.updatedComment?.isDraft&&(c=void 0),a?(this.deleteCommentPinAnnotation(e,!0),this.domService.resetSelectedAnnotationsMap(!1,"comment")):(s&&e.comments?.length&&this.enableAutoCategorize$?.value&&this.setCommentCategory(e),this.updateComment(e,!1,!1,c,!0),e?.multiThreadAnnotationId&&(i.type===jt.ADDED||i.type===jt.NEWLY_ADDED)&&e.comments?.length===1?setTimeout(()=>{this.domService.resetSelectedAnnotationsMap(!1,"comment")},100):this.domService.updateSelectedAnnotationInMap([e]));let p=this.getCustomPinById(e.annotationId),h={type:i.type,annotation:$n(e),targetAnnotationId:e.annotationId,targetCommentId:i.updatedComment?.commentId,updateContext:(_,E)=>{this.updateCommentAnnotationContext(e.annotationId,_,E)}};p!==void 0&&(h.element=p),delete h?.annotation?.pageInfo,delete h?.annotation?.targetElement,delete h?.annotation?.targetTextRange,h?.type===jt.DELETED&&(e.comments?.length||(h.annotation=null)),a||this.commentUpdated$.next(h)}catch(r){this.loggingService.catch("Error in CommentService saveComment: ",r)}})}attachComment(e,i=[],r){try{this.loggingService.log("%c[WB] Calling FUNCTION: attachComment","color: green;");let a=cr(e,i);if(a){let c={targetElement:{xpath:this.domService.getXPath(a),topPercentage:50,leftPercentage:90},targetElementId:e};this.addComment(void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,c,void 0,void 0,void 0,r)}}catch(a){this.loggingService.catch("Error in CommentService attachComment: ",a)}}updateNotificationsDatabase(e,i,r,a={}){try{let s=I({annotationData:e,targetAnnotationData:i,actionType:r,notificationSource:"comment"},a);this.notificationService.updateNotificationDatabase(s)}catch(s){this.loggingService.catch("Error in CommentService updateNotificationsDatabase: ",s)}}getUserContacts$(){return this.contactService.getUserContacts$()}addUserContact(e){this.contactService.addUserContact(e)}getElementFromComment(e){try{let i=null;if(e?.ghostComment)!i&&e.ghostComment?.targetElement?.fXpath&&(i=this.domService.getElementFromXPath(e.ghostComment?.targetElement?.fXpath),i&&!this.domService.isElementVisible(i)&&(i=null)),!i&&e.ghostComment?.targetElement?.cfXpath&&(i=this.domService.getElementFromXPath(e.ghostComment?.targetElement?.cfXpath),i&&!this.domService.isElementVisible(i)&&(i=null)),!i&&e.ghostComment?.targetElement?.xpath&&(i=this.domService.getElementFromXPath(e.ghostComment?.targetElement?.xpath),i&&!this.domService.isElementVisible(i)&&(i=null));else{let r=!1;!i&&e?.targetElement?.xpath&&(r=this.domService.isXpathWithId(e?.targetElement?.xpath),i=this.domService.getElementFromXPath(e?.targetElement?.xpath),i&&!this.domService.isElementVisible(i)&&(i=null)),r||(!i&&e?.targetElement?.cfXpath&&(i=this.domService.getElementFromXPath(e?.targetElement?.cfXpath),i&&!this.domService.isElementVisible(i)&&(i=null)),!i&&e?.targetElement?.fXpath&&(i=this.domService.getElementFromXPath(e?.targetElement?.fXpath),i&&!this.domService.isElementVisible(i)&&(i=null)))}return i&&!xo(i)&&(i=null),i}catch(i){return this.loggingService.catch("Error in CommentService getElementFromComment: ",i),null}}getElementFromComments(e){try{let i=[],r=null;if(e?.ghostComment)!r&&e.ghostComment?.targetElement?.fXpath&&(r=this.domService.getElementFromXPath(e.ghostComment?.targetElement?.fXpath),r&&!this.domService.isElementVisible(r)&&(r=null)),!r&&e.ghostComment?.targetElement?.cfXpath&&(r=this.domService.getElementFromXPath(e.ghostComment?.targetElement?.cfXpath),r&&!this.domService.isElementVisible(r)&&(r=null)),!r&&e.ghostComment?.targetElement?.xpath&&(r=this.domService.getElementFromXPath(e.ghostComment?.targetElement?.xpath),r&&!this.domService.isElementVisible(r)&&(r=null));else{let a=!1;!r&&e?.targetElement?.xpath&&(a=this.domService.isXpathWithId(e?.targetElement?.xpath),r=this.domService.getElementFromXPath(e?.targetElement?.xpath),r&&!this.domService.isElementVisible(r)&&(r=null)),a||(!r&&e?.targetElement?.cfXpath&&(r=this.domService.getElementFromXPath(e?.targetElement?.cfXpath),r&&!this.domService.isElementVisible(r)&&(r=null)),!r&&e?.targetElement?.fXpath&&(r=this.domService.getElementFromXPath(e?.targetElement?.fXpath),r&&!this.domService.isElementVisible(r)&&(r=null)))}return r&&!xo(r)&&(r=null),e?.targetElementId&&(i=Array.from(Uie(e.targetElementId,["id","data-id"]))),r&&!i.includes(r)&&i.push(r),i}catch(i){return this.loggingService.catch("Error in CommentService getElementFromComment: ",i),[]}}getGhostCommentTargetElement(e){try{let i=e.targetElement?.fXpath||e.targetElement?.xpath,r=null;if(i)for(;!r&&i;)r=this.domService.getElementFromXPath(i),r&&(!this.domService.isElementVisible(r)||!xo(r))&&(r=null),r||(i=i.substring(0,i.lastIndexOf("/")));return i==="/"&&(i=""),i?{xpath:i,topPercentage:e?.targetElement?.topPercentage||0,leftPercentage:e?.targetElement?.leftPercentage||0}:null}catch(i){return this.loggingService.catch("Error in CommentService getGhostCommentTargetElement: ",i),null}}setGhostCommentMessage(e){try{if(e?.ghostComment){e.ghostComment.message="Original content not found.",e.ghostComment.type=Us.ELEMENT_DELETED;let i=e?.pageInfo?.deviceInfo?.deviceType,r=new Jn().getDeviceType();i&&i!==r&&(e.ghostComment.type=Us.DIFFERENT_DEVICE,e.ghostComment.message=`Original comment was added on ${i}.`,[Zo.MOBILE,Zo.TABLET].includes(i)&&[Zo.MOBILE,Zo.TABLET].includes(r)||[Zo.DESKTOP,Zo.MONITOR].includes(i)&&[Zo.DESKTOP,Zo.MONITOR].includes(r)?e.ghostComment.isSameGroup=!0:e.ghostComment.isSameGroup=!1)}}catch(i){this.loggingService.catch("Error in CommentService setGhostCommentMessage: ",i)}}addAnnotationToGhostCommentAnnotationMap(e){try{let i=this.ghostCommentAnnotationMap$.value||{},r=i[e?.annotationId]||{};Co(e.ghostComment,r)||(i[e?.annotationId]=e.ghostComment,this.ghostCommentAnnotationMap$.next(i))}catch(i){this.loggingService.catch("Error in CommentService addAnnotationToGhostCommentAnnotationMap: ",i)}}removeAnnotationFromGhostCommentAnnotationMap(e){try{let i=this.ghostCommentAnnotationMap$.value||{};i[e?.annotationId]&&(delete i[e?.annotationId],this.ghostCommentAnnotationMap$.next(i))}catch(i){this.loggingService.catch("Error in CommentService removeAnnotationFromGhostCommentAnnotationMap: ",i)}}getGhostCommentAnnotationMap$(){return this.ghostCommentAnnotationMap$.asObservable()}getGhostCommentAnnotationMap(){return this.ghostCommentAnnotationMap$.value||{}}getUnreadCommentsMap$(){return this.unreadCommentsMap$.asObservable().pipe(Kt(_o))}getUnreadCommentsMap(){return this.unreadCommentsMap$.value}getUnreadCommentCountByAnnotationId$(e){return this.getUnreadCommentsMap$().pipe(ce(i=>i?{count:i[e]||0}:null))}getUnreadCommentAnnotationCountOnCurrentDocument$(){return this.getUnreadCommentsMap$().pipe(ce(e=>e?{count:Object.keys(e??{}).length||0}:null))}getUnreadCommentCountOnCurrentDocument$(){return this.getUnreadCommentsMap$().pipe(ce(e=>e?{count:Object.values(e).reduce((r,a)=>r+a,0)}:null))}getUnreadCommentCountByLocationId$(e){return this.getUnreadCommentsMap$().pipe(ce(i=>{if(i){let r=this.docService.getDocumentPaths(),a=[],s=0;return r?.documentId&&(a=this.getCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:r?.organizationId,documentId:r?.documentId}),a&&Object.keys(i).forEach(c=>{a?.find(h=>h.annotationId===c)?.location?.id===e&&(s+=i[c])})),{count:s}}else return null}))}getUnreadCommentAnnotationCountByLocationId$(e){return this.getUnreadCommentsMap$().pipe(ce(i=>{if(i){let r=this.docService.getDocumentPaths(),a=[],s=0;return r?.documentId&&(a=this.getCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:r?.organizationId,documentId:r?.documentId}),Object.keys(i).forEach(c=>{i[c]&&a?.find(h=>h.annotationId===c)?.location?.id===e&&(s+=1)})),{count:s}}else return null}))}setCommentAnnotationsAsRead(e){try{for(let i of e)this.viewsService.setCommentAnnotationAsRead(i)}catch(i){this.loggingService.catch("Error in CommentService setCommentAnnotationsAsRead: ",i)}}setCommentAnnotationsAsResolved(e){try{let i=this.customFilterService.resolvedStatus;if(i){for(let r of e)if(i?.id!==r?.status?.id){let a=JSON.parse(JSON.stringify(r||{}));r.status=this.customFilterService.resolvedStatus;let s={annotation:r,type:jt.STATUS_CHANGED,oldStatus:a.status,newStatus:this.customFilterService.resolvedStatus};this.saveComment(r,s)}}}catch(i){this.loggingService.catch("Error in CommentService setCommentAnnotationsAsResolved: ",i)}}updateCommentDialogPosition(){try{this.updateCommentDialogPositionTriggerSubject$.next()}catch(e){this.loggingService.catch("Error in CommentService updateCommentDialogPosition: ",e)}}updateCommentDialogPositionTrigger$(){return this.updateCommentDialogPositionTriggerSubject$.asObservable()}enableAreaComment(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{areaComment:!0}}),this.areaCommentEnabled$.value===!0)return;this.areaCommentEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableAreaComment: ",e)}}disableAreaComment(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{areaComment:!1}}),this.areaCommentEnabled$.value===!1)return;this.areaCommentEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableAreaComment: ",e)}}getAreaCommentEnabled$(){return this.areaCommentEnabled$.asObservable()}getAreaCommentEnabled(){return this.areaCommentEnabled$.value}setPinCursorImage(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setPinCursorImage","color: green;"),e&&(e=`url(${e}) 0 31, auto`),this.commentPinCursorImage$.next(e)}catch(i){this.loggingService.catch("Error in CommentService setPinCursorImage: ",i)}}getPinCursorImage$(){return this.commentPinCursorImage$.asObservable()}getPinCursorImage(){return this.commentPinCursorImage$.value}setCommentAnnotationsFromCommentsContainer(e){try{this.commentAnnotationsFromCommentsContainer$.next(e)}catch(i){this.loggingService.catch("Error in CommentService setCommentAnnotationsFromCommentsContainer: ",i)}}getCommentAnnotationsFromCommentsContainer$(){return this.commentAnnotationsFromCommentsContainer$.asObservable()}getCommentAnnotationsFromCommentsContainer(){return this.commentAnnotationsFromCommentsContainer$.value}addManualComment(e){return ee(this,null,function*(){try{return this.loggingService.log("%c[WB] Calling FUNCTION: addManualComment","color: green;"),new Promise((i,r)=>{let a=this.domService.getLastDocumentClick()?.target,s=e?.location||this.docService.getAdditionLocationFromElement(a);if(s?.id){let c=this.docService.getLocationByClientLocationId(s.id);c&&(s=c)}this.addComment(void 0,void 0,void 0,void 0,void 0,void 0,void 0,s,void 0,e,void 0,void 0,void 0,c=>{i(c)}),this.addCommentMode$?.value&&!this.persistentCommentMode$?.value&&this.disableAddCommentMode()})}catch(i){return this.loggingService.catch("Error in CommentService addManualComment: ",i),null}})}getCommentUrl(e){try{return e?.pageInfo?.commentUrl?e.pageInfo.commentUrl:(e?.pageInfo||(e.pageInfo=_i(),e.pageInfo&&(e.pageInfo.screenWidth=this.domService.getCurrentWindowSizeValue()?.screenWidth)),e.pageInfo.commentUrl=this.generateCommentUrl(e),this.updateComment(e),e.pageInfo?.commentUrl)}catch(i){this.loggingService.catch("Error in CommentService getCommentUrl: ",i);return}}uploadFile(e,i){let r=`${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentPaths?.documentId}/${U.FIREBASE_PARTIAL_PATH_COMMENT}/${i.annotationId}`;this.documentPaths?.organizationId&&(r=`${U.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${this.documentPaths.organizationId}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentPaths?.documentId}/${U.FIREBASE_PARTIAL_PATH_COMMENT}/${i.annotationId}`);let a={organizationId:i.metadata?.clientOrganizationId??null,documentId:i.metadata?.clientDocumentId??null,commentAnnotationId:i.annotationId,apiKey:i.metadata?.apiKey??null,folderId:i.metadata?.folderId??null,attachmentId:null};return this.storageService.uploadFile({path:r,file:e,metadata:a,useAttachmentResolver:this.attachmentResolverService.attachmentDataProviderAvailable()})}downloadAttachment(e){this.storageService.downloadAttachment(e)}deleteAttachment({attachment:e,metadata:i}){return this.storageService.deleteAttachment({attachment:e,metadata:i,useAttachmentResolver:this.attachmentResolverService.attachmentDataProviderAvailable()})}deleteReaction(e){try{this.reactionService.deleteReactionPinAnnotation(e)}catch(i){this.loggingService.catch("Error in CommentService deleteReaction: ",i)}}generateCommentUrl(e){let i=new URL(window.location.href);return i.searchParams.delete(U.URL_PARAMS.COMMENT_ID),i.searchParams.append(U.URL_PARAMS.COMMENT_ID,e.annotationId),i.href}getCustomPinById(e){if(this.customPinsById.has(e))return this.customPinsById.get(e)}setCustomStatuses(e){try{if(e===void 0)return;this.customStatusesShown$.next(!0),this.customFilterService.setCustomStatusFilters(e)}catch(i){this.loggingService.catch("Error in CommentService setCustomStatuses: ",i)}}getCustomStatusesShown$(){return this.customStatusesShown$.asObservable()}getCustomStatusesShown(){return this.customStatusesShown$.value}setCustomPriorities(e){try{if(e===void 0)return;this.customFilterService.setCustomPriorityFilters(e)}catch(i){this.loggingService.catch("Error in CommentService setCustomPriorities: ",i)}}setCustomCategories(e){try{if(e===void 0)return;this.customFilterService.setCustomCategories(e)}catch(i){this.loggingService.catch("Error in CommentService setCustomCategories: ",i)}}addCommentOnSelectedText(){try{let e=this.authService.getUser();if(this.textCommentMode$.value&&e&&!(e?.isReadOnly||e?.isAnonymous)&&this.authService.isFeatureAllowed(Re.COMMENT)){let i=this.domService.getRange();if(window.getSelection()?.toString()&&!ZO()&&i?.commonAncestorContainer&&this.isElementInsideAllowedElements(i.commonAncestorContainer)&&!fd(i.commonAncestorContainer)){let r=i?this.domService.getTargetTextRangeFromSelectionRange(i):void 0;this.domService.clearTextSelection(),setTimeout(()=>{this.addComment(void 0,r)},100)}}}catch(e){this.loggingService.catch("Error in CommentService addCommentOnSelectedText: ",e)}}getInlineCommentSectionConfig(e){try{let i;if(e){let r=e?.closest(`[${U.ATTRIBUTES.VELT_TARGET_INLINE_COMMENT_ELEMENT_ID}]`);if(r){let a=r.getAttribute(U.ATTRIBUTES.VELT_TARGET_INLINE_COMMENT_ELEMENT_ID);a&&(i={},i.targetInlineCommentElementId=a,r.getAttribute(U.ATTRIBUTES.VELT_INLINE_COMMENT_SECTION_CONFIG)&&(i.config=JSON.parse(r.getAttribute(U.ATTRIBUTES.VELT_INLINE_COMMENT_SECTION_CONFIG)||"{}")))}}return i}catch(i){this.loggingService.catch("Error in CommentService getInlineCommentSectionConfig: ",i)}}createCustomListDataOnAnnotation(e){try{if(e===void 0)return;this.customChipDropdownData$.next(e)}catch(i){this.loggingService.catch("Error in CommentService createCustomListDataOnAnnotation: ",i)}}getCustomChipDropdownData$(){return this.customChipDropdownData$.asObservable()}getCustomChipDropdownData(){return this.customChipDropdownData$.value}setSubscribedUsersDataInCommentAnnotation(e){try{let i={},r=e?.unsubscribedUsers||{},a={};if(e?.subscribedUsers&&Object.keys(e.subscribedUsers||{}).forEach(s=>{let c=e.subscribedUsers?.[s];c?.type==="manual"&&(i[s]=c)}),e?.assignedTo?.userId){let s=Rt(e?.assignedTo?.userId);r[s]||i[s]?.type!=="manual"&&(i[s]={user:e?.assignedTo,type:"auto"})}e?.comments?.filter(s=>!s?.isDraft)?.forEach(s=>{if(s?.from?.userId){let c=Rt(s?.from?.userId);r[c]||i[c]?.type!=="manual"&&(i[c]={user:s?.from,type:"auto"})}s?.to?.forEach(c=>{if(c?.userId){let p=Rt(c.userId);r[p]||i[p]?.type!=="manual"&&(i[p]={user:c,type:"auto"})}}),s?.toOrganizationUserGroup?.forEach(c=>{if(c?.groupId)a[c?.groupId]={type:"auto"};else if(c?.clientGroupId){let p=Rt(c.clientGroupId);a[p]={type:"auto"}}})}),e.subscribedUsers=i,e.unsubscribedUsers=r,e.subscribedGroups=a}catch(i){this.loggingService.catch("Error in CommentService setSubscribeUsersDataInCommentAnnotation: ",i)}}getCopyLink$(){return this.copyLink$.asObservable()}setCopyLink(e){try{this.copyLink$.next(e)}catch(i){this.loggingService.catch("Error in CommentService setCopyLink: ",i)}}getCommentAnnotationById(e){return this.commentAnnotationById$.pipe(ge(()=>{let{annotationId:i,documentId:r}=e;if(r){let a=fn(r).toString();return this.getDataCommentAnnotationsFromDocumentId(a).pipe(ce(s=>s.find(p=>p.annotationId===i)||null))}else{let a=this.docService.getDocumentPaths();if(a?.documentId){let s=this.getCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:a?.organizationId,documentId:a?.documentId});if(s){let c=s.find(p=>p.annotationId===i);return re(c||null)}}}return re(null)}),Ln(i=>(this.loggingService.catch("Error in CommentService getCommentAnnotationById: ",i),re(null))))}getDataCommentAnnotationsFromDocumentId(e){return this.configService?.getApiKey()?this.commonDbService.dbListener({feature:"allComments",properties:{documentId:e||this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,isCollection:!0}}).pipe(ce(i=>i?.data),ce(i=>{let r=[];return i&&(r=Object.values(i??{}).filter(a=>typeof a=="object")),r})):re([])}enableCollapsedComments(){try{this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{collapsedComments:!0}}),this.collapsedComments$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableCollapsedComments: ",e)}}disableCollapsedComments(){try{this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{collapsedComments:!1}}),this.collapsedComments$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableCollapsedComments: ",e)}}getCollapsedComments$(){return this.collapsedComments$.asObservable()}enableFullExpanded(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{fullExpanded:!0}}),this.fullExpanded$.value===!0)return;this.fullExpanded$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableFullExpanded: ",e)}}disableFullExpanded(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{fullExpanded:!1}}),this.fullExpanded$.value===!1)return;this.fullExpanded$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableFullExpanded: ",e)}}getFullExpanded$(){return this.fullExpanded$.asObservable()}getFullExpanded(){return this.fullExpanded$.value}setSidebarCustomActionEventData(e,i,r,a){try{this.sidebarCustomActionEventData$.next({actions:e,data:i,unreadDataMap:r,systemFilteredData:a})}catch(s){this.loggingService.catch("Error in CommentService emitOnSidebarCustomAction: ",s)}}getSidebarCustomActionEventData(){return this.sidebarCustomActionEventData$.asObservable()}setCommentSidebarData(e,i){try{this.sidebarData$.next({data:e,options:i})}catch(r){this.loggingService.catch("Error in CommentService setCommentSidebarData: ",r)}}getSidebarCustomData(){return this.sidebarData$.asObservable()}setSidebarCustomActionEventDataAllChanges(e,i,r,a){return ee(this,null,function*(){try{this.sidebarCustomActionEventDataAllChanges$.next({actions:e,data:i,unreadDataMap:r,systemFilteredData:a});let s=yield this.metadataService.getGlobalMetadata(),c={buttonContext:{selections:this.buttonService.buttonToggleMapValue()},unreadCommentAnnotationsMap:r,commentAnnotations:i,systemFilteredAnnotations:a,metadata:s};this.commentActionsService?.triggerAction(Yi.COMMENT_SIDEBAR_DATA_UPDATE,c)}catch(s){this.loggingService.catch("Error in CommentService setSidebarCustomActionEventDataAllChanges: ",s)}})}setSidebarCustomActionEventDataOnInit(e,i,r,a){return ee(this,null,function*(){try{this.sidebarCustomActionEventDataOnInit$.next({actions:e,data:i,unreadDataMap:r,systemFilteredData:a});let c={metadata:yield this.metadataService.getGlobalMetadata(),unreadCommentAnnotationsMap:r,commentAnnotations:i,systemFilteredAnnotations:a,buttonContext:{selections:this.buttonService.buttonToggleMapValue()}};this.commentActionsService?.triggerAction(Yi.COMMENT_SIDEBAR_DATA_INIT,c)}catch(s){this.loggingService.catch("Error in CommentService setSidebarCustomActionEventDataOnInit: ",s)}})}getSidebarCustomActionEventDataAllChanges(){return this.sidebarCustomActionEventDataAllChanges$.asObservable()}getSidebarCustomActionEventDataOnInit(){return this.sidebarCustomActionEventDataOnInit$.asObservable()}getSidebarCustomActionEventDataOnInitValue(){return this.sidebarCustomActionEventDataOnInit$.getValue()}setTransformContext(e){try{e?Co(this.transformContext$.value,e)||this.transformContext$.next(e):this.transformContext$.next(null)}catch(i){this.loggingService.catch("Error in CommentService setTransformContext: ",i)}}getTransformContext$(){return this.transformContext$.asObservable()}getTransformContext(){return this.transformContext$.value}enableSidebarCustomActions(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{customActions:!0}}),this.customActions$.value===!0)return;this.customActions$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableSidebarCustomActions: ",e)}}disableSidebarCustomActions(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{customActions:!1}}),this.customActions$.value===!1)return;this.customActions$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableSidebarCustomActions: ",e)}}getSidebarCustomActionsValue(){return this.customActions$.getValue()}enableQueryParamsComments(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{queryParamsComments:!0}}),this.queryParamsComments$.value===!0)return;this.queryParamsComments$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableQueryParamsComments: ",e)}}disableQueryParamsComments(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{queryParamsComments:!1}}),this.queryParamsComments$.value===!1)return;this.queryParamsComments$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableQueryParamsComments: ",e)}}getQueryParamsComments$(){return this.queryParamsComments$.asObservable()}getQueryParamsComments(){return this.queryParamsComments$.value}enableResolveStatusAccessAdminOnly(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{resolveStatusAccessAdminOnly:!0}}),this.resolveStatusAccessAdminOnly$.value===!0)return;this.resolveStatusAccessAdminOnly$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableResolveStatusAccessAdminOnly: ",e)}}disableResolveStatusAccessAdminOnly(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{resolveStatusAccessAdminOnly:!1}}),this.resolveStatusAccessAdminOnly$.value===!1)return;this.resolveStatusAccessAdminOnly$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableResolveStatusAccessAdminOnly: ",e)}}getResolveStatusAccessAdminOnly$(){return this.resolveStatusAccessAdminOnly$.asObservable()}getResolveStatusAccessAdminOnly(){return this.resolveStatusAccessAdminOnly$.value}enableSvgAsImg(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{svgAsImg:!0}}),this.svgAsImg$.value===!0)return;this.svgAsImg$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableSvgAsImg: ",e)}}disableSvgAsImg(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{svgAsImg:!1}}),this.svgAsImg$.value===!1)return;this.svgAsImg$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableSvgAsImg: ",e)}}getSvgAsImg$(){return this.svgAsImg$.asObservable()}getSvgAsImg(){return this.svgAsImg$.value}enableCommentToNearestAllowedElement(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{commentToNearestAllowedElement:!0}}),this.commentToNearestAllowedElement$.value===!0)return;this.commentToNearestAllowedElement$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableCommentToNearestAllowedElement: ",e)}}disableCommentToNearestAllowedElement(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{commentToNearestAllowedElement:!1}}),this.commentToNearestAllowedElement$.value===!1)return;this.commentToNearestAllowedElement$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableCommentToNearestAllowedElement: ",e)}}getCommentToNearestAllowedElement$(){return this.commentToNearestAllowedElement$.asObservable()}getCommentToNearestAllowedElement(){return this.commentToNearestAllowedElement$.value}enableFocusedThreadMode(){try{if(this.focusedThreadMode$.value===!0)return;this.focusedThreadMode$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableFocusedThreadMode: ",e)}}disableFocusedThreadMode(){try{if(this.focusedThreadMode$.value===!1)return;this.focusedThreadMode$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableFocusedThreadMode: ",e)}}getFocusedThreadMode$(){return this.focusedThreadMode$.asObservable()}enableReadOnly(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{readOnly:!0}}),this.readOnly$.value===!0)return;this.readOnly$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableReadOnly: ",e)}}disableReadOnly(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{readOnly:!1}}),this.readOnly$.value===!1)return;this.readOnly$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableReadOnly: ",e)}}getReadOnly$(){return this.readOnly$.asObservable()}getReadOnly(){return this.readOnly$.value}sanitizeCommentAnnotation(e){try{return e?.comments?.length&&e.comments.forEach(i=>{i?.commentHtml&&(i.commentHtml=this.domService.sanitizeHtml(i.commentHtml))}),e}catch(i){return this.loggingService.catch("Error in CommentService sanitizeCommentAnnotation: ",i),e}}enableCustomAutocompleteSearch(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{customAutocompleteSearch:!0}}),this.customAutocompleteSearch$.value===!0)return;this.customAutocompleteSearch$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableCustomAutocompleteSearch: ",e)}}disableCustomAutocompleteSearch(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{customAutocompleteSearch:!1}}),this.customAutocompleteSearch$.value===!1)return;this.customAutocompleteSearch$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableCustomAutocompleteSearch: ",e)}}getCustomAutocompleteSearch$(){return this.customAutocompleteSearch$.asObservable()}getCustomAutocompleteSearch(){return this.customAutocompleteSearch$.value}enableDeleteThreadWithFirstComment(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{deleteThreadWithFirstComment:!0}}),this.deleteThreadWithFirstComment$.value===!0)return;this.deleteThreadWithFirstComment$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableDeleteThreadWithFirstComment: ",e)}}disableDeleteThreadWithFirstComment(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{deleteThreadWithFirstComment:!1}}),this.deleteThreadWithFirstComment$.value===!1)return;this.deleteThreadWithFirstComment$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableDeleteThreadWithFirstComment: ",e)}}getDeleteThreadWithFirstComment$(){return this.deleteThreadWithFirstComment$.asObservable()}enableExpandMentionGroups(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{expandMentionGroups:!0}}),this.expandMentionGroups$.value===!0)return;this.expandMentionGroups$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableExpandMentionGroups: ",e)}}disableExpandMentionGroups(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{expandMentionGroups:!1}}),this.expandMentionGroups$.value===!1)return;this.expandMentionGroups$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableExpandMentionGroups: ",e)}}getExpandMentionGroups$(){return this.expandMentionGroups$.asObservable()}getExpandMentionGroups(){return this.expandMentionGroups$.value}enableShowMentionGroupsFirst(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{showMentionGroupsFirst:!0}}),this.showMentionGroupsFirst$.value===!0)return;this.showMentionGroupsFirst$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableShowMentionGroupsFirst: ",e)}}disableShowMentionGroupsFirst(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{showMentionGroupsFirst:!1}}),this.showMentionGroupsFirst$.value===!1)return;this.showMentionGroupsFirst$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableShowMentionGroupsFirst: ",e)}}getShowMentionGroupsFirst$(){return this.showMentionGroupsFirst$.asObservable()}getShowMentionGroupsFirst(){return this.showMentionGroupsFirst$.value}enableShowMentionGroupsOnly(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{showMentionGroupsOnly:!0}}),this.showMentionGroupsOnly$.value===!0)return;this.showMentionGroupsOnly$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableShowMentionGroupsOnly: ",e)}}disableShowMentionGroupsOnly(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{showMentionGroupsOnly:!1}}),this.showMentionGroupsOnly$.value===!1)return;this.showMentionGroupsOnly$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableShowMentionGroupsOnly: ",e)}}getShowMentionGroupsOnly$(){return this.showMentionGroupsOnly$.asObservable()}getShowMentionGroupsOnly(){return this.showMentionGroupsOnly$.value}setAnalyticsFeatureConfig({config:e,feature:i}){try{this.analyticsService.setFeatureConfig({feature:i||Re.COMMENT,config:e})}catch(r){this.loggingService.catch("Error in CommentService setAnalyticsFeatureConfig: ",r)}}};o.\u0275fac=function(i){return new(i||o)(J(Qe),J(fc),J(bn),J($t),J(lt),J(pn),J(je),J(Fe),J(vi),J(gm),J(gi),J(Bp),J(Vo),J(qi),J(gn),J(y),J(Vn),J($o),J(er),J(Ise),J(yi),J(Za),J(Gv),J(fm),J($v),J(Lp))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var b=(()=>{let _DynamicDataService=class _DynamicDataService{constructor(n,o,t,e,i){this.authService=n,this.commentService=o,this.loggingService=t,this.injector=e,this.docService=i,this.subscriptions=[],this.commonData$=new fe({}),this.evaluateConditionTriggered=new De,this.conditionRegex=/\{(.*?)\}/g,this.extractedProps={},this.condition="",this.dataComponentConfigSignal=be({});try{this.subscriptions.push(this.authService.getUser$().subscribe(r=>{this.commonData$.next(T(I({},this.commonData$.value),{user:r}))})),this.subscriptions.push(this.commentService.getUnreadCommentAnnotationCountOnCurrentDocument$().subscribe(r=>{this.commonData$.next(T(I({},this.commonData$.value),{unreadCommentAnnotationCount:r?.count||0}))})),this.subscriptions.push(this.commentService.getUnreadCommentCountOnCurrentDocument$().subscribe(r=>{this.commonData$.next(T(I({},this.commonData$.value),{unreadCommentCount:r?.count||0}))})),this.subscriptions.push(this.docService.getUIState$().subscribe(r=>{this.commonData$.next(I(I({},this.commonData$.value),r))})),this.subscriptions.push(this.getCommonData().subscribe(r=>{this.dataComponentConfigSignal.update(a=>(a=I(I({},a),r),a)),this.executeConditionalClasses()})),this.subscriptions.push(this.evaluateConditionTriggered.subscribe(r=>{this.extractedProps=r.extractedProps,this.evaluateCondition(r.className,r.elementRef,r.condition)}))}catch(r){this.loggingService.catch("Error in DynamicDataService constructor: ",r)}}ngOnDestroy(){try{this.subscriptions.forEach(n=>n.unsubscribe())}catch(n){this.loggingService.catch("Error in DynamicDataService ngOnDestroy: ",n)}}getCommonData(){return this.commonData$.asObservable()}getModifiedPathBasedOnCondition(n,o){try{return Object.keys(o).forEach(t=>{o[t].path=this.modifyPathBasedOnCondition(t,n)}),o}catch(t){this.loggingService.catch("Error in DynamicDataService getModifiedPathBasedOnCondition: ",t)}}getComputedValues(n,o,t,e,i,r){try{Object.keys(t).forEach(a=>{let s;if(Pi(n)?s=zi(()=>la(n(),t[a].path)):s=zi(()=>la(n,t[a].path)),Pi(s()))pr(()=>{try{let c=s()();t[a].value=c,this.evaluateConditionTriggered.emit({extractedProps:t,className:e,elementRef:i,condition:r})}catch{}},{injector:this.injector,allowSignalWrites:!0});else{let c=s();t[a].value=c,this.evaluateConditionTriggered.emit({extractedProps:t,className:e,elementRef:i,condition:r})}})}catch(a){this.loggingService.catch("Error in DynamicDataService getComputedValues: ",a)}}modifyPathBasedOnCondition(n,o){try{let t=n;if(n.startsWith("userContact."))t=n.replace("userContact","selectorItem.contact");else if(n.startsWith("comment."))t=n.replace("comment","commentObj");else if(n.startsWith("commentAnnotation."))t=n.replace("commentAnnotation","componentConfigSignal.annotation");else if(n.startsWith("commentAnnotations."))t=n.replace("commentAnnotations","componentConfigSignal.annotations");else{let e=n.match(/^([^.\[]+)/),i=e?e[1]:"";if(i&&o&&typeof o=="function"&&o()&&i in o()){let r=n.match(/\[(.*?)\]/);if(r&&r[1]){let a=r[1];if(a.includes(".")){let s=a.split(".")[0];s&&o()&&s in o()?t=n:t=n.replace(`[${a}]`,`[componentConfigSignal.${a}]`)}else t=n}else t=n}else t="componentConfigSignal."+n}return t}catch(t){return this.loggingService.catch("Error in DynamicDataService modifyPathBasedOnCondition: ",t),n}}applyConditionalClasses(n,o){try{this.elementRef=n,this.data=o}catch(t){this.loggingService.catch("Error in DynamicDataService applyConditionalClasses: ",t)}}executeConditionalClasses(){try{let n=this.getHostElementAttributes(this.elementRef),t=[...Object.keys(n).filter(e=>e.startsWith("velt-class-")).map(e=>({name:e,value:n[e]}))];if(n["velt-class"]){let e=n["velt-class"],i=/'([^']+)':\s*([^,]+)(?:,|$)/g,r=[],a=0,s=100,c;for(;(c=i.exec(e))!==null;){if(a++>s){this.loggingService.catch("Too many class definitions detected.");break}if(c.length<3)continue;let[,p,h]=c;!p||!h||p.split(" ").forEach(_=>{_.trim()&&r.push({name:`velt-class-${_.trim()}`,value:h.trim()})})}t=[...t,...r]}this.data&&typeof this.data=="object"&&Object.keys(this.data).forEach(e=>{this.updateDataComponentConfigSignal(e,this.data[e])}),t.forEach(e=>{let i=e.name.replace("velt-class-","");this.condition=e.value,this.condition&&(this.extractProps(),this.extractedProps=this.getModifiedPathBasedOnCondition(this.dataComponentConfigSignal,this.extractedProps),this.getComputedValues(this.dataComponentConfigSignal,this.evaluateCondition,this.extractedProps,i,this.elementRef,e.value))})}catch(n){this.loggingService.catch("Error in DynamicDataService applyConditionalClasses: ",n)}}updateDataComponentConfigSignal(n,o){try{n==="dataComponentConfigSignal"?this.dataComponentConfigSignal.set(o):this.dataComponentConfigSignal.update(t=>T(I({},t),{[n]:o}))}catch(t){this.loggingService.catch("Error in DataComponent updateDataComponentConfigSignal: ",t)}}extractProps(){try{this.extractedProps={},this.conditionRegex.lastIndex=0;let n;for(;(n=this.conditionRegex.exec(this.condition))!==null;){let o=n[1];this.extractedProps[o]={value:null,path:null,isDynamicPath:this.hasDynamicParts(o)}}}catch(n){this.loggingService.catch("Error in DynamicDataService extractProps: ",n)}}hasDynamicParts(n){try{let o=/\[[^\]'"]*[^\]'"]\]/.test(n),t=/\[[^[\]]*[\.\[][^[\]]*\]/.test(n);return o||t}catch(o){return this.loggingService.catch("Error checking for dynamic path: ",o),!1}}evaluateCondition(n,o,t){try{if(t){let e=this.extractedProps,i=t.replace(this.conditionRegex,(s,c)=>{let p=e[c];return p&&p.value!==void 0?typeof p.value=="string"?`'${p.value}'`:p.value:"false"}),r=this.sanitizeCondition(i),a=this.safeEval(r);return n&&o&&(a?this.setHostElementClasses(o,n):this.removeHostElementClasses(o,n)),a}return!1}catch(e){return this.loggingService.catch("Error in IfComponent evaluateCondition: ",e),!1}}sanitizeCondition(n){try{return n.replace(/[^a-zA-Z0-9\s\+\-\*\/\%\(\)\!\=\<\>\|\&\.\[\]\{\},'"]/g,"")}catch(o){return this.loggingService.catch("Error in IfComponent sanitizeCondition: ",o),""}}safeEval(expression){try{return eval(expression)}catch(n){return!1}}getHostElementAttributes(n){try{let o=n,t={};for(let e of o.attributes)t[e.name]=e.value;return t}catch{return{}}}setHostElementClasses(n,o){try{n.classList.add(o)}catch{}}removeHostElementClasses(n,o){try{n.classList.remove(o)}catch{}}};_DynamicDataService.\u0275fac=function(o){return new(o||_DynamicDataService)(J(je),J(Te),J(y),J(Et),J(lt))},_DynamicDataService.\u0275prov=Ae({token:_DynamicDataService,factory:_DynamicDataService.\u0275fac,providedIn:"root"});let DynamicDataService=_DynamicDataService;return DynamicDataService})();var H=(()=>{let o=class o{set veltIf(e){try{e&&this.setIfCondition(e)}catch(i){this._loggingService.catch("Error in BaseComponent set veltIf:",i)}}constructor(e,i,r){this._elementRef=e,this._dynamicDataService=i,this._loggingService=r,this.componentConfigSignal=be({}),this.veltElement=!0,this.conditionSignal=be(null)}initializeComponentConfigSignal(e){try{this.componentConfigSignal.set(e)}catch(i){this._loggingService.catch("Error in BaseComponent initializeComponentConfigSignal:",i)}}ngOnInit(){try{this._dynamicDataService.applyConditionalClasses(this._elementRef?.nativeElement,{componentConfigSignal:this.componentConfigSignal})}catch(e){this._loggingService.catch("Error in BaseComponent ngOnInit:",e)}}ngOnDestroy(){}setIfCondition(e){try{this.conditionSignal.set(e)}catch(i){this._loggingService.catch("Error in BaseComponent setIfCondition:",i)}}};o.\u0275fac=function(i){return new(i||o)(u(N),u(b),u(y))},o.\u0275cmp=M({type:o,selectors:[["app-base"]],hostVars:1,hostBindings:function(i,r){i&2&&x("data-velt-element",r.veltElement)},inputs:{componentConfigSignal:"componentConfigSignal",template:"template",wireframe:"wireframe",veltIf:"veltIf"},standalone:!1,decls:0,vars:0,template:function(i,r){},encapsulation:2});let n=o;return n})();var nt=(()=>{let o=class o extends H{onDarkModeChange(){return this.darkModeSubject$.asObservable()}constructor(e,i,r,a,s,c,p){super(e,c,p),this._elementRef=e,this._themeService=i,this._changeDetector=r,this._featureService=a,this._componentDarkModeObservable=s,this._componentDarkMode=null,this._globalDarkMode=!1,this._featureDarkMode=!1,this._themeSubscriptions=[],this._darkMode=!1,this.darkMode=!1,this.darkModeSubject$=new fe(!1);try{this._themeSubscriptions.push(this._themeService.getDarkMode$().subscribe(h=>{this._globalDarkMode=h,this.setDarkMode()})),this._featureService&&(this._featureService instanceof Te?this._themeSubscriptions.push(this._featureService.getCommentContainerDarkMode().subscribe(h=>{this._featureDarkMode=h,this.setDarkMode()})):this._featureService instanceof er&&this._themeSubscriptions.push(this._featureService.getDarkMode$().subscribe(h=>{h!==null&&(this._featureDarkMode=h),this.setDarkMode()}))),this._componentDarkModeObservable&&this._componentDarkModeObservable instanceof Ft&&this._themeSubscriptions.push(this._componentDarkModeObservable.subscribe(h=>{this._componentDarkMode=h,this.setDarkMode()}))}catch{}}ngOnInit(){super.ngOnInit()}ngOnChanges(e){try{if(e._darkMode){let i=e._darkMode.currentValue;typeof i=="string"&&(i=i==="true"),this._componentDarkMode=i,this.setDarkMode()}}catch{}}setComponentDarkMode(e){try{this._componentDarkMode=e,this.setDarkMode()}catch{}}setDarkMode(){try{this._componentDarkMode===null?this._featureDarkMode?this.darkMode=!0:this.darkMode=!!this._globalDarkMode:this.darkMode=!!this._componentDarkMode,this.darkMode?this._elementRef.nativeElement.hasAttribute("dark")||this._elementRef.nativeElement.setAttribute("dark",""):this._elementRef.nativeElement.hasAttribute("dark")&&this._elementRef.nativeElement.removeAttribute("dark"),this.darkModeSubject$.next(this.darkMode),this._changeDetector&&this._changeDetector.markForCheck()}catch{}}ngOnDestroy(){try{super.ngOnDestroy(),this._themeSubscriptions.forEach(e=>{e.unsubscribe()})}catch{}}};o.\u0275fac=function(i){return new(i||o)(u(N),u(Ye),u(Xt),u("FeatureService",8),u(Ft),u(b),u(y))},o.\u0275cmp=M({type:o,selectors:[["app-themed"]],inputs:{_darkMode:[0,"darkMode","_darkMode"]},standalone:!1,features:[V,qe],decls:0,vars:0,template:function(i,r){},encapsulation:2,changeDetection:0});let n=o;return n})();var Ge=(()=>{let o=class o{constructor(e){this.loggingService=e,this.wireframeMap=new fe(new Map);try{this.loggingService.log("%c[WB] Creating CLASS: WireframeService","color: blue;")}catch(i){this.loggingService.catch("Error in WireframeService constructor: ",i)}}setWireframe(e,i){try{let r=this.wireframeMap.value;r.set(e,i),this.wireframeMap.next(r)}catch(r){this.loggingService.catch("Error in WireframeService setWireframe: ",r)}}setWireframeMap(e){try{let i=this.wireframeMap.value;e.forEach((r,a)=>{i.set(a,r)}),this.wireframeMap.next(i)}catch(i){this.loggingService.catch("Error in WireframeService setWireframeMap: ",i)}}getWireframe(e,i=!0){try{let r=this.wireframeMap.value,a=r.get(e);if(!a&&i){let s=e?.split("---")[0];s&&(a=r.get(s))}return a&&(a?.children?.length>0||a?.innerHTML?.trim()?.length>0)?a:void 0}catch(r){this.loggingService.catch("Error in WireframeService getWireframe: ",r);return}}getConditionElement(e,i=!0){try{let r=this.wireframeMap.value,a=r.get(e);if(!a&&i){let s=e?.split("---")[0];s&&(a=r.get(s))}return a}catch(r){this.loggingService.catch("Error in WireframeService getConditionElement: ",r);return}}getWireframe$(e,i=!0){return this.wireframeMap.asObservable().pipe(ce(r=>this.getWireframe(e,i)))}setChildren(e){try{this.wireframeMap.next(e)}catch(i){this.loggingService.catch("Error in WireframeService setChildren: ",i)}}getWireframeMap(){return this.wireframeMap.value}};o.\u0275fac=function(i){return new(i||o)(J(y))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var xse=n=>({componentConfigSignal:n}),r9e=(n,o)=>({condition:n,data:o}),a9e=(n,o,t,e,i)=>({template:n,context:o,componentName:"velt-confirm-dialog-wireframe",variant:t,setIfCondition:e,componentElementRef:i});function s9e(n,o){if(n&1&&(f(0),w(1,"app-confirm-dialog-title",5)(2,"app-confirm-dialog-message",5),C(3,"div",6),w(4,"app-confirm-dialog-reject",5)(5,"app-confirm-dialog-approve",5),S(),v()),n&2){let t=l(3);d(),m("componentConfigSignal",t.componentConfigSignal),d(),m("componentConfigSignal",t.componentConfigSignal),d(2),m("componentConfigSignal",t.componentConfigSignal),d(),m("componentConfigSignal",t.componentConfigSignal)}}function l9e(n,o){if(n&1&&(f(0),g(1,s9e,6,4,"ng-container",4),v()),n&2){let t=l().ngIf,e=l();d(),m("veltDynamicTemplate",$(3,a9e,e.template,P(1,xse,e.componentConfigSignal),t.variant,e.setIfCondition.bind(e),e.elementRef))}}function c9e(n,o){if(n&1&&(f(0),g(1,l9e,2,9,"ng-container",3),v()),n&2){let t=l();d(),m("veltIf",F(3,r9e,t.conditionSignal(),P(1,xse,t.componentConfigSignal)))}}var da=(()=>{let o=class o extends nt{constructor(e,i,r,a,s,c,p){super(s,a,void 0,void 0,void 0,p,e),this.loggingService=e,this.dialogRef=i,this.wireframeService=r,this.themeService=a,this.elementRef=s,this.dynamicDataService=p,this.subscriptions=[],this.componentConfigSignal=be({title:"",message:"",yesButton:"",noButton:"",variant:"",closeDialog:this.closeDialog.bind(this)}),this.veltElement=!0;try{c&&(this.componentConfigSignal.update(h=>(h=I(I({},h),c),h)),c?.darkMode&&[!0,!1].includes(c?.darkMode)&&super.setComponentDarkMode(c?.darkMode)),this.setZIndex()}catch(h){this.loggingService.catch("Error in ConfirmDialogComponent constructor: ",h)}}ngOnInit(){try{this.loggingService.log("%c[WB] Calling FUNCTION: ngOnInit","color: green;");let e="velt-confirm-dialog-wireframe";super.ngOnInit(),this.componentConfigSignal().variant&&(e+=`---${this.componentConfigSignal().variant}`),this.subscriptions.push(this.wireframeService.getWireframe$(e).subscribe(i=>{if(i){let r=document.createElement(i.tagName);r.innerHTML=i.innerHTML,this.template=r}}))}catch(e){this.loggingService.catch("Error in ConfirmDialogComponent OnInit: ",e)}}ngOnDestroy(){super.ngOnDestroy();try{this.subscriptions.forEach(e=>e.unsubscribe())}catch(e){this.loggingService.catch("Error in ConfirmDialogComponent OnDestroy: ",e)}}setZIndex(){try{if(this.dialogRef){let e=this.dialogRef._overlayRef;e&&(e.backdropElement&&(e.backdropElement.style.zIndex="2147483647"),e.hostElement&&(e.hostElement.style.zIndex="2147483647"))}}catch(e){this.loggingService.catch("Error in ConfirmDialogComponent setZIndex: ",e)}}closeDialog(e){try{this.dialogRef.close(e)}catch(i){this.loggingService.catch("Error in ConfirmDialogComponent closeDialog: ",i)}}};o.\u0275fac=function(i){return new(i||o)(u(y),u(Ko),u(Ge),u(Ye),u(N),u(ml,8),u(b))},o.\u0275cmp=M({type:o,selectors:[["snippyly-confirm-dialog"]],hostVars:1,hostBindings:function(i,r){i&2&&x("data-velt-element",r.veltElement)},standalone:!1,features:[j([b]),V],decls:3,vars:4,consts:[["floatingConfirmationRef",""],[1,"velt-confirm-dialog",3,"snippylyOverlay","snippylyOverlayZIndex","snippylyOverlayBackdropZIndex"],[4,"ngIf"],[4,"veltIf"],[4,"veltDynamicTemplate"],[3,"componentConfigSignal"],["mat-dialog-actions",""]],template:function(i,r){if(i&1&&(C(0,"div",1,0),g(2,c9e,2,6,"ng-container",2),S()),i&2){let a=de(1);m("snippylyOverlay",a)("snippylyOverlayZIndex",1200)("snippylyOverlayBackdropZIndex",1100),d(2),m("ngIf",r.componentConfigSignal())}},styles:["html[_ngcontent-%COMP%]{--velt-base-rem-unit: 1}*[data-snippyly-element=true][_ngcontent-%COMP%], *[data-velt-element=true][_ngcontent-%COMP%]{font-family:var(--velt-default-font-family)}velt-wireframe[_ngcontent-%COMP%]{display:none!important}*[_ngcontent-%COMP%]{outline:0}[_nghost-%COMP%]{--velt-green: var(--velt-light-mode-green);--velt-magenta: var(--velt-light-mode-magenta);--velt-amber: var(--velt-light-mode-amber);--velt-purple: var(--velt-light-mode-purple);--velt-cyan: var(--velt-light-mode-cyan);--velt-orange: var(--velt-light-mode-orange);--velt-black: var(--velt-light-mode-black);--velt-white: var(--velt-light-mode-white);--velt-gray: var(--velt-light-mode-gray);--velt-error: var(--velt-light-mode-error);--velt-error-hover: var(--velt-light-mode-error-hover);--velt-error-foreground: var(--velt-light-mode-error-foreground);--velt-error-light: var(--velt-light-mode-error-light);--velt-error-transparent: var(--velt-light-mode-error-transparent);--velt-warning: var(--velt-light-mode-warning);--velt-warning-hover: var(--velt-light-mode-warning-hover);--velt-warning-foreground: var(--velt-light-mode-warning-foreground);--velt-warning-light: var(--velt-light-mode-warning-light);--velt-warning-transparent: var(--velt-light-mode-warning-transparent);--velt-success: var(--velt-light-mode-success);--velt-success-hover: var(--velt-light-mode-success-hover);--velt-success-foreground: var(--velt-light-mode-success-foreground);--velt-success-light: var(--velt-light-mode-success-light);--velt-success-transparent: var(--velt-light-mode-success-transparent);--velt-accent: var(--velt-light-mode-accent);--velt-accent-text: var(--velt-light-mode-accent-text);--velt-accent-hover: var(--velt-light-mode-accent-hover);--velt-accent-foreground: var(--velt-light-mode-accent-foreground);--velt-accent-light: var(--velt-light-mode-accent-light);--velt-accent-transparent: var(--velt-light-mode-accent-transparent);--velt-text-0: var(--velt-light-mode-text-0);--velt-text-1: var(--velt-light-mode-text-1);--velt-text-2: var(--velt-light-mode-text-2);--velt-text-3: var(--velt-light-mode-text-3);--velt-text-4: var(--velt-light-mode-text-4);--velt-text-5: var(--velt-light-mode-text-5);--velt-text-6: var(--velt-light-mode-text-6);--velt-text-7: var(--velt-light-mode-text-7);--velt-text-8: var(--velt-light-mode-text-8);--velt-text-9: var(--velt-light-mode-text-9);--velt-text-10: var(--velt-light-mode-text-10);--velt-text-11: var(--velt-light-mode-text-11);--velt-text-12: var(--velt-light-mode-text-12);--velt-background-0: var(--velt-light-mode-background-0);--velt-background-1: var(--velt-light-mode-background-1);--velt-background-2: var(--velt-light-mode-background-2);--velt-background-3: var(--velt-light-mode-background-3);--velt-background-4: var(--velt-light-mode-background-4);--velt-background-5: var(--velt-light-mode-background-5);--velt-background-6: var(--velt-light-mode-background-6);--velt-background-7: var(--velt-light-mode-background-7);--velt-background-8: var(--velt-light-mode-background-8);--velt-background-9: var(--velt-light-mode-background-9);--velt-background-10: var(--velt-light-mode-background-10);--velt-border-0: var(--velt-light-mode-border-0);--velt-border-1: var(--velt-light-mode-border-1);--velt-border-2: var(--velt-light-mode-border-2);--velt-border-3: var(--velt-light-mode-border-3);--velt-border-4: var(--velt-light-mode-border-4);--velt-border-5: var(--velt-light-mode-border-5);--velt-border-6: var(--velt-light-mode-border-6);--velt-border-7: var(--velt-light-mode-border-7);--velt-border-8: var(--velt-light-mode-border-8);--velt-border-9: var(--velt-light-mode-border-9);--velt-border-10: var(--velt-light-mode-border-10);--velt-background-transparent: var(--velt-light-mode-background-transparent);--velt-border-transparent: var(--velt-light-mode-border-transparent);--velt-animation-transparent: var(--velt-light-mode-animation-transparent)}[dark][_nghost-%COMP%]{--velt-green: var(--velt-dark-mode-green);--velt-magenta: var(--velt-dark-mode-magenta);--velt-amber: var(--velt-dark-mode-amber);--velt-purple: var(--velt-dark-mode-purple);--velt-cyan: var(--velt-dark-mode-cyan);--velt-orange: var(--velt-dark-mode-orange);--velt-black: var(--velt-dark-mode-black);--velt-white: var(--velt-dark-mode-white);--velt-gray: var(--velt-dark-mode-gray);--velt-error: var(--velt-dark-mode-error);--velt-error-hover: var(--velt-dark-mode-error-hover);--velt-error-foreground: var(--velt-dark-mode-error-foreground);--velt-error-light: var(--velt-dark-mode-error-light);--velt-error-transparent: var(--velt-dark-mode-error-transparent);--velt-warning: var(--velt-dark-mode-warning);--velt-warning-hover: var(--velt-dark-mode-warning-hover);--velt-warning-foreground: var(--velt-dark-mode-warning-foreground);--velt-warning-light: var(--velt-dark-mode-warning-light);--velt-warning-transparent: var(--velt-dark-mode-warning-transparent);--velt-success: var(--velt-dark-mode-success);--velt-success-hover: var(--velt-dark-mode-success-hover);--velt-success-foreground: var(--velt-dark-mode-success-foreground);--velt-success-light: var(--velt-dark-mode-success-light);--velt-success-transparent: var(--velt-dark-mode-success-transparent);--velt-accent: var(--velt-dark-mode-accent);--velt-accent-text: var(--velt-dark-mode-accent-text);--velt-accent-hover: var(--velt-dark-mode-accent-hover);--velt-accent-foreground: var(--velt-dark-mode-accent-foreground);--velt-accent-light: var(--velt-dark-mode-accent-light);--velt-accent-transparent: var(--velt-dark-mode-accent-transparent);--velt-text-0: var(--velt-dark-mode-text-0);--velt-text-1: var(--velt-dark-mode-text-1);--velt-text-2: var(--velt-dark-mode-text-2);--velt-text-3: var(--velt-dark-mode-text-3);--velt-text-4: var(--velt-dark-mode-text-4);--velt-text-5: var(--velt-dark-mode-text-5);--velt-text-6: var(--velt-dark-mode-text-6);--velt-text-7: var(--velt-dark-mode-text-7);--velt-text-8: var(--velt-dark-mode-text-8);--velt-text-9: var(--velt-dark-mode-text-9);--velt-text-10: var(--velt-dark-mode-text-10);--velt-text-11: var(--velt-dark-mode-text-11);--velt-text-12: var(--velt-dark-mode-text-12);--velt-background-0: var(--velt-dark-mode-background-0);--velt-background-1: var(--velt-dark-mode-background-1);--velt-background-2: var(--velt-dark-mode-background-2);--velt-background-3: var(--velt-dark-mode-background-3);--velt-background-4: var(--velt-dark-mode-background-4);--velt-background-5: var(--velt-dark-mode-background-5);--velt-background-6: var(--velt-dark-mode-background-6);--velt-background-7: var(--velt-dark-mode-background-7);--velt-background-8: var(--velt-dark-mode-background-8);--velt-background-9: var(--velt-dark-mode-background-9);--velt-background-10: var(--velt-dark-mode-background-10);--velt-border-0: var(--velt-dark-mode-border-0);--velt-border-1: var(--velt-dark-mode-border-1);--velt-border-2: var(--velt-dark-mode-border-2);--velt-border-3: var(--velt-dark-mode-border-3);--velt-border-4: var(--velt-dark-mode-border-4);--velt-border-5: var(--velt-dark-mode-border-5);--velt-border-6: var(--velt-dark-mode-border-6);--velt-border-7: var(--velt-dark-mode-border-7);--velt-border-8: var(--velt-dark-mode-border-8);--velt-border-9: var(--velt-dark-mode-border-9);--velt-border-10: var(--velt-dark-mode-border-10);--velt-background-transparent: var(--velt-dark-mode-background-transparent);--velt-border-transparent: var(--velt-dark-mode-border-transparent);--velt-animation-transparent: var(--velt-dark-mode-animation-transparent)}.velt-confirm-dialog[_ngcontent-%COMP%]{width:455px;padding:40px;display:block;box-sizing:border-box;background-color:var(--velt-background-0)}.mat-mdc-dialog-actions[_ngcontent-%COMP%]{justify-content:space-between;gap:var(--velt-spacing-md);min-height:auto} mat-dialog-container .mat-mdc-dialog-surface.mdc-dialog__surface:has(snippyly-confirm-dialog){border-radius:var(--velt-border-radius-xl);padding:0}@media (max-width: 768px){.velt-confirm-dialog[_ngcontent-%COMP%]{width:auto;max-width:455px;padding:24px}}"],changeDetection:0});let n=o;return n})();var fc=(()=>{let o=class o{constructor(e,i,r,a,s,c,p,h,_,E,D,B){this.analyticsService=e,this.configService=i,this.docService=r,this.databaseService=a,this.commonDbService=s,this.authService=c,this.domService=p,this.afAuth=h,this.iamService=_,this.dialog=E,this.loggingService=D,this.notificationService=B,this.areaAnnotationById$=new fe({}),this.documentPaths=null,this.db=Ci(),this.areaEnabled$=new fe(!0),this.allowedElementIds$=new fe([]),this.addAreaMode$=new fe(!1),this.loggingService.log("%c[WB] Creating CLASS: AreaService","color: blue;"),this.analyticsService.setAreaService(this),this.authService.setAreaService(this),this.databaseService.getDb().pipe(Ne(G=>!!G),Je(1)).subscribe(G=>{G&&(this.db=G,this.getDocumentPaths())},G=>{this.loggingService.catch("Error in AreaService getDb subscription: ",G)}),this.domService.onWindowPointerMove$().subscribe(G=>{if(this.addAreaMode$.value){this.highlightElement&&this.domService.removeHighlightFromElement(this.highlightElement);let X=this.domService.getBackgroundElement(G.clientX,G.clientY);X&&(this.isElementInsideAllowedElements(X)?GO(G.target)?this.domService.removeClassFromElement(document.body,"show-pin-cursor"):(this.domService.addClassToElement(document.body,"show-pin-cursor"),this.highlightElement=X,this.domService.highlightElement(this.highlightElement,U.CURSOR.AREA_PIN)):this.domService.removeClassFromElement(document.body,"show-pin-cursor"))}},G=>{this.loggingService.catch("Error in AreaService onWindowPointerMove$ subscription: ",G)}),this.domService.onWindowKeyupEsc$().subscribe(G=>{this.addAreaMode$.value&&this.disableAddAreaMode()},G=>{this.loggingService.catch("Error in AreaService onWindowKeyupEsc$ subscription: ",G)}),this.domService.onDocumentClick$().subscribe(G=>{if(G&&this.addAreaMode$.value){if(G.preventDefault(),G.stopPropagation(),!GO(G.target)){let X=this.domService.getBackgroundElement(G.clientX,G.clientY);X&&this.isElementInsideAllowedElements(X)&&this.addArea(G)}this.disableAddAreaMode()}},G=>{this.loggingService.catch("Error in AreaService onDocumentClick$ subscription: ",G)}),this.addAreaMode$.subscribe(G=>{this.highlightElement&&this.domService.removeHighlightFromElement(this.highlightElement),G?this.domService.addClassToElement(document.body,"snippyly-add-area-mode"):(this.domService.removeClassFromElement(document.body,"snippyly-add-area-mode"),this.domService.removeClassFromElement(document.body,"show-pin-cursor"))},G=>{this.loggingService.catch("Error in AreaService addAreaMode$ subscription: ",G)}),this.domService.onWindowKeyupBackspace$().subscribe(G=>{this.deleteAreaPinAnnotations("keyupBackspace")},G=>{this.loggingService.catch("Error in AreaService onWindowKeyupBackspace$ subscription: ",G)}),this.domService.onWindowKeyupDelete$().subscribe(G=>{this.deleteAreaPinAnnotations("keyupDelete")},G=>{this.loggingService.catch("Error in AreaService onWindowKeyupDelete$ subscription: ",G)})}clearCache(){this.loggingService.log("%c[WB] Calling FUNCTION: clearCache in AreaService","color: green;");try{this.areaAnnotationById$.next({}),this.areaEnabled$.next(!0),this.allowedElementIds$.next([]),this.addAreaMode$.next(!1),this.highlightElement=null}catch(e){this.loggingService.catch("Error in AreaService clearCache: ",e)}}getDocumentPaths(){this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentPaths","color: green;"),this.docService.getDocumentPaths$()}setAllowedElementIds(e){this.allowedElementIds$.next(e||[])}getAllowedElementIds(){return this.allowedElementIds$.asObservable()}getAllAreaAnnotations(e,i,r){this.loggingService.log("%c[WB] Calling FUNCTION: getAllAreaAnnotations","color: green;");let a,s;try{if(e&&(s=fn(e)),i&&typeof i=="object"){let c=Xo(i);a=fn(JSON.stringify(c))}}catch(c){this.loggingService.catch("Error in AreaService getAllAreaAnnotations: ",c)}return Wn(this.afAuth).pipe(Ne(c=>!!c),ge(c=>this.isFeatureAllowed({firebaseUser:c,annotations:[],filteredAnnotations:[]})),ge(c=>c.featureAllowed?this.iamService.isUserAllowed$().pipe(ce(p=>(c.featureAllowed=p,c))):re(c)),ge(c=>c.featureAllowed?this.authService.isPlanExpired$().pipe(ce(p=>(c.featureAllowed=!p,c))):re(c)),ge(c=>c.featureAllowed?re(c).pipe(ge(p=>this.docService.getDocumentPaths$().pipe(ce(h=>(this.documentPaths=h,p.documentPaths=h,p)))),ge(p=>s?this.getDataFromDocumentIds([s]).pipe(ce(h=>(p.annotations=h||[],I({},p)))):this.docService.getDocumentIds$().pipe(ge(h=>{let _=h?.length>0?h.map(E=>E.documentId):[this.documentPaths?.documentId??""];return this.getDataFromDocumentIds(_).pipe(ce(E=>(p.annotations=E||[],I({},p))))}))),ge(p=>this.docService.getLocation$().pipe(ce(h=>(p.location=h,p)))),ge(p=>this.docService.getLocations$().pipe(ce(h=>(p.customLocations=h,p)))),ce(p=>{if(p.filteredAnnotations=[],s&&!a)return p.filteredAnnotations=p.annotations?.slice(),p;{let h=[],_=[];return a?h.push(a):(h.push(p?.location?.locationId),h.push(...Object.values(p?.customLocations||[]).map(E=>E.locationId)),p?.location?.location?.id&&_.push(p?.location?.location?.id)),p.filteredAnnotations=this.filterAnnotationsByLocationIds(p?.annotations,h,_),p}}),ge(p=>r?re(p):p?.annotations?.length?this.domService.onWindowResize$().pipe(ce(()=>p)):re(p)),ge(p=>r?re(p):p?.annotations?.length?this.domService.onDomChange$("AreaService getAllAreaAnnotations").pipe(ce(()=>p)):re(p)),ce(p=>(p.filteredAnnotations=p.filteredAnnotations?.map(h=>{let _=Object.assign({},h);return _.areaProperties=this.calculateAreaAnnotationPosition(_),_}),p)),ge(p=>p?.filteredAnnotations?re(p?.filteredAnnotations||[]):re([])),ge(p=>{if(this.authService.isFeatureAllowed(Re.COMMENT))return re(p);{let h=p?.filter(_=>!_?.targetAnnotations?.filter(E=>E?.type===Re.COMMENT)?.length);return re(h)}})):re([])),Kt(_o))}isFeatureAllowed(e){return this.configService.getConfig$().pipe(Ne(i=>!!i),ce(i=>T(I({},e),{config:i})),ge(i=>this.authService.getUser$().pipe(ce(r=>T(I({},i),{user:r})))),ge(i=>Xi(i.config,i.user,Re.AREA)?re(T(I({},i),{featureAllowed:!0})):(this.loggingService.warn("Area feature is not allowed."),re(T(I({},i),{featureAllowed:!1})))))}getDataFromDocumentIds(e,i){return this.getDataFromDocuments({documentIds:e,filters:i})}getDataFromDocuments(e){if(this.configService.getApiKey()){let{documentIds:i,filters:r}=e;if(i?.some(p=>!p)||!this.documentPaths)return re([]);let a=this.docService.getFolderConfig(),s=re([]),c={useCollectionGroup:!0,isCollection:!0,useQuery:!0};if(this.commonDbService.shouldUseFirestore()||(c.documentId=i?.length?i[0]:void 0,c.organizationId=this.documentPaths?.organizationId),a?.veltFolderId&&a?.allDocuments)s=this.commonDbService.dbListener({feature:"allAreas",properties:T(I({},c),{firestoreQuery:[Fi(mt("metadata.apiKey","==",this.configService?.getApiKey()),mt("metadata.veltFolderId","==",a?.veltFolderId),mt("metadata.organizationId","==",this.documentPaths?.organizationId))]})});else{let p=[];for(let h=0;h<(i?.length??0);h+=U.LISTENER_BATCH_SIZE)p.push(i?.slice(h,h+U.LISTENER_BATCH_SIZE)??[]);s=Dn(p.map(h=>this.commonDbService.dbListener({feature:"allAreas",properties:T(I({},c),{firestoreQuery:[Fi(mt("metadata.apiKey","==",this.configService?.getApiKey()),mt("metadata.documentId","in",h),mt("metadata.organizationId","==",this.documentPaths?.organizationId),...a?.veltFolderId?[mt("metadata.veltFolderId","==",a?.veltFolderId)]:[])]})}).pipe($r()))).pipe(ce(h=>ca(h)))}return s.pipe(ce(({data:p,operation:h})=>{let _=[];return p&&(_=Object.values(p??{}).filter(E=>typeof E=="object")),{data:_,operation:h}}),ce(({data:p,operation:h})=>{if(!i)return{data:p,documentMap:{},operation:h};let _=p.reduce((E,D)=>{let B=D.metadata?.documentId;return B&&(E[B]||(E[B]=[]),E[B].push(D)),E},{});return{data:p,documentMap:_,operation:h}}),ce(({data:p,documentMap:h,operation:_})=>{if(!r)if(_?.type==="removed"){if(_?.ids?.length){let E=this.areaAnnotationById$.value;_?.ids?.forEach(D=>{delete E?.[D]}),this.areaAnnotationById$.next(E)}}else Object.entries(h??{}).forEach(([E,D])=>{this.setAreaAnnotationsByOrganizationIdAndDocumentId({organizationId:this.documentPaths?.organizationId,documentId:E,annotations:D})});return p}))}else return re([])}setAreaAnnotationsByOrganizationIdAndDocumentId({organizationId:e,documentId:i,annotations:r,queryHash:a}){try{if(i){e||(e=U.NO_ORGANIZATION_ID),a||(a=U.DEFAULT_QUERY_HASH);let s={};r?.forEach(p=>{p?.annotationId&&(s[p?.annotationId]=p)});let c=I(I({},this.areaAnnotationById$.value),s);this.areaAnnotationById$.next(c)}}catch(s){this.loggingService.catch("Error in AreaService setAreaAnnotationsByOrganizationIdAndDocumentId:",s)}}getAnnotationById(e){try{return this.areaAnnotationById$.value?.[e]?this.areaAnnotationById$.value?.[e]:void 0}catch(i){this.loggingService.catch("Error in AreaService getAnnotationById: ",i);return}}filterAnnotationsByLocationIds(e,i,r){try{return e.filter(a=>i.includes(a.locationId)||r?.includes(a?.location?.id)||i?.find(s=>s==a?.location?.id)||r?.find(s=>s==a?.locationId+""))}catch(a){return this.loggingService.catch("Error in AreaService filterAnnotationsByLocations:",a),[]}}calculateAreaAnnotationPosition(e){try{if(e.targetElements?.length){let i=e.targetElements[0],r=e.targetElements[1];if(i?.xpath&&r?.xpath){let a=this.domService.getElementFromXPath(i.xpath);a&&ji(a)&&(a=null),!a&&i.cfXpath&&(a=this.domService.getElementFromXPath(i.cfXpath),a&&ji(a)&&(a=null)),!a&&i.fXpath&&(a=this.domService.getElementFromXPath(i.fXpath),a&&ji(a)&&(a=null));let s=this.domService.getElementFromXPath(r.xpath);if(s&&ji(s)&&(s=null),!s&&r.cfXpath&&(s=this.domService.getElementFromXPath(r.cfXpath),s&&ji(s)&&(s=null)),!s&&r.fXpath&&(s=this.domService.getElementFromXPath(r.fXpath),s&&ji(s)&&(s=null)),a&&s){let c=IV(a,s);if(c){let p=a.getBoundingClientRect(),h={};p&&p.width&&p.height&&(h={top:p.height*i.topPercentage/100,left:p.width*i.leftPercentage/100});let _=s.getBoundingClientRect(),E={};_&&_.width&&_.height&&(E={top:_.height*r.topPercentage/100,left:_.width*r.leftPercentage/100});let D=EV(h.left,h.top,a,c),B=EV(E.left,E.top,s,c),G,X,he,Ie,Me={};D.x>B.x?D.y>B.y?(Ie={x:D.x,y:D.y},G={x:B.x,y:B.y},Me.handle1=Ie,Me.handle2=G):(X={x:D.x,y:D.y},he={x:B.x,y:B.y},Me.handle1=X,Me.handle2=he):D.y>B.y?(he={x:D.x,y:D.y},X={x:B.x,y:B.y},Me.handle1=he,Me.handle2=X):(G={x:D.x,y:D.y},Ie={x:B.x,y:B.y},Me.handle1=G,Me.handle2=Ie);let Le={topLeft:G||{x:he?.x,y:X?.y},bottomRight:Ie||{x:X?.x,y:he?.y},topRight:X||{x:Ie?.x,y:G?.y},bottomLeft:he||{x:G?.x,y:Ie?.y}};return Me.coordinates=Le,Me.targetElement=this.domService.getXPath(c),Me}}}}return}catch(i){this.loggingService.catch("Error in AreaService calculateAreaAnnotationPosition:",i);return}}addArea(e,i=[],r,a,s){this.loggingService.log("%c[WB] Calling FUNCTION: addArea","color: green;");try{let c=this.authService.getUser();if(c)if(c.isReadOnly||c.isAnonymous)this.loggingService.catch("Anonymous/Readonly users cannot add areas.");else{let p=new tM;a&&(p.annotationId=a),p.from=c,p.color=U.DEFAULT_ANNOTATION_COLOR,p.lastUpdated=this.timestamp,r&&(p.targetAnnotations=[r]),p.props=new Cl;let h=this.domService.getCurrentWindowSizeValue();if(p.props.screenWidth=h.screenWidth,p.props.screenHeight=h.screenHeight,p.props.screenScrollHeight=h.screenScrollHeight,p.props.viewportWidth=window.innerWidth,p.props.viewportHeight=window.innerHeight,e||i?.length>0){let D=e?this.getPointsForAreaPinAnnotation(e):i;p.targetElements=[],D.forEach(B=>{p.targetElements.push(this.getTargetElementForAreaPinAnnotation(e,{clientX:B.x,clientY:B.y}))})}this.setLocationToAreaAnnotation(p),s&&(p.locationId=s.locationId,p.location=s.location),p.pageInfo=_i(),p.pageInfo&&(p.pageInfo.screenWidth=this.domService.getCurrentWindowSizeValue()?.screenWidth);let _=this.getElementForAreaAnnotation(p),E=this.docService.getBaseMetadata("area",{element:_});return p?.metadata||(p.metadata={}),p.metadata=I(I({},p.metadata),E),this.saveAreaToDb(p),p}return}catch(c){this.loggingService.catch("Error in AreaService addArea: ",c);return}}setLocationToAreaAnnotation(e){try{let i=this.docService.getLocation();i?(e.locationId=i.locationId,e.location=i.location):(delete e.locationId,delete e.location)}catch(i){this.loggingService.catch("Error in AreaService setLocationToAreaAnnotation:",i)}}getElementForAreaAnnotation(e){try{let i,r,a;return e.targetElements?.length&&(e.targetElements[0]?.xpath&&(r=this.domService.getElementFromXPath(e.targetElements[0].xpath)),e.targetElements[1]?.xpath&&(a=this.domService.getElementFromXPath(e.targetElements[1].xpath))),i=IV(r,a),i}catch(i){return this.loggingService.catch("Error in AreaService getElementForAreaAnnotation: ",i),null}}saveAreaToDb(e){this.loggingService.log("%c[WB] Calling FUNCTION: saveAreaToDb","color: green;");try{this.authService.getUser()&&this.authService.isFeatureAllowed(Re.AREA)&&Dn([this.docService.getDocumentPaths$(),this.databaseService.getDb()]).pipe(Ne(([i,r])=>!!i&&!!r),Je(1),ge(([i,r])=>{if(this.documentPaths=i,this.db=r,this.documentPaths?.area){let a=on(this.db,`${this.documentPaths?.area}`),s;e.annotationId?s=on(this.db,`${this.documentPaths?.area}/${e.annotationId}`):e.annotationId=this.commonDbService.generateDocumentId(),e.pageInfo&&(e.pageInfo.areaUrl=this.generateAreaUrl(e));let c=JSON.parse(JSON.stringify(e));if(c.position=null,!c?.metadata?.documentId){c?.metadata||(c.metadata={});let _=this.docService.getBaseMetadata();c.metadata=I(I({},c?.metadata),_)}this.domService.toggleAnnotationSelection(c),this.analyticsService.trackEvent(Z.Events.Area.AREA_ADDED,{annotationId:e.annotationId});let{documentId:p,organizationId:h}=this.getDocumentIdAndOrganizationIdFromAreaAnnotation(e);return this.commonDbService.setData({feature:"area",properties:{id:e.annotationId,documentId:p,organizationId:h},data:JSON.parse(JSON.stringify(c))})}else return re(null)})).subscribe(()=>{},i=>{this.loggingService.catch("Error in AreaService saveAreaToDb subscription: ",i)})}catch(i){this.loggingService.catch("Error in AreaService saveAreaToDb: ",i)}}getDocumentIdAndOrganizationIdFromAreaAnnotation(e){try{return{documentId:e?.metadata?.documentId,organizationId:e?.metadata?.organizationId}}catch(i){return this.loggingService.catch("Error in AreaService getDocumentIdAndOrganizationIdFromAreaAnnotation: ",i),{}}}updateArea(e,i=!1,r){try{r&&this.setLocationToAreaAnnotation(e),i&&this.updateNotificationsDatabase(e,UO.UPDATED),this.updateAreaToDb(e)}catch(a){this.loggingService.catch("Error in AreaService updateArea: ",a)}}updateAreaToDb(e){this.loggingService.log("%c[WB] Calling FUNCTION: updateAreaToDb","color: green;");try{if(this.domService.updateSelectedAnnotationInMap([e]),this.authService.getUser()&&this.authService.isFeatureAllowed(Re.AREA)){let i=JSON.parse(JSON.stringify(e));if(i.position=null,!i?.metadata?.documentId){i?.metadata||(i.metadata={});let s=this.docService.getBaseMetadata();i.metadata=I(I({},i?.metadata),s)}let{documentId:r,organizationId:a}=this.getDocumentIdAndOrganizationIdFromAreaAnnotation(e);this.commonDbService.setData({feature:"area",properties:{id:e.annotationId,documentId:r,organizationId:a},data:JSON.parse(JSON.stringify(i))})}}catch(i){this.loggingService.catch("Error in AreaService updateAreaToDb: ",i)}}deleteAreaPinAnnotations(e){try{let i=this.domService.getSelectedAnnotationsMap(),r=this.authService.getUser(),a=[];Object.keys(i??{}).forEach(s=>ee(this,null,function*(){let c=i[s];c.type==="area"&&r&&c.from&&(r?.isAdmin||c.from.userId===r.userId)&&a.push(c)})),a?.length&&(this.analyticsService.trackEvent(Z.Events.Area.AREA_DELETE_TRIGGERED,{triggerType:e,annotationId:a.map(s=>s.annotationId).join()}),this.dialog.open(da,{data:{title:"Delete area?",message:"This selected area will be deleted.",yesButton:"Delete",noButton:"Cancel",variant:"area"}}).afterClosed().pipe(Je(1)).subscribe(s=>{s&&(a.forEach(c=>ee(this,null,function*(){yield this.deleteAreaPinAnnotation(c)})),setTimeout(()=>{document.querySelectorAll(`[${U.SNIPPYLY_HIGHLIGHT}]`).forEach(p=>{this.domService.removeHighlightFromElement(p)})},100))})),this.domService.resetSelectedAnnotationsMap(!0,"area")}catch(i){this.loggingService.catch("Error in AreaService deleteAreaPinAnnotations: ",i)}}getAreaAnnotationsByOrganizationIdAndDocumentId({organizationId:e,documentId:i}){try{let r={};return Object.values(this.areaAnnotationById$.value??{}).forEach(a=>{a?.metadata?.documentId==i&&a?.metadata?.organizationId==e&&(r[a?.annotationId]=a)}),Object.values(r??{})}catch(r){return this.loggingService.catch("Error in AreaService getAreaAnnotationsByOrganizationIdAndDocumentId:",r),[]}}onDeleteTargetAnnotation(e,i){try{if(this.docService.getDocumentId()&&this.areaAnnotationById$.value){let a=Object.values(this.areaAnnotationById$.value||{}),s;i?s=a.find(c=>c?.annotationId===i):s=a.find(c=>c?.targetAnnotations?.find(p=>p?.annotationId===e)),s&&(s.targetAnnotations=s.targetAnnotations?.filter(c=>c?.annotationId!==e),s.targetAnnotations?.length?this.updateAreaToDb(s):this.deleteAreaPinAnnotation(s))}}catch(r){this.loggingService.catch("Error in AreaService onDeleteTargetAnnotation: ",r)}}deleteAreaPinAnnotation(e){if(this.authService.isFeatureAllowed(Re.AREA)&&this.documentPaths?.area&&e?.annotationId){this.updateNotificationsDatabase(e,UO.DELETED),this.analyticsService.trackEvent(Z.Events.Area.AREA_DELETED,{annotationId:e.annotationId});let{documentId:i,organizationId:r}=this.getDocumentIdAndOrganizationIdFromAreaAnnotation(e);return this.commonDbService.deleteData({feature:"area",properties:{id:e.annotationId,documentId:i,organizationId:r}})}else return Promise.resolve()}enableArea(){try{this.areaEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in AreaService enableArea: ",e)}}disableArea(){try{this.areaEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in AreaService disableArea: ",e)}}getAreaEnabled$(){try{return this.areaEnabled$.asObservable()}catch(e){return this.loggingService.catch("Error in AreaService getAreaEnabled$: ",e),re(!1)}}getAreaEnabled(){try{return this.areaEnabled$.value}catch(e){return this.loggingService.catch("Error in AreaService getAreaEnabled: ",e),!1}}enableAddAreaMode(){this.authService.isFeatureAllowed(Re.AREA)?(this.analyticsService.trackEvent(Z.Events.Area.AREA_ADD_MODE_ENABLED),this.addAreaMode$.next(!0)):this.loggingService.catch("Error in AreaService enableAddAreaMode: ","Area feature is not enabled.")}disableAddAreaMode(){this.analyticsService.trackEvent(Z.Events.Area.AREA_ADD_MODE_DISABLED),this.addAreaMode$.next(!1)}addAreaModeChange(){return this.addAreaMode$.asObservable()}getTargetElementForAreaPinAnnotation(e,i){try{let r=e,a=r?.touches?.length?r.touches[0]?.clientX:r?.clientX,s=r?.touches?.length?r.touches[0]?.clientY:r?.clientY;i&&(a=i.clientX,s=i.clientY);let c=this.domService.getBackgroundElement(a,s);if(c){let p=this.domService.getXPath(c),h=this.domService.getXPath(c,!0),_=this.domService.getXPath(c,!0,!0),E=c.getBoundingClientRect(),D=a-E.x,B=s-E.y,G=D*100/(E.width||1),X=B*100/(E.height||1);return{xpath:p,fXpath:h,cfXpath:_,leftPercentage:G,topPercentage:X}}else return null}catch(r){return this.loggingService.catch("Error in AreaService getTargetElementForAreaPinAnnotation: ",r),null}}getPointsForAreaPinAnnotation(e){let i=[],r=e,a=r?.touches?.length?r.touches[0]?.clientX:r.clientX,s=r?.touches?.length?r.touches[0]?.clientY:r.clientY;return i.push({x:a,y:s}),i.push({x:a+100,y:s+100}),i}get timestamp(){return this.commonDbService.getServerTimestamp()}isElementInsideAllowedElements(e){try{return this.domService.isElementInsideListedElementIds(e,this.allowedElementIds$.value)}catch(i){return this.loggingService.catch("Error in AreaService isElementInsideAllowedElements: ",i),!1}}updateNotificationsDatabase(e,i){try{let r={annotationData:e,actionType:i,notificationSource:"area"};this.notificationService.updateNotificationDatabase(r)}catch(r){this.loggingService.catch("Error in AreaService updateNotificationsDatabase: ",r)}}getAreaUrl(e){try{return e?.pageInfo?.areaUrl?e.pageInfo.areaUrl:(e?.pageInfo||(e.pageInfo=_i(),e.pageInfo&&(e.pageInfo.screenWidth=this.domService.getCurrentWindowSizeValue()?.screenWidth)),e.pageInfo.areaUrl=this.generateAreaUrl(e),this.updateArea(e),e.pageInfo?.areaUrl)}catch(i){this.loggingService.catch("Error in AreaService getAreaUrl: ",i);return}}generateAreaUrl(e){let i=new URL(window.location.href);return i.searchParams.delete(U.URL_PARAMS.TAG_ID),i.searchParams.append(U.URL_PARAMS.TAG_ID,e.annotationId),i.href}generateAreaAnnotationId(){return ee(this,null,function*(){try{if(this.docService.getDocumentPaths()?.area){let i=this.commonDbService.generateDocumentId();return yield Ip(10),i||""}else return""}catch(e){return this.loggingService.catch("Error in AreaService generateAreaAnnotationId: ",e),""}})}};o.\u0275fac=function(i){return new(i||o)(J(Qe),J($t),J(lt),J(pn),J(bn),J(je),J(Fe),J(vi),J(gn),J(qi),J(y),J(Vn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var li=class{constructor(o){this.injector=o,this.hideAnalytics=!1}ha(o){try{this.hideAnalytics=o}catch{}}getService(o){return this.injector.get(o)}trackEvent(o,t={},e=!0){try{this.hideAnalytics||(t||(t={}),t=T(I({},t),{source:"external"}),this.getService(Qe).trackAuthenticatedEvent(o,t,e))}catch(i){this.getService(y).catch("Error in _trackEvent: ",i);return}}};var PM=class extends li{constructor(o){super(o),this.getService(y).log("%c[WB] Creating CLASS: AreaElement","color: blue;"),this.enableArea=this._enableAreaComment,this.disableArea=this._disableAreaComment,this.enableAreaComment=this._enableAreaComment,this.disableAreaComment=this._disableAreaComment}_enableAreaComment(){this.getService(y).log("%c[WB] Calling FUNCTION: enableAreaComment","color: green;");try{this.trackEvent(Z.Events.Area.ENABLE_AREA_COMMENT_TRIGGERED),this.getService(fc).enableArea()}catch(o){this.getService(y).catch("Error in _enableAreaComment: ",o)}}_disableAreaComment(){this.getService(y).log("%c[WB] Calling FUNCTION: disableAreaComment","color: green;");try{this.trackEvent(Z.Events.Area.DISABLE_AREA_COMMENT_TRIGGERED),this.getService(fc).disableArea()}catch(o){this.getService(y).catch("Error in _disableAreaComment: ",o)}}};var vm=(()=>{let o=class o{constructor(e,i,r,a,s,c,p,h,_,E,D,B){this.analyticsService=e,this.configService=i,this.docService=r,this.databaseService=a,this.authService=s,this.domService=c,this.afAuth=p,this.iamService=h,this.dialog=_,this.loggingService=E,this.notificationService=D,this.commonDbService=B,this.arrowAnnotations$=new fe({}),this.arrowAnnotationsByDocumentId$=new fe({}),this.documentPaths=null,this.db=Ci(),this.allowedElementIds$=new fe([]),this.addArrowMode$=new fe(!1),this.loggingService.log("%c[WB] Creating CLASS: ArrowService","color: blue;"),this.databaseService.getDb().pipe(Ne(G=>!!G),Je(1)).subscribe(G=>{G&&(this.db=G,this.getDocumentPaths())},G=>{this.loggingService.catch("Error in ArrowService getDb subscription: ",G)}),this.domService.onWindowPointerMove$().subscribe(G=>{if(this.addArrowMode$.value){let X=!0,he=this.domService.getBackgroundElement(G.clientX,G.clientY);he&&(this.isElementInsideAllowedElements(he)?zO(G.target)?this.domService.removeClassFromElement(document.body,"show-pin-cursor"):(this.domService.addClassToElement(document.body,"show-pin-cursor"),this.highlightElement&&this.highlightElement!==he&&this.domService.removeHighlightFromElement(this.highlightElement),this.highlightElement=he,this.domService.highlightElement(this.highlightElement,U.CURSOR.ARROW_PIN),X=!1):this.domService.removeClassFromElement(document.body,"show-pin-cursor")),this.highlightElement&&X&&(this.domService.removeHighlightFromElement(this.highlightElement),this.highlightElement=null)}},G=>{this.loggingService.catch("Error in ArrowService onWindowPointerMove$ subscription: ",G)}),this.domService.onWindowKeyupEsc$().subscribe(G=>{this.addArrowMode$.value&&this.disableAddArrowMode()},G=>{this.loggingService.catch("Error in ArrowService onWindowKeyupEsc$ subscription: ",G)}),this.domService.onDocumentClick$().subscribe(G=>{if(G&&this.addArrowMode$.value){if(!zO(G.target)){let X=this.domService.getBackgroundElement(G.clientX,G.clientY);X&&this.isElementInsideAllowedElements(X)&&(G.preventDefault(),G.stopPropagation(),this.addArrow(G))}this.disableAddArrowMode()}},G=>{this.loggingService.catch("Error in ArrowService onDocumentClick$ subscription: ",G)}),this.addArrowMode$.subscribe(G=>{this.highlightElement&&this.domService.removeHighlightFromElement(this.highlightElement),G?this.domService.addClassToElement(document.body,"snippyly-add-arrow-mode"):(this.domService.removeClassFromElement(document.body,"snippyly-add-arrow-mode"),this.domService.removeClassFromElement(document.body,"show-pin-cursor"))},G=>{this.loggingService.catch("Error in ArrowService addArrowMode$ subscription: ",G)}),this.domService.onWindowKeyupBackspace$().subscribe(G=>{this.deleteArrowPinAnnotations("keyupBackspace")},G=>{this.loggingService.catch("Error in ArrowService onWindowKeyupBackspace$ subscription: ",G)}),this.domService.onWindowKeyupDelete$().subscribe(G=>{this.deleteArrowPinAnnotations("keyupDelete")},G=>{this.loggingService.catch("Error in ArrowService onWindowKeyupDelete$ subscription: ",G)})}getDocumentPaths(){this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentPaths","color: green;"),this.docService.getDocumentPaths$()}setAllowedElementIds(e){this.allowedElementIds$.next(e||[])}getAllowedElementIds(){return this.allowedElementIds$.asObservable()}getAllArrowAnnotations(e,i,r){this.loggingService.log("%c[WB] Calling FUNCTION: getAllArrowAnnotations","color: green;");let a,s;try{if(e&&(s=fn(e)),i&&typeof i=="object"){let c=Xo(i);a=fn(JSON.stringify(c))}}catch(c){this.loggingService.catch("Error in ArrowService getAllArrowAnnotations: ",c)}return Wn(this.afAuth).pipe(Ne(c=>!!c),ge(c=>this.isFeatureAllowed({firebaseUser:c,annotations:[],filteredAnnotations:[]})),ge(c=>c.featureAllowed?this.iamService.isUserAllowed$().pipe(ce(p=>(c.featureAllowed=p,c))):re(c)),ge(c=>c.featureAllowed?this.authService.isPlanExpired$().pipe(ce(p=>(c.featureAllowed=!p,c))):re(c)),ge(c=>c.featureAllowed?re(c).pipe(ge(p=>this.docService.getDocumentPaths$().pipe(ce(h=>(this.documentPaths=h,p.documentPaths=h,p)))),ge(p=>this.getDataFromDocumentId(s).pipe(ce(h=>(p.annotations=h||[],I({},p))))),ge(p=>this.docService.getLocation$().pipe(ce(h=>(p.location=h,p)))),ge(p=>this.docService.getLocations$().pipe(ce(h=>(p.customLocations=h,p)))),ce(p=>{if(p.filteredAnnotations=[],s&&!a)return p.filteredAnnotations=p.annotations?.slice(),p;{let h=[];return a?h.push(a):(h.push(p?.location?.locationId),h.push(...Object.values(p?.customLocations||[]).map(_=>_.locationId))),p.filteredAnnotations=this.filterAnnotationsByLocationIds(p?.annotations,h),p}}),ge(p=>r?re(p):p?.annotations?.length?this.domService.onWindowResize$().pipe(ce(()=>p)):re(p)),ge(p=>r?re(p):p?.annotations?.length?this.domService.onDomChange$("ArrowService getAllArrowAnnotations").pipe(ce(()=>p)):re(p)),ce(p=>(p?.filteredAnnotations?.forEach(h=>{this.calculateArrowAnnotationPosition(h)}),p)),ge(p=>p?.filteredAnnotations?re(p?.filteredAnnotations||[]):re([]))):re([])),Kt(_o))}isFeatureAllowed(e){return this.configService.getConfig$().pipe(Ne(i=>!!i),ce(i=>T(I({},e),{config:i})),ge(i=>this.authService.getUser$().pipe(ce(r=>T(I({},i),{user:r})))),ge(i=>Xi(i.config,i.user,Re.ARROW)?re(T(I({},i),{featureAllowed:!0})):(this.loggingService.warn("Arrow feature is not allowed."),re(T(I({},i),{featureAllowed:!1})))))}getDataFromDocumentId(e){return this.databaseService.getDb().pipe(Ne(i=>!!i),ge(i=>(this.db=i,this.loggingService.log(this.db),this.configService.getApiKey()&&this.documentPaths?.arrow&&this.documentPaths?this.commonDbService.dbListener({feature:"allArrows",properties:{documentId:e??this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,skipFirestore:!0}}).pipe(ce(r=>({data:r?.data,operation:r?.operation})),ce(({data:r,operation:a})=>{let s=[];return r&&(s=Object.values(r).filter(c=>typeof c=="object")),{data:s,operation:a}}),Ln(r=>(this.loggingService.catch("Error in ArrowService getDataFromDocumentId: ",r),re({data:[],operation:null}))),ce(({data:r,operation:a})=>{if(a?.type==="removed"){if(a?.ids?.length){let s=this.arrowAnnotationsByDocumentId$.value;a?.ids?.forEach(c=>{delete s?.[c]}),this.arrowAnnotationsByDocumentId$.next(s)}}else this.setArrowAnnotationsByDocumentId(e||this.documentPaths?.documentId,r);return r})):re([]))))}setArrowAnnotationsByDocumentId(e,i){try{if(e){let r=T(I({},this.arrowAnnotationsByDocumentId$.value),{[e]:i});this.arrowAnnotationsByDocumentId$.next(r)}}catch(r){this.loggingService.catch("Error in ArrowService setArrowAnnotationsByDocumentId:",r)}}filterAnnotationsByLocationIds(e,i){try{return e.filter(r=>i.includes(r.locationId))}catch(r){return this.loggingService.catch("Error in ArrowService filterAnnotationsByLocations:",r),[]}}calculateArrowAnnotationPosition(e){try{if(e.targetElement){let i=this.domService.getXPath(e.targetElement?.xpath);if(i){let r=i.iterateNext();if(r&&xo(r)){let a=r.getBoundingClientRect();if(a&&a.width&&a.height){let{height:s,width:c}=Ep(r);e.position={top:s*e.targetElement.topPercentage/100,left:c*e.targetElement.leftPercentage/100}}else e.position=null}else e.position=null}else e.position=null}}catch(i){this.loggingService.catch("Error in ArrowService calculateArrowAnnotationPosition:",i)}}addArrow(e){this.loggingService.log("%c[WB] Calling FUNCTION: addArrow","color: green;");try{let i=this.authService.getUser();if(i)if(i.isReadOnly||i.isAnonymous)this.loggingService.catch("Anonymous/Readonly users cannot add arrows.");else{let r=new nM;r.from=i,r.color=i?.color||U.DEFAULT_ANNOTATION_COLOR,r.lastUpdated=this.timestamp,r.props=new Cl;let a=this.domService.getCurrentWindowSizeValue();if(r.props.screenWidth=a.screenWidth,r.props.screenHeight=a.screenHeight,r.props.screenScrollHeight=a.screenScrollHeight,r.props.viewportWidth=window.innerWidth,r.props.viewportHeight=window.innerHeight,r.props.arrowLength=U.VELT_MIN_ARROW_LENGTH,(e?.clientX||0)>U.VELT_MIN_ARROW_LENGTH?r.props.arrowAngle=135:r.props.arrowAngle=45,e&&(r.targetElement=this.domService.getTargetElementForCursorPosition(e)),r?.targetElement?.xpath){let s=this.domService.getXPath(r.targetElement.xpath);if(s){let c=s.iterateNext();c&&(xo(c)||(r.targetElement=null))}}this.setLocationToArrowAnnotation(r),r.pageInfo=_i(),r.pageInfo&&(r.pageInfo.screenWidth=this.domService.getCurrentWindowSizeValue()?.screenWidth),this.saveArrowToDb(r)}}catch(i){this.loggingService.catch("Error in ArrowService addArrow: ",i)}}setLocationToArrowAnnotation(e){try{let i=this.docService.getLocation();i?(e.locationId=i.locationId,e.location=i.location):(delete e.locationId,delete e.location);try{if(e.targetElement?.xpath){let r=this.domService.getElementFromXPath(e.targetElement.xpath),a=this.docService.getAdditionLocationFromElement(r);if(a){let s=this.docService.addLocation(a);s&&(e.locationId=s.locationId,e.location=s.location)}}}catch{}}catch(i){this.loggingService.catch("Error in ArrowService setLocationToArrowAnnotation:",i)}}saveArrowToDb(e){this.loggingService.log("%c[WB] Calling FUNCTION: saveArrowToDb","color: green;");try{this.authService.getUser()&&this.authService.isFeatureAllowed(Re.ARROW)&&this.docService.getDocumentPaths$().pipe(Ne(i=>!!i),Je(1),ge(i=>(this.documentPaths=i,this.loggingService.log(this.documentPaths),this.databaseService.getDb().pipe(Ne(r=>!!r),Je(1),ge(r=>{if(this.db=r,this.loggingService.log(this.db),this.documentPaths?.arrow){let a=on(this.db,`${this.documentPaths?.arrow}`);e.annotationId=this.commonDbService.generateDocumentId(),e.pageInfo&&(e.pageInfo.arrowUrl=this.generateArrowUrl(e));let s=JSON.parse(JSON.stringify(e));return s.position=null,this.domService.toggleAnnotationSelection(s),this.analyticsService.trackEvent(Z.Events.Arrow.ARROW_DRAFT_ADDED,{annotationId:e.annotationId}),this.commonDbService.setData({feature:"arrow",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",id:e.annotationId,skipFirestore:!0},data:JSON.parse(JSON.stringify(s))})}else return re(null)}))))).subscribe(()=>{},i=>{this.loggingService.catch("Error in ArrowService saveArrowToDb subscription: ",i)})}catch(i){this.loggingService.catch("Error in ArrowService saveArrowToDb: ",i)}}updateArrow(e,i=!1,r){try{r&&this.setLocationToArrowAnnotation(e),i&&this.updateNotificationsDatabase(e,VO.UPDATED),this.updateArrowToDb(e)}catch(a){this.loggingService.catch("Error in ArrowService updateArrow: ",a)}}updateArrowToDb(e){this.loggingService.log("%c[WB] Calling FUNCTION: updateArrowToDb","color: green;");try{if(e?.targetElement?.xpath){let i=this.domService.getXPath(e.targetElement.xpath);if(i){let r=i.iterateNext();r&&(xo(r)||(e.targetElement=null))}}this.domService.updateSelectedAnnotationInMap([e]),this.authService.getUser()&&this.authService.isFeatureAllowed(Re.ARROW)&&this.docService.getDocumentPaths$().pipe(Ne(i=>!!i),Je(1),ge(i=>(this.documentPaths=i,this.loggingService.log(this.documentPaths),this.databaseService.getDb().pipe(Ne(r=>!!r),Je(1),ge(r=>{if(this.db=r,this.loggingService.log(this.db),this.documentPaths?.arrow&&e?.annotationId){let a=JSON.parse(JSON.stringify(e));return a.position=null,this.commonDbService.setData({feature:"arrow",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",id:e.annotationId,skipFirestore:!0},data:JSON.parse(JSON.stringify(a))})}else return re(null)}))))).subscribe(()=>{},i=>{this.loggingService.catch("Error in ArrowService updateArrowToDb subscription: ",i)})}catch(i){this.loggingService.catch("Error in ArrowService updateArrowToDb: ",i)}}deleteArrowPinAnnotations(e){try{let i=this.domService.getSelectedAnnotationsMap(),r=this.authService.getUser(),a=[];Object.keys(i).forEach(s=>ee(this,null,function*(){let c=i[s];if(c.type==="arrow"){let p=r&&!r?.isAnonymous&&!r?.isGuest;r&&c.from&&(p||c.from.userId===r.userId)&&a.push(c)}})),a?.length&&(this.analyticsService.trackEvent(Z.Events.Arrow.ARROW_DELETE_TRIGGERED,{triggerType:e,annotationId:a.map(s=>s.annotationId).join()}),this.dialog.open(da,{data:{title:"Delete arrow?",message:"This selected arrow will be deleted.",yesButton:"Delete",noButton:"Cancel",variant:"arrow"}}).afterClosed().pipe(Je(1)).subscribe(s=>{s&&(a.forEach(c=>ee(this,null,function*(){yield this.deleteArrowPinAnnotation(c)})),setTimeout(()=>{document.querySelectorAll(`[${U.SNIPPYLY_HIGHLIGHT}]`).forEach(p=>{this.domService.removeHighlightFromElement(p)})},100))})),this.domService.resetSelectedAnnotationsMap(!0,"arrow")}catch(i){this.loggingService.catch("Error in ArrowService deleteArrowPinAnnotations: ",i)}}deleteArrowPinAnnotation(e){return this.authService.isFeatureAllowed(Re.ARROW)&&this.documentPaths?.arrow&&e?.annotationId?(this.updateNotificationsDatabase(e,VO.DELETED),this.analyticsService.trackEvent(Z.Events.Arrow.ARROW_DELETED,{annotationId:e.annotationId}),this.commonDbService.deleteData({feature:"arrow",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",id:e.annotationId,skipFirestore:!0}})):Promise.resolve()}enableAddArrowMode(){this.authService.isFeatureAllowed(Re.ARROW)?(this.analyticsService.trackEvent(Z.Events.Arrow.ARROW_ADD_MODE_ENABLED),this.addArrowMode$.next(!0)):this.loggingService.catch("Error in ArrowService enableAddArrowMode: ","Arrow feature is not enabled.")}disableAddArrowMode(){this.analyticsService.trackEvent(Z.Events.Arrow.ARROW_ADD_MODE_DISABLED),this.addArrowMode$.next(!1)}addArrowModeChange(){return this.addArrowMode$.asObservable()}get timestamp(){return this.commonDbService.getServerTimestamp()}isElementInsideAllowedElements(e){try{return this.domService.isElementInsideListedElementIds(e,this.allowedElementIds$.value)}catch(i){return this.loggingService.catch("Error in ArrowService isElementInsideAllowedElements: ",i),!1}}updateNotificationsDatabase(e,i){try{let r={annotationData:e,actionType:i,notificationSource:"arrow"};this.notificationService.updateNotificationDatabase(r)}catch(r){this.loggingService.catch("Error in ArrowService updateNotificationsDatabase: ",r)}}getArrowUrl(e){try{return e?.pageInfo?.arrowUrl?e.pageInfo.arrowUrl:(e?.pageInfo||(e.pageInfo=_i(),e.pageInfo&&(e.pageInfo.screenWidth=this.domService.getCurrentWindowSizeValue()?.screenWidth)),e.pageInfo.arrowUrl=this.generateArrowUrl(e),this.updateArrow(e),e.pageInfo?.arrowUrl)}catch(i){this.loggingService.catch("Error in ArrowService getArrowUrl: ",i);return}}generateArrowUrl(e){let i=new URL(window.location.href);return i.searchParams.delete(U.URL_PARAMS.TAG_ID),i.searchParams.append(U.URL_PARAMS.TAG_ID,e.annotationId),i.href}};o.\u0275fac=function(i){return new(i||o)(J(Qe),J($t),J(lt),J(pn),J(je),J(Fe),J(vi),J(gn),J(qi),J(y),J(Vn),J(bn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var RM=class extends li{constructor(o){super(o),this.getService(y).log("%c[WB] Creating CLASS: ArrowElement","color: blue;"),this.allowedElementIds=this._allowedElementIds}_allowedElementIds(o){this.getService(y).log("%c[WB] Calling FUNCTION: allowedElementIds","color: green;");try{this.trackEvent(Z.Events.Arrow.ALLOWED_ELEMENT_IDS_TRIGGERED,{payload:{elementIds:o}}),this.getService(vm).setAllowedElementIds(o)}catch(t){this.getService(y).catch("Error in allowedElementIds: ",t)}}};var zs=(()=>{let o=class o{constructor(e){this.loggingService=e,this.autocompleteDataMap$=new fe({}),this.onAutocompleteChipClick$=new et;try{this.loggingService.log("%c[WB] Creating CLASS: AutocompleteService","color: blue;"),this.create({hotkey:"@",type:"contact",data:[]})}catch(i){this.loggingService.catch("Error in AutocompleteService constructor: ",i)}}create(e){try{if(this.loggingService.log("%c[WB] Calling AutocompleteService FUNCTION: create","color: green;"),e?.hotkey){let i=this.autocompleteDataMap$.value;i[e.hotkey]=e,this.autocompleteDataMap$.next(i)}}catch(i){this.loggingService.catch("Error in AutocompleteService create: ",i)}}remove(e){try{this.loggingService.log("%c[WB] Calling AutocompleteService FUNCTION: remove","color: green;");let i=this.autocompleteDataMap$.value;delete i[e],this.autocompleteDataMap$.next(i)}catch(i){this.loggingService.catch("Error in AutocompleteService remove: ",i)}}getAutocompleteDataMap$(){return this.autocompleteDataMap$.asObservable()}getAutocompleteDataMap(){return this.autocompleteDataMap$.value}setOnAutocompleteChipClick(e){this.onAutocompleteChipClick$.next(e)}getOnAutocompleteChipClick$(){return this.onAutocompleteChipClick$.asObservable()}};o.\u0275fac=function(i){return new(i||o)(J(y))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var FM=class extends li{constructor(o){super(o),this.getService(y).log("%c[WB] Creating CLASS: AutocompleteElement","color: blue;"),this.create=this._create,this.onAutocompleteChipClick=this._onAutocompleteChipClick}_create(o){this.getService(y).log("%c[WB] Calling FUNCTION: create","color: green;");try{return this.trackEvent(Z.Events.Autocomplete.CREATE_TRIGGERED,{payload:{data:o}}),this.getService(zs).create(o)}catch(t){this.getService(y).catch("Error in _create: ",t)}}_onAutocompleteChipClick(){this.getService(y).log("%c[WB] Calling FUNCTION: onAutocompleteChipClick","color: green;");try{return this.trackEvent(Z.Events.Autocomplete.ON_AUTOCOMPLETE_CHIP_CLICK_TRIGGERED),this.getService(zs).getOnAutocompleteChipClick$()}catch(o){return this.getService(y).catch("Error in _onAutocompleteChipClick: ",o),re(null)}}};var ni=(()=>{let o=class o{constructor(e,i,r,a,s,c,p,h,_,E,D){this.analyticsService=e,this.authService=i,this.commentService=r,this.contactService=a,this.customFilterService=s,this.docService=c,this.iamService=p,this.loggingService=h,this.metadataService=_,this.reactionService=E,this.commonDbService=D,this.actionSubjects=new Map,this.defaultSource="internal",this.isUserAdmin=!1,this.subscriptions=[],this.loggingService.log("%c[WB] Creating CLASS: CommentActionsService","color: blue;");try{this.commentService.setCommentActionsService(this),this.iamService.isUserAdmin$().subscribe(B=>{this.isUserAdmin=B})}catch(B){this.loggingService.catch("Error in CommentActionsService constructor: ",B)}}addCommentAnnotation(a,s){return ee(this,arguments,function*({annotation:e,options:i},r){try{return this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: addCommentAnnotation","color: green;"),new Promise(c=>{this.commentService.addComment(void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,p=>ee(this,null,function*(){let h=yield this.getAddCommentAnnotationEventFromCommentAddEventData(p);c(h)}),void 0,void 0,e)})}catch(c){return this.loggingService.catch("Error in CommentActionsService addCommentAnnotation: ",c),null}})}getAddCommentAnnotationEventFromCommentAddEventData(e){return ee(this,null,function*(){try{let i=yield this.metadataService.getGlobalMetadata();return{commentAnnotation:$n(e?.annotation),annotationId:e?.annotation?.annotationId,metadata:i,addContext:e?.addContext,elementRef:e?.elementRef}}catch(i){return this.loggingService.catch("Error in CommentActionsService getAddCommentAnnotationEventFromData: ",i),null}})}triggerAddCommentAnnotationEvent(e){try{this.triggerAction(Yi.ADD_COMMENT_ANNOTATION,e)}catch(i){this.loggingService.catch("Error in CommentActionsService triggerAddCommentAnnotationEvent: ",i)}}triggerAnnotationNotFoundError(e){try{this.loggingService.catch("Annotation not found:","The annotation with the given id was not found.")}catch(i){this.loggingService.catch("Error in CommentActionsService triggerAnnotationNotFoundError: ",i)}}deleteCommentAnnotation(a,s){return ee(this,arguments,function*({annotationId:e,options:i},r){try{if(this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: deleteCommentAnnotation","color: green;"),!this.authService.getUser())return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),null;let p=this.commentService.getAnnotationById(e,i);if(p){let h=this.authService.getUser();if(this.isUserAdmin||h?.userId===p?.from?.userId){this.commentService.deleteCommentPinAnnotation(p);let _=yield this.metadataService.getGlobalMetadata(),E={annotationId:p.annotationId,commentAnnotation:$n(p),metadata:_};return this.triggerAction(Yi.DELETE_COMMENT_ANNOTATION,E),E}else this.loggingService.catch("Access Denied","You must be the author of the comment or an admin to delete it.")}else this.triggerAnnotationNotFoundError(e);return null}catch(c){return this.loggingService.catch("Error in CommentActionsService deleteCommentAnnotation: ",c),null}})}updatePriority(s,c){return ee(this,arguments,function*({annotationId:e,priority:i,options:r},a){try{if(this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: updatePriority","color: green;"),!this.authService.getUser())return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),null;let h=this.commentService.getAnnotationById(e,r);if(h){h=JSON.parse(JSON.stringify(h));let _=h.priority?JSON.parse(JSON.stringify(h.priority)):null;_&&i&&_?.id===i?.id?h.priority=void 0:h.priority=i,this.commentService.saveComment(h,{type:jt.PRIORITY_CHANGED,newPriority:i,oldPriority:_});let E=yield this.metadataService.getGlobalMetadata(),D={newPriority:i,oldPriority:_,annotationId:e,commentAnnotation:$n(h),metadata:E};return this.triggerAction(Yi.UPDATE_PRIORITY,D),this.analyticsService.trackEvent(Z.Events.Comments.COMMENT_PRIORITY_CHANGED,{annotationId:e,commentType:this.commentService.getCommentType(h),oldPriority:h.priority,newPriority:i,commentMode:this.commentService.getCommentMode(),source:a??this.defaultSource}),D}else this.triggerAnnotationNotFoundError(e);return null}catch(p){return this.loggingService.catch("Error in CommentActionsService updatePriority: ",p),null}})}updateStatus(s,c){return ee(this,arguments,function*({annotationId:e,status:i,options:r},a){try{if(this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: updateStatus","color: green;"),!this.authService.getUser())return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),null;let h=this.commentService.getAnnotationById(e,r);if(h){h=JSON.parse(JSON.stringify(h));let _=h.status?JSON.parse(JSON.stringify(h.status)):null;h.status=i,this.commentService.saveComment(h,{type:jt.STATUS_CHANGED,newStatus:i,oldStatus:_});let E=yield this.metadataService.getGlobalMetadata(),D={newStatus:i,oldStatus:_,annotationId:e,commentAnnotation:$n(h),metadata:E};return this.triggerAction(Yi.UPDATE_STATUS,D),this.analyticsService.trackEvent(Z.Events.Comments.COMMENT_STATUS_CHANGED,{annotationId:e,commentType:this.commentService.getCommentType(h),oldStatus:_,newStatus:i,commentMode:this.commentService.getCommentMode(),source:a??this.defaultSource}),D}else this.triggerAnnotationNotFoundError(e);return null}catch(p){return this.loggingService.catch("Error in CommentActionsService updateStatus: ",p),null}})}updateAccess(s,c){return ee(this,arguments,function*({annotationId:e,accessMode:i,options:r},a){try{if(this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: updateAccess","color: green;"),!this.authService.getUser())return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),null;let h=this.commentService.getAnnotationById(e,r);if(h)if(this.isUserAdmin){h=JSON.parse(JSON.stringify(h));let _=h.iam?.accessMode;h.iam.accessMode=i,this.commentService.saveComment(h,{type:jt.ACCESS_MODE_CHANGED,newAccessMode:i,oldAccessMode:_});let E=yield this.metadataService.getGlobalMetadata(),D={newAccessMode:i,oldAccessMode:_,annotationId:e,commentAnnotation:$n(h),metadata:E};switch(this.triggerAction(Yi.UPDATE_ACCESS,D),i){case Ki.PRIVATE:this.analyticsService.trackEvent(Z.Events.Comments.COMMENT_ACCESS_MODE_CHANGED,{type:Ki.PRIVATE,source:a??this.defaultSource});break;case Ki.PUBLIC:this.analyticsService.trackEvent(Z.Events.Comments.COMMENT_ACCESS_MODE_CHANGED,{type:Ki.PUBLIC,source:a??this.defaultSource});break;default:break}return D}else this.loggingService.catch("Access Denied","You must be an admin to update the access mode of the comment.");else this.triggerAnnotationNotFoundError(e);return null}catch(p){return this.loggingService.catch("Error in CommentActionsService updateAccess: ",p),null}})}resolveCommentAnnotation(r){return ee(this,arguments,function*({annotationId:e,options:i}){try{if(this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: resolveCommentAnnotation","color: green;"),!this.authService.getUser())return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),null;let s=this.commentService.getAnnotationById(e,i);if(s){s=JSON.parse(JSON.stringify(s));let c=this.customFilterService.resolvedStatus,p=s.status?JSON.parse(JSON.stringify(s.status)):null;c&&(s.status=c,this.commentService.saveComment(s,{type:jt.STATUS_CHANGED,newStatus:c,oldStatus:p}));let h=yield this.metadataService.getGlobalMetadata(),_={annotationId:e,commentAnnotation:$n(s),metadata:h};return this.triggerAction(Yi.RESOLVE_COMMENT,_),_}else this.triggerAnnotationNotFoundError(e);return null}catch(a){return this.loggingService.catch("Error in CommentActionsService resolveCommentAnnotation: ",a),null}})}getLink(a,s){return ee(this,arguments,function*({annotationId:e,options:i},r){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: getLink","color: green;");let c=this.commentService.getAnnotationById(e,i);if(c){let p=this.commentService.getCommentUrl(c)??null,h=yield this.metadataService.getGlobalMetadata();return{link:p,annotationId:e,commentAnnotation:$n(c),metadata:h}}else this.triggerAnnotationNotFoundError(e);return null}catch(c){return this.loggingService.catch("Error in CommentActionsService getLink: ",c),null}})}copyLink(a,s){return ee(this,arguments,function*({annotationId:e,options:i},r){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: copyLink","color: green;");let c=yield this.getLink({annotationId:e,options:i},r);if(c?.link){fs(c.link),this.commentService.setCopyLink(c.link),this.analyticsService.trackEvent(Z.Events.Comments.COMMENT_LINK_COPIED,{annotationId:e,commentType:this.commentService.getCommentType(c.commentAnnotation),commentMode:this.commentService.getCommentMode(),source:r??this.defaultSource,link:c.link});let p=yield this.metadataService.getGlobalMetadata(),h={link:c.link,annotationId:e,commentAnnotation:$n(c.commentAnnotation),metadata:p};return this.triggerAction(Yi.COPY_LINK,h),h}return null}catch(c){return this.loggingService.catch("Error in CommentActionsService copyLink: ",c),null}})}addComment(p,h){return ee(this,arguments,function*({annotationId:e,comment:i,assignedTo:r,assigned:a,options:s},c){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: addComment","color: green;");let _=this.authService.getUser();if(!_)return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),null;if(_){let E=this.commentService.getAnnotationById(e,s),D=E?.comments?.length?jt.ADDED:jt.NEWLY_ADDED;if(E){let B=new pc;B=I(I({},B),i),B.lastUpdated=new Date,B.attachments||(B.attachments=[]),B.attachments=B.attachments.filter(he=>he?.attachmentId),B.createdAt=this.timestamp,B.from=_,r&&(E.assignedTo=r),this.commentService.saveComment(E,{type:D,updatedComment:B,assigned:a});let G=yield this.metadataService.getGlobalMetadata(),X={annotationId:e,commentId:B?.commentId,comment:B,commentAnnotation:$n(E),metadata:G};return this.triggerAction(Yi.ADD_COMMENT,X),this.analyticsService.trackEvent(Z.Events.Comments.COMMENT_ADDED,{annotationId:e,commentThreadId:i?.commentId,commentType:this.commentService.getCommentType(E),commentMode:this.commentService.getCommentMode(),source:c??this.defaultSource}),X}else this.triggerAnnotationNotFoundError(e)}return null}catch(_){return this.loggingService.catch("Error in CommentActionsService addComment: ",_),null}})}approveCommentAnnotation(a,s){return ee(this,arguments,function*({annotationId:e,options:i},r){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: approveCommentAnnotation","color: green;");let c=this.commentService.getAnnotationById(e,i);if(c){c.approved=!0,this.commentService.saveComment(c,{type:jt.APPROVED}),this.analyticsService.trackEvent(Z.Events.Comments.COMMENT_APPROVED,{annotationId:e,commentType:this.commentService.getCommentType(c),commentMode:this.commentService.getCommentMode(),source:r??this.defaultSource});let p=yield this.metadataService.getGlobalMetadata(),h={annotationId:e,commentAnnotation:$n(c),metadata:p};return this.triggerAction(Yi.APPROVE_COMMENT_ANNOTATION,h),h}else this.triggerAnnotationNotFoundError(e);return null}catch(c){return this.loggingService.catch("Error in CommentActionsService approveComment: ",c),null}})}acceptCommentAnnotation(a,s){return ee(this,arguments,function*({annotationId:e,options:i},r){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: acceptCommentAnnotation","color: green;");let c=this.commentService.getAnnotationById(e,i),p=this.authService.getUser();if(c&&p){let h=c.status?JSON.parse(JSON.stringify(c.status)):null;c.status=U.CommentAcceptStatus,this.commentService.saveComment(c,{type:jt.ACCEPTED,oldStatus:h,newStatus:U.CommentAcceptStatus});let _=yield this.metadataService.getGlobalMetadata(),E={annotationId:e,commentAnnotation:$n(c),metadata:_,actionUser:p,replaceContentHtml:c?.comments?.length?c?.comments[0]?.replaceContentHtml:void 0,replaceContentText:c?.comments?.length?c?.comments[0]?.replaceContentText:void 0};return this.triggerAction(Yi.ACCEPT_COMMENT_ANNOTATION,E),this.analyticsService.trackEvent(Z.Events.Comments.COMMENT_ACCEPTED,{annotationId:e,commentType:this.commentService.getCommentType(c),commentMode:this.commentService.getCommentMode(),source:r??this.defaultSource}),E}else this.triggerAnnotationNotFoundError(e);return null}catch(c){return this.loggingService.catch("Error in CommentActionsService acceptCommentAnnotation: ",c),null}})}rejectCommentAnnotation(a,s){return ee(this,arguments,function*({annotationId:e,options:i},r){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: rejectCommentAnnotation","color: green;");let c=this.commentService.getAnnotationById(e,i),p=this.authService.getUser();if(c&&p){let h=c.status?JSON.parse(JSON.stringify(c.status)):null;c.status=U.CommentRejectStatus,this.commentService.saveComment(c,{type:jt.REJECTED,oldStatus:h,newStatus:U.CommentRejectStatus});let _=yield this.metadataService.getGlobalMetadata(),E={annotationId:e,commentAnnotation:$n(c),metadata:_,actionUser:p,replaceContentHtml:c?.comments?.length?c?.comments[0]?.replaceContentHtml:void 0,replaceContentText:c?.comments?.length?c?.comments[0]?.replaceContentText:void 0};return this.triggerAction(Yi.REJECT_COMMENT_ANNOTATION,E),this.analyticsService.trackEvent(Z.Events.Comments.COMMENT_REJECTED,{annotationId:e,commentType:this.commentService.getCommentType(c),commentMode:this.commentService.getCommentMode(),source:r??this.defaultSource}),E}else this.triggerAnnotationNotFoundError(e);return null}catch(c){return this.loggingService.catch("Error in CommentActionsService rejectCommentAnnotation: ",c),null}})}toggleNotificationSubscription(a,s){return ee(this,arguments,function*({annotationId:e,options:i},r){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: toggleNotificationSubscription","color: green;");let c=this.commentService.getAnnotationById(e,i),p=this.authService.getUser();if(c&&p){let h=Rt(p.userId);if(h){c.subscribedUsers||(c.subscribedUsers={}),c.unsubscribedUsers||(c.unsubscribedUsers={});let _,E=!1;if(c?.unsubscribedUsers?.[h])E=!1;else if(c?.subscribedUsers?.[h])E=!0;else{let G=this.contactService.getCurrentOrganizationUserIAM();if(G){let X=G.groups||{};Object.keys(X).forEach(he=>{c?.subscribedGroups?.[he]&&(E=!0)})}}if(r==="subscribe"||!r&&!E)delete c.unsubscribedUsers[h],c.subscribedUsers[h]={user:p,type:"manual"},_=jt.SUBSCRIBED;else if(r==="unsubscribe"||!r&&E)delete c.subscribedUsers[h],c.unsubscribedUsers[h]={user:p,type:"manual"},_=jt.UNSUBSCRIBED;else return null;this.commentService.saveComment(c,{type:_});let D=yield this.metadataService.getGlobalMetadata(),B={annotationId:e,commentAnnotation:$n(c),metadata:D};return _===jt.SUBSCRIBED?this.triggerAction(Yi.SUBSCRIBE_COMMENT_ANNOTATION,B):this.triggerAction(Yi.UNSUBSCRIBE_COMMENT_ANNOTATION,B),B}}else this.triggerAnnotationNotFoundError(e);return null}catch(c){return this.loggingService.catch("Error in CommentActionsService toggleNotificationSubscription: ",c),null}})}assignUser(s,c){return ee(this,arguments,function*({annotationId:e,assignedTo:i,options:r},a){try{if(this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: assignUser","color: green;"),!this.authService.getUser())return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),null;let h=this.commentService.getAnnotationById(e,r);if(h){h.assignedTo=i,this.commentService.saveComment(h,{type:jt.ASSIGNED,assignedTo:i});let _=yield this.metadataService.getGlobalMetadata(),E={annotationId:e,assignedTo:i,commentAnnotation:$n(h),metadata:_};return this.triggerAction(Yi.ASSIGN_USER,E),this.analyticsService.trackEvent(Z.Events.Comments.COMMENT_ASSIGNED,{annotationId:e,commentType:this.commentService.getCommentType(h),commentMode:this.commentService.getCommentMode(),source:a??this.defaultSource,assignedToUserId:i?.userId}),E}else this.triggerAnnotationNotFoundError(e);return null}catch(p){return this.loggingService.catch("Error in CommentActionsService assignUser: ",p),null}})}getComment(r){return ee(this,arguments,function*({annotationId:e,options:i}){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: getComment","color: green;");let a=this.commentService.getAnnotationById(e,i);return a?a.comments||[]:(this.triggerAnnotationNotFoundError(e),[])}catch(a){return this.loggingService.catch("Error in CommentActionsService getComment: ",a),[]}})}updateOrDeleteComment(e,i,r,a,s){return ee(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: updateOrDeleteComment","color: green;"),i?.commentText?.trim()||i?.attachments?.length||i?.recorders?.length){let c=this.authService.getUser();if(this.isUserAdmin||c?.userId===i?.from?.userId){i.lastUpdated=new Date,i.status=jt.UPDATED,i.isEdited||(i.isEdited=!0,i.editedAt=new Date),this.commentService.saveComment(e,{type:jt.UPDATED,updatedComment:i});let p=yield this.metadataService.getGlobalMetadata(),h={annotationId:e?.annotationId,commentId:i?.commentId,comment:i,commentAnnotation:$n(e),metadata:p};return this.triggerAction(Yi.UPDATE_COMMENT,h),this.analyticsService.trackEvent(Z.Events.Comments.COMMENT_EDITED,{annotationId:e?.annotationId,commentThreadId:i?.commentId,commentType:this.commentService.getCommentType(e),commentMode:this.commentService.getCommentMode(),source:s??this.defaultSource}),h}else this.loggingService.catch("Access Denied","You must be the author of the comment or an admin to update it.")}else yield this.deleteComment({annotationId:e?.annotationId,commentId:i.commentId,skipDeleteThreadConfirmation:r,options:a});return null}catch(c){return this.loggingService.catch("Error in CommentActionsService updateOrDeleteComment: ",c),null}})}updateComment(p,h){return ee(this,arguments,function*({annotationId:e,comment:i,skipDeleteThreadConfirmation:r,merge:a,options:s},c){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: updateComment","color: green;");let _=this.commentService.getAnnotationById(e,s),E=this.authService.getUser();if(!E)return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),null;if(_&&E){let D=i,B=_.comments?.find(G=>G.commentId===i.commentId);if(B){if(this.isUserAdmin||E?.userId===B?.from?.userId)return a&&(D=I(I({},B),i)),D.from=B.from,D.createdAt=B.createdAt,D.lastUpdated=new Date,yield this.updateOrDeleteComment(_,D,r,s,c);this.loggingService.catch("Access Denied","You must be the author of the comment or an admin to update it.")}}else this.triggerAnnotationNotFoundError(e);return null}catch(_){return this.loggingService.catch("Error in CommentActionsService updateComment: ",_),null}})}deleteComment(c,p){return ee(this,arguments,function*({annotationId:e,commentId:i,skipDeleteThreadConfirmation:r,options:a},s){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: deleteComment","color: green;");let h=this.commentService.getAnnotationById(e,a),_=this.authService.getUser();if(h){let E=h.comments?.find(D=>D?.commentId===i);if(E)if(this.isUserAdmin||_?.userId===E?.from?.userId){this.commentService.saveComment(h,{type:jt.DELETED,updatedComment:E,skipDeleteThreadConfirmation:r});let D=yield this.metadataService.getGlobalMetadata(),B={annotationId:e,commentId:i,commentAnnotation:$n(h),comment:E,metadata:D};return this.triggerAction(Yi.DELETE_COMMENT,B),B}else this.loggingService.catch("Access Denied","You must be the author of the comment or an admin to delete it.")}else this.triggerAnnotationNotFoundError(e);return null}catch(h){return this.loggingService.catch("Error in CommentActionsService deleteComment: ",h),null}})}addAttachment(s,c){return ee(this,arguments,function*({annotationId:e,files:i,options:r},a){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: addAttachment","color: green;");let p=[],h=this.commentService.getAnnotationById(e,r);if(h||a==="internal"){let D=[];i.forEach(B=>{let{valid:G,file:X,maxAllowedSize:he,error:Ie}=this.validateFile(B);G&&X?D.push(this.uploadFile(X,h||{}).then(Me=>({valid:G,file:X,maxAllowedSize:he,error:Ie,attachment:Me||void 0}))):D.push(Promise.resolve({valid:G,file:X,maxAllowedSize:he,error:Ie,attachment:void 0}))}),p=yield Promise.all(D)}else this.triggerAnnotationNotFoundError(e);let _=yield this.metadataService.getGlobalMetadata(),E={annotationId:e,commentAnnotation:h?$n(h):void 0,attachments:p,metadata:_};return this.triggerAction(Yi.ADD_ATTACHMENT,E),p}catch(p){return this.loggingService.catch("Error in CommentActionsService addAttachment: ",p),[]}})}validateFile(e){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: validateFile","color: green;");let i=100*1024*1024;(e?.type?.includes("image")||e?.type?.includes("pdf"))&&(i=15*1024*1024);let r=e.size<=i;return{valid:r,file:e,maxAllowedSize:i,maxAllowedSizeInMB:i/1024/1024,error:r?void 0:`File size should be less than ${i/1024/1024} MB`}}catch(i){return this.loggingService.catch("Error in CommentActionsService validateFile: ",i),{valid:!1,maxAllowedSize:0,maxAllowedSizeInMB:0,error:"Error in validating file"}}}deleteAttachment(s){return ee(this,arguments,function*({annotationId:e,commentId:i,attachmentId:r,options:a}){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: deleteAttachment","color: green;");let c=this.commentService.getAnnotationById(e,a);if(c){let p=c.comments?.find(_=>_?.commentId===i),h=c.metadata;if(p){let _=this.authService.getUser();if(this.isUserAdmin||_?.userId===p?.from?.userId){let E=p.attachments?.find(D=>D?.attachmentId===r);if(E){p.attachments=p.attachments?.filter(X=>X?.attachmentId!==r);let D={attachmentId:E.attachmentId,organizationId:h?.organizationId??null,documentId:h?.documentId??null,folderId:h?.folderId??null,commentAnnotationId:c.annotationId,apiKey:h?.apiKey??null};yield this.commentService.deleteAttachment({attachment:E,metadata:D});let B=yield this.metadataService.getGlobalMetadata(),G={attachment:E,annotationId:e,commentId:i,commentAnnotation:$n(c),metadata:B};return this.triggerAction(Yi.DELETE_ATTACHMENT,G),this.updateComment({annotationId:e,comment:p,options:a}),G}}else this.loggingService.catch("Access Denied","You must be the author of the comment or an admin to delete the attachment.")}}else this.triggerAnnotationNotFoundError(e);return null}catch(c){return this.loggingService.catch("Error in CommentActionsService deleteAttachment: ",c),null}})}getAttachment(a){return ee(this,arguments,function*({annotationId:e,commentId:i,options:r}){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: getAttachment","color: green;");let s=this.commentService.getAnnotationById(e,r);return s?s.comments?.find(p=>p?.commentId===i)?.attachments||[]:(this.triggerAnnotationNotFoundError(e),[])}catch(s){return this.loggingService.catch("Error in CommentActionsService getAttachment: ",s),[]}})}uploadFile(e,i){return ee(this,null,function*(){try{return this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: uploadFile","color: green;"),this.commentService.uploadFile(e,i)}catch(r){return this.loggingService.catch("Error in CommentActionsService uploadFile: ",r),null}})}getRecording(a){return ee(this,arguments,function*({annotationId:e,commentId:i,options:r}){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: getRecording","color: green;");let s=this.commentService.getAnnotationById(e,r);return s?s.comments?.find(p=>p?.commentId===i)?.recorders||[]:(this.triggerAnnotationNotFoundError(e),[])}catch(s){return this.loggingService.catch("Error in CommentActionsService getRecording: ",s),[]}})}deleteRecording(s){return ee(this,arguments,function*({annotationId:e,commentId:i,recorderId:r,options:a}){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: deleteRecording","color: green;");let c=this.commentService.getAnnotationById(e,a);if(c){let p=c.comments?.find(h=>h?.commentId===i);if(p){let h=this.authService.getUser();if(this.isUserAdmin||h?.userId===p?.from?.userId){let _=p.recorders?.find(E=>E?.id===r);if(_){p.recorders=p.recorders?.filter(B=>B?.id!==r);let E=yield this.metadataService.getGlobalMetadata(),D={annotationId:e,commentId:i,recording:_,commentAnnotation:$n(c),metadata:E};return this.triggerAction(Yi.DELETE_RECORDING,D),this.updateComment({annotationId:e,comment:p,skipDeleteThreadConfirmation:!0,options:a}),D}}else this.loggingService.catch("Access Denied","You must be the author of the comment or an admin to delete the recording.")}}else this.triggerAnnotationNotFoundError(e);return null}catch(c){return this.loggingService.catch("Error in CommentActionsService deleteRecording: ",c),null}})}fetchCommentAnnotations(e){return ee(this,null,function*(){try{let i=yield this.commentService.fetchCommentAnnotations(e),r;if(i?.hasMore){let s=i?.data[i?.data?.length-1];r=yield hV(s?.lastUpdated?.toString()??"","veltencrypttoken","veltencrypttoken")}let a=i?.data?.reduce((s,c)=>(s[c.metadata.clientDocumentId??c.metadata.documentId]=s[c.metadata.clientDocumentId??c.metadata.documentId]||[],s[c.metadata.clientDocumentId??c.metadata.documentId].push($n(c)),s),{});return I({data:a},i?.hasMore?{nextPageToken:r}:{})}catch(i){return this.loggingService.catch("Error in CommentActionsService fetchCommentAnnotations: ",i),{data:null}}})}toggleReaction(c,p){return ee(this,arguments,function*({annotationId:e,commentId:i,reaction:r,options:a},s){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: toggleReaction","color: green;");let h=this.commentService.getAnnotationById(e,a),_=this.authService.getUser();if(h&&_){let E=h.comments?.find(D=>D?.commentId===i);if(E){let D=yield this.reactionService.addOrUpdateReaction(r.reactionId,E?.reactionAnnotationIds||[],void 0,void 0,h?.annotationId,r.customReaction,s),B=jt.REACTION_ADDED;if(D){D?.reactions?.find(he=>he.from?.userId===_?.userId)||(B=jt.REACTION_DELETED),E.reactionAnnotationIds||(E.reactionAnnotationIds=[]),E.reactionAnnotationIds.includes(D.annotationId)||E.reactionAnnotationIds.push(D.annotationId),D?.reactions?.length||(E.reactionAnnotationIds=E.reactionAnnotationIds.filter(he=>he!==D.annotationId)),this.commentService.saveComment(h,{type:B,updatedComment:E});let G=yield this.metadataService.getGlobalMetadata(),X={annotationId:e,commentId:i,reaction:D,commentAnnotation:$n(h),metadata:G};return s==="add"?this.triggerAction(Yi.ADD_REACTION,X):s==="delete"?this.triggerAction(Yi.DELETE_REACTION,X):this.triggerAction(Yi.TOGGLE_REACTION,X),X}}}else this.triggerAnnotationNotFoundError(e);return null}catch(h){return this.loggingService.catch("Error in CommentActionsService toggleReaction: ",h),null}})}onComposerClick(i){return ee(this,arguments,function*({commentAnnotation:e}){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: onComposerClick","color: green;");let r=yield this.metadataService.getGlobalMetadata(),a={commentAnnotation:e?.annotationId?$n(e):void 0,metadata:r};this.triggerAction(Yi.COMPOSER_CLICKED,a)}catch(r){this.loggingService.catch("Error in CommentActionsService onComposerClick: ",r)}})}autocompleteSearch(e){return ee(this,null,function*(){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: autocompleteSearch","color: green;");let i=yield this.metadataService.getGlobalMetadata();e.metadata=i,this.triggerAction(Yi.AUTOCOMPLETE_SEARCH,e)}catch(i){this.loggingService.catch("Error in CommentActionsService autocompleteSearch: ",i)}})}convert(e){try{if(e?.options){let{documentId:i,organizationId:r}=this.docService.getServerId(e?.options);e.options=T(I({},e?.options),{documentId:i,organizationId:r})}return this}catch(i){return this.loggingService.catch("Error in CommentActionsService convert: ",i),this}}triggerAction(e,i){try{this.actionSubjects.has(e)||this.actionSubjects.set(e,new et),this.actionSubjects.get(e)?.next(i)}catch(r){this.loggingService.catch("Error in CommentActionsService triggerAction: ",r)}}onAction(e){try{return this.actionSubjects.has(e)||this.actionSubjects.set(e,new et),this.actionSubjects.get(e)?.asObservable()}catch(i){return this.loggingService.catch("Error in CommentActionsService onAction: ",i),re(null)}}get timestamp(){return this.commonDbService.getServerTimestamp()}getCommentAnnotations(e){try{if(e){if(e?.allDocuments&&!e?.folderId)return this.loggingService.catch("folderId is required when allDocuments is true."),re({data:null});if(!e?.allDocuments&&!e?.documentIds?.length)return this.loggingService.catch("documentIds is required."),re({data:null})}return this.commentService.getAllCommentAnnotations({excludeDomChanges:!0,skipPositionCalculation:!0,query:e}).pipe(ce(i=>i?i.reduce((r,a)=>{let s=a.metadata?.clientDocumentId;return!s||e?.documentIds&&!e?.documentIds?.includes(s)||(r[s]||(r[s]=[]),r[s].push(a)),r},{}):null),ce(i=>({data:i})))}catch(i){return this.loggingService.catch("Error in CommentActionsService getCommentAnnotation: ",i),re({data:null})}}getCommentAnnotationsCount$(e){try{return this.commentService.getAnnotationsCount(e).pipe(ce(i=>i||{data:null}))}catch(i){return this.loggingService.catch("Error in CommentActionsService getCommentAnnotation: ",i),re({data:null})}}};o.\u0275fac=function(i){return new(i||o)(J(Qe),J(je),J(Te),J(gi),J($o),J(lt),J(gn),J(y),J(fm),J(er),J(bn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Wv=(()=>{let o=class o{constructor(e,i){this.httpClient=e,this.loggingService=i,this.fileContentMap$=new fe({})}getFileContent(e){try{let i=fn(e);return this.fileContentMap$.value[i]?re(this.fileContentMap$.value[i]):this.httpClient.get(e,{responseType:"text"}).pipe(ce(r=>(this.fileContentMap$.next(T(I({},this.fileContentMap$.value),{[i]:r})),r)))}catch(i){return this.loggingService.catch("Error in TranscriptionService saveRecorderToDb: ",i),re(null)}}getVttFileTextToArray(e){try{let c=[],p=e.split(`
|
|
382
382
|
`);for(var i=0;i<p.length;i++)if(p[i].indexOf("-->")!==-1){var r=p[i].split(" --> ")[0],a=p[i].split(" --> ")[1],s=p[i+1];c.push({startTime:r,endTime:a,startTimeInSeconds:this.getTimeInSecondsFromVttTime(r),endTimeInSeconds:this.getTimeInSecondsFromVttTime(a),text:s})}return c}catch(c){return this.loggingService.catch("Error in TranscriptionService getVttFileTextToArray: ",c),[]}}getTimeInSecondsFromVttTime(e){try{let i=e.split(":"),r=0;i.length===3&&(r=parseInt(i[0]),i.shift());let a=parseInt(i[0]),s=parseInt(i[1].split(".")[0]),c=parseInt(i[1].split(".")[1]);return((r*60*60+a*60+s)*1e3+c)/1e3}catch(i){return this.loggingService.catch("Error in TranscriptionService getTimeInSecondsFromVttTime: ",i),0}}};o.\u0275fac=function(i){return new(i||o)(J(Q4),J(y))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Qi=(()=>{let o=class o{constructor(e,i,r,a,s,c,p,h,_,E,D,B,G,X,he,Ie,Me,Le,We){this.analyticsService=e,this.configService=i,this.docService=r,this.databaseService=a,this.commonDbService=s,this.authService=c,this.domService=p,this.afAuth=h,this.iamService=_,this.functions=E,this.avatarService=D,this.contactService=B,this.storageService=G,this.dialog=X,this.loggingService=he,this.notificationService=Ie,this.transcriptionService=Me,this.recorderService=Le,this.recorderUtilsService=We,this.recorderAnnotationById$=new fe({}),this.documentPaths=null,this.db=Ci(),this.allowedElementIds$=new fe([]),this.addRecorderMode$=new fe(!1),this.recorderContainerDarkMode$=new fe(!1),this.recordingTranscriptionEnabled$=new fe(!0),this.draftRecordings$=new fe([]),this.recorderNotesFound$=new fe(!1),this.recordedData=null,this.videoEditorAutoOpen$=new fe({}),this.getAllRecorderAnnotations().subscribe(ke=>{}),this.loggingService.log("%c[WB] Creating CLASS: RecorderAnnotationService","color: blue;"),this.analyticsService.setRecorderAnnotationService(this),this.authService.setRecorderAnnotationService(this),this.databaseService.getDb().pipe(Ne(ke=>!!ke),Je(1)).subscribe(ke=>{ke&&(this.db=ke,this.getDocumentPaths())},ke=>{this.loggingService.catch("Error in RecorderAnnotationService getDb subscription: ",ke)}),this.domService.onWindowPointerMove$().subscribe(ke=>{if(this.addRecorderMode$.value){this.highlightElement&&this.domService.removeHighlightFromElement(this.highlightElement);let we=this.domService.getBackgroundElement(ke.clientX,ke.clientY);we&&(this.isElementInsideAllowedElements(we)?WO(ke.target)?this.domService.removeClassFromElement(document.body,"show-pin-cursor"):(this.domService.addClassToElement(document.body,"show-pin-cursor"),this.highlightElement=we):this.domService.removeClassFromElement(document.body,"show-pin-cursor"))}},ke=>{this.loggingService.catch("Error in RecorderAnnotationService onWindowPointerMove$ subscription: ",ke)}),this.domService.onWindowKeyupEsc$().subscribe(ke=>{this.addRecorderMode$.value&&this.disableAddRecorderMode()},ke=>{this.loggingService.catch("Error in RecorderAnnotationService onWindowKeyupEsc$ subscription: ",ke)}),this.domService.onDocumentClick$().subscribe(ke=>{if(ke&&this.addRecorderMode$.value){if(ke.preventDefault(),ke.stopPropagation(),!WO(ke.target)){let we=this.domService.getBackgroundElement(ke.clientX,ke.clientY);we&&this.isElementInsideAllowedElements(we)}this.disableAddRecorderMode()}},ke=>{this.loggingService.catch("Error in RecorderAnnotationService onDocumentClick$ subscription: ",ke)}),this.addRecorderMode$.subscribe(ke=>{this.highlightElement&&this.domService.removeHighlightFromElement(this.highlightElement),ke?this.domService.addClassToElement(document.body,"snippyly-add-recorder-mode"):(this.domService.removeClassFromElement(document.body,"snippyly-add-recorder-mode"),this.domService.removeClassFromElement(document.body,"show-pin-cursor"))},ke=>{this.loggingService.catch("Error in RecorderAnnotationService addRecorderMode$ subscription: ",ke)}),this.domService.onWindowKeyupBackspace$().subscribe(ke=>{this.deleteRecorderPinAnnotations()},ke=>{this.loggingService.catch("Error in RecorderAnnotationService onWindowKeyupBackspace$ subscription: ",ke)}),this.domService.onWindowKeyupDelete$().subscribe(ke=>{this.deleteRecorderPinAnnotations()},ke=>{this.loggingService.catch("Error in RecorderAnnotationService onWindowKeyupDelete$ subscription: ",ke)}),this.recorderService.onRecordedData().subscribe(ke=>{this.recordedData=ke},ke=>{this.loggingService.catch("Error in RecorderAnnotationService onRecordedData subscription: ",ke)}),this.domService.getDeleteCommmentAnnotations$().subscribe(ke=>{ke?.length&&ke.forEach(we=>ee(this,null,function*(){}))},ke=>{this.loggingService.catch("Error in RecorderAnnotationService onWindowKeyupDelete$ subscription: ",ke)})}clearCache(){this.loggingService.log("%c[WB] Calling FUNCTION: clearCache in RecorderAnnotationService","color: green;");try{this.recorderAnnotationById$.next({}),this.documentPaths=null,this.allowedElementIds$.next([]),this.addRecorderMode$.next(!1),this.highlightElement=null}catch(e){this.loggingService.catch("Error in RecorderAnnotationService clearCache: ",e)}}getDocumentPaths(){this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentPaths","color: green;");try{this.docService.getDocumentPaths$().pipe(In(e=>{this.documentPaths=e})).subscribe(()=>{},e=>{this.loggingService.catch("Error in getDocumentPaths subscription: ",e)})}catch(e){this.loggingService.catch("Error in CursorService getDocumentPaths: ",e)}}getAnonymousAvatarImage(){return this.loggingService.log("%c[WB] Calling FUNCTION: getAnonymousAvatarImage","color: green;"),this.avatarService.generateUserImage()}setAllowedElementIds(e){this.allowedElementIds$.next(e||[])}getAllowedElementIds(){return this.allowedElementIds$.asObservable()}getDraftRecordings$(){return this.draftRecordings$.asObservable()}getRecorderDataByRecorderId(e){try{return this.recorderAnnotationById$.pipe(ce(()=>this.getAnnotationById(e)),ge(i=>ee(this,null,function*(){return i?yield this.createRecorderData(i,!0):void 0})))}catch(i){return this.loggingService.catch("Error in RecorderAnnotationService getRecorderDataByRecorderId: ",i),re(void 0)}}getRecorderDataByRecorderIds(e){return ee(this,null,function*(){try{let i={};return yield Promise.all(e.recorderIds.map(r=>ee(this,null,function*(){let a=this.getAnnotationById(r);if(!a)return;let s=yield this.createRecorderData(a,!0);s&&(i[r]=s)}))),{data:Object.keys(i).length>0?i:null}}catch(i){return this.loggingService.catch("Error in RecorderAnnotationService getRecorderDataByRecorderIds: ",i),{data:null}}})}fetchRecorderDataByRecorderIds(e){return ee(this,null,function*(){try{let i=this.recorderAnnotationById$.value,r=[],a=Object.values(i);return e?.recorderIds?.length&&(a=a.filter(s=>e.recorderIds.includes(s.annotationId))),a.length===0?[]:(yield Promise.all(a.map(s=>ee(this,null,function*(){if(!s)return;let c=yield this.createRecorderData(s,!0);c&&r.push(c)}))),r)}catch(i){return this.loggingService.catch("Error in RecorderAnnotationService fetchRecorderDataByRecorderIds: ",i),[]}})}getRecordings(e){try{return this.recorderAnnotationById$.pipe(ge(i=>ee(this,null,function*(){let r=[],a=Object.values(i);return e?.recorderIds?.length&&(a=a.filter(s=>e.recorderIds.includes(s.annotationId))),a.length===0?[]:(yield Promise.all(a.map(s=>ee(this,null,function*(){if(!s)return;let c=yield this.createRecorderData(s,!0);c&&r.push(c)}))),r)})),Ln(i=>(this.loggingService.catch("Error in RecorderAnnotationService getRecordings: ",i),re([]))))}catch(i){return this.loggingService.catch("Error in RecorderAnnotationService getRecordings: ",i),re([])}}setRecorderActionsService(e){try{this.recorderActionsService=e}catch(i){this.loggingService.catch("Error in RecorderAnnotationService setRecorderActionsService: ",i)}}getVttFileTextToArray(e){try{return this.transcriptionService.getVttFileTextToArray(e)}catch(i){this.loggingService.catch("Error in RecorderAnnotationService getVttFileTextToArray: ",i)}}getAllRecorderAnnotations(e,i,r){this.loggingService.log("%c[WB] Calling FUNCTION: getAllRecorderAnnotations","color: green;");let a,s;try{if(e&&(s=fn(e)),i&&typeof i=="object"){let c=Xo(i);a=fn(JSON.stringify(c))}}catch(c){this.loggingService.catch("Error in RecorderAnnotationService getAllRecorderAnnotations: ",c)}return Wn(this.afAuth).pipe(Ne(c=>!!c),ge(c=>this.isFeatureAllowed({firebaseUser:c,annotations:[],filteredAnnotations:[]})),ge(c=>c.featureAllowed?this.iamService.isUserAllowed$().pipe(ce(p=>(c.featureAllowed=p,c))):re(c)),ge(c=>c.featureAllowed?this.authService.isPlanExpired$().pipe(ce(p=>(c.featureAllowed=!p,c))):re(c)),ge(c=>c.featureAllowed?re(c).pipe(ge(p=>this.docService.getDocumentPaths$().pipe(ce(h=>(this.documentPaths=h,p.documentPaths=h,p)))),ge(p=>s?this.getDataFromDocumentIds([s]).pipe(ce(h=>(p.annotations=h||[],I({},p)))):this.docService.getDocumentIds$().pipe(ge(h=>{let _=h?.length>0?h.map(E=>E.documentId):[this.documentPaths?.documentId??""];return this.getDataFromDocumentIds(_).pipe(ce(E=>(p.annotations=E||[],I({},p))))}))),ge(p=>this.docService.getLocation$().pipe(ce(h=>(p.location=h,p)))),ge(p=>this.docService.getLocations$().pipe(ce(h=>(p.customLocations=h,p)))),ce(p=>{if(p.filteredAnnotations=[],s&&!a)return p.filteredAnnotations=p.annotations?.slice(),p;{let h=[];return a?h.push(a):(h.push(p?.location?.locationId),h.push(...Object.values(p?.customLocations||[]).map(_=>_.locationId))),p.filteredAnnotations=this.filterAnnotationsByLocationIds(p?.annotations,h),p}}),ge(p=>r?re(p):p?.annotations?.length?this.domService.onWindowResize$().pipe(ce(()=>p)):re(p)),ge(p=>r?re(p):p?.annotations?.length?this.domService.onDomChange$("RecorderAnnotationService getAllRecorderAnnotations").pipe(ce(()=>p)):re(p)),ce(p=>{let h=[];return p?.filteredAnnotations?.forEach(_=>{this.calculateRecorderAnnotationPosition(_),_?.targetElement||h.push(_)}),this.draftRecordings$.next(h),p}),ge(p=>p?.filteredAnnotations?re(p?.filteredAnnotations||[]):re([]))):re([])),Kt(_o))}isFeatureAllowed(e){return this.configService.getConfig$().pipe(Ne(i=>!!i),ce(i=>T(I({},e),{config:i})),ge(i=>this.authService.getUser$().pipe(ce(r=>T(I({},i),{user:r})))),ge(i=>Xi(i.config,i.user,Re.RECORDER)?re(T(I({},i),{featureAllowed:!0})):(this.loggingService.warn("Recorder feature is not allowed."),re(T(I({},i),{featureAllowed:!1})))))}getDataFromDocumentIds(e,i){return this.getDataFromDocuments({documentIds:e,filters:i})}getDataFromDocuments(e){if(this.configService?.getApiKey()){let{documentIds:i,filters:r}=e;if(i?.some(p=>!p)||!this.documentPaths)return re([]);let a=this.docService.getFolderConfig(),s=re([]),c={useCollectionGroup:!0,isCollection:!0,useQuery:!0};if(this.commonDbService.shouldUseFirestore()||(c.documentId=i?.length?i[0]:void 0,c.organizationId=this.documentPaths?.organizationId),a?.veltFolderId&&a?.allDocuments)s=this.commonDbService.dbListener({feature:"allRecorders",properties:T(I({},c),{firestoreQuery:[Fi(mt("metadata.apiKey","==",this.configService?.getApiKey()),mt("metadata.veltFolderId","==",a?.veltFolderId),mt("metadata.organizationId","==",this.documentPaths?.organizationId))]})});else{let p=[];for(let h=0;h<(i?.length??0);h+=U.LISTENER_BATCH_SIZE)p.push(i?.slice(h,h+U.LISTENER_BATCH_SIZE)??[]);s=Dn(p.map(h=>this.commonDbService.dbListener({feature:"allRecorders",properties:T(I({},c),{firestoreQuery:[Fi(mt("metadata.apiKey","==",this.configService?.getApiKey()),mt("metadata.documentId","in",h),mt("metadata.organizationId","==",this.documentPaths?.organizationId),...a?.veltFolderId?[mt("metadata.veltFolderId","==",a?.veltFolderId)]:[])]})}).pipe($r()))).pipe(ce(h=>ca(h)))}return s.pipe(ce(p=>({data:p?.data,operation:p?.operation})),ce(({data:p,operation:h})=>{let _=[];return p&&(_=Object.values(p).filter(E=>typeof E=="object")),{data:_,operation:h}}),ce(({data:p,operation:h})=>{if(!i)return{data:p,documentMap:{},operation:h};let _=p.reduce((E,D)=>{let B=D.metadata?.documentId;return B&&(E[B]||(E[B]=[]),E[B].push(D)),E},{});return{data:p,documentMap:_,operation:h}}),ce(({data:p,documentMap:h,operation:_})=>{if(!r)if(_?.type==="removed"){if(_?.ids?.length){let E=this.recorderAnnotationById$.value;_?.ids?.forEach(D=>{delete E?.[D]}),this.recorderAnnotationById$.next(E)}}else Object.entries(h).forEach(([E,D])=>{this.setRecorderAnnotationsByOrganizationIdAndDocumentId({organizationId:this.documentPaths?.organizationId,documentId:E,annotations:D})});return p}),Ln(p=>(this.loggingService.catch("Error in RecorderAnnotationService getDataFromDocumentId: ",p),re([]))))}else return re([])}setRecorderAnnotationsByOrganizationIdAndDocumentId({organizationId:e,documentId:i,annotations:r,queryHash:a}){try{if(i){e||(e=U.NO_ORGANIZATION_ID),a||(a=U.DEFAULT_QUERY_HASH);let s={};r?.forEach(p=>{p?.annotationId&&(s[p?.annotationId]=p)});let c=I(I({},this.recorderAnnotationById$.value),s);this.recorderAnnotationById$.next(c)}}catch(s){this.loggingService.catch("Error in RecorderAnnotationService setRecorderAnnotationsByOrganizationIdAndDocumentId:",s)}}filterAnnotationsByLocationIds(e,i){try{return e.filter(r=>i.includes(r.locationId))}catch(r){return this.loggingService.catch("Error in RecorderAnnotationService filterAnnotationsByLocations:",r),[]}}calculateRecorderAnnotationPosition(e){try{if(e.targetElement){let i=this.domService.getXPath(e.targetElement?.xpath);if(i){let r=i.iterateNext();if(r&&xo(r)){let a=r.getBoundingClientRect();if(a&&a.width&&a.height){let{height:s,width:c}=Ep(r);e.position={top:s*e.targetElement.topPercentage/100,left:c*e.targetElement.leftPercentage/100}}else e.position=null}else e.position=null}else e.position=null}}catch(i){this.loggingService.catch("Error in RecorderAnnotationService calculateRecorderAnnotationPosition:",i)}}getAnnotationById(e,i){try{let r=this.recorderAnnotationById$.value?.[e];if(r){let{documentId:a,organizationId:s}=i||{};if(a&&r.metadata?.documentId!==a||s&&r.metadata?.organizationId!==s)return}return r}catch(r){this.loggingService.catch("Error in RecorderAnnotationService getAnnotationById: ",r);return}}getBaseMetadataFromRecorderAnnotationId(e){try{let i=this.recorderAnnotationById$.value?.[e];if(i)return i.metadata}catch(i){this.loggingService.catch("Error in RecorderAnnotationService getBaseMetadataFromRecorderAnnotationId: ",i)}}getRecorderAnnotationById(e,i){return this.recorderAnnotationById$.pipe(ge(()=>{let r=this.getAnnotationById(e,i);return r?re(r):re(null)}),Ln(r=>(this.loggingService.catch("Error in RecorderAnnotationService getCommentAnnotationById: ",r),re(null))))}getRecorderAnnotationsByOrganizationIdAndDocumentId({organizationId:e,documentId:i}){try{let r={};return Object.values(this.recorderAnnotationById$.value).forEach(a=>{a?.metadata?.documentId==i&&a?.metadata?.organizationId==e&&(r[a?.annotationId]=a)}),Object.values(r)}catch(r){return this.loggingService.catch("Error in RecorderAnnotationService getRecorderAnnotationsByOrganizationIdAndDocumentId:",r),[]}}setLocationToRecorderAnnotation(e){try{let i=this.docService.getLocation();i?(e.locationId=i.locationId,e.location=i.location):(delete e.locationId,delete e.location);try{if(e.targetElement?.xpath){let r=this.domService.getElementFromXPath(e.targetElement.xpath),a=this.docService.getAdditionLocationFromElement(r);if(a){let s=this.docService.addLocation(a);s&&(e.locationId=s.locationId,e.location=s.location)}}}catch{}}catch(i){this.loggingService.catch("Error in RecorderAnnotationService setLocationToRecorderAnnotation:",i)}}addRecorder(e,i,r){this.loggingService.log("%c[WB] Calling FUNCTION: addRecorder","color: green;");try{let a=this.authService.getUser();if(a){if(a.isReadOnly||a.isAnonymous)return this.loggingService.catch("Anonymous/Readonly users cannot add recorders."),re(null);{i.from=a,i.color=U.DEFAULT_ANNOTATION_COLOR,i.lastUpdated=this.timestamp;let{topPositionX:s,topPositionY:c}=this.domService.getTopLeftPosition();i.positionX=s,i.positionY=c;let p=this.domService.getCurrentWindowSizeValue();if(i.screenWidth=p.screenWidth,i.screenHeight=p.screenHeight,i.screenScrollHeight=p.screenScrollHeight,i.recorderedElementPath="",e&&(i.targetElement=this.domService.getTargetElementForCursorPosition(e)),i?.targetElement?.xpath){let h=this.domService.getXPath(i.targetElement.xpath);if(h){let _=h.iterateNext();_&&(xo(_)||(i.targetElement=null))}}return this.setLocationToRecorderAnnotation(i),i.pageInfo=_i(),i.pageInfo&&(i.pageInfo.screenWidth=this.domService.getCurrentWindowSizeValue()?.screenWidth),this.saveRecorderToDb(i,r)}}else return re(null)}catch(a){return this.loggingService.catch("Error in RecorderAnnotationService addRecorder: ",a),re(null)}}saveRecorderToDb(e,i){this.loggingService.log("%c[WB] Calling FUNCTION: saveRecorderToDb","color: green;");try{return this.authService.getUser()&&this.authService.isFeatureAllowed(Re.RECORDER)?this.docService.getDocumentPaths$().pipe(Ne(r=>!!r),Je(1),ge(r=>(this.documentPaths=r,this.loggingService.log(this.documentPaths),this.databaseService.getDb().pipe(Ne(a=>!!a),Je(1),ge(a=>ee(this,null,function*(){if(this.db=a,this.loggingService.log(this.db),this.documentPaths?.recorder){let s=on(this.db,`${this.documentPaths?.recorder}`);e.annotationId=this.commonDbService.generateDocumentId(),e.pageInfo&&(e.pageInfo.recorderUrl=this.generateRecorderUrl(e));let c=JSON.parse(JSON.stringify(e));if(c.position=null,!c?.metadata?.documentId){c?.metadata||(c.metadata={});let _=this.docService.getBaseMetadata("recorder",{commentAnnotationId:e.commentAnnotationId});c.metadata=I(I({},c?.metadata),_)}let{documentId:p,organizationId:h}=c?.metadata||{};return yield this.commonDbService.setData({feature:"recorder",properties:{id:e.annotationId,documentId:p,organizationId:h},data:JSON.parse(JSON.stringify(c))}),this.analyticsService.trackEvent(Z.Events.Recording.RECORDING_ADDED,{annotationId:e.annotationId,recorderType:e.recordingType,recorderMode:e.mode,recorderSize:e?.attachments?.length?e?.attachments[0]?.size:e?.attachment?.size,sourceFeature:i||"recording"}),this.setVideoEditorAutoOpen({[e.annotationId]:!0}),this.processRecording(e,"recording","merge"),this.updateNotificationsDatabase(e,Jf.ADDED),e}else return null})))))):re(null)}catch(r){return this.loggingService.catch("Error in RecorderAnnotationService saveRecorderToDb: ",r),re(null)}}processRecording(e,i,r){return ee(this,null,function*(){try{let a=Cr(this.functions,Zn?.cloudFunction?.processRecording,{timeout:36e5}),s=this.docService.getDocumentPaths();e?.metadata?.documentId&&(s=new xd({apiKey:this.configService.getApiKey(),clientDocumentId:e.metadata.clientDocumentId,clientOrganizationId:e.metadata.clientOrganizationId,documentId:e.metadata.documentId,organizationId:e.metadata.organizationId}));let c={databaseUrl:this.authService.getFirebaseConfig()?.firebaseOptions?.databaseURL,entirePath:s?.recorder+e?.annotationId,fromUser:this.authService.getUser(),clientOrganizationId:s?.clientOrganizationId,clientDocumentId:s?.clientDocumentId,apiKey:this.configService.getApiKey(),sdkVersion:Ta(),sdkType:this.configService.getSdkType(),useFirestore:this.commonDbService.shouldUseFirestore(),storageBucket:this.authService.getFirebaseConfig()?.firebaseOptions?.storageBucket,documentPath:s?.recorder,annotationId:e?.annotationId,sourceFeature:i||"recording",annotationData:e,skipMerge:!0,transcriptionEnabled:this.getRecordingTranscriptionEnabled(),type:r,returnType:"transcription"};if(c?.useFirestore){let D=yield this.recorderUtilsService.encryptRecorderAnnotation(e);c.annotationData=D}let p=this.documentPaths?.organizationId,h=this.documentPaths?.documentId;e?.metadata?.documentId&&(h=e.metadata.documentId,p=e.metadata.organizationId);let _=`${this.configService.getApiKey()}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_RECORDER}`;p&&(_=`${this.configService.getApiKey()}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${p}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${h}/${U.FIREBASE_PARTIAL_PATH_RECORDER}`),c.bucketPath=_;let E=yield a(c);if(E.data&&this.recordedData){let D=this.getAnnotationById(this.recordedData.id);if(!D)return;let B=yield this.createRecorderData(D,!1);if(B){if(E?.data?.transcriptedText&&(B.transcription.contentSummary=E.data.transcriptedText),E.data.vttUrl)try{let G=yield this.transcriptionService.getFileContent(E.data.vttUrl).toPromise();G&&(B.transcription.transcriptSegments=this.getVttFileTextToArray(G),B.transcription.vttFileUrl=E.data.vttUrl)}catch(G){this.loggingService.catch("Error fetching VTT content: ",G)}D?.attachments?.length&&this.recordedData&&(this.recordedData.videoUrl=D.attachments[0].url),this.recorderActionsService?.onTranscriptionDone(B),this.recorderActionsService?.onRecordingDone(B)}this.recorderService.setRecordedData(this.recordedData)}}catch(a){this.loggingService.catch("Error in RecorderAnnotationService processRecording: ",a)}})}getDocumentIdAndOrganizationIdFromRecorderAnnotation(e){try{return{documentId:e?.metadata?.documentId,organizationId:e?.metadata?.organizationId}}catch(i){return this.loggingService.catch("Error in RecorderAnnotationService getDocumentIdAndOrganizationIdFromRecorderAnnotation: ",i),{}}}createRecorderData(e,i=!1){return ee(this,null,function*(){try{let r=sv(e?.metadata||{}),a=aS(e?.from),s={recorderId:e?.annotationId||"",from:a,assets:[],metadata:r,transcription:{transcriptSegments:[],vttFileUrl:"",contentSummary:""}};if(e?.transcription?.transcriptedText&&(s.transcription.contentSummary=e.transcription.transcriptedText),e?.attachments?.forEach(c=>{c?.url&&s.assets.push({url:c.url,mimeType:c.mimeType,fileName:c.name,fileSizeInBytes:c.size,fileFormat:c.type,thumbnailUrl:c.thumbnail})}),i&&e?.transcription?.vttUrl)try{let c=yield this.transcriptionService.getFileContent(e.transcription.vttUrl).toPromise();c&&(s.transcription.transcriptSegments=this.getVttFileTextToArray(c),s.transcription.vttFileUrl=e.transcription.vttUrl)}catch(c){this.loggingService.catch("Error fetching VTT content: ",c)}return s}catch(r){return this.loggingService.catch("Error in RecorderAnnotationService createRecorderData: ",r),null}})}updateRecorder(e,i=!1,r){try{r&&this.setLocationToRecorderAnnotation(e),i&&this.updateNotificationsDatabase(e,Jf.UPDATED),this.updateRecorderToDb(e)}catch(a){this.loggingService.catch("Error in RecorderAnnotationService updateRecorder: ",a)}}resolveRecorder(e){try{this.domService.resetSelectedAnnotationsMap(!1),this.updateNotificationsDatabase(e,Jf.RESOLVED),this.updateRecorderToDb(e),this.domService.updateSelectedAnnotationInMap([e])}catch(i){this.loggingService.catch("Error in RecorderAnnotationService resolveRecorder: ",i)}}updateRecorderToDb(e){this.loggingService.log("%c[WB] Calling FUNCTION: updateRecorderToDb","color: green;");try{if(e?.targetElement?.xpath){let i=this.domService.getXPath(e.targetElement.xpath);if(i){let r=i.iterateNext();r&&(xo(r)||(e.targetElement=null))}}if(this.domService.updateSelectedAnnotationInMap([e]),this.authService.getUser()&&this.authService.isFeatureAllowed(Re.RECORDER)){let i=JSON.parse(JSON.stringify(e));if(i.position=null,!i?.metadata?.documentId){i?.metadata||(i.metadata={});let s=this.docService.getBaseMetadata();i.metadata=I(I({},i?.metadata),s)}let{documentId:r,organizationId:a}=this.getDocumentIdAndOrganizationIdFromRecorderAnnotation(e);this.commonDbService.setData({feature:"recorder",properties:{id:e.annotationId,documentId:r,organizationId:a},data:JSON.parse(JSON.stringify(i))})}}catch(i){this.loggingService.catch("Error in RecorderAnnotationService updateRecorderToDb: ",i)}}deleteRecorderPinAnnotations(){try{let e=this.domService.getSelectedAnnotationsMap(),i=this.authService.getUser(),r=[];Object.keys(e).forEach(a=>ee(this,null,function*(){let s=e[a];s.type==="recorder"&&i&&s.from&&(i?.isAdmin||s.from.userId===i.userId)&&r.push(s)})),r?.length&&(this.analyticsService.trackEvent(Z.Events.Recording.RECORDING_DELETE_TRIGGERED,{annotationId:r.map(a=>a.annotationId).join()}),this.dialog.open(da,{data:{title:"Delete recording?",message:"This selected recording will be deleted.",yesButton:"Delete",noButton:"Cancel",darkMode:this.recorderContainerDarkMode$.value,variant:"recorder"}}).afterClosed().pipe(Je(1)).subscribe(a=>{a&&(r.forEach(s=>ee(this,null,function*(){yield this.deleteRecorderPinAnnotation(s)})),setTimeout(()=>{document.querySelectorAll(`[${U.SNIPPYLY_HIGHLIGHT}]`).forEach(c=>{this.domService.removeHighlightFromElement(c)})},100))}),this.domService.resetSelectedAnnotationsMap(!0,"recorder"))}catch(e){this.loggingService.catch("Error in RecorderAnnotationService deleteRecorderPinAnnotations: ",e)}}deleteRecorderPinAnnotation(e,i){if(this.authService.isFeatureAllowed(Re.RECORDER)&&this.documentPaths?.recorder&&e?.annotationId){this.updateNotificationsDatabase(e,Jf.DELETED),e?.attachment&&this.storageService.deleteAttachment({attachment:e.attachment}),e?.attachments&&e.attachments.forEach(s=>{this.storageService.deleteAttachment({attachment:s}).catch(c=>{this.loggingService.catch("Error in RecorderAnnotationService deleteRecorderPinAnnotation delete attachment: ",c)})}),e?.transcription&&(e?.transcription?.srtBucketPath&&this.storageService.deleteFileFromPath(e.transcription.srtBucketPath).catch(s=>{this.loggingService.catch("Error in RecorderAnnotationService deleteRecorderPinAnnotation delete srt file: ",s)}),e?.transcription?.vttBucketPath&&this.storageService.deleteFileFromPath(e.transcription.vttBucketPath).catch(s=>{this.loggingService.catch("Error in RecorderAnnotationService deleteRecorderPinAnnotation delete vtt file: ",s)})),this.analyticsService.trackEvent(Z.Events.Recording.RECORDING_DELETED,{annotationId:e.annotationId,recorderType:e.recordingType,recorderMode:e.mode,recorderSize:e?.attachments?.length?e?.attachments[0]?.size:e.attachment?.size,sourceFeature:i||"recording"});let{documentId:r,organizationId:a}=this.getDocumentIdAndOrganizationIdFromRecorderAnnotation(e);return this.commonDbService.deleteData({feature:"recorder",properties:{id:e.annotationId,documentId:r,organizationId:a}}).then(s=>ee(this,null,function*(){let c=yield this.createRecorderData(e,!0);c&&this.recorderActionsService?.onDeleteRecording(c)}))}else return Promise.resolve()}enableAddRecorderMode(){this.authService.isFeatureAllowed(Re.RECORDER)?this.addRecorderMode$.next(!0):this.loggingService.catch("Error in RecorderAnnotationService enableAddRecorderMode: ","Recorder feature is not enabled.")}disableAddRecorderMode(){this.addRecorderMode$.next(!1)}addRecorderModeChange(){return this.addRecorderMode$.asObservable()}setRecorderContainerDarkMode(e){try{if(this.recorderContainerDarkMode$.value===e)return;this.recorderContainerDarkMode$.next(e)}catch(i){this.loggingService.catch("Error in RecorderAnnotationService setRecorderContainerDarkMode: ",i)}}getRecorderContainerDarkMode(){return this.recorderContainerDarkMode$.asObservable()}enableRecordingTranscription(){try{if(this.analyticsService.setFeatureConfig({feature:Re.RECORDER,config:{recordingTranscription:!0}}),this.recordingTranscriptionEnabled$.value===!0)return;this.recordingTranscriptionEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in RecorderAnnotationService enableRecordingTranscription: ",e)}}disableRecordingTranscription(){try{if(this.analyticsService.setFeatureConfig({feature:Re.RECORDER,config:{recordingTranscription:!1}}),this.recordingTranscriptionEnabled$.value===!1)return;this.recordingTranscriptionEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in RecorderAnnotationService disableRecordingTranscription: ",e)}}getRecordingTranscriptionEnabled(){return this.recordingTranscriptionEnabled$.value}getRecordingTranscriptionEnabled$(){return this.recordingTranscriptionEnabled$.asObservable()}get timestamp(){return this.commonDbService.getServerTimestamp()}isElementInsideAllowedElements(e){try{return this.domService.isElementInsideListedElementIds(e,this.allowedElementIds$.value)}catch(i){return this.loggingService.catch("Error in RecorderAnnotationService isElementInsideAllowedElements: ",i),!1}}attachRecorder(e){let i=document.getElementById(e);if(i){let r=this.domService.getXPath(i),a=this.getRecorderPinAnnotationObject();a&&(a.targetElement={xpath:r,topPercentage:50,leftPercentage:90},this.saveRecorderToDb(a))}}getRecorderPinAnnotationObject(){let e=this.authService.getUser();if(e)if(e.isReadOnly||e.isAnonymous)this.loggingService.catch("Anonymous/Readonly users cannot add recorders.");else{let i=new Pp;i.from=e,i.color=U.DEFAULT_ANNOTATION_COLOR,i.lastUpdated=this.timestamp;let{topPositionX:r,topPositionY:a}=this.domService.getTopLeftPosition();i.positionX=r,i.positionY=a;let s=this.domService.getCurrentWindowSizeValue();i.screenWidth=s.screenWidth,i.screenHeight=s.screenHeight,i.screenScrollHeight=s.screenScrollHeight,i.recorderedElementPath="";let c=this.docService.getLocation();return c&&(i.locationId=c.locationId,i.location=c.location),i}return null}updateNotificationsDatabase(e,i,r={}){try{let a=I({annotationData:e,actionType:i,notificationSource:"recorder",recordingType:e?.recordingType},r);this.notificationService.updateNotificationDatabase(a)}catch(a){this.loggingService.catch("Error in RecorderAnnotationService updateNotificationsDatabase: ",a)}}getUserContacts$(){return this.contactService.getUserContacts$()}addUserContact(e){this.contactService.addUserContact(e)}getRecorderUrl(e){try{return e?.pageInfo?.recorderUrl?e.pageInfo.recorderUrl:e?.annotationId?(e?.pageInfo||(e.pageInfo=_i(),e.pageInfo&&(e.pageInfo.screenWidth=this.domService.getCurrentWindowSizeValue()?.screenWidth)),e.pageInfo.recorderUrl=this.generateRecorderUrl(e),this.updateRecorder(e),e.pageInfo?.recorderUrl):""}catch(i){this.loggingService.catch("Error in RecorderAnnotationService getRecorderUrl: ",i);return}}uploadFile(e,i){let r=this.documentPaths?.organizationId,a=this.documentPaths?.documentId;i?.metadata?.documentId&&(a=i.metadata.documentId,r=i.metadata.organizationId);let s=`${U.FIREBASE_PARTIAL_PATH_DOCS}/${a}/${U.FIREBASE_PARTIAL_PATH_RECORDER}`;return r&&(s=`${U.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${r}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${a}/${U.FIREBASE_PARTIAL_PATH_RECORDER}`),this.storageService.uploadFile({path:s,file:e})}downloadAttachment(e){this.storageService.downloadAttachment(e)}deleteAttachment(e){return this.storageService.deleteAttachment({attachment:e})}generateRecorderUrl(e){let i=new URL(window.location.href);return i.searchParams.delete(U.URL_PARAMS.RECORDER_ID),i.searchParams.append(U.URL_PARAMS.RECORDER_ID,e.annotationId),i.href}setRecorderNotesFound(e){try{this.recorderNotesFound$.next(e)}catch(i){this.loggingService.catch("Error in RecorderAnnotationService setRecorderNotesFound: ",i)}}getRecorderNotesFound$(){try{return this.recorderNotesFound$.asObservable()}catch(e){return this.loggingService.catch("Error in RecorderAnnotationService getRecorderNotesFound: ",e),re(!1)}}getRecorderNotesFound(){try{return this.recorderNotesFound$.value}catch(e){return this.loggingService.catch("Error in RecorderAnnotationService getRecorderNotesFound: ",e),!1}}trimVideoRecording(e,i){return ee(this,null,function*(){try{let s=(yield Cr(this.functions,Zn?.cloudFunction?.trimVideoRecording,{timeout:36e5})({videoUrl:e,segments:i})).data;if(s&&s.videoData){let c=atob(s.videoData),p=new ArrayBuffer(c.length),h=new Uint8Array(p);for(let _=0;_<c.length;_++)h[_]=c.charCodeAt(_);return new Blob([h],{type:s.mimeType||"video/mp4"})}return null}catch(r){return this.loggingService.catch("Error in RecorderAnnotationService trimVideoRecording: ",r),null}})}setVideoEditorAutoOpen(e){try{this.videoEditorAutoOpen$.next(I(I({},this.videoEditorAutoOpen$.value),e))}catch(i){this.loggingService.catch("Error in RecorderAnnotationService setVideoEditorAutoOpen: ",i)}}getVideoEditorAutoOpen$(){try{return this.videoEditorAutoOpen$.asObservable()}catch(e){return this.loggingService.catch("Error in RecorderAnnotationService getVideoEditorAutoOpen: ",e),re({})}}getVideoEditorAutoOpen(){try{return this.videoEditorAutoOpen$.value}catch(e){return this.loggingService.catch("Error in RecorderAnnotationService getVideoEditorAutoOpen: ",e),{}}}};o.\u0275fac=function(i){return new(i||o)(J(Qe),J($t),J(lt),J(pn),J(bn),J(je),J(Fe),J(vi),J(gn),J(Vo),J(gm),J(gi),J(Bp),J(qi),J(y),J(Vn),J(Wv),J(yi),J(jv))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var LM=class extends li{constructor(o){super(o),this.getService(y).log("%c[WB] Creating CLASS: CommentElement","color: blue;"),this.getAllCommentAnnotations=this._getAllCommentAnnotations,this.deleteSelectedComment=this._deleteSelectedComment,this.enableTextComments=this._enableTextComments,this.disableTextComments=this._disableTextComments,this.allowedElementIds=this._allowedElementIds,this.allowedElementClassNames=this._allowedElementClassNames,this.allowedElementQuerySelectors=this._allowedElementQuerySelectors,this.disableFloatingCommentDialog=this._disableFloatingComments,this.enableFloatingCommentDialog=this._enableFloatingComments,this.attachComment=this._attachComment,this.openCommentSidebar=this._openCommentSidebar,this.closeCommentSidebar=this._closeCommentSidebar,this.toggleCommentSidebar=this._toggleCommentSidebar,this.enableModeratorMode=this._enableModeratorMode,this.disableModeratorMode=this._disableModeratorMode,this.enableStreamMode=this._enableStreamMode,this.disableStreamMode=this._disableStreamMode,this.enableSignInButton=this._enableSignInButton,this.disableSignInButton=this._disableSignInButton,this.enableUpgradeButton=this._enableUpgradeButton,this.disableUpgradeButton=this._disableUpgradeButton,this.onCommentModeChange=this._onCommentModeChange,this.enableAttachments=this._enableAttachment,this.disableAttachments=this._disableAttachment,this.isUserGlobalContact=this._isUserGlobalContact,this.enableDeviceInfo=this._enableDeviceInfo,this.disableDeviceInfo=this._disableDeviceInfo,this.enableCommentMode=this._enableCommentMode,this.disableCommentMode=this._disableCommentMode,this.enablePersistentCommentMode=this._enablePersistentCommentMode,this.disablePersistentCommentMode=this._disablePersistentCommentMode,this.enableCommentIndex=this._enableCommentIndex,this.disableCommentIndex=this._disableCommentIndex,this.enablePopoverMode=this._enablePopoverMode,this.disablePopoverMode=this._disablePopoverMode,this.enableDialogOnHover=this._enableDialogOnHover,this.enablePopoverTriangleComponent=this._enablePopoverTriangleComponent,this.disablePopoverTriangleComponent=this._disablePopoverTriangleComponent,this.disableDialogOnHover=this._disableDialogOnHover,this.enableDialogOnTargetElementClick=this._enableDialogOnTargetElementClick,this.disableDialogOnTargetElementClick=this._disableDialogOnTargetElementClick,this.enablePriority=this._enablePriority,this.disablePriority=this._disablePriority,this.enableStatus=this._enableStatus,this.disableStatus=this._disableStatus,this.enableResolveButton=this._enableResolveButton,this.disableResolveButton=this._disableResolveButton,this.enableGhostComments=this._enableGhostComments,this.disableGhostComments=this._disableGhostComments,this.enableGhostCommentsIndicator=this._enableGhostCommentsIndicator,this.disableGhostCommentsIndicator=this._disableGhostCommentsIndicator,this.setCustomStatus=this._setCustomStatus,this.setCustomPriority=this._setCustomPriority,this.setCustomCategory=this._setCustomCategory,this.enableInboxMode=this._enableInboxMode,this.disableInboxMode=this._disableInboxMode,this.enableAutoCategorize=this._enableAutoCategorize,this.disableAutoCategorize=this._disableAutoCategorize,this.enableDarkMode=this._enableDarkMode,this.disableDarkMode=this._disableDarkMode,this.setContextProvider=this._setContextProvider,this.enableSuggestionMode=this._enableSuggestionMode,this.disableSuggestionMode=this._disableSuggestionMode,this.enableMobileMode=this._enableMobileMode,this.disableMobileMode=this._disableMobileMode,this.enableInlineCommentMode=this._enableInlineCommentMode,this.disableInlineCommentMode=this._disableInlineCommentMode,this.enableMinimap=this._enableMinimap,this.disableMinimap=this._disableMinimap,this.showCommentsOnDom=this._showCommentsOnDom,this.hideCommentsOnDom=this._hideCommentsOnDom,this.enableCommentTool=this._enableCommentTool,this.disableCommentTool=this._disableCommentTool,this.setTotalMediaLength=this._setTotalMediaLength,this.onCommentAdd=this._onCommentAdd,this.onCommentUpdate=this._onCommentUpdate,this.addCommentOnSelectedText=this._addCommentOnSelectedText,this.enableSidebarUrlNavigation=this._enableSidebarUrlNavigation,this.disableSidebarUrlNavigation=this._disableSidebarUrlNavigation,this.setDStrategy=this._setDStrategy,this.enableSidebarButtonOnCommentDialog=this._enableSidebarButtonOnCommentDialog,this.disableSidebarButtonOnCommentDialog=this._disableSidebarButtonOnCommentDialog,this.onSidebarButtonOnCommentDialogClick=this._onSidebarButtonOnCommentDialogClick,this.enableReactions=this._enableReactions,this.disableReactions=this._disableReactions,this.setRecordings=this._setRecordings,this.addCommentOnElement=this._addCommentOnElement,this.enablePrivateCommentMode=this._enablePrivateCommentMode,this.disablePrivateCommentMode=this._disablePrivateCommentMode,this.enableScrollToComment=this._enableScrollToComment,this.disableScrollToComment=this._disableScrollToComment,this.enableUserMentions=this._enableUserMentions,this.disableUserMentions=this._disableUserMentions,this.setCommentSidebarFilters=this._setCommentSidebarFilters,this.enableCommentPinHighlighter=this._enableCommentPinHighlighter,this.disableCommentPinHighlighter=this._disableCommentPinHighlighter,this.enableDeleteOnBackspace=this._enableDeleteOnBackspace,this.disableDeleteOnBackspace=this._disableDeleteOnBackspace,this.enableHotkey=this._enableHotkey,this.disableHotkey=this._disableHotkey,this.enableDeviceIndicatorOnCommentPins=this._enableDeviceIndicatorOnCommentPins,this.disableDeviceIndicatorOnCommentPins=this._disableDeviceIndicatorOnCommentPins,this.getElementRefByAnnotationId=this._getElementRefByAnnotationId,this.scrollToCommentByAnnotationId=this._scrollToCommentByAnnotationId,this.selectCommentByAnnotationId=this._selectCommentByAnnotationId,this.enableRecordingSummary=this._enableRecordingSummary,this.disableRecordingSummary=this._disableRecordingSummary,this.enableRecordingTranscription=this._enableRecordingTranscription,this.disableRecordingTranscription=this._disableRecordingTranscription,this.enableRecordingCountdown=this._enableRecordingCountdown,this.disableRecordingCountdown=this._disableRecordingCountdown,this.setUnreadIndicatorMode=this._setUnreadIndicatorMode,this.enableEnterKeyToSubmit=this._enableEnterKeyToSubmit,this.disableEnterKeyToSubmit=this._disableEnterKeyToSubmit,this.enablePinShadowDOM=this._enablePinShadowDOM,this.disablePinShadowDOM=this._disablePinShadowDOM,this.enableDialogShadowDOM=this._enableDialogShadowDOM,this.disableDialogShadowDOM=this._disableDialogShadowDOM,this.enableSidebarShadowDOM=this._enableSidebarShadowDOM,this.disableSidebarShadowDOM=this._disableSidebarShadowDOM,this.enableChangeDetectionInCommentMode=this._enableChangeDetectionInCommentMode,this.disableChangeDetectionInCommentMode=this._disableChangeDetectionInCommentMode,this.showResolvedCommentsOnDom=this._showResolvedCommentsOnDom,this.hideResolvedCommentsOnDom=this._hideResolvedCommentsOnDom,this.setCustomReactions=this._setCustomReactions,this.onCommentSelectionChange=this._onCommentSelectionChange,this.getUnreadCommentCountByAnnotationId=this._getUnreadCommentCountByAnnotationId,this.getUnreadCommentAnnotationCountOnCurrentDocument=this._getUnreadCommentAnnotationCountOnCurrentDocument,this.getUnreadCommentCountOnCurrentDocument=this._getUnreadCommentCountOnCurrentDocument,this.getUnreadCommentAnnotationCountByLocationId=this._getUnreadCommentAnnotationCountByLocationId,this.getUnreadCommentCountByLocationId=this._getUnreadCommentCountByLocationId,this.updateCommentDialogPosition=this._updateCommentDialogPosition,this.enableAreaComment=this._enableAreaComment,this.disableAreaComment=this._disableAreaComment,this.setPinCursorImage=this._setPinCursorImage,this.addManualComment=this._addManualComment,this.createCustomListDataOnAnnotation=this._createCustomListDataOnAnnotation,this.createCustomListDataOnComment=this._createCustomListDataOnComment,this.excludeLocationIdsFromSidebar=this._excludeLocationIdsFromSidebar,this.enableBubbleOnPin=this._enableBubbleOnPin,this.disableBubbleOnPin=this._disableBubbleOnPin,this.enableBubbleOnPinHover=this._enableBubbleOnPinHover,this.disableBubbleOnPinHover=this._disableBubbleOnPinHover,this.enableMultiThreadMode=this._enableMultiThread,this.disableMultiThreadMode=this._disableMultiThread,this.enableMultiThread=this._enableMultiThread,this.disableMultiThread=this._disableMultiThread,this.updateContext=this._updateContext,this.getSelectedComments=this._getSelectedComments,this.enableDeleteReplyConfirmation=this._enableDeleteReplyConfirmation,this.disableDeleteReplyConfirmation=this._disableDeleteReplyConfirmation,this.onCopyLink=this._onCopyLink,this.getCommentAnnotationById=this._getCommentAnnotationById,this.enableCollapsedComments=this._enableCollapsedComments,this.disableCollapsedComments=this._disableCollapsedComments,this.onCommentSidebarActionButtonClick=this._onCommentSidebarActionButtonClick,this.setCommentSidebarData=this._setCommentSidebarData,this.onCommentSidebarInit=this._onCommentSidebarInit,this.onCommentSidebarData=this._onCommentSidebarData,this.setCommentSidebarDefaultCustomActions=this._setCommentSidebarDefaultCustomActions,this.enableSidebarCustomActions=this._enableSidebarCustomActions,this.disableSidebarCustomActions=this._disableSidebarCustomActions,this.enableQueryParamsComments=this._enableQueryParamsComments,this.disableQueryParamsComments=this._disableQueryParamsComments,this.enableResolveStatusAccessAdminOnly=this._enableResolveStatusAccessAdminOnly,this.disableResolveStatusAccessAdminOnly=this._disableResolveStatusAccessAdminOnly,this.enableSeenByUsers=this._enableSeenByUsers,this.disableSeenByUsers=this._disableSeenByUsers,this.enableShortUserName=this._enableShortUserName,this.disableShortUserName=this._disableShortUserName,this.addCommentAnnotation=this._addCommentAnnotation,this.approveCommentAnnotation=this._approveCommentAnnotation,this.acceptCommentAnnotation=this._acceptCommentAnnotation,this.rejectCommentAnnotation=this._rejectCommentAnnotation,this.subscribeCommentAnnotation=this._subscribeCommentAnnotation,this.unsubscribeCommentAnnotation=this._unsubscribeCommentAnnotation,this.deleteCommentAnnotation=this._deleteCommentAnnotation,this.getCommentAnnotations=this._getCommentAnnotations,this.getCommentAnnotationsCount=this._getCommentAnnotationsCount,this.assignUser=this._assignUser,this.updatePriority=this._updatePriority,this.updateStatus=this._updateStatus,this.updateAccess=this._updateAccess,this.resolveCommentAnnotation=this._resolveCommentAnnotation,this.getLink=this._getLink,this.copyLink=this._copyLink,this.addComment=this._addComment,this.updateComment=this._updateComment,this.deleteComment=this._deleteComment,this.getComment=this._getComment,this.addAttachment=this._addAttachment,this.deleteAttachment=this._deleteAttachment,this.getAttachment=this._getAttachment,this.deleteRecording=this._deleteRecording,this.getRecording=this._getRecording,this.addReaction=this._addReaction,this.deleteReaction=this._deleteReaction,this.toggleReaction=this._toggleReaction,this.enableReadOnly=this._enableReadOnly,this.disableReadOnly=this._disableReadOnly,this.enableCustomAutocompleteSearch=this._enableCustomAutocompleteSearch,this.disableCustomAutocompleteSearch=this._disableCustomAutocompleteSearch,this.fetchCommentAnnotations=this._fetchCommentAnnotations,this.setTransformContext=this._setTransformContext,this.enableSvgAsImg=this._enableSvgAsImg,this.disableSvgAsImg=this._disableSvgAsImg,this.enableFullExpanded=this._enableFullExpanded,this.disableFullExpanded=this._disableFullExpanded,this.enableCommentToNearestAllowedElement=this._enableCommentToNearestAllowedElement,this.disableCommentToNearestAllowedElement=this._disableCommentToNearestAllowedElement,this.enableDraftMode=this._enableDraftMode,this.disableDraftMode=this._disableDraftMode,this.on=this._on}_getAllCommentAnnotations(o,t){this.getService(y).log("%c[WB] Calling FUNCTION: getOnlineUsers","color: green;");try{return this.trackEvent(Z.Events.Comments.GET_ALL_COMMENT_ANNOTATIONS_TRIGGERED,{payload:{documentId:o,location:t}}),this.getService(Te).getAllCommentAnnotations({customClientDocumentId:o,params:t,excludeDomChanges:!0,skipPositionCalculation:!0}).pipe(ce(e=>e?.length?e?.map(i=>$n(i)):e))}catch(e){return this.getService(y).catch("Error in _getLiveCommentsOnCurrentDocument: ",e),re(null)}}_deleteSelectedComment(){this.getService(y).log("%c[WB] Calling FUNCTION: deleteSelectedComment","color: green;");try{return this.trackEvent(Z.Events.Comments.DELETE_SELECTED_COMMENT_TRIGGERED),this.getService(Te).deleteCommentPinAnnotations("commentElement")}catch(o){return this.getService(y).catch("Error in _deleteSelectedComment: ",o),Promise.resolve(null)}}_enableTextComments(){this.getService(y).log("%c[WB] Calling FUNCTION: enableTextComments","color: green;");try{this.trackEvent(Z.Events.Comments.ENABLE_TEXT_COMMENTS_TRIGGERED),this.getService(Te).enableTextComments()}catch(o){this.getService(y).catch("Error in _enableTextComments: ",o)}}_disableTextComments(){this.getService(y).log("%c[WB] Calling FUNCTION: disableTextComments","color: green;");try{this.trackEvent(Z.Events.Comments.DISABLE_TEXT_COMMENTS_TRIGGERED),this.getService(Te).disableTextComments()}catch(o){this.getService(y).catch("Error in _disableTextComments: ",o)}}_allowedElementIds(o){this.getService(y).log("%c[WB] Calling FUNCTION: allowedElementIds","color: green;");try{this.trackEvent(Z.Events.Comments.ALLOWED_ELEMENT_IDS_TRIGGERED,{payload:{elementIds:o}}),this.getService(Te).setAllowedElementIds(o)}catch(t){this.getService(y).catch("Error in allowedElementIds: ",t)}}_allowedElementClassNames(o){this.getService(y).log("%c[WB] Calling FUNCTION: allowedElementClassNames","color: green;");try{this.trackEvent(Z.Events.Comments.ALLOWED_ELEMENT_CLASS_NAMES_TRIGGERED,{payload:{classNames:o}}),this.getService(Te).setAllowedElementClassNames(o)}catch(t){this.getService(y).catch("Error in allowedElementClassNames: ",t)}}_allowedElementQuerySelectors(o){this.getService(y).log("%c[WB] Calling FUNCTION: allowedElementQuerySelectors","color: green;");try{this.trackEvent(Z.Events.Comments.ALLOWED_ELEMENT_QUERY_SELECTORS_TRIGGERED,{payload:{querySelectors:o}}),this.getService(Te).setAllowedElementQuerySelectors(o)}catch(t){this.getService(y).catch("Error in allowedElementQuerySelectors: ",t)}}_disableFloatingComments(){this.getService(y).log("%c[WB] Calling FUNCTION: disableFloatingComments","color: green;");try{this.trackEvent(Z.Events.Comments.DISABLE_FLOATING_COMMENT_DIALOG_TRIGGERED),this.getService(Te).disableFloatingComments(!0)}catch(o){this.getService(y).catch("Error in _disableFloatingComments: ",o)}}_enableFloatingComments(){this.getService(y).log("%c[WB] Calling FUNCTION: enableFloatingComments","color: green;");try{this.trackEvent(Z.Events.Comments.ENABLE_FLOATING_COMMENT_DIALOG_TRIGGERED),this.getService(Te).disableFloatingComments(!1)}catch(o){this.getService(y).catch("Error in _enableFloatingComments: ",o)}}_attachComment(o){this.getService(y).log("%c[WB] Calling FUNCTION: attachComment","color: green;");try{this.trackEvent(Z.Events.Comments.ATTACH_COMMENT_TRIGGERED,{payload:{elementId:o}}),this.getService(Te).attachComment(o,["id","data-id"])}catch(t){this.getService(y).catch("Error in _attachComment: ",t)}}_openCommentSidebar(){this.getService(y).log("%c[WB] Calling FUNCTION: openCommentSidebar","color: green;");try{this.trackEvent(Z.Events.Comments.OPEN_COMMENT_SIDEBAR_TRIGGERED),this.getService(Te).setSidebarVisibility(!0,!0)}catch(o){this.getService(y).catch("Error in _openCommentSidebar: ",o)}}_closeCommentSidebar(){this.getService(y).log("%c[WB] Calling FUNCTION: closeCommentSidebar","color: green;");try{this.trackEvent(Z.Events.Comments.CLOSE_COMMENT_SIDEBAR_TRIGGERED),this.getService(Te).setSidebarVisibility(!1,!0)}catch(o){this.getService(y).catch("Error in _closeCommentSidebar: ",o)}}_toggleCommentSidebar(){this.getService(y).log("%c[WB] Calling FUNCTION: toggleCommentSidebar","color: green;");try{this.trackEvent(Z.Events.Comments.TOGGLE_COMMENT_SIDEBAR_TRIGGERED),this.getService(Te).toggleSidebarVisibility(!0)}catch(o){this.getService(y).catch("Error in _toggleCommentSidebar: ",o)}}_enableModeratorMode(){this.getService(y).log("%c[WB] Calling FUNCTION: enableModeratorMode","color: green;");try{this.trackEvent(Z.Events.Comments.ENABLE_MODERATOR_MODE_TRIGGERED),this.getService(Te).setModeratorMode(!0)}catch(o){this.getService(y).catch("Error in _enableModeratorMode: ",o)}}_disableModeratorMode(){this.getService(y).log("%c[WB] Calling FUNCTION: disableModeratorMode","color: green;");try{this.trackEvent(Z.Events.Comments.DISABLE_MODERATOR_MODE_TRIGGERED),this.getService(Te).setModeratorMode(!1)}catch(o){this.getService(y).catch("Error in _disableModeratorMode: ",o)}}_enableStreamMode(){this.getService(y).log("%c[WB] Calling FUNCTION: enableStreamMode","color: green;");try{this.trackEvent(Z.Events.Comments.ENABLE_STREAM_MODE_TRIGGERED),this.getService(Te).setStreamMode(!0)}catch(o){this.getService(y).catch("Error in _enableStreamMode: ",o)}}_disableStreamMode(){this.getService(y).log("%c[WB] Calling FUNCTION: disableStreamMode","color: green;");try{this.trackEvent(Z.Events.Comments.DISABLE_STREAM_MODE_TRIGGERED),this.getService(Te).setStreamMode(!1)}catch(o){this.getService(y).catch("Error in _disableStreamMode: ",o)}}_enableSignInButton(){this.getService(y).log("%c[WB] Calling FUNCTION: enableSignInButton","color: green;");try{this.trackEvent(Z.Events.Comments.ENABLE_SIGN_IN_BUTTON_TRIGGERED),this.getService(Te).enableSignInButton(!0)}catch(o){this.getService(y).catch("Error in _enableSignInButton: ",o)}}_disableSignInButton(){this.getService(y).log("%c[WB] Calling FUNCTION: disableSignInButton","color: green;");try{this.trackEvent(Z.Events.Comments.DISABLE_SIGN_IN_BUTTON_TRIGGERED),this.getService(Te).enableSignInButton(!1)}catch(o){this.getService(y).catch("Error in _disableSignInButton: ",o)}}_enableUpgradeButton(){this.getService(y).log("%c[WB] Calling FUNCTION: enableUpgradeButton","color: green;");try{this.trackEvent(Z.Events.Comments.ENABLE_UPGRADE_BUTTON_TRIGGERED),this.getService(Te).enableUpgradeButton(!0)}catch(o){this.getService(y).catch("Error in _enableUpgradeButton: ",o)}}_disableUpgradeButton(){this.getService(y).log("%c[WB] Calling FUNCTION: disableUpgradeButton","color: green;");try{this.trackEvent(Z.Events.Comments.DISABLE_UPGRADE_BUTTON_TRIGGERED),this.getService(Te).enableUpgradeButton(!1)}catch(o){this.getService(y).catch("Error in _disableUpgradeButton: ",o)}}_onCommentModeChange(){this.getService(y).log("%c[WB] Calling FUNCTION: onCommentModeChange","color: green;");try{return this.trackEvent(Z.Events.Comments.ON_COMMENT_MODE_CHANGE_TRIGGERED),this.getService(Te).addCommentModeChange()}catch(o){return this.getService(y).catch("Error in _onCommentModeChange: ",o),re(!1)}}_enableAttachment(){this.getService(y).log("%c[WB] Calling FUNCTION: enableAttachment","color: green;");try{this.trackEvent(Z.Events.Comments.ENABLE_ATTACHMENTS_TRIGGERED),this.getService(Te).enableAttachment(!0)}catch(o){this.getService(y).catch("Error in _enableAttachment: ",o)}}_disableAttachment(){this.getService(y).log("%c[WB] Calling FUNCTION: disableAttachment","color: green;");try{this.trackEvent(Z.Events.Comments.DISABLE_ATTACHMENTS_TRIGGERED),this.getService(Te).enableAttachment(!1)}catch(o){this.getService(y).catch("Error in _disableAttachment: ",o)}}_isUserGlobalContact(){this.getService(y).log("%c[WB] Calling FUNCTION: isUserGlobalContact","color: green;");try{return this.trackEvent(Z.Events.Comments.IS_USER_GLOBAL_CONTACT_TRIGGERED),this.getService(Te).isUserGlobalContact$()}catch(o){return this.getService(y).catch("Error in _isUserGlobalContact: ",o),re(!1)}}_enableDeviceInfo(){this.getService(y).log("%c[WB] Calling FUNCTION: enableDeviceInfo","color: green;");try{this.trackEvent(Z.Events.Comments.ENABLE_DEVICE_INFO_TRIGGERED),this.getService(Te).showScreenSizeInfo(!0)}catch(o){this.getService(y).catch("Error in _enableDeviceInfo: ",o)}}_disableDeviceInfo(){this.getService(y).log("%c[WB] Calling FUNCTION: disableDeviceInfo","color: green;");try{this.trackEvent(Z.Events.Comments.DISABLE_DEVICE_INFO_TRIGGERED),this.getService(Te).showScreenSizeInfo(!1)}catch(o){this.getService(y).catch("Error in _disableDeviceInfo: ",o)}}_enableCommentMode(){this.getService(y).log("%c[WB] Calling FUNCTION: enableCommentMode","color: green;");try{this.trackEvent(Z.Events.Comments.ENABLE_COMMENT_MODE_TRIGGERED),this.getService(Te).enableAddCommentMode()}catch(o){this.getService(y).catch("Error in _enableCommentMode: ",o)}}_disableCommentMode(){this.getService(y).log("%c[WB] Calling FUNCTION: disableCommentMode","color: green;");try{this.trackEvent(Z.Events.Comments.DISABLE_COMMENT_MODE_TRIGGERED),this.getService(Te).disableAddCommentMode()}catch(o){this.getService(y).catch("Error in _disableCommentMode: ",o)}}_enablePersistentCommentMode(){this.getService(y).log("%c[WB] Calling FUNCTION: enablePersistentCommentMode","color: green;");try{this.trackEvent(Z.Events.Comments.ENABLE_PERSISTENT_COMMENT_MODE_TRIGGERED),this.getService(Te).enablePersistentCommentMode()}catch(o){this.getService(y).catch("Error in _enablePersistentCommentMode: ",o)}}_disablePersistentCommentMode(){this.getService(y).log("%c[WB] Calling FUNCTION: disablePersistentCommentMode","color: green;");try{this.trackEvent(Z.Events.Comments.DISABLE_PERSISTENT_COMMENT_MODE_TRIGGERED),this.getService(Te).disablePersistentCommentMode()}catch(o){this.getService(y).catch("Error in _disablePersistentCommentMode: ",o)}}_showCommentIndex(o){this.getService(y).log("%c[WB] Calling FUNCTION: showCommentIndex","color: green;");try{this.getService(Te).showCommentIndex(o)}catch(t){this.getService(y).catch("Error in _showCommentIndex: ",t)}}_enableCommentIndex(){this.getService(y).log("%c[WB] Calling FUNCTION: enableCommentIndex","color: green;");try{this.trackEvent(Z.Events.Comments.ENABLE_COMMENT_INDEX_TRIGGERED),this.getService(Te).showCommentIndex(!0)}catch(o){this.getService(y).catch("Error in _enableCommentIndex: ",o)}}_disableCommentIndex(){this.getService(y).log("%c[WB] Calling FUNCTION: disableCommentIndex","color: green;");try{this.trackEvent(Z.Events.Comments.DISABLE_COMMENT_INDEX_TRIGGERED),this.getService(Te).showCommentIndex(!1)}catch(o){this.getService(y).catch("Error in _disableCommentIndex: ",o)}}_enablePopoverMode(){this.getService(y).log("%c[WB] Calling FUNCTION: enablePopoverMode","color: green;");try{this.trackEvent(Z.Events.Comments.ENABLE_POPOVER_MODE_TRIGGERED),this.getService(Te).enablePopoverMode()}catch(o){this.getService(y).catch("Error in _enablePopoverMode: ",o)}}_disablePopoverMode(){this.getService(y).log("%c[WB] Calling FUNCTION: disablePopoverMode","color: green;");try{this.trackEvent(Z.Events.Comments.DISABLE_POPOVER_MODE_TRIGGERED),this.getService(Te).disablePopoverMode()}catch(o){this.getService(y).catch("Error in _disablePopoverMode: ",o)}}_enableDialogOnHover(){this.getService(y).log("%c[WB] Calling FUNCTION: enableDialogOnHover","color: green;");try{this.trackEvent(Z.Events.Comments.ENABLE_DIALOG_ON_HOVER_TRIGGERED),this.getService(Te).setEnableDialogOnHover(!0)}catch(o){this.getService(y).catch("Error in _enableDialogOnHover: ",o)}}_disableDialogOnHover(){this.getService(y).log("%c[WB] Calling FUNCTION: disableDialogOnHover","color: green;");try{this.trackEvent(Z.Events.Comments.DISABLE_DIALOG_ON_HOVER_TRIGGERED),this.getService(Te).setEnableDialogOnHover(!1)}catch(o){this.getService(y).catch("Error in _disableDialogOnHover: ",o)}}_enablePopoverTriangleComponent(){this.getService(y).log("%c[WB] Calling FUNCTION: enablePopoverTriangleComponent","color: green;");try{this.trackEvent(Z.Events.Comments.ENABLE_POPOVER_TRIANGLE_COMPONENT_TRIGGERED),this.getService(Te).enablePopoverTriangleComponent()}catch(o){this.getService(y).catch("Error in _enablePopoverTriangleComponent: ",o)}}_disablePopoverTriangleComponent(){this.getService(y).log("%c[WB] Calling FUNCTION: disablePopoverTriangleComponent","color: green;");try{this.trackEvent(Z.Events.Comments.DISABLE_POPOVER_TRIANGLE_COMPONENT_TRIGGERED),this.getService(Te).disablePopoverTriangleComponent()}catch(o){this.getService(y).catch("Error in _disablePopoverTriangleComponent: ",o)}}_enableDialogOnTargetElementClick(){this.getService(y).log("%c[WB] Calling FUNCTION: enableDialogOnTargetElementClick","color: green;");try{this.trackEvent(Z.Events.Comments.ENABLE_DIALOG_ON_TARGET_ELEMENT_CLICK_TRIGGERED),this.getService(Te).setEnableDialogOnTargetElementClick(!0)}catch(o){this.getService(y).catch("Error in _enableDialogOnTargetElementClick: ",o)}}_disableDialogOnTargetElementClick(){this.getService(y).log("%c[WB] Calling FUNCTION: disableDialogOnTargetElementClick","color: green;");try{this.trackEvent(Z.Events.Comments.DISABLE_DIALOG_ON_TARGET_ELEMENT_CLICK_TRIGGERED),this.getService(Te).setEnableDialogOnTargetElementClick(!1)}catch(o){this.getService(y).catch("Error in _disableDialogOnTargetElementClick: ",o)}}_enablePriority(){this.getService(y).log("%c[WB] Calling FUNCTION: enablePriority","color: green;");try{this.trackEvent(Z.Events.Comments.ENABLE_PRIORITY_TRIGGERED),this.getService(Te).setEnablePriority(!0)}catch(o){this.getService(y).catch("Error in _enablePriority: ",o)}}_disablePriority(){this.getService(y).log("%c[WB] Calling FUNCTION: disablePriority","color: green;");try{this.trackEvent(Z.Events.Comments.DISABLE_PRIORITY_TRIGGERED),this.getService(Te).setEnablePriority(!1)}catch(o){this.getService(y).catch("Error in _disablePriority: ",o)}}_enableStatus(){this.getService(y).log("%c[WB] Calling FUNCTION: enableStatus","color: green;");try{this.trackEvent(Z.Events.Comments.ENABLE_STATUS_TRIGGERED),this.getService(Te).setEnableStatus(!0)}catch(o){this.getService(y).catch("Error in _enableStatus: ",o)}}_disableStatus(){this.getService(y).log("%c[WB] Calling FUNCTION: disableStatus","color: green;");try{this.trackEvent(Z.Events.Comments.DISABLE_STATUS_TRIGGERED),this.getService(Te).setEnableStatus(!1)}catch(o){this.getService(y).catch("Error in _disableStatus: ",o)}}_enableResolveButton(){this.getService(y).log("%c[WB] Calling FUNCTION: enableResolveButton","color: green;");try{this.trackEvent(Z.Events.Comments.ENABLE_RESOLVE_BUTTON_TRIGGERED),this.getService(Te).setEnableResolve(!0)}catch(o){this.getService(y).catch("Error in _enableResolveButton: ",o)}}_disableResolveButton(){this.getService(y).log("%c[WB] Calling FUNCTION: disableResolveButton","color: green;");try{this.trackEvent(Z.Events.Comments.DISABLE_RESOLVE_BUTTON_TRIGGERED),this.getService(Te).setEnableResolve(!1)}catch(o){this.getService(y).catch("Error in _disableResolveButton: ",o)}}_enableGhostComments(){this.getService(y).log("%c[WB] Calling FUNCTION: enableGhostComments","color: green;");try{this.trackEvent(Z.Events.Comments.ENABLE_GHOST_COMMENTS_TRIGGERED),this.getService(Te).enableGhostComments()}catch(o){this.getService(y).catch("Error in _enableGhostCommentsInDOM: ",o)}}_disableGhostComments(){this.getService(y).log("%c[WB] Calling FUNCTION: disableGhostComments","color: green;");try{this.trackEvent(Z.Events.Comments.DISABLE_GHOST_COMMENTS_TRIGGERED),this.getService(Te).disableGhostComments()}catch(o){this.getService(y).catch("Error in _disableGhostComments: ",o)}}_enableGhostCommentsIndicator(){this.getService(y).log("%c[WB] Calling FUNCTION: enableGhostCommentsIndicator","color: green;");try{this.trackEvent(Z.Events.Comments.ENABLE_GHOST_COMMENTS_INDICATOR_TRIGGERED),this.getService(Te).enableGhostCommentsMessage()}catch(o){this.getService(y).catch("Error in _enableGhostCommentsIndicator: ",o)}}_disableGhostCommentsIndicator(){this.getService(y).log("%c[WB] Calling FUNCTION: disableGhostCommentsIndicator","color: green;");try{this.trackEvent(Z.Events.Comments.DISABLE_GHOST_COMMENTS_INDICATOR_TRIGGERED),this.getService(Te).disableGhostCommentsMessage()}catch(o){this.getService(y).catch("Error in _disableGhostCommentsIndicator: ",o)}}_setCustomStatus(o){this.getService(y).log("%c[WB] Calling FUNCTION: setCustomStatus","color: green;");try{this.trackEvent(Z.Events.Comments.SET_CUSTOM_STATUS_TRIGGERED,{payload:{customStatuses:o}}),this.getService(Te).setCustomStatuses(o)}catch(t){this.getService(y).catch("Error in _setCustomStatus: ",t)}}_enableInboxMode(){this.getService(y).log("%c[WB] Calling FUNCTION: enableInboxMode","color: green;");try{this.trackEvent(Z.Events.Comments.ENABLE_INBOX_MODE_TRIGGERED),this.getService(Te).enableInboxMode()}catch(o){this.getService(y).catch("Error in _enableInboxMode: ",o)}}_setCustomPriority(o){this.getService(y).log("%c[WB] Calling FUNCTION: setCustomPriority","color: green;");try{this.trackEvent(Z.Events.Comments.SET_CUSTOM_PRIORITY_TRIGGERED,{payload:{customPriorities:o}}),this.getService(Te).setCustomPriorities(o)}catch(t){this.getService(y).catch("Error in _setCustomPriority: ",t)}}_setCustomCategory(o){this.getService(y).log("%c[WB] Calling FUNCTION: setCustomCategory","color: green;");try{this.trackEvent(Z.Events.Comments.SET_CUSTOM_CATEGORY_TRIGGERED,{payload:{customCategories:o}}),this.getService(Te).setCustomCategories(o)}catch(t){this.getService(y).catch("Error in _setCustomCategory: ",t)}}_disableInboxMode(){this.getService(y).log("%c[WB] Calling FUNCTION: disableInboxMode","color: green;");try{this.trackEvent(Z.Events.Comments.DISABLE_INBOX_MODE_TRIGGERED),this.getService(Te).disableInboxMode()}catch(o){this.getService(y).catch("Error in _disableInboxMode: ",o)}}_enableAutoCategorize(){this.getService(y).log("%c[WB] Calling FUNCTION: enableAutoCategorize","color: green;");try{this.trackEvent(Z.Events.Comments.ENABLE_AUTO_CATEGORIZE_TRIGGERED),this.getService(Te).setEnableAutoCategorize(!0)}catch(o){this.getService(y).catch("Error in _enableAutoCategorize: ",o)}}_disableAutoCategorize(){this.getService(y).log("%c[WB] Calling FUNCTION: disableAutoCategorize","color: green;");try{this.trackEvent(Z.Events.Comments.DISABLE_AUTO_CATEGORIZE_TRIGGERED),this.getService(Te).setEnableAutoCategorize(!1)}catch(o){this.getService(y).catch("Error in _disableAutoCategorize: ",o)}}_enableDarkMode(){this.getService(y).log("%c[WB] Calling FUNCTION: enableDarkMode","color: green;");try{this.trackEvent(Z.Events.Comments.ENABLE_DARK_MODE_TRIGGERED),this.getService(Te).setCommentContainerDarkMode(!0)}catch(o){this.getService(y).catch("Error in _enableDarkMode: ",o)}}_disableDarkMode(){this.getService(y).log("%c[WB] Calling FUNCTION: disableDarkMode","color: green;");try{this.trackEvent(Z.Events.Comments.DISABLE_DARK_MODE_TRIGGERED),this.getService(Te).setCommentContainerDarkMode(!1)}catch(o){this.getService(y).catch("Error in _disableDarkMode: ",o)}}_setContextProvider(o){try{this.trackEvent(Z.Events.Comments.SET_CONTEXT_PROVIDER_TRIGGERED,{payload:{documentId:Bae,location}}),this.getService(Te).setContextProvider(o)}catch(t){this.getService(y).catch("Error in _setContextProvider: ",t)}}_enableSuggestionMode(){this.getService(y).log("%c[WB] Calling FUNCTION: enableSuggestionMode","color: green;");try{this.trackEvent(Z.Events.Comments.ENABLE_SUGGESTION_MODE_TRIGGERED),this.getService(Te).setSuggestionMode(!0)}catch(o){this.getService(y).catch("Error in _enableSuggestionMode: ",o)}}_disableSuggestionMode(){this.getService(y).log("%c[WB] Calling FUNCTION: disableSuggestionMode","color: green;");try{this.trackEvent(Z.Events.Comments.DISABLE_SUGGESTION_MODE_TRIGGERED),this.getService(Te).setSuggestionMode(!1)}catch(o){this.getService(y).catch("Error in _disableSuggestionMode: ",o)}}_enableMobileMode(){this.getService(y).log("%c[WB] Calling FUNCTION: enableMobileMode","color: green;");try{this.trackEvent(Z.Events.Comments.ENABLE_MOBILE_MODE_TRIGGERED),this.getService(Te).setMobileMode(!0)}catch(o){this.getService(y).catch("Error in _enableMobileMode: ",o)}}_disableMobileMode(){this.getService(y).log("%c[WB] Calling FUNCTION: disableMobileMode","color: green;");try{this.trackEvent(Z.Events.Comments.DISABLE_MOBILE_MODE_TRIGGERED),this.getService(Te).setMobileMode(!1)}catch(o){this.getService(y).catch("Error in _disableMobileMode: ",o)}}_enableInlineCommentMode(){this.getService(y).log("%c[WB] Calling FUNCTION: enableInlineCommentMode","color: green;");try{this.trackEvent(Z.Events.Comments.ENABLE_INLINE_COMMENT_MODE_TRIGGERED),this.getService(Te).enableInlineCommentMode()}catch(o){this.getService(y).catch("Error in _enableInlineCommentMode: ",o)}}_disableInlineCommentMode(){this.getService(y).log("%c[WB] Calling FUNCTION: disableInlineCommentMode","color: green;");try{this.trackEvent(Z.Events.Comments.DISABLE_INLINE_COMMENT_MODE_TRIGGERED),this.getService(Te).disableInlineCommentMode()}catch(o){this.getService(y).catch("Error in _disableInlineCommentMode: ",o)}}_enableMinimap(){this.getService(y).log("%c[WB] Calling FUNCTION: enableMinimap","color: green;");try{this.trackEvent(Z.Events.Comments.ENABLE_MINIMAP_TRIGGERED),this.getService(Te).enableMinimap()}catch(o){this.getService(y).catch("Error in _enableMinimap: ",o)}}_disableMinimap(){this.getService(y).log("%c[WB] Calling FUNCTION: disableMinimap","color: green;");try{this.trackEvent(Z.Events.Comments.DISABLE_MINIMAP_TRIGGERED),this.getService(Te).disableMinimap()}catch(o){this.getService(y).catch("Error in _disableMinimap: ",o)}}_showCommentsOnDom(){this.getService(y).log("%c[WB] Calling FUNCTION: showCommentsOnDom","color: green;");try{this.trackEvent(Z.Events.Comments.SHOW_COMMENTS_ON_DOM_TRIGGERED),this.getService(Te).showCommentsOnDom()}catch(o){this.getService(y).catch("Error in _showCommentsOnDom: ",o)}}_hideCommentsOnDom(){this.getService(y).log("%c[WB] Calling FUNCTION: hideCommentsOnDom","color: green;");try{this.trackEvent(Z.Events.Comments.HIDE_COMMENTS_ON_DOM_TRIGGERED),this.getService(Te).hideCommentsOnDom()}catch(o){this.getService(y).catch("Error in _hideCommentsOnDom: ",o)}}_enableCommentTool(){this.getService(y).log("%c[WB] Calling FUNCTION: enableCommentTool","color: green;");try{this.trackEvent(Z.Events.Comments.ENABLE_COMMENT_TOOL_TRIGGERED),this.getService(Te).enableCommentTool()}catch(o){this.getService(y).catch("Error in _enableCommentTool: ",o)}}_disableCommentTool(){this.getService(y).log("%c[WB] Calling FUNCTION: disableCommentTool","color: green;");try{this.trackEvent(Z.Events.Comments.DISABLE_COMMENT_TOOL_TRIGGERED),this.getService(Te).disableCommentTool()}catch(o){this.getService(y).catch("Error in _disableCommentTool: ",o)}}_setTotalMediaLength(o){this.getService(y).log("%c[WB] Calling FUNCTION: setTotalMediaLength","color: green;");try{this.trackEvent(Z.Events.Comments.SET_TOTAL_MEDIA_LENGTH_TRIGGERED,{payload:{length:o}}),this.getService(Te).setTotalMediaLength(o)}catch(t){this.getService(y).catch("Error in _setTotalMediaLength: ",t)}}_onCommentAdd(){this.getService(y).log("%c[WB] Calling FUNCTION: onCommentAdd","color: green;");try{return this.trackEvent(Z.Events.Comments.ON_COMMENT_ADD_TRIGGERED),this.getService(Te).onCommentAdd$()}catch(o){return this.getService(y).catch("Error in _onCommentAdd: ",o),re()}}_onCommentUpdate(){this.getService(y).log("%c[WB] Calling FUNCTION: onCommentUpdate","color: green;");try{return this.trackEvent(Z.Events.Comments.ON_COMMENT_UPDATE_TRIGGERED),this.getService(Te).onCommentUpdate$()}catch(o){return this.getService(y).catch("Error in _onCommentUpdate: ",o),re()}}_addCommentOnSelectedText(){this.getService(y).log("%c[WB] Calling FUNCTION: addCommentOnSelectedText","color: green;");try{this.trackEvent(Z.Events.Comments.ADD_COMMENT_ON_SELECTED_TEXT_TRIGGERED),this.getService(Te).addCommentOnSelectedText()}catch(o){this.getService(y).catch("Error in _addCommentOnSelectedText: ",o)}}_enableSidebarUrlNavigation(){this.getService(y).log("%c[WB] Calling FUNCTION: enableSidebarUrlNavigation","color: green;");try{this.trackEvent(Z.Events.Comments.ENABLE_SIDEBAR_URL_NAVIGATION_TRIGGERED),this.getService(Te).enableSidebarUrlNavigation()}catch(o){this.getService(y).catch("Error in _enableSidebarUrlNavigation: ",o)}}_disableSidebarUrlNavigation(){this.getService(y).log("%c[WB] Calling FUNCTION: disableSidebarUrlNavigation","color: green;");try{this.trackEvent(Z.Events.Comments.DISABLE_SIDEBAR_URL_NAVIGATION_TRIGGERED),this.getService(Te).disableSidebarUrlNavigation()}catch(o){this.getService(y).catch("Error in _disableSidebarUrlNavigation: ",o)}}_setDStrategy(o){this.getService(y).log("%c[WB] Calling FUNCTION: setDStrategy","color: green;");try{this.trackEvent(Z.Events.Comments.SET_D_STRATEGY_TRIGGERED,{payload:{strategy:o}}),this.getService(Te).setDetectionStrategy(o)}catch(t){this.getService(y).catch("Error in _setDStrategy: ",t)}}_enableSidebarButtonOnCommentDialog(){this.getService(y).log("%c[WB] Calling FUNCTION: enableSidebarButtonOnCommentDialog","color: green;");try{this.trackEvent(Z.Events.Comments.ENABLE_SIDEBAR_BUTTON_ON_COMMENT_DIALOG_TRIGGERED),this.getService(Te).enableSidebarButtonOnCommentDialog()}catch(o){this.getService(y).catch("Error in _enableSidebarButtonOnCommentDialog: ",o)}}_disableSidebarButtonOnCommentDialog(){this.getService(y).log("%c[WB] Calling FUNCTION: disableSidebarButtonOnCommentDialog","color: green;");try{this.trackEvent(Z.Events.Comments.DISABLE_SIDEBAR_BUTTON_ON_COMMENT_DIALOG_TRIGGERED),this.getService(Te).disableSidebarButtonOnCommentDialog()}catch(o){this.getService(y).catch("Error in _disableSidebarButtonOnCommentDialog: ",o)}}_onSidebarButtonOnCommentDialogClick(){this.getService(y).log("%c[WB] Calling FUNCTION: onSidebarButtonOnCommentDialogClick","color: green;");try{return this.trackEvent(Z.Events.Comments.ON_SIDEBAR_BUTTON_ON_COMMENT_DIALOG_CLICK_TRIGGERED),this.getService(Te).getSidebarButtonOnCommentDialogClick$()}catch(o){return this.getService(y).catch("Error in _onSidebarButtonOnCommentDialogClick: ",o),re(null)}}_enableReactions(){this.getService(y).log("%c[WB] Calling FUNCTION: enableReactions","color: green;");try{this.trackEvent(Z.Events.Comments.ENABLE_REACTIONS_TRIGGERED),this.getService(Te).enableReactions()}catch(o){this.getService(y).catch("Error in _enableReactions: ",o)}}_disableReactions(){this.getService(y).log("%c[WB] Calling FUNCTION: disableReactions","color: green;");try{this.trackEvent(Z.Events.Comments.DISABLE_REACTIONS_TRIGGERED),this.getService(Te).disableReactions()}catch(o){this.getService(y).catch("Error in _disableReactions: ",o)}}_setRecordings(o){this.getService(y).log("%c[WB] Calling FUNCTION: setRecordings","color: green;");try{this.trackEvent(Z.Events.Comments.SET_RECORDINGS_TRIGGERED,{payload:{allowedRecordings:o}}),typeof o=="string"&&(o=o?.split(",")?.map(t=>t.trim())),this.getService(Te).setAllowedRecordings(o)}catch(t){this.getService(y).catch("Error in _setRecordings: ",t)}}_addCommentOnElement(o){this.getService(y).log("%c[WB] Calling FUNCTION: addCommentOnElement","color: green;");try{this.trackEvent(Z.Events.Comments.ADD_COMMENT_ON_ELEMENT_TRIGGERED,{payload:{data:o}}),this.getService(Te).addCommentOnElement(o)}catch(t){this.getService(y).catch("Error in _addCommentOnElement: ",t)}}_enablePrivateCommentMode(){this.getService(y).log("%c[WB] Calling FUNCTION: enablePrivateCommentMode","color: green;");try{this.trackEvent(Z.Events.Comments.ENABLE_PRIVATE_COMMENT_MODE_TRIGGERED),this.getService(Te).enablePrivateCommentMode()}catch(o){this.getService(y).catch("Error in _enablePrivateCommentMode: ",o)}}_disablePrivateCommentMode(){this.getService(y).log("%c[WB] Calling FUNCTION: disablePrivateCommentMode","color: green;");try{this.trackEvent(Z.Events.Comments.DISABLE_PRIVATE_COMMENT_MODE_TRIGGERED),this.getService(Te).disablePrivateCommentMode()}catch(o){this.getService(y).catch("Error in _disablePrivateCommentMode: ",o)}}_enableScrollToComment(){this.getService(y).log("%c[WB] Calling FUNCTION: enableScrollToComment","color: green;");try{this.trackEvent(Z.Events.Comments.ENABLE_SCROLL_TO_COMMENT_TRIGGERED),this.getService(Te).enableScrollToComment()}catch(o){this.getService(y).catch("Error in _enableScrollToComment: ",o)}}_disableScrollToComment(){this.getService(y).log("%c[WB] Calling FUNCTION: disableScrollToComment","color: green;");try{this.trackEvent(Z.Events.Comments.DISABLE_SCROLL_TO_COMMENT_TRIGGERED),this.getService(Te).disableScrollToComment()}catch(o){this.getService(y).catch("Error in _disableScrollToComment: ",o)}}_enableUserMentions(){this.getService(y).log("%c[WB] Calling FUNCTION: enableUserMentions","color: green;");try{this.trackEvent(Z.Events.Comments.ENABLE_USER_MENTIONS_TRIGGERED),this.getService(Te).enableUserMentions()}catch(o){this.getService(y).catch("Error in _enableUserMentions: ",o)}}_disableUserMentions(){this.getService(y).log("%c[WB] Calling FUNCTION: disableUserMentions","color: green;");try{this.trackEvent(Z.Events.Comments.DISABLE_USER_MENTIONS_TRIGGERED),this.getService(Te).disableUserMentions()}catch(o){this.getService(y).catch("Error in _disableUserMentions: ",o)}}_setCommentSidebarFilters(o){this.getService(y).log("%c[WB] Calling FUNCTION: setCommentSidebarFilters","color: green;");try{this.trackEvent(Z.Events.Comments.SET_COMMENT_SIDEBAR_FILTERS_TRIGGERED,{payload:{filters:o}}),this.getService(Te).setCommentSidebarFilters(o)}catch(t){this.getService(y).catch("Error in _setCommentSidebarFilters: ",t)}}_enableCommentPinHighlighter(){this.getService(y).log("%c[WB] Calling FUNCTION: enableCommentPinHighlighter","color: green;");try{this.trackEvent(Z.Events.Comments.ENABLE_COMMENT_PIN_HIGHLIGHTER_TRIGGERED),this.getService(Te).enableCommentPinHighlighter()}catch(o){this.getService(y).catch("Error in _enableCommentPinHighlighter: ",o)}}_disableCommentPinHighlighter(){this.getService(y).log("%c[WB] Calling FUNCTION: disableCommentPinHighlighter","color: green;");try{this.getService(Te).disableCommentPinHighlighter()}catch(o){this.getService(y).catch("Error in _disableCommentPinHighlighter: ",o)}}_enableDeleteOnBackspace(){this.getService(y).log("%c[WB] Calling FUNCTION: enableDeleteOnBackspace","color: green;");try{this.trackEvent(Z.Events.Comments.ENABLE_DELETE_ON_BACKSPACE_TRIGGERED),this.getService(Te).enableDeleteOnBackspace()}catch(o){this.getService(y).catch("Error in _enableDeleteOnBackspace: ",o)}}_disableDeleteOnBackspace(){this.getService(y).log("%c[WB] Calling FUNCTION: disableDeleteOnBackspace","color: green;");try{this.trackEvent(Z.Events.Comments.DISABLE_DELETE_ON_BACKSPACE_TRIGGERED),this.getService(Te).disableDeleteOnBackspace()}catch(o){this.getService(y).catch("Error in _disableDeleteOnBackspace: ",o)}}_enableHotkey(){this.getService(y).log("%c[WB] Calling FUNCTION: enableHotkey","color: green;");try{this.trackEvent(Z.Events.Comments.ENABLE_HOTKEY_TRIGGERED),this.getService(Te).enableHotkey()}catch(o){this.getService(y).catch("Error in _enableHotkey: ",o)}}_disableHotkey(){this.getService(y).log("%c[WB] Calling FUNCTION: disableHotkey","color: green;");try{this.trackEvent(Z.Events.Comments.DISABLE_HOTKEY_TRIGGERED),this.getService(Te).disableHotkey()}catch(o){this.getService(y).catch("Error in _disableHotkey: ",o)}}_enableDeviceIndicatorOnCommentPins(){this.getService(y).log("%c[WB] Calling FUNCTION: enableDeviceIndicatorOnCommentPins","color: green;");try{this.trackEvent(Z.Events.Comments.ENABLE_DEVICE_INDICATOR_ON_COMMENT_PINS_TRIGGERED),this.getService(Te).enableDeviceIndicatorOnCommentPins()}catch(o){this.getService(y).catch("Error in _enableDeviceIndicatorOnCommentPins: ",o)}}_disableDeviceIndicatorOnCommentPins(){this.getService(y).log("%c[WB] Calling FUNCTION: disableDeviceIndicatorOnCommentPins","color: green;");try{this.trackEvent(Z.Events.Comments.DISABLE_DEVICE_INDICATOR_ON_COMMENT_PINS_TRIGGERED),this.getService(Te).disableDeviceIndicatorOnCommentPins()}catch(o){this.getService(y).catch("Error in _disableDeviceIndicatorOnCommentPins: ",o)}}_getElementRefByAnnotationId(o){this.getService(y).log("%c[WB] Calling FUNCTION: getElementRefByAnnotationId","color: green;");try{return this.trackEvent(Z.Events.Comments.GET_ELEMENT_REF_BY_ANNOTATION_ID_TRIGGERED,{payload:{annotationId:o}}),this.getService(Te).getElementRefByAnnotationId(o)}catch(t){this.getService(y).catch("Error in _getElementRefByAnnotationId: ",t);return}}_scrollToCommentByAnnotationId(o){this.getService(y).log("%c[WB] Calling FUNCTION: scrollToCommentByAnnotationId","color: green;");try{this.trackEvent(Z.Events.Comments.SCROLL_TO_COMMENT_BY_ANNOTATION_ID_TRIGGERED,{payload:{annotationId:o}}),this.getService(Te).scrollToCommentByAnnotationId(o)}catch(t){this.getService(y).catch("Error in _scrollToCommentByAnnotationId: ",t)}}_selectCommentByAnnotationId(o){this.getService(y).log("%c[WB] Calling FUNCTION: selectCommentByAnnotationId","color: green;");try{this.trackEvent(Z.Events.Comments.SELECT_COMMENT_BY_ANNOTATION_ID_TRIGGERED,{payload:{annotationId:o}}),this.getService(Te).selectCommentByAnnotationId(o)}catch(t){this.getService(y).catch("Error in _selectCommentByAnnotationId: ",t)}}_enableRecordingSummary(){this.getService(y).log("%c[WB] Calling FUNCTION: enableRecordingSummary","color: green;");try{this.trackEvent(Z.Events.Comments.ENABLE_RECORDING_SUMMARY_TRIGGERED),this.getService(Te).enableRecordingSummary()}catch(o){this.getService(y).catch("Error in _enableRecordingSummary: ",o)}}_disableRecordingSummary(){this.getService(y).log("%c[WB] Calling FUNCTION: disableRecordingSummary","color: green;");try{this.trackEvent(Z.Events.Comments.DISABLE_RECORDING_SUMMARY_TRIGGERED),this.getService(Te).disableRecordingSummary()}catch(o){this.getService(y).catch("Error in _disableRecordingSummary: ",o)}}_enableRecordingTranscription(){this.getService(y).log("%c[WB] Calling FUNCTION: enableRecordingTranscription","color: green;");try{this.trackEvent(Z.Events.Comments.ENABLE_RECORDING_TRANSCRIPTION_TRIGGERED),this.getService(Qi).enableRecordingTranscription()}catch(o){this.getService(y).catch("Error in _enableRecordingTranscription: ",o)}}_disableRecordingTranscription(){this.getService(y).log("%c[WB] Calling FUNCTION: disableRecordingTranscription","color: green;");try{this.trackEvent(Z.Events.Comments.DISABLE_RECORDING_TRANSCRIPTION_TRIGGERED),this.getService(Qi).disableRecordingTranscription()}catch(o){this.getService(y).catch("Error in _disableRecordingTranscription: ",o)}}_enableRecordingCountdown(){this.getService(y).log("%c[WB] Calling FUNCTION: enableRecordingCountdown","color: green;");try{this.trackEvent(Z.Events.Comments.ENABLE_RECORDING_COUNTDOWN_TRIGGERED),this.getService(Te).enableRecordingCountdown()}catch(o){this.getService(y).catch("Error in _enableRecordingCountdown: ",o)}}_disableRecordingCountdown(){this.getService(y).log("%c[WB] Calling FUNCTION: disableRecordingCountdown","color: green;");try{this.trackEvent(Z.Events.Comments.DISABLE_RECORDING_COUNTDOWN_TRIGGERED),this.getService(Te).disableRecordingCountdown()}catch(o){this.getService(y).catch("Error in _disableRecordingCountdown: ",o)}}_setUnreadIndicatorMode(o){this.getService(y).log("%c[WB] Calling FUNCTION: setUnreadIndicatorMode","color: green;");try{this.trackEvent(Z.Events.Comments.SET_UNREAD_INDICATOR_MODE_TRIGGERED,{payload:{mode:o}}),this.getService(Te).setUnreadIndicatorMode(o)}catch(t){this.getService(y).catch("Error in _setUnreadIndicatorMode: ",t)}}_enableEnterKeyToSubmit(){this.getService(y).log("%c[WB] Calling FUNCTION: enableEnterKeyToSubmit","color: green;");try{this.trackEvent(Z.Events.Comments.ENABLE_ENTER_KEY_TO_SUBMIT_TRIGGERED),this.getService(Te).enableEnterKeyToSubmit()}catch(o){this.getService(y).catch("Error in _enableEnterKeyToSubmit: ",o)}}_disableEnterKeyToSubmit(){this.getService(y).log("%c[WB] Calling FUNCTION: disableEnterKeyToSubmit","color: green;");try{this.trackEvent(Z.Events.Comments.DISABLE_ENTER_KEY_TO_SUBMIT_TRIGGERED),this.getService(Te).disableEnterKeyToSubmit()}catch(o){this.getService(y).catch("Error in _disableEnterKeyToSubmit: ",o)}}_enablePinShadowDOM(){this.getService(y).log("%c[WB] Calling FUNCTION: enablePinShadowDOM","color: green;");try{this.trackEvent(Z.Events.Comments.ENABLE_PIN_SHADOW_DOM_TRIGGERED),this.getService(Te).enablePinShadowDOM()}catch(o){this.getService(y).catch("Error in _enablePinShadowDOM: ",o)}}_disablePinShadowDOM(){this.getService(y).log("%c[WB] Calling FUNCTION: disablePinShadowDOM","color: green;");try{this.trackEvent(Z.Events.Comments.DISABLE_PIN_SHADOW_DOM_TRIGGERED),this.getService(Te).disablePinShadowDOM()}catch(o){this.getService(y).catch("Error in _disablePinShadowDOM: ",o)}}_enableDialogShadowDOM(){this.getService(y).log("%c[WB] Calling FUNCTION: enableDialogShadowDOM","color: green;");try{this.trackEvent(Z.Events.Comments.ENABLE_DIALOG_SHADOW_DOM_TRIGGERED),this.getService(Te).enableDialogShadowDOM()}catch(o){this.getService(y).catch("Error in _enableDialogShadowDOM: ",o)}}_disableDialogShadowDOM(){this.getService(y).log("%c[WB] Calling FUNCTION: disableDialogShadowDOM","color: green;");try{this.trackEvent(Z.Events.Comments.DISABLE_DIALOG_SHADOW_DOM_TRIGGERED),this.getService(Te).disableDialogShadowDOM()}catch(o){this.getService(y).catch("Error in _disableDialogShadowDOM: ",o)}}_enableSidebarShadowDOM(){this.getService(y).log("%c[WB] Calling FUNCTION: enableSidebarShadowDOM","color: green;");try{this.trackEvent(Z.Events.Comments.ENABLE_SIDEBAR_SHADOW_DOM_TRIGGERED),this.getService(Te).enableSidebarShadowDOM()}catch(o){this.getService(y).catch("Error in _enableSidebarShadowDOM: ",o)}}_disableSidebarShadowDOM(){this.getService(y).log("%c[WB] Calling FUNCTION: disableSidebarShadowDOM","color: green;");try{this.trackEvent(Z.Events.Comments.DISABLE_SIDEBAR_SHADOW_DOM_TRIGGERED),this.getService(Te).disableSidebarShadowDOM()}catch(o){this.getService(y).catch("Error in _disableSidebarShadowDOM: ",o)}}_enableChangeDetectionInCommentMode(){this.getService(y).log("%c[WB] Calling FUNCTION: enableChangeDetectionInCommentMode","color: green;");try{this.trackEvent(Z.Events.Comments.ENABLE_CHANGE_DETECTION_IN_COMMENT_MODE_TRIGGERED),this.getService(Te).enableChangeDetectionInCommentMode()}catch(o){this.getService(y).catch("Error in _enableChangeDetectionInCommentMode: ",o)}}_disableChangeDetectionInCommentMode(){this.getService(y).log("%c[WB] Calling FUNCTION: disableChangeDetectionInCommentMode","color: green;");try{this.trackEvent(Z.Events.Comments.DISABLE_CHANGE_DETECTION_IN_COMMENT_MODE_TRIGGERED),this.getService(Te).disableChangeDetectionInCommentMode()}catch(o){this.getService(y).catch("Error in _disableChangeDetectionInCommentMode: ",o)}}_showResolvedCommentsOnDom(){this.getService(y).log("%c[WB] Calling FUNCTION: showResolvedCommentsOnDom","color: green;");try{this.trackEvent(Z.Events.Comments.SHOW_RESOLVED_COMMENTS_ON_DOM_TRIGGERED),this.getService(Te).showResolvedCommentsOnDom()}catch(o){this.getService(y).catch("Error in _showResolvedCommentsOnDom: ",o)}}_hideResolvedCommentsOnDom(){this.getService(y).log("%c[WB] Calling FUNCTION: hideResolvedCommentsOnDom","color: green;");try{this.trackEvent(Z.Events.Comments.HIDE_RESOLVED_COMMENTS_ON_DOM_TRIGGERED),this.getService(Te).hideResolvedCommentsOnDom()}catch(o){this.getService(y).catch("Error in _hideResolvedCommentsOnDom: ",o)}}_setCustomReactions(o){this.getService(y).log("%c[WB] Calling FUNCTION: setCustomReactions","color: green;");try{this.trackEvent(Z.Events.Comments.SET_CUSTOM_REACTIONS_TRIGGERED,{payload:{reactions:o}}),this.getService(Te).setCustomReactions(o)}catch(t){this.getService(y).catch("Error in _setCustomReactions: ",t)}}_onCommentSelectionChange(){this.getService(y).log("%c[WB] Calling FUNCTION: onCommentSelectionChange","color: green;");try{return this.trackEvent(Z.Events.Comments.ON_COMMENT_SELECTION_CHANGE_TRIGGERED),this.getService(Te).onCommentSelectionChange$()}catch(o){return this.getService(y).catch("Error in _onCommentSelectionChange: ",o),re(null)}}_getUnreadCommentCountByAnnotationId(o){this.getService(y).log("%c[WB] Calling FUNCTION: getUnreadCommentCountByAnnotationId","color: green;");try{return this.trackEvent(Z.Events.Comments.GET_UNREAD_COMMENT_COUNT_BY_ANNOTATION_ID_TRIGGERED,{payload:{commentAnnotationId:o}}),this.getService(Te).getUnreadCommentCountByAnnotationId$(o)}catch(t){return this.getService(y).catch("Error in _getUnreadCommentCountByAnnotationId: ",t),re(null)}}_getUnreadCommentAnnotationCountOnCurrentDocument(){this.getService(y).log("%c[WB] Calling FUNCTION: getUnreadCommentAnnotationCountOnCurrentDocument","color: green;");try{return this.trackEvent(Z.Events.Comments.GET_UNREAD_COMMENT_ANNOTATION_COUNT_ON_CURRENT_DOCUMENT_TRIGGERED),this.getService(Te).getUnreadCommentAnnotationCountOnCurrentDocument$()}catch(o){return this.getService(y).catch("Error in _getUnreadCommentAnnotationCountOnCurrentDocument: ",o),re(null)}}_getUnreadCommentCountOnCurrentDocument(){this.getService(y).log("%c[WB] Calling FUNCTION: getUnreadCommentCountOnCurrentDocument","color: green;");try{return this.trackEvent(Z.Events.Comments.GET_UNREAD_COMMENT_COUNT_ON_CURRENT_DOCUMENT_TRIGGERED),this.getService(Te).getUnreadCommentCountOnCurrentDocument$()}catch(o){return this.getService(y).catch("Error in _getUnreadCommentCountOnCurrentDocument: ",o),re(null)}}_getUnreadCommentAnnotationCountByLocationId(o){this.getService(y).log("%c[WB] Calling FUNCTION: getUnreadCommentAnnotationCountByLocationId","color: green;");try{return this.trackEvent(Z.Events.Comments.GET_UNREAD_COMMENT_ANNOTATION_COUNT_BY_LOCATION_ID_TRIGGERED,{payload:{locationId:o}}),this.getService(Te).getUnreadCommentAnnotationCountByLocationId$(o)}catch(t){return this.getService(y).catch("Error in _getUnreadCommentAnnotationCountByLocationId: ",t),re(null)}}_getUnreadCommentCountByLocationId(o){this.getService(y).log("%c[WB] Calling FUNCTION: getUnreadCommentCountByLocationId","color: green;");try{return this.trackEvent(Z.Events.Comments.GET_UNREAD_COMMENT_COUNT_BY_LOCATION_ID_TRIGGERED,{payload:{locationId:o}}),this.getService(Te).getUnreadCommentCountByLocationId$(o)}catch(t){return this.getService(y).catch("Error in _getUnreadCommentCountByLocationId: ",t),re(null)}}_updateCommentDialogPosition(){this.getService(y).log("%c[WB] Calling FUNCTION: updateCommentDialogPosition","color: green;");try{this.trackEvent(Z.Events.Comments.UPDATE_COMMENT_DIALOG_POSITION_TRIGGERED),this.getService(Te).updateCommentDialogPosition()}catch(o){this.getService(y).catch("Error in _updateCommentDialogPosition: ",o)}}_enableAreaComment(){this.getService(y).log("%c[WB] Calling FUNCTION: enableAreaComment","color: green;");try{this.trackEvent(Z.Events.Comments.ENABLE_AREA_COMMENT_TRIGGERED),this.getService(Te).enableAreaComment()}catch(o){this.getService(y).catch("Error in _enableAreaComment: ",o)}}_disableAreaComment(){this.getService(y).log("%c[WB] Calling FUNCTION: disableAreaComment","color: green;");try{this.trackEvent(Z.Events.Comments.DISABLE_AREA_COMMENT_TRIGGERED),this.getService(Te).disableAreaComment()}catch(o){this.getService(y).catch("Error in _disableAreaComment: ",o)}}_setPinCursorImage(o){this.getService(y).log("%c[WB] Calling FUNCTION: setPinCursorImage","color: green;");try{this.trackEvent(Z.Events.Comments.SET_PIN_CURSOR_IMAGE_TRIGGERED,{payload:{image:o}}),this.getService(Te).setPinCursorImage(o)}catch(t){this.getService(y).catch("Error in _setPinCursorImage: ",t)}}_addManualComment(o){this.getService(y).log("%c[WB] Calling FUNCTION: addManualComment","color: green;");try{return this.trackEvent(Z.Events.Comments.ADD_MANUAL_COMMENT_TRIGGERED,{payload:{config:o}}),this.getService(Te).addManualComment(o)}catch(t){return this.getService(y).catch("Error in _addManualComment: ",t),Promise.resolve()}}_createCustomListDataOnAnnotation(o){this.getService(y).log("%c[WB] Calling FUNCTION: createCustomListDataOnAnnotation","color: green;");try{this.trackEvent(Z.Events.Comments.CREATE_CUSTOM_LIST_DATA_ON_ANNOTATION_TRIGGERED,{payload:{data:o}}),this.getService(Te).createCustomListDataOnAnnotation(o)}catch(t){this.getService(y).catch("Error in _createCustomListDataOnAnnotation: ",t)}}_createCustomListDataOnComment(o){this.getService(y).log("%c[WB] Calling FUNCTION: createCustomListDataOnComment","color: green;");try{return this.trackEvent(Z.Events.Comments.CREATE_CUSTOM_LIST_DATA_ON_COMMENT_TRIGGERED,{payload:{data:o}}),this.getService(zs).create(o)}catch(t){this.getService(y).catch("Error in _createCustomListDataOnComment: ",t)}}_excludeLocationIdsFromSidebar(o){this.getService(y).log("%c[WB] Calling FUNCTION: excludeLocationIdsFromSidebar","color: green;");try{this.trackEvent(Z.Events.Comments.EXCLUDE_LOCATION_IDS_FROM_SIDEBAR_TRIGGERED,{payload:{locationIds:o}}),this.getService(Te).setExcludeLocationIdsFromSidebar(o)}catch(t){this.getService(y).catch("Error in _excludeLocationIdsFromSidebar: ",t)}}_enableBubbleOnPin(){this.getService(y).log("%c[WB] Calling FUNCTION: enableBubbleOnPin","color: green;");try{this.trackEvent(Z.Events.Comments.ENABLE_BUBBLE_ON_PIN_TRIGGERED),this.getService(Te).enableBubbleOnPin()}catch(o){this.getService(y).catch("Error in _enableBubbleOnPin: ",o)}}_disableBubbleOnPin(){this.getService(y).log("%c[WB] Calling FUNCTION: disableBubbleOnPin","color: green;");try{this.trackEvent(Z.Events.Comments.DISABLE_BUBBLE_ON_PIN_TRIGGERED),this.getService(Te).disableBubbleOnPin()}catch(o){this.getService(y).catch("Error in _disableBubbleOnPin: ",o)}}_enableBubbleOnPinHover(){this.getService(y).log("%c[WB] Calling FUNCTION: enableBubbleOnPinHover","color: green;");try{this.trackEvent(Z.Events.Comments.ENABLE_BUBBLE_ON_PIN_HOVER_TRIGGERED),this.getService(Te).enableBubbleOnPinHover()}catch(o){this.getService(y).catch("Error in _enableBubbleOnPinHover: ",o)}}_disableBubbleOnPinHover(){this.getService(y).log("%c[WB] Calling FUNCTION: disableBubbleOnPinHover","color: green;");try{this.trackEvent(Z.Events.Comments.DISABLE_BUBBLE_ON_PIN_HOVER_TRIGGERED),this.getService(Te).disableBubbleOnPinHover()}catch(o){this.getService(y).catch("Error in _disableBubbleOnPinHover: ",o)}}_enableMultiThread(){this.getService(y).log("%c[WB] Calling FUNCTION: enableMultiThread","color: green;");try{this.trackEvent(Z.Events.Comments.ENABLE_MULTI_THREAD_TRIGGERED),this.getService(Te).enableMultiThread()}catch(o){this.getService(y).catch("Error in _enableMultiThread: ",o)}}_disableMultiThread(){this.getService(y).log("%c[WB] Calling FUNCTION: disableMultiThread","color: green;");try{this.trackEvent(Z.Events.Comments.DISABLE_MULTI_THREAD_TRIGGERED),this.getService(Te).disableMultiThread()}catch(o){this.getService(y).catch("Error in _disableMultiThread: ",o)}}_updateContext(o,t,e){this.getService(y).log("%c[WB] Calling FUNCTION: updateContext","color: green;");try{return this.trackEvent(Z.Events.Comments.UPDATE_CONTEXT_TRIGGERED,{payload:{annotationId:o,context:t,config:e}}),this.getService(Te).updateCommentAnnotationContext(o,t,e)}catch(i){return this.getService(y).catch("Error in _updateContext: ",i),Promise.resolve()}}_getSelectedComments(){this.getService(y).log("%c[WB] Calling FUNCTION: getSelectedComments","color: green;");try{return this.trackEvent(Z.Events.Comments.GET_SELECTED_COMMENTS_TRIGGERED),this.getService(Fe).getSelectedComments$()}catch(o){return this.getService(y).catch("Error in _getSelectedComments: ",o),re([])}}_enableDeleteReplyConfirmation(){this.getService(y).log("%c[WB] Calling FUNCTION: enableDeleteReplyConfirmation","color: green;");try{this.trackEvent(Z.Events.Comments.ENABLE_DELETE_REPLY_CONFIRMATION_TRIGGERED),this.getService(Te).enableDeleteReplyConfirmation()}catch(o){this.getService(y).catch("Error in _enableDeleteReplyConfirmation: ",o)}}_disableDeleteReplyConfirmation(){this.getService(y).log("%c[WB] Calling FUNCTION: disableDeleteReplyConfirmation","color: green;");try{this.getService(Te).disableDeleteReplyConfirmation()}catch(o){this.getService(y).catch("Error in _disableDeleteReplyConfirmation: ",o)}}_onCopyLink(){this.getService(y).log("%c[WB] Calling FUNCTION: onCopyLink","color: green;");try{return this.trackEvent(Z.Events.Comments.ON_COPY_LINK_TRIGGERED),this.getService(Te).getCopyLink$()}catch(o){return this.getService(y).catch("Error in _onCopyLink: ",o),re("")}}_getCommentAnnotationById(o){this.getService(y).log("%c[WB] Calling FUNCTION: getCommentAnnotationById","color: green;");try{return this.trackEvent(Z.Events.Comments.GET_COMMENT_ANNOTATION_BY_ID_TRIGGERED,{payload:{config:o}}),this.getService(Te).getCommentAnnotationById(o)}catch(t){return this.getService(y).catch("Error in _getCommentAnnotationById: ",t),re(null)}}_enableCollapsedComments(){this.getService(y).log("%c[WB] Calling FUNCTION: enableCollapsedComments","color: green;");try{this.trackEvent(Z.Events.Comments.ENABLE_COLLAPSED_COMMENTS_TRIGGERED),this.getService(Te).enableCollapsedComments()}catch(o){this.getService(y).catch("Error in _enableCollapsedComments: ",o)}}_disableCollapsedComments(){this.getService(y).log("%c[WB] Calling FUNCTION: disableCollapsedComments","color: green;");try{this.trackEvent(Z.Events.Comments.DISABLE_COLLAPSED_COMMENTS_TRIGGERED),this.getService(Te).disableCollapsedComments()}catch(o){this.getService(y).catch("Error in _disableCollapsedComments: ",o)}}_onCommentSidebarActionButtonClick(){this.getService(y).log("%c[WB] Calling FUNCTION: onCommentSidebarActionButtonClick","color: green;");try{return this.trackEvent(Z.Events.Comments.ON_COMMENT_SIDEBAR_ACTION_BUTTON_CLICK_TRIGGERED),this.getService(Te).getSidebarCustomActionEventData()}catch(o){return this.getService(y).catch("Error in _onCommentSidebarActionButtonClick: ",o),re(null)}}_setCommentSidebarData(o,t){this.getService(y).log("%c[WB] Calling FUNCTION: setCommentSidebarData","color: green;");try{this.trackEvent(Z.Events.Comments.SET_COMMENT_SIDEBAR_DATA_TRIGGERED,{payload:{data:o,options:t}}),this.getService(Te).setCommentSidebarData(o,t)}catch(e){this.getService(y).catch("Error in _setCommentSidebarData: ",e)}}_onCommentSidebarInit(){this.getService(y).log("%c[WB] Calling FUNCTION: onCommentSidebarInit","color: green;");try{return this.trackEvent(Z.Events.Comments.ON_COMMENT_SIDEBAR_INIT_TRIGGERED),this.getService(Te).getSidebarCustomActionEventDataOnInit()}catch(o){return this.getService(y).catch("Error in _onCommentSidebarInit: ",o),re(null)}}_onCommentSidebarData(){this.getService(y).log("%c[WB] Calling FUNCTION: onCommentSidebarData","color: green;");try{return this.trackEvent(Z.Events.Comments.ON_COMMENT_SIDEBAR_DATA_TRIGGERED),this.getService(Te).getSidebarCustomActionEventDataAllChanges()}catch(o){return this.getService(y).catch("Error in _onCommentSidebarData: ",o),re(null)}}_setCommentSidebarDefaultCustomActions(o){this.getService(y).log("%c[WB] Calling FUNCTION: setCommentSidebarDefaultCustomActions","color: green;");try{this.trackEvent(Z.Events.Comments.SET_COMMENT_SIDEBAR_DEFAULT_CUSTOM_ACTIONS_TRIGGERED,{payload:{actions:o}}),this.getService(Te).setSidebarCustomActionEventData(o,[],{},[])}catch(t){this.getService(y).catch("Error in _setCommentSidebarDefaultCustomActions: ",t)}}_enableSidebarCustomActions(){this.getService(y).log("%c[WB] Calling FUNCTION: enableSidebarCustomActions","color: green;");try{this.trackEvent(Z.Events.Comments.ENABLE_SIDEBAR_CUSTOM_ACTIONS_TRIGGERED),this.getService(Te).enableSidebarCustomActions()}catch(o){this.getService(y).catch("Error in _enableSidebarCustomActions: ",o)}}_disableSidebarCustomActions(){this.getService(y).log("%c[WB] Calling FUNCTION: disableSidebarCustomActions","color: green;");try{this.trackEvent(Z.Events.Comments.DISABLE_SIDEBAR_CUSTOM_ACTIONS_TRIGGERED),this.getService(Te).disableSidebarCustomActions()}catch(o){this.getService(y).catch("Error in _disableSidebarCustomActions: ",o)}}_enableQueryParamsComments(){this.getService(y).log("%c[WB] Calling FUNCTION: enableQueryParamsComments","color: green;");try{this.trackEvent(Z.Events.Comments.ENABLE_QUERY_PARAMS_COMMENTS_TRIGGERED),this.getService(Te).enableQueryParamsComments()}catch(o){this.getService(y).catch("Error in _enableQueryParamsComments: ",o)}}_disableQueryParamsComments(){this.getService(y).log("%c[WB] Calling FUNCTION: disableQueryParamsComments","color: green;");try{this.trackEvent(Z.Events.Comments.DISABLE_QUERY_PARAMS_COMMENTS_TRIGGERED),this.getService(Te).disableQueryParamsComments()}catch(o){this.getService(y).catch("Error in _disableQueryParamsComments: ",o)}}_enableResolveStatusAccessAdminOnly(){this.getService(y).log("%c[WB] Calling FUNCTION: enableResolveStatusAccessAdminOnly","color: green;");try{this.trackEvent(Z.Events.Comments.ENABLE_RESOLVE_STATUS_ACCESS_ADMIN_ONLY_TRIGGERED),this.getService(Te).enableResolveStatusAccessAdminOnly()}catch(o){this.getService(y).catch("Error in _enableResolveStatusAccessAdminOnly: ",o)}}_disableResolveStatusAccessAdminOnly(){this.getService(y).log("%c[WB] Calling FUNCTION: disableResolveStatusAccessAdminOnly","color: green;");try{this.trackEvent(Z.Events.Comments.DISABLE_RESOLVE_STATUS_ACCESS_ADMIN_ONLY_TRIGGERED),this.getService(Te).disableResolveStatusAccessAdminOnly()}catch(o){this.getService(y).catch("Error in _disableResolveStatusAccessAdminOnly: ",o)}}_enableSeenByUsers(){this.getService(y).log("%c[WB] Calling FUNCTION: enableSeenByUsers","color: green;");try{this.trackEvent(Z.Events.Comments.ENABLE_SEEN_BY_USERS_TRIGGERED),this.getService(Te).enableSeenByUsers()}catch(o){this.getService(y).catch("Error in _enableSeenByUsers: ",o)}}_disableSeenByUsers(){this.getService(y).log("%c[WB] Calling FUNCTION: disableSeenByUsers","color: green;");try{this.trackEvent(Z.Events.Comments.DISABLE_SEEN_BY_USERS_TRIGGERED),this.getService(Te).disableSeenByUsers()}catch(o){this.getService(y).catch("Error in _disableSeenByUsers: ",o)}}_enableShortUserName(){this.getService(y).log("%c[WB] Calling FUNCTION: enableShortUserName","color: green;");try{this.trackEvent(Z.Events.Comments.ENABLE_SHORT_USER_NAME_TRIGGERED),this.getService(Te).enableShortUserName()}catch(o){this.getService(y).catch("Error in _enableShortUserName: ",o)}}_disableShortUserName(){this.getService(y).log("%c[WB] Calling FUNCTION: disableShortUserName","color: green;");try{this.trackEvent(Z.Events.Comments.DISABLE_SHORT_USER_NAME_TRIGGERED),this.getService(Te).disableShortUserName()}catch(o){this.getService(y).catch("Error in _disableShortUserName: ",o)}}_addCommentAnnotation(o){return ee(this,null,function*(){this.getService(y).log("%c[WB] Calling FUNCTION: addCommentAnnotation","color: green;");try{return this.trackEvent(Z.Events.Comments.ADD_COMMENT_ANNOTATION_TRIGGERED,{payload:{addCommentAnnotationRequest:o}}),this.getService(ni).convert(o).addCommentAnnotation(o,"external")}catch(t){return this.getService(y).catch("Error in _addCommentAnnotation: ",t),null}})}_approveCommentAnnotation(o){return ee(this,null,function*(){this.getService(y).log("%c[WB] Calling FUNCTION: approveCommentAnnotation","color: green;");try{return this.trackEvent(Z.Events.Comments.APPROVE_COMMENT_ANNOTATION_TRIGGERED,{payload:{approveCommentAnnotationRequest:o}}),this.getService(ni).convert(o).approveCommentAnnotation(o,"external")}catch(t){return this.getService(y).catch("Error in _approveCommentAnnotation: ",t),null}})}_acceptCommentAnnotation(o){return ee(this,null,function*(){this.getService(y).log("%c[WB] Calling FUNCTION: acceptCommentAnnotation","color: green;");try{return this.trackEvent(Z.Events.Comments.ACCEPT_COMMENT_ANNOTATION_TRIGGERED,{payload:{acceptCommentAnnotationRequest:o}}),this.getService(ni).convert(o).acceptCommentAnnotation(o,"external")}catch(t){return this.getService(y).catch("Error in _acceptCommentAnnotation: ",t),null}})}_rejectCommentAnnotation(o){return ee(this,null,function*(){this.getService(y).log("%c[WB] Calling FUNCTION: rejectCommentAnnotation","color: green;");try{return this.trackEvent(Z.Events.Comments.REJECT_COMMENT_ANNOTATION_TRIGGERED,{payload:{rejectCommentAnnotationRequest:o}}),this.getService(ni).convert(o).rejectCommentAnnotation(o,"external")}catch(t){return this.getService(y).catch("Error in _rejectCommentAnnotation: ",t),null}})}_subscribeCommentAnnotation(o){return ee(this,null,function*(){this.getService(y).log("%c[WB] Calling FUNCTION: subscribeCommentAnnotation","color: green;");try{return this.trackEvent(Z.Events.Comments.SUBSCRIBE_COMMENT_ANNOTATION_TRIGGERED,{payload:{subscribeCommentAnnotationRequest:o}}),this.getService(ni).convert(o).toggleNotificationSubscription(o,"subscribe")}catch(t){return this.getService(y).catch("Error in _subscribeCommentAnnotation: ",t),null}})}_unsubscribeCommentAnnotation(o){return ee(this,null,function*(){this.getService(y).log("%c[WB] Calling FUNCTION: unsubscribeCommentAnnotation","color: green;");try{return this.trackEvent(Z.Events.Comments.UNSUBSCRIBE_COMMENT_ANNOTATION_TRIGGERED,{payload:{unsubscribeCommentAnnotationRequest:o}}),this.getService(ni).convert(o).toggleNotificationSubscription(o,"unsubscribe")}catch(t){return this.getService(y).catch("Error in _unsubscribeCommentAnnotation: ",t),null}})}_deleteCommentAnnotation(o){return ee(this,null,function*(){this.getService(y).log("%c[WB] Calling FUNCTION: deleteCommentAnnotation","color: green;");try{return this.trackEvent(Z.Events.Comments.DELETE_COMMENT_ANNOTATION_TRIGGERED,{payload:{deleteCommentAnnotationRequest:o}}),this.getService(ni).convert(o).deleteCommentAnnotation(o,"external")}catch(t){return this.getService(y).catch("Error in _deleteCommentAnnotation: ",t),null}})}_getCommentAnnotations(o){this.getService(y).log("%c[WB] Calling FUNCTION: getCommentAnnotations","color: green;");try{return this.trackEvent(Z.Events.Comments.GET_COMMENT_ANNOTATIONS_TRIGGERED,{payload:{query:o}}),this.getService(ni).getCommentAnnotations(o).pipe(ce(t=>(t.data&&Object.keys(t.data).forEach(e=>{if(t.data?.[e]?.length){let i=t.data[e];t.data[e]=i?.map(r=>$n(r))}}),t)))}catch(t){return this.getService(y).catch("Error in _getCommentAnnotations: ",t),re({data:null})}}_getCommentAnnotationsCount(o){this.getService(y).log("%c[WB] Calling FUNCTION: getCommentAnnotationsCount","color: green;");try{return this.trackEvent(Z.Events.Comments.GET_COMMENT_ANNOTATIONS_COUNT_TRIGGERED,{payload:{query:o}}),this.getService(ni).getCommentAnnotationsCount$(o)}catch(t){return this.getService(y).catch("Error in _getCommentAnnotationsCount: ",t),re({data:null})}}_assignUser(o){return ee(this,null,function*(){this.getService(y).log("%c[WB] Calling FUNCTION: assignUser","color: green;");try{return this.trackEvent(Z.Events.Comments.ASSIGN_USER_TRIGGERED,{payload:{assignUserRequest:o}}),this.getService(ni).convert(o).assignUser(o,"external")}catch(t){return this.getService(y).catch("Error in _assignUser: ",t),null}})}_updatePriority(o){return ee(this,null,function*(){this.getService(y).log("%c[WB] Calling FUNCTION: updatePriority","color: green;");try{return this.trackEvent(Z.Events.Comments.UPDATE_PRIORITY_TRIGGERED,{payload:{updatePriorityRequest:o}}),this.getService(ni).convert(o).updatePriority(o,"external")}catch(t){return this.getService(y).catch("Error in _updatePriority: ",t),null}})}_updateStatus(o){return ee(this,null,function*(){this.getService(y).log("%c[WB] Calling FUNCTION: updateStatus","color: green;");try{return this.trackEvent(Z.Events.Comments.UPDATE_STATUS_TRIGGERED,{payload:{updateStatusRequest:o}}),this.getService(ni).convert(o).updateStatus(o,"external")}catch(t){return this.getService(y).catch("Error in _updateStatus: ",t),null}})}_updateAccess(o){return ee(this,null,function*(){this.getService(y).log("%c[WB] Calling FUNCTION: updateAccess","color: green;");try{return this.trackEvent(Z.Events.Comments.UPDATE_ACCESS_TRIGGERED,{payload:{updateAccessRequest:o}}),this.getService(ni).convert(o).updateAccess(o,"external")}catch(t){return this.getService(y).catch("Error in _updateAccess: ",t),null}})}_resolveCommentAnnotation(o){return ee(this,null,function*(){this.getService(y).log("%c[WB] Calling FUNCTION: resolveCommentAnnotation","color: green;");try{return this.trackEvent(Z.Events.Comments.RESOLVE_COMMENT_ANNOTATION_TRIGGERED,{payload:{resolveCommentAnnotationRequest:o}}),this.getService(ni).convert(o).resolveCommentAnnotation(o)}catch(t){return this.getService(y).catch("Error in _resolveCommentAnnotation: ",t),null}})}_getLink(o){return ee(this,null,function*(){this.getService(y).log("%c[WB] Calling FUNCTION: getLink","color: green;");try{return this.trackEvent(Z.Events.Comments.GET_LINK_TRIGGERED,{payload:{getLinkRequest:o}}),this.getService(ni).convert(o).getLink(o,"external")}catch(t){return this.getService(y).catch("Error in _getLink: ",t),null}})}_copyLink(o){return ee(this,null,function*(){this.getService(y).log("%c[WB] Calling FUNCTION: copyLink","color: green;");try{return this.trackEvent(Z.Events.Comments.COPY_LINK_TRIGGERED,{payload:{copyLinkRequest:o}}),this.getService(ni).convert(o).copyLink(o,"external")}catch(t){return this.getService(y).catch("Error in _copyLink: ",t),null}})}_addComment(o){return ee(this,null,function*(){this.getService(y).log("%c[WB] Calling FUNCTION: addComment","color: green;");try{return this.trackEvent(Z.Events.Comments.ADD_COMMENT_TRIGGERED,{payload:{addCommentRequest:o}}),this.getService(ni).convert(o).addComment(o,"external")}catch(t){return this.getService(y).catch("Error in _addComment: ",t),null}})}_updateComment(o){return ee(this,null,function*(){this.getService(y).log("%c[WB] Calling FUNCTION: updateComment","color: green;");try{return this.trackEvent(Z.Events.Comments.UPDATE_COMMENT_TRIGGERED,{payload:{updateCommentRequest:o}}),this.getService(ni).convert(o).updateComment(o,"external")}catch(t){return this.getService(y).catch("Error in _updateComment: ",t),null}})}_deleteComment(o){return ee(this,null,function*(){this.getService(y).log("%c[WB] Calling FUNCTION: deleteComment","color: green;");try{return this.trackEvent(Z.Events.Comments.DELETE_COMMENT_TRIGGERED,{payload:{deleteCommentRequest:o}}),this.getService(ni).convert(o).deleteComment(o,"external")}catch(t){return this.getService(y).catch("Error in _deleteComment: ",t),null}})}_getComment(o){return ee(this,null,function*(){this.getService(y).log("%c[WB] Calling FUNCTION: getComment","color: green;");try{return this.trackEvent(Z.Events.Comments.GET_COMMENT_TRIGGERED,{payload:{getCommentRequest:o}}),this.getService(ni).convert(o).getComment(o)}catch(t){return this.getService(y).catch("Error in _getComment: ",t),[]}})}_addAttachment(o){return ee(this,null,function*(){this.getService(y).log("%c[WB] Calling FUNCTION: addAttachment","color: green;");try{return this.trackEvent(Z.Events.Comments.ADD_ATTACHMENT_TRIGGERED,{payload:{addAttachmentRequest:o}}),this.getService(ni).convert(o).addAttachment(o)}catch(t){return this.getService(y).catch("Error in _addAttachment: ",t),Promise.resolve([])}})}_deleteAttachment(o){return ee(this,null,function*(){this.getService(y).log("%c[WB] Calling FUNCTION: deleteAttachment","color: green;");try{return this.trackEvent(Z.Events.Comments.DELETE_ATTACHMENT_TRIGGERED,{payload:{deleteAttachmentRequest:o}}),this.getService(ni).convert(o).deleteAttachment(o)}catch(t){return this.getService(y).catch("Error in _deleteAttachment: ",t),null}})}_getAttachment(o){return ee(this,null,function*(){this.getService(y).log("%c[WB] Calling FUNCTION: getAttachment","color: green;");try{return this.trackEvent(Z.Events.Comments.GET_ATTACHMENT_TRIGGERED,{payload:{getAttachmentRequest:o}}),this.getService(ni).convert(o).getAttachment(o)}catch(t){return this.getService(y).catch("Error in _getAttachment: ",t),[]}})}_getRecording(o){return ee(this,null,function*(){this.getService(y).log("%c[WB] Calling FUNCTION: getRecording","color: green;");try{return this.trackEvent(Z.Events.Comments.GET_RECORDING_TRIGGERED,{payload:{getRecordingRequest:o}}),this.getService(ni).convert(o).getRecording(o)}catch(t){return this.getService(y).catch("Error in _getRecording: ",t),[]}})}_deleteRecording(o){return ee(this,null,function*(){this.getService(y).log("%c[WB] Calling FUNCTION: deleteRecording","color: green;");try{return this.trackEvent(Z.Events.Comments.DELETE_RECORDING_TRIGGERED,{payload:{deleteRecordingRequest:o}}),this.getService(ni).convert(o).deleteRecording(o)}catch(t){return this.getService(y).catch("Error in _deleteRecording: ",t),null}})}_fetchCommentAnnotations(o){return ee(this,null,function*(){this.getService(y).log("%c[WB] Calling FUNCTION: fetchCommentAnnotations","color: green;");try{return this.trackEvent(Z.Events.Comments.FETCH_COMMENT_ANNOTATIONS_TRIGGERED,{payload:{fetchCommentAnnotationsRequest:o}}),this.getService(ni).fetchCommentAnnotations(o)}catch(t){return this.getService(y).catch("Error in _fetchCommentAnnotations: ",t),{data:null}}})}_addReaction(o){return ee(this,null,function*(){this.getService(y).log("%c[WB] Calling FUNCTION: addReaction","color: green;");try{return this.trackEvent(Z.Events.Comments.ADD_REACTION_TRIGGERED,{payload:{addReactionRequest:o}}),this.getService(ni).convert(o).toggleReaction(o,"add")}catch(t){return this.getService(y).catch("Error in _addReaction: ",t),null}})}_deleteReaction(o){return ee(this,null,function*(){this.getService(y).log("%c[WB] Calling FUNCTION: deleteReaction","color: green;");try{return this.trackEvent(Z.Events.Comments.DELETE_REACTION_TRIGGERED,{payload:{deleteReactionRequest:o}}),this.getService(ni).convert(o).toggleReaction(o,"delete")}catch(t){return this.getService(y).catch("Error in _deleteReaction: ",t),null}})}_toggleReaction(o){return ee(this,null,function*(){this.getService(y).log("%c[WB] Calling FUNCTION: toggleReaction","color: green;");try{return this.trackEvent(Z.Events.Comments.TOGGLE_REACTION_TRIGGERED,{payload:{toggleReactionRequest:o}}),this.getService(ni).convert(o).toggleReaction(o)}catch(t){return this.getService(y).catch("Error in _toggleReaction: ",t),null}})}_on(o){this.getService(y).log("%c[WB] Calling FUNCTION: on","color: green;");try{return this.trackEvent(Z.Events.Comments.ON_ACTION_TRIGGERED,{payload:{action:o}}),this.getService(ni).onAction(o)}catch(t){return this.getService(y).catch("Error in _on: ",t),re(null)}}_enableReadOnly(){return ee(this,null,function*(){this.getService(y).log("%c[WB] Calling FUNCTION: enableReadOnly","color: green;");try{return this.trackEvent(Z.Events.Comments.ENABLE_READ_ONLY_TRIGGERED),this.getService(Te).enableReadOnly()}catch(o){this.getService(y).catch("Error in _toggleReaction: ",o);return}})}_disableReadOnly(){return ee(this,null,function*(){this.getService(y).log("%c[WB] Calling FUNCTION: disableReadOnly","color: green;");try{return this.trackEvent(Z.Events.Comments.DISABLE_READ_ONLY_TRIGGERED),this.getService(Te).disableReadOnly()}catch(o){this.getService(y).catch("Error in _disableReadOnly: ",o);return}})}_enableCustomAutocompleteSearch(){this.getService(y).log("%c[WB] Calling FUNCTION: enableCustomAutocompleteSearch","color: green;");try{this.trackEvent(Z.Events.Comments.ENABLE_CUSTOM_AUTOCOMPLETE_SEARCH_TRIGGERED),this.getService(Te).enableCustomAutocompleteSearch()}catch(o){this.getService(y).catch("Error in _enableCustomAutocompleteSearch: ",o);return}}_disableCustomAutocompleteSearch(){this.getService(y).log("%c[WB] Calling FUNCTION: disableCustomAutocompleteSearch","color: green;");try{this.trackEvent(Z.Events.Comments.DISABLE_CUSTOM_AUTOCOMPLETE_SEARCH_TRIGGERED),this.getService(Te).disableCustomAutocompleteSearch()}catch(o){this.getService(y).catch("Error in _disableCustomAutocompleteSearch: ",o);return}}_setTransformContext(o){this.getService(y).log("%c[WB] Calling FUNCTION: setTransformContext","color: green;");try{this.trackEvent(Z.Events.Comments.SET_TRANSFORM_CONTEXT_TRIGGERED,{payload:{transformContext:o}}),this.getService(Te).setTransformContext(o)}catch(t){this.getService(y).catch("Error in _setTransformContext: ",t);return}}_enableSvgAsImg(){this.getService(y).log("%c[WB] Calling FUNCTION: enableSvgAsImg","color: green;");try{this.trackEvent(Z.Events.Comments.ENABLE_SVG_AS_IMG_TRIGGERED),this.getService(Te).enableSvgAsImg()}catch(o){this.getService(y).catch("Error in _enableSvgAsImg: ",o);return}}_disableSvgAsImg(){this.getService(y).log("%c[WB] Calling FUNCTION: disableSvgAsImg","color: green;");try{this.trackEvent(Z.Events.Comments.DISABLE_SVG_AS_IMG_TRIGGERED),this.getService(Te).disableSvgAsImg()}catch(o){this.getService(y).catch("Error in _disableSvgAsImg: ",o);return}}_enableFullExpanded(){this.getService(y).log("%c[WB] Calling FUNCTION: enableFullExpanded","color: green;");try{this.trackEvent(Z.Events.Comments.ENABLE_FULL_EXPANDED_TRIGGERED),this.getService(Te).enableFullExpanded()}catch(o){this.getService(y).catch("Error in _enableFullExpanded: ",o);return}}_disableFullExpanded(){this.getService(y).log("%c[WB] Calling FUNCTION: disableFullExpanded","color: green;");try{this.trackEvent(Z.Events.Comments.DISABLE_FULL_EXPANDED_TRIGGERED),this.getService(Te).disableFullExpanded()}catch(o){this.getService(y).catch("Error in _disableFullExpanded: ",o);return}}_enableCommentToNearestAllowedElement(){this.getService(y).log("%c[WB] Calling FUNCTION: enableCommentToNearestAllowedElement","color: green;");try{this.trackEvent(Z.Events.Comments.ENABLE_COMMENT_TO_NEAREST_ALLOWED_ELEMENT_TRIGGERED),this.getService(Te).enableCommentToNearestAllowedElement()}catch(o){this.getService(y).catch("Error in _enableCommentToNearestAllowedElement: ",o);return}}_disableCommentToNearestAllowedElement(){this.getService(y).log("%c[WB] Calling FUNCTION: disableCommentToNearestAllowedElement","color: green;");try{this.trackEvent(Z.Events.Comments.DISABLE_COMMENT_TO_NEAREST_ALLOWED_ELEMENT_TRIGGERED),this.getService(Te).disableCommentToNearestAllowedElement()}catch(o){this.getService(y).catch("Error in _disableCommentToNearestAllowedElement: ",o);return}}_enableDraftMode(){this.getService(y).log("%c[WB] Calling FUNCTION: enableDraftMode","color: green;");try{this.trackEvent(Z.Events.Comments.ENABLE_DRAFT_MODE_TRIGGERED),this.getService(Te).enableDraftMode()}catch(o){this.getService(y).catch("Error in _enableDraftMode: ",o);return}}_disableDraftMode(){this.getService(y).log("%c[WB] Calling FUNCTION: disableDraftMode","color: green;");try{this.trackEvent(Z.Events.Comments.DISABLE_DRAFT_MODE_TRIGGERED),this.getService(Te).disableDraftMode()}catch(o){this.getService(y).catch("Error in _disableDraftMode: ",o);return}}};var BM=class extends li{constructor(o){super(o),this.getService(y).log("%c[WB] Creating CLASS: ContactElement","color: blue;"),this.isUserGlobalContact=this._isUserGlobalContact,this.onContactSelected=this._onContactSelected,this.enableAtHere=this._enableAtHere,this.setAtHereLabel=this._setAtHereLabel,this.setAtHereDescription=this._setAtHereDescription,this.disableAtHere=this._disableAtHere,this.updateContactListScopeForOrganizationUsers=this._updateContactListScopeForOrganizationUsers,this.updateContactList=this._updateContactList,this.getContactList=this._getContactList}_isUserGlobalContact(){this.getService(y).log("%c[WB] Calling FUNCTION: isUserGlobalContact","color: green;");try{return this.trackEvent(Z.Events.Contact.IS_USER_GLOBAL_CONTACT_TRIGGERED),this.getService(gi).isUserGlobalContact$()}catch(o){return this.getService(y).catch("Error in _isUserGlobalContact: ",o),re(!1)}}_onContactSelected(){this.getService(y).log("%c[WB] Calling FUNCTION: onContactSelected","color: green;");try{return this.trackEvent(Z.Events.Contact.ON_CONTACT_SELECTED_TRIGGERED),this.getService(gi).onContactSelected$()}catch(o){return this.getService(y).catch("Error in _onContactSelected: ",o),re(null)}}_enableAtHere(){this.getService(y).log("%c[WB] Calling FUNCTION: enableAtHere","color: green;");try{this.trackEvent(Z.Events.Contact.ENABLE_AT_HERE_TRIGGERED),this.getService(gi).enableAtHere()}catch(o){this.getService(y).catch("Error in _enableAtHere: ",o)}}_setAtHereLabel(o){this.getService(y).log("%c[WB] Calling FUNCTION: setAtHereLabel","color: green;");try{this.trackEvent(Z.Events.Contact.SET_AT_HERE_LABEL_TRIGGERED,{payload:{label:o}}),this.getService(gi).setAtHereLabel(o)}catch(t){this.getService(y).catch("Error in setAtHereLabel: ",t)}}_setAtHereDescription(o){this.getService(y).log("%c[WB] Calling FUNCTION: setAtHereDescription","color: green;");try{this.trackEvent(Z.Events.Contact.SET_AT_HERE_DESCRIPTION_TRIGGERED,{payload:{description:o}}),this.getService(gi).setAtHereDescription(o)}catch(t){this.getService(y).catch("Error in setAtHereDescription: ",t)}}_disableAtHere(){this.getService(y).log("%c[WB] Calling FUNCTION: disableAtHere","color: green;");try{this.trackEvent(Z.Events.Contact.DISABLE_AT_HERE_TRIGGERED),this.getService(gi).disableAtHere()}catch(o){this.getService(y).catch("Error in _disableAtHere: ",o)}}_updateContactListScopeForOrganizationUsers(o){this.getService(y).log("%c[WB] Calling FUNCTION: updateContactListScopeForOrganizationUsers","color: green;");try{this.trackEvent(Z.Events.Contact.UPDATE_CONTACT_LIST_SCOPE_FOR_ORGANIZATION_USERS_TRIGGERED,{payload:{scope:o}}),this.getService(gi).updateContactListScopeForOrganizationUsers(o)}catch(t){this.getService(y).catch("Error in _updateContactListScopeForOrganizationUsers: ",t)}}_updateContactList(o,t){this.getService(y).log("%c[WB] Calling FUNCTION: _updateContactList","color: green;");try{this.trackEvent(Z.Events.Contact.UPDATE_CONTACT_LIST_TRIGGERED,{payload:{userContacts:o,config:t}}),typeof o=="object"&&o instanceof Array&&(!t||t&&typeof t=="object")&&(o=JSON.parse(JSON.stringify(o)),this.getService(gi).convert(t).updateContactList(o,t))}catch(e){this.getService(y).catch("Error in _updateContactList: ",e)}}_getContactList(){this.getService(y).log("%c[WB] Calling FUNCTION: getContactList","color: green;");try{return this.trackEvent(Z.Events.Contact.GET_CONTACT_LIST_TRIGGERED),this.getService(gi).getContactList$()}catch(o){return this.getService(y).catch("Error in _getContactList: ",o),re(null)}}};var Xa=function(n){return n.CLICK="click",n.HOVER="hover",n.SCROLL="scroll",n.NAVIGATE="navigate",n}(Xa||{}),Td=class{constructor(){this.type=Xa.HOVER,this.data=null,this.pageInfo=_i(),this.timestamp=Date.now()}},VM=class{constructor(o,t){this.targetXpath=o,this.xpath=t}};var UM=class{constructor(){this.sessionId=null,this.isLeader=!1,this.lastProcessedActionTimestamp=null}};var Wu=class{constructor(o){this.snippylyId=o,this.joinTimestamp=Date.now()}};var jM=class{constructor(o,t,e){this.followers=[],this.actionStack=[],this.id=xn(),this.leaderId=o,this.leaderName=t,this.followers.push(new Wu(e))}};var Tse=(()=>{let o=class o{constructor(e,i,r,a,s){this.databaseService=e,this.docService=i,this.loggingService=r,this.authService=a,this.commonDbService=s,this.currentUser$=new fe(null),this.currentSession$=new fe(null);try{this.databaseService.getDb().pipe(Ne(c=>!!c),Je(1)).subscribe(c=>{c&&(this.db=c)},c=>{this.loggingService.catch("Error in FlockSessionService getDb subscription: ",c)}),this.authService.getUser$().subscribe(c=>{c&&c.userSnippylyId&&(this.user=c)})}catch(c){this.loggingService.catch("Error in FlockSessionService constructor: ",c)}}startCurrentFlockUserSubscription(e){try{this.currentUserSub?.unsubscribe(),e&&e.userSnippylyId&&(this.user=e,this.subscribeToCurrentFlockUser(e?.userSnippylyId))}catch(i){this.loggingService.catch("Error in FlockSessionService startCurrentFlockUserSubscription: ",i)}}stopCurrentFlockUserSubscription(){try{this.currentUserSub?.unsubscribe()}catch(e){this.loggingService.catch("Error in FlockSessionService stopCurrentFlockUserSubscription: ",e)}}provisionFlockSession(e,i,r){try{let a=this.docService.getDocumentPaths();a&&this.db&&this.commonDbService.dbListener({feature:"flockUser",properties:{documentId:a?.documentId,organizationId:a?.organizationId,id:e,skipFirestore:!0}}).pipe(Je(1)).subscribe(s=>{s?.data&&s?.data?.sessionId?this.subscribeToCurrentSession(s?.data?.sessionId,r):this.createFlockSession(e,i,r)})}catch(a){this.loggingService.catch("Error in FlockSessionService provisionFlockSession: ",a)}return null}swapLeader(e,i,r){try{if(this.updateRemoteFlockUser(e,{isLeader:!1}),this.updateRemoteFlockUser(i,{isLeader:!0}),this.currentSession){this.currentSession.leaderId=i,this.currentSession.leaderName=r,this.currentSession.followers.push(new Wu(e));let a=this.currentSession.followers.findIndex(s=>s.snippylyId===i);a>-1&&this.currentSession.followers.splice(a,1),this.updateSession(this.currentSession.id,this.currentSession)}}catch(a){this.loggingService.catch("Error in FlockSessionService swapLeader: ",a)}}createFlockSession(e,i,r){try{let a=new jM(e,i,r);return this.updateRemoteFlockUser(e,{snippylyId:e,sessionId:a.id,isLeader:!0}),this.updateSession(a.id,a),this.subscribeToCurrentSession(a.id),a.id}catch(a){this.loggingService.catch("Error in FlockSessionService createFlockSession: ",a)}return null}removeFollowerFromCurrentSession(e){try{if(this.currentSession){this.updateRemoteFlockUser(e,{sessionId:null,lastProcessedActionTimestamp:null});let i=this.currentSession.followers.findIndex(r=>r.snippylyId===e);if(i>-1){if(this.currentSession.followers.splice(i,1),this.currentSession.followers.length===0){this.deleteSession(this.currentSession.id);return}this.updateSession(this.currentSession.id,this.currentSession),this.user&&this.user.userSnippylyId&&this.user.userSnippylyId===e&&(this.sessionSub?.unsubscribe(),this.currentSession=void 0,this.currentSession$?.next(null))}}}catch(i){this.loggingService.catch("Error in FlockSessionService removeFollowerFromSession: ",i)}}updateRemoteFlockUser(e,i={}){try{if(!e)return;let r=this.docService.getDocumentPaths();for(let a in i)i.hasOwnProperty(a)&&i[a]===void 0&&delete i[a];r&&this.db&&this.commonDbService.updateData({feature:"flockUser",properties:{documentId:r?.documentId??"",organizationId:r?.organizationId??"",id:e,skipFirestore:!0},data:JSON.parse(JSON.stringify(i))})}catch(r){this.loggingService.catch("Error in FlockSessionService updateRemoteFlockUser: ",r)}}subscribeToCurrentSession(e,i=void 0){try{let r=this.docService.getDocumentPaths();r&&this.db&&(this.sessionSub&&this.sessionSub.unsubscribe(),this.sessionSub=this.commonDbService.dbListener({feature:"flockSession",properties:{documentId:r?.documentId,organizationId:r?.organizationId,id:e,skipFirestore:!0}}).subscribe(a=>{a?.data&&typeof a?.data=="object"&&Object.keys(a?.data)?.length>0?(this.currentSession=a?.data,i!==void 0&&this.currentSession?.followers.findIndex(s=>s.snippylyId===i)===-1&&(this.currentSession.followers.push(new Wu(i)),this.updateSession(this.currentSession.id,this.currentSession)),this.currentSession$.next(this.currentSession??null)):(this.currentSession=void 0,this.currentSession$.next(null))}))}catch(r){this.loggingService.catch("Error in FlockSessionService subscribeToCurrentSession: ",r)}}subscribeToCurrentFlockUser(e){try{let i=this.docService.getDocumentPaths();i&&this.db&&(this.currentUserSub&&this.currentUserSub.unsubscribe(),this.currentUserSub=this.commonDbService.dbListener({feature:"flockUser",properties:{documentId:i?.documentId,organizationId:i?.organizationId,id:e,skipFirestore:!0}}).pipe(Ln(r=>(this.loggingService.catch("Error in FlockSessionService subscribeToCurrentFlockUser: ",r),re(null)))).subscribe(r=>{r?.data&&typeof r?.data=="object"&&Object.keys(r?.data)?.length>0&&(this.currentUser$.next(r?.data),r?.data?.sessionId&&this.subscribeToCurrentSession(r?.data?.sessionId))},r=>{this.loggingService.catch("Error in FlockSessionService subscribeToCurrentFlockUser subscription: ",r)}))}catch(i){this.loggingService.catch("Error in FlockSessionService subscribeToCurrentFlockUser: ",i)}}updateSession(e,i={}){try{if(!e)return;let r=this.docService.getDocumentPaths();for(let a in i)i.hasOwnProperty(a)&&i[a]===void 0&&delete i[a];r&&this.db&&this.commonDbService.updateData({feature:"flockSession",properties:{documentId:r?.documentId??"",organizationId:r?.organizationId??"",id:e,skipFirestore:!0},data:JSON.parse(JSON.stringify(i))})}catch(r){this.loggingService.catch("Error in FlockSessionService updateSession: ",r)}}deleteSession(e){try{let i=this.docService.getDocumentPaths();i&&this.db&&(this.commonDbService.deleteData({feature:"flockSession",properties:{documentId:i?.documentId??"",organizationId:i?.organizationId??"",id:e,skipFirestore:!0}}),this.currentSession&&e===this.currentSession.id&&(this.updateRemoteFlockUser(this.currentSession.leaderId,{sessionId:null,isLeader:!1,lastProcessedActionTimestamp:null}),this.currentSession.followers.forEach(r=>{this.updateRemoteFlockUser(r.snippylyId,{sessionId:null,lastProcessedActionTimestamp:null})}),this.currentSession=void 0,this.currentSession$.next(null),this.sessionSub?.unsubscribe()))}catch(i){this.loggingService.catch("Error in FlockSessionService deleteSession: ",i)}}addActionToStack(e,i){try{i=i&&JSON.parse(JSON.stringify(i));let r=this.docService.getDocumentPaths();if(r&&this.db&&e){let a=on(this.db,`${r.flock}/sessions/${e}/actionStack`);UA(a,s=>s?(s.unshift(i),s.slice(0,5)):[i]),i.type===Xa.NAVIGATE&&this.updateSession(e,{pageInfo:i.pageInfo})}}catch(r){this.loggingService.catch("Error in FlockSessionService addActionToStack: ",r)}}};o.\u0275fac=function(i){return new(i||o)(J(pn),J(lt),J(y),J(je),J(bn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var wse={en:{"Action button":"Action button",Yes:"Yes",Delete:"Delete",Cancel:"Cancel","Delete thread?":"Delete thread?","All replies to this thread will be lost.":"All replies to this thread will be lost.","Delete comment?":"Delete comment?","This selected comment will be deleted.":"This selected comment will be deleted.","Delete recording?":"Delete recording?","This selected recording will be deleted.":"This selected recording will be deleted.","Delete area?":"Delete area?","This selected area will be deleted.":"This selected area will be deleted.","Delete arrow?":"Delete arrow?","This selected arrow will be deleted.":"This selected arrow will be deleted.","Delete tag?":"Delete tag?","This selected tag will be deleted.":"This selected tag will be deleted.","Contact us":"Contact us","Let us know how can we help you!":"Let us know how can we help you!","Your email address":"Your email address","How can we help?":"How can we help?",Send:"Send","Allow mic permission to":"Allow mic permission to","enable your audio":"enable your audio","1. Click the":"1. Click the","page info icon in your browser\u2019s address bar":"page info icon in your browser\u2019s address bar","2. Turn on Microphone":"2. Turn on Microphone","2. Turn on Camera":"2. Turn on Camera","Allow camera permission":"Allow camera permission","to enable your video":"to enable your video",dropdown:"dropdown","assign dropdown":"assign dropdown","custom dropdown":"custom dropdown","options dropdown":"options dropdown","priority dropdown":"priority dropdown","status dropdown":"status dropdown","seen dropdown":"seen dropdown",menu:"menu","assign menu":"assign menu","custom menu":"custom menu","options menu":"options menu","priority menu":"priority menu","status menu":"status menu","seen menu":"seen menu","menu items":"menu items","assign menu items":"assign menu items","custom menu items":"custom menu items","options menu items":"options menu items","priority menu items":"priority menu items","status menu items":"status menu items","seen menu items":"seen menu items","Playback Speed":"Playback Speed","Subtitles not available":"Subtitles not available","Transcription not available":"Transcription not available",Feedback:"Feedback","Provide feedback on your Superflow experience.":"Provide feedback on your Superflow experience.","Tell us the details...":"Tell us the details...","You are following":"You are following","You are leading.":"You are leading.",Stop:"Stop",following:"following",leading:"leading","is editing.":"is editing.","requested edit access.":"requested edit access.","You are editing.":"You are editing.","You are editing on different tab.":"You are editing on different tab.","Access Requested":"Access Requested","Request access":"Request access","Edit here":"Edit here",Settings:"Settings",Audio:"Audio",Microphone:"Microphone",Video:"Video",Camera:"Camera","Save changes":"Save changes","Audio settings":"Audio settings","No device found":"No device found","Video settings":"Video settings","Media source settings":"Media source settings","Audio recording preview":"Audio recording preview","Cancel recording":"Cancel recording","Video recording icon":"Video recording icon","Screen recording icon":"Screen recording icon","Audio recording icon":"Audio recording icon","Recording preview bottom panel":"Recording preview bottom panel","Starting recording in":"Starting recording in","Recording control buttons":"Recording control buttons","Toggle camera":"Toggle camera",off:"off",on:"on","Camera is off":"Camera is off","Close recording preview":"Close recording preview","Toggle microphone":"Toggle microphone",Close:"Close",Open:"Open","recording settings":"recording settings","Start Recording":"Start Recording","Report bugs":"Report bugs","Let us know about any bugs so we can fix them ASAP!":"Let us know about any bugs so we can fix them ASAP!","Thank you! We will get back to you soon.":"Thank you! We will get back to you soon.","Thank you for your feedback!":"Thank you for your feedback!","Thanks for reporting the bug. We will get back to you soon.":"Thanks for reporting the bug. We will get back to you soon.","Invitation sent!":"Invitation sent!","User removed!":"User removed!",members:"members","Invalid contact":"Invalid contact","Invalid email":"Invalid email","Comment pin":"Comment pin","Add text comment":"Add text comment","Add comment annotation":"Add comment annotation","Use AI to rewrite selected text":"Use AI to rewrite selected text","Select a shorter text":"Select a shorter text","Select a longer text":"Select a longer text",Rewrite:"Rewrite","Ask ChatGPT":"Ask ChatGPT","Text comment tools":"Text comment tools","Avatar for comment author":"Avatar for comment author","comments in this thread":"comments in this thread","Assign To":"Assign To","Attach files":"Attach files","Attach files input":"Attach files input","All comments":"All comments","View all comments":"View all comments","Approve comment":"Approve comment",Approve:"Approve","Assign thread":"Assign thread",Search:"Search","Search users":"Search users","Avatar for assigned user":"Avatar for assigned user","Assigned to":"Assigned to","Comment assignment details":"Comment assignment details","Assigned to:":"Assigned to:","Comment dialog thread":"Comment dialog thread","Close comment dialog":"Close comment dialog","Comment Index":"Comment Index",Suggestion:"Suggestion","Comment tools and actions":"Comment tools and actions","Mention someone using @ symbol":"Mention someone using @ symbol","Mention someone using @ symbol while editing":"Mention someone using @ symbol while editing","Type @ to mention someone":"Type @ to mention someone","Type @ to mention someone while editing":"Type @ to mention someone while editing","Add file attachment to comment":"Add file attachment to comment","Record voice message":"Record voice message","Click to start voice recording":"Click to start voice recording","Record video message":"Record video message","Click to start screen recording":"Click to start screen recording","Record your screen":"Record your screen","Save new comment":"Save new comment","Save edited comment":"Save edited comment","Assign user":"Assign user","Remove File":"Remove File","Image attachment:":"Image attachment:","unnamed image":"unnamed image","Actions for image:":"Actions for image:","Uploading image:":"Uploading image:","Delete image:":"Delete image:","Preview of image:":"Preview of image:","Remove invalid file:":"Remove invalid file:","Error message:":"Error message:","Invalid file:":"Invalid file:","Actions for invalid file:":"Actions for invalid file:","File error:":"File error:","File cannot be uploaded":"File cannot be uploaded","Preview of invalid file:":"Preview of invalid file:","Invalid file":"Invalid file",unknown:"unknown","Delete file":"Delete file","File attachment:":"File attachment:","unnamed file":"unnamed file","File type icon for":"File type icon for","Details for file:":"Details for file:","Filename:":"Filename:","File size:":"File size:","Uploading file:":"Uploading file:","Actions for file:":"Actions for file:","Remove file:":"Remove file:","Attached files":"Attached files","total attachments":"total attachments","File attachments":"File attachments",valid:"valid","invalid files":"invalid files","User avatar for":"User avatar for","unknown user":"unknown user","New comment composer":"New comment composer","Comment or type @ to add others":"Comment or type @ to add others","Write a comment...":"Write a comment...","Edit comment composer":"Edit comment composer","Comment or add emails with @":"Comment or add emails with @","Private comment mode - only visible to your team":"Private comment mode - only visible to your team","Only for your team":"Only for your team","Screen recording":"Screen recording",unnamed:"unnamed","Screen recording controls":"Screen recording controls","Edit comment section":"Edit comment section","Add new comment section":"Add new comment section","Custom annotation options":"Custom annotation options","Toggle annotation options":"Toggle annotation options","Annotation:":"Annotation:",Select:"Select","Remaining count:":"Remaining count:","Delete comment controls":"Delete comment controls","Delete this comment":"Delete this comment","Ghost comment notification":"Ghost comment notification","Original content not found.":"Original content not found.","Comment dialog header":"Comment dialog header","Comment dialog header controls":"Comment dialog header controls","Comment metadata":"Comment metadata","1 more reply":"1 more reply","more replies":"more replies","Show 1 more reply":"Show 1 more reply","Navigate to comment location":"Navigate to comment location","Assign comment":"Assign comment","Delete thread":"Delete thread","Delete comment":"Delete comment","Edit comment":"Edit comment",Edit:"Edit","Make it private":"Make it private","Make it public":"Make it public",Subscribe:"Subscribe",Unsubscribe:"Unsubscribe","priority level":"priority level","Priority name":"Priority name",P0:"P0",P1:"P1",P2:"P2","Selected priority:":"Selected priority:","Selected priority indicator":"Selected priority indicator","Priority:":"Priority:","Priority item":"Priority item","Thread priority:":"Thread priority:","Private comment banner":"Private comment banner","Resolve thread":"Resolve thread","Sign In":"Sign In","Status dropdown for":"Status dropdown for",comment:"comment","Status name:":"Status name:","Status option:":"Status option:","Status:":"Status:","Accept suggestion":"Accept suggestion",Accept:"Accept","Reject suggestion":"Reject suggestion",Reject:"Reject","Suggestion actions":"Suggestion actions","Delete Attachment":"Delete Attachment","Download Attachment":"Download Attachment",Attachment:"Attachment",preview:"preview","Image attachment controls":"Image attachment controls","Image attachment actions":"Image attachment actions","Delete attachment":"Delete attachment","Download attachment":"Download attachment","File name:":"File name:","Attachment:":"Attachment:",Attachments:"Attachments","Avatar for":"Avatar for",user:"user","Draft comment status":"Draft comment status",Draft:"Draft",Comment:"Comment","Comment by":"Comment by",Me:"Me","Comment reactions":"Comment reactions","Comment recordings":"Comment recordings","Name for":"Name for","Time for":"Time for","Seen by":"Seen by","Users who viewed this comment":"Users who viewed this comment","List of users who have seen this comment":"List of users who have seen this comment","Seen By":"Seen By","Comment viewers list":"Comment viewers list","Show comment viewers":"Show comment viewers","Comment viewers dropdown":"Comment viewers dropdown",now:"now",Unread:"Unread","Comment thread":"Comment thread","Comment content":"Comment content","Author information":"Author information","Author details and status":"Author details and status","Comment device information":"Comment device information","Inline mode metadata":"Inline mode metadata","Comment actions":"Comment actions","Reaction options":"Reaction options","Comment message":"Comment message",of:"of","Show more replies":"Show more replies",replies:"replies",Reply:"Reply",reply:"reply",Show:"Show","Show reply":"Show reply","Unresolve comment":"Unresolve comment","Upgrade plan":"Upgrade plan",Upgrade:"Upgrade","Copy link to comment":"Copy link to comment","Link Copied!":"Link Copied!","Copy thread link":"Copy thread link","Emoji reactions menu":"Emoji reactions menu","Open emoji reactions menu":"Open emoji reactions menu",Priority:"Priority","Private Comment":"Private Comment",Resolve:"Resolve",Unresolve:"Unresolve","Comment bubble":"Comment bubble","Multi-thread comment dialog":"Multi-thread comment dialog","Comment dialog":"Comment dialog","Comment bottom sheet":"Comment bottom sheet","Comment inbox container":"Comment inbox container","Single comment dialog":"Single comment dialog","Ghost comment indicator":"Ghost comment indicator","Private comment":"Private comment","Comment icon":"Comment icon","Exit comment mode":"Exit comment mode","to exit":"to exit",exit:"exit","Private Comment Mode":"Private Comment Mode","Comment Mode":"Comment Mode","Comment mode icon":"Comment mode icon","Comments stream view":"Comments stream view","Comments inbox":"Comments inbox","Comments location overview":"Comments location overview","Comments minimap":"Comments minimap","Go to comments here.":"Go to comments here.","Close comments sidebar":"Close comments sidebar","Add your first comment":"Add your first comment","No comments to display":"No comments to display","filter section":"filter section",All:"All","Close filter panel":"Close filter panel","Apply filters and close panel":"Apply filters and close panel",Done:"Done","checkbox checked":"checkbox checked","checkbox unchecked":"checkbox unchecked",items:"items","Current viewing page":"Current viewing page","This page":"This page",selected:"selected","not selected":"not selected",pages:"pages",people:"people",priorities:"priorities",statuses:"statuses",Filters:"Filters",versions:"versions","View All":"View All","View all":"View all","Comment filters":"Comment filters","Available filters":"Available filters","Apply or cancel filters":"Apply or cancel filters","Filter comments":"Filter comments","filters applied":"filters applied","Return to all comments":"Return to all comments","Back to all comments":"Back to all comments","Search through comments":"Search through comments","Filter and status controls":"Filter and status controls","Unknown user":"Unknown user","Comment dialog for":"Comment dialog for",Collapse:"Collapse",Expand:"Expand","comment group":"comment group",arrow:"arrow","Comments list with":"Comments list with","Location filter options":"Location filter options",Pages:"Pages","Filter comments by location":"Filter comments by location","menu expanded":"menu expanded","menu collapsed":"menu collapsed","Location filter dropdown":"Location filter dropdown","Mark all comments as read":"Mark all comments as read","Mark all as read":"Mark all as read","Mark all comments as resolved":"Mark all comments as resolved","Mark all as resolved":"Mark all as resolved","Bulk actions for comments":"Bulk actions for comments","Actions menu":"Actions menu",expanded:"expanded",collapsed:"collapsed","Comment actions dropdown":"Comment actions dropdown","Show unread and read comments":"Show unread and read comments","Unread and read":"Unread and read","Show read comments only":"Show read comments only","Read only":"Read only","Show resolved comments only":"Show resolved comments only",Resolved:"Resolved","Show unread comments only":"Show unread comments only","Unread only":"Unread only","Selected indicator":"Selected indicator","Sort comments by date":"Sort comments by date","Sort by date":"Sort by date","Sort comments by unread status":"Sort comments by unread status","Sort by unread":"Sort by unread","Sort and filter comments":"Sort and filter comments","custom filter applied":"custom filter applied","Comment filters and sorting":"Comment filters and sorting",filtered:"filtered","Page comment composer":"Page comment composer","Add a comment to the page":"Add a comment to the page","Comments and feedback panel":"Comments and feedback panel","Reset all comment filters":"Reset all comment filters","Clear filters":"Clear filters","Loading comments":"Loading comments","Comment status filters":"Comment status filters",status:"status","status icon":"status icon","Status filter options":"Status filter options","Status filter dropdown":"Status filter dropdown","Comments sidebar":"Comments sidebar","Comments panel":"Comments panel","Comment composer":"Comment composer","Comments section panel":"Comments section panel",Comments:"Comments","Loading Comments":"Loading Comments","Comments section":"Comments section","No comments found for applied filters.":"No comments found for applied filters.","Comments list":"Comments list","Comment actions menu":"Comment actions menu","More actions":"More actions","Filter and sort options":"Filter and sort options","Collapse threads":"Collapse threads","Comments dialog":"Comments dialog","Clear all filters":"Clear all filters","Comments information":"Comments information","Toggle comments sidebar":"Toggle comments sidebar","Click to mute":"Click to mute","Click to unmute":"Click to unmute","Stop sharing":"Stop sharing","Share screen":"Share screen","Invite users to join this huddle":"Invite users to join this huddle","Please select a contact to invite":"Please select a contact to invite","Chat with everyone":"Chat with everyone","Enable audio or video to change the settings":"Enable audio or video to change the settings","Change audio/video settings":"Change audio/video settings",Leave:"Leave","In-call messages":"In-call messages","Type here...":"Type here...","Audio Huddle":"Audio Huddle","Video Huddle":"Video Huddle","Screen Huddle":"Screen Huddle","1 person is":"1 person is","people are":"people are","on a call now":"on a call now","You can join the call":"You can join the call","Stop Sharing":"Stop Sharing","is sharing now.":"is sharing now.",You:"You","Close notifications panel":"Close notifications panel","Notification item":"Notification item","All notifications list":"All notifications list","All notifications":"All notifications","All notifications read":"All notifications read","Document notification":"Document notification","Document name:":"Document name:",Untitled:"Untitled","Document ID:":"Document ID:",Document:"Document","unread notifications":"unread notifications","Document notifications panel":"Document notifications panel","For you notifications panel":"For you notifications panel","Notification message:":"Notification message:","Notification headline:":"Notification headline:","Notification time:":"Notification time:","Unread notification":"Unread notification",Notification:"Notification",unread:"unread",read:"read",Load:"Load","more notifications":"more notifications","Load More":"Load More","User notifications for":"User notifications for",notification:"notification",notifications:"notifications",available:"available",Notifications:"Notifications","User:":"User:","People notifications panel":"People notifications panel",Documents:"Documents","For You":"For You",People:"People","Notification categories":"Notification categories","Mark all notifications as read":"Mark all notifications as read","Notification actions":"Notification actions","View all notifications":"View all notifications","Notifications panel":"Notifications panel","Notifications bell icon - no unread notifications":"Notifications bell icon - no unread notifications","Notifications count":"Notifications count","Notification bell with":"Notification bell with","User online":"User online","mins ago.":"mins ago.","Reaction count":"Reaction count","Reaction with":"Reaction with","Reaction by":"Reaction by","Users who reacted":"Users who reacted","Reaction details":"Reaction details","React with":"React with",emoji:"emoji","Choose a reaction":"Choose a reaction","Available reactions":"Available reactions","Add reaction":"Add reaction","Reaction selector":"Reaction selector","Start audio recording":"Start audio recording","Audio Recording":"Audio Recording","Screen Recording":"Screen Recording","Start video recording":"Start video recording","Video Recording":"Video Recording","Recording options menu":"Recording options menu","Available recording types":"Available recording types",Record:"Record","Record audio":"Record audio","Record screen":"Record screen","Record video":"Record video","Recording controls for":"Recording controls for",recording:"recording","Stop recording":"Stop recording","Recording duration":"Recording duration","Resume recording":"Resume recording","Pause recording":"Pause recording","Currently recording:":"Currently recording:",none:"none","Audio waveform visualization":"Audio waveform visualization","Currently recording":"Currently recording","Recording paused":"Recording paused","Recording information":"Recording information","Recording controls":"Recording controls","Expand recording panel":"Expand recording panel","Collapse recording panel":"Collapse recording panel","Floating mode container for":"Floating mode container for","Screen recording preview":"Screen recording preview","Expanded view":"Expanded view","Mini preview":"Mini preview","Recording control panel":"Recording control panel","Draggable recording panel":"Draggable recording panel","Currently saving recording":"Currently saving recording","Saving Recording...":"Saving Recording...",Paused:"Paused","Video preview":"Video preview","Screen recording panel":"Screen recording panel","Draggable recording controls":"Draggable recording controls","Video recording preview":"Video recording preview","recording player":"recording player",Draggable:"Draggable",player:"player","recording pin":"recording pin","Created by":"Created by",Play:"Play","Draggable recording pin by":"Draggable recording pin by","Recording player":"Recording player","Audio recording":"Audio recording","Audio player":"Audio player","Audio player controls":"Audio player controls","Audio content and controls":"Audio content and controls","Playback controls":"Playback controls","Playback time":"Playback time","Audio waveform":"Audio waveform",Subtitles:"Subtitles","Additional controls and information":"Additional controls and information","Pause button":"Pause button","Pause audio":"Pause audio","Play audio":"Play audio","Audio progress":"Audio progress","Copy link to recording":"Copy link to recording","Delete recording":"Delete recording","Enter full screen mode":"Enter full screen mode","Recording name:":"Recording name:","Untitled recording":"Untitled recording","Recording player controls":"Recording player controls","Pause video":"Pause video","Play video":"Play video","Video subtitles":"Video subtitles","Toggle subtitles":"Toggle subtitles","Seek video playback":"Seek video playback","Video playback controls":"Video playback controls","Video transcription":"Video transcription","Video player":"Video player","Video player container":"Video player container","Video player with controls":"Video player with controls","Video information and controls":"Video information and controls","Video transcription summary":"Video transcription summary","Fullscreen video player":"Fullscreen video player","Expanded video player":"Expanded video player","Getting data ...":"Getting data ...","Get more options":"Get more options","Max 3 rewrites allowed":"Max 3 rewrites allowed",left:"left","Show original text":"Show original text","Select a rewritten text to create a task":"Select a rewritten text to create a task","Create Task":"Create Task","How would you like to change this copy?":"How would you like to change this copy?",Suggestions:"Suggestions","Selected users":"Selected users","additional users":"additional users",Reassign:"Reassign",Remove:"Remove","Please select a contact to assign":"Please select a contact to assign",Summary:"Summary","see more":"see more","see less":"see less","Invite users":"Invite users","No users are added.":"No users are added.",Invited:"Invited","General access":"General access","Copy Link":"Copy Link","Send invite":"Send invite","Go Back":"Go Back","Total Views":"Total Views","Views Today":"Views Today",View:"View",Views:"Views",Today:"Today","Search comments":"Search comments","In Progress":"In Progress",Status:"Status","Not set":"Not set","Comment Type":"Comment Type",Public:"Public",Private:"Private","Group By":"Group By","Assigned to Me":"Assigned to Me","Added by Me":"Added by Me",Other:"Other",Desktop:"Desktop",Mobile:"Mobile",Tablet:"Tablet",Others:"Others","Default - MacBook Pro Microphone (Built-in)":"Default - MacBook Pro Microphone (Built-in)","iPhone Microphone":"iPhone Microphone","MacBook Pro Microphone (Built-in)":"MacBook Pro Microphone (Built-in)","Sorting options":"Sorting options","Created First":"Created First","Created Last":"Created Last","Updated First":"Updated First","Updated Last":"Updated Last"}};var Gs=(()=>{let o=class o{constructor(e){this.loggingService=e,this.currentLanguageSignal=be(navigator.language.split("-")[0]),this.autoTranslationSignal=be(!1),this.translationsMap=new Map,this.translationCache=new Map,this.translationsUpdateSignal=be(0),this.currentLanguage=this.currentLanguageSignal.asReadonly(),this.autoTranslation=this.autoTranslationSignal.asReadonly(),this.translationsVersion=this.translationsUpdateSignal.asReadonly(),this.currentTranslations=zi(()=>{let i=this.currentLanguageSignal(),r=this.translationsUpdateSignal();return this.translationsMap.get(i)||{}}),this.loggingService.log("%c[WB] Calling FUNCTION: constructor","color: green;"),this.setTranslations(wse),pr(()=>{let i=this.currentLanguageSignal();this.translationCache.clear(),this.translationsUpdateSignal.update(r=>r+1)},{allowSignalWrites:!0})}translate(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: translate","color: green;");let i=this.currentLanguageSignal(),r=this.translationsUpdateSignal(),a=`${i}:${e}:${r}`,s=this.translationCache.get(i);if(s?.has(a))return s.get(a)||e;let c=this.currentTranslations()[e];return this.translationCache.has(i)||this.translationCache.set(i,new Map),this.translationCache.get(i)?.set(a,c||e),rv(c)?e:c}catch{return e}}setTranslations(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setTranslations","color: green;");let i=!1;Object.entries(e).forEach(([r,a])=>{if(a&&typeof a=="object"){let s=this.translationsMap.get(r)||{};Object.keys(a).forEach(p=>{s.hasOwnProperty(p)||(i=!0)});let c=I(I({},s),a);this.translationsMap.set(r,c),this.translationCache.delete(r)}}),this.translationsUpdateSignal.update(r=>r+1),i&&setTimeout(()=>{this.translationsUpdateSignal.update(r=>r+1)},0)}catch(i){this.loggingService.catch("Error in setTranslations: ",i)}}setLanguage(e){return ee(this,null,function*(){try{this.loggingService.log("%c[WB] Calling FUNCTION: setLanguage","color: green;"),this.currentLanguageSignal.set(e)}catch(i){this.loggingService.catch("Error in setLanguage: ",i)}})}enableAutoTranslation(){try{this.loggingService.log("%c[WB] Calling FUNCTION: enableAutoTranslation","color: green;"),this.autoTranslationSignal.set(!0)}catch(e){this.loggingService.catch("Error in enableAutoTranslation: ",e)}}disableAutoTranslation(){try{this.loggingService.log("%c[WB] Calling FUNCTION: disableAutoTranslation","color: green;"),this.autoTranslationSignal.set(!1),this.translationCache.clear()}catch(e){this.loggingService.catch("Error in disableAutoTranslation: ",e)}}};o.\u0275fac=function(i){return new(i||o)(J(y))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var me=(()=>{let o=class o{constructor(e,i){this.domService=e,this.translateService=i,this.sanitizedCache=new Map}transform(e){if(e==null)return"";let i=typeof e=="boolean"||typeof e=="number"?String(e):e;try{let r=this.translateService.currentLanguage(),a=this.translateService.translationsVersion(),s=`${r}:${i}:${a}`,c=this.sanitizedCache.get(s);if(c)return c;let p=this.translateService.translate(i),h=this.domService.sanitizeHtml(p);return this.sanitizedCache.set(s,h),this.sanitizedCache.size>1e3&&this.sanitizedCache.clear(),h}catch(r){return console.warn("Translation error:",r),i}}};o.\u0275fac=function(i){return new(i||o)(u(Fe,16),u(Gs,16))},o.\u0275pipe=Ui({name:"translate",type:o,pure:!0,standalone:!1});let n=o;return n})();function p9e(n,o){if(n&1&&(C(0,"span",6),te(1),A(2,"translate"),S()),n&2){let t=l(2).ngIf;d(),dr("",O(2,2,"You are following")," ",t.leaderName,"")}}function g9e(n,o){n&1&&(C(0,"span",6),te(1),A(2,"translate"),S()),n&2&&(d(),$e(O(2,1,"You are leading.")))}function u9e(n,o){if(n&1){let t=q();C(0,"div",2),z("click",function(){k(t);let i=l().ngIf,r=l();return R(i.type==="following"?r.closeOverlay():void 0)}),C(1,"div",3),g(2,p9e,3,4,"span",4)(3,g9e,3,3,"span",4),C(4,"button",5),z("click",function(){k(t);let i=l(2);return R(i.closeOverlay())}),te(5),A(6,"translate"),A(7,"translate"),S()()()}if(n&2){let t=l().ngIf;pe("no-pointer",t.type==="leading"),d(2),m("ngIf",t.type==="following"),d(),m("ngIf",t.type==="leading"),d(2),dr("",O(6,6,"Stop")," ",O(7,8,t.type),"")}}function h9e(n,o){if(n&1&&(f(0),g(1,u9e,8,10,"div",1),v()),n&2){let t=o.ngIf;d(),m("ngIf",t.leaderName!==""||t.type==="leading")}}var h$=(()=>{let o=class o extends nt{closeOverlay(){this.closeOverlayEvent.emit()}constructor(e,i,r){super(i,r),this.loggingService=e,this.elementRef=i,this.themeService=r,this.closeOverlayEvent=new De,this.componentConfigSignal=be({leaderName:"",type:"following"})}ngOnInit(){}setLeaderName(e){try{this.componentConfigSignal.update(i=>(i=T(I({},i),{leaderName:e}),i))}catch(i){this.loggingService.catch("Error in FollowOverlayComponent setLeaderName: ",i)}}getLeaderName(){return this.componentConfigSignal().leaderName}setType(e){try{this.componentConfigSignal.update(i=>(i=T(I({},i),{type:e}),i))}catch(i){this.loggingService.catch("Error in FollowOverlayComponent setType: ",i)}}ngOnDestroy(){try{super.ngOnDestroy()}catch{}}};o.\u0275fac=function(i){return new(i||o)(u(y),u(N),u(Ye))},o.\u0275cmp=M({type:o,selectors:[["snippyly-follow-overlay"]],outputs:{closeOverlayEvent:"closeOverlayEvent"},standalone:!1,features:[V],decls:1,vars:1,consts:[[4,"ngIf"],["data-velt-ignore","","class","follow-overlay-container",3,"no-pointer","click",4,"ngIf"],["data-velt-ignore","",1,"follow-overlay-container",3,"click"],["data-velt-ignore","",1,"follow-dialog"],["data-velt-ignore","","class","follow-text",4,"ngIf"],["data-velt-ignore","",1,"follow-btn",3,"click"],["data-velt-ignore","",1,"follow-text"]],template:function(i,r){i&1&&g(0,h9e,2,1,"ng-container",0),i&2&&m("ngIf",r.componentConfigSignal())},dependencies:[K,me],styles:[`html{--velt-base-rem-unit: 1}*[data-snippyly-element=true],*[data-velt-element=true]{font-family:var(--velt-default-font-family)}velt-wireframe{display:none!important}.follow-overlay-container{position:fixed;top:0;left:0;width:100%;height:100%;background-color:transparent;z-index:var(--velt-follow-mode-overlay-z-index);display:flex;justify-content:center;align-items:flex-end}.follow-overlay-container .follow-dialog{background-color:var(--legacy-velt-follow-overlay-bg-color);color:var(--legacy-velt-follow-overlay-text-color);font-size:12px;display:flex;justify-content:center;align-items:center;gap:calc((1.2rem + 0px) * var(--velt-base-rem-unit));padding:calc((.9rem + 0px) * var(--velt-base-rem-unit)) calc((1.1rem + 0px) * var(--velt-base-rem-unit));border-radius:90px;margin-bottom:calc((2rem + 0px) * var(--velt-base-rem-unit));box-shadow:0 8px 16px -8px #0f0f0f1a;border:1px solid var(--legacy-velt-follow-overlay-border-color)}.follow-overlay-container .follow-dialog .follow-btn{background-color:var(--legacy-velt-follow-overlay-btn-color);padding:8px 12px;border-radius:90px;display:inline-flex;justify-content:center;align-items:center;border:none;font-weight:600;font-size:14px;cursor:pointer;pointer-events:all}.follow-overlay-container .follow-dialog .follow-btn:hover{transition:background-color .5s;background-color:var(--legacy-velt-follow-overlay-btn-hover-color)}.follow-overlay-container.no-pointer{pointer-events:none}
|
|
383
|
-
`],encapsulation:3,changeDetection:0});let n=o;return n})();var Dse=(()=>{let o=class o{constructor(e,i,r,a){this.componentFactoryResolver=e,this.applicationRef=i,this.injector=r,this.loggingService=a,this.darkMode=!1}createFollowOverlay(e,i){try{let a=this.componentFactoryResolver.resolveComponentFactory(h$).create(this.injector);a.instance.setLeaderName(e),a.instance.closeOverlayEvent.pipe(Je(1)).subscribe(()=>{this.removeOverlay(),i()}),this.applicationRef.attachView(a.hostView),this.overlayRef=a,this.overlayRef.instance.darkMode=this.darkMode;let s=this.overlayRef.location.nativeElement;s.id="snippyly-follow-overlay",s.setAttribute(U.ATTRIBUTES.VELT_IGNORE,""),document.body.appendChild(s)}catch(r){this.loggingService.catch("Error in FlockOverlayService createFollowOverlay: ",r)}}createLeaderOverlay(e){let r=this.componentFactoryResolver.resolveComponentFactory(h$).create(this.injector);r.instance.setType("leading"),r.instance.closeOverlayEvent.pipe(Je(1)).subscribe(()=>{this.removeOverlay(),e()}),this.applicationRef.attachView(r.hostView),this.overlayRef=r,this.overlayRef.instance.darkMode=this.darkMode;let a=this.overlayRef.location.nativeElement;a.id="snippyly-follow-overlay",a.setAttribute(U.ATTRIBUTES.VELT_IGNORE,""),document.body.appendChild(a)}changeLeaderName(e){this.overlayRef&&this.overlayRef.instance.setLeaderName(e)}getLeaderName(){return this.overlayRef?this.overlayRef.instance.getLeaderName():null}removeOverlay(){if(this.overlayRef){let e=this.overlayRef.location.nativeElement;this.applicationRef.detachView(this.overlayRef.hostView),this.overlayRef.destroy(),e.shadowRoot&&e.shadowRoot.removeChild(e.shadowRoot.childNodes[0]),e.remove(),this.overlayRef=void 0}}setDarkMode(e){try{this.darkMode=e,this.overlayRef&&(this.overlayRef.instance.darkMode=e)}catch(i){this.loggingService.catch("Error in FlockOverlayService setDarkMode: ",i)}}};o.\u0275fac=function(i){return new(i||o)(J(Io),J(mi),J(Et),J(y))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var vc=(()=>{let o=class o{constructor(e,i,r,a,s){this.authService=e,this.domService=i,this.loggingService=r,this.flockSessionService=a,this.flockOverlayService=s,this.flockLeader$=new fe({userId:"",name:""}),this.flockMode$=new fe(!1),this.currentFlockUser=null,this.localScrollData=[],this.domSubscriptions=[],this.followOverlayCreated=!1,this.leaderOverlayCreated=!1,this.windowFocused=!0,this.tabFocused=!0,this.useHistoryAPI=!0,this.disableDefaultNavigation=!1;try{this.flockLeader$.subscribe(c=>{let{userId:p,name:h}=c,_=p;if(this.provisionFollowUser(),_&&this.currentFlockUser&&this.currentFlockUser.snippylyId)if(this.currentFlockUser.sessionId){if(this.currentFlockUser.snippylyId&&this.currentFlockUser.isLeader){this.flockSessionService.swapLeader(this.currentFlockUser.snippylyId,_,h);return}this.removeCurrentUserFromSession()}else this.flockSessionService.provisionFlockSession(_,h,this.currentFlockUser.snippylyId)},c=>{this.loggingService.catch("Error in FlockService flockLeader$ subscription: ",c)}),this.flockSessionService.currentSession$.subscribe(c=>{if(c!==null){if(this.currentFlockUser&&(this.currentFlockUser.sessionId===null||this.currentFlockUser.sessionId===void 0)&&this.currentFlockUser.snippylyId&&(this.currentFlockUser.sessionId=c.id,this.flockSessionService.updateRemoteFlockUser(this.currentFlockUser.snippylyId,this.currentFlockUser)),this.currentFlockUser&&!this.currentFlockUser.isLeader&&!this.followOverlayCreated&&(this.leaderOverlayCreated&&(this.flockOverlayService.removeOverlay(),this.leaderOverlayCreated=!1),this.followOverlayCreated=!0,this.flockOverlayService.createFollowOverlay(c.leaderName,()=>{this.removeCurrentUserFromSession(),this.followOverlayCreated=!1})),this.currentFlockUser&&this.currentFlockUser.isLeader&&!this.leaderOverlayCreated&&(this.followOverlayCreated&&(this.flockOverlayService.removeOverlay(),this.followOverlayCreated=!1),this.leaderOverlayCreated=!0,this.flockOverlayService.createLeaderOverlay(()=>{this.removeCurrentUserFromSession(),this.leaderOverlayCreated=!1})),this.currentFlockUser&&!this.currentFlockUser.isLeader&&c.actionStack){let p=c.actionStack[0];p&&this.currentFlockUser.lastProcessedActionTimestamp!==p.timestamp&&this.processAction(p)}if(this.currentFlockUser&&!this.currentFlockUser.isLeader&&this.followOverlayCreated&&this.flockOverlayService.getLeaderName()!==null&&c.leaderName!==this.flockOverlayService.getLeaderName()&&this.flockOverlayService.changeLeaderName(c.leaderName),this.currentFlockUser&&this.currentFlockUser.isLeader){let p=_i();if(c.pageInfo){if(p&&p.url!==c.pageInfo.url){let h=new Td;h.type=Xa.NAVIGATE,this.flockSessionService.addActionToStack(c.id,h)}}else{this.flockSessionService.updateSession(c.id,{pageInfo:p});let h=new Td;h.type=Xa.NAVIGATE,this.flockSessionService.addActionToStack(c.id,h)}}}else this.currentFlockUser&&this.leaderOverlayCreated&&(this.flockOverlayService.removeOverlay(),this.leaderOverlayCreated=!1),this.currentFlockUser&&this.followOverlayCreated&&(this.flockOverlayService.removeOverlay(),this.followOverlayCreated=!1)}),this.flockSessionService.currentUser$.subscribe(c=>{if(c!==null&&(this.currentFlockUser&&this.currentFlockUser.isLeader!==c.isLeader&&(this.domSubscriptions.forEach(p=>p.unsubscribe()),this.domSubscriptions=[]),this.currentFlockUser=c,c.sessionId&&this.domSubscriptions.length===0))if(c.isLeader){if(!this.tabFocused||!this.windowFocused)return;this.subscribeToLeaderDOMEvents()}else this.subscribeToFollowerDOMEvents()}),Dn([this.authService.getUser$(),this.getFlockMode$()]).subscribe(([c,p])=>{c&&c.userSnippylyId&&p?this.flockSessionService.startCurrentFlockUserSubscription(c):this.flockSessionService.stopCurrentFlockUserSubscription()})}catch(c){this.loggingService.catch("Error in FlockService constructor: ",c)}}provisionFollowUser(){try{if(this.currentFlockUser===null){let e=this.authService.getUser();e&&e.userSnippylyId&&(this.currentFlockUser=new UM,this.currentFlockUser.snippylyId=e.userSnippylyId)}}catch(e){this.loggingService.catch("Error in FlockService provisionFollowUser: ",e)}}startFollowingUser(e,i){try{if(this.provisionFollowUser(),e&&this.currentFlockUser&&this.currentFlockUser.snippylyId){if(this.currentFlockUser.sessionId){if(this.currentFlockUser.snippylyId&&this.currentFlockUser.isLeader){this.flockSessionService.swapLeader(this.currentFlockUser.snippylyId,e,i);return}this.removeCurrentUserFromSession()}this.flockSessionService.provisionFlockSession(e,i,this.currentFlockUser.snippylyId)}}catch(r){this.loggingService.catch("Error in FlockService startFollowingUser: ",r)}}stopFollowingUser(){try{this.removeCurrentUserFromSession()}catch(e){this.loggingService.catch("Error in FlockService stopFollowingUser: ",e)}}subscribeToUrlChanges(){try{if(this.useHistoryAPI){let e=window.history.pushState,i=window.history.replaceState;window.history.pushState=(...r)=>{e.apply(window.history,r),this.onUrlChange()},window.history.replaceState=(...r)=>{i.apply(window.history,r),this.onUrlChange()},this.domSubscriptions.push({unsubscribe:()=>{window.history.pushState=e,window.history.replaceState=i}}),this.domSubscriptions.push(oi(window,"popstate").subscribe(()=>{this.onUrlChange()}))}}catch(e){this.loggingService.catch("Error in FlockService subscribeToUrlChanges: ",e)}}onUrlChange(){try{if(this.currentFlockUser&&this.currentFlockUser.sessionId&&this.currentFlockUser.isLeader){let e=new Td;e.type=Xa.NAVIGATE,this.flockSessionService.addActionToStack(this.currentFlockUser.sessionId,e)}}catch(e){this.loggingService.catch("Error in FlockService onUrlChange: ",e)}}processAction(e){try{switch(e.type){case Xa.CLICK:this.clickUserElement(e.data);break;case Xa.HOVER:this.scrollToHoveredElement(e.data);break;case Xa.SCROLL:this.scrollToFollowedUser(e.data);break;case Xa.NAVIGATE:this.checkMatchingUrl(e.pageInfo);break}this.currentFlockUser&&this.currentFlockUser.snippylyId&&this.flockSessionService.updateRemoteFlockUser(this.currentFlockUser.snippylyId,{lastProcessedActionTimestamp:e.timestamp})}catch(i){this.loggingService.catch("Error in FlockService processAction: ",i)}}subscribeToLeaderDOMEvents(){try{this.domSubscriptions.length>0&&(this.domSubscriptions.forEach(e=>e.unsubscribe()),this.domSubscriptions=[]),this.domSubscriptions.push(oi(window,"mouseover").pipe(jr(500)).subscribe(e=>{let i=e?.target;if(i){let r=window.getComputedStyle(i);if(r.position==="fixed"||r.position==="sticky"||i.hasAttribute(U.ATTRIBUTES.VELT_IGNORE))return;i=SV(i,{x:e.clientX,y:e.clientY}),this.updateHoveredElement(i)}})),this.domSubscriptions.push(this.domService.onWindowClick$().subscribe(e=>{let i=e?.target;if(i){if(i.hasAttribute(U.ATTRIBUTES.VELT_IGNORE))return;this.updateClickedElement(i)}})),this.subscribeToUrlChanges(),this.subscribeToScrollables()}catch(e){this.loggingService.catch("Error in FlockService subscribeToLeaderDOMEvents: ",e)}}subscribeToFollowerDOMEvents(){}updateClickedElement(e){try{if(this.currentFlockUser&&this.currentFlockUser.sessionId){let i=this.domService.getXPath(e),r=iv(e),a=this.domService.getXPath(r),s={id:Math.random().toString(36).substring(2),xpath:i,parentXpath:a},c=new Td;c.type=Xa.CLICK,c.data=s,this.flockSessionService.addActionToStack(this.currentFlockUser.sessionId,c)}}catch(i){this.loggingService.catch("Error in FlockService updateClickedElement: ",i)}}updateHoveredElement(e){try{if(this.currentFlockUser&&this.currentFlockUser.sessionId){let i=this.domService.getXPath(e),r=iv(e),a=this.domService.getXPath(r),s={id:Math.random().toString(36).substring(2),xpath:i,parentXpath:a},c=new Td;c.type=Xa.HOVER,c.data=s,this.flockSessionService.addActionToStack(this.currentFlockUser.sessionId,c)}}catch(i){this.loggingService.catch("Error in FlockService updateHoveredElement: ",i)}}subscribeToScrollables(){try{let e=Wie();e.push(document),e?.forEach(i=>{this.domSubscriptions.push(oi(i,"scroll").pipe(jr(100)).subscribe(r=>{this.currentFlockUser&&this.currentFlockUser.sessionId&&this.currentFlockUser.isLeader&&this.updateScrollPositionOfElement(i)}))})}catch(e){this.loggingService.catch("Error in FlockService getScrollableElements: ",e)}}updateScrollPositionOfElement(e){try{if(this.currentFlockUser&&this.currentFlockUser.sessionId){let i=new VM("","");if(e===document){let s=Kie();if(s){let c=SV(s);c&&(i.targetXpath=this.domService.getXPath(c))}i.xpath=""}else{let s=Yie(e);i.targetXpath=this.domService.getXPath(s),i.xpath=this.domService.getXPath(e)}let r=!1,a=!1;if(this.localScrollData.forEach((s,c)=>{s.xpath===s.xpath&&(i.targetXpath!==s.targetXpath&&(r=!0),this.localScrollData[c]=Object.assign(s,i),a=!0)}),a||this.localScrollData.push(i),r||!a){let s=new Td;s.type=Xa.SCROLL,s.data=i,this.flockSessionService.addActionToStack(this.currentFlockUser.sessionId,s)}}}catch(i){this.loggingService.catch("Error in FlockService calculateScrollPositionOfAnElement: ",i)}}enableFlockMode(e){try{if(this.flockMode$.next(!0),e){let{useHistoryAPI:i,onNavigate:r,disableDefaultNavigation:a,darkMode:s}=e;i!==void 0&&(this.useHistoryAPI=i),r!==void 0&&typeof r=="function"&&(this.onNavigate=r),a!==void 0&&(this.disableDefaultNavigation=a),this.flockOverlayService.setDarkMode(s)}}catch(i){this.loggingService.catch("Error in FlockService enableFlockMode: ",i)}}disableFlockMode(){try{this.flockMode$.next(!1),this.onNavigateEmitter=void 0,this.useHistoryAPI=!0,this.onNavigate=void 0}catch(e){this.loggingService.catch("Error in FlockService disableFlockMode: ",e)}}setDisableFlockNavigation(e){try{this.disableDefaultNavigation=e}catch(i){this.loggingService.catch("Error in FlockService setDisableFlockNavigation: ",i)}}getFlockMode$(){return this.flockMode$.asObservable()}getFlockMode(){return this.flockMode$.value}setNavigateEmitter(e){try{this.onNavigateEmitter=e}catch(i){this.loggingService.catch("Error in FlockService setNavigateEmitter: ",i)}}setTabFocused(e){try{if(this.tabFocused=e,!this.currentFlockUser)return;this.currentFlockUser.isLeader&&this.currentFlockUser.sessionId&&(this.tabFocused&&this.domSubscriptions.length===0?this.subscribeToLeaderDOMEvents():!this.tabFocused&&this.domSubscriptions.length>0&&(this.domSubscriptions.forEach(r=>{r.unsubscribe()}),this.domSubscriptions=[]))}catch(i){this.loggingService.catch("Error in FlockService setTabFocused: ",i)}}setWindowFocused(e){try{if(this.windowFocused=e,!this.currentFlockUser)return;this.currentFlockUser.isLeader&&this.currentFlockUser.sessionId&&(this.windowFocused&&this.domSubscriptions.length===0?this.subscribeToLeaderDOMEvents():!this.windowFocused&&this.domSubscriptions.length>0&&(this.domSubscriptions.forEach(r=>{r.unsubscribe()}),this.domSubscriptions=[]))}catch(i){this.loggingService.catch("Error in FlockService setWindowFocused: ",i)}}setFlockLeader(e,i){try{this.flockLeader$.next({userId:e,name:i})}catch(r){this.loggingService.catch("Error in FlockService setFlockLeader: ",r)}}isInSession(){try{return!!(this.currentFlockUser&&this.currentFlockUser.sessionId)}catch(e){this.loggingService.catch("Error in FlockService isFollowing: ",e)}return!1}removeCurrentUserFromSession(){try{this.domSubscriptions.forEach(e=>e.unsubscribe()),this.domSubscriptions=[],this.currentFlockUser&&(this.currentFlockUser.isLeader?this.currentFlockUser.sessionId&&this.flockSessionService.deleteSession(this.currentFlockUser.sessionId):this.currentFlockUser.snippylyId&&this.flockSessionService.removeFollowerFromCurrentSession(this.currentFlockUser.snippylyId))}catch(e){this.loggingService.catch("Error in FlockService removeCurrentUserFromSession: ",e)}}checkMatchingUrl(e){try{let r=_i()?.url,a=e.url;if(r!==a&&a!==void 0){let{url:s,path:c,baseUrl:p}=e;if(this.onNavigate!==void 0&&typeof this.onNavigate=="function"){this.onNavigate({url:s,path:c,baseUrl:p});return}if(this.onNavigateEmitter&&this.onNavigateEmitter.emit({url:s,path:c,baseUrl:p}),this.disableDefaultNavigation)return;window.location.href=a}}catch(i){this.loggingService.catch("Error in FlockService checkMatchingUrl: ",i)}}scrollToFollowedUser(e){try{if(e.xpath===""){let i=this.domService.getElementFromXPath(e.targetXpath);i&&XO(i)}else{let i=this.domService.getElementFromXPath(e.xpath),r=this.domService.getElementFromXPath(e.targetXpath);i&&r&&(XO(i),bV(i,r))}}catch(i){this.loggingService.catch("Error in FlockService scrollToFollowedUser: ",i)}}clickUserElement(e){try{let i=this.domService.getElementFromXPath(e.xpath);i&&this.lastClickedElement?.id!==e.id&&(i?.click(),this.lastClickedElement=e)}catch(i){this.loggingService.catch("Error in FlockService clickUserElement: ",i)}}scrollToHoveredElement(e){try{let i=this.domService.getElementFromXPath(e.xpath);if(i&&e.parentXpath)if(e.parentXpath==="/html")XO(i);else{let r=this.domService.getElementFromXPath(e.parentXpath);r&&bV(r,i,!0)}}catch(i){this.loggingService.catch("Error in FlockService clickUserElement: ",i)}}};o.\u0275fac=function(i){return new(i||o)(J(je),J(Fe),J(y),J(Tse),J(Dse))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Di=(()=>{let o=class o{constructor(e,i,r,a,s,c,p,h,_,E){this.afAuth=e,this.analyticsService=i,this.authService=r,this.configService=a,this.databaseService=s,this.docService=c,this.domService=p,this.iamService=h,this.loggingService=_,this.commonDbService=E,this.db=Ci(),this.liveStateDataMap$=new fe({}),this.liveStateDataMapDraft={},this.singleEditorMode$=new fe(!1),this.singleEditorModeConfig$=new fe(null),this.singleEditorLiveStateData$=new fe(null),this.singleEditorLiveStateData={},this.editorAccessTimeout$=new fe(U.LIVE_STATE_REQUEST_EDITOR_ACCESS_WAIT_TIME),this.editorAccessTransferOnTimeOut$=new fe(!0),this.defaultSingleEditorUIEnabled$=new fe(!0),this.editorAccessTimer$=new fe(new Lv),this.autoSyncState$=new fe(!1),this.serverConnectionState$=new fe(ul.PENDING_INIT),this.user=null,this.keydownSubscription=null,this.isEditor$=new fe(null),this.preventEventsOnElementMap={},this.PREVENT_EVENTS=["click","mouseup","mousedown"],this.autoSyncStateHistory=null,this.singleEditorModeContainerIds$=new fe([]),this.inputChangeSubscriptionMap={},this.childListMutationSubscription=null,this.tabId=this.domService.getTabId();try{this.loggingService.log("%c[WB] Creating CLASS: LiveStateService","color: blue;"),this.databaseService.getDb().pipe(Ne(D=>!!D),Je(1)).subscribe(D=>{D&&(this.db=D,this.getUser(),this.getDocumentPaths(),this.subscribeLiveStateData().subscribe(),this.singleEditorMode$.subscribe(B=>{B&&this.detectKeydownOnInput()}),this.autoSyncState$.subscribe(B=>{B?(this.detectLiveSyncInputs(),this.observeElementAddedOnDom()):(this.unsubscribeInputChanges(),this.childListMutationSubscription?.unsubscribe(),this.childListMutationSubscription=null)}),this.updateOnDatabaseDisconnect().subscribe(()=>{},B=>{this.loggingService.catch("Error in LiveStateService constructor updateOnDatabaseDisconnect: ",B)}),this.updateServerStateOnDatabaseDisconnect().subscribe(()=>{},B=>{this.loggingService.catch("Error in LiveStateService constructor updateServerStateOnDatabaseDisconnect: ",B)}))},D=>{this.loggingService.catch("Error in LiveStateService getDb subscription: ",D)}),this.liveStateDataMap$.pipe(Ne(D=>!!D?.default?.autoSyncState),ce(D=>D.default?.autoSyncState),Kt((D,B)=>JSON.stringify(D||{})===JSON.stringify(B||{}))).subscribe(D=>{D&&(this.getAutoSyncState()&&(!this.autoSyncStateHistory&&D?.history&&this.updateLiveStateSyncInputDataLocally(D.history),D?.current&&this.updateLiveStateSyncInputDataLocally({[D.current.liveStateDataId]:D.current})),!this.autoSyncStateHistory&&D?.history&&(this.autoSyncStateHistory=D.history))}),this.docService.addPreDocumentIdChangeFunction("live-state-service",D=>this.isUserEditor()?.isEditor&&(!this.getSingleEditorModeConfig()?.singleTabEditor||this.isUserEditor()?.isEditorOnCurrentTab)?this.removeEditorAccess():Promise.resolve())}catch(D){this.loggingService.catch("Error in LiveStateService constructor: ",D)}}observeElementAddedOnDom(){try{this.loggingService.log("%c[WB] Calling FUNCTION: observeElementAddedOnDom","color: green;"),this.childListMutationSubscription&&(this.childListMutationSubscription.unsubscribe(),this.childListMutationSubscription=null),this.childListMutationSubscription=this.domService.getChildListMutation$().subscribe(e=>{e?.length&&e.forEach(i=>{let r=Array.from(i.addedNodes||[]).filter(a=>a instanceof HTMLElement);r?.forEach(a=>{xV(a,!0)?.forEach(p=>{typeof p?.getAttribute=="function"&&p?.getAttribute(U.ATTRIBUTES.VELT_SYNC_STATE)&&this.subscribeInputChanges(p)})}),r?.length&&this.isEditor$?.value?.isEditor===!1&&(this.disableInputElements(),this.disableElementEvents())})},e=>{this.loggingService.catch("Error in LiveStateService domService getChildListMutation$ subscription: ",e)})}catch(e){this.loggingService.catch("Error in LiveStateService observeElementAddedOnDom: ",e)}}detectKeydownOnInput(){try{this.loggingService.log("%c[WB] Calling FUNCTION: detectKeydownOnInput","color: green;"),this.unsubscribeKeydownSubscription(),this.keydownSubscription=this.domService.onWindowKeydown$().pipe(Ne(e=>e?.target instanceof HTMLInputElement||e?.target instanceof HTMLTextAreaElement||e?.target instanceof HTMLSelectElement),Ne(e=>!!this.isElementInsideSingleEditorModeContainerElements(e?.target)),Je(1)).subscribe(e=>{this.unsubscribeKeydownSubscription(),this.getSingleEditorModeConfig()?.customMode||this.setUserAsEditor()},e=>{this.loggingService.catch("Error in LiveStateService detectKeydownOnInput subscription: ",e)})}catch(e){this.loggingService.catch("Error in LiveStateService detectKeydownOnInput: ",e)}}unsubscribeKeydownSubscription(){try{this.loggingService.log("%c[WB] Calling FUNCTION: unsubscribeKeydownSubscription","color: green;"),this.keydownSubscription&&(this.keydownSubscription.unsubscribe(),this.keydownSubscription=null)}catch(e){this.loggingService.catch("Error in LiveStateService unsubscribeKeydownSubscription: ",e)}}getDocumentPaths(){try{this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentPaths","color: green;"),this.docService.getDocumentPaths$().subscribe(e=>{this.documentPaths=e,this.updateLiveStateDataFromDraft()})}catch(e){this.loggingService.catch("Error in LiveStateService getDocumentPaths: ",e)}}getUser(){try{this.loggingService.log("%c[WB] Calling FUNCTION: getUser","color: green;"),this.authService.getUser$().subscribe(e=>{this.user=e,this.updateLiveStateDataFromDraft()})}catch(e){this.loggingService.catch("Error in LiveStateService getUser: ",e)}}updateLiveStateDataFromDraft(){try{this.loggingService.log("%c[WB] Calling FUNCTION: updateLiveStateDataFromDraft","color: green;"),this.liveStateDataMapDraft?.custom&&this.user&&this.documentPaths&&(Object.keys(this.liveStateDataMapDraft.custom).forEach(e=>{this.setLiveStateData(e,this.liveStateDataMapDraft.custom[e])}),this.liveStateDataMapDraft={})}catch(e){this.loggingService.catch("Error in LiveStateService updateLiveStateDataFromDraft: ",e)}}subscribeLiveStateData(){return this.loggingService.log("%c[WB] Calling FUNCTION: getOnlineUsersOnCurrentDocument","color: green;"),Wn(this.afAuth).pipe(Ne(e=>!!e),ge(e=>this.isFeatureAllowed({firebaseUser:e,liveStateData:{}})),ge(e=>e.featureAllowed?this.iamService.isUserAllowed$().pipe(ce(i=>(e.featureAllowed=i,e))):re(e)),ge(e=>e.featureAllowed?this.authService.isPlanExpired$().pipe(ce(i=>(e.featureAllowed=!i,e))):re(e)),ge(e=>e.featureAllowed?re(e).pipe(ge(i=>this.docService.getDocumentPaths$().pipe(ce(r=>(this.documentPaths=r,i.documentPaths=r,i)))),In(i=>{this.serverConnectionState$?.value===ul.PENDING_INIT&&i?.documentPaths?.liveState&&this.serverConnectionState$.next(ul.PENDING_DATA)}),ge(i=>this.getDataFromDocumentId().pipe(ce(r=>(i.liveStateData=r,I({},i))))),ge(i=>this.getSingleEditorMode$().pipe(ce(()=>i))),ce(i=>{if(this.serverConnectionState$?.value!==ul.ONLINE&&this.serverConnectionState$.next(ul.ONLINE),i.liveStateData)this.liveStateDataMap$.next(i.liveStateData);else{let r=this.liveStateDataMap$.value;r&&Object.keys(r).length>0&&this.liveStateDataMap$.next({})}this.getSingleEditorMode()&&this.updateSingleEditorLiveSyncData(i?.liveStateData?.default?.singleEditorMode||{})})):re({})))}updateSingleEditorLiveSyncData(e){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: updateSingleEditorLiveSyncData","color: green;"),Co(e,{})&&!this.keydownSubscription&&this.detectKeydownOnInput(),e&&!e?.editor&&this.isEditor$?.value!==void 0&&this.isEditor$.next(void 0),Co(this.singleEditorLiveStateData,e))return;if(this.singleEditorLiveStateData=e,this.singleEditorLiveStateData$.next(e),this.singleEditorLiveStateData?.editor){let i=this.authService.getUser();this.singleEditorLiveStateData?.editor?.userId!==i?.userId?this.makeReader():this.makeEditor()}else this.isEditor$?.value!==void 0&&this.isEditor$.next(void 0),this.enableInputElements(),this.enableElementEvents();this.editorAccessTimerInterval&&this.singleEditorLiveStateData?.requestEditorAccess?.status!=="pending"&&this.clearEditorAccessTimerInterval(),this.requestAccessTimer&&this.singleEditorLiveStateData?.requestEditorAccess?.status!=="pending"?this.clearRequestAccessTimer():this.singleEditorLiveStateData?.requestEditorAccess?.status==="pending"&&this.isUserEditor()?.isEditor&&this.isUserEditor()?.isEditorOnCurrentTab&&this.setRequestAccessTimer(this.singleEditorLiveStateData?.requestEditorAccess?.editorAccessTimeout||U.LIVE_STATE_REQUEST_EDITOR_ACCESS_WAIT_TIME)}catch{}}isFeatureAllowed(e){return this.configService.getConfig$().pipe(Ne(i=>!!i),ce(i=>T(I({},e),{config:i})),ge(i=>this.authService.getUser$().pipe(ce(r=>T(I({},i),{user:r})))),ge(i=>Xi(i.config,i.user,Re.LIVE_STATE_SYNC)?re(T(I({},i),{featureAllowed:!0})):(this.loggingService.warn("Live state sync feature is not allowed."),re(T(I({},i),{featureAllowed:!1})))))}getDataFromDocumentId(e){return this.databaseService.getDb().pipe(Ne(i=>!!i),ge(i=>(this.db=i,this.configService?.getApiKey()&&this.documentPaths?.liveState?this.commonDbService.dbListener({feature:"allLiveStates",properties:{documentId:e??this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,skipFirestore:!0}}).pipe(ce(r=>r?.data),Ln(r=>(this.loggingService.catch("Error in LiveStateService getDataFromDocumentId: ",r),re({})))):re({}))))}getLiveStateData$(e,i){try{return this.loggingService.log("%c[WB] Calling FUNCTION: getLiveStateData$","color: green;"),Wn(this.afAuth).pipe(Ne(r=>!!r),ge(r=>this.isFeatureAllowed({firebaseUser:r,liveStateData:{}})),ge(r=>r.featureAllowed?this.iamService.isUserAllowed$().pipe(ce(a=>(r.featureAllowed=a,r))):re(r)),ge(r=>r.featureAllowed?this.authService.isPlanExpired$().pipe(ce(a=>(r.featureAllowed=!a,r))):re(r)),ge(r=>r.featureAllowed?re(r).pipe(ge(a=>this.docService.getDocumentPaths$().pipe(ce(s=>(this.documentPaths=s,a.documentPaths=s,a)))),ge(a=>{let s=i?.listenToNewChangesOnly?1:0;return this.getLiveStateDataFromDatabase$(e).pipe(xs(s))}),ce(a=>{if(a)if(e){let s=Rt(e+""),c=a?.[s];if(c){let p=c?.data;if(c?.tabId&&this.tabId&&c?.tabId===this.tabId)return;if(c?.isDataStringified&&typeof p=="string")try{p=JSON.parse(p)}catch{}return p}else return}else{let s={};return Object.keys(a||{}).forEach(c=>{if(a[c]?.liveStateDataId){let p=a[c],h=p?.data;if(p?.isDataStringified&&typeof h=="string")try{h=JSON.parse(h)}catch{}s[p.liveStateDataId]=h}}),s}return a})):re(void 0).pipe(Ne(Boolean))),Kt((r,a)=>JSON.stringify(r||{})===JSON.stringify(a||{})),Ne(r=>r!==void 0),ce(r=>r))}catch(r){return this.loggingService.catch("Error in LiveStateService getLiveStateData$: ",r),re(null)}}getLiveStateDataFromDatabase$(e){try{return this.databaseService.getDb().pipe(Ne(i=>!!i),ge(i=>{this.db=i;let r=e?Rt(e+""):void 0;return this.configService?.getApiKey()&&this.documentPaths?.liveState?this.commonDbService.dbListener({feature:r?"liveStateCustom":"allLiveStateCustoms",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,id:r,skipFirestore:!0}}).pipe(ce(a=>a?.data),ce(a=>{if(a)return r?{[r]:a}:a}),Ln(a=>(this.loggingService.catch("Error in LiveStateService getLiveStateDataFromDatabase$: ",a),re(null)))):re(void 0)}))}catch(i){return this.loggingService.catch("Error in LiveStateService getLiveStateDataFromDatabase$: ",i),re(void 0)}}setLiveStateData(e,i,r){return ee(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: setLiveStateData","color: green;");try{let a=this.authService.getUser();if(e&&this.documentPaths?.liveState&&a){let s=Rt(e+""),c=!1;try{if(r?.merge&&typeof i=="object"){let h=yield this.commonDbService.getData({feature:"liveStateCustom",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",id:s,skipFirestore:!0}});if(h?.isDataStringified){let _=JSON.parse(h?.data);typeof i=="object"&&(i=I(I({},_),i))}}}catch{}try{typeof i=="object"&&(i=JSON.stringify(i),c=!0)}catch{}let p={id:s,lastUpdated:this.timestamp,liveStateDataId:e,data:i,updatedBy:a,tabId:this.tabId,isDataStringified:c};yield this.commonDbService.setData({feature:"liveStateCustom",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",id:s,skipFirestore:!0},data:JSON.parse(JSON.stringify(p))})}else this.loggingService.warn("liveStateDataId or documentPaths or user is null"),this.liveStateDataMapDraft?.custom||(this.liveStateDataMapDraft.custom={}),e&&(this.liveStateDataMapDraft.custom[e]=i)}catch(a){this.loggingService.catch("Error in LiveStateService _setLiveStateData: ",a)}})}getFormElements(){try{return this.loggingService.log("%c[WB] Calling FUNCTION: getInputElements","color: green;"),document.querySelectorAll("input, textarea, select, button, [contenteditable]")}catch(e){return this.loggingService.catch("Error in LiveStateService getInputElements: ",e),null}}disableInputElements(){try{this.loggingService.log("%c[WB] Calling FUNCTION: disableInputElements","color: green;"),this.getFormElements()?.forEach(i=>{if(this.isElementInsideSingleEditorModeContainerElements(i)&&!this.isSingleEditorModeDisabledForElement(i)&&!ji(i)){let r=i?.hasAttribute("disabled");i?.hasAttribute("contenteditable")&&(r=i?.getAttribute("contenteditable")==="false"),r||(i.setAttribute("disabled","true"),i.setAttribute(U.ATTRIBUTES.VELT_SYNC_ACCESS_AUTO,"true"),i?.hasAttribute("contenteditable")&&i.setAttribute("contenteditable","false"))}})}catch(e){this.loggingService.catch("Error in LiveStateService disableInputElements: ",e)}}enableInputElements(){try{this.loggingService.log("%c[WB] Calling FUNCTION: enableInputElements","color: green;"),this.getFormElements()?.forEach(i=>{i?.hasAttribute(U.ATTRIBUTES.VELT_SYNC_ACCESS_AUTO)&&(i.removeAttribute("disabled"),i.removeAttribute(U.ATTRIBUTES.VELT_SYNC_ACCESS_AUTO),i?.getAttribute("contenteditable")&&i.setAttribute("contenteditable","true"))})}catch(e){this.loggingService.catch("Error in LiveStateService enableInputElements: ",e)}}disableElementEvents(){try{this.loggingService.log("%c[WB] Calling FUNCTION: disableElementEvents","color: green;"),document.querySelectorAll(`[${U.ATTRIBUTES.VELT_SYNC_ACCESS}]`)?.forEach(i=>{let r=this.domService.getXPath(i);r&&!this.preventEventsOnElementMap[r]&&(this.preventEventsOnElementMap[r]={element:i,events:{}},this.PREVENT_EVENTS.forEach(a=>{let s=oi(i,a,{capture:!0}).subscribe(c=>{try{c.preventDefault(),c.stopPropagation()}catch(p){this.loggingService.catch("Error in LiveStateService disableElementEvents subscription: ",p)}});this.preventEventsOnElementMap[r]?.events[a]?.unsubscribe(),this.preventEventsOnElementMap[r].events[a]=s}))})}catch(e){this.loggingService.catch("Error in LiveStateService disableElementClicks: ",e)}}enableElementEvents(){try{this.loggingService.log("%c[WB] Calling FUNCTION: enableElementEvents","color: green;"),Object.keys(this.preventEventsOnElementMap).forEach(e=>{let i=this.preventEventsOnElementMap[e];Object.keys(i.events||{}).forEach(r=>{i?.events[r]?.unsubscribe()})}),this.preventEventsOnElementMap={}}catch(e){this.loggingService.catch("Error in LiveStateService enableElementClicks: ",e)}}setUserAsEditor(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: setUserAsEditor","color: green;"),this.user&&this.documentPaths?.liveStateSingleEditorMode){let e={editor:this.user,tabId:this.tabId,editorAt:this.timestamp};this.commonDbService.setData({feature:"liveStateSingleEditorMode",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",skipFirestore:!0},data:JSON.parse(JSON.stringify(e))}),this.analyticsService.trackEvent(Z.Events.LiveStateSync.SET_USER_AS_EDITOR_TRIGGERED,{editorUserId:this.user?.userSnippylyId,tabId:this.tabId})}}catch(e){this.loggingService.catch("Error in LiveStateService setUserAsEditor: ",e)}}setRequestAccessTimer(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setRequestAccessTimer","color: green;"),this.requestAccessTimer||(this.requestAccessTimer=setTimeout(()=>{this.getEditorAccessTransferOnTimeOut()&&this.acceptEditorAccessRequest(),this.clearRequestAccessTimer()},e*1e3),this.setEditorAccessTimerInterval(e))}catch(i){this.loggingService.catch("Error in LiveStateService setRequestAccessTimer: ",i)}}clearRequestAccessTimer(){try{this.loggingService.log("%c[WB] Calling FUNCTION: clearRequestAccessTimer","color: green;"),this.requestAccessTimer&&(clearTimeout(this.requestAccessTimer),this.requestAccessTimer=null)}catch(e){this.loggingService.catch("Error in LiveStateService clearRequestAccessTimer: ",e)}}requestEditorAccess(){this.loggingService.log("%c[WB] Calling FUNCTION: requestEditorAccess","color: green;");try{return this.analyticsService.trackEvent(Z.Events.LiveStateSync.REQUEST_EDITOR_ACCESS_TRIGGERED),new Ft(e=>{let i=null;try{if(this.user&&this.documentPaths?.liveStateSingleEditorMode){let r=this.getEditorAccessTimeout(),a=on(this.db,`${this.documentPaths?.liveStateSingleEditorMode}`),s={requestEditorAccess:{user:this.user,requestedAt:this.timestamp,status:"pending",editorAccessTimeout:r,tabId:this.tabId}};this.commonDbService.updateData({feature:"liveStateSingleEditorMode",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",skipFirestore:!0},errorCallback:c=>{this.loggingService.catch("Error in LiveStateService requestEditorAccess: ",c),e.next(null),e.complete()},callback:()=>{r&&(this.requestAccessTimer=setTimeout(()=>{this.getEditorAccessTransferOnTimeOut()&&this.setUserAsEditor()},(r+3)*1e3),this.setEditorAccessTimerInterval(r+3)),i=this.getSingleEditorLiveStateData$().subscribe(c=>{c&&(c?.requestEditorAccess?c?.requestEditorAccess?.status==="cancelled"&&(e.next(null),e.complete()):c?.editor?.userId===this.user?.userId?(e.next(!0),e.complete()):(e.next(!1),e.complete()))})},data:JSON.parse(JSON.stringify(s))})}else e.next(!1),e.complete()}catch(r){this.loggingService.catch("Error in LiveStateService requestEditorAccess: ",r),e.next(null),e.complete()}return()=>{i&&i?.unsubscribe()}})}catch(e){return this.loggingService.catch("Error in LiveStateService requestEditorAccess: ",e),re(null)}}makeEditor(){try{this.loggingService.log("%c[WB] Calling FUNCTION: makeEditor","color: green;");let e=this.singleEditorLiveStateData?.tabId===this.tabId;this.isEditor$.next({isEditor:!0,isEditorOnCurrentTab:e}),this.getSingleEditorModeConfig()?.customMode||(!this.getSingleEditorModeConfig()?.singleTabEditor||e?(this.enableInputElements(),this.enableElementEvents()):(this.disableInputElements(),this.disableElementEvents()))}catch(e){this.loggingService.catch("Error in LiveStateService makeEditor: ",e)}}makeReader(){try{this.loggingService.log("%c[WB] Calling FUNCTION: makeReader","color: green;"),this.isEditor$.next({isEditor:!1,isEditorOnCurrentTab:!1}),this.getSingleEditorModeConfig()?.customMode||(this.disableInputElements(),this.disableElementEvents())}catch(e){this.loggingService.catch("Error in makeReader: ",e)}}acceptEditorAccessRequest(){return ee(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: acceptEditorAccessRequest","color: green;"),this.user&&this.singleEditorLiveStateData?.requestEditorAccess&&this.isUserEditor()?.isEditor&&this.documentPaths?.liveStateSingleEditorMode){let e=this.singleEditorLiveStateData?.requestEditorAccess?.user,i=this.singleEditorLiveStateData?.requestEditorAccess?.tabId;if(e&&i){let r={editor:e,requestEditorAccess:null,tabId:i,editorAt:this.timestamp};this.commonDbService.updateData({feature:"liveStateSingleEditorMode",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",skipFirestore:!0},data:JSON.parse(JSON.stringify(r))}),this.analyticsService.trackEvent(Z.Events.LiveStateSync.ACCEPT_EDITOR_ACCESS_REQUEST_TRIGGERED,{editorUserId:e?.userSnippylyId,tabId:i})}}}catch(e){this.loggingService.catch("Error in acceptEditorAccessRequest: ",e)}})}rejectEditorAccessRequest(){return ee(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: rejectEditorAccessRequest","color: green;"),this.user&&this.singleEditorLiveStateData?.requestEditorAccess&&this.isUserEditor()?.isEditor&&this.documentPaths?.liveStateSingleEditorMode){let e={requestEditorAccess:null};this.commonDbService.updateData({feature:"liveStateSingleEditorMode",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",skipFirestore:!0},data:JSON.parse(JSON.stringify(e))}),this.analyticsService.trackEvent(Z.Events.LiveStateSync.REJECT_EDITOR_ACCESS_REQUEST_TRIGGERED)}}catch(e){this.loggingService.catch("Error in LiveStateService rejectEditorAccessRequest: ",e)}})}cancelEditorAccessRequest(){return ee(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: cancelEditorAccessRequest","color: green;"),this.user&&this.singleEditorLiveStateData?.requestEditorAccess&&this.documentPaths?.liveStateSingleEditorMode){let e={requestEditorAccess:T(I({},this.singleEditorLiveStateData?.requestEditorAccess),{status:"cancelled"})};this.commonDbService.updateData({feature:"liveStateSingleEditorMode",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",skipFirestore:!0},data:JSON.parse(JSON.stringify(e))}),e={requestEditorAccess:null},this.commonDbService.updateData({feature:"liveStateSingleEditorMode",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",skipFirestore:!0},data:JSON.parse(JSON.stringify(e))}),this.analyticsService.trackEvent(Z.Events.LiveStateSync.CANCEL_EDITOR_ACCESS_REQUEST_TRIGGERED)}}catch(e){this.loggingService.catch("Error in LiveStateService cancelEditorAccessRequest: ",e)}})}editCurrentTab(){return ee(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: editCurrentTab","color: green;"),this.user&&this.isUserEditor()?.isEditor&&!this.isUserEditor()?.isEditorOnCurrentTab&&this.documentPaths?.liveStateSingleEditorMode){let e={tabId:this.tabId};this.commonDbService.updateData({feature:"liveStateSingleEditorMode",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",skipFirestore:!0},data:JSON.parse(JSON.stringify(e))}),this.analyticsService.trackEvent(Z.Events.LiveStateSync.EDIT_CURRENT_TAB_TRIGGERED,{tabId:this.tabId})}}catch(e){this.loggingService.catch("Error in LiveStateService editCurrentTab: ",e)}})}isUserEditor$(){try{return this.loggingService.log("%c[WB] Calling FUNCTION: isUserEditor$","color: green;"),this.isEditor$.asObservable()}catch(e){return this.loggingService.catch("Error in LiveStateService isUserEditor$: ",e),re(null)}}isUserEditor(){try{return this.loggingService.log("%c[WB] Calling FUNCTION: isUserEditor","color: green;"),this.isEditor$.value}catch(e){return this.loggingService.catch("Error in LiveStateService isUserEditor: ",e),null}}getEditor$(){try{return this.loggingService.log("%c[WB] Calling FUNCTION: getEditor$","color: green;"),this.getSingleEditorLiveStateData$().pipe(ce(e=>e?.editor||null),Kt())}catch(e){return this.loggingService.catch("Error in LiveStateService getEditor$: ",e),re(null)}}isEditorAccessRequested$(){try{return this.loggingService.log("%c[WB] Calling FUNCTION: isEditorAccessRequested$","color: green;"),this.isUserEditor$().pipe(ge(e=>e?.isEditor?this.singleEditorLiveStateData$.pipe(ce(i=>i?.requestEditorAccess?{requestStatus:"requested",requestedBy:i?.requestEditorAccess?.user}:null)):re(null)),Kt((e,i)=>JSON.stringify(e||{})===JSON.stringify(i||{})))}catch(e){return this.loggingService.catch("Error in LiveStateService isEditorAccessRequested$: ",e),re(null)}}removeEditorAccess(){return ee(this,null,function*(){try{this.loggingService.log("%c[WB] Calling FUNCTION: removeEditorAccess","color: green;"),(this.user||this.authService.getAuthUser())&&this.documentPaths?.liveStateSingleEditorMode&&(yield this.commonDbService.deleteData({feature:"liveStateSingleEditorMode",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",skipFirestore:!0}}))}catch(e){this.loggingService.catch("Error in LiveStateService removeEditorAccess: ",e)}})}getSingleEditorLiveStateData$(){return this.singleEditorLiveStateData$.asObservable()}enableSingleEditorMode(e){try{if(this.singleEditorMode$.value===!0)return;this.singleEditorMode$.next(!0),e?this.singleEditorModeConfig$.next(e):this.singleEditorModeConfig$.next(new cM)}catch(i){this.loggingService.catch("Error in LiveStateService enableSingleEditorMode: ",i)}}disableSingleEditorMode(){try{if(this.singleEditorMode$.value===!1)return;this.singleEditorMode$.next(!1)}catch(e){this.loggingService.catch("Error in LiveStateService disableSingleEditorMode: ",e)}}getSingleEditorMode$(){return this.singleEditorMode$.asObservable()}getSingleEditorMode(){return this.singleEditorMode$.value}getSingleEditorModeConfig$(){return this.singleEditorModeConfig$.asObservable()}getSingleEditorModeConfig(){return this.singleEditorModeConfig$.value}enableAutoSyncState(){try{if(this.autoSyncState$.value===!0)return;this.autoSyncState$.next(!0)}catch(e){this.loggingService.catch("Error in LiveStateService enableAutoSyncState: ",e)}}disableAutoSyncState(){try{if(this.autoSyncState$.value===!1)return;this.autoSyncState$.next(!1)}catch(e){this.loggingService.catch("Error in LiveStateService disableAutoSyncState: ",e)}}getAutoSyncState$(){return this.autoSyncState$.asObservable()}getAutoSyncState(){return this.autoSyncState$.value}setEditorAccessTimeout(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setEditorAccessTimeout","color: green;"),e&&this.editorAccessTimeout$.next(e)}catch(i){this.loggingService.catch("Error in LiveStateService setEditorAccessTimeout: ",i)}}getEditorAccessTimeout$(){return this.editorAccessTimeout$.asObservable()}getEditorAccessTimeout(){return this.editorAccessTimeout$.value}enableEditorAccessTransferOnTimeOut(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableEditorAccessTransferOnTimeOut","color: green;"),this.editorAccessTransferOnTimeOut$.value===!0)return;this.editorAccessTransferOnTimeOut$.next(!0)}catch(e){this.loggingService.catch("Error in LiveStateService enableEditorAccessTransferOnTimeOut: ",e)}}disableEditorAccessTransferOnTimeOut(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableEditorAccessTransferOnTimeOut","color: green;"),this.editorAccessTransferOnTimeOut$.value===!1)return;this.editorAccessTransferOnTimeOut$.next(!1)}catch(e){this.loggingService.catch("Error in LiveStateService disableEditorAccessTransferOnTimeOut: ",e)}}getEditorAccessTransferOnTimeOut$(){return this.editorAccessTransferOnTimeOut$.asObservable()}getEditorAccessTransferOnTimeOut(){return this.editorAccessTransferOnTimeOut$.value}enableDefaultSingleEditorUI(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableDefaultSingleEditorUI","color: green;"),this.defaultSingleEditorUIEnabled$.value===!0)return;this.defaultSingleEditorUIEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in LiveStateService enableDefaultSingleEditorUI: ",e)}}disableDefaultSingleEditorUI(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableDefaultSingleEditorUI","color: green;"),this.defaultSingleEditorUIEnabled$.value===!1)return;this.defaultSingleEditorUIEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in LiveStateService disableDefaultSingleEditorUI: ",e)}}getDefaultSingleEditorUIEnabled$(){return this.defaultSingleEditorUIEnabled$.asObservable()}getDefaultSingleEditorUIEnabled(){return this.defaultSingleEditorUIEnabled$.value}setEditorAccessTimerInterval(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setEditorAccessTimerInterval","color: green;"),this.clearEditorAccessTimerInterval(),e>0&&(this.editorAccessTimer$.next({state:"inProgress",durationLeft:e}),this.editorAccessTimerInterval=setInterval(()=>{try{e-=1,e<0?this.clearEditorAccessTimerInterval():e?this.editorAccessTimer$.next({state:"inProgress",durationLeft:e}):this.editorAccessTimer$.next({state:"completed"})}catch(i){this.loggingService.catch("Error in LiveStateService setEditorAccessTimerCountdown interval: ",i),this.clearEditorAccessTimerInterval()}},1e3))}catch(i){this.loggingService.catch("Error in LiveStateService setEditorAccessTimerCountdown: ",i),this.clearEditorAccessTimerInterval()}}clearEditorAccessTimerInterval(){try{this.loggingService.log("%c[WB] Calling FUNCTION: clearEditorAccessTimerInterval","color: green;"),this.editorAccessTimerInterval&&(clearInterval(this.editorAccessTimerInterval),this.editorAccessTimerInterval=null,this.editorAccessTimer$.next({state:"idle"}))}catch(e){this.loggingService.catch("Error in LiveStateService clearEditorAccessTimerInterval: ",e)}}getEditorAccessTimer$(){return this.editorAccessTimer$.asObservable()}onServerConnectionStateChange$(){return this.serverConnectionState$.asObservable()}detectLiveSyncInputs(){try{document.querySelectorAll(`[${U.ATTRIBUTES.VELT_SYNC_STATE}]`)?.forEach(i=>{this.subscribeInputChanges(i)})}catch(e){this.loggingService.catch("Error in LiveStateService detectLiveSyncInputs: ",e)}}subscribeInputChanges(e){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: subscribeInputChanges","color: green;"),e){let i=e.tagName,r=this.domService.getXPath(e),a=Rt(r);if(this.inputChangeSubscriptionMap[a])this.loggingService.warn("subscription already exists",a,e);else{this.inputChangeSubscriptionMap[a]={id:a,element:e};let s;switch(i?.toLowerCase()){case"input":s=oi(e,"input").pipe(jr(300)).subscribe(p=>{let h={value:p?.target?.value,tagName:p?.target?.tagName,type:p?.target?.type};this.setLiveStateSyncInputData(p?.target,h)});break;case"textarea":s=oi(e,"input").pipe(jr(300)).subscribe(p=>{let h={value:p?.target?.value,tagName:p?.target?.tagName};this.setLiveStateSyncInputData(p?.target,h)});break;default:e.getAttribute("contenteditable")&&(s=oi(e,"input").pipe(jr(300)).subscribe(p=>{let h={innerText:p?.target?.innerText,innerHTML:this.domService.sanitizeHtml(p?.target?.innerHTML),tagName:p?.target?.tagName,isContentEditable:!0};this.setLiveStateSyncInputData(p?.target,h)}));break}s&&(this.inputChangeSubscriptionMap[a]?.subscriptions||(this.inputChangeSubscriptionMap[a]={subscriptions:[]}),this.inputChangeSubscriptionMap[a].subscriptions?.push(s))}}}catch(i){this.loggingService.catch("Error in LiveStateService subscribeInputChanges: ",i)}}unsubscribeInputChanges(){try{this.loggingService.log("%c[WB] Calling FUNCTION: unsubscribeInputChanges","color: green;"),Object.keys(this.inputChangeSubscriptionMap).forEach(e=>{this.inputChangeSubscriptionMap[e]?.subscriptions?.forEach(r=>{r.unsubscribe()})}),this.inputChangeSubscriptionMap={}}catch(e){this.loggingService.catch("Error in LiveStateService unsubscribeInputChanges: ",e)}}setLiveStateSyncInputData(e,i){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: setLiveStateSyncInputData","color: green;"),this.user&&this.documentPaths?.liveState){let r=this.domService.getXPath(e),a=Rt(r),s={id:a,lastUpdated:this.timestamp,liveStateDataId:r,data:i,updatedBy:this.user,tabId:this.tabId};this.commonDbService.updateData({feature:"liveStateAutoSyncStateCurrent",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",skipFirestore:!0},data:JSON.parse(JSON.stringify(s))}),this.commonDbService.updateData({feature:"liveStateAutoSyncStateHistoryId",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",id:a,skipFirestore:!0},data:JSON.parse(JSON.stringify(s))})}}catch(r){this.loggingService.catch("Error in LiveStateService setLiveStateSyncInputData: ",r)}}updateLiveStateSyncInputDataLocally(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: updateLiveStateSyncInputDataLocally","color: green;"),this.user&&Object.keys(e).forEach(i=>{let r=e[i],a=this.domService.getElementFromXPath(r?.liveStateDataId),s=!1;if(r?.updatedBy?.userSnippylyId!==this.user?.userSnippylyId)s=!0;else{let c=r?.tabId&&this.tabId&&r?.tabId!==this.tabId,p=a?.contains(document.activeElement);c&&!eoe()&&!p&&(s=!0)}if(s&&a)switch(a.value=r?.data?.value,a.tagName?.toLowerCase()){case"input":a.value=r?.data?.value;break;case"textarea":a.value=r?.data?.value;break;default:a.getAttribute("contenteditable")&&(a.innerHTML=this.domService.sanitizeHtml(r?.data?.innerHTML))}})}catch(i){this.loggingService.catch("Error in LiveStateService updateLiveStateSyncInputDataLocally: ",i)}}setSingleEditorModeContainerIds(e){this.singleEditorModeContainerIds$.next(e||[])}getSingleEditorModeContainerIds(){return this.singleEditorModeContainerIds$.asObservable()}isElementInsideSingleEditorModeContainerElements(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: isElementInsideSingleEditorModeContainerElements","color: green;");let i=this.singleEditorModeContainerIds$.value,r=document.querySelectorAll(`[${U.ATTRIBUTES.VELT_SINGLE_EDITOR_MODE_CONTAINER}]`);if(!i?.length&&!r?.length)return!0;if(i?.length)for(let a=0;a<i.length;a++){let s=document.getElementById(i[a]);if(s&&s.contains(e))return!0}if(r?.length)for(let a=0;a<r.length;a++){let s=r[a];if(s&&s.contains(e))return!0}return!1}catch(i){return this.loggingService.catch("Error in LiveStateService isElementInsideSingleEditorModeContainerElements: ",i),!1}}isSingleEditorModeDisabledForElement(e){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: isSingleEditorModeDisabledForElement","color: green;"),e){if(e.getAttribute(U.ATTRIBUTES.VELT_SYNC_ACCESS_DISABLED))return!0;{let r=e?.parentElement;if(r)return this.isSingleEditorModeDisabledForElement(r)}}return!1}catch(i){return this.loggingService.catch("Error in LiveStateService isSingleEditorModeDisabledForElement: ",i),!1}}updateOnDatabaseDisconnect(){return this.loggingService.log("%c[WB] Calling FUNCTION: updateOnDatabaseDisconnect","color: green;"),this.isUserEditor$().pipe(In(e=>{try{if(this.documentPaths?.liveStateSingleEditorMode){let i=on(this.db,`${this.documentPaths?.liveStateSingleEditorMode}`);e?.isEditor&&(!this.getSingleEditorModeConfig()?.singleTabEditor||e?.isEditorOnCurrentTab)?cl(i).remove():cl(i).cancel()}}catch(i){this.loggingService.catch("Error in LiveStateService updateOnDatabaseDisconnect tap: ",i)}}))}updateServerStateOnDatabaseDisconnect(){return this.loggingService.log("%c[WB] Calling FUNCTION: updateServerStateOnDatabaseDisconnect","color: green;"),Wn(this.afAuth).pipe(Ne(e=>!!e),ge(e=>this.docService.getDocumentPaths$().pipe(ce(i=>e))),In(e=>ee(this,null,function*(){try{if(this.docService.getDocumentPaths()?.liveState&&e){let r=on(this.db,".info/connected"),a=!0;gu(r,s=>{let c=s.val();if(a&&c===!1){a=!1;return}a=!1,c===!1?this.serverConnectionState$.next(ul.OFFLINE):this.serverConnectionState$.value===ul.OFFLINE&&this.serverConnectionState$.next(ul.ONLINE)})}}catch(i){this.loggingService.catch("Error in updateServerStateOnDatabaseDisconnect:",i)}})))}get timestamp(){return this.commonDbService.getServerTimestamp()}};o.\u0275fac=function(i){return new(i||o)(J(vi),J(Qe),J(je),J($t),J(pn),J(lt),J(Fe),J(gn),J(y),J(bn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Cm=(()=>{let o=class o{constructor(e,i,r,a,s,c,p,h,_,E,D,B){this.analyticsService=e,this.docService=i,this.authService=r,this.afAuth=a,this.iamService=s,this.databaseService=c,this.configService=p,this.avatarService=h,this.loggingService=_,this.flockService=E,this.liveStateService=D,this.commonDbService=B,this.db=Ci(),this.presenceUser$=new fe(new dM),this.documentPaths=null,this.inactivityTime=5*60*1e3,this.presenceUsers$=new fe([]),this.presenceUsersSubscription=null,this.includeSelf$=new fe(!0),this.loggingService.log("%c[WB] Creating CLASS: PresenceService","color: blue;"),this.databaseService.getDb().pipe(Ne(G=>!!G),Je(1)).subscribe(G=>{G&&(this.db=G,this.getUser(),this.getDocumentPaths(),this.getLocation(),this.updateOnUserDbConnectionStateChange().subscribe(()=>{},X=>{this.loggingService.catch("Error in PresenceService constructor updateOnUserDbConnectionStateChange: ",X)}),this.updateOnDatabaseDisconnect().subscribe(()=>{},X=>{this.loggingService.catch("Error in PresenceService constructor updateOnDatabaseDisconnect: ",X)}),this.updateOnDocumentFocusChange(),this.updateOnAllowedFeatureListChange())},G=>{this.loggingService.catch("Error in PresenceService constructor: ",G)}),this.authService.addPreSignOutFuction("presence-signout",this.signOutUser.bind(this)),this.presenceUsers$.pipe(Vi()).subscribe(([G,X])=>{sessionStorage.getItem(U.SESSION_STORAGE.VELT_PRESENCE_MULTIPLE_USERS_DETECTED)||X?.length>1&&G.length!==X.length&&(this.analyticsService.trackEvent(Z.Events.Presence.PRESENCE_MULTIPLE_USERS_DETECTED,{totalUsers:X.length,presenceSnippylyUserIds:X.map(he=>he.userSnippylyId),presenceClientUserIds:X.map(he=>he.userId)}),sessionStorage.setItem(U.SESSION_STORAGE.VELT_PRESENCE_MULTIPLE_USERS_DETECTED,"true"))})}getUser(){this.loggingService.log("%c[WB] Calling FUNCTION: getUser","color: green;"),this.authService.getUser$().pipe(Ne(e=>!!e)).subscribe(e=>{e&&this.setPresenceUser(e)},e=>{this.loggingService.catch("Error in getUser: ",e)})}getDocumentPaths(){this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentPaths","color: green;"),this.docService.getDocumentPaths$().pipe(In(e=>{this.documentPaths=e}),Vi(),In(([e,i])=>{e&&this.updateUserStatusOnDocumentChange(U.PRESENCE_STATUS_OFFLINE,e),i&&this.updateUserStatusOnDocumentChange(U.PRESENCE_STATUS_ONLINE,i)})).subscribe(()=>{},e=>{this.loggingService.catch("Error in getDocumentPaths: ",e)})}getLocation(){this.docService.getLocation$().pipe(In(e=>{this.updateUserOnLocationChange(e)})).subscribe(()=>{},e=>{this.loggingService.catch("Error in getLocation: ",e)})}getPresenceUser(){return this.loggingService.log("%c[WB] Calling FUNCTION: getPresenceUser","color: green;"),this.presenceUser$.asObservable()}getOnlineUsersOnCurrentDocument(){return this.loggingService.log("%c[WB] Calling FUNCTION: getOnlineUsersOnCurrentDocument","color: green;"),Wn(this.afAuth).pipe(Ne(e=>!!e),ge(e=>this.isFeatureAllowed({firebaseUser:e,users:[],filteredUsers:[]})),ge(e=>e.featureAllowed?this.iamService.isUserAllowed$().pipe(ce(i=>(e.featureAllowed=i,e))):re(e)),ge(e=>e.featureAllowed?this.authService.isPlanExpired$().pipe(ce(i=>(e.featureAllowed=!i,e))):re(e)),ge(e=>e.featureAllowed?re(e).pipe(ge(i=>this.docService.getDocumentPaths$().pipe(ce(r=>(this.documentPaths=r,i.documentPaths=r,i)))),ge(i=>this.getDataFromDocumentId().pipe(ce(r=>(i.users=r||[],I({},i))))),ce(i=>(i.filteredUsers=this.filterOnlineUsers(i.users,i.firebaseUser),i)),ge(i=>this.getIncludeSelf$().pipe(ce(r=>(r||(i.filteredUsers=i?.filteredUsers?.filter(a=>a?.userSnippylyId!==i.user?.userSnippylyId)),i)))),ge(i=>i?.filteredUsers?re(i?.filteredUsers||[]):re([]))):re([])))}isFeatureAllowed(e){return this.configService.getConfig$().pipe(Ne(i=>!!i),ce(i=>T(I({},e),{config:i})),ge(i=>this.authService.getUser$().pipe(ce(r=>T(I({},i),{user:r})))),ge(i=>Xi(i.config,i.user,Re.PRESENCE)?re(T(I({},i),{featureAllowed:!0})):(this.loggingService.warn("Presence feature is not allowed."),re(T(I({},i),{featureAllowed:!1})))))}getDataFromDocumentId(e){return this.databaseService.getDb().pipe(Ne(i=>!!i),ge(i=>(this.db=i,this.loggingService.log(this.db),this.configService?.getApiKey()&&this.documentPaths?.presence?this.commonDbService.dbListener({feature:"allPresence",properties:{documentId:e??this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,skipFirestore:!0}}).pipe(Ln(r=>(this.loggingService.catch("Error in PresenceService getDataFromDocumentId: ",r),re(null))),ce(r=>r?.data),ce(r=>{let a=[];return r&&(a=Object.values(r).filter(s=>typeof s=="object")),a})):re([]))))}filterOnlineUsers(e,i){this.loggingService.log("%c[WB] Calling FUNCTION: filterOnlineUsers","color: green;");try{let a=e.slice().filter(s=>{let c=Sp(s.timestamp);return s.userSnippylyId&&(s.onlineStatus===U.PRESENCE_STATUS_ONLINE||s.onlineStatus===U.PRESENCE_STATUS_AWAY)&&c<this.inactivityTime});return this.presenceUsers$.next(a),a}catch(r){return this.loggingService.catch("Error in filterOnlineUsers:",r),[]}}enableIncludeSelf(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableIncludeSelf","color: green;"),this.includeSelf$.value===!0)return;this.includeSelf$.next(!0)}catch(e){this.loggingService.catch("Error in PresenceService enableIncludeSelf: ",e)}}disableIncludeSelf(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableIncludeSelf","color: green;"),this.includeSelf$.value===!1)return;this.includeSelf$.next(!1)}catch(e){this.loggingService.catch("Error in PresenceService disableIncludeSelf: ",e)}}getIncludeSelf$(){return this.includeSelf$.asObservable()}getIncludeSelf(){return this.includeSelf$.value}getPresenceUserFromExternalId(e){try{if(this.presenceUsers$.value&&this.presenceUsers$.value.length>0){let i=this.presenceUsers$.value.find(r=>r.userId===e);if(i)return i}return null}catch(i){return this.loggingService.catch("Error in getNameFromSnippylyId:",i),null}}getAnonymousAvatarImage(){return this.loggingService.log("%c[WB] Calling FUNCTION: getAnonymousAvatarImage","color: green;"),this.avatarService.generateUserImage()}updateCurrentPresenceUser(e){return ee(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: updateCurrentPresenceUser","color: green;");try{if(this.documentPaths?.presence&&e&&e.userId&&this.authService.isFeatureAllowed(Re.PRESENCE)){if(!e.isAnonymous){e.pageInfo=new Zi;let i=JSON.parse(JSON.stringify(e));this.authService.getUser()&&this.commonDbService.updateData({feature:"presence",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,userId:e.userSnippylyId,skipFirestore:!0},data:JSON.parse(JSON.stringify(T(I({},i),{timestamp:this.timestamp})))})}this.presenceUser$.next(e)}}catch(i){this.loggingService.catch("Error in updateCurrentPresenceUser:",i)}})}setCurrentPresenceUserStatus(e){return ee(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: setCurrentPresenceUserStatus","color: green;");try{this.loggingService.log(e);let i=this.presenceUser$.value;if(i.onlineStatus!==e){this.presenceUsersSubscription&&this.presenceUsersSubscription?.unsubscribe();let r=i.onlineStatus,a=e;this.presenceUsersSubscription=this.getPresenceUsers$().pipe(Ne(s=>!!s?.length),Je(1)).subscribe(s=>{s?.length>1&&this.analyticsService.trackEvent(Z.Events.Presence.PRESENCE_USER_STATUS_CHANGED,{oldStatus:r,newStatus:a,totalUsers:s?.length,presenceSnippylyUserIds:s?.map(c=>c.userSnippylyId),presenceClientUserIds:s?.map(c=>c.userId)})})}i.onlineStatus=e,e===U.PRESENCE_STATUS_OFFLINE&&this.flockService.isInSession()&&this.flockService.removeCurrentUserFromSession(),e===U.PRESENCE_STATUS_OFFLINE&&this.liveStateService.isUserEditor()?.isEditor&&this.liveStateService.removeEditorAccess(),this.updateCurrentPresenceUser(i)}catch(i){this.loggingService.catch("Error in setCurrentPresenceUserStatus:",i)}})}updateUserStatusOnDocumentChange(e,i){return ee(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: updateUserStatusOnDocumentChange","color: green;");try{let r=this.presenceUser$.value;if(r.onlineStatus=e,i?.presence&&r&&r.userId&&!r.isAnonymous&&this.authService.isFeatureAllowed(Re.PRESENCE)){let a=JSON.parse(JSON.stringify(r));this.commonDbService.updateData({feature:"presence",properties:{documentId:i?.documentId,organizationId:i?.organizationId,userId:r.userSnippylyId,skipFirestore:!0},data:JSON.parse(JSON.stringify(a))})}}catch(r){this.loggingService.catch("Error in updateUserStatusOnDocumentChange:",r)}})}updateUserOnLocationChange(e){return ee(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: updateUserOnLocationChange","color: green;");try{let i=this.presenceUser$.value;if(i.location=e?e.location:null,i.locationId=e?e?.locationId:null,this.documentPaths?.presence&&i&&i.userId&&!i.isAnonymous&&this.authService.isFeatureAllowed(Re.PRESENCE)){let r=JSON.parse(JSON.stringify(i));this.commonDbService.updateData({feature:"presence",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,userId:i.userSnippylyId,skipFirestore:!0},data:JSON.parse(JSON.stringify(r))})}}catch(i){this.loggingService.catch("Error in updateUserOnLocationChange:",i)}})}updateOnUserDbConnectionStateChange(){this.loggingService.log("%c[WB] Calling FUNCTION: updateOnUserDbConnectionStateChange","color: green;");let e=on(this.db,".info/connected"),i=Af(e).pipe(ce(r=>r?U.PRESENCE_STATUS_ONLINE:U.PRESENCE_STATUS_OFFLINE));return Wn(this.afAuth).pipe(xs(1),ge(r=>r?i:re(U.PRESENCE_STATUS_OFFLINE)),In(r=>this.setCurrentPresenceUserStatus(r)))}updateOnDocumentFocusChange(){this.loggingService.log("%c[WB] Calling FUNCTION: updateOnDocumentFocusChange","color: green;");try{document&&document.addEventListener("visibilitychange",e=>{this.authService.getUser()&&(document.visibilityState==="hidden"?(this.setCurrentPresenceUserStatus(U.PRESENCE_STATUS_AWAY),this.flockService.getFlockMode()&&this.flockService.setTabFocused(!1)):(this.setCurrentPresenceUserStatus(U.PRESENCE_STATUS_ONLINE),this.flockService.getFlockMode()&&this.flockService.setTabFocused(!0)))}),window&&(window.addEventListener("focus",()=>{this.authService.getUser()&&(this.setCurrentPresenceUserStatus(U.PRESENCE_STATUS_ONLINE),this.flockService.getFlockMode()&&this.flockService.setWindowFocused(!0))}),window.addEventListener("blur",()=>{this.authService.getUser()&&(document.visibilityState!=="hidden"&&this.setCurrentPresenceUserStatus(U.PRESENCE_STATUS_AWAY),this.flockService.getFlockMode()&&this.flockService.setWindowFocused(!1))}))}catch(e){this.loggingService.catch("Error in updateOnDocumentFocusChange:",e)}}updateOnAllowedFeatureListChange(){try{this.configService.getConfig$().subscribe(e=>{if(e&&e.featureAllowList?.length){let i=this.presenceUser$.value,r=!1;if(e.featureAllowList.includes(Re.PRESENCE)?i?.onlineStatus!==U.PRESENCE_STATUS_ONLINE&&(i.onlineStatus=U.PRESENCE_STATUS_ONLINE,r=!0):i?.onlineStatus!==U.PRESENCE_STATUS_OFFLINE&&(i.onlineStatus=U.PRESENCE_STATUS_OFFLINE,r=!0),r&&this.authService.getUser()&&this.documentPaths?.presence&&i&&i.userId&&!i.isAnonymous){let a=JSON.parse(JSON.stringify(i));this.commonDbService.updateData({feature:"presence",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,userId:i.userSnippylyId,skipFirestore:!0},data:JSON.parse(JSON.stringify(a))})}}})}catch(e){this.loggingService.catch("Error in updateOnAllowedFeatureListChange:",e)}}updateOnDatabaseDisconnect(){return this.loggingService.log("%c[WB] Calling FUNCTION: updateOnDatabaseDisconnect","color: green;"),Wn(this.afAuth).pipe(Ne(e=>!!e),ge(e=>this.docService.getDocumentPaths$().pipe(ce(i=>e))),In(e=>ee(this,null,function*(){try{if(this.documentPaths?.presence&&e){let i=yield ad(e,!0).catch(a=>null);if(!i)return;let{user:r}=i.claims;if(!r?.isAnonymous){let a=on(this.db,`${this.documentPaths.presence}/${e.uid}`);this.flockService.isInSession()&&this.flockService.removeCurrentUserFromSession(),this.liveStateService.isUserEditor()?.isEditor&&this.liveStateService.removeEditorAccess(),cl(a).update({onlineStatus:U.PRESENCE_STATUS_OFFLINE,timestamp:this.timestamp}).catch(s=>{this.loggingService.catch("Error in updateOnDatabaseDisconnect:",s)})}}}catch(i){this.loggingService.catch("Error in updateOnDatabaseDisconnect:",i)}})))}setPresenceUser(e){this.loggingService.log("%c[WB] Calling FUNCTION: setPresenceUser","color: green;");try{let i=this.presenceUser$.value;i.userId=e?.userId,i.name=e?.name,i.email=e?.email,i.photoUrl=e?.photoUrl,i.userSnippylyId=e?.userSnippylyId,i.color=e?.color,i.textColor=e?.textColor,i.initial=e?.initial,i.timestamp=this.timestamp,i.type=e?.type,i.isReadOnly=e?.isReadOnly,i.isAnonymous=e?.isAnonymous;let r=e?.name?.split(" ");if(r&&r.length>0){let a=r[0],s=r.length>1?r[r.length-1]:null,c=s?s[0]:null;a&&(i.name=`${a} ${c?c+".":""}`)}this.updateCurrentPresenceUser(i)}catch(i){this.loggingService.catch("Error in setPresenceUser:",i)}}signOutUser(e){return new Promise((i,r)=>{try{this.documentPaths?.presence&&e?this.commonDbService.dbListener({feature:"presence",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,userId:e.uid,skipFirestore:!0}}).pipe(Je(1)).subscribe(a=>{a?.data?(this.flockService.isInSession()&&this.flockService.removeCurrentUserFromSession(),this.liveStateService.isUserEditor()?.isEditor&&this.liveStateService.removeEditorAccess(),this.commonDbService.updateData({feature:"presence",errorCallback:s=>{r(s)},callback:()=>{i(null)},properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,userId:e.uid,skipFirestore:!0},data:JSON.parse(JSON.stringify(T(I({},a?.data??{}),{timestamp:this.timestamp,onlineStatus:U.PRESENCE_STATUS_OFFLINE})))})):i(null)},a=>{this.loggingService.catch("Error in signOutUser subscription: ",a),r(a)}):i(null)}catch(a){this.loggingService.catch("Error in signOutUser:",a),r(a)}})}setInactivityTime(e){this.inactivityTime=e,this.analyticsService.trackEvent(Z.Events.Presence.PRESENCE_SET_CUSTOM_INACTIVITY_TIMER,{inactivityTime:this.inactivityTime})}getPresenceUsers$(){return this.presenceUsers$.asObservable()}getPresenceUsers(){return this.presenceUsers$.value}get timestamp(){return this.commonDbService.getServerTimestamp()}};o.\u0275fac=function(i){return new(i||o)(J(Qe),J(lt),J(je),J(vi),J(gn),J(pn),J($t),J(gm),J(y),J(vc),J(Di),J(bn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var qv=(()=>{let o=class o{constructor(e,i,r,a,s,c,p,h,_,E,D){this.analyticsService=e,this.configService=i,this.presenceService=r,this.docService=a,this.afAuth=s,this.iamService=c,this.domService=p,this.databaseService=h,this.authService=_,this.loggingService=E,this.commonDbService=D,this.db=Df(),this.cursorUser$=new fe(new Fv),this.documentPaths=null,this.inactivityTime=2*60*1e3,this.allowedElementIds$=new fe([]),this.cursorTagAvailable$=new fe(!1),this.cursorTagAvailable=!1,this.cursorUsers$=new fe([]),this.loggingService.log("%c[WB] Creating CLASS: CursorService","color: blue;");try{this.checkCursorTagAvailable(),this.databaseService.getDb().pipe(Ne(B=>!!B),ge(B=>this.cursorTagAvailable$.pipe(Ne(G=>!!G),Je(1),ce(()=>B))),Je(1)).subscribe(B=>{B&&(this.db=B,this.cursorTagAvailable&&(this.getPresenceUser(),this.getDocumentPaths(),this.getLocation(),this.updateOnDatabaseDisconnect().subscribe(()=>{},G=>{this.loggingService.catch("Error in CursorService constructor updateOnDatabaseDisconnect: ",G)}),this.addMouseMoveListener(),this.addScreenSizeChangeListener(),this.updateOnAllowedFeatureListChange()))},B=>{this.loggingService.catch("Error in CursorService constructor getDb: ",B)}),this.cursorUsers$.pipe(Vi()).subscribe(([B,G])=>{sessionStorage.getItem(U.SESSION_STORAGE.VELT_CURSOR_MULTIPLE_USERS_DETECTED)||G?.length>1&&B.length!==G.length&&(this.analyticsService.trackEvent(Z.Events.Cursor.CURSOR_MULTIPLE_USERS_DETECTED,{totalUsers:G.length,cursorSnippylyUserIds:G.map(X=>X.userSnippylyId),cursorClientUserIds:G.map(X=>X.userId)}),sessionStorage.setItem(U.SESSION_STORAGE.VELT_CURSOR_MULTIPLE_USERS_DETECTED,"true"))}),this.authService.addPreSignOutFuction("cursor-signout",this.signOutUser.bind(this))}catch(B){this.loggingService.catch("Error in CursorService constructor: ",B)}}checkCursorTagAvailable(){this.loggingService.log("%c[WB] Calling FUNCTION: checkCursorTagAvailable","color: green;");try{this.cursorTagAvailable=!!document.querySelector(U.TAGS.VELT_CURSOR)||!!document.querySelector(U.TAGS.SNIPPYLY_CURSOR),this.cursorTagAvailable$.next(this.cursorTagAvailable)}catch(e){this.loggingService.catch("Error in CursorService checkCursorTagAvailable: ",e)}}addScreenSizeChangeListener(){this.loggingService.log("%c[WB] Calling FUNCTION: addScreenSizeChangeListener","color: green;");try{this.docService.getDocumentPaths$().pipe(Ne(e=>!!e),ge(e=>this.domService.getCurrentWindowSize$("CursorService addScreenSizeChangeListener").pipe(Ne(i=>!!i)))).subscribe(e=>{this.setCurrentCursorUserScreenSize(e)},e=>{this.loggingService.catch("Error in addScreenSizeChangeListener getCurrentWindowSize: ",e)})}catch(e){this.loggingService.catch("Error in CursorService addScreenSizeChangeListener: ",e)}}addMouseMoveListener(){this.loggingService.log("%c[WB] Calling FUNCTION: addMouseMoveListener","color: green;");try{this.domService.onWindowPointerMove$().pipe(t7(50)).subscribe(e=>{e&&this.setCurrentCursorUserPosition(e.pageX,e.pageY,this.domService.getTargetElementForCursorPosition(e,!0,!1,!1))},e=>{this.loggingService.catch("Error in addMouseMoveListener getCurrentMousePosition: ",e)})}catch(e){this.loggingService.catch("Error in CursorService addMouseMoveListener: ",e)}}getDocumentPaths(){this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentPaths","color: green;");try{this.docService.getDocumentPaths$().pipe(In(e=>{this.documentPaths=e}),Vi(),In(([e,i])=>{e&&this.updateUserStatusOnDocumentChange(U.PRESENCE_STATUS_OFFLINE,e),i&&this.updateUserStatusOnDocumentChange(U.PRESENCE_STATUS_ONLINE,i)})).subscribe(()=>{},e=>{this.loggingService.catch("Error in getDocumentPaths subscription: ",e)})}catch(e){this.loggingService.catch("Error in CursorService getDocumentPaths: ",e)}}getLocation(){try{this.docService.getLocation$().pipe(In(e=>{this.updateUserOnLocationChange(e)})).subscribe(()=>{},e=>{this.loggingService.catch("Error in getLocation subscription: ",e)})}catch(e){this.loggingService.catch("Error in CursorService getLocation: ",e)}}getCursorUser(){return this.loggingService.log("%c[WB] Calling FUNCTION: getCursorUser","color: green;"),this.cursorUser$.asObservable()}getPresenceUser(){this.loggingService.log("%c[WB] Calling FUNCTION: getPresenceUser","color: green;"),this.presenceService.getPresenceUser().pipe(Ne(e=>!!e),Ln(e=>re(e.code))).subscribe(e=>{this.setCursorUser(e)},e=>{this.loggingService.catch("Error in getPresenceUser: ",e)})}getLiveCursorsOnCurrentDocument(){return this.loggingService.log("%c[WB] Calling FUNCTION: getLiveCursorsOnCurrentDocument","color: green;"),Wn(this.afAuth).pipe(Ne(e=>!!e),ge(e=>this.isFeatureAllowed({firebaseUser:e,users:[],filteredUsers:[]})),ge(e=>e.featureAllowed?this.iamService.isUserAllowed$().pipe(ce(i=>(e.featureAllowed=i,e))):re(e)),ge(e=>e.featureAllowed?this.authService.isPlanExpired$().pipe(ce(i=>(e.featureAllowed=!i,e))):re(e)),ge(e=>!e.featureAllowed||e?.user?.isAnonymous?re([]):re(e).pipe(ge(i=>this.docService.getDocumentPaths$().pipe(ce(r=>(this.documentPaths=r,i.documentPaths=r,i)))),ge(i=>this.getDataFromDocumentId().pipe(ce(r=>(i.users=r||[],I({},i))))),ce(i=>(i.filteredUsers=this.filterOnlineUsers(i.users,i.firebaseUser),i)),ge(i=>i?.filteredUsers?.length?this.domService.getCurrentWindowSize$("CursorService getLiveCursorsOnCurrentDocument").pipe(ce(()=>i)):re(i)),ce(i=>(i?.filteredUsers?.forEach(r=>{this.calculateCursorUserPosition(r)}),i)),ge(i=>i?.filteredUsers?re(i?.filteredUsers||[]):re([])))))}isFeatureAllowed(e){return this.configService.getConfig$().pipe(Ne(i=>!!i),ce(i=>T(I({},e),{config:i})),ge(i=>this.authService.getUser$().pipe(ce(r=>T(I({},i),{user:r})))),ge(i=>Xi(i.config,i.user,Re.CURSOR)?re(T(I({},i),{featureAllowed:!0})):(this.loggingService.warn("Cursor feature is not allowed."),re(T(I({},i),{featureAllowed:!1})))))}getDataFromDocumentId(e){return this.databaseService.getDb().pipe(Ne(i=>!!i),ge(i=>(this.db=i,this.loggingService.log(this.db),this.configService?.getApiKey()&&this.documentPaths?.cursor?this.commonDbService.dbListener({feature:"allCursors",properties:{documentId:e??this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,skipFirestore:!0}}).pipe(Ln(r=>(this.loggingService.catch("Error in CursorService getDataFromDocumentId: ",r),re(null))),ce(r=>r?.data),ce(r=>{let a=[];return r&&(a=Object.values(r).filter(s=>typeof s=="object")),a})):re([]))))}calculateCursorUserPosition(e){try{if(e?.targetElement){let i=this.domService.getXPath(e.targetElement?.xpath);if(i){let r=i.iterateNext();if(r&&this.isElementInsideAllowedElements(r)){let a=r.getBoundingClientRect();a&&a.width&&a.height&&(e.position={top:a.top+a.height*e.targetElement.topPercentage/100,left:a.left+a.width*e.targetElement.leftPercentage/100})}}}}catch(i){this.loggingService.catch("Error in calculateCursorUserPosition:",i)}}filterOnlineUsers(e,i){try{let a=e.slice().filter(c=>{let p=Sp(c.timestamp);return c.userSnippylyId&&c.onlineStatus===U.PRESENCE_STATUS_ONLINE&&p<this.inactivityTime});this.cursorUsers$.next(a),a=a.filter(c=>c?.userSnippylyId!==i?.uid);let s=this.docService.getLocation();return s&&s.locationId?a=a.filter(c=>c.locationId===s.locationId):a=a.filter(c=>!c.locationId),a}catch(r){return this.loggingService.catch("Error in filterOnlineUsers:",r),[]}}setCursorUser(e){this.loggingService.log("%c[WB] Calling FUNCTION: setCursorUser","color: green;");try{let i=this.cursorUser$.value;i.userId=e?.userId,i.name=e?.name,i.email=e?.email,i.photoUrl=e?.photoUrl,i.comment="",this.authService.isFeatureAllowed(Re.PRESENCE)&&(i.onlineStatus=e?.onlineStatus),i.userSnippylyId=e?.userSnippylyId,i.color=e?.color,i.textColor=e?.textColor,i.initial=e?.initial,i.timestamp=this.timestamp,i.type=e?.type,i.isReadOnly=e?.isReadOnly,i.isAnonymous=e?.isAnonymous;let r=this.domService.getCurrentWindowSizeValue();i.screenWidth=r?.screenWidth,i.screenHeight=r?.screenHeight,i.screenScrollHeight=r?.screenScrollHeight,this.updateCurrentCursorUser(i)}catch(i){this.loggingService.catch("Error in setCursorUser:",i)}}setCurrentCursorUserPosition(e,i,r){try{let a=this.cursorUser$.value;a?.onlineStatus===U.PRESENCE_STATUS_ONLINE&&(a.positionX=e,a.positionY=i,r?a.targetElement=r:a.targetElement=null,this.updateCurrentCursorUser(a))}catch(a){this.loggingService.catch("Error in setCurrentCursorUserPosition:",a)}}setCurrentCursorUserScreenSize(e){try{if(e.screenWidth!==0&&e.screenHeight!==0){let i=this.cursorUser$.value;i?.onlineStatus===U.PRESENCE_STATUS_ONLINE&&(i.screenWidth=e.screenWidth,i.screenHeight=e.screenHeight,i.screenScrollHeight=e.screenScrollHeight,this.updateCurrentCursorUser(i))}}catch(i){this.loggingService.catch("Error in setCurrentCursorUserScreenSize:",i)}}updateCurrentCursorUser(e){return ee(this,null,function*(){try{if(this.documentPaths&&e&&e.userId&&this.authService.isFeatureAllowed(Re.CURSOR)){if(!e.isAnonymous){e.pageInfo=new Zi;let i=JSON.parse(JSON.stringify(e));this.commonDbService.updateData({feature:"cursor",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",id:e.userSnippylyId,skipFirestore:!0},data:JSON.parse(JSON.stringify(T(I({},i),{timestamp:this.timestamp})))})}this.cursorUser$.next(e)}}catch(i){this.loggingService.catch("Error in updateCurrentCursorUser:",i)}})}updateUserStatusOnDocumentChange(e,i){return ee(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: updateUserStatusOnDocumentChange","color: green;");try{let r=this.cursorUser$.value;if(r.onlineStatus=e,i&&r&&r.userId&&!r.isAnonymous&&this.authService.isFeatureAllowed(Re.CURSOR)){let a=JSON.parse(JSON.stringify(r));this.commonDbService.updateData({feature:"cursor",properties:{documentId:i?.documentId??"",organizationId:i?.organizationId??"",id:r.userSnippylyId,skipFirestore:!0},data:JSON.parse(JSON.stringify(T(I({},a),{timestamp:this.timestamp})))})}}catch(r){this.loggingService.catch("Error in updateUserStatusOnDocumentChange:",r)}})}updateUserOnLocationChange(e){return ee(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: updateUserOnLocationChange","color: green;");try{let i=this.cursorUser$.value;if(i.location=e?e.location:null,i.locationId=e?e?.locationId:null,this.documentPaths&&i&&i.userId&&!i.isAnonymous&&this.authService.isFeatureAllowed(Re.CURSOR)){let r=JSON.parse(JSON.stringify(i));this.commonDbService.updateData({feature:"cursor",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",id:i.userSnippylyId,skipFirestore:!0},data:JSON.parse(JSON.stringify(T(I({},r),{timestamp:this.timestamp})))})}}catch(i){this.loggingService.catch("Error in updateUserOnLocationChange:",i)}})}updateOnAllowedFeatureListChange(){try{this.configService.getConfig$().subscribe(e=>{if(e&&e.featureAllowList?.length){let i=this.cursorUser$.value,r=!1;if(e.featureAllowList.includes(Re.CURSOR)?i?.onlineStatus!==U.PRESENCE_STATUS_ONLINE&&(i.onlineStatus=U.PRESENCE_STATUS_ONLINE,r=!0):i?.onlineStatus!==U.PRESENCE_STATUS_OFFLINE&&(i.onlineStatus=U.PRESENCE_STATUS_OFFLINE,r=!0),r&&this.documentPaths&&i&&i.userId&&!i.isAnonymous){let a=JSON.parse(JSON.stringify(i));this.commonDbService.updateData({feature:"cursor",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",id:i.userSnippylyId,skipFirestore:!0},data:JSON.parse(JSON.stringify(T(I({},a),{timestamp:this.timestamp})))})}}})}catch(e){this.loggingService.catch("Error in updateOnAllowedFeatureListChange:",e)}}updateOnDatabaseDisconnect(){return this.loggingService.log("%c[WB] Calling FUNCTION: updateOnDatabaseDisconnect","color: green;"),Wn(this.afAuth).pipe(Ne(e=>!!e),ge(e=>this.docService.getDocumentPaths$().pipe(ce(i=>e))),In(e=>ee(this,null,function*(){try{if(this.documentPaths&&e){let i=yield ad(e,!0).catch(a=>null);if(!i)return;let{user:r}=i.claims;if(!r?.isAnonymous){let a=on(this.db,`${this.documentPaths.cursor}/${e.uid}`);cl(a).update({onlineStatus:U.PRESENCE_STATUS_OFFLINE,comment:"",timestamp:this.timestamp}).catch(s=>{this.loggingService.catch("Error in updateOnDatabaseDisconnect:",s)})}}}catch(i){this.loggingService.catch("Error in updateOnDatabaseDisconnect:",i)}})))}signOutUser(e){return new Promise((i,r)=>{try{this.documentPaths&&e?this.commonDbService.dbListener({feature:"cursor",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,id:e.uid,skipFirestore:!0}}).pipe(Je(1)).subscribe(a=>{a?.data?this.commonDbService.updateData({feature:"cursor",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",id:e.uid,skipFirestore:!0},callback:()=>{i(null)},data:JSON.parse(JSON.stringify(T(I({},a?.data??{}),{timestamp:this.timestamp,onlineStatus:U.PRESENCE_STATUS_OFFLINE})))}):i(null)},a=>{this.loggingService.catch("Error in signOutUser subscription: ",a),r(a)}):i(null)}catch(a){this.loggingService.catch("Error in signOutUser:",a),r(a)}})}setInactivityTime(e){this.inactivityTime=e,this.analyticsService.trackEvent(Z.Events.Cursor.CURSOR_SET_CUSTOM_INACTIVITY_TIMER,{inactivityTime:this.inactivityTime})}setAllowedElementIds(e){this.allowedElementIds$.next(e||[])}getAllowedElementIds(){return this.allowedElementIds$.asObservable()}isElementInsideAllowedElements(e){try{return this.domService.isElementInsideListedElementIds(e,this.allowedElementIds$.value)}catch(i){return this.loggingService.catch("Error in CursorService isElementInsideAllowedElements: ",i),!1}}get timestamp(){return this.commonDbService.getServerTimestamp()}};o.\u0275fac=function(i){return new(i||o)(J(Qe),J($t),J(Cm),J(lt),J(vi),J(gn),J(Fe),J(pn),J(je),J(y),J(bn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var HM=class extends li{constructor(o){super(o),this.getService(y).log("%c[WB] Creating CLASS: CursorElement","color: blue;"),this.getLiveCursorsOnCurrentDocument=this._getOnlineUsersOnCurrentDocument,this.getOnlineUsersOnCurrentDocument=this._getOnlineUsersOnCurrentDocument,this.setInactivityTime=this._setInactivityTime,this.allowedElementIds=this._allowedElementIds}_getOnlineUsersOnCurrentDocument(){this.getService(y).log("%c[WB] Calling FUNCTION: getOnlineUsersOnCurrentDocument","color: green;");try{return this.trackEvent(Z.Events.Cursor.GET_LIVE_CURSORS_ON_CURRENT_DOCUMENT_TRIGGERED),this.getService(qv).getLiveCursorsOnCurrentDocument()}catch(o){return this.getService(y).catch("Error in _getOnlineUsersOnCurrentDocument: ",o),re(null)}}_setInactivityTime(o){this.getService(y).log("%c[WB] Calling FUNCTION: _setInactivityTime","color: green;");try{this.trackEvent(Z.Events.Cursor.SET_INACTIVITY_TIME_TRIGGERED,{payload:{time:o}}),isNaN(o)?this.getService(y).catch("Error in setInactivityTime: ","Provided value is not a number."):this.getService(qv).setInactivityTime(o)}catch(t){this.getService(y).catch("Error in setInactivityTime: ",t)}}_allowedElementIds(o){this.getService(y).log("%c[WB] Calling FUNCTION: allowedElementIds","color: green;");try{this.trackEvent(Z.Events.Cursor.ALLOWED_ELEMENT_IDS_TRIGGERED,{payload:{elementIds:o}}),this.getService(qv).setAllowedElementIds(o)}catch(t){this.getService(y).catch("Error in allowedElementIds: ",t)}}};var zM=class extends li{constructor(o){super(o),this.getService(y).log("%c[WB] Creating CLASS: DocElement","color: blue;"),this.getDocumentMetadata=this._getDocumentMetadata}_getDocumentMetadata(){this.getService(y).log("%c[WB] Calling FUNCTION: getDocumentMetadata","color: green;");try{return this.trackEvent(Z.Events.Doc.GET_DOCUMENT_METADATA_TRIGGERED),this.getService(lt).getDocumentMetadata$()}catch(o){return this.getService(y).catch("Error in getDocumentMetadata: ",o),re(null)}}};var mr=(()=>{let o=class o{constructor(e,i,r,a,s,c,p,h,_,E,D,B,G){this.afAuth=e,this.analyticsService=i,this.authService=r,this.databaseService=a,this.docService=s,this.configService=c,this.domService=p,this.huddleUtilsService=h,this.functions=_,this.loggingService=E,this.notificationService=D,this.commonDbService=B,this.usersService=G,this.documentPaths=null,this.localStream$=new fe(null),this.peerConnectionMap={},this.localStream=new MediaStream,this.screenSharingStream=new MediaStream,this.screenSharingStream$=new fe(null),this.remoteStreamMap={},this.remoteStreamMap$=new fe(null),this.localStreamState$=new fe({}),this.peerConnectionStateMap={},this.peerConnectionStateMap$=new fe({}),this.hudleToolComponentId$=new fe(null),this.attendees$=new fe([]),this.invitees$=new fe([]),this.huddleJoined$=new fe(!1),this.userHuddleStartTime$=new fe(null),this.messages$=new fe([]),this.messagesPanelVisible$=new fe(!1),this.huddleOnCursorMode$=new fe(!1),this.flockModeOnAvatarClickEnabled$=new fe(!1),this.chatEnabled$=new fe(!0),this.huddleOnCursorModeByAttendeeId$=new fe({}),this.huddleCursorAvailableByAttendeeId$=new fe({}),this.remoteStreamsByUserId$=new fe({}),this.messagesSubscription=null,this.huddleJoined=!1,this.onAnswerConnectionIdHistory={},this.onOfferUidHistory={},this.senders={},this.db=Ci(),this.dbRefsRemoveOnDropCall=[],this.servers={iceServers:[{urls:["stun:stun1.l.google.com:19302","stun:stun2.l.google.com:19302"]}]},this.databaseService.getDb().pipe(Ne(X=>!!X),Je(1)).subscribe(X=>{try{X&&(this.db=X,this.isHuddleTagInstalled()&&(sessionStorage.getItem("skipTwilioIceServers")||this.getTwilioIceServers()),this.getUser(),this.getDocumentPaths())}catch(he){this.loggingService.catch("Error in HuddleService getDb:",he)}},X=>{this.loggingService.catch("Error in HuddleService getDb subscription: ",X)}),this.docService.addPreDocumentIdChangeFunction("huddle-service",X=>ee(this,null,function*(){this.huddleJoined$.value&&(yield this.dropCall(),yield this.removeLocalStream(),yield this.removeAttendee(),this.attendees$.next([]))})),this.getAttendees().subscribe(),this.getInvitees().subscribe(),this.localStream$.subscribe(X=>{X&&(this.localStream=X)}),this.screenSharingStream$.subscribe(X=>{X&&(this.screenSharingStream=X)}),this.configService.getConfig$().subscribe(X=>{try{!X?.featureAllowList?.find(Ie=>Ie===Re.CURSOR)&&this.huddleOnCursorMode$.next(!1)}catch(he){this.loggingService.catch("Error in HuddleService configService.getConfig$:",he)}},X=>{this.loggingService.catch("Error in HuddleService configService.getConfig$ subscription: ",X)}),this.attendees$.subscribe(X=>{try{if(X?.length){if(this.huddleOnCursorMode$?.value){let he=this.huddleOnCursorModeByAttendeeId$.getValue()||{};X.forEach(Ie=>{he[Ie.userSnippylyId]=!0}),this.huddleOnCursorModeByAttendeeId$.next(he)}this.huddleJoined$?.value&&(X?.find(he=>he?.huddleOnCursorMode)?this.addCursorTag():this.removeCursorTag())}}catch(he){this.loggingService.catch("Error in HuddleService attendees$:",he)}},X=>{this.loggingService.catch("Error in HuddleService attendees$ subscription: ",X)}),Dn([this.huddleJoined$,this.huddleOnCursorMode$]).subscribe(([X,he])=>{try{if(X){if(he){let Ie=this.attendees$.getValue()||[],Me=this.huddleOnCursorModeByAttendeeId$.getValue()||{};Ie.forEach(Le=>{Me[Le.userSnippylyId]=!0}),document?.body?.setAttribute(U.ATTRIBUTES.VELT_HUDDLE_ON_CURSOR_MODE,"true")}else this.huddleOnCursorModeByAttendeeId$.next({}),document?.body?.removeAttribute(U.ATTRIBUTES.VELT_HUDDLE_ON_CURSOR_MODE);this.updateHuddleOnCursorMode()}else this.removeCursorTag(),document?.body?.removeAttribute(U.ATTRIBUTES.VELT_HUDDLE_ON_CURSOR_MODE)}catch(Ie){this.loggingService.catch("Error in HuddleService huddleJoined$:",Ie)}},X=>{this.loggingService.catch("Error in HuddleService huddleJoined$ subscription: ",X)}),this.huddleOnCursorModeByAttendeeId$.subscribe(X=>{try{this.huddleJoined&&(Object.keys(X).length?this.addCursorTag():this.removeCursorTag())}catch(he){this.loggingService.catch("Error in HuddleService huddleOnCursorModeByAttendeeId$:",he)}},X=>{this.loggingService.catch("Error in HuddleService huddleOnCursorModeByAttendeeId$ subscription: ",X)}),this.authService.addPreSignOutFuction("huddle-signout",this.signOutUser.bind(this))}isHuddleTagInstalled(){try{return!!document?.querySelector(`${U.TAGS.VELT_HUDDLE}`)||!!document?.querySelector(`${U.TAGS.SNIPPYLY_HUDDLE}`)}catch(e){return this.loggingService.catch("Error in HuddleService isHuddleTagInstalled:",e),!1}}getTwilioIceServers(){return ee(this,null,function*(){try{let i=(yield Cr(this.functions,Zn.cloudFunction.getIceServers,{timeout:12e5})())?.data;i&&i?.iceServers&&(this.servers.iceServers=i.iceServers)}catch(e){this.loggingService.catch("Error in HuddleService getTwilioIceServers:",e)}})}getRemoteStream(){return this.loggingService.log("%c[WB] Calling FUNCTION: getRemoteStream","color: green;"),this.remoteStreamMap$.asObservable()}getPeerConnectionStateMap(){return this.loggingService.log("%c[WB] Calling FUNCTION: getPeerConnectionStateMap","color: green;"),this.peerConnectionStateMap$.asObservable()}getLocalStreamState(){return this.loggingService.log("%c[WB] Calling FUNCTION: getLocalStreamState","color: green;"),this.localStreamState$.asObservable()}getScreenSharingStream(){return this.loggingService.log("%c[WB] Calling FUNCTION: getScreenSharingStream","color: green;"),this.screenSharingStream$.asObservable()}getAttendees(){return Wn(this.afAuth).pipe(Ne(e=>!!e),ce(e=>({firebaseUser:e})),ge(e=>this.configService.getConfig$().pipe(Ne(i=>!!i),ce(i=>T(I({},e),{config:i})))),ge(e=>this.authService.getUser$().pipe(ce(i=>T(I({},e),{user:i})))),ge(e=>Xi(e.config,e.user,Re.HUDDLE)?re(T(I({},e),{allowed:!0})):(this.loggingService.warn("Huddle feature is not allowed."),re(T(I({},e),{allowed:!1})))),ge(e=>this.docService.getDocumentPaths$().pipe(ce(i=>(this.documentPaths=i,e)))),ge(e=>e?.allowed?e?.user?.isAnonymous?re(null):this.documentPaths?.huddle?this.commonDbService.dbListener({feature:"allHuddleAttendees",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,skipFirestore:!0}}).pipe(ce(i=>i?.data),ce(i=>i?(this.attendees$.next(Object.values(i)),Object.values(i)):(this.attendees$.next([]),null))):re(null):re([])))}getInvitees(){try{return Wn(this.afAuth).pipe(Ne(e=>!!e),ce(e=>({firebaseUser:e})),ge(e=>this.configService.getConfig$().pipe(Ne(i=>!!i),ce(i=>T(I({},e),{config:i})))),ge(e=>this.authService.getUser$().pipe(ce(i=>T(I({},e),{user:i})))),ge(e=>Xi(e.config,e.user,Re.HUDDLE)?re(T(I({},e),{allowed:!0})):(this.loggingService.warn("Huddle feature is not allowed."),re(T(I({},e),{allowed:!1})))),ge(e=>this.docService.getDocumentPaths$().pipe(ce(i=>(this.documentPaths=i,e)))),ge(e=>e?.allowed?e?.user?.isAnonymous?re(null):this.documentPaths?.huddle?this.commonDbService.dbListener({feature:"allHuddleInvitees",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,skipFirestore:!0}}).pipe(ce(i=>i?.data),ce(i=>i?(this.invitees$.next(Object.values(i)),Object.values(i)):(this.invitees$.next([]),null))):re(null):re([])))}catch(e){return this.loggingService.catch("Error in HuddleService getInvitees:",e),re([])}}clearHuddleInvitees(){try{this.documentPaths?.huddle&&this.commonDbService.deleteData({feature:"allHuddleInvitees",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,skipFirestore:!0}})}catch(e){this.loggingService.catch("Error in HuddleService clearHuddleInvitees:",e)}}getUser(){this.loggingService.log("%c[WB] Calling FUNCTION: getUser","color: green;"),this.authService.getUser$().pipe(Ne(e=>!!e)).subscribe(e=>{e&&(this.user=e)},e=>{this.loggingService.catch("Error in getUser: ",e)})}getDocumentPaths(){this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentPaths","color: green;"),this.docService.getDocumentPaths$().pipe(In(e=>{this.documentPaths=e})).subscribe(()=>{},e=>{this.loggingService.catch("Error in getDocumentPaths: ",e)})}setHuddleToolComponentId(e){this.hudleToolComponentId$.next(e||null)}getHuddleToolComponentId(){return this.hudleToolComponentId$.asObservable()}joinHuddle(e){return ee(this,null,function*(){try{this.loggingService.log("%c[WB] Calling FUNCTION: joinHuddle","color: green;"),this.documentPaths?.huddle?(this.initialHuddleType=e,this.huddleJoined=!0,this.huddleJoined$.next(!0),this.initLocalStreams(),this.huddle=on(this.db,this.documentPaths?.huddle),this.iceCandidates=on(this.db,`${this.documentPaths?.huddle}/iceCandidates`),this.connections=on(this.db,`${this.documentPaths?.huddle}/connections`),this.attendees=on(this.db,`${this.documentPaths?.huddle}/attendees`),this.messages=on(this.db,`${this.documentPaths?.huddle}/messages`),this.setHuddleListener(),this.addAttendee(),this.callExistingAttendees(),this.userHuddleStartTime$.next(new Date().getTime())):this.loggingService.catch("Error in joinHuddle: documentPaths not found")}catch(i){this.loggingService.catch("Error in HuddleService joinHuddle:",i)}})}initLocalStreams(){try{if(!this.localStream$?.value?.getTracks()?.length){let e=new MediaStream([this.silence(),this.black()]);this.localStream$.next(e)}if(!this.screenSharingStream$?.value?.getTracks()?.length){let e=new MediaStream([this.black()]);this.screenSharingStream$.next(e)}}catch(e){this.loggingService.catch("Error in HuddleService initLocalStreams:",e)}}setHuddleListener(){this.loggingService.log("%c[WB] Calling FUNCTION: setHuddleListener","color: green;"),gu(this.connections,e=>{try{if(e.exists()){let i=e.val();Object.values(i).forEach(a=>{let s=Object.values(a);if(s&&s.length>0){let p=s[0]?.connectionId;this.onHuddleSnapshot(p,a)}}),Object.keys(this.remoteStreamMap).forEach(a=>ee(this,null,function*(){i[a]||(this.remoteStreamMap[a]&&Object.values(this.remoteStreamMap[a]).forEach(s=>{s.getTracks().forEach(c=>{c.stop()})}),delete this.remoteStreamMap[a],yield this.removeIceCandidates(a))})),this.remoteStreamMap$.next(this.remoteStreamMap)}else Object.keys(this.remoteStreamMap).forEach(i=>ee(this,null,function*(){Object.values(this.remoteStreamMap[i]).forEach(r=>{r.getTracks().forEach(a=>{a.stop()})}),yield this.removeIceCandidates(i)})),this.remoteStreamMap={},this.remoteStreamMap$.next(this.remoteStreamMap)}catch(i){this.loggingService.catch("Error in HuddleService setHuddleLister onValue:",i)}}),SL(this.iceCandidates).subscribe(e=>{try{e.event==="child_added"&&this.onIceCandidateSnapshot(e.snapshot)}catch(i){this.loggingService.catch("Error in HuddleService iceCandidates stateChanges:",i)}}),SL(this.attendees).subscribe(e=>{try{if(e.event==="child_removed"){let i=e?.snapshot?.val();if(i){delete this.onOfferUidHistory[i?.userSnippylyId];let r=this.getCombinedId(this.user.userSnippylyId,i?.userSnippylyId);delete this.onAnswerConnectionIdHistory[r],this.closeConnection(r)}}}catch(i){this.loggingService.catch("Error in HuddleService iceCandidates stateChanges:",i)}}),this.messagesSubscription&&this.messagesSubscription.unsubscribe(),this.messagesSubscription=new Ft(e=>{let i=gu(this.messages,r=>e.next(r),r=>e.error(r));return()=>i()}).pipe(ge(e=>this.usersService.getUserById$().pipe(ce(()=>e))),ge(e=>{if(e.exists()){let i=e.val();return bo(this.huddleUtilsService.resolveUsersFromHuddleMessages(Object.values(i||{})))}return re([])}),Ln(e=>(this.loggingService.catch("Error in HuddleService messages onValue:",e),re([])))).subscribe(e=>{this.messages$.next(e)})}onHuddleSnapshot(e,i){try{this.loggingService.log("%c[WB] Calling FUNCTION: onHuddleSnapshot","color: green;"),i.offerData&&!i.answerData&&i.offerData.from!==this.user.userSnippylyId&&i.offerData.to===this.user.userSnippylyId&&!(e in this.peerConnectionMap)&&!this.onOfferUidHistory[i.offerData.from]?(this.loggingService.log("offer received"),this.loggingService.log(i),this.onOfferUidHistory[i.offerData.from]=!0,this.onOffer(e,i.offerData)):i.answerData&&i.answerData.from!==this.user.userSnippylyId&&i.answerData.to===this.user.userSnippylyId&&this.peerConnectionMap[e]&&this.peerConnectionMap[e]?.connectionState!=="connected"&&!this.onAnswerConnectionIdHistory[e]&&(this.loggingService.log("answer received"),this.loggingService.log(i),this.onAnswerConnectionIdHistory[e]=!0,this.onAnswer(e,i.answerData))}catch(r){this.loggingService.catch("Error in HuddleService onHuddleSnapshot:",r)}}onIceCandidateSnapshot(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: onIceCandidateSnapshot","color: green;"),this.loggingService.log("ice candidate received");let i=e.val(),r=i.connectionId;i?.from!==this.user.userSnippylyId&&r in this.peerConnectionMap&&this.onIceCandidateChange(r,i)}catch(i){this.loggingService.catch("Error in HuddleService onIceCandidateSnapshot:",i)}}onOffer(e,i){return ee(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: onOffer","color: green;"),this.createPeerConnection(e,i.from)){this.addLocalStreamToPeerConnection(e,!0);let a=i.offer;yield this.setRemoteDescription(e,a),yield this.sendAnswer(e,i.from)}}catch(r){this.loggingService.catch("Error in HuddleService onOffer:",r)}})}sendAnswer(e,i){return ee(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: sendAnswer","color: green;"),this.loggingService.log(e),this.documentPaths?.huddle&&e){let r=yield this.peerConnectionMap[e].createAnswer();yield this.setLocalDescription(e,r);let s={answer:{type:r.type,sdp:r.sdp},from:this.user.userSnippylyId,connectionId:e,to:i},c=on(this.db,`${this.documentPaths?.huddle}/connections/${e}`);this.dbRefsRemoveOnDropCall.push({type:"connection",dbRef:c}),yield jA(c,{answerData:s}),cl(c).remove()}else this.loggingService.catch("Error in sendAnswer: documentPaths not found")}catch(r){this.loggingService.catch("Error in HuddleService onHuddleSnapshot:",r)}})}onAnswer(e,i){return ee(this,null,function*(){try{this.loggingService.log("%c[WB] Calling FUNCTION: onAnswer","color: green;");let r=i.answer;yield this.setRemoteDescription(e,r)}catch(r){this.loggingService.catch("Error in HuddleService onAnswer:",r)}})}onIceCandidateChange(e,i){return ee(this,null,function*(){try{this.loggingService.log("%c[WB] Calling FUNCTION: onIceCandidateChange","color: green;");let r=i.candidate;this.loggingService.log("onIceCandidateChange",r),yield this.peerConnectionMap[e].addIceCandidate(new RTCIceCandidate(r))}catch(r){this.loggingService.catch("Error in HuddleService onIceCandidateChange:",r)}})}setRemoteDescription(e,i){return ee(this,null,function*(){try{this.loggingService.log("%c[WB] Calling FUNCTION: setRemoteDescription","color: green;"),yield this.peerConnectionMap[e].setRemoteDescription(new RTCSessionDescription(i))}catch(r){this.loggingService.catch("Error in HuddleService setRemoteDescription:",r)}})}addAttendee(){return ee(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: addAttendee","color: green;"),this.documentPaths?.huddle&&this.user?.userSnippylyId){let e=T(I({},this.user),{timestamp:this.timestamp,streamMetadata:{webcam:this.localStream?.id,screen:this.screenSharingStream?.id},initialHuddleType:this.initialHuddleType,huddleOnCursorMode:this.huddleOnCursorMode$?.value});e=this.huddleUtilsService.formatHuddleAttendeeData(e);let i=on(this.db,`${this.documentPaths?.huddle}/attendees/${this.user.userSnippylyId}`);yield Of(i,JSON.parse(JSON.stringify(e))),this.dbRefsRemoveOnDropCall.push({type:"attendee",dbRef:i}),cl(i).remove(),yield this.updateUserHuddleState()}else this.loggingService.catch("Error in addAttendee: documentPaths not found")}catch(e){this.loggingService.catch("Error in HuddleService addAttendee:",e)}})}callExistingAttendees(){try{this.loggingService.log("%c[WB] Calling FUNCTION: callExistingAttendees","color: green;"),hee(this.attendees).pipe(Je(1)).subscribe(e=>{e&&e.length>1?(e.forEach(i=>{i.userSnippylyId!==this.user.userSnippylyId&&!this.onOfferUidHistory[i.userSnippylyId]&&(this.loggingService.log("calling"),this.loggingService.log(i),this.initOffer(i.userSnippylyId))}),this.addLocalStreamToAllPeerConnections()):this.deleteMessages()})}catch(e){this.loggingService.catch("Error in HuddleService callExistingAttendees:",e)}}addLocalStreamToAllPeerConnections(){return ee(this,null,function*(){try{this.loggingService.log("%c[WB] Calling FUNCTION: addLocalStreamToAllPeerConnections","color: green;"),Object.keys(this.senders).forEach(e=>{this.loggingService.log(this.senders[e]),this.localStream.getTracks().forEach(i=>{this.loggingService.log(i),this.senders[e].replaceTrack(i)})})}catch(e){this.loggingService.catch("Error in HuddleService addLocalStreamToAllPeerConnections:",e)}})}initOffer(e){return ee(this,null,function*(){try{this.loggingService.log("%c[WB] Calling FUNCTION: initOffer","color: green;");let i=this.createPeerConnection(null,e);i&&(this.addLocalStreamToPeerConnection(i,!1),yield this.sendOffer(i,e))}catch(i){this.loggingService.catch("Error in HuddleService initOffer:",i)}})}createPeerConnection(e,i){try{return this.loggingService.log("%c[WB] Calling FUNCTION: createPeerConnection","color: green;"),e||(e=this.getCombinedId(this.user?.userSnippylyId,i)),e in this.peerConnectionMap?null:(this.loggingService.log("creating pc"),this.peerConnectionMap[e]=new RTCPeerConnection(this.servers),this.peerConnectionMap[e].onicecandidateerror=r=>{this.loggingService.log("Huddle: onicecandidateerror",r)},this.peerConnectionMap[e].onicecandidate=r=>{if(this.loggingService.log("pc onicecandidate"),r.candidate){let a={candidate:r.candidate.toJSON(),from:this.user.userSnippylyId,connectionId:e},s=fee(this.iceCandidates,a);this.dbRefsRemoveOnDropCall.push({type:"iceCandidate",dbRef:s}),cl(s).remove()}},this.peerConnectionMap[e].ontrack=r=>{this.loggingService.log("pc ontrack"),this.onTrack(e,r)},this.peerConnectionMap[e].onconnectionstatechange=r=>ee(this,null,function*(){this.logStatuses("onconnectionstatechange",e,r),this.peerConnectionMap[e].connectionState==="failed"&&(this.removeConnection(e),this.closeConnection(e),this.checkForRemovingAttendee())}),this.peerConnectionMap[e].onicegatheringstatechange=r=>ee(this,null,function*(){this.logStatuses("onicegatheringstatechange",e,r)}),this.peerConnectionMap[e].onsignalingstatechange=r=>ee(this,null,function*(){this.logStatuses("onsignalingstatechange",e,r)}),this.peerConnectionMap[e].oniceconnectionstatechange=r=>ee(this,null,function*(){this.loggingService.log("pc oniceconnectionstatechange"),this.logStatuses("oniceconnectionstatechange",e,r);try{this.peerConnectionStateMap[e]=this.peerConnectionMap[e].iceConnectionState,this.peerConnectionStateMap$.next(this.peerConnectionStateMap),this.peerConnectionMap[e]?.iceConnectionState==="connected"?(this.loggingService.log("connected"),this.updateTransceiverDirection(e)):this.peerConnectionMap[e]?.iceConnectionState==="disconnected"?this.loggingService.log("Disconnected"):this.peerConnectionMap[e].iceConnectionState==="closed"&&(this.loggingService.log("Closed"),this.closeConnection(e))}catch(a){this.loggingService.catch("Error in HuddleService oniceconnectionstatechange:",a)}}),this.peerConnectionMap[e].onnegotiationneeded=()=>{this.loggingService.log("pc onnegotiationneeded"),this.logStatuses("onnegotiationneeded",e)},e)}catch(r){return this.loggingService.catch("Error in HuddleService createPeerConnection:",r),""}}logStatuses(e,i,r){let a={};["connectionState","iceConnectionState","iceGatheringState","signalingState"].forEach(c=>{a[c]=this.peerConnectionMap[i][c]}),this.loggingService.log("Huddle: logStatues: ",i,e,a,r,this.peerConnectionMap[i])}checkForRemovingAttendee(){return ee(this,null,function*(){try{this.documentPaths?.huddle&&this.user?.userSnippylyId&&(Object.keys(this.peerConnectionMap)?.length||(this.commonDbService.deleteData({feature:"huddleAttendee",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,id:this.user?.userSnippylyId,skipFirestore:!0}}),this.joinHuddle(this.initialHuddleType)))}catch(e){this.loggingService.catch("Error in HuddleService checkForRemovingAttendee:",e)}})}closeConnection(e){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: closeConnection","color: green;"),this.peerConnectionMap[e]){let i=this.peerConnectionMap[e];i.getTransceivers()?.forEach(a=>{a.stop()}),i.getReceivers()?.forEach(a=>{a.track?.stop()}),i.close(),delete this.peerConnectionMap[e],delete this.onAnswerConnectionIdHistory[e],delete this.senders[e];let r=e.split("__").find(a=>a!==this.user?.userSnippylyId);r&&delete this.onOfferUidHistory[r]}}catch(i){this.loggingService.catch("Error in HuddleService closeConnection:",i)}}removeConnection(e){return ee(this,null,function*(){try{this.documentPaths?.huddle&&e&&this.commonDbService.deleteData({feature:"huddleConnection",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,id:e,skipFirestore:!0}})}catch(i){this.loggingService.catch("Error in HuddleService removeConnection:",i)}})}addLocalStreamToPeerConnection(e,i){try{this.loggingService.log("%c[WB] Calling FUNCTION: addLocalStreamToPeerConnection","color: green;"),i?(this.localStream.getTracks().forEach(r=>{this.peerConnectionMap[e].addTrack(r,this.localStream)}),this.screenSharingStream?.getVideoTracks()?.forEach(r=>{this.peerConnectionMap[e].addTrack(r,this.screenSharingStream)})):(this.localStream.getTracks().forEach(r=>{this.peerConnectionMap[e].addTrack(r,this.localStream)}),this.screenSharingStream?.getVideoTracks()?.forEach(r=>{this.peerConnectionMap[e].addTrack(r,this.screenSharingStream)}))}catch(r){this.loggingService.catch("Error in HuddleService addLocalStreamToPeerConnection:",r)}}updateTransceiverDirection(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: updateTransceiverDirection","color: green;");let i=this.peerConnectionMap[e].getTransceivers();this.loggingService.log(i),i.map(r=>{this.loggingService.log(r.currentDirection),r.currentDirection!=="sendrecv"&&(r.direction="sendrecv"),this.senders[e]=r.sender})}catch(i){this.loggingService.catch("Error in HuddleService updateTransceiverDirection:",i)}}generateKey(){this.loggingService.log("%c[WB] Calling FUNCTION: generateKey","color: green;");let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",i="";for(let r=0;r<20;r++)i+=e.charAt(Math.floor(Math.random()*e.length));return i}getCombinedId(e,i){try{return e.localeCompare(i)===-1?`${e}__${i}`:`${i}__${e}`}catch(r){return this.loggingService.catch("Error in HuddleService getCombinedId:",r),""}}sendOffer(e,i){return ee(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: sendOffer","color: green;"),this.documentPaths?.huddle&&e){this.onOfferUidHistory[i]=!0;let r=yield this.peerConnectionMap[e].createOffer();yield this.setLocalDescription(e,r);let a={sdp:r.sdp,type:r.type};i||(i="all");let s={offer:a,from:this.user.userSnippylyId,connectionId:e,to:i},c=on(this.db,`${this.documentPaths?.huddle}/connections/${e}`);yield Of(c,{offerData:s}),this.dbRefsRemoveOnDropCall.push({type:"connection",dbRef:c}),cl(c).remove()}}catch(r){this.loggingService.catch("Error in HuddleService sendOffer:",r)}})}setLocalDescription(e,i){return ee(this,null,function*(){try{this.loggingService.log("%c[WB] Calling FUNCTION: setLocalDescription","color: green;"),yield this.peerConnectionMap[e].setLocalDescription(i)}catch(r){this.loggingService.catch("Error in HuddleService setLocalDescription:",r)}})}onTrack(e,i){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: onTrack","color: green;"),this.remoteStreamMap[e]||(this.remoteStreamMap[e]={}),this.loggingService.log(i.receiver.track),i?.streams?.length){this.remoteStreamMap[e][i.streams[0].id]=i.streams[0];let r=e.split("__").find(s=>s!==this.user?.userSnippylyId),a=this.attendees$.value?.find(s=>s?.userSnippylyId===r);a&&(a?.streamMetadata?.webcam===i.streams[0].id&&(this.remoteStreamMap[e].webcam=i.streams[0]),a?.streamMetadata?.screen===i.streams[0].id&&(this.remoteStreamMap[e].screen=i.streams[0])),this.remoteStreamMap$.next(this.remoteStreamMap)}}catch(r){this.loggingService.catch("Error in HuddleService onTrack:",r)}}toggleScreenSharing(e){return ee(this,null,function*(){try{if(e)this.screenSharingStream=yield navigator.mediaDevices?.getDisplayMedia({video:!0}),Object.keys(this.peerConnectionMap).forEach(i=>{this.peerConnectionMap[i].getSenders().find(s=>s?.track?.kind==this.screenSharingStream?.getVideoTracks()[0].kind)?.replaceTrack(this.screenSharingStream?.getVideoTracks()[0])});else{let i=this.localStream;Object.keys(this.peerConnectionMap).forEach(r=>{this.peerConnectionMap[r].getSenders().find(c=>c?.track?.kind==i.getVideoTracks()[0].kind)?.replaceTrack(i.getVideoTracks()[0])}),this.screenSharingStream?.getTracks().forEach(r=>r.stop())}}catch(i){this.loggingService.catch("Error in HuddleService toggleScreenSharing:",i)}})}setLocalStream(e){return ee(this,null,function*(){try{if(this.localStream=new MediaStream([this.silence(),this.black()]),e?.audio||e?.video){let i=e,r=ac();e?.audio&&(e?.audio instanceof Object?i.audio=T(I({},e?.audio),{deviceId:r?.selectedAudioDevice?.deviceId}):i.audio={deviceId:r?.selectedAudioDevice?.deviceId}),e?.video&&(e?.video instanceof Object?i.video=T(I({},e?.video),{deviceId:r?.selectedVideoDevice?.deviceId}):i.video={deviceId:r?.selectedVideoDevice?.deviceId});let a=yield navigator.mediaDevices.getUserMedia(i);a?.getAudioTracks()?.length&&(this.localStream.getAudioTracks().forEach(s=>this.localStream.removeTrack(s)),a.getAudioTracks().forEach(s=>this.localStream.addTrack(s))),a?.getVideoTracks()?.length&&(this.localStream.getVideoTracks().forEach(s=>this.localStream.removeTrack(s)),a.getVideoTracks().forEach(s=>this.localStream.addTrack(s)))}this.localStream$.next(this.localStream)}catch(i){this.loggingService.catch("Error in HuddleService setLocalStream:",i)}})}setScreenSharingStream(){return ee(this,null,function*(){try{let e=yield navigator.mediaDevices?.getDisplayMedia({video:!0});e&&this.screenSharingStream$.next(e)}catch(e){this.loggingService.catch("Error in HuddleService setScreenSharingStream:",e)}})}removeLocalStream(){return ee(this,null,function*(){try{this.localStream$?.value&&(this.localStream$.value.getTracks().forEach(i=>{i.stop()}),this.localStream$.next(null))}catch(e){this.loggingService.catch("Error in HuddleService removeLocalStream:",e)}})}toggleLocalStreamAudio(e){return ee(this,null,function*(){try{let i=this.localStream$.value;if(i){let r=i.getAudioTracks()[0];if(r.enabled&&!e)r.stop(),i.getAudioTracks()?.forEach(a=>{i.removeTrack(a)}),i.addTrack(this.silence()),this.analyticsService.trackEvent(Z.Events.Huddle.HUDDLE_AUDIO_MUTED,{huddleType:this.initialHuddleType,totalUsers:this.getHuddleAttendees()?.length||0,totalUserHuddleDuration:this.getTotalUserHuddleDuration(),huddleSnippylyUserIds:this.getHuddleAttendees()?.map(a=>a?.userSnippylyId),huddleClientUserIds:this.getHuddleAttendees()?.map(a=>a?.userId)});else{let a=ac(),s=yield navigator.mediaDevices.getUserMedia({audio:{deviceId:a?.selectAudioDevice?.deviceId}});s&&(i.getAudioTracks()?.forEach(c=>{i.removeTrack(c)}),s.getAudioTracks()?.forEach(c=>{i.addTrack(c)}),this.analyticsService.trackEvent(Z.Events.Huddle.HUDDLE_AUDIO_UNMUTED,{huddleType:this.initialHuddleType,totalUsers:this.getHuddleAttendees()?.length||0,totalUserHuddleDuration:this.getTotalUserHuddleDuration(),huddleSnippylyUserIds:this.getHuddleAttendees()?.map(c=>c?.userSnippylyId),huddleClientUserIds:this.getHuddleAttendees()?.map(c=>c?.userId)}))}Object.keys(this.peerConnectionMap).forEach(a=>{this.peerConnectionMap[a].getSenders().find(p=>p?.track?.kind==i?.getAudioTracks()[0].kind)?.replaceTrack(i?.getAudioTracks()[0])}),this.updateUserHuddleState()}}catch(i){this.loggingService.catch("Error in HuddleService toggleLocalStreamAudio:",i)}})}toggleLocalStreamVideo(e){return ee(this,null,function*(){try{let i=this.localStream$.value;if(i){let r=i.getVideoTracks()[0];if(r.enabled&&!e)r.stop(),i.getVideoTracks()?.forEach(a=>{i.removeTrack(a)}),i.addTrack(this.black()),this.analyticsService.trackEvent(Z.Events.Huddle.HUDDLE_VIDEO_TURNED_OFF,{huddleType:this.initialHuddleType,totalUsers:this.getHuddleAttendees()?.length||0,totalUserHuddleDuration:this.getTotalUserHuddleDuration(),huddleSnippylyUserIds:this.getHuddleAttendees()?.map(a=>a?.userSnippylyId),huddleClientUserIds:this.getHuddleAttendees()?.map(a=>a?.userId)});else{let a=ac(),s=yield navigator.mediaDevices.getUserMedia({video:{deviceId:a?.selectedVideoDevice?.deviceId}});s&&(i.getVideoTracks()?.forEach(c=>{i.removeTrack(c)}),s.getVideoTracks()?.forEach(c=>{i.addTrack(c)}),this.analyticsService.trackEvent(Z.Events.Huddle.HUDDLE_VIDEO_TURNED_ON,{huddleType:this.initialHuddleType,totalUsers:this.getHuddleAttendees()?.length||0,totalUserHuddleDuration:this.getTotalUserHuddleDuration(),huddleSnippylyUserIds:this.getHuddleAttendees()?.map(c=>c?.userSnippylyId),huddleClientUserIds:this.getHuddleAttendees()?.map(c=>c?.userId)}))}Object.keys(this.peerConnectionMap).forEach(a=>{this.peerConnectionMap[a].getSenders().find(p=>p?.track?.kind==i?.getVideoTracks()[0].kind)?.replaceTrack(i?.getVideoTracks()[0])}),this.updateUserHuddleState()}}catch(i){this.loggingService.catch("Error in HuddleService toggleLocalStreamVideo:",i)}})}toggleLocalScreenSharing(){return ee(this,null,function*(){try{let e=this.screenSharingStream;if(e){if(e.getVideoTracks()[0].enabled)this.stopScreenSharingStream();else{let r=yield navigator.mediaDevices?.getDisplayMedia({video:!0});r&&(e.getVideoTracks()?.forEach(a=>{e.removeTrack(a)}),r.getVideoTracks()?.forEach(a=>{e.addTrack(a),a.onended=()=>{this.stopScreenSharingStream(),this.updateScreenSharingTracksToPeers(),this.updateUserHuddleState()}})),this.screenSharingStream$.next(e),this.analyticsService.trackEvent(Z.Events.Huddle.HUDDLE_SCREENSHARING_STARTED,{huddleType:this.initialHuddleType,totalUsers:this.getHuddleAttendees()?.length||0,totalUserHuddleDuration:this.getTotalUserHuddleDuration(),huddleSnippylyUserIds:this.getHuddleAttendees()?.map(a=>a?.userSnippylyId),huddleClientUserIds:this.getHuddleAttendees()?.map(a=>a?.userId)})}this.updateScreenSharingTracksToPeers(),this.updateUserHuddleState()}}catch(e){this.loggingService.catch("Error in HuddleService toggleLocalScreenSharing:",e)}})}stopScreenSharingStream(){return ee(this,null,function*(){let e=this.screenSharingStream;if(e){let i=e.getVideoTracks()[0];i.enabled&&(i.stop(),e.getVideoTracks()?.forEach(r=>{e.removeTrack(r)}),e.addTrack(this.black()),this.analyticsService.trackEvent(Z.Events.Huddle.HUDDLE_SCREENSHARING_STOPPED,{huddleType:this.initialHuddleType,totalUsers:this.getHuddleAttendees()?.length||0,totalUserHuddleDuration:this.getTotalUserHuddleDuration(),huddleSnippylyUserIds:this.getHuddleAttendees()?.map(r=>r?.userSnippylyId),huddleClientUserIds:this.getHuddleAttendees()?.map(r=>r?.userId)}))}})}updateScreenSharingTracksToPeers(){return ee(this,null,function*(){Object.keys(this.peerConnectionMap).forEach(e=>{let r=this.peerConnectionMap[e].getSenders().filter(a=>a?.track?.kind==this.screenSharingStream?.getVideoTracks()[0].kind);r?.length>1&&r[1]?.replaceTrack(this.screenSharingStream?.getVideoTracks()[0])})})}dropCall(){return ee(this,null,function*(){try{this.messagesSubscription&&this.messagesSubscription.unsubscribe(),this.removeHuddleSessionData(),this.huddleJoined=!1,this.huddleJoined$.next(!1),this.peerConnectionMap&&Object.keys(this.peerConnectionMap).forEach(e=>{let i=this.peerConnectionMap[e];i.getTransceivers()?.forEach(r=>{r.stop()}),i.getSenders()?.forEach(r=>{r.track?.stop()}),i.getReceivers()?.forEach(r=>{r.track?.stop()}),i.close()}),this.peerConnectionMap={},this.dbRefsRemoveOnDropCall.forEach(e=>ee(this,null,function*(){yield VA(e.dbRef)})),this.onOfferUidHistory={},this.onAnswerConnectionIdHistory={},this.senders={},this.peerConnectionStateMap={},this.peerConnectionStateMap$.next(this.peerConnectionStateMap),this.localStream.getTracks().forEach(e=>{e.stop()}),this.screenSharingStream.getTracks().forEach(e=>{e.stop()}),this.localStream=new MediaStream([this.silence(),this.black()]),this.screenSharingStream=new MediaStream([this.black()]),this.localStream$.next(this.localStream),this.screenSharingStream$.next(this.screenSharingStream),this.localStreamState$.next({audioState:!1,videoState:!1,screenSharingState:!1}),this.analyticsService.trackEvent(Z.Events.Huddle.HUDDLE_LEFT,{huddleType:this.initialHuddleType,totalUsers:this.getHuddleAttendees()?.length||0,totalUserHuddleDuration:this.getTotalUserHuddleDuration(),huddleSnippylyUserIds:this.getHuddleAttendees()?.map(e=>e?.userSnippylyId),huddleClientUserIds:this.getHuddleAttendees()?.map(e=>e?.userId)})}catch(e){this.loggingService.catch("Error in HuddleService dropCall:",e)}})}updateHuddleSessionData(e,i,r){try{let a=JSON.parse(sessionStorage.getItem(U.SESSION_STORAGE.SNIPPYLY_HUDDLE_DATA)||"{}");r?sessionStorage.setItem(U.SESSION_STORAGE.SNIPPYLY_HUDDLE_DATA,JSON.stringify(r)):(a[e]=i,sessionStorage.setItem(U.SESSION_STORAGE.SNIPPYLY_HUDDLE_DATA,JSON.stringify(a)))}catch(a){this.loggingService.catch("Error in HuddleService updateHuddleSessionData:",a)}}getHuddleSessionData(){try{return sessionStorage.getItem(U.SESSION_STORAGE.SNIPPYLY_HUDDLE_DATA)?JSON.parse(sessionStorage.getItem(U.SESSION_STORAGE.SNIPPYLY_HUDDLE_DATA)):null}catch(e){return this.loggingService.catch("Error in HuddleService getHuddleSessionData:",e),null}}removeHuddleSessionData(){try{sessionStorage.removeItem(U.SESSION_STORAGE.SNIPPYLY_HUDDLE_DATA)}catch(e){this.loggingService.catch("Error in HuddleService removeHuddleSessionData:",e)}}removeAttendee(){return ee(this,null,function*(){try{if(this.documentPaths?.huddle&&this.user.userSnippylyId){yield this.commonDbService.deleteData({feature:"huddleAttendee",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,id:this.user?.userSnippylyId,skipFirestore:!0}});return}else return}catch(e){return this.loggingService.catch("Error in HuddleService removeAttendee:",e),Promise.resolve(null)}})}updateUserHuddleState(){return ee(this,null,function*(){try{if(this.attendees&&this.user&&this.documentPaths?.huddle){let e=this.getAudioState(),i=this.getVideoState(),r=this.getScreenSharingState();this.localStreamState$.next({audioState:e,videoState:i,screenSharingState:r});let a={audioState:e,videoState:i,screenSharingState:r};yield this.commonDbService.setData({feature:"huddleAttendeeState",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,id:this.user?.userSnippylyId,skipFirestore:!0},data:a})}}catch(e){this.loggingService.catch("Error in HuddleService updateUserHuddleState:",e)}})}updateHuddleOnCursorMode(){return ee(this,null,function*(){try{if(this.attendees&&this.user&&this.documentPaths?.huddle){let e=on(this.db,`${this.documentPaths?.huddle}/attendees/${this.user.userSnippylyId}/huddleOnCursorMode`);yield Of(e,!!this.huddleOnCursorMode$.value)}}catch(e){this.loggingService.catch("Error in HuddleService updateHuddleOnCursorMode:",e)}})}getAudioState(){try{let e=this.localStream$.value;if(e){let i=e?.getAudioTracks();return!!(i?.length?i[0]:null)?.enabled}return!1}catch(e){return this.loggingService.catch("Error in HuddleService getAudioState:",e),!1}}getVideoState(){try{let e=this.localStream$.value;if(e){let i=e?.getVideoTracks();return!!(i?.length?i[0]:null)?.enabled}return!1}catch(e){return this.loggingService.catch("Error in HuddleService getVideoState:",e),!1}}getScreenSharingState(){try{let e=this.screenSharingStream;if(e){let i=e?.getVideoTracks();return!!(i?.length?i[0]:null)?.enabled}return!1}catch(e){return this.loggingService.catch("Error in HuddleService getVideoState:",e),!1}}removeIceCandidates(e){return ee(this,null,function*(){try{if(this.documentPaths?.huddle&&e){let i=yield this.commonDbService?.getData({feature:"allHuddleIceCandidates",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",skipFirestore:!0}});Object.keys(i).length>0&&Object.keys(i).forEach(r=>ee(this,null,function*(){i[r].connectionId===e&&this.commonDbService.deleteData({feature:"huddleIceCandidate",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,id:r,skipFirestore:!0}})}))}}catch(i){this.loggingService.catch("Error in HuddleService dropCall:",i)}})}get timestamp(){return this.commonDbService.getServerTimestamp()}silence(){try{let e=new AudioContext,i=e.createOscillator(),r=i.connect(e.createMediaStreamDestination());return i.start(),Object.assign(r.stream.getAudioTracks()[0],{enabled:!1})}catch(e){this.loggingService.catch("Error in HuddleService silence:",e)}}black({width:e=640,height:i=480}={}){try{let r=Object.assign(document.createElement("canvas"),{width:e,height:i});r.getContext("2d")?.fillRect(0,0,e,i);let a=r.captureStream();return Object.assign(a.getVideoTracks()[0],{enabled:!1})}catch(r){this.loggingService.catch("Error in HuddleService black:",r)}}getInitialHuddleType(){try{return this.initialHuddleType}catch(e){return this.loggingService.catch("Error in HuddleService getInitialHuddleType:",e),null}}getHuddleAttendees$(){try{return this.attendees$.asObservable()}catch(e){return this.loggingService.catch("Error in HuddleService getHuddleAttendees$:",e),re([])}}getHuddleAttendees(){try{return this.attendees$.value}catch(e){return this.loggingService.catch("Error in HuddleService getHuddleAttendees:",e),null}}getHuddleInvitees$(){try{return this.invitees$.asObservable()}catch(e){return this.loggingService.catch("Error in HuddleService getHuddleInvitees$:",e),re([])}}getHuddleInvitees(){try{return this.invitees$.value}catch(e){return this.loggingService.catch("Error in HuddleService getHuddleInvitees:",e),null}}getHuddleStartTime(){try{return this.userHuddleStartTime$.value}catch(e){return this.loggingService.catch("Error in HuddleService getHuddleStartTime:",e),null}}getTotalUserHuddleDuration(){try{return this.userHuddleStartTime$.value?new Date().getTime()-this.userHuddleStartTime$.value:null}catch(e){return this.loggingService.catch("Error in HuddleService gettotalUserHuddleDuration:",e),null}}inviteUsers(e){try{this.updateInvitees(e);let i={};i.notificationSource="huddleInvite",i.huddleInvitees=e,i.huddleType=this.getInitialHuddleType(),this.updateNotificationsDatabase(i)}catch(i){this.loggingService.catch("Error in HuddleService inviteUsers:",i)}}updateInvitees(e){try{if(this.documentPaths?.huddle){let i={};e.forEach(r=>{if(r?.email){let a=Rt(r.email);i[a]=r}}),this.commonDbService.setData({feature:"allHuddleInvitees",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,skipFirestore:!0},data:i})}}catch(i){this.loggingService.catch("Error in HuddleService updateInvitees:",i)}}updateNotificationsDatabase(e={}){try{let i=I({notificationSource:"huddle"},e);this.notificationService.updateNotificationDatabase(i)}catch(i){this.loggingService.catch("Error in HuddleService updateNotificationsDatabase: ",i)}}getHuddleJoined$(){try{return this.huddleJoined$.asObservable()}catch(e){return this.loggingService.catch("Error in HuddleService getHuddleJoined$:",e),re(!1)}}getHuddleCursorAvailableByAttendeeId(){try{return this.huddleCursorAvailableByAttendeeId$.value}catch(e){return this.loggingService.catch("Error in HuddleService getHuddleCursorAvailableByAttendeeId:",e),null}}getHuddleCursorAvailableByAttendeeId$(){try{return this.huddleCursorAvailableByAttendeeId$.asObservable()}catch(e){return this.loggingService.catch("Error in HuddleService getHuddleCursorAvailableByAttendeeId$:",e),re({})}}updateHuddleCursorAvailableByAttendeeId(e,i){try{let r=this.huddleCursorAvailableByAttendeeId$.value;r[e]=i,this.huddleCursorAvailableByAttendeeId$.next(r)}catch(r){this.loggingService.catch("Error in HuddleService updateCursorUserAvailableByUserId:",r)}}setRemoteStreamsByUserId(e){try{this.remoteStreamsByUserId$.next(e)}catch(i){this.loggingService.catch("Error in HuddleService setRemoteStreamsByUserId:",i)}}getRemoteStreamsByUserId$(){try{return this.remoteStreamsByUserId$.asObservable()}catch(e){return this.loggingService.catch("Error in HuddleService getRemoteStreamsByUserId$:",e),re({})}}enableHuddleOnCursorMode(){try{this.huddleOnCursorMode$.next(!0)}catch(e){this.loggingService.catch("Error in HuddleService enableHuddleOnCursorMode:",e)}}disableHuddleOnCursorMode(){try{this.huddleOnCursorMode$.next(!1)}catch(e){this.loggingService.catch("Error in HuddleService disableHuddleOnCursorMode:",e)}}getHuddleOnCursorMode$(){try{return this.huddleOnCursorMode$.asObservable()}catch(e){return this.loggingService.catch("Error in HuddleService getHuddleOnCursorMode$:",e),re(!1)}}enableFlockModeOnAvatarClick(){try{this.flockModeOnAvatarClickEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in HuddleService enableFlockModeOnAvatarClick:",e)}}disableFlockModeOnAvatarClick(){try{this.flockModeOnAvatarClickEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in HuddleService disableFlockModeOnAvatarClick:",e)}}getFlockModeOnAvatarClick$(){try{return this.flockModeOnAvatarClickEnabled$.asObservable()}catch(e){return this.loggingService.catch("Error in HuddleService getFlockModeOnAvatarClick$:",e),re(!1)}}getFlockModeOnAvatarClick(){try{return this.flockModeOnAvatarClickEnabled$.value}catch(e){return this.loggingService.catch("Error in HuddleService getFlockModeOnAvatarClick:",e),!1}}enableChat(){try{this.chatEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in HuddleService enableChat:",e)}}disableChat(){try{this.chatEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in HuddleService disableChat:",e)}}getChatEnabled$(){try{return this.chatEnabled$.asObservable()}catch(e){return this.loggingService.catch("Error in HuddleService getChatEnabled$:",e),re(!1)}}getChatEnabled(){try{return this.chatEnabled$.value}catch(e){return this.loggingService.catch("Error in HuddleService getChatEnabled:",e),!1}}getHuddleOnCursorModeByAttendeeId$(){try{return this.huddleOnCursorModeByAttendeeId$.asObservable()}catch(e){return this.loggingService.catch("Error in HuddleService getHuddleOnCursorModeByAttendeeId$:",e),re({})}}toggleHuddleOnCursorModeByAttendeeId(e){try{let i=this.huddleOnCursorModeByAttendeeId$.value;i[e]?delete i[e]:i[e]=!0,this.huddleOnCursorModeByAttendeeId$.next(i)}catch(i){this.loggingService.catch("Error in HuddleService toggleHuddleOnCursorModeByAttendeeId:",i)}}addCursorTag(){try{if(!document.querySelector(`${U.TAGS.SNIPPYLY_CURSOR}`)){let e=document.createElement(U.TAGS.SNIPPYLY_CURSOR);e.setAttribute("snippyly-temporary","true"),document.body.appendChild(e)}}catch(e){this.loggingService.catch("Error in HuddleService addCursorTag:",e)}}removeCursorTag(){try{let e=document.querySelector(`${U.TAGS.SNIPPYLY_CURSOR}`);e?.hasAttribute("snippyly-temporary")&&e.remove()}catch(e){this.loggingService.catch("Error in HuddleService removeCursorTag:",e)}}sendMessage(e){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: sendMessage","color: green;"),this.documentPaths?.huddle&&this.user){let i=new lM;i.message=e,i.from=this.user,i.timestamp=this.timestamp,this.commonDbService.setData({feature:"huddleMessage",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,id:i.id,skipFirestore:!0},data:i})}}catch(i){this.loggingService.catch("Error in HuddleService sendMessage:",i)}}getMessages$(){try{return this.loggingService.log("%c[WB] Calling FUNCTION: getMessages$","color: green;"),this.messages$.asObservable()}catch(e){return this.loggingService.catch("Error in HuddleService getMessages$:",e),re([])}}deleteMessages(){try{this.loggingService.log("%c[WB] Calling FUNCTION: deleteMessages","color: green;"),this.documentPaths?.huddle&&this.commonDbService.deleteData({feature:"allHuddleMessages",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,skipFirestore:!0}})}catch(e){this.loggingService.catch("Error in HuddleService deleteMessages:",e)}}showMessagesPanel(){try{this.loggingService.log("%c[WB] Calling FUNCTION: showMessagesPanel","color: green;"),this.messagesPanelVisible$.next(!0)}catch(e){this.loggingService.catch("Error in HuddleService showMessagesPanel:",e)}}hideMessagesPanel(){try{this.loggingService.log("%c[WB] Calling FUNCTION: hideMessagesPanel","color: green;"),this.messagesPanelVisible$.next(!1)}catch(e){this.loggingService.catch("Error in HuddleService hideMessagesPanel:",e)}}toggleMessagesPanel(){try{this.loggingService.log("%c[WB] Calling FUNCTION: toggleMessagesPanel","color: green;"),this.messagesPanelVisible$.next(!this.messagesPanelVisible$.value)}catch(e){this.loggingService.catch("Error in HuddleService toggleMessagesPanel:",e)}}getMessagesPanelVisible$(){try{return this.loggingService.log("%c[WB] Calling FUNCTION: getMessagesPanelVisible$","color: green;"),this.messagesPanelVisible$.asObservable()}catch(e){return this.loggingService.catch("Error in HuddleService getMessagesPanelVisible$:",e),re(!1)}}getMessagesPanelVisible(){try{return this.loggingService.log("%c[WB] Calling FUNCTION: getMessagesPanelVisible","color: green;"),this.messagesPanelVisible$.value}catch(e){return this.loggingService.catch("Error in HuddleService getMessagesPanelVisible:",e),!1}}signOutUser(e){return ee(this,null,function*(){try{this.loggingService.log("%c[WB] Calling FUNCTION: signOutUser","color: green;"),this.huddleJoined$.value&&(yield this.dropCall(),yield this.removeLocalStream(),yield this.removeAttendee())}catch(i){this.loggingService.catch("Error in HuddleService signOutUser:",i)}})}};o.\u0275fac=function(i){return new(i||o)(J(vi),J(Qe),J(je),J(pn),J(lt),J($t),J(Fe),J(xM),J(Vo),J(y),J(Vn),J(bn),J(Hn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var GM=class extends li{constructor(o){super(o),this.getService(y).log("%c[WB] Creating CLASS: HuddleElement","color: blue;"),this.enableCursorMode=this._enableCursorMode,this.disableCursorMode=this._disableCursorMode,this.enableChat=this._enableChat,this.disableChat=this._disableChat,this.enableFlockModeOnAvatarClick=this._enableFlockModeOnAvatarClick,this.disableFlockModeOnAvatarClick=this._disableFlockModeOnAvatarClick}_enableCursorMode(){this.getService(y).log("%c[WB] Calling FUNCTION: _enableCursorMode","color: green;");try{this.trackEvent(Z.Events.Huddle.ENABLE_HUDDLE_ON_CURSOR_MODE_TRIGGERED),this.getService(mr).enableHuddleOnCursorMode()}catch(o){this.getService(y).catch("Error in enableCursorMode: ",o)}}_disableCursorMode(){this.getService(y).log("%c[WB] Calling FUNCTION: _disableCursorMode","color: green;");try{this.trackEvent(Z.Events.Huddle.DISABLE_HUDDLE_ON_CURSOR_MODE_TRIGGERED),this.getService(mr).disableHuddleOnCursorMode()}catch(o){this.getService(y).catch("Error in disableCursorMode: ",o)}}_enableChat(){this.getService(y).log("%c[WB] Calling FUNCTION: _enableChat","color: green;");try{this.trackEvent(Z.Events.Huddle.ENABLE_CHAT_TRIGGERED),this.getService(mr).enableChat()}catch(o){this.getService(y).catch("Error in enableChat: ",o)}}_disableChat(){this.getService(y).log("%c[WB] Calling FUNCTION: _disableChat","color: green;");try{this.trackEvent(Z.Events.Huddle.DISABLE_CHAT_TRIGGERED),this.getService(mr).disableChat()}catch(o){this.getService(y).catch("Error in disableChat: ",o)}}_enableFlockModeOnAvatarClick(){this.getService(y).log("%c[WB] Calling FUNCTION: _enableFlockModeOnAvatarClick","color: green;");try{this.trackEvent(Z.Events.Huddle.ENABLE_FLOCK_MODE_ON_AVATAR_CLICK_TRIGGERED),this.getService(mr).enableFlockModeOnAvatarClick()}catch(o){this.getService(y).catch("Error in enableFlockModeOnAvatarClick: ",o)}}_disableFlockModeOnAvatarClick(){this.getService(y).log("%c[WB] Calling FUNCTION: _disableFlockModeOnAvatarClick","color: green;");try{this.trackEvent(Z.Events.Huddle.DISABLE_FLOCK_MODE_ON_AVATAR_CLICK_TRIGGERED),this.getService(mr).disableFlockModeOnAvatarClick()}catch(o){this.getService(y).catch("Error in disableFlockModeOnAvatarClick: ",o)}}};var WM=class extends li{constructor(o){super(o),this.getService(y).log("%c[WB] Creating CLASS: LiveStateElement","color: blue;"),this.getLiveStateData$=this._getLiveStateData,this.getLiveStateData=this._getLiveStateData,this.setLiveStateData=this._setLiveStateData,this.enableSingleEditorMode=this._enableSingleEditorMode,this.disableSingleEditorMode=this._disableSingleEditorMode,this.isUserEditor$=this._isUserEditor,this.isUserEditor=this._isUserEditor,this.getEditor=this._getEditor,this.setUserAsEditor=this._setUserAsEditor,this.resetUserAccess=this._resetUserAccess,this.singleEditorModeContainerIds=this._singleEditorModeContainerIds,this.enableAutoSyncState=this._enableAutoSyncState,this.disableAutoSyncState=this._disableAutoSyncState,this.requestEditorAccess=this._requestEditorAccess,this.isEditorAccessRequested=this._isEditorAccessRequested,this.acceptEditorAccessRequest=this._acceptEditorAccessRequest,this.rejectEditorAccessRequest=this._rejectEditorAccessRequest,this.cancelEditorAccessRequest=this._cancelEditorAccessRequest,this.editCurrentTab=this._editCurrentTab,this.setEditorAccessTimeout=this._setEditorAccessTimeout,this.enableEditorAccessTransferOnTimeOut=this._enableEditorAccessTransferOnTimeOut,this.disableEditorAccessTransferOnTimeOut=this._disableEditorAccessTransferOnTimeOut,this.enableDefaultSingleEditorUI=this._enableDefaultSingleEditorUI,this.disableDefaultSingleEditorUI=this._disableDefaultSingleEditorUI,this.getEditorAccessTimer=this._getEditorAccessTimer,this.onServerConnectionStateChange=this._onServerConnectionStateChange}_getLiveStateData(o,t){this.getService(y).log("%c[WB] Calling FUNCTION: getLiveStateData","color: green;");try{return this.trackEvent(Z.Events.LiveStateSync.GET_LIVE_STATE_DATA_TRIGGERED),this.getService(Di).getLiveStateData$(o,t)}catch(e){return this.getService(y).catch("Error in _getLiveStateData: ",e),re(null)}}_setLiveStateData(o,t,e){this.getService(y).log("%c[WB] Calling FUNCTION: setLiveStateData","color: green;");try{return this.trackEvent(Z.Events.LiveStateSync.SET_LIVE_STATE_DATA_TRIGGERED),this.getService(Di).setLiveStateData(o,t,e)}catch(i){return this.getService(y).catch("Error in _setLiveStateData: ",i),Promise.resolve()}}_enableSingleEditorMode(o){this.getService(y).log("%c[WB] Calling FUNCTION: enableSingleEditorMode","color: green;");try{this.trackEvent(Z.Events.LiveStateSync.ENABLE_SINGLE_EDITOR_MODE_TRIGGERED),this.getService(Di).enableSingleEditorMode(o)}catch(t){this.getService(y).catch("Error in _enableSingleEditorMode: ",t)}}_disableSingleEditorMode(){this.getService(y).log("%c[WB] Calling FUNCTION: disableSingleEditorMode","color: green;");try{this.trackEvent(Z.Events.LiveStateSync.DISABLE_SINGLE_EDITOR_MODE_TRIGGERED),this.getService(Di).disableSingleEditorMode()}catch(o){this.getService(y).catch("Error in _disableSingleEditorMode: ",o)}}_isUserEditor(){this.getService(y).log("%c[WB] Calling FUNCTION: isUserEditor$","color: green;");try{return this.trackEvent(Z.Events.LiveStateSync.IS_USER_EDITOR_TRIGGERED),this.getService(Di).isUserEditor$()}catch(o){return this.getService(y).catch("Error in _isUserEditor$: ",o),re(null)}}_getEditor(){this.getService(y).log("%c[WB] Calling FUNCTION: getEditor","color: green;");try{return this.trackEvent(Z.Events.LiveStateSync.GET_EDITOR_TRIGGERED),this.getService(Di).getEditor$()}catch(o){return this.getService(y).catch("Error in _getEditor: ",o),re(null)}}_setUserAsEditor(){this.getService(y).log("%c[WB] Calling FUNCTION: setUserAsEditor","color: green;");try{this.trackEvent(Z.Events.LiveStateSync.SET_USER_AS_EDITOR_TRIGGERED),this.getService(Di).setUserAsEditor()}catch(o){this.getService(y).catch("Error in _setUserAsEditor: ",o)}}_resetUserAccess(){this.getService(y).log("%c[WB] Calling FUNCTION: resetUserAccess","color: green;");try{this.trackEvent(Z.Events.LiveStateSync.RESET_USER_ACCESS_TRIGGERED),this.getService(Di).removeEditorAccess()}catch(o){this.getService(y).catch("Error in _resetUserAccess: ",o)}}_singleEditorModeContainerIds(o){this.getService(y).log("%c[WB] Calling FUNCTION: singleEditorModeContainerIds","color: green;");try{this.trackEvent(Z.Events.LiveStateSync.SINGLE_EDITOR_MODE_CONTAINER_IDS_TRIGGERED),this.getService(Di).setSingleEditorModeContainerIds(o)}catch(t){this.getService(y).catch("Error in _singleEditorModeContainerIds: ",t)}}_enableAutoSyncState(){this.getService(y).log("%c[WB] Calling FUNCTION: enableAutoSyncState","color: green;");try{this.trackEvent(Z.Events.LiveStateSync.ENABLE_AUTO_SYNC_STATE_TRIGGERED),this.getService(Di).enableAutoSyncState()}catch(o){this.getService(y).catch("Error in _enableAutoSyncState: ",o)}}_disableAutoSyncState(){this.getService(y).log("%c[WB] Calling FUNCTION: disableAutoSyncState","color: green;");try{this.trackEvent(Z.Events.LiveStateSync.DISABLE_AUTO_SYNC_STATE_TRIGGERED),this.getService(Di).disableAutoSyncState()}catch(o){this.getService(y).catch("Error in _disableAutoSyncState: ",o)}}_requestEditorAccess(){this.getService(y).log("%c[WB] Calling FUNCTION: requestEditorAccess","color: green;");try{return this.trackEvent(Z.Events.LiveStateSync.REQUEST_EDITOR_ACCESS_TRIGGERED),this.getService(Di).requestEditorAccess()}catch(o){return this.getService(y).catch("Error in _requestEditorAccess: ",o),re(null)}}_isEditorAccessRequested(){this.getService(y).log("%c[WB] Calling FUNCTION: isEditorAccessRequested","color: green;");try{return this.trackEvent(Z.Events.LiveStateSync.IS_EDITOR_ACCESS_REQUESTED_TRIGGERED),this.getService(Di).isEditorAccessRequested$()}catch(o){return this.getService(y).catch("Error in _isEditorAccessRequested: ",o),re(null)}}_acceptEditorAccessRequest(){this.getService(y).log("%c[WB] Calling FUNCTION: acceptEditorAccessRequest","color: green;");try{this.trackEvent(Z.Events.LiveStateSync.ACCEPT_EDITOR_ACCESS_REQUEST_TRIGGERED),this.getService(Di).acceptEditorAccessRequest()}catch(o){this.getService(y).catch("Error in _acceptEditorAccessRequest: ",o)}}_rejectEditorAccessRequest(){this.getService(y).log("%c[WB] Calling FUNCTION: rejectEditorAccessRequest","color: green;");try{this.trackEvent(Z.Events.LiveStateSync.REJECT_EDITOR_ACCESS_REQUEST_TRIGGERED),this.getService(Di).rejectEditorAccessRequest()}catch(o){this.getService(y).catch("Error in _rejectEditorAccessRequest: ",o)}}_cancelEditorAccessRequest(){this.getService(y).log("%c[WB] Calling FUNCTION: cancelEditorAccessRequest","color: green;");try{this.trackEvent(Z.Events.LiveStateSync.CANCEL_EDITOR_ACCESS_REQUEST_TRIGGERED),this.getService(Di).cancelEditorAccessRequest()}catch(o){this.getService(y).catch("Error in _cancelEditorAccessRequest: ",o)}}_editCurrentTab(){this.getService(y).log("%c[WB] Calling FUNCTION: editCurrentTab","color: green;");try{this.trackEvent(Z.Events.LiveStateSync.EDIT_CURRENT_TAB_TRIGGERED),this.getService(Di).editCurrentTab()}catch(o){this.getService(y).catch("Error in _editCurrentTab: ",o)}}_setEditorAccessTimeout(o){this.getService(y).log("%c[WB] Calling FUNCTION: setEditorAccessTimeout","color: green;");try{this.trackEvent(Z.Events.LiveStateSync.SET_EDITOR_ACCESS_TIMEOUT_TRIGGERED),this.getService(Di).setEditorAccessTimeout(o)}catch(t){this.getService(y).catch("Error in _setEditorAccessTimeout: ",t)}}_enableEditorAccessTransferOnTimeOut(){this.getService(y).log("%c[WB] Calling FUNCTION: enableEditorAccessTransferOnTimeOut","color: green;");try{this.trackEvent(Z.Events.LiveStateSync.ENABLE_EDITOR_ACCESS_TRANSFER_ON_TIMEOUT_TRIGGERED),this.getService(Di).enableEditorAccessTransferOnTimeOut()}catch(o){this.getService(y).catch("Error in _enableEditorAccessTransferOnTimeOut: ",o)}}_disableEditorAccessTransferOnTimeOut(){this.getService(y).log("%c[WB] Calling FUNCTION: disableEditorAccessTransferOnTimeOut","color: green;");try{this.trackEvent(Z.Events.LiveStateSync.DISABLE_EDITOR_ACCESS_TRANSFER_ON_TIMEOUT_TRIGGERED),this.getService(Di).disableEditorAccessTransferOnTimeOut()}catch(o){this.getService(y).catch("Error in _disableEditorAccessTransferOnTimeOut: ",o)}}_enableDefaultSingleEditorUI(){this.getService(y).log("%c[WB] Calling FUNCTION: enableDefaultSingleEditorUI","color: green;");try{this.trackEvent(Z.Events.LiveStateSync.ENABLE_DEFAULT_SINGLE_EDITOR_UI_TRIGGERED),this.getService(Di).enableDefaultSingleEditorUI()}catch(o){this.getService(y).catch("Error in _enableDefaultSingleEditorUI: ",o)}}_disableDefaultSingleEditorUI(){this.getService(y).log("%c[WB] Calling FUNCTION: disableDefaultSingleEditorUI","color: green;");try{this.trackEvent(Z.Events.LiveStateSync.DISABLE_DEFAULT_SINGLE_EDITOR_UI_TRIGGERED),this.getService(Di).disableDefaultSingleEditorUI()}catch(o){this.getService(y).catch("Error in _disableDefaultSingleEditorUI: ",o)}}_getEditorAccessTimer(){this.getService(y).log("%c[WB] Calling FUNCTION: getEditorAccessTimer","color: green;");try{return this.trackEvent(Z.Events.LiveStateSync.GET_EDITOR_ACCESS_TIMER_TRIGGERED),this.getService(Di).getEditorAccessTimer$()}catch(o){return this.getService(y).catch("Error in _getEditorAccessTimer: ",o),re(new Lv)}}_onServerConnectionStateChange(){this.getService(y).log("%c[WB] Calling FUNCTION: onServerConnectionStateChange","color: green;");try{return this.trackEvent(Z.Events.LiveStateSync.ON_SERVER_CONNECTION_STATE_CHANGE_TRIGGERED),this.getService(Di).onServerConnectionStateChange$()}catch(o){return this.getService(y).catch("Error in _onServerConnectionStateChange: ",o),re(ul.PENDING_INIT)}}};var qM=class extends li{constructor(o){super(o),this.getService(y).log("%c[WB] Creating CLASS: ViewsElement","color: blue;"),this.openHistoryPanel=this._openHistoryPanel,this.closeHistoryPanel=this._closeHistoryPanel,this.toggleHistoryPanel=this._toggleHistoryPanel,this.getNotificationsData=this._getNotificationsData,this.setMaxDays=this._setMaxDays,this.setTabConfig=this._setTabConfig,this.enableReadNotificationsOnForYouTab=this._enableReadNotificationsOnForYouTab,this.disableReadNotificationsOnForYouTab=this._disableReadNotificationsOnForYouTab,this.setAllNotificationsAsRead=this._setAllNotificationsAsRead,this.getUnreadNotificationsCount=this._getUnreadNotificationsCount,this.markNotificationAsReadById=this._markNotificationAsReadById}_openHistoryPanel(){this.getService(y).log("%c[WB] Calling FUNCTION: _openHistoryPanel","color: green;");try{this.trackEvent(Z.Events.Notifications.OPEN_HISTORY_PANEL_TRIGGERED),this.getService(Vn).setHistoryPanelVisibility(!0,!0)}catch(o){this.getService(y).catch("Error in openHistoryPanel: ",o)}}_closeHistoryPanel(){this.getService(y).log("%c[WB] Calling FUNCTION: _closeHistoryPanel","color: green;");try{this.trackEvent(Z.Events.Notifications.CLOSE_HISTORY_PANEL_TRIGGERED),this.getService(Vn).setHistoryPanelVisibility(!1,!0)}catch(o){this.getService(y).catch("Error in closeHistoryPanel: ",o)}}_toggleHistoryPanel(){this.getService(y).log("%c[WB] Calling FUNCTION: _toggleHistoryPanel","color: green;");try{this.trackEvent(Z.Events.Notifications.TOGGLE_HISTORY_PANEL_TRIGGERED),this.getService(Vn).toggleHistoryPanelVisibility(!0)}catch(o){this.getService(y).catch("Error in toggleHistoryPanel: ",o)}}_getNotificationsData(){this.getService(y).log("%c[WB] Calling FUNCTION: _getNotificationsData","color: green;");try{return this.trackEvent(Z.Events.Notifications.GET_NOTIFICATIONS_DATA_TRIGGERED),this.getService(Vn).getNotifications$()}catch(o){return this.getService(y).catch("Error in getNotificationsData: ",o),re([])}}_setMaxDays(o){this.getService(y).log("%c[WB] Calling FUNCTION: _setMaxDays","color: green;");try{this.trackEvent(Z.Events.Notifications.SET_MAX_DAYS_TRIGGERED),this.getService(Vn).setMaxDays(o)}catch(t){this.getService(y).catch("Error in setMaxDays: ",t)}}_setTabConfig(o){this.getService(y).log("%c[WB] Calling FUNCTION: _setTabConfig","color: green;");try{this.trackEvent(Z.Events.Notifications.SET_TAB_CONFIG_TRIGGERED),this.getService(Vn).setTabConfig(o)}catch(t){this.getService(y).catch("Error in setTabConfig: ",t)}}_enableReadNotificationsOnForYouTab(){this.getService(y).log("%c[WB] Calling FUNCTION: _enableReadNotificationsOnForYouTab","color: green;");try{this.trackEvent(Z.Events.Notifications.ENABLE_READ_NOTIFICATIONS_ON_FOR_YOU_TAB_TRIGGERED),this.getService(Vn).enableReadNotificationsOnForYouTab()}catch(o){this.getService(y).catch("Error in enableReadNotificationsOnForYouTab: ",o)}}_disableReadNotificationsOnForYouTab(){this.getService(y).log("%c[WB] Calling FUNCTION: _disableReadNotificationsOnForYouTab","color: green;");try{this.trackEvent(Z.Events.Notifications.DISABLE_READ_NOTIFICATIONS_ON_FOR_YOU_TAB_TRIGGERED),this.getService(Vn).disableReadNotificationsOnForYouTab()}catch(o){this.getService(y).catch("Error in disableReadNotificationsOnForYouTab: ",o)}}_setAllNotificationsAsRead(o){this.getService(y).log("%c[WB] Calling FUNCTION: _setAllNotificationsAsRead","color: green;");try{this.trackEvent(Z.Events.Notifications.SET_ALL_NOTIFICATIONS_AS_READ_TRIGGERED),this.getService(Vn).setAllNotificationsAsRead(o)}catch(t){this.getService(y).catch("Error in setAllNotificationsAsRead: ",t)}}_getUnreadNotificationsCount(){this.getService(y).log("%c[WB] Calling FUNCTION: _getUnreadNotificationsCount","color: green;");try{return this.trackEvent(Z.Events.Notifications.GET_UNREAD_NOTIFICATIONS_COUNT_TRIGGERED),this.getService(Vn).getUnreadNotificationsCount$()}catch(o){return this.getService(y).catch("Error in getUnreadNotificationsCount: ",o),re({forYou:null,all:null})}}_markNotificationAsReadById(o){this.getService(y).log("%c[WB] Calling FUNCTION: _markNotificationAsReadById","color: green;");try{this.trackEvent(Z.Events.Notifications.MARK_NOTIFICATION_AS_READ_BY_ID_TRIGGERED,{payload:{notificationId:o}}),this.getService(Vn).markNotificationAsReadById(o)}catch(t){this.getService(y).catch("Error in markNotificationAsReadById: ",t)}}};var YM=class extends li{constructor(o){super(o),this.getService(y).log("%c[WB] Creating CLASS: PresenceElement","color: blue;"),this.getOnlineUsersOnCurrentDocument=this._getOnlineUsersOnCurrentDocument,this.setInactivityTime=this._setInactivityTime,this.enableFlockMode=this._enableFlockMode,this.disableFlockMode=this._disableFlockMode,this.startFollowingUser=this._startFollowingUser,this.stopFollowingUser=this._stopFollowingUser,this.enableSelf=this._enableSelf,this.disableSelf=this._disableSelf}_getOnlineUsersOnCurrentDocument(){this.getService(y).log("%c[WB] Calling FUNCTION: getOnlineUsers","color: green;");try{return this.trackEvent(Z.Events.Presence.GET_ONLINE_USERS_ON_CURRENT_DOCUMENT_TRIGGERED),this.getService(Cm).getOnlineUsersOnCurrentDocument()}catch(o){return this.getService(y).catch("Error in _getOnlineUsersOnCurrentDocument: ",o),re(null)}}_setInactivityTime(o){this.getService(y).log("%c[WB] Calling FUNCTION: _setInactivityTime","color: green;");try{this.trackEvent(Z.Events.Presence.SET_INACTIVITY_TIME_TRIGGERED,{payload:{time:o}}),isNaN(o)?this.getService(y).catch("Error in setInactivityTime: ","Provided value is not a number."):this.getService(Cm).setInactivityTime(o)}catch(t){this.getService(y).catch("Error in setInactivityTime: ",t)}}_disableFlockMode(){try{this.trackEvent(Z.Events.Presence.DISABLE_FLOCK_MODE_TRIGGERED),this.getService(vc).disableFlockMode()}catch(o){this.getService(y).catch("Error in _disableFlockMode: ",o)}}_enableFlockMode(o){try{this.trackEvent(Z.Events.Presence.ENABLE_FLOCK_MODE_TRIGGERED,{payload:{options:o}}),this.getService(vc).enableFlockMode(o)}catch(t){this.getService(y).catch("Error in _enableFlockMode: ",t)}}_stopFollowingUser(){try{this.trackEvent(Z.Events.Presence.STOP_FOLLOWING_USER_TRIGGERED),this.getService(vc).stopFollowingUser()}catch(o){this.getService(y).catch("Error in _stopFollowingUser: ",o)}}_startFollowingUser(o){try{this.trackEvent(Z.Events.Presence.START_FOLLOWING_USER_TRIGGERED,{payload:{externalId:o}});let t=this.getService(Cm).getPresenceUserFromExternalId(o);return t&&t.userSnippylyId&&t.name!==void 0?(this.getService(vc).startFollowingUser(t.userSnippylyId,t.name),{success:!0,msg:"Joined flock session."}):{success:!1,msg:"User could not be found."}}catch(t){return this.getService(y).catch("Error in _startFollowingUser: ",t),{success:!1,msg:"Unknown error.",raw:t}}}_enableSelf(){try{this.trackEvent(Z.Events.Presence.ENABLE_SELF_TRIGGERED),this.getService(Cm).enableIncludeSelf()}catch(o){this.getService(y).catch("Error in _enableSelf: ",o)}}_disableSelf(){try{this.trackEvent(Z.Events.Presence.DISABLE_SELF_TRIGGERED),this.getService(Cm).disableIncludeSelf()}catch(o){this.getService(y).catch("Error in _disableSelf: ",o)}}};var KM=class extends li{constructor(o){super(o),this.getService(y).log("%c[WB] Creating CLASS: ReactionElement","color: blue;"),this.enableDarkMode=this._enableDarkMode,this.disableDarkMode=this._disableDarkMode,this.setCustomReactions=this._setCustomReactions}_enableDarkMode(){this.getService(y).log("%c[WB] Calling FUNCTION: enableDarkMode","color: green;");try{this.trackEvent(Z.Events.Reactions.ENABLE_DARK_MODE_TRIGGERED),this.getService(er).enableDarkMode()}catch(o){this.getService(y).catch("Error in _enableDarkMode: ",o)}}_disableDarkMode(){this.getService(y).log("%c[WB] Calling FUNCTION: disableDarkMode","color: green;");try{this.trackEvent(Z.Events.Reactions.DISABLE_DARK_MODE_TRIGGERED),this.getService(er).disableDarkMode()}catch(o){this.getService(y).catch("Error in _disableDarkMode: ",o)}}_setCustomReactions(o){this.getService(y).log("%c[WB] Calling FUNCTION: setCustomReactions","color: green;");try{this.trackEvent(Z.Events.Reactions.SET_CUSTOM_REACTIONS_TRIGGERED,{payload:{reactions:o}}),this.getService(er).setCustomReactions(o)}catch(t){this.getService(y).catch("Error in _setCustomReactions: ",t)}}};var Ose=(()=>{let o=class o{constructor(e,i,r){this.loggingService=e,this.recorderAnnotationService=i,this.recorderService=r,this.actionSubjects=new Map,this.subscriptions=[];try{this.recorderAnnotationService.setRecorderActionsService(this),this.recorderService.setRecorderActionsService(this)}catch(a){this.loggingService.catch("Error in RecorderActionsService constructor: ",a)}}onTranscriptionDone(e){try{this.triggerAction(LO.TRANSCRIPTION_DONE,e)}catch(i){this.loggingService.catch("Error in RecorderActionsService onTranscriptionDone: ",i)}}onRecordingDone(e){try{this.triggerAction(LO.RECORDING_DONE,e)}catch(i){this.loggingService.catch("Error in RecorderActionsService onRecordingDone: ",i)}}onDeleteRecording(e){try{this.triggerAction(LO.DELETE_RECORDING,e)}catch(i){this.loggingService.catch("Error in RecorderActionsService onDeleteRecording: ",i)}}triggerAction(e,i){try{this.actionSubjects.has(e)||this.actionSubjects.set(e,new et),this.actionSubjects.get(e)?.next(i)}catch(r){this.loggingService.catch("Error in RecorderActionsService triggerAction: ",r)}}onAction(e){try{return this.actionSubjects.has(e)||this.actionSubjects.set(e,new et),this.actionSubjects.get(e)?.asObservable()}catch(i){return this.loggingService.catch("Error in RecorderActionsService onAction: ",i),re(null)}}};o.\u0275fac=function(i){return new(i||o)(J(y),J(Qi),J(yi))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var ZM=class extends li{constructor(o){super(o),this.getService(y).log("%c[WB] Creating CLASS: RecorderElement","color: blue;"),this.initRecording=this._initRecording,this.onRecordedData=this._onRecordedData,this.enableDarkMode=this._enableDarkMode,this.disableDarkMode=this._disableDarkMode,this.enableRecordingCountdown=this._enableRecordingCountdown,this.disableRecordingCountdown=this._disableRecordingCountdown,this.getRecordingDataByRecorderId=this._getRecordingDataByRecorderId,this.enableRecordingTranscription=this._enableRecordingTranscription,this.disableRecordingTranscription=this._disableRecordingTranscription,this.getRecordingData=this._getRecordingData,this.enableVideoEditor=this._enableVideoEditor,this.disableVideoEditor=this._disableVideoEditor,this.getRecordings=this._getRecordings,this.fetchRecordings=this._fetchRecordings,this.on=this._on}_initRecording(o,t){this.getService(y).log("%c[WB] Calling FUNCTION: initRecording","color: green;");try{return this.trackEvent(Z.Events.Recording.INIT_RECORDING_TRIGGERED,{payload:{type:o,panelId:t}}),this.getService(yi).initRecording(o,t)}catch(e){return this.getService(y).catch("Error in _initRecording: ",e),re(null)}}_onRecordedData(){this.getService(y).log("%c[WB] Calling FUNCTION: onRecordedData","color: green;");try{return this.trackEvent(Z.Events.Recording.ON_RECORDED_DATA_TRIGGERED),this.getService(yi).onRecordedData()}catch(o){return this.getService(y).catch("Error in _onRecordedData: ",o),re(null)}}_enableDarkMode(){this.getService(y).log("%c[WB] Calling FUNCTION: enableDarkMode","color: green;");try{this.trackEvent(Z.Events.Recording.ENABLE_DARK_MODE_TRIGGERED),this.getService(Qi).setRecorderContainerDarkMode(!0)}catch(o){this.getService(y).catch("Error in _enableDarkMode: ",o)}}_disableDarkMode(){this.getService(y).log("%c[WB] Calling FUNCTION: disableDarkMode","color: green;");try{this.trackEvent(Z.Events.Recording.DISABLE_DARK_MODE_TRIGGERED),this.getService(Qi).setRecorderContainerDarkMode(!1)}catch(o){this.getService(y).catch("Error in _disableDarkMode: ",o)}}_enableRecordingCountdown(){this.getService(y).log("%c[WB] Calling FUNCTION: enableRecordingCountdown","color: green;");try{this.trackEvent(Z.Events.Recording.ENABLE_RECORDING_COUNTDOWN_TRIGGERED),this.getService(yi).enableRecordingCountdown()}catch(o){this.getService(y).catch("Error in _enableRecordingCountdown: ",o)}}_disableRecordingCountdown(){this.getService(y).log("%c[WB] Calling FUNCTION: disableRecordingCountdown","color: green;");try{this.trackEvent(Z.Events.Recording.DISABLE_RECORDING_COUNTDOWN_TRIGGERED),this.getService(yi).disableRecordingCountdown()}catch(o){this.getService(y).catch("Error in _disableRecordingCountdown: ",o)}}_getRecordingDataByRecorderId(o){this.getService(y).log("%c[WB] Calling FUNCTION: getRecordingDataByRecorderId","color: green;");try{return this.trackEvent(Z.Events.Recording.GET_RECORDING_DATA_BY_RECORDER_ID_TRIGGERED,{payload:{recorderId:o}}),this.getService(Qi).getRecorderDataByRecorderId(o)}catch(t){return this.getService(y).catch("Error in _getRecordingDataByRecorderId: ",t),re(null)}}_getRecordings(o){this.getService(y).log("%c[WB] Calling FUNCTION: getRecordings","color: green;");try{return this.trackEvent(Z.Events.Recording.GET_RECORDINGS_TRIGGERED,{payload:{query:o}}),this.getService(Qi).getRecordings(o)}catch(t){return this.getService(y).catch("Error in _getRecordings: ",t),re([])}}_getRecordingData(o){this.getService(y).log("%c[WB] Calling FUNCTION: getRecordingData","color: green;");try{return this.trackEvent(Z.Events.Recording.GET_RECORDING_DATA_TRIGGERED,{payload:{query:o}}),this.getService(Qi).getRecorderDataByRecorderIds(o)}catch(t){return this.getService(y).catch("Error in _getRecordingData: ",t),Promise.resolve({data:null})}}_fetchRecordings(o){this.getService(y).log("%c[WB] Calling FUNCTION: fetchRecordings","color: green;");try{return this.trackEvent(Z.Events.Recording.FETCH_RECORDINGS_TRIGGERED,{payload:{query:o}}),this.getService(Qi).fetchRecorderDataByRecorderIds(o)}catch(t){return this.getService(y).catch("Error in _fetchRecordings: ",t),Promise.resolve([])}}_enableRecordingTranscription(){this.getService(y).log("%c[WB] Calling FUNCTION: enableRecordingTranscription","color: green;");try{this.trackEvent(Z.Events.Recording.ENABLE_RECORDING_TRANSCRIPTION_TRIGGERED),this.getService(Qi).enableRecordingTranscription()}catch(o){this.getService(y).catch("Error in _enableRecordingTranscription: ",o)}}_disableRecordingTranscription(){this.getService(y).log("%c[WB] Calling FUNCTION: disableRecordingTranscription","color: green;");try{this.trackEvent(Z.Events.Recording.DISABLE_RECORDING_TRANSCRIPTION_TRIGGERED),this.getService(Qi).disableRecordingTranscription()}catch(o){this.getService(y).catch("Error in _disableRecordingTranscription: ",o)}}_on(o){this.getService(y).log("%c[WB] Calling FUNCTION: on","color: green;");try{return this.trackEvent(Z.Events.Recording.ON_ACTION_TRIGGERED,{payload:{action:o}}),this.getService(Ose).onAction(o)}catch(t){return this.getService(y).catch("Error in _on: ",t),re(null)}}_enableVideoEditor(){this.getService(y).log("%c[WB] Calling FUNCTION: enableVideoEditor","color: green;");try{this.trackEvent(Z.Events.Recording.ENABLE_VIDEO_EDITOR_TRIGGERED),this.getService(yi).enableVideoEditor()}catch(o){this.getService(y).catch("Error in _enableVideoEditor: ",o)}}_disableVideoEditor(){this.getService(y).log("%c[WB] Calling FUNCTION: disableVideoEditor","color: green;");try{this.trackEvent(Z.Events.Recording.DISABLE_VIDEO_EDITOR_TRIGGERED),this.getService(yi).disableVideoEditor()}catch(o){this.getService(y).catch("Error in _disableVideoEditor: ",o)}}};var Cc=(()=>{let o=class o{constructor(e,i,r,a,s,c){this.analyticsService=e,this.authService=i,this.configService=r,this.domService=a,this.loggingService=s,this.functions=c,this.rewriterAnnotations$=new fe([]),this.rewriterOptions$=new fe({}),this.rewriterEnabled$=new fe(!1),this.lastOpenAIPromptCalledAt=0,this.getRewriterEnabled$().subscribe(p=>{try{if(p){let h=document.querySelectorAll(U.TAGS.SNIPPYLY_REWRITER);if(!document.querySelectorAll(U.TAGS.VELT_REWRITER)?.length&&!h?.length){let E=document.createElement(U.TAGS.VELT_REWRITER);document.body.appendChild(E),this.authService.getUser$().pipe(Ne(D=>!!D),Je(1)).subscribe(D=>{this.analyticsService.trackEvent(Z.Events.Rewriter.REWRITER_ENABLED,{isMobileDevice:this.domService.isMobileDevice()})})}}else{let h=document.querySelectorAll(U.TAGS.SNIPPYLY_REWRITER);h?.length&&h.forEach(E=>{E.remove()});let _=document.querySelectorAll(U.TAGS.VELT_REWRITER);_?.length&&_.forEach(E=>{E.remove()})}}catch(h){this.loggingService.catch("Error in rewriterEnabled$: ",h)}},p=>{this.loggingService.catch("Error in rewriterEnabled$ subscription: ",p)})}getRewriterAnnotations$(){try{return this.rewriterAnnotations$.asObservable()}catch(e){return this.loggingService.catch("Error in getRewriterAnnotations$(): ",e),re([])}}addRewriter(e,i,r){this.loggingService.log("%c[WB] Calling FUNCTION: addRewriter","color: green;");try{let a=this.authService.getUser();if(a)if(a.isReadOnly||a.isAnonymous)this.loggingService.catch("Anonymous/Readonly users cannot add rewriters.");else{let s=new hM;s.from=a,s.color=U.DEFAULT_ANNOTATION_COLOR,i&&(s.targetTextRange=i),r&&(s.rewriterType=r),this.saveRewriterToDb(s)}}catch(a){this.loggingService.catch("Error in RewriterService addRewriter: ",a)}}saveRewriterToDb(e){this.loggingService.log("%c[WB] Calling FUNCTION: saveRewriterToDb","color: green;");try{e?.annotationId||(e.annotationId=Math.random().toString(36).substring(2)+Date.now().toString(36));let i=this.rewriterAnnotations$.getValue();i.push(e),this.rewriterAnnotations$.next(i),this.domService.toggleAnnotationSelection(e)}catch(i){this.loggingService.catch("Error in RewriterService saveRewriterToDb: ",i)}}removeRewriter(e){try{let i=this.rewriterAnnotations$.getValue(),r=i.findIndex(a=>a.annotationId===e.annotationId);r>-1&&(i.splice(r,1),this.rewriterAnnotations$.next(i))}catch(i){this.loggingService.catch("Error in RewriterService removeRewriter: ",i)}}getRewriterOptions(e,i,r){try{if(this.lastOpenAIPromptCalledAt&&Date.now()-this.lastOpenAIPromptCalledAt<1e3)return this.lastOpenAIPromptCalledAt=Date.now(),re([]);this.lastOpenAIPromptCalledAt=Date.now();let a=Cr(this.functions,Zn.cloudFunction.chatgptCompletion,{timeout:20*60*1e3}),s=i?.[0]?.role==="system"?i?.[0]?.content:null;return this.analyticsService.trackEvent(Z.Events.Rewriter.REWRITE_PROMPT_SUBMITTED,{isMobileDevice:this.domService.isMobileDevice(),prompt:s,type:e}),bo(a({messages:i,type:e,apiKey:this.configService.getApiKey(),sdkVersion:Ta(),sdkType:this.configService.getSdkType()})).pipe(ce(c=>c?.data?c.data:[]))}catch(a){return this.loggingService.catch("Error in RewriterService getRewriterOptions: ",a),re([])}}enableRewriter(){try{this.rewriterEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in RewriterService enableRewriter: ",e)}}disableRewriter(){try{this.rewriterEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in RewriterService disableRewriter: ",e)}}getRewriterEnabled$(){try{return this.rewriterEnabled$.asObservable()}catch(e){return this.loggingService.catch("Error in RewriterService getRewriterEnabled$: ",e),re(!1)}}resetRewriter(){try{this.domService.resetSelectedAnnotationsMap(!1,"rewriter"),this.rewriterAnnotations$.next([])}catch(e){this.loggingService.catch("Error in RewriterService resetRewriter: ",e)}}getChatGPTInput(e,i,r=[]){try{let a="";return e&&(a=`
|
|
383
|
+
`],encapsulation:3,changeDetection:0});let n=o;return n})();var Dse=(()=>{let o=class o{constructor(e,i,r,a){this.componentFactoryResolver=e,this.applicationRef=i,this.injector=r,this.loggingService=a,this.darkMode=!1}createFollowOverlay(e,i){try{let a=this.componentFactoryResolver.resolveComponentFactory(h$).create(this.injector);a.instance.setLeaderName(e),a.instance.closeOverlayEvent.pipe(Je(1)).subscribe(()=>{this.removeOverlay(),i()}),this.applicationRef.attachView(a.hostView),this.overlayRef=a,this.overlayRef.instance.darkMode=this.darkMode;let s=this.overlayRef.location.nativeElement;s.id="snippyly-follow-overlay",s.setAttribute(U.ATTRIBUTES.VELT_IGNORE,""),document.body.appendChild(s)}catch(r){this.loggingService.catch("Error in FlockOverlayService createFollowOverlay: ",r)}}createLeaderOverlay(e){let r=this.componentFactoryResolver.resolveComponentFactory(h$).create(this.injector);r.instance.setType("leading"),r.instance.closeOverlayEvent.pipe(Je(1)).subscribe(()=>{this.removeOverlay(),e()}),this.applicationRef.attachView(r.hostView),this.overlayRef=r,this.overlayRef.instance.darkMode=this.darkMode;let a=this.overlayRef.location.nativeElement;a.id="snippyly-follow-overlay",a.setAttribute(U.ATTRIBUTES.VELT_IGNORE,""),document.body.appendChild(a)}changeLeaderName(e){this.overlayRef&&this.overlayRef.instance.setLeaderName(e)}getLeaderName(){return this.overlayRef?this.overlayRef.instance.getLeaderName():null}removeOverlay(){if(this.overlayRef){let e=this.overlayRef.location.nativeElement;this.applicationRef.detachView(this.overlayRef.hostView),this.overlayRef.destroy(),e.shadowRoot&&e.shadowRoot.removeChild(e.shadowRoot.childNodes[0]),e.remove(),this.overlayRef=void 0}}setDarkMode(e){try{this.darkMode=e,this.overlayRef&&(this.overlayRef.instance.darkMode=e)}catch(i){this.loggingService.catch("Error in FlockOverlayService setDarkMode: ",i)}}};o.\u0275fac=function(i){return new(i||o)(J(Io),J(mi),J(Et),J(y))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var vc=(()=>{let o=class o{constructor(e,i,r,a,s){this.authService=e,this.domService=i,this.loggingService=r,this.flockSessionService=a,this.flockOverlayService=s,this.flockLeader$=new fe({userId:"",name:""}),this.flockMode$=new fe(!1),this.currentFlockUser=null,this.localScrollData=[],this.domSubscriptions=[],this.followOverlayCreated=!1,this.leaderOverlayCreated=!1,this.windowFocused=!0,this.tabFocused=!0,this.useHistoryAPI=!0,this.disableDefaultNavigation=!1;try{this.flockLeader$.subscribe(c=>{let{userId:p,name:h}=c,_=p;if(this.provisionFollowUser(),_&&this.currentFlockUser&&this.currentFlockUser.snippylyId)if(this.currentFlockUser.sessionId){if(this.currentFlockUser.snippylyId&&this.currentFlockUser.isLeader){this.flockSessionService.swapLeader(this.currentFlockUser.snippylyId,_,h);return}this.removeCurrentUserFromSession()}else this.flockSessionService.provisionFlockSession(_,h,this.currentFlockUser.snippylyId)},c=>{this.loggingService.catch("Error in FlockService flockLeader$ subscription: ",c)}),this.flockSessionService.currentSession$.subscribe(c=>{if(c!==null){if(this.currentFlockUser&&(this.currentFlockUser.sessionId===null||this.currentFlockUser.sessionId===void 0)&&this.currentFlockUser.snippylyId&&(this.currentFlockUser.sessionId=c.id,this.flockSessionService.updateRemoteFlockUser(this.currentFlockUser.snippylyId,this.currentFlockUser)),this.currentFlockUser&&!this.currentFlockUser.isLeader&&!this.followOverlayCreated&&(this.leaderOverlayCreated&&(this.flockOverlayService.removeOverlay(),this.leaderOverlayCreated=!1),this.followOverlayCreated=!0,this.flockOverlayService.createFollowOverlay(c.leaderName,()=>{this.removeCurrentUserFromSession(),this.followOverlayCreated=!1})),this.currentFlockUser&&this.currentFlockUser.isLeader&&!this.leaderOverlayCreated&&(this.followOverlayCreated&&(this.flockOverlayService.removeOverlay(),this.followOverlayCreated=!1),this.leaderOverlayCreated=!0,this.flockOverlayService.createLeaderOverlay(()=>{this.removeCurrentUserFromSession(),this.leaderOverlayCreated=!1})),this.currentFlockUser&&!this.currentFlockUser.isLeader&&c.actionStack){let p=c.actionStack[0];p&&this.currentFlockUser.lastProcessedActionTimestamp!==p.timestamp&&this.processAction(p)}if(this.currentFlockUser&&!this.currentFlockUser.isLeader&&this.followOverlayCreated&&this.flockOverlayService.getLeaderName()!==null&&c.leaderName!==this.flockOverlayService.getLeaderName()&&this.flockOverlayService.changeLeaderName(c.leaderName),this.currentFlockUser&&this.currentFlockUser.isLeader){let p=_i();if(c.pageInfo){if(p&&p.url!==c.pageInfo.url){let h=new Td;h.type=Xa.NAVIGATE,this.flockSessionService.addActionToStack(c.id,h)}}else{this.flockSessionService.updateSession(c.id,{pageInfo:p});let h=new Td;h.type=Xa.NAVIGATE,this.flockSessionService.addActionToStack(c.id,h)}}}else this.currentFlockUser&&this.leaderOverlayCreated&&(this.flockOverlayService.removeOverlay(),this.leaderOverlayCreated=!1),this.currentFlockUser&&this.followOverlayCreated&&(this.flockOverlayService.removeOverlay(),this.followOverlayCreated=!1)}),this.flockSessionService.currentUser$.subscribe(c=>{if(c!==null&&(this.currentFlockUser&&this.currentFlockUser.isLeader!==c.isLeader&&(this.domSubscriptions.forEach(p=>p.unsubscribe()),this.domSubscriptions=[]),this.currentFlockUser=c,c.sessionId&&this.domSubscriptions.length===0))if(c.isLeader){if(!this.tabFocused||!this.windowFocused)return;this.subscribeToLeaderDOMEvents()}else this.subscribeToFollowerDOMEvents()}),Dn([this.authService.getUser$(),this.getFlockMode$()]).subscribe(([c,p])=>{c&&c.userSnippylyId&&p?this.flockSessionService.startCurrentFlockUserSubscription(c):this.flockSessionService.stopCurrentFlockUserSubscription()})}catch(c){this.loggingService.catch("Error in FlockService constructor: ",c)}}provisionFollowUser(){try{if(this.currentFlockUser===null){let e=this.authService.getUser();e&&e.userSnippylyId&&(this.currentFlockUser=new UM,this.currentFlockUser.snippylyId=e.userSnippylyId)}}catch(e){this.loggingService.catch("Error in FlockService provisionFollowUser: ",e)}}startFollowingUser(e,i){try{if(this.provisionFollowUser(),e&&this.currentFlockUser&&this.currentFlockUser.snippylyId){if(this.currentFlockUser.sessionId){if(this.currentFlockUser.snippylyId&&this.currentFlockUser.isLeader){this.flockSessionService.swapLeader(this.currentFlockUser.snippylyId,e,i);return}this.removeCurrentUserFromSession()}this.flockSessionService.provisionFlockSession(e,i,this.currentFlockUser.snippylyId)}}catch(r){this.loggingService.catch("Error in FlockService startFollowingUser: ",r)}}stopFollowingUser(){try{this.removeCurrentUserFromSession()}catch(e){this.loggingService.catch("Error in FlockService stopFollowingUser: ",e)}}subscribeToUrlChanges(){try{if(this.useHistoryAPI){let e=window.history.pushState,i=window.history.replaceState;window.history.pushState=(...r)=>{e.apply(window.history,r),this.onUrlChange()},window.history.replaceState=(...r)=>{i.apply(window.history,r),this.onUrlChange()},this.domSubscriptions.push({unsubscribe:()=>{window.history.pushState=e,window.history.replaceState=i}}),this.domSubscriptions.push(oi(window,"popstate").subscribe(()=>{this.onUrlChange()}))}}catch(e){this.loggingService.catch("Error in FlockService subscribeToUrlChanges: ",e)}}onUrlChange(){try{if(this.currentFlockUser&&this.currentFlockUser.sessionId&&this.currentFlockUser.isLeader){let e=new Td;e.type=Xa.NAVIGATE,this.flockSessionService.addActionToStack(this.currentFlockUser.sessionId,e)}}catch(e){this.loggingService.catch("Error in FlockService onUrlChange: ",e)}}processAction(e){try{switch(e.type){case Xa.CLICK:this.clickUserElement(e.data);break;case Xa.HOVER:this.scrollToHoveredElement(e.data);break;case Xa.SCROLL:this.scrollToFollowedUser(e.data);break;case Xa.NAVIGATE:this.checkMatchingUrl(e.pageInfo);break}this.currentFlockUser&&this.currentFlockUser.snippylyId&&this.flockSessionService.updateRemoteFlockUser(this.currentFlockUser.snippylyId,{lastProcessedActionTimestamp:e.timestamp})}catch(i){this.loggingService.catch("Error in FlockService processAction: ",i)}}subscribeToLeaderDOMEvents(){try{this.domSubscriptions.length>0&&(this.domSubscriptions.forEach(e=>e.unsubscribe()),this.domSubscriptions=[]),this.domSubscriptions.push(oi(window,"mouseover").pipe(jr(500)).subscribe(e=>{let i=e?.target;if(i){let r=window.getComputedStyle(i);if(r.position==="fixed"||r.position==="sticky"||i.hasAttribute(U.ATTRIBUTES.VELT_IGNORE))return;i=SV(i,{x:e.clientX,y:e.clientY}),this.updateHoveredElement(i)}})),this.domSubscriptions.push(this.domService.onWindowClick$().subscribe(e=>{let i=e?.target;if(i){if(i.hasAttribute(U.ATTRIBUTES.VELT_IGNORE))return;this.updateClickedElement(i)}})),this.subscribeToUrlChanges(),this.subscribeToScrollables()}catch(e){this.loggingService.catch("Error in FlockService subscribeToLeaderDOMEvents: ",e)}}subscribeToFollowerDOMEvents(){}updateClickedElement(e){try{if(this.currentFlockUser&&this.currentFlockUser.sessionId){let i=this.domService.getXPath(e),r=iv(e),a=this.domService.getXPath(r),s={id:Math.random().toString(36).substring(2),xpath:i,parentXpath:a},c=new Td;c.type=Xa.CLICK,c.data=s,this.flockSessionService.addActionToStack(this.currentFlockUser.sessionId,c)}}catch(i){this.loggingService.catch("Error in FlockService updateClickedElement: ",i)}}updateHoveredElement(e){try{if(this.currentFlockUser&&this.currentFlockUser.sessionId){let i=this.domService.getXPath(e),r=iv(e),a=this.domService.getXPath(r),s={id:Math.random().toString(36).substring(2),xpath:i,parentXpath:a},c=new Td;c.type=Xa.HOVER,c.data=s,this.flockSessionService.addActionToStack(this.currentFlockUser.sessionId,c)}}catch(i){this.loggingService.catch("Error in FlockService updateHoveredElement: ",i)}}subscribeToScrollables(){try{let e=Wie();e.push(document),e?.forEach(i=>{this.domSubscriptions.push(oi(i,"scroll").pipe(jr(100)).subscribe(r=>{this.currentFlockUser&&this.currentFlockUser.sessionId&&this.currentFlockUser.isLeader&&this.updateScrollPositionOfElement(i)}))})}catch(e){this.loggingService.catch("Error in FlockService getScrollableElements: ",e)}}updateScrollPositionOfElement(e){try{if(this.currentFlockUser&&this.currentFlockUser.sessionId){let i=new VM("","");if(e===document){let s=Kie();if(s){let c=SV(s);c&&(i.targetXpath=this.domService.getXPath(c))}i.xpath=""}else{let s=Yie(e);i.targetXpath=this.domService.getXPath(s),i.xpath=this.domService.getXPath(e)}let r=!1,a=!1;if(this.localScrollData.forEach((s,c)=>{s.xpath===s.xpath&&(i.targetXpath!==s.targetXpath&&(r=!0),this.localScrollData[c]=Object.assign(s,i),a=!0)}),a||this.localScrollData.push(i),r||!a){let s=new Td;s.type=Xa.SCROLL,s.data=i,this.flockSessionService.addActionToStack(this.currentFlockUser.sessionId,s)}}}catch(i){this.loggingService.catch("Error in FlockService calculateScrollPositionOfAnElement: ",i)}}enableFlockMode(e){try{if(this.flockMode$.next(!0),e){let{useHistoryAPI:i,onNavigate:r,disableDefaultNavigation:a,darkMode:s}=e;i!==void 0&&(this.useHistoryAPI=i),r!==void 0&&typeof r=="function"&&(this.onNavigate=r),a!==void 0&&(this.disableDefaultNavigation=a),this.flockOverlayService.setDarkMode(s)}}catch(i){this.loggingService.catch("Error in FlockService enableFlockMode: ",i)}}disableFlockMode(){try{this.flockMode$.next(!1),this.onNavigateEmitter=void 0,this.useHistoryAPI=!0,this.onNavigate=void 0}catch(e){this.loggingService.catch("Error in FlockService disableFlockMode: ",e)}}setDisableFlockNavigation(e){try{this.disableDefaultNavigation=e}catch(i){this.loggingService.catch("Error in FlockService setDisableFlockNavigation: ",i)}}getFlockMode$(){return this.flockMode$.asObservable()}getFlockMode(){return this.flockMode$.value}setNavigateEmitter(e){try{this.onNavigateEmitter=e}catch(i){this.loggingService.catch("Error in FlockService setNavigateEmitter: ",i)}}setTabFocused(e){try{if(this.tabFocused=e,!this.currentFlockUser)return;this.currentFlockUser.isLeader&&this.currentFlockUser.sessionId&&(this.tabFocused&&this.domSubscriptions.length===0?this.subscribeToLeaderDOMEvents():!this.tabFocused&&this.domSubscriptions.length>0&&(this.domSubscriptions.forEach(r=>{r.unsubscribe()}),this.domSubscriptions=[]))}catch(i){this.loggingService.catch("Error in FlockService setTabFocused: ",i)}}setWindowFocused(e){try{if(this.windowFocused=e,!this.currentFlockUser)return;this.currentFlockUser.isLeader&&this.currentFlockUser.sessionId&&(this.windowFocused&&this.domSubscriptions.length===0?this.subscribeToLeaderDOMEvents():!this.windowFocused&&this.domSubscriptions.length>0&&(this.domSubscriptions.forEach(r=>{r.unsubscribe()}),this.domSubscriptions=[]))}catch(i){this.loggingService.catch("Error in FlockService setWindowFocused: ",i)}}setFlockLeader(e,i){try{this.flockLeader$.next({userId:e,name:i})}catch(r){this.loggingService.catch("Error in FlockService setFlockLeader: ",r)}}isInSession(){try{return!!(this.currentFlockUser&&this.currentFlockUser.sessionId)}catch(e){this.loggingService.catch("Error in FlockService isFollowing: ",e)}return!1}removeCurrentUserFromSession(){try{this.domSubscriptions.forEach(e=>e.unsubscribe()),this.domSubscriptions=[],this.currentFlockUser&&(this.currentFlockUser.isLeader?this.currentFlockUser.sessionId&&this.flockSessionService.deleteSession(this.currentFlockUser.sessionId):this.currentFlockUser.snippylyId&&this.flockSessionService.removeFollowerFromCurrentSession(this.currentFlockUser.snippylyId))}catch(e){this.loggingService.catch("Error in FlockService removeCurrentUserFromSession: ",e)}}checkMatchingUrl(e){try{let r=_i()?.url,a=e.url;if(r!==a&&a!==void 0){let{url:s,path:c,baseUrl:p}=e;if(this.onNavigate!==void 0&&typeof this.onNavigate=="function"){this.onNavigate({url:s,path:c,baseUrl:p});return}if(this.onNavigateEmitter&&this.onNavigateEmitter.emit({url:s,path:c,baseUrl:p}),this.disableDefaultNavigation)return;window.location.href=a}}catch(i){this.loggingService.catch("Error in FlockService checkMatchingUrl: ",i)}}scrollToFollowedUser(e){try{if(e.xpath===""){let i=this.domService.getElementFromXPath(e.targetXpath);i&&XO(i)}else{let i=this.domService.getElementFromXPath(e.xpath),r=this.domService.getElementFromXPath(e.targetXpath);i&&r&&(XO(i),bV(i,r))}}catch(i){this.loggingService.catch("Error in FlockService scrollToFollowedUser: ",i)}}clickUserElement(e){try{let i=this.domService.getElementFromXPath(e.xpath);i&&this.lastClickedElement?.id!==e.id&&(i?.click(),this.lastClickedElement=e)}catch(i){this.loggingService.catch("Error in FlockService clickUserElement: ",i)}}scrollToHoveredElement(e){try{let i=this.domService.getElementFromXPath(e.xpath);if(i&&e.parentXpath)if(e.parentXpath==="/html")XO(i);else{let r=this.domService.getElementFromXPath(e.parentXpath);r&&bV(r,i,!0)}}catch(i){this.loggingService.catch("Error in FlockService clickUserElement: ",i)}}};o.\u0275fac=function(i){return new(i||o)(J(je),J(Fe),J(y),J(Tse),J(Dse))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Di=(()=>{let o=class o{constructor(e,i,r,a,s,c,p,h,_,E){this.afAuth=e,this.analyticsService=i,this.authService=r,this.configService=a,this.databaseService=s,this.docService=c,this.domService=p,this.iamService=h,this.loggingService=_,this.commonDbService=E,this.db=Ci(),this.liveStateDataMap$=new fe({}),this.liveStateDataMapDraft={},this.singleEditorMode$=new fe(!1),this.singleEditorModeConfig$=new fe(null),this.singleEditorLiveStateData$=new fe(null),this.singleEditorLiveStateData={},this.editorAccessTimeout$=new fe(U.LIVE_STATE_REQUEST_EDITOR_ACCESS_WAIT_TIME),this.editorAccessTransferOnTimeOut$=new fe(!0),this.defaultSingleEditorUIEnabled$=new fe(!0),this.editorAccessTimer$=new fe(new Lv),this.autoSyncState$=new fe(!1),this.serverConnectionState$=new fe(ul.PENDING_INIT),this.user=null,this.keydownSubscription=null,this.isEditor$=new fe(null),this.preventEventsOnElementMap={},this.PREVENT_EVENTS=["click","mouseup","mousedown"],this.autoSyncStateHistory=null,this.singleEditorModeContainerIds$=new fe([]),this.inputChangeSubscriptionMap={},this.childListMutationSubscription=null,this.tabId=this.domService.getTabId();try{this.loggingService.log("%c[WB] Creating CLASS: LiveStateService","color: blue;"),this.databaseService.getDb().pipe(Ne(D=>!!D),Je(1)).subscribe(D=>{D&&(this.db=D,this.getUser(),this.getDocumentPaths(),this.subscribeLiveStateData().subscribe(),this.singleEditorMode$.subscribe(B=>{B&&this.detectKeydownOnInput()}),this.autoSyncState$.subscribe(B=>{B?(this.detectLiveSyncInputs(),this.observeElementAddedOnDom()):(this.unsubscribeInputChanges(),this.childListMutationSubscription?.unsubscribe(),this.childListMutationSubscription=null)}),this.updateOnDatabaseDisconnect().subscribe(()=>{},B=>{this.loggingService.catch("Error in LiveStateService constructor updateOnDatabaseDisconnect: ",B)}),this.updateServerStateOnDatabaseDisconnect().subscribe(()=>{},B=>{this.loggingService.catch("Error in LiveStateService constructor updateServerStateOnDatabaseDisconnect: ",B)}))},D=>{this.loggingService.catch("Error in LiveStateService getDb subscription: ",D)}),this.liveStateDataMap$.pipe(Ne(D=>!!D?.default?.autoSyncState),ce(D=>D.default?.autoSyncState),Kt((D,B)=>JSON.stringify(D||{})===JSON.stringify(B||{}))).subscribe(D=>{D&&(this.getAutoSyncState()&&(!this.autoSyncStateHistory&&D?.history&&this.updateLiveStateSyncInputDataLocally(D.history),D?.current&&this.updateLiveStateSyncInputDataLocally({[D.current.liveStateDataId]:D.current})),!this.autoSyncStateHistory&&D?.history&&(this.autoSyncStateHistory=D.history))}),this.docService.addPreDocumentIdChangeFunction("live-state-service",D=>this.isUserEditor()?.isEditor&&(!this.getSingleEditorModeConfig()?.singleTabEditor||this.isUserEditor()?.isEditorOnCurrentTab)?this.removeEditorAccess():Promise.resolve())}catch(D){this.loggingService.catch("Error in LiveStateService constructor: ",D)}}observeElementAddedOnDom(){try{this.loggingService.log("%c[WB] Calling FUNCTION: observeElementAddedOnDom","color: green;"),this.childListMutationSubscription&&(this.childListMutationSubscription.unsubscribe(),this.childListMutationSubscription=null),this.childListMutationSubscription=this.domService.getChildListMutation$().subscribe(e=>{e?.length&&e.forEach(i=>{let r=Array.from(i.addedNodes||[]).filter(a=>a instanceof HTMLElement);r?.forEach(a=>{xV(a,!0)?.forEach(p=>{typeof p?.getAttribute=="function"&&p?.getAttribute(U.ATTRIBUTES.VELT_SYNC_STATE)&&this.subscribeInputChanges(p)})}),r?.length&&this.isEditor$?.value?.isEditor===!1&&(this.disableInputElements(),this.disableElementEvents())})},e=>{this.loggingService.catch("Error in LiveStateService domService getChildListMutation$ subscription: ",e)})}catch(e){this.loggingService.catch("Error in LiveStateService observeElementAddedOnDom: ",e)}}detectKeydownOnInput(){try{this.loggingService.log("%c[WB] Calling FUNCTION: detectKeydownOnInput","color: green;"),this.unsubscribeKeydownSubscription(),this.keydownSubscription=this.domService.onWindowKeydown$().pipe(Ne(e=>e?.target instanceof HTMLInputElement||e?.target instanceof HTMLTextAreaElement||e?.target instanceof HTMLSelectElement),Ne(e=>!!this.isElementInsideSingleEditorModeContainerElements(e?.target)),Je(1)).subscribe(e=>{this.unsubscribeKeydownSubscription(),this.getSingleEditorModeConfig()?.customMode||this.setUserAsEditor()},e=>{this.loggingService.catch("Error in LiveStateService detectKeydownOnInput subscription: ",e)})}catch(e){this.loggingService.catch("Error in LiveStateService detectKeydownOnInput: ",e)}}unsubscribeKeydownSubscription(){try{this.loggingService.log("%c[WB] Calling FUNCTION: unsubscribeKeydownSubscription","color: green;"),this.keydownSubscription&&(this.keydownSubscription.unsubscribe(),this.keydownSubscription=null)}catch(e){this.loggingService.catch("Error in LiveStateService unsubscribeKeydownSubscription: ",e)}}getDocumentPaths(){try{this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentPaths","color: green;"),this.docService.getDocumentPaths$().subscribe(e=>{this.documentPaths=e,this.updateLiveStateDataFromDraft()})}catch(e){this.loggingService.catch("Error in LiveStateService getDocumentPaths: ",e)}}getUser(){try{this.loggingService.log("%c[WB] Calling FUNCTION: getUser","color: green;"),this.authService.getUser$().subscribe(e=>{this.user=e,this.updateLiveStateDataFromDraft()})}catch(e){this.loggingService.catch("Error in LiveStateService getUser: ",e)}}updateLiveStateDataFromDraft(){try{this.loggingService.log("%c[WB] Calling FUNCTION: updateLiveStateDataFromDraft","color: green;"),this.liveStateDataMapDraft?.custom&&this.user&&this.documentPaths&&(Object.keys(this.liveStateDataMapDraft.custom).forEach(e=>{this.setLiveStateData(e,this.liveStateDataMapDraft.custom[e])}),this.liveStateDataMapDraft={})}catch(e){this.loggingService.catch("Error in LiveStateService updateLiveStateDataFromDraft: ",e)}}subscribeLiveStateData(){return this.loggingService.log("%c[WB] Calling FUNCTION: getOnlineUsersOnCurrentDocument","color: green;"),Wn(this.afAuth).pipe(Ne(e=>!!e),ge(e=>this.isFeatureAllowed({firebaseUser:e,liveStateData:{}})),ge(e=>e.featureAllowed?this.iamService.isUserAllowed$().pipe(ce(i=>(e.featureAllowed=i,e))):re(e)),ge(e=>e.featureAllowed?this.authService.isPlanExpired$().pipe(ce(i=>(e.featureAllowed=!i,e))):re(e)),ge(e=>e.featureAllowed?re(e).pipe(ge(i=>this.docService.getDocumentPaths$().pipe(ce(r=>(this.documentPaths=r,i.documentPaths=r,i)))),In(i=>{this.serverConnectionState$?.value===ul.PENDING_INIT&&i?.documentPaths?.liveState&&this.serverConnectionState$.next(ul.PENDING_DATA)}),ge(i=>this.getDataFromDocumentId().pipe(ce(r=>(i.liveStateData=r,I({},i))))),ge(i=>this.getSingleEditorMode$().pipe(ce(()=>i))),ce(i=>{if(this.serverConnectionState$?.value!==ul.ONLINE&&this.serverConnectionState$.next(ul.ONLINE),i.liveStateData)this.liveStateDataMap$.next(i.liveStateData);else{let r=this.liveStateDataMap$.value;r&&Object.keys(r).length>0&&this.liveStateDataMap$.next({})}this.getSingleEditorMode()&&this.updateSingleEditorLiveSyncData(i?.liveStateData?.default?.singleEditorMode||{})})):re({})))}updateSingleEditorLiveSyncData(e){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: updateSingleEditorLiveSyncData","color: green;"),Co(e,{})&&!this.keydownSubscription&&this.detectKeydownOnInput(),e&&!e?.editor&&this.isEditor$?.value!==void 0&&this.isEditor$.next(void 0),Co(this.singleEditorLiveStateData,e))return;if(this.singleEditorLiveStateData=e,this.singleEditorLiveStateData$.next(e),this.singleEditorLiveStateData?.editor){let i=this.authService.getUser();this.singleEditorLiveStateData?.editor?.userId!==i?.userId?this.makeReader():this.makeEditor()}else this.isEditor$?.value!==void 0&&this.isEditor$.next(void 0),this.enableInputElements(),this.enableElementEvents();this.editorAccessTimerInterval&&this.singleEditorLiveStateData?.requestEditorAccess?.status!=="pending"&&this.clearEditorAccessTimerInterval(),this.requestAccessTimer&&this.singleEditorLiveStateData?.requestEditorAccess?.status!=="pending"?this.clearRequestAccessTimer():this.singleEditorLiveStateData?.requestEditorAccess?.status==="pending"&&this.isUserEditor()?.isEditor&&this.isUserEditor()?.isEditorOnCurrentTab&&this.setRequestAccessTimer(this.singleEditorLiveStateData?.requestEditorAccess?.editorAccessTimeout||U.LIVE_STATE_REQUEST_EDITOR_ACCESS_WAIT_TIME)}catch{}}isFeatureAllowed(e){return this.configService.getConfig$().pipe(Ne(i=>!!i),ce(i=>T(I({},e),{config:i})),ge(i=>this.authService.getUser$().pipe(ce(r=>T(I({},i),{user:r})))),ge(i=>Xi(i.config,i.user,Re.LIVE_STATE_SYNC)?re(T(I({},i),{featureAllowed:!0})):(this.loggingService.warn("Live state sync feature is not allowed."),re(T(I({},i),{featureAllowed:!1})))))}getDataFromDocumentId(e){return this.databaseService.getDb().pipe(Ne(i=>!!i),ge(i=>(this.db=i,this.configService?.getApiKey()&&this.documentPaths?.liveState?this.commonDbService.dbListener({feature:"allLiveStates",properties:{documentId:e??this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,skipFirestore:!0}}).pipe(ce(r=>r?.data),Ln(r=>(this.loggingService.catch("Error in LiveStateService getDataFromDocumentId: ",r),re({})))):re({}))))}getLiveStateData$(e,i){try{return this.loggingService.log("%c[WB] Calling FUNCTION: getLiveStateData$","color: green;"),Wn(this.afAuth).pipe(Ne(r=>!!r),ge(r=>this.isFeatureAllowed({firebaseUser:r,liveStateData:{}})),ge(r=>r.featureAllowed?this.iamService.isUserAllowed$().pipe(ce(a=>(r.featureAllowed=a,r))):re(r)),ge(r=>r.featureAllowed?this.authService.isPlanExpired$().pipe(ce(a=>(r.featureAllowed=!a,r))):re(r)),ge(r=>r.featureAllowed?re(r).pipe(ge(a=>this.docService.getDocumentPaths$().pipe(ce(s=>(this.documentPaths=s,a.documentPaths=s,a)))),ge(a=>{let s=i?.listenToNewChangesOnly?1:0;return this.getLiveStateDataFromDatabase$(e).pipe(xs(s))}),ce(a=>{if(a)if(e){let s=Rt(e+""),c=a?.[s];if(c){let p=c?.data;if(c?.tabId&&this.tabId&&c?.tabId===this.tabId)return;if(c?.isDataStringified&&typeof p=="string")try{p=JSON.parse(p)}catch{}return p}else return}else{let s={};return Object.keys(a||{}).forEach(c=>{if(a[c]?.liveStateDataId){let p=a[c],h=p?.data;if(p?.isDataStringified&&typeof h=="string")try{h=JSON.parse(h)}catch{}s[p.liveStateDataId]=h}}),s}return a})):re(void 0).pipe(Ne(Boolean))),Kt((r,a)=>JSON.stringify(r||{})===JSON.stringify(a||{})),Ne(r=>r!==void 0),ce(r=>r))}catch(r){return this.loggingService.catch("Error in LiveStateService getLiveStateData$: ",r),re(null)}}getLiveStateDataFromDatabase$(e){try{return this.databaseService.getDb().pipe(Ne(i=>!!i),ge(i=>{this.db=i;let r=e?Rt(e+""):void 0;return this.configService?.getApiKey()&&this.documentPaths?.liveState?this.commonDbService.dbListener({feature:r?"liveStateCustom":"allLiveStateCustoms",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,id:r,skipFirestore:!0}}).pipe(ce(a=>a?.data),ce(a=>{if(a)return r?{[r]:a}:a}),Ln(a=>(this.loggingService.catch("Error in LiveStateService getLiveStateDataFromDatabase$: ",a),re(null)))):re(void 0)}))}catch(i){return this.loggingService.catch("Error in LiveStateService getLiveStateDataFromDatabase$: ",i),re(void 0)}}setLiveStateData(e,i,r){return ee(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: setLiveStateData","color: green;");try{let a=this.authService.getUser();if(e&&this.documentPaths?.liveState&&a){let s=Rt(e+""),c=!1;try{if(r?.merge&&typeof i=="object"){let h=yield this.commonDbService.getData({feature:"liveStateCustom",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",id:s,skipFirestore:!0}});if(h?.isDataStringified){let _=JSON.parse(h?.data);typeof i=="object"&&(i=I(I({},_),i))}}}catch{}try{typeof i=="object"&&(i=JSON.stringify(i),c=!0)}catch{}let p={id:s,lastUpdated:this.timestamp,liveStateDataId:e,data:i,updatedBy:a,tabId:this.tabId,isDataStringified:c};yield this.commonDbService.setData({feature:"liveStateCustom",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",id:s,skipFirestore:!0},data:JSON.parse(JSON.stringify(p))})}else this.loggingService.warn("liveStateDataId or documentPaths or user is null"),this.liveStateDataMapDraft?.custom||(this.liveStateDataMapDraft.custom={}),e&&(this.liveStateDataMapDraft.custom[e]=i)}catch(a){this.loggingService.catch("Error in LiveStateService _setLiveStateData: ",a)}})}getFormElements(){try{return this.loggingService.log("%c[WB] Calling FUNCTION: getInputElements","color: green;"),document.querySelectorAll("input, textarea, select, button, [contenteditable]")}catch(e){return this.loggingService.catch("Error in LiveStateService getInputElements: ",e),null}}disableInputElements(){try{this.loggingService.log("%c[WB] Calling FUNCTION: disableInputElements","color: green;"),this.getFormElements()?.forEach(i=>{if(this.isElementInsideSingleEditorModeContainerElements(i)&&!this.isSingleEditorModeDisabledForElement(i)&&!ji(i)){let r=i?.hasAttribute("disabled");i?.hasAttribute("contenteditable")&&(r=i?.getAttribute("contenteditable")==="false"),r||(i.setAttribute("disabled","true"),i.setAttribute(U.ATTRIBUTES.VELT_SYNC_ACCESS_AUTO,"true"),i?.hasAttribute("contenteditable")&&i.setAttribute("contenteditable","false"))}})}catch(e){this.loggingService.catch("Error in LiveStateService disableInputElements: ",e)}}enableInputElements(){try{this.loggingService.log("%c[WB] Calling FUNCTION: enableInputElements","color: green;"),this.getFormElements()?.forEach(i=>{i?.hasAttribute(U.ATTRIBUTES.VELT_SYNC_ACCESS_AUTO)&&(i.removeAttribute("disabled"),i.removeAttribute(U.ATTRIBUTES.VELT_SYNC_ACCESS_AUTO),i?.getAttribute("contenteditable")&&i.setAttribute("contenteditable","true"))})}catch(e){this.loggingService.catch("Error in LiveStateService enableInputElements: ",e)}}disableElementEvents(){try{this.loggingService.log("%c[WB] Calling FUNCTION: disableElementEvents","color: green;"),document.querySelectorAll(`[${U.ATTRIBUTES.VELT_SYNC_ACCESS}]`)?.forEach(i=>{let r=this.domService.getXPath(i);r&&!this.preventEventsOnElementMap[r]&&(this.preventEventsOnElementMap[r]={element:i,events:{}},this.PREVENT_EVENTS.forEach(a=>{let s=oi(i,a,{capture:!0}).subscribe(c=>{try{c.preventDefault(),c.stopPropagation()}catch(p){this.loggingService.catch("Error in LiveStateService disableElementEvents subscription: ",p)}});this.preventEventsOnElementMap[r]?.events[a]?.unsubscribe(),this.preventEventsOnElementMap[r].events[a]=s}))})}catch(e){this.loggingService.catch("Error in LiveStateService disableElementClicks: ",e)}}enableElementEvents(){try{this.loggingService.log("%c[WB] Calling FUNCTION: enableElementEvents","color: green;"),Object.keys(this.preventEventsOnElementMap).forEach(e=>{let i=this.preventEventsOnElementMap[e];Object.keys(i.events||{}).forEach(r=>{i?.events[r]?.unsubscribe()})}),this.preventEventsOnElementMap={}}catch(e){this.loggingService.catch("Error in LiveStateService enableElementClicks: ",e)}}setUserAsEditor(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: setUserAsEditor","color: green;"),this.user&&this.documentPaths?.liveStateSingleEditorMode){let e={editor:this.user,tabId:this.tabId,editorAt:this.timestamp};this.commonDbService.setData({feature:"liveStateSingleEditorMode",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",skipFirestore:!0},data:JSON.parse(JSON.stringify(e))}),this.analyticsService.trackEvent(Z.Events.LiveStateSync.SET_USER_AS_EDITOR_TRIGGERED,{editorUserId:this.user?.userSnippylyId,tabId:this.tabId})}}catch(e){this.loggingService.catch("Error in LiveStateService setUserAsEditor: ",e)}}setRequestAccessTimer(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setRequestAccessTimer","color: green;"),this.requestAccessTimer||(this.requestAccessTimer=setTimeout(()=>{this.getEditorAccessTransferOnTimeOut()&&this.acceptEditorAccessRequest(),this.clearRequestAccessTimer()},e*1e3),this.setEditorAccessTimerInterval(e))}catch(i){this.loggingService.catch("Error in LiveStateService setRequestAccessTimer: ",i)}}clearRequestAccessTimer(){try{this.loggingService.log("%c[WB] Calling FUNCTION: clearRequestAccessTimer","color: green;"),this.requestAccessTimer&&(clearTimeout(this.requestAccessTimer),this.requestAccessTimer=null)}catch(e){this.loggingService.catch("Error in LiveStateService clearRequestAccessTimer: ",e)}}requestEditorAccess(){this.loggingService.log("%c[WB] Calling FUNCTION: requestEditorAccess","color: green;");try{return this.analyticsService.trackEvent(Z.Events.LiveStateSync.REQUEST_EDITOR_ACCESS_TRIGGERED),new Ft(e=>{let i=null;try{if(this.user&&this.documentPaths?.liveStateSingleEditorMode){let r=this.getEditorAccessTimeout(),a=on(this.db,`${this.documentPaths?.liveStateSingleEditorMode}`),s={requestEditorAccess:{user:this.user,requestedAt:this.timestamp,status:"pending",editorAccessTimeout:r,tabId:this.tabId}};this.commonDbService.updateData({feature:"liveStateSingleEditorMode",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",skipFirestore:!0},errorCallback:c=>{this.loggingService.catch("Error in LiveStateService requestEditorAccess: ",c),e.next(null),e.complete()},callback:()=>{r&&(this.requestAccessTimer=setTimeout(()=>{this.getEditorAccessTransferOnTimeOut()&&this.setUserAsEditor()},(r+3)*1e3),this.setEditorAccessTimerInterval(r+3)),i=this.getSingleEditorLiveStateData$().subscribe(c=>{c&&(c?.requestEditorAccess?c?.requestEditorAccess?.status==="cancelled"&&(e.next(null),e.complete()):c?.editor?.userId===this.user?.userId?(e.next(!0),e.complete()):(e.next(!1),e.complete()))})},data:JSON.parse(JSON.stringify(s))})}else e.next(!1),e.complete()}catch(r){this.loggingService.catch("Error in LiveStateService requestEditorAccess: ",r),e.next(null),e.complete()}return()=>{i&&i?.unsubscribe()}})}catch(e){return this.loggingService.catch("Error in LiveStateService requestEditorAccess: ",e),re(null)}}makeEditor(){try{this.loggingService.log("%c[WB] Calling FUNCTION: makeEditor","color: green;");let e=this.singleEditorLiveStateData?.tabId===this.tabId;this.isEditor$.next({isEditor:!0,isEditorOnCurrentTab:e}),this.getSingleEditorModeConfig()?.customMode||(!this.getSingleEditorModeConfig()?.singleTabEditor||e?(this.enableInputElements(),this.enableElementEvents()):(this.disableInputElements(),this.disableElementEvents()))}catch(e){this.loggingService.catch("Error in LiveStateService makeEditor: ",e)}}makeReader(){try{this.loggingService.log("%c[WB] Calling FUNCTION: makeReader","color: green;"),this.isEditor$.next({isEditor:!1,isEditorOnCurrentTab:!1}),this.getSingleEditorModeConfig()?.customMode||(this.disableInputElements(),this.disableElementEvents())}catch(e){this.loggingService.catch("Error in makeReader: ",e)}}acceptEditorAccessRequest(){return ee(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: acceptEditorAccessRequest","color: green;"),this.user&&this.singleEditorLiveStateData?.requestEditorAccess&&this.isUserEditor()?.isEditor&&this.documentPaths?.liveStateSingleEditorMode){let e=this.singleEditorLiveStateData?.requestEditorAccess?.user,i=this.singleEditorLiveStateData?.requestEditorAccess?.tabId;if(e&&i){let r={editor:e,requestEditorAccess:null,tabId:i,editorAt:this.timestamp};this.commonDbService.updateData({feature:"liveStateSingleEditorMode",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",skipFirestore:!0},data:JSON.parse(JSON.stringify(r))}),this.analyticsService.trackEvent(Z.Events.LiveStateSync.ACCEPT_EDITOR_ACCESS_REQUEST_TRIGGERED,{editorUserId:e?.userSnippylyId,tabId:i})}}}catch(e){this.loggingService.catch("Error in acceptEditorAccessRequest: ",e)}})}rejectEditorAccessRequest(){return ee(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: rejectEditorAccessRequest","color: green;"),this.user&&this.singleEditorLiveStateData?.requestEditorAccess&&this.isUserEditor()?.isEditor&&this.documentPaths?.liveStateSingleEditorMode){let e={requestEditorAccess:null};this.commonDbService.updateData({feature:"liveStateSingleEditorMode",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",skipFirestore:!0},data:JSON.parse(JSON.stringify(e))}),this.analyticsService.trackEvent(Z.Events.LiveStateSync.REJECT_EDITOR_ACCESS_REQUEST_TRIGGERED)}}catch(e){this.loggingService.catch("Error in LiveStateService rejectEditorAccessRequest: ",e)}})}cancelEditorAccessRequest(){return ee(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: cancelEditorAccessRequest","color: green;"),this.user&&this.singleEditorLiveStateData?.requestEditorAccess&&this.documentPaths?.liveStateSingleEditorMode){let e={requestEditorAccess:T(I({},this.singleEditorLiveStateData?.requestEditorAccess),{status:"cancelled"})};this.commonDbService.updateData({feature:"liveStateSingleEditorMode",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",skipFirestore:!0},data:JSON.parse(JSON.stringify(e))}),e={requestEditorAccess:null},this.commonDbService.updateData({feature:"liveStateSingleEditorMode",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",skipFirestore:!0},data:JSON.parse(JSON.stringify(e))}),this.analyticsService.trackEvent(Z.Events.LiveStateSync.CANCEL_EDITOR_ACCESS_REQUEST_TRIGGERED)}}catch(e){this.loggingService.catch("Error in LiveStateService cancelEditorAccessRequest: ",e)}})}editCurrentTab(){return ee(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: editCurrentTab","color: green;"),this.user&&this.isUserEditor()?.isEditor&&!this.isUserEditor()?.isEditorOnCurrentTab&&this.documentPaths?.liveStateSingleEditorMode){let e={tabId:this.tabId};this.commonDbService.updateData({feature:"liveStateSingleEditorMode",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",skipFirestore:!0},data:JSON.parse(JSON.stringify(e))}),this.analyticsService.trackEvent(Z.Events.LiveStateSync.EDIT_CURRENT_TAB_TRIGGERED,{tabId:this.tabId})}}catch(e){this.loggingService.catch("Error in LiveStateService editCurrentTab: ",e)}})}isUserEditor$(){try{return this.loggingService.log("%c[WB] Calling FUNCTION: isUserEditor$","color: green;"),this.isEditor$.asObservable()}catch(e){return this.loggingService.catch("Error in LiveStateService isUserEditor$: ",e),re(null)}}isUserEditor(){try{return this.loggingService.log("%c[WB] Calling FUNCTION: isUserEditor","color: green;"),this.isEditor$.value}catch(e){return this.loggingService.catch("Error in LiveStateService isUserEditor: ",e),null}}getEditor$(){try{return this.loggingService.log("%c[WB] Calling FUNCTION: getEditor$","color: green;"),this.getSingleEditorLiveStateData$().pipe(ce(e=>e?.editor||null),Kt())}catch(e){return this.loggingService.catch("Error in LiveStateService getEditor$: ",e),re(null)}}isEditorAccessRequested$(){try{return this.loggingService.log("%c[WB] Calling FUNCTION: isEditorAccessRequested$","color: green;"),this.isUserEditor$().pipe(ge(e=>e?.isEditor?this.singleEditorLiveStateData$.pipe(ce(i=>i?.requestEditorAccess?{requestStatus:"requested",requestedBy:i?.requestEditorAccess?.user}:null)):re(null)),Kt((e,i)=>JSON.stringify(e||{})===JSON.stringify(i||{})))}catch(e){return this.loggingService.catch("Error in LiveStateService isEditorAccessRequested$: ",e),re(null)}}removeEditorAccess(){return ee(this,null,function*(){try{this.loggingService.log("%c[WB] Calling FUNCTION: removeEditorAccess","color: green;"),(this.user||this.authService.getAuthUser())&&this.documentPaths?.liveStateSingleEditorMode&&(yield this.commonDbService.deleteData({feature:"liveStateSingleEditorMode",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",skipFirestore:!0}}))}catch(e){this.loggingService.catch("Error in LiveStateService removeEditorAccess: ",e)}})}getSingleEditorLiveStateData$(){return this.singleEditorLiveStateData$.asObservable()}enableSingleEditorMode(e){try{if(this.singleEditorMode$.value===!0)return;this.singleEditorMode$.next(!0),e?this.singleEditorModeConfig$.next(e):this.singleEditorModeConfig$.next(new cM)}catch(i){this.loggingService.catch("Error in LiveStateService enableSingleEditorMode: ",i)}}disableSingleEditorMode(){try{if(this.singleEditorMode$.value===!1)return;this.singleEditorMode$.next(!1)}catch(e){this.loggingService.catch("Error in LiveStateService disableSingleEditorMode: ",e)}}getSingleEditorMode$(){return this.singleEditorMode$.asObservable()}getSingleEditorMode(){return this.singleEditorMode$.value}getSingleEditorModeConfig$(){return this.singleEditorModeConfig$.asObservable()}getSingleEditorModeConfig(){return this.singleEditorModeConfig$.value}enableAutoSyncState(){try{if(this.autoSyncState$.value===!0)return;this.autoSyncState$.next(!0)}catch(e){this.loggingService.catch("Error in LiveStateService enableAutoSyncState: ",e)}}disableAutoSyncState(){try{if(this.autoSyncState$.value===!1)return;this.autoSyncState$.next(!1)}catch(e){this.loggingService.catch("Error in LiveStateService disableAutoSyncState: ",e)}}getAutoSyncState$(){return this.autoSyncState$.asObservable()}getAutoSyncState(){return this.autoSyncState$.value}setEditorAccessTimeout(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setEditorAccessTimeout","color: green;"),e&&this.editorAccessTimeout$.next(e)}catch(i){this.loggingService.catch("Error in LiveStateService setEditorAccessTimeout: ",i)}}getEditorAccessTimeout$(){return this.editorAccessTimeout$.asObservable()}getEditorAccessTimeout(){return this.editorAccessTimeout$.value}enableEditorAccessTransferOnTimeOut(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableEditorAccessTransferOnTimeOut","color: green;"),this.editorAccessTransferOnTimeOut$.value===!0)return;this.editorAccessTransferOnTimeOut$.next(!0)}catch(e){this.loggingService.catch("Error in LiveStateService enableEditorAccessTransferOnTimeOut: ",e)}}disableEditorAccessTransferOnTimeOut(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableEditorAccessTransferOnTimeOut","color: green;"),this.editorAccessTransferOnTimeOut$.value===!1)return;this.editorAccessTransferOnTimeOut$.next(!1)}catch(e){this.loggingService.catch("Error in LiveStateService disableEditorAccessTransferOnTimeOut: ",e)}}getEditorAccessTransferOnTimeOut$(){return this.editorAccessTransferOnTimeOut$.asObservable()}getEditorAccessTransferOnTimeOut(){return this.editorAccessTransferOnTimeOut$.value}enableDefaultSingleEditorUI(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableDefaultSingleEditorUI","color: green;"),this.defaultSingleEditorUIEnabled$.value===!0)return;this.defaultSingleEditorUIEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in LiveStateService enableDefaultSingleEditorUI: ",e)}}disableDefaultSingleEditorUI(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableDefaultSingleEditorUI","color: green;"),this.defaultSingleEditorUIEnabled$.value===!1)return;this.defaultSingleEditorUIEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in LiveStateService disableDefaultSingleEditorUI: ",e)}}getDefaultSingleEditorUIEnabled$(){return this.defaultSingleEditorUIEnabled$.asObservable()}getDefaultSingleEditorUIEnabled(){return this.defaultSingleEditorUIEnabled$.value}setEditorAccessTimerInterval(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setEditorAccessTimerInterval","color: green;"),this.clearEditorAccessTimerInterval(),e>0&&(this.editorAccessTimer$.next({state:"inProgress",durationLeft:e}),this.editorAccessTimerInterval=setInterval(()=>{try{e-=1,e<0?this.clearEditorAccessTimerInterval():e?this.editorAccessTimer$.next({state:"inProgress",durationLeft:e}):this.editorAccessTimer$.next({state:"completed"})}catch(i){this.loggingService.catch("Error in LiveStateService setEditorAccessTimerCountdown interval: ",i),this.clearEditorAccessTimerInterval()}},1e3))}catch(i){this.loggingService.catch("Error in LiveStateService setEditorAccessTimerCountdown: ",i),this.clearEditorAccessTimerInterval()}}clearEditorAccessTimerInterval(){try{this.loggingService.log("%c[WB] Calling FUNCTION: clearEditorAccessTimerInterval","color: green;"),this.editorAccessTimerInterval&&(clearInterval(this.editorAccessTimerInterval),this.editorAccessTimerInterval=null,this.editorAccessTimer$.next({state:"idle"}))}catch(e){this.loggingService.catch("Error in LiveStateService clearEditorAccessTimerInterval: ",e)}}getEditorAccessTimer$(){return this.editorAccessTimer$.asObservable()}onServerConnectionStateChange$(){return this.serverConnectionState$.asObservable()}detectLiveSyncInputs(){try{document.querySelectorAll(`[${U.ATTRIBUTES.VELT_SYNC_STATE}]`)?.forEach(i=>{this.subscribeInputChanges(i)})}catch(e){this.loggingService.catch("Error in LiveStateService detectLiveSyncInputs: ",e)}}subscribeInputChanges(e){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: subscribeInputChanges","color: green;"),e){let i=e.tagName,r=this.domService.getXPath(e),a=Rt(r);if(this.inputChangeSubscriptionMap[a])this.loggingService.warn("subscription already exists",a,e);else{this.inputChangeSubscriptionMap[a]={id:a,element:e};let s;switch(i?.toLowerCase()){case"input":s=oi(e,"input").pipe(jr(300)).subscribe(p=>{let h={value:p?.target?.value,tagName:p?.target?.tagName,type:p?.target?.type};this.setLiveStateSyncInputData(p?.target,h)});break;case"textarea":s=oi(e,"input").pipe(jr(300)).subscribe(p=>{let h={value:p?.target?.value,tagName:p?.target?.tagName};this.setLiveStateSyncInputData(p?.target,h)});break;default:e.getAttribute("contenteditable")&&(s=oi(e,"input").pipe(jr(300)).subscribe(p=>{let h={innerText:p?.target?.innerText,innerHTML:this.domService.sanitizeHtml(p?.target?.innerHTML),tagName:p?.target?.tagName,isContentEditable:!0};this.setLiveStateSyncInputData(p?.target,h)}));break}s&&(this.inputChangeSubscriptionMap[a]?.subscriptions||(this.inputChangeSubscriptionMap[a]={subscriptions:[]}),this.inputChangeSubscriptionMap[a].subscriptions?.push(s))}}}catch(i){this.loggingService.catch("Error in LiveStateService subscribeInputChanges: ",i)}}unsubscribeInputChanges(){try{this.loggingService.log("%c[WB] Calling FUNCTION: unsubscribeInputChanges","color: green;"),Object.keys(this.inputChangeSubscriptionMap).forEach(e=>{this.inputChangeSubscriptionMap[e]?.subscriptions?.forEach(r=>{r.unsubscribe()})}),this.inputChangeSubscriptionMap={}}catch(e){this.loggingService.catch("Error in LiveStateService unsubscribeInputChanges: ",e)}}setLiveStateSyncInputData(e,i){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: setLiveStateSyncInputData","color: green;"),this.user&&this.documentPaths?.liveState){let r=this.domService.getXPath(e),a=Rt(r),s={id:a,lastUpdated:this.timestamp,liveStateDataId:r,data:i,updatedBy:this.user,tabId:this.tabId};this.commonDbService.updateData({feature:"liveStateAutoSyncStateCurrent",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",skipFirestore:!0},data:JSON.parse(JSON.stringify(s))}),this.commonDbService.updateData({feature:"liveStateAutoSyncStateHistoryId",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",id:a,skipFirestore:!0},data:JSON.parse(JSON.stringify(s))})}}catch(r){this.loggingService.catch("Error in LiveStateService setLiveStateSyncInputData: ",r)}}updateLiveStateSyncInputDataLocally(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: updateLiveStateSyncInputDataLocally","color: green;"),this.user&&Object.keys(e).forEach(i=>{let r=e[i],a=this.domService.getElementFromXPath(r?.liveStateDataId),s=!1;if(r?.updatedBy?.userSnippylyId!==this.user?.userSnippylyId)s=!0;else{let c=r?.tabId&&this.tabId&&r?.tabId!==this.tabId,p=a?.contains(document.activeElement);c&&!eoe()&&!p&&(s=!0)}if(s&&a)switch(a.value=r?.data?.value,a.tagName?.toLowerCase()){case"input":a.value=r?.data?.value;break;case"textarea":a.value=r?.data?.value;break;default:a.getAttribute("contenteditable")&&(a.innerHTML=this.domService.sanitizeHtml(r?.data?.innerHTML))}})}catch(i){this.loggingService.catch("Error in LiveStateService updateLiveStateSyncInputDataLocally: ",i)}}setSingleEditorModeContainerIds(e){this.singleEditorModeContainerIds$.next(e||[])}getSingleEditorModeContainerIds(){return this.singleEditorModeContainerIds$.asObservable()}isElementInsideSingleEditorModeContainerElements(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: isElementInsideSingleEditorModeContainerElements","color: green;");let i=this.singleEditorModeContainerIds$.value,r=document.querySelectorAll(`[${U.ATTRIBUTES.VELT_SINGLE_EDITOR_MODE_CONTAINER}]`);if(!i?.length&&!r?.length)return!0;if(i?.length)for(let a=0;a<i.length;a++){let s=document.getElementById(i[a]);if(s&&s.contains(e))return!0}if(r?.length)for(let a=0;a<r.length;a++){let s=r[a];if(s&&s.contains(e))return!0}return!1}catch(i){return this.loggingService.catch("Error in LiveStateService isElementInsideSingleEditorModeContainerElements: ",i),!1}}isSingleEditorModeDisabledForElement(e){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: isSingleEditorModeDisabledForElement","color: green;"),e){if(e.getAttribute(U.ATTRIBUTES.VELT_SYNC_ACCESS_DISABLED))return!0;{let r=e?.parentElement;if(r)return this.isSingleEditorModeDisabledForElement(r)}}return!1}catch(i){return this.loggingService.catch("Error in LiveStateService isSingleEditorModeDisabledForElement: ",i),!1}}updateOnDatabaseDisconnect(){return this.loggingService.log("%c[WB] Calling FUNCTION: updateOnDatabaseDisconnect","color: green;"),this.isUserEditor$().pipe(In(e=>{try{if(this.documentPaths?.liveStateSingleEditorMode){let i=on(this.db,`${this.documentPaths?.liveStateSingleEditorMode}`);e?.isEditor&&(!this.getSingleEditorModeConfig()?.singleTabEditor||e?.isEditorOnCurrentTab)?cl(i).remove():cl(i).cancel()}}catch(i){this.loggingService.catch("Error in LiveStateService updateOnDatabaseDisconnect tap: ",i)}}))}updateServerStateOnDatabaseDisconnect(){return this.loggingService.log("%c[WB] Calling FUNCTION: updateServerStateOnDatabaseDisconnect","color: green;"),Wn(this.afAuth).pipe(Ne(e=>!!e),ge(e=>this.docService.getDocumentPaths$().pipe(ce(i=>e))),In(e=>ee(this,null,function*(){try{if(this.docService.getDocumentPaths()?.liveState&&e){let r=on(this.db,".info/connected"),a=!0;gu(r,s=>{let c=s.val();if(a&&c===!1){a=!1;return}a=!1,c===!1?this.serverConnectionState$.next(ul.OFFLINE):this.serverConnectionState$.value===ul.OFFLINE&&this.serverConnectionState$.next(ul.ONLINE)})}}catch(i){this.loggingService.catch("Error in updateServerStateOnDatabaseDisconnect:",i)}})))}get timestamp(){return this.commonDbService.getServerTimestamp()}};o.\u0275fac=function(i){return new(i||o)(J(vi),J(Qe),J(je),J($t),J(pn),J(lt),J(Fe),J(gn),J(y),J(bn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Cm=(()=>{let o=class o{constructor(e,i,r,a,s,c,p,h,_,E,D,B){this.analyticsService=e,this.docService=i,this.authService=r,this.afAuth=a,this.iamService=s,this.databaseService=c,this.configService=p,this.avatarService=h,this.loggingService=_,this.flockService=E,this.liveStateService=D,this.commonDbService=B,this.db=Ci(),this.presenceUser$=new fe(new dM),this.documentPaths=null,this.inactivityTime=5*60*1e3,this.presenceUsers$=new fe([]),this.presenceUsersSubscription=null,this.includeSelf$=new fe(!0),this.loggingService.log("%c[WB] Creating CLASS: PresenceService","color: blue;"),this.databaseService.getDb().pipe(Ne(G=>!!G),Je(1)).subscribe(G=>{G&&(this.db=G,this.getUser(),this.getDocumentPaths(),this.getLocation(),this.updateOnUserDbConnectionStateChange().subscribe(()=>{},X=>{this.loggingService.catch("Error in PresenceService constructor updateOnUserDbConnectionStateChange: ",X)}),this.updateOnDatabaseDisconnect().subscribe(()=>{},X=>{this.loggingService.catch("Error in PresenceService constructor updateOnDatabaseDisconnect: ",X)}),this.updateOnDocumentFocusChange(),this.updateOnAllowedFeatureListChange())},G=>{this.loggingService.catch("Error in PresenceService constructor: ",G)}),this.authService.addPreSignOutFuction("presence-signout",this.signOutUser.bind(this)),this.presenceUsers$.pipe(Vi()).subscribe(([G,X])=>{sessionStorage.getItem(U.SESSION_STORAGE.VELT_PRESENCE_MULTIPLE_USERS_DETECTED)||X?.length>1&&G.length!==X.length&&(this.analyticsService.trackEvent(Z.Events.Presence.PRESENCE_MULTIPLE_USERS_DETECTED,{totalUsers:X.length,presenceSnippylyUserIds:X.map(he=>he.userSnippylyId),presenceClientUserIds:X.map(he=>he.userId)}),sessionStorage.setItem(U.SESSION_STORAGE.VELT_PRESENCE_MULTIPLE_USERS_DETECTED,"true"))})}getUser(){this.loggingService.log("%c[WB] Calling FUNCTION: getUser","color: green;"),this.authService.getUser$().pipe(Ne(e=>!!e)).subscribe(e=>{e&&this.setPresenceUser(e)},e=>{this.loggingService.catch("Error in getUser: ",e)})}getDocumentPaths(){this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentPaths","color: green;"),this.docService.getDocumentPaths$().pipe(In(e=>{this.documentPaths=e}),Vi(),In(([e,i])=>{e&&this.updateUserStatusOnDocumentChange(U.PRESENCE_STATUS_OFFLINE,e),i&&this.updateUserStatusOnDocumentChange(U.PRESENCE_STATUS_ONLINE,i)})).subscribe(()=>{},e=>{this.loggingService.catch("Error in getDocumentPaths: ",e)})}getLocation(){this.docService.getLocation$().pipe(In(e=>{this.updateUserOnLocationChange(e)})).subscribe(()=>{},e=>{this.loggingService.catch("Error in getLocation: ",e)})}getPresenceUser(){return this.loggingService.log("%c[WB] Calling FUNCTION: getPresenceUser","color: green;"),this.presenceUser$.asObservable()}getOnlineUsersOnCurrentDocument(){return this.loggingService.log("%c[WB] Calling FUNCTION: getOnlineUsersOnCurrentDocument","color: green;"),Wn(this.afAuth).pipe(Ne(e=>!!e),ge(e=>this.isFeatureAllowed({firebaseUser:e,users:[],filteredUsers:[]})),ge(e=>e.featureAllowed?this.iamService.isUserAllowed$().pipe(ce(i=>(e.featureAllowed=i,e))):re(e)),ge(e=>e.featureAllowed?this.authService.isPlanExpired$().pipe(ce(i=>(e.featureAllowed=!i,e))):re(e)),ge(e=>e.featureAllowed?re(e).pipe(ge(i=>this.docService.getDocumentPaths$().pipe(ce(r=>(this.documentPaths=r,i.documentPaths=r,i)))),ge(i=>this.getDataFromDocumentId().pipe(ce(r=>(i.users=r||[],I({},i))))),ce(i=>(i.filteredUsers=this.filterOnlineUsers(i.users,i.firebaseUser),i)),ge(i=>this.getIncludeSelf$().pipe(ce(r=>(r||(i.filteredUsers=i?.filteredUsers?.filter(a=>a?.userSnippylyId!==i.user?.userSnippylyId)),i)))),ge(i=>i?.filteredUsers?re(i?.filteredUsers||[]):re([]))):re([])))}isFeatureAllowed(e){return this.configService.getConfig$().pipe(Ne(i=>!!i),ce(i=>T(I({},e),{config:i})),ge(i=>this.authService.getUser$().pipe(ce(r=>T(I({},i),{user:r})))),ge(i=>Xi(i.config,i.user,Re.PRESENCE)?re(T(I({},i),{featureAllowed:!0})):(this.loggingService.warn("Presence feature is not allowed."),re(T(I({},i),{featureAllowed:!1})))))}getDataFromDocumentId(e){return this.databaseService.getDb().pipe(Ne(i=>!!i),ge(i=>(this.db=i,this.loggingService.log(this.db),this.configService?.getApiKey()&&this.documentPaths?.presence?this.commonDbService.dbListener({feature:"allPresence",properties:{documentId:e??this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,skipFirestore:!0}}).pipe(Ln(r=>(this.loggingService.catch("Error in PresenceService getDataFromDocumentId: ",r),re(null))),ce(r=>r?.data),ce(r=>{let a=[];return r&&(a=Object.values(r).filter(s=>typeof s=="object")),a})):re([]))))}filterOnlineUsers(e,i){this.loggingService.log("%c[WB] Calling FUNCTION: filterOnlineUsers","color: green;");try{let a=e.slice().filter(s=>{let c=Sp(s.timestamp);return s.userSnippylyId&&(s.onlineStatus===U.PRESENCE_STATUS_ONLINE||s.onlineStatus===U.PRESENCE_STATUS_AWAY)&&c<this.inactivityTime});return this.presenceUsers$.next(a),a}catch(r){return this.loggingService.catch("Error in filterOnlineUsers:",r),[]}}enableIncludeSelf(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableIncludeSelf","color: green;"),this.includeSelf$.value===!0)return;this.includeSelf$.next(!0)}catch(e){this.loggingService.catch("Error in PresenceService enableIncludeSelf: ",e)}}disableIncludeSelf(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableIncludeSelf","color: green;"),this.includeSelf$.value===!1)return;this.includeSelf$.next(!1)}catch(e){this.loggingService.catch("Error in PresenceService disableIncludeSelf: ",e)}}getIncludeSelf$(){return this.includeSelf$.asObservable()}getIncludeSelf(){return this.includeSelf$.value}getPresenceUserFromExternalId(e){try{if(this.presenceUsers$.value&&this.presenceUsers$.value.length>0){let i=this.presenceUsers$.value.find(r=>r.userId===e);if(i)return i}return null}catch(i){return this.loggingService.catch("Error in getNameFromSnippylyId:",i),null}}getAnonymousAvatarImage(){return this.loggingService.log("%c[WB] Calling FUNCTION: getAnonymousAvatarImage","color: green;"),this.avatarService.generateUserImage()}updateCurrentPresenceUser(e){return ee(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: updateCurrentPresenceUser","color: green;");try{if(this.documentPaths?.presence&&e&&e.userId&&this.authService.isFeatureAllowed(Re.PRESENCE)){if(!e.isAnonymous){e.pageInfo=new Zi;let i=JSON.parse(JSON.stringify(e));this.authService.getUser()&&this.commonDbService.updateData({feature:"presence",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,userId:e.userSnippylyId,skipFirestore:!0},data:JSON.parse(JSON.stringify(T(I({},i),{timestamp:this.timestamp})))})}this.presenceUser$.next(e)}}catch(i){this.loggingService.catch("Error in updateCurrentPresenceUser:",i)}})}setCurrentPresenceUserStatus(e){return ee(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: setCurrentPresenceUserStatus","color: green;");try{this.loggingService.log(e);let i=this.presenceUser$.value;if(i.onlineStatus!==e){this.presenceUsersSubscription&&this.presenceUsersSubscription?.unsubscribe();let r=i.onlineStatus,a=e;this.presenceUsersSubscription=this.getPresenceUsers$().pipe(Ne(s=>!!s?.length),Je(1)).subscribe(s=>{s?.length>1&&this.analyticsService.trackEvent(Z.Events.Presence.PRESENCE_USER_STATUS_CHANGED,{oldStatus:r,newStatus:a,totalUsers:s?.length,presenceSnippylyUserIds:s?.map(c=>c.userSnippylyId),presenceClientUserIds:s?.map(c=>c.userId)})})}i.onlineStatus=e,e===U.PRESENCE_STATUS_OFFLINE&&this.flockService.isInSession()&&this.flockService.removeCurrentUserFromSession(),e===U.PRESENCE_STATUS_OFFLINE&&this.liveStateService.isUserEditor()?.isEditor&&this.liveStateService.removeEditorAccess(),this.updateCurrentPresenceUser(i)}catch(i){this.loggingService.catch("Error in setCurrentPresenceUserStatus:",i)}})}updateUserStatusOnDocumentChange(e,i){return ee(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: updateUserStatusOnDocumentChange","color: green;");try{let r=this.presenceUser$.value;if(r.onlineStatus=e,i?.presence&&r&&r.userId&&!r.isAnonymous&&this.authService.isFeatureAllowed(Re.PRESENCE)){let a=JSON.parse(JSON.stringify(r));this.commonDbService.updateData({feature:"presence",properties:{documentId:i?.documentId,organizationId:i?.organizationId,userId:r.userSnippylyId,skipFirestore:!0},data:JSON.parse(JSON.stringify(a))})}}catch(r){this.loggingService.catch("Error in updateUserStatusOnDocumentChange:",r)}})}updateUserOnLocationChange(e){return ee(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: updateUserOnLocationChange","color: green;");try{let i=this.presenceUser$.value;if(i.location=e?e.location:null,i.locationId=e?e?.locationId:null,this.documentPaths?.presence&&i&&i.userId&&!i.isAnonymous&&this.authService.isFeatureAllowed(Re.PRESENCE)){let r=JSON.parse(JSON.stringify(i));this.commonDbService.updateData({feature:"presence",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,userId:i.userSnippylyId,skipFirestore:!0},data:JSON.parse(JSON.stringify(r))})}}catch(i){this.loggingService.catch("Error in updateUserOnLocationChange:",i)}})}updateOnUserDbConnectionStateChange(){this.loggingService.log("%c[WB] Calling FUNCTION: updateOnUserDbConnectionStateChange","color: green;");let e=on(this.db,".info/connected"),i=Af(e).pipe(ce(r=>r?U.PRESENCE_STATUS_ONLINE:U.PRESENCE_STATUS_OFFLINE));return Wn(this.afAuth).pipe(xs(1),ge(r=>r?i:re(U.PRESENCE_STATUS_OFFLINE)),In(r=>this.setCurrentPresenceUserStatus(r)))}updateOnDocumentFocusChange(){this.loggingService.log("%c[WB] Calling FUNCTION: updateOnDocumentFocusChange","color: green;");try{document&&document.addEventListener("visibilitychange",e=>{this.authService.getUser()&&(document.visibilityState==="hidden"?(this.setCurrentPresenceUserStatus(U.PRESENCE_STATUS_AWAY),this.flockService.getFlockMode()&&this.flockService.setTabFocused(!1)):(this.setCurrentPresenceUserStatus(U.PRESENCE_STATUS_ONLINE),this.flockService.getFlockMode()&&this.flockService.setTabFocused(!0)))}),window&&(window.addEventListener("focus",()=>{this.authService.getUser()&&(this.setCurrentPresenceUserStatus(U.PRESENCE_STATUS_ONLINE),this.flockService.getFlockMode()&&this.flockService.setWindowFocused(!0))}),window.addEventListener("blur",()=>{this.authService.getUser()&&(document.visibilityState!=="hidden"&&this.setCurrentPresenceUserStatus(U.PRESENCE_STATUS_AWAY),this.flockService.getFlockMode()&&this.flockService.setWindowFocused(!1))}))}catch(e){this.loggingService.catch("Error in updateOnDocumentFocusChange:",e)}}updateOnAllowedFeatureListChange(){try{this.configService.getConfig$().subscribe(e=>{if(e&&e.featureAllowList?.length){let i=this.presenceUser$.value,r=!1;if(e.featureAllowList.includes(Re.PRESENCE)?i?.onlineStatus!==U.PRESENCE_STATUS_ONLINE&&(i.onlineStatus=U.PRESENCE_STATUS_ONLINE,r=!0):i?.onlineStatus!==U.PRESENCE_STATUS_OFFLINE&&(i.onlineStatus=U.PRESENCE_STATUS_OFFLINE,r=!0),r&&this.authService.getUser()&&this.documentPaths?.presence&&i&&i.userId&&!i.isAnonymous){let a=JSON.parse(JSON.stringify(i));this.commonDbService.updateData({feature:"presence",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,userId:i.userSnippylyId,skipFirestore:!0},data:JSON.parse(JSON.stringify(a))})}}})}catch(e){this.loggingService.catch("Error in updateOnAllowedFeatureListChange:",e)}}updateOnDatabaseDisconnect(){return this.loggingService.log("%c[WB] Calling FUNCTION: updateOnDatabaseDisconnect","color: green;"),Wn(this.afAuth).pipe(Ne(e=>!!e),ge(e=>this.docService.getDocumentPaths$().pipe(ce(i=>e))),In(e=>ee(this,null,function*(){try{if(this.documentPaths?.presence&&e){let i=yield ad(e,!0).catch(a=>null);if(!i)return;let{user:r}=i.claims;if(!r?.isAnonymous){let a=on(this.db,`${this.documentPaths.presence}/${e.uid}`);this.flockService.isInSession()&&this.flockService.removeCurrentUserFromSession(),this.liveStateService.isUserEditor()?.isEditor&&this.liveStateService.removeEditorAccess(),cl(a).update({onlineStatus:U.PRESENCE_STATUS_OFFLINE,timestamp:this.timestamp}).catch(s=>{this.loggingService.catch("Error in updateOnDatabaseDisconnect:",s)})}}}catch(i){this.loggingService.catch("Error in updateOnDatabaseDisconnect:",i)}})))}setPresenceUser(e){this.loggingService.log("%c[WB] Calling FUNCTION: setPresenceUser","color: green;");try{let i=this.presenceUser$.value;i.userId=e?.userId,i.name=e?.name,i.email=e?.email,i.photoUrl=e?.photoUrl,i.userSnippylyId=e?.userSnippylyId,i.color=e?.color,i.textColor=e?.textColor,i.initial=e?.initial,i.timestamp=this.timestamp,i.type=e?.type,i.isReadOnly=e?.isReadOnly,i.isAnonymous=e?.isAnonymous;let r=e?.name?.split(" ");if(r&&r.length>0){let a=r[0],s=r.length>1?r[r.length-1]:null,c=s?s[0]:null;a&&(i.name=`${a} ${c?c+".":""}`)}this.updateCurrentPresenceUser(i)}catch(i){this.loggingService.catch("Error in setPresenceUser:",i)}}signOutUser(e){return new Promise((i,r)=>{try{this.documentPaths?.presence&&e?this.commonDbService.dbListener({feature:"presence",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,userId:e.uid,skipFirestore:!0}}).pipe(Je(1)).subscribe(a=>{a?.data?(this.flockService.isInSession()&&this.flockService.removeCurrentUserFromSession(),this.liveStateService.isUserEditor()?.isEditor&&this.liveStateService.removeEditorAccess(),this.commonDbService.updateData({feature:"presence",errorCallback:s=>{r(s)},callback:()=>{i(null)},properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,userId:e.uid,skipFirestore:!0},data:JSON.parse(JSON.stringify(T(I({},a?.data??{}),{timestamp:this.timestamp,onlineStatus:U.PRESENCE_STATUS_OFFLINE})))})):i(null)},a=>{this.loggingService.catch("Error in signOutUser subscription: ",a),r(a)}):i(null)}catch(a){this.loggingService.catch("Error in signOutUser:",a),r(a)}})}setInactivityTime(e){this.inactivityTime=e,this.analyticsService.trackEvent(Z.Events.Presence.PRESENCE_SET_CUSTOM_INACTIVITY_TIMER,{inactivityTime:this.inactivityTime})}getPresenceUsers$(){return this.presenceUsers$.asObservable()}getPresenceUsers(){return this.presenceUsers$.value}get timestamp(){return this.commonDbService.getServerTimestamp()}};o.\u0275fac=function(i){return new(i||o)(J(Qe),J(lt),J(je),J(vi),J(gn),J(pn),J($t),J(gm),J(y),J(vc),J(Di),J(bn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var qv=(()=>{let o=class o{constructor(e,i,r,a,s,c,p,h,_,E,D){this.analyticsService=e,this.configService=i,this.presenceService=r,this.docService=a,this.afAuth=s,this.iamService=c,this.domService=p,this.databaseService=h,this.authService=_,this.loggingService=E,this.commonDbService=D,this.db=Df(),this.cursorUser$=new fe(new Fv),this.documentPaths=null,this.inactivityTime=2*60*1e3,this.allowedElementIds$=new fe([]),this.cursorTagAvailable$=new fe(!1),this.cursorTagAvailable=!1,this.cursorUsers$=new fe([]),this.loggingService.log("%c[WB] Creating CLASS: CursorService","color: blue;");try{this.checkCursorTagAvailable(),this.databaseService.getDb().pipe(Ne(B=>!!B),ge(B=>this.cursorTagAvailable$.pipe(Ne(G=>!!G),Je(1),ce(()=>B))),Je(1)).subscribe(B=>{B&&(this.db=B,this.cursorTagAvailable&&(this.getPresenceUser(),this.getDocumentPaths(),this.getLocation(),this.updateOnDatabaseDisconnect().subscribe(()=>{},G=>{this.loggingService.catch("Error in CursorService constructor updateOnDatabaseDisconnect: ",G)}),this.addMouseMoveListener(),this.addScreenSizeChangeListener(),this.updateOnAllowedFeatureListChange()))},B=>{this.loggingService.catch("Error in CursorService constructor getDb: ",B)}),this.cursorUsers$.pipe(Vi()).subscribe(([B,G])=>{sessionStorage.getItem(U.SESSION_STORAGE.VELT_CURSOR_MULTIPLE_USERS_DETECTED)||G?.length>1&&B.length!==G.length&&(this.analyticsService.trackEvent(Z.Events.Cursor.CURSOR_MULTIPLE_USERS_DETECTED,{totalUsers:G.length,cursorSnippylyUserIds:G.map(X=>X.userSnippylyId),cursorClientUserIds:G.map(X=>X.userId)}),sessionStorage.setItem(U.SESSION_STORAGE.VELT_CURSOR_MULTIPLE_USERS_DETECTED,"true"))}),this.authService.addPreSignOutFuction("cursor-signout",this.signOutUser.bind(this))}catch(B){this.loggingService.catch("Error in CursorService constructor: ",B)}}checkCursorTagAvailable(){this.loggingService.log("%c[WB] Calling FUNCTION: checkCursorTagAvailable","color: green;");try{this.cursorTagAvailable=!!document.querySelector(U.TAGS.VELT_CURSOR)||!!document.querySelector(U.TAGS.SNIPPYLY_CURSOR),this.cursorTagAvailable$.next(this.cursorTagAvailable)}catch(e){this.loggingService.catch("Error in CursorService checkCursorTagAvailable: ",e)}}addScreenSizeChangeListener(){this.loggingService.log("%c[WB] Calling FUNCTION: addScreenSizeChangeListener","color: green;");try{this.docService.getDocumentPaths$().pipe(Ne(e=>!!e),ge(e=>this.domService.getCurrentWindowSize$("CursorService addScreenSizeChangeListener").pipe(Ne(i=>!!i)))).subscribe(e=>{this.setCurrentCursorUserScreenSize(e)},e=>{this.loggingService.catch("Error in addScreenSizeChangeListener getCurrentWindowSize: ",e)})}catch(e){this.loggingService.catch("Error in CursorService addScreenSizeChangeListener: ",e)}}addMouseMoveListener(){this.loggingService.log("%c[WB] Calling FUNCTION: addMouseMoveListener","color: green;");try{this.domService.onWindowPointerMove$().pipe(t7(50)).subscribe(e=>{e&&this.setCurrentCursorUserPosition(e.pageX,e.pageY,this.domService.getTargetElementForCursorPosition(e,!0,!1,!1))},e=>{this.loggingService.catch("Error in addMouseMoveListener getCurrentMousePosition: ",e)})}catch(e){this.loggingService.catch("Error in CursorService addMouseMoveListener: ",e)}}getDocumentPaths(){this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentPaths","color: green;");try{this.docService.getDocumentPaths$().pipe(In(e=>{this.documentPaths=e}),Vi(),In(([e,i])=>{e&&this.updateUserStatusOnDocumentChange(U.PRESENCE_STATUS_OFFLINE,e),i&&this.updateUserStatusOnDocumentChange(U.PRESENCE_STATUS_ONLINE,i)})).subscribe(()=>{},e=>{this.loggingService.catch("Error in getDocumentPaths subscription: ",e)})}catch(e){this.loggingService.catch("Error in CursorService getDocumentPaths: ",e)}}getLocation(){try{this.docService.getLocation$().pipe(In(e=>{this.updateUserOnLocationChange(e)})).subscribe(()=>{},e=>{this.loggingService.catch("Error in getLocation subscription: ",e)})}catch(e){this.loggingService.catch("Error in CursorService getLocation: ",e)}}getCursorUser(){return this.loggingService.log("%c[WB] Calling FUNCTION: getCursorUser","color: green;"),this.cursorUser$.asObservable()}getPresenceUser(){this.loggingService.log("%c[WB] Calling FUNCTION: getPresenceUser","color: green;"),this.presenceService.getPresenceUser().pipe(Ne(e=>!!e),Ln(e=>re(e.code))).subscribe(e=>{this.setCursorUser(e)},e=>{this.loggingService.catch("Error in getPresenceUser: ",e)})}getLiveCursorsOnCurrentDocument(){return this.loggingService.log("%c[WB] Calling FUNCTION: getLiveCursorsOnCurrentDocument","color: green;"),Wn(this.afAuth).pipe(Ne(e=>!!e),ge(e=>this.isFeatureAllowed({firebaseUser:e,users:[],filteredUsers:[]})),ge(e=>e.featureAllowed?this.iamService.isUserAllowed$().pipe(ce(i=>(e.featureAllowed=i,e))):re(e)),ge(e=>e.featureAllowed?this.authService.isPlanExpired$().pipe(ce(i=>(e.featureAllowed=!i,e))):re(e)),ge(e=>!e.featureAllowed||e?.user?.isAnonymous?re([]):re(e).pipe(ge(i=>this.docService.getDocumentPaths$().pipe(ce(r=>(this.documentPaths=r,i.documentPaths=r,i)))),ge(i=>this.getDataFromDocumentId().pipe(ce(r=>(i.users=r||[],I({},i))))),ce(i=>(i.filteredUsers=this.filterOnlineUsers(i.users,i.firebaseUser),i)),ge(i=>i?.filteredUsers?.length?this.domService.getCurrentWindowSize$("CursorService getLiveCursorsOnCurrentDocument").pipe(ce(()=>i)):re(i)),ce(i=>(i?.filteredUsers?.forEach(r=>{this.calculateCursorUserPosition(r)}),i)),ge(i=>i?.filteredUsers?re(i?.filteredUsers||[]):re([])))))}isFeatureAllowed(e){return this.configService.getConfig$().pipe(Ne(i=>!!i),ce(i=>T(I({},e),{config:i})),ge(i=>this.authService.getUser$().pipe(ce(r=>T(I({},i),{user:r})))),ge(i=>Xi(i.config,i.user,Re.CURSOR)?re(T(I({},i),{featureAllowed:!0})):(this.loggingService.warn("Cursor feature is not allowed."),re(T(I({},i),{featureAllowed:!1})))))}getDataFromDocumentId(e){return this.databaseService.getDb().pipe(Ne(i=>!!i),ge(i=>(this.db=i,this.loggingService.log(this.db),this.configService?.getApiKey()&&this.documentPaths?.cursor?this.commonDbService.dbListener({feature:"allCursors",properties:{documentId:e??this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,skipFirestore:!0}}).pipe(Ln(r=>(this.loggingService.catch("Error in CursorService getDataFromDocumentId: ",r),re(null))),ce(r=>r?.data),ce(r=>{let a=[];return r&&(a=Object.values(r).filter(s=>typeof s=="object")),a})):re([]))))}calculateCursorUserPosition(e){try{if(e?.targetElement){let i=this.domService.getXPath(e.targetElement?.xpath);if(i){let r=i.iterateNext();if(r&&this.isElementInsideAllowedElements(r)){let a=r.getBoundingClientRect();a&&a.width&&a.height&&(e.position={top:a.top+a.height*e.targetElement.topPercentage/100,left:a.left+a.width*e.targetElement.leftPercentage/100})}}}}catch(i){this.loggingService.catch("Error in calculateCursorUserPosition:",i)}}filterOnlineUsers(e,i){try{let a=e.slice().filter(c=>{let p=Sp(c.timestamp);return c.userSnippylyId&&c.onlineStatus===U.PRESENCE_STATUS_ONLINE&&p<this.inactivityTime});this.cursorUsers$.next(a),a=a.filter(c=>c?.userSnippylyId!==i?.uid);let s=this.docService.getLocation();return s&&s.locationId?a=a.filter(c=>c.locationId===s.locationId):a=a.filter(c=>!c.locationId),a}catch(r){return this.loggingService.catch("Error in filterOnlineUsers:",r),[]}}setCursorUser(e){this.loggingService.log("%c[WB] Calling FUNCTION: setCursorUser","color: green;");try{let i=this.cursorUser$.value;i.userId=e?.userId,i.name=e?.name,i.email=e?.email,i.photoUrl=e?.photoUrl,i.comment="",this.authService.isFeatureAllowed(Re.PRESENCE)&&(i.onlineStatus=e?.onlineStatus),i.userSnippylyId=e?.userSnippylyId,i.color=e?.color,i.textColor=e?.textColor,i.initial=e?.initial,i.timestamp=this.timestamp,i.type=e?.type,i.isReadOnly=e?.isReadOnly,i.isAnonymous=e?.isAnonymous;let r=this.domService.getCurrentWindowSizeValue();i.screenWidth=r?.screenWidth,i.screenHeight=r?.screenHeight,i.screenScrollHeight=r?.screenScrollHeight,this.updateCurrentCursorUser(i)}catch(i){this.loggingService.catch("Error in setCursorUser:",i)}}setCurrentCursorUserPosition(e,i,r){try{let a=this.cursorUser$.value;a?.onlineStatus===U.PRESENCE_STATUS_ONLINE&&(a.positionX=e,a.positionY=i,r?a.targetElement=r:a.targetElement=null,this.updateCurrentCursorUser(a))}catch(a){this.loggingService.catch("Error in setCurrentCursorUserPosition:",a)}}setCurrentCursorUserScreenSize(e){try{if(e.screenWidth!==0&&e.screenHeight!==0){let i=this.cursorUser$.value;i?.onlineStatus===U.PRESENCE_STATUS_ONLINE&&(i.screenWidth=e.screenWidth,i.screenHeight=e.screenHeight,i.screenScrollHeight=e.screenScrollHeight,this.updateCurrentCursorUser(i))}}catch(i){this.loggingService.catch("Error in setCurrentCursorUserScreenSize:",i)}}updateCurrentCursorUser(e){return ee(this,null,function*(){try{if(this.documentPaths&&e&&e.userId&&this.authService.isFeatureAllowed(Re.CURSOR)){if(!e.isAnonymous){e.pageInfo=new Zi;let i=JSON.parse(JSON.stringify(e));this.commonDbService.updateData({feature:"cursor",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",id:e.userSnippylyId,skipFirestore:!0},data:JSON.parse(JSON.stringify(T(I({},i),{timestamp:this.timestamp})))})}this.cursorUser$.next(e)}}catch(i){this.loggingService.catch("Error in updateCurrentCursorUser:",i)}})}updateUserStatusOnDocumentChange(e,i){return ee(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: updateUserStatusOnDocumentChange","color: green;");try{let r=this.cursorUser$.value;if(r.onlineStatus=e,i&&r&&r.userId&&!r.isAnonymous&&this.authService.isFeatureAllowed(Re.CURSOR)){let a=JSON.parse(JSON.stringify(r));this.commonDbService.updateData({feature:"cursor",properties:{documentId:i?.documentId??"",organizationId:i?.organizationId??"",id:r.userSnippylyId,skipFirestore:!0},data:JSON.parse(JSON.stringify(T(I({},a),{timestamp:this.timestamp})))})}}catch(r){this.loggingService.catch("Error in updateUserStatusOnDocumentChange:",r)}})}updateUserOnLocationChange(e){return ee(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: updateUserOnLocationChange","color: green;");try{let i=this.cursorUser$.value;if(i.location=e?e.location:null,i.locationId=e?e?.locationId:null,this.documentPaths&&i&&i.userId&&!i.isAnonymous&&this.authService.isFeatureAllowed(Re.CURSOR)){let r=JSON.parse(JSON.stringify(i));this.commonDbService.updateData({feature:"cursor",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",id:i.userSnippylyId,skipFirestore:!0},data:JSON.parse(JSON.stringify(T(I({},r),{timestamp:this.timestamp})))})}}catch(i){this.loggingService.catch("Error in updateUserOnLocationChange:",i)}})}updateOnAllowedFeatureListChange(){try{this.configService.getConfig$().subscribe(e=>{if(e&&e.featureAllowList?.length){let i=this.cursorUser$.value,r=!1;if(e.featureAllowList.includes(Re.CURSOR)?i?.onlineStatus!==U.PRESENCE_STATUS_ONLINE&&(i.onlineStatus=U.PRESENCE_STATUS_ONLINE,r=!0):i?.onlineStatus!==U.PRESENCE_STATUS_OFFLINE&&(i.onlineStatus=U.PRESENCE_STATUS_OFFLINE,r=!0),r&&this.documentPaths&&i&&i.userId&&!i.isAnonymous){let a=JSON.parse(JSON.stringify(i));this.commonDbService.updateData({feature:"cursor",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",id:i.userSnippylyId,skipFirestore:!0},data:JSON.parse(JSON.stringify(T(I({},a),{timestamp:this.timestamp})))})}}})}catch(e){this.loggingService.catch("Error in updateOnAllowedFeatureListChange:",e)}}updateOnDatabaseDisconnect(){return this.loggingService.log("%c[WB] Calling FUNCTION: updateOnDatabaseDisconnect","color: green;"),Wn(this.afAuth).pipe(Ne(e=>!!e),ge(e=>this.docService.getDocumentPaths$().pipe(ce(i=>e))),In(e=>ee(this,null,function*(){try{if(this.documentPaths&&e){let i=yield ad(e,!0).catch(a=>null);if(!i)return;let{user:r}=i.claims;if(!r?.isAnonymous){let a=on(this.db,`${this.documentPaths.cursor}/${e.uid}`);cl(a).update({onlineStatus:U.PRESENCE_STATUS_OFFLINE,comment:"",timestamp:this.timestamp}).catch(s=>{this.loggingService.catch("Error in updateOnDatabaseDisconnect:",s)})}}}catch(i){this.loggingService.catch("Error in updateOnDatabaseDisconnect:",i)}})))}signOutUser(e){return new Promise((i,r)=>{try{this.documentPaths&&e?this.commonDbService.dbListener({feature:"cursor",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,id:e.uid,skipFirestore:!0}}).pipe(Je(1)).subscribe(a=>{a?.data?this.commonDbService.updateData({feature:"cursor",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",id:e.uid,skipFirestore:!0},callback:()=>{i(null)},data:JSON.parse(JSON.stringify(T(I({},a?.data??{}),{timestamp:this.timestamp,onlineStatus:U.PRESENCE_STATUS_OFFLINE})))}):i(null)},a=>{this.loggingService.catch("Error in signOutUser subscription: ",a),r(a)}):i(null)}catch(a){this.loggingService.catch("Error in signOutUser:",a),r(a)}})}setInactivityTime(e){this.inactivityTime=e,this.analyticsService.trackEvent(Z.Events.Cursor.CURSOR_SET_CUSTOM_INACTIVITY_TIMER,{inactivityTime:this.inactivityTime})}setAllowedElementIds(e){this.allowedElementIds$.next(e||[])}getAllowedElementIds(){return this.allowedElementIds$.asObservable()}isElementInsideAllowedElements(e){try{return this.domService.isElementInsideListedElementIds(e,this.allowedElementIds$.value)}catch(i){return this.loggingService.catch("Error in CursorService isElementInsideAllowedElements: ",i),!1}}get timestamp(){return this.commonDbService.getServerTimestamp()}};o.\u0275fac=function(i){return new(i||o)(J(Qe),J($t),J(Cm),J(lt),J(vi),J(gn),J(Fe),J(pn),J(je),J(y),J(bn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var HM=class extends li{constructor(o){super(o),this.getService(y).log("%c[WB] Creating CLASS: CursorElement","color: blue;"),this.getLiveCursorsOnCurrentDocument=this._getOnlineUsersOnCurrentDocument,this.getOnlineUsersOnCurrentDocument=this._getOnlineUsersOnCurrentDocument,this.setInactivityTime=this._setInactivityTime,this.allowedElementIds=this._allowedElementIds}_getOnlineUsersOnCurrentDocument(){this.getService(y).log("%c[WB] Calling FUNCTION: getOnlineUsersOnCurrentDocument","color: green;");try{return this.trackEvent(Z.Events.Cursor.GET_LIVE_CURSORS_ON_CURRENT_DOCUMENT_TRIGGERED),this.getService(qv).getLiveCursorsOnCurrentDocument()}catch(o){return this.getService(y).catch("Error in _getOnlineUsersOnCurrentDocument: ",o),re(null)}}_setInactivityTime(o){this.getService(y).log("%c[WB] Calling FUNCTION: _setInactivityTime","color: green;");try{this.trackEvent(Z.Events.Cursor.SET_INACTIVITY_TIME_TRIGGERED,{payload:{time:o}}),isNaN(o)?this.getService(y).catch("Error in setInactivityTime: ","Provided value is not a number."):this.getService(qv).setInactivityTime(o)}catch(t){this.getService(y).catch("Error in setInactivityTime: ",t)}}_allowedElementIds(o){this.getService(y).log("%c[WB] Calling FUNCTION: allowedElementIds","color: green;");try{this.trackEvent(Z.Events.Cursor.ALLOWED_ELEMENT_IDS_TRIGGERED,{payload:{elementIds:o}}),this.getService(qv).setAllowedElementIds(o)}catch(t){this.getService(y).catch("Error in allowedElementIds: ",t)}}};var zM=class extends li{constructor(o){super(o),this.getService(y).log("%c[WB] Creating CLASS: DocElement","color: blue;"),this.getDocumentMetadata=this._getDocumentMetadata}_getDocumentMetadata(){this.getService(y).log("%c[WB] Calling FUNCTION: getDocumentMetadata","color: green;");try{return this.trackEvent(Z.Events.Doc.GET_DOCUMENT_METADATA_TRIGGERED),this.getService(lt).getDocumentMetadata$()}catch(o){return this.getService(y).catch("Error in getDocumentMetadata: ",o),re(null)}}};var mr=(()=>{let o=class o{constructor(e,i,r,a,s,c,p,h,_,E,D,B,G){this.afAuth=e,this.analyticsService=i,this.authService=r,this.databaseService=a,this.docService=s,this.configService=c,this.domService=p,this.huddleUtilsService=h,this.functions=_,this.loggingService=E,this.notificationService=D,this.commonDbService=B,this.usersService=G,this.documentPaths=null,this.localStream$=new fe(null),this.peerConnectionMap={},this.localStream=new MediaStream,this.screenSharingStream=new MediaStream,this.screenSharingStream$=new fe(null),this.remoteStreamMap={},this.remoteStreamMap$=new fe(null),this.localStreamState$=new fe({}),this.peerConnectionStateMap={},this.peerConnectionStateMap$=new fe({}),this.hudleToolComponentId$=new fe(null),this.attendees$=new fe([]),this.invitees$=new fe([]),this.huddleJoined$=new fe(!1),this.userHuddleStartTime$=new fe(null),this.messages$=new fe([]),this.messagesPanelVisible$=new fe(!1),this.huddleOnCursorMode$=new fe(!1),this.flockModeOnAvatarClickEnabled$=new fe(!1),this.chatEnabled$=new fe(!0),this.huddleOnCursorModeByAttendeeId$=new fe({}),this.huddleCursorAvailableByAttendeeId$=new fe({}),this.remoteStreamsByUserId$=new fe({}),this.messagesSubscription=null,this.huddleJoined=!1,this.onAnswerConnectionIdHistory={},this.onOfferUidHistory={},this.senders={},this.db=Ci(),this.dbRefsRemoveOnDropCall=[],this.servers={iceServers:[{urls:["stun:stun1.l.google.com:19302","stun:stun2.l.google.com:19302"]}]},this.databaseService.getDb().pipe(Ne(X=>!!X),Je(1)).subscribe(X=>{try{X&&(this.db=X,this.isHuddleTagInstalled()&&(sessionStorage.getItem("skipTwilioIceServers")||this.getTwilioIceServers()),this.getUser(),this.getDocumentPaths())}catch(he){this.loggingService.catch("Error in HuddleService getDb:",he)}},X=>{this.loggingService.catch("Error in HuddleService getDb subscription: ",X)}),this.docService.addPreDocumentIdChangeFunction("huddle-service",X=>ee(this,null,function*(){this.huddleJoined$.value&&(yield this.dropCall(),yield this.removeLocalStream(),yield this.removeAttendee(),this.attendees$.next([]))})),this.getAttendees().subscribe(),this.getInvitees().subscribe(),this.localStream$.subscribe(X=>{X&&(this.localStream=X)}),this.screenSharingStream$.subscribe(X=>{X&&(this.screenSharingStream=X)}),this.configService.getConfig$().subscribe(X=>{try{!X?.featureAllowList?.find(Ie=>Ie===Re.CURSOR)&&this.huddleOnCursorMode$.next(!1)}catch(he){this.loggingService.catch("Error in HuddleService configService.getConfig$:",he)}},X=>{this.loggingService.catch("Error in HuddleService configService.getConfig$ subscription: ",X)}),this.attendees$.subscribe(X=>{try{if(X?.length){if(this.huddleOnCursorMode$?.value){let he=this.huddleOnCursorModeByAttendeeId$.getValue()||{};X.forEach(Ie=>{he[Ie.userSnippylyId]=!0}),this.huddleOnCursorModeByAttendeeId$.next(he)}this.huddleJoined$?.value&&(X?.find(he=>he?.huddleOnCursorMode)?this.addCursorTag():this.removeCursorTag())}}catch(he){this.loggingService.catch("Error in HuddleService attendees$:",he)}},X=>{this.loggingService.catch("Error in HuddleService attendees$ subscription: ",X)}),Dn([this.huddleJoined$,this.huddleOnCursorMode$]).subscribe(([X,he])=>{try{if(X){if(he){let Ie=this.attendees$.getValue()||[],Me=this.huddleOnCursorModeByAttendeeId$.getValue()||{};Ie.forEach(Le=>{Me[Le.userSnippylyId]=!0}),document?.body?.setAttribute(U.ATTRIBUTES.VELT_HUDDLE_ON_CURSOR_MODE,"true")}else this.huddleOnCursorModeByAttendeeId$.next({}),document?.body?.removeAttribute(U.ATTRIBUTES.VELT_HUDDLE_ON_CURSOR_MODE);this.updateHuddleOnCursorMode()}else this.removeCursorTag(),document?.body?.removeAttribute(U.ATTRIBUTES.VELT_HUDDLE_ON_CURSOR_MODE)}catch(Ie){this.loggingService.catch("Error in HuddleService huddleJoined$:",Ie)}},X=>{this.loggingService.catch("Error in HuddleService huddleJoined$ subscription: ",X)}),this.huddleOnCursorModeByAttendeeId$.subscribe(X=>{try{this.huddleJoined&&(Object.keys(X).length?this.addCursorTag():this.removeCursorTag())}catch(he){this.loggingService.catch("Error in HuddleService huddleOnCursorModeByAttendeeId$:",he)}},X=>{this.loggingService.catch("Error in HuddleService huddleOnCursorModeByAttendeeId$ subscription: ",X)}),this.authService.addPreSignOutFuction("huddle-signout",this.signOutUser.bind(this))}isHuddleTagInstalled(){try{return!!document?.querySelector(`${U.TAGS.VELT_HUDDLE}`)||!!document?.querySelector(`${U.TAGS.SNIPPYLY_HUDDLE}`)}catch(e){return this.loggingService.catch("Error in HuddleService isHuddleTagInstalled:",e),!1}}getTwilioIceServers(){return ee(this,null,function*(){try{let i=(yield Cr(this.functions,Zn.cloudFunction.getIceServers,{timeout:12e5})())?.data;i&&i?.iceServers&&(this.servers.iceServers=i.iceServers)}catch(e){this.loggingService.catch("Error in HuddleService getTwilioIceServers:",e)}})}getRemoteStream(){return this.loggingService.log("%c[WB] Calling FUNCTION: getRemoteStream","color: green;"),this.remoteStreamMap$.asObservable()}getPeerConnectionStateMap(){return this.loggingService.log("%c[WB] Calling FUNCTION: getPeerConnectionStateMap","color: green;"),this.peerConnectionStateMap$.asObservable()}getLocalStreamState(){return this.loggingService.log("%c[WB] Calling FUNCTION: getLocalStreamState","color: green;"),this.localStreamState$.asObservable()}getScreenSharingStream(){return this.loggingService.log("%c[WB] Calling FUNCTION: getScreenSharingStream","color: green;"),this.screenSharingStream$.asObservable()}getAttendees(){return Wn(this.afAuth).pipe(Ne(e=>!!e),ce(e=>({firebaseUser:e})),ge(e=>this.configService.getConfig$().pipe(Ne(i=>!!i),ce(i=>T(I({},e),{config:i})))),ge(e=>this.authService.getUser$().pipe(ce(i=>T(I({},e),{user:i})))),ge(e=>Xi(e.config,e.user,Re.HUDDLE)?re(T(I({},e),{allowed:!0})):(this.loggingService.warn("Huddle feature is not allowed."),re(T(I({},e),{allowed:!1})))),ge(e=>this.docService.getDocumentPaths$().pipe(ce(i=>(this.documentPaths=i,e)))),ge(e=>e?.allowed?e?.user?.isAnonymous?re(null):this.documentPaths?.huddle?this.commonDbService.dbListener({feature:"allHuddleAttendees",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,skipFirestore:!0}}).pipe(ce(i=>i?.data),ce(i=>i?(this.attendees$.next(Object.values(i)),Object.values(i)):(this.attendees$.next([]),null))):re(null):re([])))}getInvitees(){try{return Wn(this.afAuth).pipe(Ne(e=>!!e),ce(e=>({firebaseUser:e})),ge(e=>this.configService.getConfig$().pipe(Ne(i=>!!i),ce(i=>T(I({},e),{config:i})))),ge(e=>this.authService.getUser$().pipe(ce(i=>T(I({},e),{user:i})))),ge(e=>Xi(e.config,e.user,Re.HUDDLE)?re(T(I({},e),{allowed:!0})):(this.loggingService.warn("Huddle feature is not allowed."),re(T(I({},e),{allowed:!1})))),ge(e=>this.docService.getDocumentPaths$().pipe(ce(i=>(this.documentPaths=i,e)))),ge(e=>e?.allowed?e?.user?.isAnonymous?re(null):this.documentPaths?.huddle?this.commonDbService.dbListener({feature:"allHuddleInvitees",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,skipFirestore:!0}}).pipe(ce(i=>i?.data),ce(i=>i?(this.invitees$.next(Object.values(i)),Object.values(i)):(this.invitees$.next([]),null))):re(null):re([])))}catch(e){return this.loggingService.catch("Error in HuddleService getInvitees:",e),re([])}}clearHuddleInvitees(){try{this.documentPaths?.huddle&&this.commonDbService.deleteData({feature:"allHuddleInvitees",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,skipFirestore:!0}})}catch(e){this.loggingService.catch("Error in HuddleService clearHuddleInvitees:",e)}}getUser(){this.loggingService.log("%c[WB] Calling FUNCTION: getUser","color: green;"),this.authService.getUser$().pipe(Ne(e=>!!e)).subscribe(e=>{e&&(this.user=e)},e=>{this.loggingService.catch("Error in getUser: ",e)})}getDocumentPaths(){this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentPaths","color: green;"),this.docService.getDocumentPaths$().pipe(In(e=>{this.documentPaths=e})).subscribe(()=>{},e=>{this.loggingService.catch("Error in getDocumentPaths: ",e)})}setHuddleToolComponentId(e){this.hudleToolComponentId$.next(e||null)}getHuddleToolComponentId(){return this.hudleToolComponentId$.asObservable()}joinHuddle(e){return ee(this,null,function*(){try{this.loggingService.log("%c[WB] Calling FUNCTION: joinHuddle","color: green;"),this.documentPaths?.huddle?(this.initialHuddleType=e,this.huddleJoined=!0,this.huddleJoined$.next(!0),this.initLocalStreams(),this.huddle=on(this.db,this.documentPaths?.huddle),this.iceCandidates=on(this.db,`${this.documentPaths?.huddle}/iceCandidates`),this.connections=on(this.db,`${this.documentPaths?.huddle}/connections`),this.attendees=on(this.db,`${this.documentPaths?.huddle}/attendees`),this.messages=on(this.db,`${this.documentPaths?.huddle}/messages`),this.setHuddleListener(),this.addAttendee(),this.callExistingAttendees(),this.userHuddleStartTime$.next(new Date().getTime())):this.loggingService.catch("Error in joinHuddle: documentPaths not found")}catch(i){this.loggingService.catch("Error in HuddleService joinHuddle:",i)}})}initLocalStreams(){try{if(!this.localStream$?.value?.getTracks()?.length){let e=new MediaStream([this.silence(),this.black()]);this.localStream$.next(e)}if(!this.screenSharingStream$?.value?.getTracks()?.length){let e=new MediaStream([this.black()]);this.screenSharingStream$.next(e)}}catch(e){this.loggingService.catch("Error in HuddleService initLocalStreams:",e)}}setHuddleListener(){this.loggingService.log("%c[WB] Calling FUNCTION: setHuddleListener","color: green;"),gu(this.connections,e=>{try{if(e.exists()){let i=e.val();Object.values(i).forEach(a=>{let s=Object.values(a);if(s&&s.length>0){let p=s[0]?.connectionId;this.onHuddleSnapshot(p,a)}}),Object.keys(this.remoteStreamMap).forEach(a=>ee(this,null,function*(){i[a]||(this.remoteStreamMap[a]&&Object.values(this.remoteStreamMap[a]).forEach(s=>{s.getTracks().forEach(c=>{c.stop()})}),delete this.remoteStreamMap[a],yield this.removeIceCandidates(a))})),this.remoteStreamMap$.next(this.remoteStreamMap)}else Object.keys(this.remoteStreamMap).forEach(i=>ee(this,null,function*(){Object.values(this.remoteStreamMap[i]).forEach(r=>{r.getTracks().forEach(a=>{a.stop()})}),yield this.removeIceCandidates(i)})),this.remoteStreamMap={},this.remoteStreamMap$.next(this.remoteStreamMap)}catch(i){this.loggingService.catch("Error in HuddleService setHuddleLister onValue:",i)}}),SL(this.iceCandidates).subscribe(e=>{try{e.event==="child_added"&&this.onIceCandidateSnapshot(e.snapshot)}catch(i){this.loggingService.catch("Error in HuddleService iceCandidates stateChanges:",i)}}),SL(this.attendees).subscribe(e=>{try{if(e.event==="child_removed"){let i=e?.snapshot?.val();if(i){delete this.onOfferUidHistory[i?.userSnippylyId];let r=this.getCombinedId(this.user.userSnippylyId,i?.userSnippylyId);delete this.onAnswerConnectionIdHistory[r],this.closeConnection(r)}}}catch(i){this.loggingService.catch("Error in HuddleService iceCandidates stateChanges:",i)}}),this.messagesSubscription&&this.messagesSubscription.unsubscribe(),this.messagesSubscription=new Ft(e=>{let i=gu(this.messages,r=>e.next(r),r=>e.error(r));return()=>i()}).pipe(ge(e=>this.usersService.getUserById$().pipe(ce(()=>e))),ge(e=>{if(e.exists()){let i=e.val();return bo(this.huddleUtilsService.resolveUsersFromHuddleMessages(Object.values(i||{})))}return re([])}),Ln(e=>(this.loggingService.catch("Error in HuddleService messages onValue:",e),re([])))).subscribe(e=>{this.messages$.next(e)})}onHuddleSnapshot(e,i){try{this.loggingService.log("%c[WB] Calling FUNCTION: onHuddleSnapshot","color: green;"),i.offerData&&!i.answerData&&i.offerData.from!==this.user.userSnippylyId&&i.offerData.to===this.user.userSnippylyId&&!(e in this.peerConnectionMap)&&!this.onOfferUidHistory[i.offerData.from]?(this.loggingService.log("offer received"),this.loggingService.log(i),this.onOfferUidHistory[i.offerData.from]=!0,this.onOffer(e,i.offerData)):i.answerData&&i.answerData.from!==this.user.userSnippylyId&&i.answerData.to===this.user.userSnippylyId&&this.peerConnectionMap[e]&&this.peerConnectionMap[e]?.connectionState!=="connected"&&!this.onAnswerConnectionIdHistory[e]&&(this.loggingService.log("answer received"),this.loggingService.log(i),this.onAnswerConnectionIdHistory[e]=!0,this.onAnswer(e,i.answerData))}catch(r){this.loggingService.catch("Error in HuddleService onHuddleSnapshot:",r)}}onIceCandidateSnapshot(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: onIceCandidateSnapshot","color: green;"),this.loggingService.log("ice candidate received");let i=e.val(),r=i.connectionId;i?.from!==this.user.userSnippylyId&&r in this.peerConnectionMap&&this.onIceCandidateChange(r,i)}catch(i){this.loggingService.catch("Error in HuddleService onIceCandidateSnapshot:",i)}}onOffer(e,i){return ee(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: onOffer","color: green;"),this.createPeerConnection(e,i.from)){this.addLocalStreamToPeerConnection(e,!0);let a=i.offer;yield this.setRemoteDescription(e,a),yield this.sendAnswer(e,i.from)}}catch(r){this.loggingService.catch("Error in HuddleService onOffer:",r)}})}sendAnswer(e,i){return ee(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: sendAnswer","color: green;"),this.loggingService.log(e),this.documentPaths?.huddle&&e){let r=yield this.peerConnectionMap[e].createAnswer();yield this.setLocalDescription(e,r);let s={answer:{type:r.type,sdp:r.sdp},from:this.user.userSnippylyId,connectionId:e,to:i},c=on(this.db,`${this.documentPaths?.huddle}/connections/${e}`);this.dbRefsRemoveOnDropCall.push({type:"connection",dbRef:c}),yield jA(c,{answerData:s}),cl(c).remove()}else this.loggingService.catch("Error in sendAnswer: documentPaths not found")}catch(r){this.loggingService.catch("Error in HuddleService onHuddleSnapshot:",r)}})}onAnswer(e,i){return ee(this,null,function*(){try{this.loggingService.log("%c[WB] Calling FUNCTION: onAnswer","color: green;");let r=i.answer;yield this.setRemoteDescription(e,r)}catch(r){this.loggingService.catch("Error in HuddleService onAnswer:",r)}})}onIceCandidateChange(e,i){return ee(this,null,function*(){try{this.loggingService.log("%c[WB] Calling FUNCTION: onIceCandidateChange","color: green;");let r=i.candidate;this.loggingService.log("onIceCandidateChange",r),yield this.peerConnectionMap[e].addIceCandidate(new RTCIceCandidate(r))}catch(r){this.loggingService.catch("Error in HuddleService onIceCandidateChange:",r)}})}setRemoteDescription(e,i){return ee(this,null,function*(){try{this.loggingService.log("%c[WB] Calling FUNCTION: setRemoteDescription","color: green;"),yield this.peerConnectionMap[e].setRemoteDescription(new RTCSessionDescription(i))}catch(r){this.loggingService.catch("Error in HuddleService setRemoteDescription:",r)}})}addAttendee(){return ee(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: addAttendee","color: green;"),this.documentPaths?.huddle&&this.user?.userSnippylyId){let e=T(I({},this.user),{timestamp:this.timestamp,streamMetadata:{webcam:this.localStream?.id,screen:this.screenSharingStream?.id},initialHuddleType:this.initialHuddleType,huddleOnCursorMode:this.huddleOnCursorMode$?.value});e=this.huddleUtilsService.formatHuddleAttendeeData(e);let i=on(this.db,`${this.documentPaths?.huddle}/attendees/${this.user.userSnippylyId}`);yield Of(i,JSON.parse(JSON.stringify(e))),this.dbRefsRemoveOnDropCall.push({type:"attendee",dbRef:i}),cl(i).remove(),yield this.updateUserHuddleState()}else this.loggingService.catch("Error in addAttendee: documentPaths not found")}catch(e){this.loggingService.catch("Error in HuddleService addAttendee:",e)}})}callExistingAttendees(){try{this.loggingService.log("%c[WB] Calling FUNCTION: callExistingAttendees","color: green;"),hee(this.attendees).pipe(Je(1)).subscribe(e=>{e&&e.length>1?(e.forEach(i=>{i.userSnippylyId!==this.user.userSnippylyId&&!this.onOfferUidHistory[i.userSnippylyId]&&(this.loggingService.log("calling"),this.loggingService.log(i),this.initOffer(i.userSnippylyId))}),this.addLocalStreamToAllPeerConnections()):this.deleteMessages()})}catch(e){this.loggingService.catch("Error in HuddleService callExistingAttendees:",e)}}addLocalStreamToAllPeerConnections(){return ee(this,null,function*(){try{this.loggingService.log("%c[WB] Calling FUNCTION: addLocalStreamToAllPeerConnections","color: green;"),Object.keys(this.senders).forEach(e=>{this.loggingService.log(this.senders[e]),this.localStream.getTracks().forEach(i=>{this.loggingService.log(i),this.senders[e].replaceTrack(i)})})}catch(e){this.loggingService.catch("Error in HuddleService addLocalStreamToAllPeerConnections:",e)}})}initOffer(e){return ee(this,null,function*(){try{this.loggingService.log("%c[WB] Calling FUNCTION: initOffer","color: green;");let i=this.createPeerConnection(null,e);i&&(this.addLocalStreamToPeerConnection(i,!1),yield this.sendOffer(i,e))}catch(i){this.loggingService.catch("Error in HuddleService initOffer:",i)}})}createPeerConnection(e,i){try{return this.loggingService.log("%c[WB] Calling FUNCTION: createPeerConnection","color: green;"),e||(e=this.getCombinedId(this.user?.userSnippylyId,i)),e in this.peerConnectionMap?null:(this.loggingService.log("creating pc"),this.peerConnectionMap[e]=new RTCPeerConnection(this.servers),this.peerConnectionMap[e].onicecandidateerror=r=>{this.loggingService.log("Huddle: onicecandidateerror",r)},this.peerConnectionMap[e].onicecandidate=r=>{if(this.loggingService.log("pc onicecandidate"),r.candidate){let a={candidate:r.candidate.toJSON(),from:this.user.userSnippylyId,connectionId:e},s=fee(this.iceCandidates,a);this.dbRefsRemoveOnDropCall.push({type:"iceCandidate",dbRef:s}),cl(s).remove()}},this.peerConnectionMap[e].ontrack=r=>{this.loggingService.log("pc ontrack"),this.onTrack(e,r)},this.peerConnectionMap[e].onconnectionstatechange=r=>ee(this,null,function*(){this.logStatuses("onconnectionstatechange",e,r),this.peerConnectionMap[e].connectionState==="failed"&&(this.removeConnection(e),this.closeConnection(e),this.checkForRemovingAttendee())}),this.peerConnectionMap[e].onicegatheringstatechange=r=>ee(this,null,function*(){this.logStatuses("onicegatheringstatechange",e,r)}),this.peerConnectionMap[e].onsignalingstatechange=r=>ee(this,null,function*(){this.logStatuses("onsignalingstatechange",e,r)}),this.peerConnectionMap[e].oniceconnectionstatechange=r=>ee(this,null,function*(){this.loggingService.log("pc oniceconnectionstatechange"),this.logStatuses("oniceconnectionstatechange",e,r);try{this.peerConnectionStateMap[e]=this.peerConnectionMap[e].iceConnectionState,this.peerConnectionStateMap$.next(this.peerConnectionStateMap),this.peerConnectionMap[e]?.iceConnectionState==="connected"?(this.loggingService.log("connected"),this.updateTransceiverDirection(e)):this.peerConnectionMap[e]?.iceConnectionState==="disconnected"?this.loggingService.log("Disconnected"):this.peerConnectionMap[e].iceConnectionState==="closed"&&(this.loggingService.log("Closed"),this.closeConnection(e))}catch(a){this.loggingService.catch("Error in HuddleService oniceconnectionstatechange:",a)}}),this.peerConnectionMap[e].onnegotiationneeded=()=>{this.loggingService.log("pc onnegotiationneeded"),this.logStatuses("onnegotiationneeded",e)},e)}catch(r){return this.loggingService.catch("Error in HuddleService createPeerConnection:",r),""}}logStatuses(e,i,r){let a={};["connectionState","iceConnectionState","iceGatheringState","signalingState"].forEach(c=>{a[c]=this.peerConnectionMap[i][c]}),this.loggingService.log("Huddle: logStatues: ",i,e,a,r,this.peerConnectionMap[i])}checkForRemovingAttendee(){return ee(this,null,function*(){try{this.documentPaths?.huddle&&this.user?.userSnippylyId&&(Object.keys(this.peerConnectionMap)?.length||(this.commonDbService.deleteData({feature:"huddleAttendee",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,id:this.user?.userSnippylyId,skipFirestore:!0}}),this.joinHuddle(this.initialHuddleType)))}catch(e){this.loggingService.catch("Error in HuddleService checkForRemovingAttendee:",e)}})}closeConnection(e){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: closeConnection","color: green;"),this.peerConnectionMap[e]){let i=this.peerConnectionMap[e];i.getTransceivers()?.forEach(a=>{a.stop()}),i.getReceivers()?.forEach(a=>{a.track?.stop()}),i.close(),delete this.peerConnectionMap[e],delete this.onAnswerConnectionIdHistory[e],delete this.senders[e];let r=e.split("__").find(a=>a!==this.user?.userSnippylyId);r&&delete this.onOfferUidHistory[r]}}catch(i){this.loggingService.catch("Error in HuddleService closeConnection:",i)}}removeConnection(e){return ee(this,null,function*(){try{this.documentPaths?.huddle&&e&&this.commonDbService.deleteData({feature:"huddleConnection",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,id:e,skipFirestore:!0}})}catch(i){this.loggingService.catch("Error in HuddleService removeConnection:",i)}})}addLocalStreamToPeerConnection(e,i){try{this.loggingService.log("%c[WB] Calling FUNCTION: addLocalStreamToPeerConnection","color: green;"),i?(this.localStream.getTracks().forEach(r=>{this.peerConnectionMap[e].addTrack(r,this.localStream)}),this.screenSharingStream?.getVideoTracks()?.forEach(r=>{this.peerConnectionMap[e].addTrack(r,this.screenSharingStream)})):(this.localStream.getTracks().forEach(r=>{this.peerConnectionMap[e].addTrack(r,this.localStream)}),this.screenSharingStream?.getVideoTracks()?.forEach(r=>{this.peerConnectionMap[e].addTrack(r,this.screenSharingStream)}))}catch(r){this.loggingService.catch("Error in HuddleService addLocalStreamToPeerConnection:",r)}}updateTransceiverDirection(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: updateTransceiverDirection","color: green;");let i=this.peerConnectionMap[e].getTransceivers();this.loggingService.log(i),i.map(r=>{this.loggingService.log(r.currentDirection),r.currentDirection!=="sendrecv"&&(r.direction="sendrecv"),this.senders[e]=r.sender})}catch(i){this.loggingService.catch("Error in HuddleService updateTransceiverDirection:",i)}}generateKey(){this.loggingService.log("%c[WB] Calling FUNCTION: generateKey","color: green;");let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",i="";for(let r=0;r<20;r++)i+=e.charAt(Math.floor(Math.random()*e.length));return i}getCombinedId(e,i){try{return e.localeCompare(i)===-1?`${e}__${i}`:`${i}__${e}`}catch(r){return this.loggingService.catch("Error in HuddleService getCombinedId:",r),""}}sendOffer(e,i){return ee(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: sendOffer","color: green;"),this.documentPaths?.huddle&&e){this.onOfferUidHistory[i]=!0;let r=yield this.peerConnectionMap[e].createOffer();yield this.setLocalDescription(e,r);let a={sdp:r.sdp,type:r.type};i||(i="all");let s={offer:a,from:this.user.userSnippylyId,connectionId:e,to:i},c=on(this.db,`${this.documentPaths?.huddle}/connections/${e}`);yield Of(c,{offerData:s}),this.dbRefsRemoveOnDropCall.push({type:"connection",dbRef:c}),cl(c).remove()}}catch(r){this.loggingService.catch("Error in HuddleService sendOffer:",r)}})}setLocalDescription(e,i){return ee(this,null,function*(){try{this.loggingService.log("%c[WB] Calling FUNCTION: setLocalDescription","color: green;"),yield this.peerConnectionMap[e].setLocalDescription(i)}catch(r){this.loggingService.catch("Error in HuddleService setLocalDescription:",r)}})}onTrack(e,i){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: onTrack","color: green;"),this.remoteStreamMap[e]||(this.remoteStreamMap[e]={}),this.loggingService.log(i.receiver.track),i?.streams?.length){this.remoteStreamMap[e][i.streams[0].id]=i.streams[0];let r=e.split("__").find(s=>s!==this.user?.userSnippylyId),a=this.attendees$.value?.find(s=>s?.userSnippylyId===r);a&&(a?.streamMetadata?.webcam===i.streams[0].id&&(this.remoteStreamMap[e].webcam=i.streams[0]),a?.streamMetadata?.screen===i.streams[0].id&&(this.remoteStreamMap[e].screen=i.streams[0])),this.remoteStreamMap$.next(this.remoteStreamMap)}}catch(r){this.loggingService.catch("Error in HuddleService onTrack:",r)}}toggleScreenSharing(e){return ee(this,null,function*(){try{if(e)this.screenSharingStream=yield navigator.mediaDevices?.getDisplayMedia({video:!0}),Object.keys(this.peerConnectionMap).forEach(i=>{this.peerConnectionMap[i].getSenders().find(s=>s?.track?.kind==this.screenSharingStream?.getVideoTracks()[0].kind)?.replaceTrack(this.screenSharingStream?.getVideoTracks()[0])});else{let i=this.localStream;Object.keys(this.peerConnectionMap).forEach(r=>{this.peerConnectionMap[r].getSenders().find(c=>c?.track?.kind==i.getVideoTracks()[0].kind)?.replaceTrack(i.getVideoTracks()[0])}),this.screenSharingStream?.getTracks().forEach(r=>r.stop())}}catch(i){this.loggingService.catch("Error in HuddleService toggleScreenSharing:",i)}})}setLocalStream(e){return ee(this,null,function*(){try{if(this.localStream=new MediaStream([this.silence(),this.black()]),e?.audio||e?.video){let i=e,r=ac();e?.audio&&(e?.audio instanceof Object?i.audio=T(I({},e?.audio),{deviceId:r?.selectedAudioDevice?.deviceId}):i.audio={deviceId:r?.selectedAudioDevice?.deviceId}),e?.video&&(e?.video instanceof Object?i.video=T(I({},e?.video),{deviceId:r?.selectedVideoDevice?.deviceId}):i.video={deviceId:r?.selectedVideoDevice?.deviceId});let a=yield navigator.mediaDevices.getUserMedia(i);a?.getAudioTracks()?.length&&(this.localStream.getAudioTracks().forEach(s=>this.localStream.removeTrack(s)),a.getAudioTracks().forEach(s=>this.localStream.addTrack(s))),a?.getVideoTracks()?.length&&(this.localStream.getVideoTracks().forEach(s=>this.localStream.removeTrack(s)),a.getVideoTracks().forEach(s=>this.localStream.addTrack(s)))}this.localStream$.next(this.localStream)}catch(i){this.loggingService.catch("Error in HuddleService setLocalStream:",i)}})}setScreenSharingStream(){return ee(this,null,function*(){try{let e=yield navigator.mediaDevices?.getDisplayMedia({video:!0});e&&this.screenSharingStream$.next(e)}catch(e){this.loggingService.catch("Error in HuddleService setScreenSharingStream:",e)}})}removeLocalStream(){return ee(this,null,function*(){try{this.localStream$?.value&&(this.localStream$.value.getTracks().forEach(i=>{i.stop()}),this.localStream$.next(null))}catch(e){this.loggingService.catch("Error in HuddleService removeLocalStream:",e)}})}toggleLocalStreamAudio(e){return ee(this,null,function*(){try{let i=this.localStream$.value;if(i){let r=i.getAudioTracks()[0];if(r.enabled&&!e)r.stop(),i.getAudioTracks()?.forEach(a=>{i.removeTrack(a)}),i.addTrack(this.silence()),this.analyticsService.trackEvent(Z.Events.Huddle.HUDDLE_AUDIO_MUTED,{huddleType:this.initialHuddleType,totalUsers:this.getHuddleAttendees()?.length||0,totalUserHuddleDuration:this.getTotalUserHuddleDuration(),huddleSnippylyUserIds:this.getHuddleAttendees()?.map(a=>a?.userSnippylyId),huddleClientUserIds:this.getHuddleAttendees()?.map(a=>a?.userId)});else{let a=ac(),s=yield navigator.mediaDevices.getUserMedia({audio:{deviceId:a?.selectAudioDevice?.deviceId}});s&&(i.getAudioTracks()?.forEach(c=>{i.removeTrack(c)}),s.getAudioTracks()?.forEach(c=>{i.addTrack(c)}),this.analyticsService.trackEvent(Z.Events.Huddle.HUDDLE_AUDIO_UNMUTED,{huddleType:this.initialHuddleType,totalUsers:this.getHuddleAttendees()?.length||0,totalUserHuddleDuration:this.getTotalUserHuddleDuration(),huddleSnippylyUserIds:this.getHuddleAttendees()?.map(c=>c?.userSnippylyId),huddleClientUserIds:this.getHuddleAttendees()?.map(c=>c?.userId)}))}Object.keys(this.peerConnectionMap).forEach(a=>{this.peerConnectionMap[a].getSenders().find(p=>p?.track?.kind==i?.getAudioTracks()[0].kind)?.replaceTrack(i?.getAudioTracks()[0])}),this.updateUserHuddleState()}}catch(i){this.loggingService.catch("Error in HuddleService toggleLocalStreamAudio:",i)}})}toggleLocalStreamVideo(e){return ee(this,null,function*(){try{let i=this.localStream$.value;if(i){let r=i.getVideoTracks()[0];if(r.enabled&&!e)r.stop(),i.getVideoTracks()?.forEach(a=>{i.removeTrack(a)}),i.addTrack(this.black()),this.analyticsService.trackEvent(Z.Events.Huddle.HUDDLE_VIDEO_TURNED_OFF,{huddleType:this.initialHuddleType,totalUsers:this.getHuddleAttendees()?.length||0,totalUserHuddleDuration:this.getTotalUserHuddleDuration(),huddleSnippylyUserIds:this.getHuddleAttendees()?.map(a=>a?.userSnippylyId),huddleClientUserIds:this.getHuddleAttendees()?.map(a=>a?.userId)});else{let a=ac(),s=yield navigator.mediaDevices.getUserMedia({video:{deviceId:a?.selectedVideoDevice?.deviceId}});s&&(i.getVideoTracks()?.forEach(c=>{i.removeTrack(c)}),s.getVideoTracks()?.forEach(c=>{i.addTrack(c)}),this.analyticsService.trackEvent(Z.Events.Huddle.HUDDLE_VIDEO_TURNED_ON,{huddleType:this.initialHuddleType,totalUsers:this.getHuddleAttendees()?.length||0,totalUserHuddleDuration:this.getTotalUserHuddleDuration(),huddleSnippylyUserIds:this.getHuddleAttendees()?.map(c=>c?.userSnippylyId),huddleClientUserIds:this.getHuddleAttendees()?.map(c=>c?.userId)}))}Object.keys(this.peerConnectionMap).forEach(a=>{this.peerConnectionMap[a].getSenders().find(p=>p?.track?.kind==i?.getVideoTracks()[0].kind)?.replaceTrack(i?.getVideoTracks()[0])}),this.updateUserHuddleState()}}catch(i){this.loggingService.catch("Error in HuddleService toggleLocalStreamVideo:",i)}})}toggleLocalScreenSharing(){return ee(this,null,function*(){try{let e=this.screenSharingStream;if(e){if(e.getVideoTracks()[0].enabled)this.stopScreenSharingStream();else{let r=yield navigator.mediaDevices?.getDisplayMedia({video:!0});r&&(e.getVideoTracks()?.forEach(a=>{e.removeTrack(a)}),r.getVideoTracks()?.forEach(a=>{e.addTrack(a),a.onended=()=>{this.stopScreenSharingStream(),this.updateScreenSharingTracksToPeers(),this.updateUserHuddleState()}})),this.screenSharingStream$.next(e),this.analyticsService.trackEvent(Z.Events.Huddle.HUDDLE_SCREENSHARING_STARTED,{huddleType:this.initialHuddleType,totalUsers:this.getHuddleAttendees()?.length||0,totalUserHuddleDuration:this.getTotalUserHuddleDuration(),huddleSnippylyUserIds:this.getHuddleAttendees()?.map(a=>a?.userSnippylyId),huddleClientUserIds:this.getHuddleAttendees()?.map(a=>a?.userId)})}this.updateScreenSharingTracksToPeers(),this.updateUserHuddleState()}}catch(e){this.loggingService.catch("Error in HuddleService toggleLocalScreenSharing:",e)}})}stopScreenSharingStream(){return ee(this,null,function*(){let e=this.screenSharingStream;if(e){let i=e.getVideoTracks()[0];i.enabled&&(i.stop(),e.getVideoTracks()?.forEach(r=>{e.removeTrack(r)}),e.addTrack(this.black()),this.analyticsService.trackEvent(Z.Events.Huddle.HUDDLE_SCREENSHARING_STOPPED,{huddleType:this.initialHuddleType,totalUsers:this.getHuddleAttendees()?.length||0,totalUserHuddleDuration:this.getTotalUserHuddleDuration(),huddleSnippylyUserIds:this.getHuddleAttendees()?.map(r=>r?.userSnippylyId),huddleClientUserIds:this.getHuddleAttendees()?.map(r=>r?.userId)}))}})}updateScreenSharingTracksToPeers(){return ee(this,null,function*(){Object.keys(this.peerConnectionMap).forEach(e=>{let r=this.peerConnectionMap[e].getSenders().filter(a=>a?.track?.kind==this.screenSharingStream?.getVideoTracks()[0].kind);r?.length>1&&r[1]?.replaceTrack(this.screenSharingStream?.getVideoTracks()[0])})})}dropCall(){return ee(this,null,function*(){try{this.messagesSubscription&&this.messagesSubscription.unsubscribe(),this.removeHuddleSessionData(),this.huddleJoined=!1,this.huddleJoined$.next(!1),this.peerConnectionMap&&Object.keys(this.peerConnectionMap).forEach(e=>{let i=this.peerConnectionMap[e];i.getTransceivers()?.forEach(r=>{r.stop()}),i.getSenders()?.forEach(r=>{r.track?.stop()}),i.getReceivers()?.forEach(r=>{r.track?.stop()}),i.close()}),this.peerConnectionMap={},this.dbRefsRemoveOnDropCall.forEach(e=>ee(this,null,function*(){yield VA(e.dbRef)})),this.onOfferUidHistory={},this.onAnswerConnectionIdHistory={},this.senders={},this.peerConnectionStateMap={},this.peerConnectionStateMap$.next(this.peerConnectionStateMap),this.localStream.getTracks().forEach(e=>{e.stop()}),this.screenSharingStream.getTracks().forEach(e=>{e.stop()}),this.localStream=new MediaStream([this.silence(),this.black()]),this.screenSharingStream=new MediaStream([this.black()]),this.localStream$.next(this.localStream),this.screenSharingStream$.next(this.screenSharingStream),this.localStreamState$.next({audioState:!1,videoState:!1,screenSharingState:!1}),this.analyticsService.trackEvent(Z.Events.Huddle.HUDDLE_LEFT,{huddleType:this.initialHuddleType,totalUsers:this.getHuddleAttendees()?.length||0,totalUserHuddleDuration:this.getTotalUserHuddleDuration(),huddleSnippylyUserIds:this.getHuddleAttendees()?.map(e=>e?.userSnippylyId),huddleClientUserIds:this.getHuddleAttendees()?.map(e=>e?.userId)})}catch(e){this.loggingService.catch("Error in HuddleService dropCall:",e)}})}updateHuddleSessionData(e,i,r){try{let a=JSON.parse(sessionStorage.getItem(U.SESSION_STORAGE.SNIPPYLY_HUDDLE_DATA)||"{}");r?sessionStorage.setItem(U.SESSION_STORAGE.SNIPPYLY_HUDDLE_DATA,JSON.stringify(r)):(a[e]=i,sessionStorage.setItem(U.SESSION_STORAGE.SNIPPYLY_HUDDLE_DATA,JSON.stringify(a)))}catch(a){this.loggingService.catch("Error in HuddleService updateHuddleSessionData:",a)}}getHuddleSessionData(){try{return sessionStorage.getItem(U.SESSION_STORAGE.SNIPPYLY_HUDDLE_DATA)?JSON.parse(sessionStorage.getItem(U.SESSION_STORAGE.SNIPPYLY_HUDDLE_DATA)):null}catch(e){return this.loggingService.catch("Error in HuddleService getHuddleSessionData:",e),null}}removeHuddleSessionData(){try{sessionStorage.removeItem(U.SESSION_STORAGE.SNIPPYLY_HUDDLE_DATA)}catch(e){this.loggingService.catch("Error in HuddleService removeHuddleSessionData:",e)}}removeAttendee(){return ee(this,null,function*(){try{if(this.documentPaths?.huddle&&this.user.userSnippylyId){yield this.commonDbService.deleteData({feature:"huddleAttendee",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,id:this.user?.userSnippylyId,skipFirestore:!0}});return}else return}catch(e){return this.loggingService.catch("Error in HuddleService removeAttendee:",e),Promise.resolve(null)}})}updateUserHuddleState(){return ee(this,null,function*(){try{if(this.attendees&&this.user&&this.documentPaths?.huddle){let e=this.getAudioState(),i=this.getVideoState(),r=this.getScreenSharingState();this.localStreamState$.next({audioState:e,videoState:i,screenSharingState:r});let a={audioState:e,videoState:i,screenSharingState:r};yield this.commonDbService.setData({feature:"huddleAttendeeState",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,id:this.user?.userSnippylyId,skipFirestore:!0},data:a})}}catch(e){this.loggingService.catch("Error in HuddleService updateUserHuddleState:",e)}})}updateHuddleOnCursorMode(){return ee(this,null,function*(){try{if(this.attendees&&this.user&&this.documentPaths?.huddle){let e=on(this.db,`${this.documentPaths?.huddle}/attendees/${this.user.userSnippylyId}/huddleOnCursorMode`);yield Of(e,!!this.huddleOnCursorMode$.value)}}catch(e){this.loggingService.catch("Error in HuddleService updateHuddleOnCursorMode:",e)}})}getAudioState(){try{let e=this.localStream$.value;if(e){let i=e?.getAudioTracks();return!!(i?.length?i[0]:null)?.enabled}return!1}catch(e){return this.loggingService.catch("Error in HuddleService getAudioState:",e),!1}}getVideoState(){try{let e=this.localStream$.value;if(e){let i=e?.getVideoTracks();return!!(i?.length?i[0]:null)?.enabled}return!1}catch(e){return this.loggingService.catch("Error in HuddleService getVideoState:",e),!1}}getScreenSharingState(){try{let e=this.screenSharingStream;if(e){let i=e?.getVideoTracks();return!!(i?.length?i[0]:null)?.enabled}return!1}catch(e){return this.loggingService.catch("Error in HuddleService getVideoState:",e),!1}}removeIceCandidates(e){return ee(this,null,function*(){try{if(this.documentPaths?.huddle&&e){let i=yield this.commonDbService?.getData({feature:"allHuddleIceCandidates",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",skipFirestore:!0}});Object.keys(i).length>0&&Object.keys(i).forEach(r=>ee(this,null,function*(){i[r].connectionId===e&&this.commonDbService.deleteData({feature:"huddleIceCandidate",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,id:r,skipFirestore:!0}})}))}}catch(i){this.loggingService.catch("Error in HuddleService dropCall:",i)}})}get timestamp(){return this.commonDbService.getServerTimestamp()}silence(){try{let e=new AudioContext,i=e.createOscillator(),r=i.connect(e.createMediaStreamDestination());return i.start(),Object.assign(r.stream.getAudioTracks()[0],{enabled:!1})}catch(e){this.loggingService.catch("Error in HuddleService silence:",e)}}black({width:e=640,height:i=480}={}){try{let r=Object.assign(document.createElement("canvas"),{width:e,height:i});r.getContext("2d")?.fillRect(0,0,e,i);let a=r.captureStream();return Object.assign(a.getVideoTracks()[0],{enabled:!1})}catch(r){this.loggingService.catch("Error in HuddleService black:",r)}}getInitialHuddleType(){try{return this.initialHuddleType}catch(e){return this.loggingService.catch("Error in HuddleService getInitialHuddleType:",e),null}}getHuddleAttendees$(){try{return this.attendees$.asObservable()}catch(e){return this.loggingService.catch("Error in HuddleService getHuddleAttendees$:",e),re([])}}getHuddleAttendees(){try{return this.attendees$.value}catch(e){return this.loggingService.catch("Error in HuddleService getHuddleAttendees:",e),null}}getHuddleInvitees$(){try{return this.invitees$.asObservable()}catch(e){return this.loggingService.catch("Error in HuddleService getHuddleInvitees$:",e),re([])}}getHuddleInvitees(){try{return this.invitees$.value}catch(e){return this.loggingService.catch("Error in HuddleService getHuddleInvitees:",e),null}}getHuddleStartTime(){try{return this.userHuddleStartTime$.value}catch(e){return this.loggingService.catch("Error in HuddleService getHuddleStartTime:",e),null}}getTotalUserHuddleDuration(){try{return this.userHuddleStartTime$.value?new Date().getTime()-this.userHuddleStartTime$.value:null}catch(e){return this.loggingService.catch("Error in HuddleService gettotalUserHuddleDuration:",e),null}}inviteUsers(e){try{this.updateInvitees(e);let i={};i.notificationSource="huddleInvite",i.huddleInvitees=e,i.huddleType=this.getInitialHuddleType(),this.updateNotificationsDatabase(i)}catch(i){this.loggingService.catch("Error in HuddleService inviteUsers:",i)}}updateInvitees(e){try{if(this.documentPaths?.huddle){let i={};e.forEach(r=>{if(r?.email){let a=Rt(r.email);i[a]=r}}),this.commonDbService.setData({feature:"allHuddleInvitees",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,skipFirestore:!0},data:i})}}catch(i){this.loggingService.catch("Error in HuddleService updateInvitees:",i)}}updateNotificationsDatabase(e={}){try{let i=I({notificationSource:"huddle"},e);this.notificationService.updateNotificationDatabase(i)}catch(i){this.loggingService.catch("Error in HuddleService updateNotificationsDatabase: ",i)}}getHuddleJoined$(){try{return this.huddleJoined$.asObservable()}catch(e){return this.loggingService.catch("Error in HuddleService getHuddleJoined$:",e),re(!1)}}getHuddleCursorAvailableByAttendeeId(){try{return this.huddleCursorAvailableByAttendeeId$.value}catch(e){return this.loggingService.catch("Error in HuddleService getHuddleCursorAvailableByAttendeeId:",e),null}}getHuddleCursorAvailableByAttendeeId$(){try{return this.huddleCursorAvailableByAttendeeId$.asObservable()}catch(e){return this.loggingService.catch("Error in HuddleService getHuddleCursorAvailableByAttendeeId$:",e),re({})}}updateHuddleCursorAvailableByAttendeeId(e,i){try{let r=this.huddleCursorAvailableByAttendeeId$.value;r[e]=i,this.huddleCursorAvailableByAttendeeId$.next(r)}catch(r){this.loggingService.catch("Error in HuddleService updateCursorUserAvailableByUserId:",r)}}setRemoteStreamsByUserId(e){try{this.remoteStreamsByUserId$.next(e)}catch(i){this.loggingService.catch("Error in HuddleService setRemoteStreamsByUserId:",i)}}getRemoteStreamsByUserId$(){try{return this.remoteStreamsByUserId$.asObservable()}catch(e){return this.loggingService.catch("Error in HuddleService getRemoteStreamsByUserId$:",e),re({})}}enableHuddleOnCursorMode(){try{this.huddleOnCursorMode$.next(!0)}catch(e){this.loggingService.catch("Error in HuddleService enableHuddleOnCursorMode:",e)}}disableHuddleOnCursorMode(){try{this.huddleOnCursorMode$.next(!1)}catch(e){this.loggingService.catch("Error in HuddleService disableHuddleOnCursorMode:",e)}}getHuddleOnCursorMode$(){try{return this.huddleOnCursorMode$.asObservable()}catch(e){return this.loggingService.catch("Error in HuddleService getHuddleOnCursorMode$:",e),re(!1)}}enableFlockModeOnAvatarClick(){try{this.flockModeOnAvatarClickEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in HuddleService enableFlockModeOnAvatarClick:",e)}}disableFlockModeOnAvatarClick(){try{this.flockModeOnAvatarClickEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in HuddleService disableFlockModeOnAvatarClick:",e)}}getFlockModeOnAvatarClick$(){try{return this.flockModeOnAvatarClickEnabled$.asObservable()}catch(e){return this.loggingService.catch("Error in HuddleService getFlockModeOnAvatarClick$:",e),re(!1)}}getFlockModeOnAvatarClick(){try{return this.flockModeOnAvatarClickEnabled$.value}catch(e){return this.loggingService.catch("Error in HuddleService getFlockModeOnAvatarClick:",e),!1}}enableChat(){try{this.chatEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in HuddleService enableChat:",e)}}disableChat(){try{this.chatEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in HuddleService disableChat:",e)}}getChatEnabled$(){try{return this.chatEnabled$.asObservable()}catch(e){return this.loggingService.catch("Error in HuddleService getChatEnabled$:",e),re(!1)}}getChatEnabled(){try{return this.chatEnabled$.value}catch(e){return this.loggingService.catch("Error in HuddleService getChatEnabled:",e),!1}}getHuddleOnCursorModeByAttendeeId$(){try{return this.huddleOnCursorModeByAttendeeId$.asObservable()}catch(e){return this.loggingService.catch("Error in HuddleService getHuddleOnCursorModeByAttendeeId$:",e),re({})}}toggleHuddleOnCursorModeByAttendeeId(e){try{let i=this.huddleOnCursorModeByAttendeeId$.value;i[e]?delete i[e]:i[e]=!0,this.huddleOnCursorModeByAttendeeId$.next(i)}catch(i){this.loggingService.catch("Error in HuddleService toggleHuddleOnCursorModeByAttendeeId:",i)}}addCursorTag(){try{if(!document.querySelector(`${U.TAGS.SNIPPYLY_CURSOR}`)){let e=document.createElement(U.TAGS.SNIPPYLY_CURSOR);e.setAttribute("snippyly-temporary","true"),document.body.appendChild(e)}}catch(e){this.loggingService.catch("Error in HuddleService addCursorTag:",e)}}removeCursorTag(){try{let e=document.querySelector(`${U.TAGS.SNIPPYLY_CURSOR}`);e?.hasAttribute("snippyly-temporary")&&e.remove()}catch(e){this.loggingService.catch("Error in HuddleService removeCursorTag:",e)}}sendMessage(e){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: sendMessage","color: green;"),this.documentPaths?.huddle&&this.user){let i=new lM;i.message=e,i.from=this.user,i.timestamp=this.timestamp,this.commonDbService.setData({feature:"huddleMessage",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,id:i.id,skipFirestore:!0},data:i})}}catch(i){this.loggingService.catch("Error in HuddleService sendMessage:",i)}}getMessages$(){try{return this.loggingService.log("%c[WB] Calling FUNCTION: getMessages$","color: green;"),this.messages$.asObservable()}catch(e){return this.loggingService.catch("Error in HuddleService getMessages$:",e),re([])}}deleteMessages(){try{this.loggingService.log("%c[WB] Calling FUNCTION: deleteMessages","color: green;"),this.documentPaths?.huddle&&this.commonDbService.deleteData({feature:"allHuddleMessages",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,skipFirestore:!0}})}catch(e){this.loggingService.catch("Error in HuddleService deleteMessages:",e)}}showMessagesPanel(){try{this.loggingService.log("%c[WB] Calling FUNCTION: showMessagesPanel","color: green;"),this.messagesPanelVisible$.next(!0)}catch(e){this.loggingService.catch("Error in HuddleService showMessagesPanel:",e)}}hideMessagesPanel(){try{this.loggingService.log("%c[WB] Calling FUNCTION: hideMessagesPanel","color: green;"),this.messagesPanelVisible$.next(!1)}catch(e){this.loggingService.catch("Error in HuddleService hideMessagesPanel:",e)}}toggleMessagesPanel(){try{this.loggingService.log("%c[WB] Calling FUNCTION: toggleMessagesPanel","color: green;"),this.messagesPanelVisible$.next(!this.messagesPanelVisible$.value)}catch(e){this.loggingService.catch("Error in HuddleService toggleMessagesPanel:",e)}}getMessagesPanelVisible$(){try{return this.loggingService.log("%c[WB] Calling FUNCTION: getMessagesPanelVisible$","color: green;"),this.messagesPanelVisible$.asObservable()}catch(e){return this.loggingService.catch("Error in HuddleService getMessagesPanelVisible$:",e),re(!1)}}getMessagesPanelVisible(){try{return this.loggingService.log("%c[WB] Calling FUNCTION: getMessagesPanelVisible","color: green;"),this.messagesPanelVisible$.value}catch(e){return this.loggingService.catch("Error in HuddleService getMessagesPanelVisible:",e),!1}}signOutUser(e){return ee(this,null,function*(){try{this.loggingService.log("%c[WB] Calling FUNCTION: signOutUser","color: green;"),this.huddleJoined$.value&&(yield this.dropCall(),yield this.removeLocalStream(),yield this.removeAttendee())}catch(i){this.loggingService.catch("Error in HuddleService signOutUser:",i)}})}};o.\u0275fac=function(i){return new(i||o)(J(vi),J(Qe),J(je),J(pn),J(lt),J($t),J(Fe),J(xM),J(Vo),J(y),J(Vn),J(bn),J(Hn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var GM=class extends li{constructor(o){super(o),this.getService(y).log("%c[WB] Creating CLASS: HuddleElement","color: blue;"),this.enableCursorMode=this._enableCursorMode,this.disableCursorMode=this._disableCursorMode,this.enableChat=this._enableChat,this.disableChat=this._disableChat,this.enableFlockModeOnAvatarClick=this._enableFlockModeOnAvatarClick,this.disableFlockModeOnAvatarClick=this._disableFlockModeOnAvatarClick}_enableCursorMode(){this.getService(y).log("%c[WB] Calling FUNCTION: _enableCursorMode","color: green;");try{this.trackEvent(Z.Events.Huddle.ENABLE_HUDDLE_ON_CURSOR_MODE_TRIGGERED),this.getService(mr).enableHuddleOnCursorMode()}catch(o){this.getService(y).catch("Error in enableCursorMode: ",o)}}_disableCursorMode(){this.getService(y).log("%c[WB] Calling FUNCTION: _disableCursorMode","color: green;");try{this.trackEvent(Z.Events.Huddle.DISABLE_HUDDLE_ON_CURSOR_MODE_TRIGGERED),this.getService(mr).disableHuddleOnCursorMode()}catch(o){this.getService(y).catch("Error in disableCursorMode: ",o)}}_enableChat(){this.getService(y).log("%c[WB] Calling FUNCTION: _enableChat","color: green;");try{this.trackEvent(Z.Events.Huddle.ENABLE_CHAT_TRIGGERED),this.getService(mr).enableChat()}catch(o){this.getService(y).catch("Error in enableChat: ",o)}}_disableChat(){this.getService(y).log("%c[WB] Calling FUNCTION: _disableChat","color: green;");try{this.trackEvent(Z.Events.Huddle.DISABLE_CHAT_TRIGGERED),this.getService(mr).disableChat()}catch(o){this.getService(y).catch("Error in disableChat: ",o)}}_enableFlockModeOnAvatarClick(){this.getService(y).log("%c[WB] Calling FUNCTION: _enableFlockModeOnAvatarClick","color: green;");try{this.trackEvent(Z.Events.Huddle.ENABLE_FLOCK_MODE_ON_AVATAR_CLICK_TRIGGERED),this.getService(mr).enableFlockModeOnAvatarClick()}catch(o){this.getService(y).catch("Error in enableFlockModeOnAvatarClick: ",o)}}_disableFlockModeOnAvatarClick(){this.getService(y).log("%c[WB] Calling FUNCTION: _disableFlockModeOnAvatarClick","color: green;");try{this.trackEvent(Z.Events.Huddle.DISABLE_FLOCK_MODE_ON_AVATAR_CLICK_TRIGGERED),this.getService(mr).disableFlockModeOnAvatarClick()}catch(o){this.getService(y).catch("Error in disableFlockModeOnAvatarClick: ",o)}}};var WM=class extends li{constructor(o){super(o),this.getService(y).log("%c[WB] Creating CLASS: LiveStateElement","color: blue;"),this.getLiveStateData$=this._getLiveStateData,this.getLiveStateData=this._getLiveStateData,this.setLiveStateData=this._setLiveStateData,this.enableSingleEditorMode=this._enableSingleEditorMode,this.disableSingleEditorMode=this._disableSingleEditorMode,this.isUserEditor$=this._isUserEditor,this.isUserEditor=this._isUserEditor,this.getEditor=this._getEditor,this.setUserAsEditor=this._setUserAsEditor,this.resetUserAccess=this._resetUserAccess,this.singleEditorModeContainerIds=this._singleEditorModeContainerIds,this.enableAutoSyncState=this._enableAutoSyncState,this.disableAutoSyncState=this._disableAutoSyncState,this.requestEditorAccess=this._requestEditorAccess,this.isEditorAccessRequested=this._isEditorAccessRequested,this.acceptEditorAccessRequest=this._acceptEditorAccessRequest,this.rejectEditorAccessRequest=this._rejectEditorAccessRequest,this.cancelEditorAccessRequest=this._cancelEditorAccessRequest,this.editCurrentTab=this._editCurrentTab,this.setEditorAccessTimeout=this._setEditorAccessTimeout,this.enableEditorAccessTransferOnTimeOut=this._enableEditorAccessTransferOnTimeOut,this.disableEditorAccessTransferOnTimeOut=this._disableEditorAccessTransferOnTimeOut,this.enableDefaultSingleEditorUI=this._enableDefaultSingleEditorUI,this.disableDefaultSingleEditorUI=this._disableDefaultSingleEditorUI,this.getEditorAccessTimer=this._getEditorAccessTimer,this.onServerConnectionStateChange=this._onServerConnectionStateChange}_getLiveStateData(o,t){this.getService(y).log("%c[WB] Calling FUNCTION: getLiveStateData","color: green;");try{return this.trackEvent(Z.Events.LiveStateSync.GET_LIVE_STATE_DATA_TRIGGERED),this.getService(Di).getLiveStateData$(o,t)}catch(e){return this.getService(y).catch("Error in _getLiveStateData: ",e),re(null)}}_setLiveStateData(o,t,e){this.getService(y).log("%c[WB] Calling FUNCTION: setLiveStateData","color: green;");try{return this.trackEvent(Z.Events.LiveStateSync.SET_LIVE_STATE_DATA_TRIGGERED),this.getService(Di).setLiveStateData(o,t,e)}catch(i){return this.getService(y).catch("Error in _setLiveStateData: ",i),Promise.resolve()}}_enableSingleEditorMode(o){this.getService(y).log("%c[WB] Calling FUNCTION: enableSingleEditorMode","color: green;");try{this.trackEvent(Z.Events.LiveStateSync.ENABLE_SINGLE_EDITOR_MODE_TRIGGERED),this.getService(Di).enableSingleEditorMode(o)}catch(t){this.getService(y).catch("Error in _enableSingleEditorMode: ",t)}}_disableSingleEditorMode(){this.getService(y).log("%c[WB] Calling FUNCTION: disableSingleEditorMode","color: green;");try{this.trackEvent(Z.Events.LiveStateSync.DISABLE_SINGLE_EDITOR_MODE_TRIGGERED),this.getService(Di).disableSingleEditorMode()}catch(o){this.getService(y).catch("Error in _disableSingleEditorMode: ",o)}}_isUserEditor(){this.getService(y).log("%c[WB] Calling FUNCTION: isUserEditor$","color: green;");try{return this.trackEvent(Z.Events.LiveStateSync.IS_USER_EDITOR_TRIGGERED),this.getService(Di).isUserEditor$()}catch(o){return this.getService(y).catch("Error in _isUserEditor$: ",o),re(null)}}_getEditor(){this.getService(y).log("%c[WB] Calling FUNCTION: getEditor","color: green;");try{return this.trackEvent(Z.Events.LiveStateSync.GET_EDITOR_TRIGGERED),this.getService(Di).getEditor$()}catch(o){return this.getService(y).catch("Error in _getEditor: ",o),re(null)}}_setUserAsEditor(){this.getService(y).log("%c[WB] Calling FUNCTION: setUserAsEditor","color: green;");try{this.trackEvent(Z.Events.LiveStateSync.SET_USER_AS_EDITOR_TRIGGERED),this.getService(Di).setUserAsEditor()}catch(o){this.getService(y).catch("Error in _setUserAsEditor: ",o)}}_resetUserAccess(){this.getService(y).log("%c[WB] Calling FUNCTION: resetUserAccess","color: green;");try{this.trackEvent(Z.Events.LiveStateSync.RESET_USER_ACCESS_TRIGGERED),this.getService(Di).removeEditorAccess()}catch(o){this.getService(y).catch("Error in _resetUserAccess: ",o)}}_singleEditorModeContainerIds(o){this.getService(y).log("%c[WB] Calling FUNCTION: singleEditorModeContainerIds","color: green;");try{this.trackEvent(Z.Events.LiveStateSync.SINGLE_EDITOR_MODE_CONTAINER_IDS_TRIGGERED),this.getService(Di).setSingleEditorModeContainerIds(o)}catch(t){this.getService(y).catch("Error in _singleEditorModeContainerIds: ",t)}}_enableAutoSyncState(){this.getService(y).log("%c[WB] Calling FUNCTION: enableAutoSyncState","color: green;");try{this.trackEvent(Z.Events.LiveStateSync.ENABLE_AUTO_SYNC_STATE_TRIGGERED),this.getService(Di).enableAutoSyncState()}catch(o){this.getService(y).catch("Error in _enableAutoSyncState: ",o)}}_disableAutoSyncState(){this.getService(y).log("%c[WB] Calling FUNCTION: disableAutoSyncState","color: green;");try{this.trackEvent(Z.Events.LiveStateSync.DISABLE_AUTO_SYNC_STATE_TRIGGERED),this.getService(Di).disableAutoSyncState()}catch(o){this.getService(y).catch("Error in _disableAutoSyncState: ",o)}}_requestEditorAccess(){this.getService(y).log("%c[WB] Calling FUNCTION: requestEditorAccess","color: green;");try{return this.trackEvent(Z.Events.LiveStateSync.REQUEST_EDITOR_ACCESS_TRIGGERED),this.getService(Di).requestEditorAccess()}catch(o){return this.getService(y).catch("Error in _requestEditorAccess: ",o),re(null)}}_isEditorAccessRequested(){this.getService(y).log("%c[WB] Calling FUNCTION: isEditorAccessRequested","color: green;");try{return this.trackEvent(Z.Events.LiveStateSync.IS_EDITOR_ACCESS_REQUESTED_TRIGGERED),this.getService(Di).isEditorAccessRequested$()}catch(o){return this.getService(y).catch("Error in _isEditorAccessRequested: ",o),re(null)}}_acceptEditorAccessRequest(){this.getService(y).log("%c[WB] Calling FUNCTION: acceptEditorAccessRequest","color: green;");try{this.trackEvent(Z.Events.LiveStateSync.ACCEPT_EDITOR_ACCESS_REQUEST_TRIGGERED),this.getService(Di).acceptEditorAccessRequest()}catch(o){this.getService(y).catch("Error in _acceptEditorAccessRequest: ",o)}}_rejectEditorAccessRequest(){this.getService(y).log("%c[WB] Calling FUNCTION: rejectEditorAccessRequest","color: green;");try{this.trackEvent(Z.Events.LiveStateSync.REJECT_EDITOR_ACCESS_REQUEST_TRIGGERED),this.getService(Di).rejectEditorAccessRequest()}catch(o){this.getService(y).catch("Error in _rejectEditorAccessRequest: ",o)}}_cancelEditorAccessRequest(){this.getService(y).log("%c[WB] Calling FUNCTION: cancelEditorAccessRequest","color: green;");try{this.trackEvent(Z.Events.LiveStateSync.CANCEL_EDITOR_ACCESS_REQUEST_TRIGGERED),this.getService(Di).cancelEditorAccessRequest()}catch(o){this.getService(y).catch("Error in _cancelEditorAccessRequest: ",o)}}_editCurrentTab(){this.getService(y).log("%c[WB] Calling FUNCTION: editCurrentTab","color: green;");try{this.trackEvent(Z.Events.LiveStateSync.EDIT_CURRENT_TAB_TRIGGERED),this.getService(Di).editCurrentTab()}catch(o){this.getService(y).catch("Error in _editCurrentTab: ",o)}}_setEditorAccessTimeout(o){this.getService(y).log("%c[WB] Calling FUNCTION: setEditorAccessTimeout","color: green;");try{this.trackEvent(Z.Events.LiveStateSync.SET_EDITOR_ACCESS_TIMEOUT_TRIGGERED),this.getService(Di).setEditorAccessTimeout(o)}catch(t){this.getService(y).catch("Error in _setEditorAccessTimeout: ",t)}}_enableEditorAccessTransferOnTimeOut(){this.getService(y).log("%c[WB] Calling FUNCTION: enableEditorAccessTransferOnTimeOut","color: green;");try{this.trackEvent(Z.Events.LiveStateSync.ENABLE_EDITOR_ACCESS_TRANSFER_ON_TIMEOUT_TRIGGERED),this.getService(Di).enableEditorAccessTransferOnTimeOut()}catch(o){this.getService(y).catch("Error in _enableEditorAccessTransferOnTimeOut: ",o)}}_disableEditorAccessTransferOnTimeOut(){this.getService(y).log("%c[WB] Calling FUNCTION: disableEditorAccessTransferOnTimeOut","color: green;");try{this.trackEvent(Z.Events.LiveStateSync.DISABLE_EDITOR_ACCESS_TRANSFER_ON_TIMEOUT_TRIGGERED),this.getService(Di).disableEditorAccessTransferOnTimeOut()}catch(o){this.getService(y).catch("Error in _disableEditorAccessTransferOnTimeOut: ",o)}}_enableDefaultSingleEditorUI(){this.getService(y).log("%c[WB] Calling FUNCTION: enableDefaultSingleEditorUI","color: green;");try{this.trackEvent(Z.Events.LiveStateSync.ENABLE_DEFAULT_SINGLE_EDITOR_UI_TRIGGERED),this.getService(Di).enableDefaultSingleEditorUI()}catch(o){this.getService(y).catch("Error in _enableDefaultSingleEditorUI: ",o)}}_disableDefaultSingleEditorUI(){this.getService(y).log("%c[WB] Calling FUNCTION: disableDefaultSingleEditorUI","color: green;");try{this.trackEvent(Z.Events.LiveStateSync.DISABLE_DEFAULT_SINGLE_EDITOR_UI_TRIGGERED),this.getService(Di).disableDefaultSingleEditorUI()}catch(o){this.getService(y).catch("Error in _disableDefaultSingleEditorUI: ",o)}}_getEditorAccessTimer(){this.getService(y).log("%c[WB] Calling FUNCTION: getEditorAccessTimer","color: green;");try{return this.trackEvent(Z.Events.LiveStateSync.GET_EDITOR_ACCESS_TIMER_TRIGGERED),this.getService(Di).getEditorAccessTimer$()}catch(o){return this.getService(y).catch("Error in _getEditorAccessTimer: ",o),re(new Lv)}}_onServerConnectionStateChange(){this.getService(y).log("%c[WB] Calling FUNCTION: onServerConnectionStateChange","color: green;");try{return this.trackEvent(Z.Events.LiveStateSync.ON_SERVER_CONNECTION_STATE_CHANGE_TRIGGERED),this.getService(Di).onServerConnectionStateChange$()}catch(o){return this.getService(y).catch("Error in _onServerConnectionStateChange: ",o),re(ul.PENDING_INIT)}}};var qM=class extends li{constructor(o){super(o),this.getService(y).log("%c[WB] Creating CLASS: ViewsElement","color: blue;"),this.openHistoryPanel=this._openHistoryPanel,this.closeHistoryPanel=this._closeHistoryPanel,this.toggleHistoryPanel=this._toggleHistoryPanel,this.getNotificationsData=this._getNotificationsData,this.setMaxDays=this._setMaxDays,this.setTabConfig=this._setTabConfig,this.enableReadNotificationsOnForYouTab=this._enableReadNotificationsOnForYouTab,this.disableReadNotificationsOnForYouTab=this._disableReadNotificationsOnForYouTab,this.setAllNotificationsAsRead=this._setAllNotificationsAsRead,this.getUnreadNotificationsCount=this._getUnreadNotificationsCount,this.markNotificationAsReadById=this._markNotificationAsReadById}_openHistoryPanel(){this.getService(y).log("%c[WB] Calling FUNCTION: _openHistoryPanel","color: green;");try{this.trackEvent(Z.Events.Notifications.OPEN_HISTORY_PANEL_TRIGGERED),this.getService(Vn).setHistoryPanelVisibility(!0,!0)}catch(o){this.getService(y).catch("Error in openHistoryPanel: ",o)}}_closeHistoryPanel(){this.getService(y).log("%c[WB] Calling FUNCTION: _closeHistoryPanel","color: green;");try{this.trackEvent(Z.Events.Notifications.CLOSE_HISTORY_PANEL_TRIGGERED),this.getService(Vn).setHistoryPanelVisibility(!1,!0)}catch(o){this.getService(y).catch("Error in closeHistoryPanel: ",o)}}_toggleHistoryPanel(){this.getService(y).log("%c[WB] Calling FUNCTION: _toggleHistoryPanel","color: green;");try{this.trackEvent(Z.Events.Notifications.TOGGLE_HISTORY_PANEL_TRIGGERED),this.getService(Vn).toggleHistoryPanelVisibility(!0)}catch(o){this.getService(y).catch("Error in toggleHistoryPanel: ",o)}}_getNotificationsData(){this.getService(y).log("%c[WB] Calling FUNCTION: _getNotificationsData","color: green;");try{return this.trackEvent(Z.Events.Notifications.GET_NOTIFICATIONS_DATA_TRIGGERED),this.getService(Vn).getNotifications$()}catch(o){return this.getService(y).catch("Error in getNotificationsData: ",o),re([])}}_setMaxDays(o){this.getService(y).log("%c[WB] Calling FUNCTION: _setMaxDays","color: green;");try{this.trackEvent(Z.Events.Notifications.SET_MAX_DAYS_TRIGGERED,{payload:{days:o}}),this.getService(Vn).setMaxDays(o)}catch(t){this.getService(y).catch("Error in setMaxDays: ",t)}}_setTabConfig(o){this.getService(y).log("%c[WB] Calling FUNCTION: _setTabConfig","color: green;");try{this.trackEvent(Z.Events.Notifications.SET_TAB_CONFIG_TRIGGERED,{payload:{tabConfig:o}}),this.getService(Vn).setTabConfig(o)}catch(t){this.getService(y).catch("Error in setTabConfig: ",t)}}_enableReadNotificationsOnForYouTab(){this.getService(y).log("%c[WB] Calling FUNCTION: _enableReadNotificationsOnForYouTab","color: green;");try{this.trackEvent(Z.Events.Notifications.ENABLE_READ_NOTIFICATIONS_ON_FOR_YOU_TAB_TRIGGERED),this.getService(Vn).enableReadNotificationsOnForYouTab()}catch(o){this.getService(y).catch("Error in enableReadNotificationsOnForYouTab: ",o)}}_disableReadNotificationsOnForYouTab(){this.getService(y).log("%c[WB] Calling FUNCTION: _disableReadNotificationsOnForYouTab","color: green;");try{this.trackEvent(Z.Events.Notifications.DISABLE_READ_NOTIFICATIONS_ON_FOR_YOU_TAB_TRIGGERED),this.getService(Vn).disableReadNotificationsOnForYouTab()}catch(o){this.getService(y).catch("Error in disableReadNotificationsOnForYouTab: ",o)}}_setAllNotificationsAsRead(o){this.getService(y).log("%c[WB] Calling FUNCTION: _setAllNotificationsAsRead","color: green;");try{this.trackEvent(Z.Events.Notifications.SET_ALL_NOTIFICATIONS_AS_READ_TRIGGERED,{payload:{config:o}}),this.getService(Vn).setAllNotificationsAsRead(o)}catch(t){this.getService(y).catch("Error in setAllNotificationsAsRead: ",t)}}_getUnreadNotificationsCount(){this.getService(y).log("%c[WB] Calling FUNCTION: _getUnreadNotificationsCount","color: green;");try{return this.trackEvent(Z.Events.Notifications.GET_UNREAD_NOTIFICATIONS_COUNT_TRIGGERED),this.getService(Vn).getUnreadNotificationsCount$()}catch(o){return this.getService(y).catch("Error in getUnreadNotificationsCount: ",o),re({forYou:null,all:null})}}_markNotificationAsReadById(o){this.getService(y).log("%c[WB] Calling FUNCTION: _markNotificationAsReadById","color: green;");try{this.trackEvent(Z.Events.Notifications.MARK_NOTIFICATION_AS_READ_BY_ID_TRIGGERED,{payload:{notificationId:o}}),this.getService(Vn).markNotificationAsReadById(o)}catch(t){this.getService(y).catch("Error in markNotificationAsReadById: ",t)}}};var YM=class extends li{constructor(o){super(o),this.getService(y).log("%c[WB] Creating CLASS: PresenceElement","color: blue;"),this.getOnlineUsersOnCurrentDocument=this._getOnlineUsersOnCurrentDocument,this.setInactivityTime=this._setInactivityTime,this.enableFlockMode=this._enableFlockMode,this.disableFlockMode=this._disableFlockMode,this.startFollowingUser=this._startFollowingUser,this.stopFollowingUser=this._stopFollowingUser,this.enableSelf=this._enableSelf,this.disableSelf=this._disableSelf}_getOnlineUsersOnCurrentDocument(){this.getService(y).log("%c[WB] Calling FUNCTION: getOnlineUsers","color: green;");try{return this.trackEvent(Z.Events.Presence.GET_ONLINE_USERS_ON_CURRENT_DOCUMENT_TRIGGERED),this.getService(Cm).getOnlineUsersOnCurrentDocument()}catch(o){return this.getService(y).catch("Error in _getOnlineUsersOnCurrentDocument: ",o),re(null)}}_setInactivityTime(o){this.getService(y).log("%c[WB] Calling FUNCTION: _setInactivityTime","color: green;");try{this.trackEvent(Z.Events.Presence.SET_INACTIVITY_TIME_TRIGGERED,{payload:{time:o}}),isNaN(o)?this.getService(y).catch("Error in setInactivityTime: ","Provided value is not a number."):this.getService(Cm).setInactivityTime(o)}catch(t){this.getService(y).catch("Error in setInactivityTime: ",t)}}_disableFlockMode(){try{this.trackEvent(Z.Events.Presence.DISABLE_FLOCK_MODE_TRIGGERED),this.getService(vc).disableFlockMode()}catch(o){this.getService(y).catch("Error in _disableFlockMode: ",o)}}_enableFlockMode(o){try{this.trackEvent(Z.Events.Presence.ENABLE_FLOCK_MODE_TRIGGERED,{payload:{options:o}}),this.getService(vc).enableFlockMode(o)}catch(t){this.getService(y).catch("Error in _enableFlockMode: ",t)}}_stopFollowingUser(){try{this.trackEvent(Z.Events.Presence.STOP_FOLLOWING_USER_TRIGGERED),this.getService(vc).stopFollowingUser()}catch(o){this.getService(y).catch("Error in _stopFollowingUser: ",o)}}_startFollowingUser(o){try{this.trackEvent(Z.Events.Presence.START_FOLLOWING_USER_TRIGGERED,{payload:{externalId:o}});let t=this.getService(Cm).getPresenceUserFromExternalId(o);return t&&t.userSnippylyId&&t.name!==void 0?(this.getService(vc).startFollowingUser(t.userSnippylyId,t.name),{success:!0,msg:"Joined flock session."}):{success:!1,msg:"User could not be found."}}catch(t){return this.getService(y).catch("Error in _startFollowingUser: ",t),{success:!1,msg:"Unknown error.",raw:t}}}_enableSelf(){try{this.trackEvent(Z.Events.Presence.ENABLE_SELF_TRIGGERED),this.getService(Cm).enableIncludeSelf()}catch(o){this.getService(y).catch("Error in _enableSelf: ",o)}}_disableSelf(){try{this.trackEvent(Z.Events.Presence.DISABLE_SELF_TRIGGERED),this.getService(Cm).disableIncludeSelf()}catch(o){this.getService(y).catch("Error in _disableSelf: ",o)}}};var KM=class extends li{constructor(o){super(o),this.getService(y).log("%c[WB] Creating CLASS: ReactionElement","color: blue;"),this.enableDarkMode=this._enableDarkMode,this.disableDarkMode=this._disableDarkMode,this.setCustomReactions=this._setCustomReactions}_enableDarkMode(){this.getService(y).log("%c[WB] Calling FUNCTION: enableDarkMode","color: green;");try{this.trackEvent(Z.Events.Reactions.ENABLE_DARK_MODE_TRIGGERED),this.getService(er).enableDarkMode()}catch(o){this.getService(y).catch("Error in _enableDarkMode: ",o)}}_disableDarkMode(){this.getService(y).log("%c[WB] Calling FUNCTION: disableDarkMode","color: green;");try{this.trackEvent(Z.Events.Reactions.DISABLE_DARK_MODE_TRIGGERED),this.getService(er).disableDarkMode()}catch(o){this.getService(y).catch("Error in _disableDarkMode: ",o)}}_setCustomReactions(o){this.getService(y).log("%c[WB] Calling FUNCTION: setCustomReactions","color: green;");try{this.trackEvent(Z.Events.Reactions.SET_CUSTOM_REACTIONS_TRIGGERED,{payload:{reactions:o}}),this.getService(er).setCustomReactions(o)}catch(t){this.getService(y).catch("Error in _setCustomReactions: ",t)}}};var Ose=(()=>{let o=class o{constructor(e,i,r){this.loggingService=e,this.recorderAnnotationService=i,this.recorderService=r,this.actionSubjects=new Map,this.subscriptions=[];try{this.recorderAnnotationService.setRecorderActionsService(this),this.recorderService.setRecorderActionsService(this)}catch(a){this.loggingService.catch("Error in RecorderActionsService constructor: ",a)}}onTranscriptionDone(e){try{this.triggerAction(LO.TRANSCRIPTION_DONE,e)}catch(i){this.loggingService.catch("Error in RecorderActionsService onTranscriptionDone: ",i)}}onRecordingDone(e){try{this.triggerAction(LO.RECORDING_DONE,e)}catch(i){this.loggingService.catch("Error in RecorderActionsService onRecordingDone: ",i)}}onDeleteRecording(e){try{this.triggerAction(LO.DELETE_RECORDING,e)}catch(i){this.loggingService.catch("Error in RecorderActionsService onDeleteRecording: ",i)}}triggerAction(e,i){try{this.actionSubjects.has(e)||this.actionSubjects.set(e,new et),this.actionSubjects.get(e)?.next(i)}catch(r){this.loggingService.catch("Error in RecorderActionsService triggerAction: ",r)}}onAction(e){try{return this.actionSubjects.has(e)||this.actionSubjects.set(e,new et),this.actionSubjects.get(e)?.asObservable()}catch(i){return this.loggingService.catch("Error in RecorderActionsService onAction: ",i),re(null)}}};o.\u0275fac=function(i){return new(i||o)(J(y),J(Qi),J(yi))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var ZM=class extends li{constructor(o){super(o),this.getService(y).log("%c[WB] Creating CLASS: RecorderElement","color: blue;"),this.initRecording=this._initRecording,this.onRecordedData=this._onRecordedData,this.enableDarkMode=this._enableDarkMode,this.disableDarkMode=this._disableDarkMode,this.enableRecordingCountdown=this._enableRecordingCountdown,this.disableRecordingCountdown=this._disableRecordingCountdown,this.getRecordingDataByRecorderId=this._getRecordingDataByRecorderId,this.enableRecordingTranscription=this._enableRecordingTranscription,this.disableRecordingTranscription=this._disableRecordingTranscription,this.getRecordingData=this._getRecordingData,this.enableVideoEditor=this._enableVideoEditor,this.disableVideoEditor=this._disableVideoEditor,this.getRecordings=this._getRecordings,this.fetchRecordings=this._fetchRecordings,this.on=this._on}_initRecording(o,t){this.getService(y).log("%c[WB] Calling FUNCTION: initRecording","color: green;");try{return this.trackEvent(Z.Events.Recording.INIT_RECORDING_TRIGGERED,{payload:{type:o,panelId:t}}),this.getService(yi).initRecording(o,t)}catch(e){return this.getService(y).catch("Error in _initRecording: ",e),re(null)}}_onRecordedData(){this.getService(y).log("%c[WB] Calling FUNCTION: onRecordedData","color: green;");try{return this.trackEvent(Z.Events.Recording.ON_RECORDED_DATA_TRIGGERED),this.getService(yi).onRecordedData()}catch(o){return this.getService(y).catch("Error in _onRecordedData: ",o),re(null)}}_enableDarkMode(){this.getService(y).log("%c[WB] Calling FUNCTION: enableDarkMode","color: green;");try{this.trackEvent(Z.Events.Recording.ENABLE_DARK_MODE_TRIGGERED),this.getService(Qi).setRecorderContainerDarkMode(!0)}catch(o){this.getService(y).catch("Error in _enableDarkMode: ",o)}}_disableDarkMode(){this.getService(y).log("%c[WB] Calling FUNCTION: disableDarkMode","color: green;");try{this.trackEvent(Z.Events.Recording.DISABLE_DARK_MODE_TRIGGERED),this.getService(Qi).setRecorderContainerDarkMode(!1)}catch(o){this.getService(y).catch("Error in _disableDarkMode: ",o)}}_enableRecordingCountdown(){this.getService(y).log("%c[WB] Calling FUNCTION: enableRecordingCountdown","color: green;");try{this.trackEvent(Z.Events.Recording.ENABLE_RECORDING_COUNTDOWN_TRIGGERED),this.getService(yi).enableRecordingCountdown()}catch(o){this.getService(y).catch("Error in _enableRecordingCountdown: ",o)}}_disableRecordingCountdown(){this.getService(y).log("%c[WB] Calling FUNCTION: disableRecordingCountdown","color: green;");try{this.trackEvent(Z.Events.Recording.DISABLE_RECORDING_COUNTDOWN_TRIGGERED),this.getService(yi).disableRecordingCountdown()}catch(o){this.getService(y).catch("Error in _disableRecordingCountdown: ",o)}}_getRecordingDataByRecorderId(o){this.getService(y).log("%c[WB] Calling FUNCTION: getRecordingDataByRecorderId","color: green;");try{return this.trackEvent(Z.Events.Recording.GET_RECORDING_DATA_BY_RECORDER_ID_TRIGGERED,{payload:{recorderId:o}}),this.getService(Qi).getRecorderDataByRecorderId(o)}catch(t){return this.getService(y).catch("Error in _getRecordingDataByRecorderId: ",t),re(null)}}_getRecordings(o){this.getService(y).log("%c[WB] Calling FUNCTION: getRecordings","color: green;");try{return this.trackEvent(Z.Events.Recording.GET_RECORDINGS_TRIGGERED,{payload:{query:o}}),this.getService(Qi).getRecordings(o)}catch(t){return this.getService(y).catch("Error in _getRecordings: ",t),re([])}}_getRecordingData(o){this.getService(y).log("%c[WB] Calling FUNCTION: getRecordingData","color: green;");try{return this.trackEvent(Z.Events.Recording.GET_RECORDING_DATA_TRIGGERED,{payload:{query:o}}),this.getService(Qi).getRecorderDataByRecorderIds(o)}catch(t){return this.getService(y).catch("Error in _getRecordingData: ",t),Promise.resolve({data:null})}}_fetchRecordings(o){this.getService(y).log("%c[WB] Calling FUNCTION: fetchRecordings","color: green;");try{return this.trackEvent(Z.Events.Recording.FETCH_RECORDINGS_TRIGGERED,{payload:{query:o}}),this.getService(Qi).fetchRecorderDataByRecorderIds(o)}catch(t){return this.getService(y).catch("Error in _fetchRecordings: ",t),Promise.resolve([])}}_enableRecordingTranscription(){this.getService(y).log("%c[WB] Calling FUNCTION: enableRecordingTranscription","color: green;");try{this.trackEvent(Z.Events.Recording.ENABLE_RECORDING_TRANSCRIPTION_TRIGGERED),this.getService(Qi).enableRecordingTranscription()}catch(o){this.getService(y).catch("Error in _enableRecordingTranscription: ",o)}}_disableRecordingTranscription(){this.getService(y).log("%c[WB] Calling FUNCTION: disableRecordingTranscription","color: green;");try{this.trackEvent(Z.Events.Recording.DISABLE_RECORDING_TRANSCRIPTION_TRIGGERED),this.getService(Qi).disableRecordingTranscription()}catch(o){this.getService(y).catch("Error in _disableRecordingTranscription: ",o)}}_on(o){this.getService(y).log("%c[WB] Calling FUNCTION: on","color: green;");try{return this.trackEvent(Z.Events.Recording.ON_ACTION_TRIGGERED,{payload:{action:o}}),this.getService(Ose).onAction(o)}catch(t){return this.getService(y).catch("Error in _on: ",t),re(null)}}_enableVideoEditor(){this.getService(y).log("%c[WB] Calling FUNCTION: enableVideoEditor","color: green;");try{this.trackEvent(Z.Events.Recording.ENABLE_VIDEO_EDITOR_TRIGGERED),this.getService(yi).enableVideoEditor()}catch(o){this.getService(y).catch("Error in _enableVideoEditor: ",o)}}_disableVideoEditor(){this.getService(y).log("%c[WB] Calling FUNCTION: disableVideoEditor","color: green;");try{this.trackEvent(Z.Events.Recording.DISABLE_VIDEO_EDITOR_TRIGGERED),this.getService(yi).disableVideoEditor()}catch(o){this.getService(y).catch("Error in _disableVideoEditor: ",o)}}};var Cc=(()=>{let o=class o{constructor(e,i,r,a,s,c){this.analyticsService=e,this.authService=i,this.configService=r,this.domService=a,this.loggingService=s,this.functions=c,this.rewriterAnnotations$=new fe([]),this.rewriterOptions$=new fe({}),this.rewriterEnabled$=new fe(!1),this.lastOpenAIPromptCalledAt=0,this.getRewriterEnabled$().subscribe(p=>{try{if(p){let h=document.querySelectorAll(U.TAGS.SNIPPYLY_REWRITER);if(!document.querySelectorAll(U.TAGS.VELT_REWRITER)?.length&&!h?.length){let E=document.createElement(U.TAGS.VELT_REWRITER);document.body.appendChild(E),this.authService.getUser$().pipe(Ne(D=>!!D),Je(1)).subscribe(D=>{this.analyticsService.trackEvent(Z.Events.Rewriter.REWRITER_ENABLED,{isMobileDevice:this.domService.isMobileDevice()})})}}else{let h=document.querySelectorAll(U.TAGS.SNIPPYLY_REWRITER);h?.length&&h.forEach(E=>{E.remove()});let _=document.querySelectorAll(U.TAGS.VELT_REWRITER);_?.length&&_.forEach(E=>{E.remove()})}}catch(h){this.loggingService.catch("Error in rewriterEnabled$: ",h)}},p=>{this.loggingService.catch("Error in rewriterEnabled$ subscription: ",p)})}getRewriterAnnotations$(){try{return this.rewriterAnnotations$.asObservable()}catch(e){return this.loggingService.catch("Error in getRewriterAnnotations$(): ",e),re([])}}addRewriter(e,i,r){this.loggingService.log("%c[WB] Calling FUNCTION: addRewriter","color: green;");try{let a=this.authService.getUser();if(a)if(a.isReadOnly||a.isAnonymous)this.loggingService.catch("Anonymous/Readonly users cannot add rewriters.");else{let s=new hM;s.from=a,s.color=U.DEFAULT_ANNOTATION_COLOR,i&&(s.targetTextRange=i),r&&(s.rewriterType=r),this.saveRewriterToDb(s)}}catch(a){this.loggingService.catch("Error in RewriterService addRewriter: ",a)}}saveRewriterToDb(e){this.loggingService.log("%c[WB] Calling FUNCTION: saveRewriterToDb","color: green;");try{e?.annotationId||(e.annotationId=Math.random().toString(36).substring(2)+Date.now().toString(36));let i=this.rewriterAnnotations$.getValue();i.push(e),this.rewriterAnnotations$.next(i),this.domService.toggleAnnotationSelection(e)}catch(i){this.loggingService.catch("Error in RewriterService saveRewriterToDb: ",i)}}removeRewriter(e){try{let i=this.rewriterAnnotations$.getValue(),r=i.findIndex(a=>a.annotationId===e.annotationId);r>-1&&(i.splice(r,1),this.rewriterAnnotations$.next(i))}catch(i){this.loggingService.catch("Error in RewriterService removeRewriter: ",i)}}getRewriterOptions(e,i,r){try{if(this.lastOpenAIPromptCalledAt&&Date.now()-this.lastOpenAIPromptCalledAt<1e3)return this.lastOpenAIPromptCalledAt=Date.now(),re([]);this.lastOpenAIPromptCalledAt=Date.now();let a=Cr(this.functions,Zn.cloudFunction.chatgptCompletion,{timeout:20*60*1e3}),s=i?.[0]?.role==="system"?i?.[0]?.content:null;return this.analyticsService.trackEvent(Z.Events.Rewriter.REWRITE_PROMPT_SUBMITTED,{isMobileDevice:this.domService.isMobileDevice(),prompt:s,type:e}),bo(a({messages:i,type:e,apiKey:this.configService.getApiKey(),sdkVersion:Ta(),sdkType:this.configService.getSdkType()})).pipe(ce(c=>c?.data?c.data:[]))}catch(a){return this.loggingService.catch("Error in RewriterService getRewriterOptions: ",a),re([])}}enableRewriter(){try{this.rewriterEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in RewriterService enableRewriter: ",e)}}disableRewriter(){try{this.rewriterEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in RewriterService disableRewriter: ",e)}}getRewriterEnabled$(){try{return this.rewriterEnabled$.asObservable()}catch(e){return this.loggingService.catch("Error in RewriterService getRewriterEnabled$: ",e),re(!1)}}resetRewriter(){try{this.domService.resetSelectedAnnotationsMap(!1,"rewriter"),this.rewriterAnnotations$.next([])}catch(e){this.loggingService.catch("Error in RewriterService resetRewriter: ",e)}}getChatGPTInput(e,i,r=[]){try{let a="";return e&&(a=`
|
|
384
384
|
${a}
|
|
385
385
|
<|im_start|>system
|
|
386
386
|
${e}
|