@veltdev/sdk-dev 4.5.2-beta.33 → 4.5.2-beta.35

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/velt.js CHANGED
@@ -1,4 +1,4 @@
1
- var SNIPPYLY_VERSION = '4.5.2-beta.33';
1
+ var SNIPPYLY_VERSION = '4.5.2-beta.35';
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 R_e=Object.create;var EO=Object.defineProperty,N_e=Object.defineProperties,F_e=Object.getOwnPropertyDescriptor,L_e=Object.getOwnPropertyDescriptors,B_e=Object.getOwnPropertyNames,IO=Object.getOwnPropertySymbols,PW=Object.getPrototypeOf,F7=Object.prototype.hasOwnProperty,MW=Object.prototype.propertyIsEnumerable,V_e=Reflect.get;var AW=(i,o,n)=>o in i?EO(i,o,{enumerable:!0,configurable:!0,writable:!0,value:n}):i[o]=n,I=(i,o)=>{for(var n in o||={})F7.call(o,n)&&AW(i,n,o[n]);if(IO)for(var n of IO(o))MW.call(o,n)&&AW(i,n,o[n]);return i},T=(i,o)=>N_e(i,L_e(o));var L7=(i,o)=>{var n={};for(var e in i)F7.call(i,e)&&o.indexOf(e)<0&&(n[e]=i[e]);if(i!=null&&IO)for(var e of IO(i))o.indexOf(e)<0&&MW.call(i,e)&&(n[e]=i[e]);return n};var U_e=(i,o)=>()=>(o||i((o={exports:{}}).exports,o),o.exports),xO=(i,o)=>{for(var n in o)EO(i,n,{get:o[n],enumerable:!0})},j_e=(i,o,n,e)=>{if(o&&typeof o=="object"||typeof o=="function")for(let t of B_e(o))!F7.call(i,t)&&t!==n&&EO(i,t,{get:()=>o[t],enumerable:!(e=F_e(o,t))||e.enumerable});return i};var kW=(i,o,n)=>(n=i!=null?R_e(PW(i)):{},j_e(o||!i||!i.__esModule?EO(n,"default",{value:i,enumerable:!0}):n,i));var Jm=(i,o,n)=>V_e(PW(i),n,o);var Q=(i,o,n)=>new Promise((e,t)=>{var r=c=>{try{s(n.next(c))}catch(p){t(p)}},a=c=>{try{s(n.throw(c))}catch(p){t(p)}},s=c=>c.done?e(c.value):Promise.resolve(c.value).then(r,a);s((n=n.apply(i,o)).next())});var KG=U_e((c0o,YG)=>{"use strict";var It={};It.generateIdentifier=function(){return Math.random().toString(36).substring(2,12)};It.localCName=It.generateIdentifier();It.splitLines=function(i){return i.trim().split(`
@@ -192,8 +192,8 @@ This typically indicates that your device does not have a healthy Internet conne
192
192
  <a href="${this.videoPlayerUrl}" target="_blank">
193
193
  <img src="${o||this.thumbnailWithPlayIconUrl||this.thumbnailUrl}" />
194
194
  </a>
195
- `}};var tg=class{constructor(){this.type="recorder",this.recordingType="audio",this.mode="floating",this.attachment=null,this.attachments=[],this.pageInfo=new oo}};var Sk=class{constructor(){this.type="rewriter",this.rewriterType="copywriter",this.pageInfo=new oo}};var bb=class{constructor(){this.screenWidth=0,this.screenHeight=0,this.screenScrollHeight=0}};var ng=class{constructor(){this.pageInfo=new oo}},Ib=function(i){return i.Start="start",i.End="end",i}(Ib||{}),u0=function(i){return i.Avatar="avatar",i.Label="label",i}(u0||{});var bk=class{constructor(){this.sources=[],this.playerState=new Eb}},Eb=class{constructor(){this.volume=1}};var xb=class{constructor(){this.to=[],this.resolved=!1,this.type="tag",this.pageInfo=new oo}};var ig=class{constructor(){this.visibility="private"}};var Ik=class{constructor(){this.reactions=[],this.type="reaction",this.pageInfo=new oo,this.isReactionResolverUsed=!1}};var Ek=class{};var ks=function(i){return i.EDITOR="editor",i.VIEWER="viewer",i}(ks||{}),wr=function(i){return i.DOES_NOT_EXIST="does_not_exist",i.PERMISSION_DENIED="permission_denied",i}(wr||{});var Ft=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.analyticsService=t,this.config$=new ve(null),this.disableLogsConfig$=new ve({warnings:!0,suppressAll:!1}),this.apiKey$=new ve(""),this.baseFeatureAllowList=[],this.sf$=new ve(!1),this.sdkType$=new ve("core"),this.logsEnabled$=new ve(!0),this.safeEval$=new ve(!1),this.encryptionProvider$=new ve(null);try{this.analyticsService.setConfigService(this),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(),ot.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(t){this.loggingService.catch("Error in ConfigService initConfig: ",t)}}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 t=this.config$.value;t&&(e?.length?t.featureAllowList=this.baseFeatureAllowList.filter(r=>!e.includes(r)):t.featureAllowList=this.baseFeatureAllowList.slice()),this.config$.next(t)}catch(t){this.loggingService.catch("Error in ConfigService disableFeatures: ",t)}}setSF(e){try{this.sf$.next(e),this.analyticsService.setSF(e)}catch(t){this.loggingService.catch("Error in ConfigService setSF: ",t)}}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),se(!1)}}setSdkType(e){try{this.sdkType$.next(e)}catch(t){this.loggingService.catch("Error in ConfigService setSdkType: ",t)}}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),se("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(t){this.loggingService.catch("Error in ConfigService disableLogs: ",t)}}getDisableLogsConfig(){return this.disableLogsConfig$.value}getDisableLogsConfig$(){return this.disableLogsConfig$.asObservable()}getApiProxyDomain(){try{return this.config$.value?.apiProxyDomain}catch(e){this.loggingService.catch("Error in ConfigService getApiProxyDomain: ",e);return}}enableSafeEval(){try{this.safeEval$.next(!0)}catch(e){this.loggingService.catch("Error in ConfigService enableSafeEval: ",e)}}disableSafeEval(){try{this.safeEval$.next(!1)}catch(e){this.loggingService.catch("Error in ConfigService disableSafeEval: ",e)}}getSafeEval(){try{return this.safeEval$.value}catch(e){return this.loggingService.catch("Error in ConfigService getSafeEval: ",e),!1}}getSafeEval$(){try{return this.safeEval$.asObservable()}catch(e){return this.loggingService.catch("Error in ConfigService getSafeEval$: ",e),se(!1)}}setEncryptionProvider(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setEncryptionProvider","color: green;"),this.encryptionProvider$.next(e)}catch(t){this.loggingService.catch("Error in ConfigService setEncryptionProvider: ",t)}}getEncryptionProvider(){try{return this.encryptionProvider$.value}catch(e){return this.loggingService.catch("Error in ConfigService getEncryptionProvider: ",e),null}}getEncryptionProvider$(){try{return this.encryptionProvider$.asObservable()}catch(e){return this.loggingService.catch("Error in ConfigService getEncryptionProvider$: ",e),se(null)}}};o.\u0275fac=function(t){return new(t||o)(ee(y),ee(et))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var Cce=(()=>{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(j.LOCALSTORAGE_DATA_ID);if(e)return JSON.parse(e);{let t=new vh;return this.setLocalStorageData(t),t}}catch(e){return this.loggingService.catch("Error in getLocalStorageData:",e),new vh}}setLocalStorageData(e){this.loggingService.log("%c[WB] Calling FUNCTION: setLocalStorageData","color: green;");try{if(e){let t=JSON.stringify(e);localStorage?.setItem(j.LOCALSTORAGE_DATA_ID,t)}}catch(t){this.loggingService.catch("Error in setLocalStorageData:",t)}}deleteLocalStorageData(){this.loggingService.log("%c[WB] Calling FUNCTION: deleteLocalStorageData","color: green;"),localStorage?.removeItem(j.LOCALSTORAGE_DATA_ID)}getSessionStorageData(){this.loggingService.log("%c[WB] Calling FUNCTION: getSessionStorageData","color: green;");try{let e=sessionStorage?.getItem(j.LOCALSTORAGE_DATA_ID);if(e)return JSON.parse(e);{let t=new vh;return this.setSessionStorageData(t),t}}catch(e){return this.loggingService.catch("Error in getSessionStorageData:",e),new vh}}setSessionStorageData(e){this.loggingService.log("%c[WB] Calling FUNCTION: setSessionStorageData","color: green;");try{if(e){let t=JSON.stringify(e);sessionStorage?.setItem(j.LOCALSTORAGE_DATA_ID,t)}}catch(t){this.loggingService.catch("Error in setSessionStorageData:",t)}}deleteSessionStorageData(){this.loggingService.log("%c[WB] Calling FUNCTION: deleteSessionStorageData","color: green;");try{sessionStorage?.removeItem(j.LOCALSTORAGE_DATA_ID)}catch(e){this.loggingService.catch("Error in deleteSessionStorageData:",e)}}};o.\u0275fac=function(t){return new(t||o)(ee(y))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var Bd=(()=>{let o=class o{constructor(e,t){this.localStorageService=e,this.loggingService=t,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 Po,t=this.localStorageService.getSessionStorageData();if(t.snippylyAvatar)e=t.snippylyAvatar;else{let r=this.generateUserAvatar();t.snippylyAvatar=r,this.localStorageService.setSessionStorageData(t)}return e}catch(e){return this.loggingService.catch("Error in getSessionAvatar:",e),new Po}}generateUserAvatar(){this.loggingService.log("%c[WB] Calling FUNCTION: generateUserAvatar","color: green;");try{let e=Math.floor(Math.random()*this.avatarList.length),t=this.avatarList[e];return t.color=this.generateUserColor(),t}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 j.AVATAR_COLOR_LIST[e%j.AVATAR_COLOR_LIST.length];let t=Math.floor(Math.random()*j.AVATAR_COLOR_LIST.length);return j.AVATAR_COLOR_LIST[t]}catch(t){return this.loggingService.catch("Error in generateUserColor:",t),""}}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(t){return new(t||o)(ee(Cce),ee(y))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var Vd=(()=>{let o=class o{constructor(e){this.loggingService=e,this.actionSubjects=new Map,this.subscriptions=[]}triggerAction(e,t){try{this.actionSubjects.has(e)||this.actionSubjects.set(e,new tt),this.actionSubjects.get(e)?.next(t)}catch(r){this.loggingService.catch("Error in CoreActionsService triggerAction: ",r)}}onAction(e){try{return this.actionSubjects.has(e)||this.actionSubjects.set(e,new tt),this.actionSubjects.get(e)?.asObservable()}catch(t){return this.loggingService.catch("Error in CoreActionsService onAction: ",t),se(null)}}};o.\u0275fac=function(t){return new(t||o)(ee(y))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var{entries:wce,setPrototypeOf:_ce,isFrozen:g8e,getPrototypeOf:u8e,getOwnPropertyDescriptor:h8e}=Object,{freeze:as,seal:Vl,create:Oce}=Object,{apply:Sz,construct:bz}=typeof Reflect<"u"&&Reflect;as||(as=function(o){return o});Vl||(Vl=function(o){return o});Sz||(Sz=function(o,n,e){return o.apply(n,e)});bz||(bz=function(o,n){return new o(...n)});var Tk=ss(Array.prototype.forEach),f8e=ss(Array.prototype.lastIndexOf),yce=ss(Array.prototype.pop),Db=ss(Array.prototype.push),v8e=ss(Array.prototype.splice),wk=ss(String.prototype.toLowerCase),fz=ss(String.prototype.toString),Sce=ss(String.prototype.match),wb=ss(String.prototype.replace),C8e=ss(String.prototype.indexOf),_8e=ss(String.prototype.trim),Fc=ss(Object.prototype.hasOwnProperty),rs=ss(RegExp.prototype.test),Ob=y8e(TypeError);function ss(i){return function(o){o instanceof RegExp&&(o.lastIndex=0);for(var n=arguments.length,e=new Array(n>1?n-1:0),t=1;t<n;t++)e[t-1]=arguments[t];return Sz(i,o,e)}}function y8e(i){return function(){for(var o=arguments.length,n=new Array(o),e=0;e<o;e++)n[e]=arguments[e];return bz(i,n)}}function di(i,o){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:wk;_ce&&_ce(i,null);let e=o.length;for(;e--;){let t=o[e];if(typeof t=="string"){let r=n(t);r!==t&&(g8e(o)||(o[e]=r),t=r)}i[t]=!0}return i}function S8e(i){for(let o=0;o<i.length;o++)Fc(i,o)||(i[o]=null);return i}function Ch(i){let o=Oce(null);for(let[n,e]of wce(i))Fc(i,n)&&(Array.isArray(e)?o[n]=S8e(e):e&&typeof e=="object"&&e.constructor===Object?o[n]=Ch(e):o[n]=e);return o}function Ab(i,o){for(;i!==null;){let e=h8e(i,o);if(e){if(e.get)return ss(e.get);if(typeof e.value=="function")return ss(e.value)}i=u8e(i)}function n(){return null}return n}var bce=as(["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"]),vz=as(["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"]),Cz=as(["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"]),b8e=as(["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"]),_z=as(["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"]),I8e=as(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),Ice=as(["#text"]),Ece=as(["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"]),yz=as(["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"]),xce=as(["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"]),Dk=as(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),E8e=Vl(/\{\{[\w\W]*|[\w\W]*\}\}/gm),x8e=Vl(/<%[\w\W]*|[\w\W]*%>/gm),T8e=Vl(/\$\{[\w\W]*/gm),D8e=Vl(/^data-[\-\w.\u00B7-\uFFFF]+$/),w8e=Vl(/^aria-[\-\w]+$/),Ace=Vl(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),O8e=Vl(/^(?:\w+script|data):/i),A8e=Vl(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),Pce=Vl(/^html$/i),P8e=Vl(/^[a-z][.\w]*(-[.\w]+)+$/i),Tce=Object.freeze({__proto__:null,ARIA_ATTR:w8e,ATTR_WHITESPACE:A8e,CUSTOM_ELEMENT:P8e,DATA_ATTR:D8e,DOCTYPE_NAME:Pce,ERB_EXPR:x8e,IS_ALLOWED_URI:Ace,IS_SCRIPT_OR_DATA:O8e,MUSTACHE_EXPR:E8e,TMPLIT_EXPR:T8e}),Pb={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,progressingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},M8e=function(){return typeof window>"u"?null:window},k8e=function(o,n){if(typeof o!="object"||typeof o.createPolicy!="function")return null;let e=null,t="data-tt-policy-suffix";n&&n.hasAttribute(t)&&(e=n.getAttribute(t));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}},Dce=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function Mce(){let i=arguments.length>0&&arguments[0]!==void 0?arguments[0]:M8e(),o=Qt=>Mce(Qt);if(o.version="3.2.5",o.removed=[],!i||!i.document||i.document.nodeType!==Pb.document||!i.Element)return o.isSupported=!1,o;let{document:n}=i,e=n,t=e.currentScript,{DocumentFragment:r,HTMLTemplateElement:a,Node:s,Element:c,NodeFilter:p,NamedNodeMap:u=i.NamedNodeMap||i.MozNamedAttrMap,HTMLFormElement:C,DOMParser:E,trustedTypes:D}=i,L=c.prototype,z=Ab(L,"cloneNode"),W=Ab(L,"remove"),J=Ab(L,"nextSibling"),ue=Ab(L,"childNodes"),ye=Ab(L,"parentNode");if(typeof a=="function"){let Qt=n.createElement("template");Qt.content&&Qt.content.ownerDocument&&(n=Qt.content.ownerDocument)}let Ae,He="",{implementation:Fe,createNodeIterator:xe,createDocumentFragment:Se,getElementsByTagName:we}=n,{importNode:_e}=e,fe=Dce();o.isSupported=typeof wce=="function"&&typeof ye=="function"&&Fe&&Fe.createHTMLDocument!==void 0;let{MUSTACHE_EXPR:Oe,ERB_EXPR:Ne,TMPLIT_EXPR:Ct,DATA_ATTR:On,ARIA_ATTR:yt,IS_SCRIPT_OR_DATA:Rt,ATTR_WHITESPACE:Bt,CUSTOM_ELEMENT:In}=Tce,{IS_ALLOWED_URI:Zt}=Tce,Yt=null,Ai=di({},[...bce,...vz,...Cz,..._z,...Ice]),Xt=null,Qn=di({},[...Ece,...yz,...xce,...Dk]),zi=Object.seal(Oce(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}})),em=null,yo=null,gl=!0,zr=!0,ul=!1,Kl=!0,zc=!1,Ag=!0,Zl=!1,Pg=!1,Ah=!1,tm=!1,Ph=!1,Mg=!1,P_=!0,Mh=!1,sO="user-content-",M_=!0,nm=!1,Gc={},Wc=null,Pr=di({},["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"]),Gr=null,kg=di({},["audio","video","img","source","image","track"]),kh=null,k_=di({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Rh="http://www.w3.org/1998/Math/MathML",qc="http://www.w3.org/2000/svg",hl="http://www.w3.org/1999/xhtml",im=hl,Rg=!1,R_=null,w7=di({},[Rh,qc,hl],fz),Zm=di({},["mi","mo","mn","ms","mtext"]),Ng=di({},["annotation-xml"]),lO=di({},["title","style","font","a","script"]),Xl=null,N_=["application/xhtml+xml","text/html"],F_="text/html",So=null,om=null,Nh=n.createElement("form"),L_=function($e){return $e instanceof RegExp||$e instanceof Function},rm=function(){let $e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(om&&om===$e)){if((!$e||typeof $e!="object")&&($e={}),$e=Ch($e),Xl=N_.indexOf($e.PARSER_MEDIA_TYPE)===-1?F_:$e.PARSER_MEDIA_TYPE,So=Xl==="application/xhtml+xml"?fz:wk,Yt=Fc($e,"ALLOWED_TAGS")?di({},$e.ALLOWED_TAGS,So):Ai,Xt=Fc($e,"ALLOWED_ATTR")?di({},$e.ALLOWED_ATTR,So):Qn,R_=Fc($e,"ALLOWED_NAMESPACES")?di({},$e.ALLOWED_NAMESPACES,fz):w7,kh=Fc($e,"ADD_URI_SAFE_ATTR")?di(Ch(k_),$e.ADD_URI_SAFE_ATTR,So):k_,Gr=Fc($e,"ADD_DATA_URI_TAGS")?di(Ch(kg),$e.ADD_DATA_URI_TAGS,So):kg,Wc=Fc($e,"FORBID_CONTENTS")?di({},$e.FORBID_CONTENTS,So):Pr,em=Fc($e,"FORBID_TAGS")?di({},$e.FORBID_TAGS,So):{},yo=Fc($e,"FORBID_ATTR")?di({},$e.FORBID_ATTR,So):{},Gc=Fc($e,"USE_PROFILES")?$e.USE_PROFILES:!1,gl=$e.ALLOW_ARIA_ATTR!==!1,zr=$e.ALLOW_DATA_ATTR!==!1,ul=$e.ALLOW_UNKNOWN_PROTOCOLS||!1,Kl=$e.ALLOW_SELF_CLOSE_IN_ATTR!==!1,zc=$e.SAFE_FOR_TEMPLATES||!1,Ag=$e.SAFE_FOR_XML!==!1,Zl=$e.WHOLE_DOCUMENT||!1,tm=$e.RETURN_DOM||!1,Ph=$e.RETURN_DOM_FRAGMENT||!1,Mg=$e.RETURN_TRUSTED_TYPE||!1,Ah=$e.FORCE_BODY||!1,P_=$e.SANITIZE_DOM!==!1,Mh=$e.SANITIZE_NAMED_PROPS||!1,M_=$e.KEEP_CONTENT!==!1,nm=$e.IN_PLACE||!1,Zt=$e.ALLOWED_URI_REGEXP||Ace,im=$e.NAMESPACE||hl,Zm=$e.MATHML_TEXT_INTEGRATION_POINTS||Zm,Ng=$e.HTML_INTEGRATION_POINTS||Ng,zi=$e.CUSTOM_ELEMENT_HANDLING||{},$e.CUSTOM_ELEMENT_HANDLING&&L_($e.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(zi.tagNameCheck=$e.CUSTOM_ELEMENT_HANDLING.tagNameCheck),$e.CUSTOM_ELEMENT_HANDLING&&L_($e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(zi.attributeNameCheck=$e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),$e.CUSTOM_ELEMENT_HANDLING&&typeof $e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(zi.allowCustomizedBuiltInElements=$e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),zc&&(zr=!1),Ph&&(tm=!0),Gc&&(Yt=di({},Ice),Xt=[],Gc.html===!0&&(di(Yt,bce),di(Xt,Ece)),Gc.svg===!0&&(di(Yt,vz),di(Xt,yz),di(Xt,Dk)),Gc.svgFilters===!0&&(di(Yt,Cz),di(Xt,yz),di(Xt,Dk)),Gc.mathMl===!0&&(di(Yt,_z),di(Xt,xce),di(Xt,Dk))),$e.ADD_TAGS&&(Yt===Ai&&(Yt=Ch(Yt)),di(Yt,$e.ADD_TAGS,So)),$e.ADD_ATTR&&(Xt===Qn&&(Xt=Ch(Xt)),di(Xt,$e.ADD_ATTR,So)),$e.ADD_URI_SAFE_ATTR&&di(kh,$e.ADD_URI_SAFE_ATTR,So),$e.FORBID_CONTENTS&&(Wc===Pr&&(Wc=Ch(Wc)),di(Wc,$e.FORBID_CONTENTS,So)),M_&&(Yt["#text"]=!0),Zl&&di(Yt,["html","head","body"]),Yt.table&&(di(Yt,["tbody"]),delete em.tbody),$e.TRUSTED_TYPES_POLICY){if(typeof $e.TRUSTED_TYPES_POLICY.createHTML!="function")throw Ob('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof $e.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw Ob('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');Ae=$e.TRUSTED_TYPES_POLICY,He=Ae.createHTML("")}else Ae===void 0&&(Ae=k8e(D,t)),Ae!==null&&typeof He=="string"&&(He=Ae.createHTML(""));as&&as($e),om=$e}},B_=di({},[...vz,...Cz,...b8e]),Wr=di({},[..._z,...I8e]),cO=function($e){let Dt=ye($e);(!Dt||!Dt.tagName)&&(Dt={namespaceURI:im,tagName:"template"});let qt=wk($e.tagName),so=wk(Dt.tagName);return R_[$e.namespaceURI]?$e.namespaceURI===qc?Dt.namespaceURI===hl?qt==="svg":Dt.namespaceURI===Rh?qt==="svg"&&(so==="annotation-xml"||Zm[so]):!!B_[qt]:$e.namespaceURI===Rh?Dt.namespaceURI===hl?qt==="math":Dt.namespaceURI===qc?qt==="math"&&Ng[so]:!!Wr[qt]:$e.namespaceURI===hl?Dt.namespaceURI===qc&&!Ng[so]||Dt.namespaceURI===Rh&&!Zm[so]?!1:!Wr[qt]&&(lO[qt]||!B_[qt]):!!(Xl==="application/xhtml+xml"&&R_[$e.namespaceURI]):!1},Ea=function($e){Db(o.removed,{element:$e});try{ye($e).removeChild($e)}catch{W($e)}},Yc=function($e,Dt){try{Db(o.removed,{attribute:Dt.getAttributeNode($e),from:Dt})}catch{Db(o.removed,{attribute:null,from:Dt})}if(Dt.removeAttribute($e),$e==="is")if(tm||Ph)try{Ea(Dt)}catch{}else try{Dt.setAttribute($e,"")}catch{}},dO=function($e){let Dt=null,qt=null;if(Ah)$e="<remove></remove>"+$e;else{let kr=Sce($e,/^[\r\n\t ]+/);qt=kr&&kr[0]}Xl==="application/xhtml+xml"&&im===hl&&($e='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+$e+"</body></html>");let so=Ae?Ae.createHTML($e):$e;if(im===hl)try{Dt=new E().parseFromString(so,Xl)}catch{}if(!Dt||!Dt.documentElement){Dt=Fe.createDocument(im,"template",null);try{Dt.documentElement.innerHTML=Rg?He:so}catch{}}let Mr=Dt.body||Dt.documentElement;return $e&&qt&&Mr.insertBefore(n.createTextNode(qt),Mr.childNodes[0]||null),im===hl?we.call(Dt,Zl?"html":"body")[0]:Zl?Dt.documentElement:Mr},mO=function($e){return xe.call($e.ownerDocument||$e,$e,p.SHOW_ELEMENT|p.SHOW_COMMENT|p.SHOW_TEXT|p.SHOW_PROCESSING_INSTRUCTION|p.SHOW_CDATA_SECTION,null)},Kc=function($e){return $e instanceof C&&(typeof $e.nodeName!="string"||typeof $e.textContent!="string"||typeof $e.removeChild!="function"||!($e.attributes instanceof u)||typeof $e.removeAttribute!="function"||typeof $e.setAttribute!="function"||typeof $e.namespaceURI!="string"||typeof $e.insertBefore!="function"||typeof $e.hasChildNodes!="function")},pO=function($e){return typeof s=="function"&&$e instanceof s};function Ql(Qt,$e,Dt){Tk(Qt,qt=>{qt.call(o,$e,Dt,om)})}let Fg=function($e){let Dt=null;if(Ql(fe.beforeSanitizeElements,$e,null),Kc($e))return Ea($e),!0;let qt=So($e.nodeName);if(Ql(fe.uponSanitizeElement,$e,{tagName:qt,allowedTags:Yt}),$e.hasChildNodes()&&!pO($e.firstElementChild)&&rs(/<[/\w!]/g,$e.innerHTML)&&rs(/<[/\w!]/g,$e.textContent)||$e.nodeType===Pb.progressingInstruction||Ag&&$e.nodeType===Pb.comment&&rs(/<[/\w]/g,$e.data))return Ea($e),!0;if(!Yt[qt]||em[qt]){if(!em[qt]&&Fh(qt)&&(zi.tagNameCheck instanceof RegExp&&rs(zi.tagNameCheck,qt)||zi.tagNameCheck instanceof Function&&zi.tagNameCheck(qt)))return!1;if(M_&&!Wc[qt]){let so=ye($e)||$e.parentNode,Mr=ue($e)||$e.childNodes;if(Mr&&so){let kr=Mr.length;for(let Rr=kr-1;Rr>=0;--Rr){let js=z(Mr[Rr],!0);js.__removalCount=($e.__removalCount||0)+1,so.insertBefore(js,J($e))}}}return Ea($e),!0}return $e instanceof c&&!cO($e)||(qt==="noscript"||qt==="noembed"||qt==="noframes")&&rs(/<\/no(script|embed|frames)/i,$e.innerHTML)?(Ea($e),!0):(zc&&$e.nodeType===Pb.text&&(Dt=$e.textContent,Tk([Oe,Ne,Ct],so=>{Dt=wb(Dt,so," ")}),$e.textContent!==Dt&&(Db(o.removed,{element:$e.cloneNode()}),$e.textContent=Dt)),Ql(fe.afterSanitizeElements,$e,null),!1)},V_=function($e,Dt,qt){if(P_&&(Dt==="id"||Dt==="name")&&(qt in n||qt in Nh))return!1;if(!(zr&&!yo[Dt]&&rs(On,Dt))){if(!(gl&&rs(yt,Dt))){if(!Xt[Dt]||yo[Dt]){if(!(Fh($e)&&(zi.tagNameCheck instanceof RegExp&&rs(zi.tagNameCheck,$e)||zi.tagNameCheck instanceof Function&&zi.tagNameCheck($e))&&(zi.attributeNameCheck instanceof RegExp&&rs(zi.attributeNameCheck,Dt)||zi.attributeNameCheck instanceof Function&&zi.attributeNameCheck(Dt))||Dt==="is"&&zi.allowCustomizedBuiltInElements&&(zi.tagNameCheck instanceof RegExp&&rs(zi.tagNameCheck,qt)||zi.tagNameCheck instanceof Function&&zi.tagNameCheck(qt))))return!1}else if(!kh[Dt]){if(!rs(Zt,wb(qt,Bt,""))){if(!((Dt==="src"||Dt==="xlink:href"||Dt==="href")&&$e!=="script"&&C8e(qt,"data:")===0&&Gr[$e])){if(!(ul&&!rs(Rt,wb(qt,Bt,"")))){if(qt)return!1}}}}}}return!0},Fh=function($e){return $e!=="annotation-xml"&&Sce($e,In)},Lg=function($e){Ql(fe.beforeSanitizeAttributes,$e,null);let{attributes:Dt}=$e;if(!Dt||Kc($e))return;let qt={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:Xt,forceKeepAttr:void 0},so=Dt.length;for(;so--;){let Mr=Dt[so],{name:kr,namespaceURI:Rr,value:js}=Mr,am=So(kr),sr=kr==="value"?js:_8e(js);if(qt.attrName=am,qt.attrValue=sr,qt.keepAttr=!0,qt.forceKeepAttr=void 0,Ql(fe.uponSanitizeAttribute,$e,qt),sr=qt.attrValue,Mh&&(am==="id"||am==="name")&&(Yc(kr,$e),sr=sO+sr),Ag&&rs(/((--!?|])>)|<\/(style|title)/i,sr)){Yc(kr,$e);continue}if(qt.forceKeepAttr||(Yc(kr,$e),!qt.keepAttr))continue;if(!Kl&&rs(/\/>/i,sr)){Yc(kr,$e);continue}zc&&Tk([Oe,Ne,Ct],Lh=>{sr=wb(sr,Lh," ")});let Xc=So($e.nodeName);if(V_(Xc,am,sr)){if(Ae&&typeof D=="object"&&typeof D.getAttributeType=="function"&&!Rr)switch(D.getAttributeType(Xc,am)){case"TrustedHTML":{sr=Ae.createHTML(sr);break}case"TrustedScriptURL":{sr=Ae.createScriptURL(sr);break}}try{Rr?$e.setAttributeNS(Rr,kr,sr):$e.setAttribute(kr,sr),Kc($e)?Ea($e):yce(o.removed)}catch{}}}Ql(fe.afterSanitizeAttributes,$e,null)},Zc=function Qt($e){let Dt=null,qt=mO($e);for(Ql(fe.beforeSanitizeShadowDOM,$e,null);Dt=qt.nextNode();)Ql(fe.uponSanitizeShadowNode,Dt,null),Fg(Dt),Lg(Dt),Dt.content instanceof r&&Qt(Dt.content);Ql(fe.afterSanitizeShadowDOM,$e,null)};return o.sanitize=function(Qt){let $e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},Dt=null,qt=null,so=null,Mr=null;if(Rg=!Qt,Rg&&(Qt="<!-->"),typeof Qt!="string"&&!pO(Qt))if(typeof Qt.toString=="function"){if(Qt=Qt.toString(),typeof Qt!="string")throw Ob("dirty is not a string, aborting")}else throw Ob("toString is not a function");if(!o.isSupported)return Qt;if(Pg||rm($e),o.removed=[],typeof Qt=="string"&&(nm=!1),nm){if(Qt.nodeName){let js=So(Qt.nodeName);if(!Yt[js]||em[js])throw Ob("root node is forbidden and cannot be sanitized in-place")}}else if(Qt instanceof s)Dt=dO("<!---->"),qt=Dt.ownerDocument.importNode(Qt,!0),qt.nodeType===Pb.element&&qt.nodeName==="BODY"||qt.nodeName==="HTML"?Dt=qt:Dt.appendChild(qt);else{if(!tm&&!zc&&!Zl&&Qt.indexOf("<")===-1)return Ae&&Mg?Ae.createHTML(Qt):Qt;if(Dt=dO(Qt),!Dt)return tm?null:Mg?He:""}Dt&&Ah&&Ea(Dt.firstChild);let kr=mO(nm?Qt:Dt);for(;so=kr.nextNode();)Fg(so),Lg(so),so.content instanceof r&&Zc(so.content);if(nm)return Qt;if(tm){if(Ph)for(Mr=Se.call(Dt.ownerDocument);Dt.firstChild;)Mr.appendChild(Dt.firstChild);else Mr=Dt;return(Xt.shadowroot||Xt.shadowrootmode)&&(Mr=_e.call(e,Mr,!0)),Mr}let Rr=Zl?Dt.outerHTML:Dt.innerHTML;return Zl&&Yt["!doctype"]&&Dt.ownerDocument&&Dt.ownerDocument.doctype&&Dt.ownerDocument.doctype.name&&rs(Pce,Dt.ownerDocument.doctype.name)&&(Rr="<!DOCTYPE "+Dt.ownerDocument.doctype.name+`>
196
- `+Rr),zc&&Tk([Oe,Ne,Ct],js=>{Rr=wb(Rr,js," ")}),Ae&&Mg?Ae.createHTML(Rr):Rr},o.setConfig=function(){let Qt=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};rm(Qt),Pg=!0},o.clearConfig=function(){om=null,Pg=!1},o.isValidAttribute=function(Qt,$e,Dt){om||rm({});let qt=So(Qt),so=So($e);return V_(qt,so,Dt)},o.addHook=function(Qt,$e){typeof $e=="function"&&Db(fe[Qt],$e)},o.removeHook=function(Qt,$e){if($e!==void 0){let Dt=f8e(fe[Qt],$e);return Dt===-1?void 0:v8e(fe[Qt],Dt,1)[0]}return yce(fe[Qt])},o.removeHooks=function(Qt){fe[Qt]=[]},o.removeAllHooks=function(){fe=Dce()},o}var Iz=Mce();var kce={ADD_TAGS:["velt-skeleton-loader"],ADD_ATTR:["border-radius"]},Be=(()=>{let o=class o{constructor(e,t,r,a){this.analyticsService=e,this.rendererFactory2=t,this.loggingService=r,this.sanitizer=a,this.isVideoEditorHandlingDelete=!1,this.pageScrollHeight=0,this.enableRectSelectionSubject$=new ve(!1),this.enableRectSelection$=this.enableRectSelectionSubject$.asObservable(),this.scrollableElementsIds$=new ve([]),this.mousedown=!1,this.windowMouseDown$=new tt,this.windowPointerMove$=new ve(null),this.windowPointerUp$=new ve(null),this.documentSelectionChange$=new ve(null),this.windowClick$=new ve(null),this.windowScroll$=new ve(null),this.windowResize$=new ve(null),this.windowKeyupBackspace$=new ve(null),this.windowKeyupDelete$=new ve(null),this.windowKeyupEsc$=new ve(null),this.windowPopState$=new ve(null),this.documentClick$=new ve(null),this.documentClickSubject$=new tt,this.documentFocus$=new ve(null),this.windowKeydownShift$=new ve(null),this.windowKeyupShift$=new ve(null),this.mutation$=new ve(null),this.childListMutation$=new ve(null),this.networkStatus$=new ve(!1),this.xpathCache=new Map,this.xpathCacheId=new Map,this.selectedAnnotationsMap$=new ve({}),this.selectedAnnotationsLocationMap$=new ve({}),this.recordingInProgress$=new ve({}),this.deleteAnnotations$=new ve([]),this.pinHighlighterClass$=new ve(null),this.dialogOpenedInSidebar$=new ve(!1),this.textHighlighterClass$=new ve(null),this.commentPinHighlighter$=new ve(!1),this.deviceInfo$=new ve(new zn),this.customCss$=new ve(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=s=>{try{let c=[];return s.forEach(p=>{if(!Xi(p))if(p instanceof HTMLElement){if(p.className.includes("cdk-overlay-container")||p.className.includes("cdk-overlay-connected-position-bounding-box"))return;if(p.className.includes("cdk-overlay")){let u=!1;p.childNodes.forEach(C=>{Xi(C)&&(u=!0)}),u||c.push(p)}else c.push(p)}else c.push(p)}),c}catch(c){return this.loggingService.catch("Error in DomService filterSnippylyNodes: ",c),[]}},this.loggingService.log("%c[WB] Creating CLASS: DomService","color: blue;");try{this.analyticsService.setDomService(this),this.renderer=this.rendererFactory2.createRenderer(null,null);let s=this.calculateScreenSize();this.currentScreenSize$=new ve(s),this.currentMousePosition$=new ve(this.currentMousePosition),this.detectNetworkStatusChange(),this.getScrollableElementsIds$().pipe(Bi(),dn(([c,p])=>{try{let u=p.filter(E=>!c.includes(E)),C=c.filter(E=>!p.includes(E));C.length&&C.map(D=>document.getElementById(D)).filter(D=>D).forEach(D=>{this.unlistenElementScroll&&this.unlistenElementScroll[D.id]&&this.unlistenElementScroll[D.id]()}),u.length&&u.map(D=>document.getElementById(D)).filter(D=>D).forEach(D=>{this.unlistenElementScroll[D.id]=this.renderer.listen(D,"scroll",L=>{let z=this.calculateScreenSize();this.currentScreenSize$.next(z)})})}catch(u){this.loggingService.catch("Error in DomService getScrollableElementsIds subscription: ",u)}})).subscribe(()=>{},c=>{this.loggingService.catch("Error in DomService getScrollableElementsIds subscription: ",c)}),this.getSelectedAnnotationsMap$().subscribe(c=>{Object.keys(c||{})?.length?cae("snippylyUserScalableNo","viewport","width=device-width, user-scalable=no"):dae("snippylyUserScalableNo")},c=>{this.loggingService.catch("Error in DomService getSelectedAnnotationsMap$ subscription: ",c)})}catch(s){this.loggingService.catch("Error in DomService constructor: ",s)}}setDocService(e){try{this.docService=e,this.subscribeToDomEvents()}catch(t){this.loggingService.catch("Error in DomService setDocService: ",t)}}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.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.unsubscribeFromDocumentFocus(),this.unsetMutationObserver())})).subscribe(),Sn([this.docService?.getOrganizationConfig$(),this.docService?.getDocumentPaths$()]).pipe(ce(([e,t])=>!!e||!!t),Et(),ce(e=>{e?this.onDocumentClick():this.unsubscribeFromDocumentClick()})).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(t){this.loggingService.catch("Error in DomService setScrollableElementsIds: ",t)}}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(t=>{try{if(t?.find(a=>a?.attributeName===j.VELT_IGNORE_CHANGE_DETECTION))return;let r=t.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 u=p.getAttribute(j.ATTRIBUTES.VELT_ELEMENT_CACHE_ID);if(u!==null&&u!==""){let C=this.xpathCacheId.get(u);C!==void 0&&(this.xpathCacheId.delete(u),this.xpathCache.delete(C))}}}),Xi(s)?!1:!!(this.filterSnippylyNodes(a.addedNodes).length||this.filterSnippylyNodes(a.removedNodes).length)});this.childListMutation$.next(r),r.push(...t.filter(a=>a.type==="attributes").filter(a=>!Xi(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(j.VELT_IGNORE_CHANGE_DETECTION):!0}return!0})),r=r.filter(a=>{let s=!0;return Object.keys(j.INGNORE_MUTATION_OBSERVER_CHANGE_TAGS).forEach(c=>{a.target?.closest(c)&&(s=!1)}),s}),r=r.filter(a=>a.target&&Ao(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(t){this.loggingService.catch("Error in DomService change detection: ",t)}}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{co(pi(window,"offline").pipe(ce(()=>!1)),pi(window,"online").pipe(ce(()=>!0)),new Ut(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 t=this.calculateScreenSize();this.deviceInfo$.next(new zn),this.currentScreenSize$.next(t)})}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 t=this.calculateScreenSize();this.currentScreenSize$.next(t)})}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()!==j.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 pi(window,"keydown")}catch(e){return this.loggingService.catch("Error in DomService onWindowKeydown$: ",e),Gg}}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 t=this.getXPath(e.target),r=e.target;if(t?.includes("name()='svg'")){let C=this.getXPath(t);C&&(r=C.iterateNext()||e.target)}let a=r.getBoundingClientRect(),s=e.clientX-a.x,c=e.clientY-a.y,p=s*100/(a.width||1),u=c*100/(a.height||1);this.currentMousePosition.element={xpath:t,topPercentage:u,leftPercentage:p}}else this.currentMousePosition.element=null;this.currentMousePosition$.next(this.currentMousePosition)}catch(t){this.loggingService.catch("Error in DomService updateCurrentMousePosition: ",t)}}getTargetElementForCursorPosition(e,t=!0,r=!1,a=!0,s){try{let c=e,p=c?.touches?.length?c.touches[0]?.clientX:c.clientX,u=c?.touches?.length?c.touches[0]?.clientY:c.clientY,C=this.getBackgroundElement(p,u,t,r);if(C&&s&&typeof s=="function"&&(C=s(C)),C){let E=this.getXPath(C),D=this.getXPath(C,!0),L=C.getBoundingClientRect(),z=p-L.x,W=u-L.y,J=z*100/(L.width||1),ue=W*100/(L.height||1),ye={xpath:E,fXpath:D,leftPercentage:J,topPercentage:ue};if(a){let Ae=this.getXPath(C,!0,!0);ye.cfXpath=Ae}return ye}else return null}catch(c){return this.loggingService.catch("Error in DomService getTargetElementForCommentPinAnnotation: ",c),null}}getBackgroundElement(e,t,r=!0,a=!1){try{let s=document.elementsFromPoint(e,t),c=[];s.forEach(u=>{Xi(u)?c=[]:Ao(u)&&c.push(u)}),a&&(c=c.filter(u=>this.isElementVisibleOnScreen(u)));let p=0;return r||c?.forEach((u,C)=>{u.tagName.toLowerCase()==="svg"&&(p=C)}),c[p]}catch(s){return this.loggingService.catch("Error in DomService getBackgroundElement: ",s),null}}getBackgroundVeltElement(e,t){try{let r=document.elementsFromPoint(e,t),a=[];return r.forEach(s=>{Xi(s)&&Ao(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(t){this.loggingService.catch("Error in DomService setPointerPosition: ",t)}}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(),t=this.currentMousePosition?.pageX||e.x+200,r=Math.min(t,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,t,r){if(e){if(!r&&this.getCommentPinHighlighter()&&(this.pinHighlighterClass$.value?this.addClassToElement(e,this.pinHighlighterClass$.value):this.addClassToElement(e,j.SNIPPYLY_HIGHLIGHT)),t&&!e.hasAttribute(j.ATTRIBUTES.DEFAULT_CURSOR)){let a=e.style.getPropertyValue("cursor"),s=e.style.getPropertyPriority("cursor"),c=a?{defaultCursorValue:a,defaultCursorPriority:s}:"";e.setAttribute(j.ATTRIBUTES.DEFAULT_CURSOR,c?JSON.stringify(c):""),e.style.setProperty("cursor",t,"important")}e.setAttribute(j.SNIPPYLY_HIGHLIGHT,"true"),e.setAttribute(j.VELT_IGNORE_CHANGE_DETECTION,"true")}}removeHighlightFromElement(e){if(e&&(this.pinHighlighterClass$.value&&this.removeClassFromElement(e,this.pinHighlighterClass$.value),this.removeClassFromElement(e,j.SNIPPYLY_HIGHLIGHT),e.removeAttribute(j.SNIPPYLY_HIGHLIGHT),e.removeAttribute(j.VELT_IGNORE_CHANGE_DETECTION),e.hasAttribute(j.ATTRIBUTES.DEFAULT_CURSOR))){try{if(e.style.removeProperty("cursor"),e.getAttribute(j.ATTRIBUTES.DEFAULT_CURSOR)){let t=JSON.parse(e.getAttribute(j.ATTRIBUTES.DEFAULT_CURSOR));e.style.setProperty("cursor",t.defaultCursorValue,t.defaultCursorPriority)}}catch{}e.removeAttribute(j.ATTRIBUTES.DEFAULT_CURSOR)}}highlightUserElement(e,t,r,a=!1){try{e&&(this.addClassToElement(e,j.VELT_LIVE_SELECTION_ON_ELEMENT),a&&this.addClassToElement(e,j.VELT_LIVE_SELECTION_ON_ELEMENT_DEFAULT),e.setAttribute(j.SNIPPYLY_HIGHLIGHT,"true"),e.setAttribute(j.VELT_IGNORE_CHANGE_DETECTION,"true"),t&&!e.style.getPropertyValue(j.VELT_SELECTION_COLOR)&&e.style.setProperty(j.VELT_SELECTION_COLOR,t),r&&e.setAttribute(j.SNIPPYLY_HIGHLIGHT_USER_NAME,r))}catch(s){this.loggingService.catch("Error in DomService highlightUserElement: ",s)}}removeHighlightUserFromElement(e){try{e&&(this.removeClassFromElement(e,j.VELT_LIVE_SELECTION_ON_ELEMENT),this.removeClassFromElement(e,j.VELT_LIVE_SELECTION_ON_ELEMENT_DEFAULT),e.removeAttribute(j.SNIPPYLY_HIGHLIGHT),e.removeAttribute(j.VELT_IGNORE_CHANGE_DETECTION),e.removeAttribute(j.VELT_SELECTION_COLOR),e.removeAttribute(j.SNIPPYLY_HIGHLIGHT_USER_NAME),e.style.removeProperty(j.VELT_SELECTION_COLOR))}catch(t){this.loggingService.catch("Error in DomService removeHighlightUserFromElement: ",t)}}previewHighlightElement(e){e&&e.setAttribute(j.SNIPPYLY_HIGHLIGHT_PREVIEW,"true")}removePreviewHighlightFromElement(e){e&&e.removeAttribute(j.SNIPPYLY_HIGHLIGHT_PREVIEW)}getXPath(e,t=!1,r=!1,a){try{let s=this.calculateXPath(e,t,r,a);if(s&&typeof s=="string"&&s.includes("/svg")){let c=s.split("/"),p=!1;c.forEach((u,C)=>{u.includes("svg")&&(p=!0),p&&(c[C]="svg:"+u)}),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,t,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&&!t)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,t,r,a)+"/"+e.tagName.toLowerCase(),u=Array.from(e.parentNode?.children||[]).filter(C=>C.nodeType===1&&C.tagName===e.tagName?C.className?.split(" ")?.filter(D=>D?.includes("snippyly")||D?.includes("velt")||["show-pin-cursor"].includes(D))[0]===c:!1);if(u.length>1){let C=u.indexOf(e)+1;p+=`[contains(concat(' ', normalize-space(@class), ' '), ' ${c} ')][${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,t,r)+"/"+e.tagName.toLowerCase()+(s.length>1?"["+([].indexOf.call(s,e)+1)+"]":"")}}catch(s){this.loggingService.catch("Error in DomService calculateXPath:",s)}}getElementFromXPath(e,t=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,t);if(r){let a=r?.iterateNext();if(a!==null&&typeof a.setAttribute=="function"){let s=xn();a.setAttribute(j.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],t=[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 bb;return r.screenWidth=Math.max(...t),r.screenHeight=Math.max(...e),r.screenScrollHeight=this.pageScrollHeight,r}catch(e){return this.loggingService.catch("Error in DomService calculateScreenSize:",e),new bb}}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),u;for(;u=p.nextNode();)u?.remove();return this.mergeAdjacentTextNodes(r.body),this.sanitizeHtml(r.body.innerHTML)}catch(t){return this.loggingService.catch("Error in DomService removeSnippylyContent: ",t),e}}mergeAdjacentTextNodes(e){try{let t=e.firstChild;for(;t;){if(t.nodeType===Node.TEXT_NODE){let r=t.nextSibling;for(;r&&r.nodeType===Node.TEXT_NODE;)t.textContent+=r.textContent,r.remove(),r=t.nextSibling}t=t.nextSibling}}catch(t){this.loggingService.catch("Error in DomService mergeAdjacentTextNodes: ",t)}}findLongestNode(e){try{for(let t=e.length-1;t>=0;t--){if(e[t]?.scrollHeight&&e[t]?.clientHeight){let r=Math.max(e[t]?.scrollHeight,e[t]?.clientHeight);this.pageScrollHeight=Math.max(r,this.pageScrollHeight),this.nodeMap[r]=e[t]}e[t]?.childNodes?.length&&this.findLongestNode(e[t]?.childNodes)}}catch(t){this.loggingService.catch("Error in DomService findLongestNode: ",t)}}resetSelectedAnnotationsMap(e=!0,t){try{let r=Array.from(document.querySelectorAll(`[${j.ATTRIBUTES.VELT_ANNOTATION_DRAFT}]`)),a=this.getDraftCommentAnnotationDialogs()||[];r.push(...a),r=Array.from(new Set(r));let s=r.map(C=>C.classList.contains("velt-annotation-draft-checked")?(C.classList.remove("velt-annotation-draft-checked"),null):(this.removeClassFromElement(C,"velt-comment-dialog-shake"),setTimeout(()=>{this.addClassToElement(C,"velt-comment-dialog-shake"),C.getAttribute(j.ATTRIBUTES.VELT_ANNOTATION_EDIT_COMMENT)||C.classList.contains("velt-annotation-draft-checked")||this.addClassToElement(C,"velt-annotation-draft-checked")},100),C.getAttribute(j.ATTRIBUTES.VELT_ANNOTATION_DRAFT))).filter(C=>C),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 C=[];Object.keys(p).forEach(E=>{if(p[E]?.type==="tag"){let D=p[E];D?.to?.length||s.includes(E)||C.push(D)}else p[E]?.comments?.length||s.includes(E)||C.push(p[E])}),this.deleteAnnotations$.next(C),this.deleteAnnotations$.next([])}let u={};Object.keys(p).forEach(C=>{if(s.includes(C)&&(u[C]=p[C]),t)switch(t){case"comment":["comment","videoPin"].includes(p[C]?.type)||(u[C]=p[C]);break;default:p[C]?.type!==t&&(u[C]=p[C]);break}}),Object.keys(u).forEach(C=>{let E=u[C]?.multiThreadAnnotationId;E&&!u[E]&&(u[E]={annotationId:E,type:"multiThread"})}),JSON.stringify(this.selectedAnnotationsMap$.value)!==JSON.stringify(u)&&this.selectedAnnotationsMap$.next(u),this.setDialogOpenedInSidebar(!1)}catch(r){this.loggingService.catch("Error in DomService resetSelectedAnnotationsMap: ",r)}}setRecordingInProgress(e,t){try{if(t)this.recordingInProgress$.next(T(I({},this.recordingInProgress$.value),{[e]:t}));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(`${j.TAGS.SNIPPYLY_COMMENT_DIALOG}`)).forEach(r=>{if(r?.shadowRoot){let a=r.shadowRoot.querySelector(`[${j.ATTRIBUTES.VELT_ANNOTATION_DRAFT}]`);a&&e.push(a)}else{let a=r.querySelector(`${j.TAGS.VELT_SHADOW_DOM_INTERNAL}`);if(a?.shadowRoot){let s=a.shadowRoot?.querySelector(`[${j.ATTRIBUTES.VELT_ANNOTATION_DRAFT}]`);s&&e.push(s)}else{let s=r.querySelector(`[${j.ATTRIBUTES.VELT_ANNOTATION_DRAFT}]`);s&&e.push(s)}}}),e}catch(e){return this.loggingService.catch("Error in DomService getDraftCommentAnnotationDialogs: ",e),[]}}getSelectedAnnotationsMap(e){try{let t=this.selectedAnnotationsMap$.value;if(e){let r={};return Object.keys(t).forEach(a=>{switch(e){case"comment":["comment","videoPin"].includes(t[a].type)&&(r[a]=t[a]);break;default:t[a].type===e&&(r[a]=t[a]);break}}),r}else return t}catch(t){return this.loggingService.catch("Error in DomService getSelectedAnnotationsMap: ",t),{}}}getSelectedAnnotationsMap$(e){return this.selectedAnnotationsMap$.asObservable().pipe(ce(t=>{if(e){let r={};return Object.keys(t).forEach(a=>{t[a].type===e&&(r[a]=t[a])}),r}else return t}))}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,t,r,a=!1,s){try{r==="sidebarShowReplies"?this.setDialogOpenedInSidebar(!0):this.setDialogOpenedInSidebar(!1);let c=JSON.parse(JSON.stringify(this.selectedAnnotationsMap$.value||{})),p=JSON.parse(JSON.stringify(this.selectedAnnotationsLocationMap$.value||{}));c[e.annotationId]&&!a?delete c[e.annotationId]:((!this.windowKeydownShift$.value||a)&&(c={}),c[e.annotationId]=e,p[e.annotationId]=t,s=e?.multiThreadAnnotationId||s,s&&(c[s]={annotationId:s,type:"multiThread"},p[s]=t)),this.selectedAnnotationsMap$.next(c),Object.keys(p).forEach(u=>{c[u]||delete p[u]}),this.selectedAnnotationsLocationMap$.next(p)}catch(c){this.loggingService.catch("Error in DomService toggleAnnotationSelection: ",c)}}setSelectedAnnotationLocation(e,t){try{let r=JSON.parse(JSON.stringify(this.getSelectedAnnotationsLocationMap()||{}));r?.[e]!==t&&(r[e]=t,this.selectedAnnotationsLocationMap$.next(r))}catch(r){this.loggingService.catch("Error in DomService setSelectedAnnotationLocation: ",r)}}updateSelectedAnnotationInMap(e){try{let t=this.selectedAnnotationsMap$.value;e.forEach(r=>{t[r.annotationId]&&(t[r.annotationId]=r)}),this.selectedAnnotationsMap$.next(t)}catch(t){this.loggingService.catch("Error in DomService updateSelectedAnnotationInMap: ",t)}}getDeleteCommmentAnnotations$(){try{return this.deleteAnnotations$.asObservable()}catch(e){return this.loggingService.catch("Error in DomService getDeleteCommmentAnnotations$: ",e),se([])}}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(t){return this.loggingService.catch("Error in DomService onDomChange$: ",t),se([])}}getChildListMutation$(){return this.childListMutation$.asObservable()}onNetworkStatusChange$(){return this.networkStatus$.asObservable()}getNetworkStatus(){return this.networkStatus$.value}getElementOffset(e,t){try{let r={offsetTop:0,offsetLeft:0},a=e;if(a===t){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!==t)if(e?.closest("svg"))for(;a&&a!==t;){let c=window.getComputedStyle(a);if(a.tagName.toLowerCase()==="svg"||a instanceof SVGElement){let p=a.parentElement;if(p){let u=p.getBoundingClientRect(),C=a.getBoundingClientRect();r.offsetLeft+=C.left-u.left,r.offsetTop+=C.top-u.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===t){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:t,height:r,top:a,bottom:s}=e?.getBoundingClientRect();return t>0||r>0||a<window.innerHeight&&s>0}else return!1}catch(t){return this.loggingService.catch("Error in DomService isElementVisible: ",t),!1}}isElementVisibleOnScreen(e){try{if(e){if(!(e instanceof Element))return!1;let t=e,r=window.getComputedStyle(t);return!(r.display==="none"||r.visibility==="hidden"||parseFloat(r.opacity)===0)}return!1}catch(t){return this.loggingService.catch("Error in DomService isElementVisibleOnScreen: ",t),!1}}getClickAndDragPointsObservable(){return new Ut(e=>{let t=pi(document,"mousedown").pipe(ce(p=>({type:p.type,x:p.clientX+window.scrollX,y:p.clientY+window.scrollY,event:p}))),r=pi(document,"mousemove").pipe(ce(p=>({type:p.type,x:p.clientX+window.scrollX,y:p.clientY+window.scrollY,event:p}))),a=pi(document,"mouseup").pipe(ce(p=>({type:p.type,x:p.clientX+window.scrollX,y:p.clientY+window.scrollY,event:p}))),c=t.pipe(he(p=>r.pipe(Bi(),ce(([u,C])=>({startPoint:p,prevPoint:u,curPoint:C})),mo(a)))).subscribe(e);return()=>c.unsubscribe()})}drawRectangle(e,t){let r=document.querySelector(".rectangle");r||(r=document.createElement("div"),this.addClassToElement(r,"rectangle"),r.setAttribute(j.ATTRIBUTES.VELT_COMMENT_DISABLED,"true"),r.setAttribute(j.VELT_IGNORE_CHANGE_DETECTION,"true"),document.body.appendChild(r));let a=Math.abs(t.x-e.x),s=Math.abs(t.y-e.y),c=Math.min(e.x,t.x),p=Math.min(e.y,t.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 t={},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),t.commonAncestorContainer=this.getTextXPath(a),t.commonAncestorContainer){let c=this.getElementFromXPath(t.commonAncestorContainer);c&&(t.commonAncestorContainerFXpath=this.getXPath(c,!0),t.commonAncestorContainerCFXpath=this.getXPath(c,!0,!0))}return t.text=e.toString(),t.occurrence=th(a,0,e.startContainer,e.startOffset,e.toString())+1,t}catch(t){this.loggingService.catch("Error in DomService getTargetTextRangeFromSelectionRange: ",t);return}}getTextXPath(e){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: getTextXPath","color: green;"),e.nodeType===Node.TEXT_NODE){let t=1,r=e.previousSibling;for(;r;)r.nodeType===Node.TEXT_NODE&&t++,r=r.previousSibling;return this.getXPath(e.parentElement)}else return this.getXPath(e)}catch(t){this.loggingService.catch("Error in DomService getTextXPath: ",t);return}}getHostElement(e){try{if(j.NON_NESTABLE_ELEMENTS[e?.tagName?.toLowerCase()]){let r=e?.closest("picture");return r?r?.parentElement:e.parentElement}let t=e.closest("svg");return t?t?.parentElement:e}catch(t){return this.loggingService.catch("Error in DomService getHostElement: ",t),e}}isElementInsideAdditionalLocationContainer(e){try{return!!e?.closest(`[${j.ATTRIBUTES.VELT_LOCATION}], [${j.ATTRIBUTES.VELT_LOCATION_ID}]`)}catch(t){return this.loggingService.catch("Error in DomService isElementInsideAdditionalLocationContainer: ",t),!1}}getAdditionalLocationContainer(e){try{return e?.closest(`[${j.ATTRIBUTES.VELT_LOCATION}], [${j.ATTRIBUTES.VELT_LOCATION_ID}]`)||null}catch(t){return this.loggingService.catch("Error in DomService getAdditionalLocationContainer: ",t),null}}isXpathWithId(e){try{return typeof e=="string"?!!e?.includes("[@id="):!1}catch(t){return this.loggingService.catch("Error in DomService isXpathWithId: ",t),!1}}getListedElements({elementIds:e,elementClassNames:t,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(t?.length)for(let s=0;s<t.length;s++){let c=document.getElementsByClassName(t[s]);for(let p=0;p<c.length;p++){let u=c[p];u&&u instanceof HTMLElement&&a.push(u)}}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 u=c[p];u&&u instanceof HTMLElement&&a.push(u)}}return a}catch(a){return this.loggingService.catch("Error in DomService getListedElements: ",a),[]}}isElementInsideListedElementIds(e,t){try{if(t?.length){for(let r=0;r<t.length;r++){let a=document.getElementById(t[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,t){try{if(t?.length){for(let r=0;r<t.length;r++){let a=document.getElementsByClassName(t[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,t){try{if(t?.length){for(let r=0;r<t.length;r++){let a=document.querySelectorAll(t[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,t){try{this.loggingService.log("%c[WB] Calling FUNCTION: addClassToElement","color: green;"),e&&(e.classList?.contains(t)||e.classList?.add(t))}catch(r){this.loggingService.catch("Error in DomService addClassToElement: ",r)}}removeClassFromElement(e,t){try{this.loggingService.log("%c[WB] Calling FUNCTION: removeClassFromElement","color: green;"),e&&e.classList?.contains(t)&&e.classList?.remove(t)}catch(r){this.loggingService.catch("Error in DomService removeClassFromElement: ",r)}}isElementInsideParentWithAttribute(e,t,r){try{let a=e;for(;a&&a!==document.body;){if(a?.getAttribute&&a?.getAttribute(t)===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(t){this.loggingService.catch("Error in DomService setVideoEditorHandlingDelete: ",t)}}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(t){this.loggingService.catch("Error in DomService setCustomCss: ",t)}}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),se(null)}}injectCustomCss(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: injectCustomCss","color: green;");let t=this.customCss$.value;if(t){let r=e?.shadowRoot?.querySelector(`[${j.VELT_CUSTOM_CSS}]`);if(r&&r.remove(),t?.type==="link"){let a=document.createElement("link");a.href=t?.value,a.rel="stylesheet",a.setAttribute(j.VELT_CUSTOM_CSS,"true"),e?.shadowRoot?.appendChild(a)}else{let a=document.createElement("style");a.innerHTML=this.sanitizeHtml(t?.value),a.setAttribute(j.VELT_CUSTOM_CSS,"true"),e?.shadowRoot?.appendChild(a)}}}catch(t){this.loggingService.catch("Error in DomService injectCustomCss: ",t)}}trimCommentHtml(e){try{let t=document.createElement("div");t.innerHTML=e,this.removeEmptyElements(t);let r=t.innerHTML;return r=r.replace(o.MULTIPLE_NBSP_REGEX," ").replace(o.TRIM_NBSP_REGEX,"").trim(),r}catch(t){return this.loggingService.catch("Error in DomService trimCommentHtml: ",t),e}}removeEmptyElements(e){try{let a=function(s){return r.test(s.innerHTML)};var t=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(t=>{t.nodeType===Node.TEXT_NODE?t.nodeValue=t.nodeValue?.replace(/\s+/g," ").trim()??"":t.nodeType===Node.ELEMENT_NODE&&this.normalizeWhitespace(t)})}catch(t){this.loggingService.catch("Error in DomService normalizeWhitespace: ",t)}}sanitizeHtml(e){try{return this.loggingService.log("%c[WB] Calling FUNCTION: sanitizeHtml","color: green;"),Iz.sanitize(e,kce)}catch(t){return this.loggingService.catch("Error in DomService sanitizeHtml: ",t),""}}sanitizeSvg(e){try{return Iz.sanitize(e,kce)}catch(t){return this.loggingService.catch("Error in DomService sanitizeSvg: ",t),e}}setDeviceInfo(){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDeviceInfo","color: green;");let e=new zn;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),se(new zn)}}getTabId(){try{let e=sessionStorage.getItem(j.SESSION_STORAGE.VELT_TAB_ID),t=this.getTabIdFromWindowName();return(!e||e!==t)&&(e=xn(),sessionStorage.setItem(j.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(t){this.loggingService.catch("Error in DomService setTabIdToWindowName: ",t)}}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 zn}}isMobileDevice(){try{return new zn().getDeviceType()===ir.MOBILE}catch(e){return this.loggingService.catch("Error in DomService isMobileDevice: ",e),!1}}isTabletDevice(){try{return new zn().getDeviceType()===ir.TABLET}catch(e){return this.loggingService.catch("Error in DomService isTabletDevice: ",e),!1}}isDesktopDevice(){try{return new zn().getDeviceType()===ir.DESKTOP}catch(e){return this.loggingService.catch("Error in DomService isDesktopDevice: ",e),!1}}deepCloneElement(e){try{var t=document.createElement(e?.tagName);return Array.from(e.attributes).forEach(r=>{t.setAttribute(r.nodeName,r.nodeValue)}),e.childNodes.forEach(r=>{r.nodeType===Node.ELEMENT_NODE?t.appendChild(this.deepCloneElement(r)):r.nodeType===Node.TEXT_NODE&&t.appendChild(document.createTextNode(r.nodeValue))}),t}catch(r){return this.loggingService.catch("Error in DomService deepCloneElement: ",r),e}}setRandomNumberToElementRecursive(e){try{if(!e)return;let t=Math.random().toString(36).substring(7);e&&e.setAttribute&&typeof e.setAttribute=="function"&&(e.getAttribute("velt-wireframe-id")||e.setAttribute("velt-wireframe-id",t)),Array.from(e.children).forEach(a=>{this.setRandomNumberToElementRecursive(a)})}catch(t){this.loggingService.catch("Error in DomService setRandomNumberToElementRecursive: ",t)}}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 zn().getDeviceType()===ir.MONITOR}catch(e){return this.loggingService.catch("Error in DomService isMonitorDevice: ",e),!1}}};o.MULTIPLE_NBSP_REGEX=/(?:&nbsp;\s*){2,}/g,o.TRIM_NBSP_REGEX=/^(?:&nbsp;\s*)+|(?:&nbsp;\s*)+$/g,o.\u0275fac=function(t){return new(t||o)(ee(et),ee(er),ee(y),ee(Ys))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var Ve=(()=>{let o=class o{constructor(e,t,r,a,s,c,p,u){this.afAuth=e,this.configService=t,this.avatarService=r,this.coreActionsService=a,this.domService=s,this.functions=c,this.analyticsService=p,this.loggingService=u,this.user$=new ve(null),this.userOptions$=new ve(null),this.userContacts$=new ve(null),this.userOrganization$=new ve(null),this.providedUser=new Po,this.firebaseConfig$=new ve(null),this.advancedQueries$=new ve(null),this.planDetails$=new ve(null),this.signOutPreviousUser$=new ve(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.onRetrySubscription=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(C=>{this.config=C}),this.forceReLoggedIn=localStorage.getItem(j.LOCAL_STORAGE.VELT_USER_FORCE_RE_LOGGED_IN)==="true",this.sessionReLoginSubscription=ei(this.afAuth).pipe(bo(this.afAuth.currentUser),Bi(),he(([C,E])=>this.domService.onNetworkStatusChange$().pipe(Le(D=>D),st(1),ce(()=>({previousUser:C,currentUser:E}))))).subscribe(D=>Q(this,[D],function*({previousUser:C,currentUser:E}){if(!E&&C){let L=C?.stsTokenManager?.expirationTime,z=new Date().getTime(),W=L-z;z>L&&(this.analyticsService.trackEvent(Z.Events.Core.SDK_SESSION_TOKEN_EXPIRED,{apiKey:this.apiKey,user:this.user$.value,lastLoggedInUserData:this.lastLoggedInUserData,timeLeft:W,forceReset:this.userOptions$.value?.forceReset,sessionReLoginCount:this.sessionReLoginCount},!0,this.user$.value?.userSnippylyId),this.user$.value&&C?.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:W,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:W,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"))))}}),C=>{this.loggingService.catch("Error in AuthService sessionReLoginSubscription: ",C)}),this.getUser$().pipe(Et(mn)).subscribe(C=>{let E=_a(C);this.coreActionsService.triggerAction($i.USER_UPDATE,E),this.coreActionsService.triggerAction($i.INIT_UPDATE,{event:$i.USER_UPDATE,payload:{user:E}})})}catch(C){this.loggingService.catch("Error in AuthService constructor: ",C)}}setApiKey(e,t){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),t||(t=new dk),this.configService.initConfig(t),t.debugMode?sessionStorage.setItem("debugMode","true"):sessionStorage.removeItem("debugMode"),this.autoLoginCalled||ei(this.afAuth).pipe(st(1)).subscribe(r=>Q(this,null,function*(){if(this.autoLoginCalled=!0,r){let a=yield Mm(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(t){this.loggingService.catch("Error in setUsersService: ",t)}}setDocService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocService","color: green;"),this.docService=e}catch(t){this.loggingService.catch("Error in setDocService: ",t)}}setContactService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setContactService","color: green;"),this.contactService=e}catch(t){this.loggingService.catch("Error in setContactService: ",t)}}setIamService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setIamService","color: green;"),this.iamService=e}catch(t){this.loggingService.catch("Error in setIamService: ",t)}}setAreaService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setAreaService","color: green;"),this.areaService=e}catch(t){this.loggingService.catch("Error in setAreaService: ",t)}}setCommentService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setCommentService","color: green;"),this.commentService=e}catch(t){this.loggingService.catch("Error in setCommentService: ",t)}}setReactionService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setReactionService","color: green;"),this.reactionService=e}catch(t){this.loggingService.catch("Error in setReactionService: ",t)}}setRecorderAnnotationService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setRecorderAnnotationService","color: green;"),this.recorderAnnotationService=e}catch(t){this.loggingService.catch("Error in setRecorderAnnotationService: ",t)}}setViewsService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setViewsService","color: green;"),this.viewsService=e}catch(t){this.loggingService.catch("Error in setViewsService: ",t)}}setCommonDbService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setCommonDbService","color: green;"),this.commonDbService=e}catch(t){this.loggingService.catch("Error in setCommonDbService: ",t)}}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")}setVeltAuthProvider(e){return Q(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: setVeltAuthProvider","color: green;");try{this.onRetrySubscription?.unsubscribe();let t=null;e.generateToken&&typeof e.generateToken=="function"&&(t=yield e.generateToken());let r=yield jj(()=>window.Velt.identify(e.user,I(I({},e.options||{}),t&&{authToken:t}),{fromProvider:!0}),e.retryConfig||{retryCount:0,retryDelay:0});return r&&e.generateToken&&typeof e.generateToken=="function"&&(this.onRetrySubscription=this.coreActionsService.onAction($i.ERROR).pipe(Le(a=>a.code==="token_expired"),st(10)).subscribe(a=>Q(this,null,function*(){if(a.code==="token_expired"){let s=this.docService?.getDocumentIds()?.map(D=>({id:D.clientDocumentId}))??[],c=this.docService?.getOptionsFromDocumentPaths()??void 0,p=[],u=this.docService?.getLocation();u&&p.push(u.location);let C=this.docService?.getLocations();C&&Object.values(C).forEach(D=>{p.push(D.location)}),(yield jj(()=>Q(this,null,function*(){try{let D=yield e.generateToken?.();return D?window.Velt.identify(e.user,I(I({},e.options||{}),D&&{authToken:D}),{fromProvider:!0}):!0}catch{return!1}}),e.retryConfig||{retryCount:0,retryDelay:0}))&&(yield this.docService?.setDocuments({documents:s,options:c,source:"internal"}),yield this.docService?.setLocations({locations:p,source:"internal",options:{appendLocation:!u}}))}}))),r}catch(t){return this.loggingService.catch("Error in setVeltAuthProvider: ",t),null}})}initializeClient(e,t,r,a,s){return Q(this,null,function*(){try{if(this.autoLoginRequired=!1,this.userOptions$.next(t),this.initializeClientToken)this.pendingUserLogin=e,this.pendingUserLoginSource=s;else{e.userSnippylyId=Av(this.configService.getApiKey(),e.userId),this.pendingUserLogin=void 0,this.pendingUserLoginSource=void 0,this.initializeClientToken=r;let c=yield ei(this.afAuth).pipe(st(1)).toPromise().catch(u=>null),p=!0;if(this.providedUser=JSON.parse(JSON.stringify(e)),c){let u=yield Mm(c,!0).catch(D=>null);if(!u)return;let{user:C,firebaseConfig:E}=u.claims;if(c?.uid!==e?.userSnippylyId||e?.groupId!==C?.groupId||e?.organizationId!==C?.organizationId||t?.forceReset||!a&&e?.organizationId&&!this.forceReLoggedIn||this.forceReLoginRequiredForAdvancedQueries(e)||this.forceReLoginRequiredForRegion(e,E)||this.forceReLoginRequiredForCommentViews(e))localStorage.setItem(j.LOCAL_STORAGE.VELT_USER_FORCE_RE_LOGGED_IN,"true"),localStorage.setItem(j.LOCAL_STORAGE.VELT_COMMENT_VIEWS_MIGRATED,"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 Mm(c,!0).catch(J=>null);if(!D)return;let{firebaseConfig:L,user:z,advancedQueries:W}=D.claims;this.validateOrganizationId(e),this.setFirebaseConfig(L),this.setAdvancedQueries(W),z&&(this.providedUser.isAdmin=!!z.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,e.userId);let u=br(this.functions,Er({url:oi.cloudFunction.validateClient,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:20*60*1e3}),C=ia(),E=(yield u({apiKey:this.apiKey,user:e,version:C,authToken:t?.authToken}))?.data;if(E.error){if(this.analyticsService.trackEvent(Z.Events.Core.SDK_VALIDATE_CLIENT_FAILED,T(I({apiKey:this.apiKey,clientUserId:e.userId,snippylyUserId:e.userSnippylyId,message:E.error,forceReset:this.userOptions$.value?.forceReset,user:this.getUserWithoutContacts(e)},E),{source:s}),!0,e.userSnippylyId,e.userId),E.error&&typeof E.error=="string")if(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",error:E?.error,source:E?.source};this.coreActionsService.triggerAction($i.ERROR,D)}else{let D={code:"too_many_retries",message:"Token expired. Too many retries.",error:E?.error,source:E?.source};this.coreActionsService.triggerAction($i.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,e.userId)}else{let D=E;this.coreActionsService.triggerAction($i.ERROR,D)}throw E}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,e.userId),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 Mm(this.afAuth.currentUser,!0).catch(W=>null);if(!D)return;let{user:L,advancedQueries:z}=D.claims;this.setAdvancedQueries(z),this.providedUser.isAdmin=!!L?.isAdmin,this.initializeSignedInUser(this.afAuth.currentUser,a)}}this.initializeClientToken=0,this.lastLoggedInUserData={user:e,userOptions:t,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=ia();return(e?parseInt(e.split(".")?.[0]||"0"):0)>=4}catch(e){return this.loggingService.catch("Error in isVersionGreaterThanOrEqualTo4: ",e),!1}}isVersion4Point5(){try{let e=ia();if(e){let t=e.split("."),r=parseInt(t[0]||"0"),a=parseInt(t[1]||"0"),s=parseInt(t[2]||"0");if(r>=4&&a>=5)return r===4&&a===5&&s===0?!e.toLowerCase().includes("beta"):!0}return!1}catch(e){return this.loggingService.catch("Error in isVersion4Point5: ",e),!1}}forceReLoginRequiredForAdvancedQueries(e){try{let t=this.isVersionGreaterThanOrEqualTo4(),r=!1;try{let a=localStorage.getItem(j.LOCAL_STORAGE.VELT_ADVANCED_QUERIES);a&&(r=JSON.parse(a)?.advancedQueriesEnabled)}catch(a){this.loggingService.catch("Error in forceReLoginRequiredForAdvancedQueries: ",a)}return!!(t&&e.organizationId&&!r)}catch(t){return this.loggingService.catch("Error in forceReLoginRequiredForAdvancedQueries: ",t),!1}}forceReLoginRequiredForCommentViews(e){try{let t=this.isVersion4Point5(),r=!1;try{let a=localStorage.getItem(j.LOCAL_STORAGE.VELT_COMMENT_VIEWS_MIGRATED);a&&(r=JSON.parse(a))}catch(a){this.loggingService.catch("Error in forceReLoginRequiredForCommentViews: ",a)}return!!(t&&e.organizationId&&!r)}catch(t){return this.loggingService.catch("Error in forceReLoginRequiredForCommentViews: ",t),!1}}forceReLoginRequiredForRegion(e,t){try{return!!(this.isVersionGreaterThanOrEqualTo4()&&e.organizationId&&!t?.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({},oi.firebaseConfig),e)})}catch(t){this.loggingService.catch("Error in setFirebaseConfig: ",t)}}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(j.LOCAL_STORAGE.VELT_ADVANCED_QUERIES,JSON.stringify(e)),this.advancedQueries$.next(e)}catch(t){this.loggingService.catch("Error in setAdvancedQueries: ",t)}}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 Sn([this.configService.getConfig$(),this.getAdvancedQueries$()]).pipe(ce(()=>this.getAdvancedQueriesEnabled()),kn(()=>se(!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;"),ei(this.afAuth).pipe(he(e=>e?this.user$.asObservable():se(null)),Et(mn))}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 t=this.user$.value;if(e.userId&&e.userId!==t?.userId||e?.groupId&&e?.groupId!==t?.groupId||e?.organizationId&&e?.organizationId!==t?.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),t){let r=I(I({},t),e);this.updateUserInternally(r)}}catch(t){this.loggingService.catch("Error in updateUser: ",t)}}signInWithCustomToken(e,t,r="manual"){this.loggingService.log("%c[WB] Calling FUNCTION: signInWithCustomToken","color: green;");try{return Oee(this.afAuth,t).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?.clearCacheOnUserCascade(),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,t){this.loggingService.log("%c[WB] Calling FUNCTION: initializeSignedInUser","color: green;");try{let r=new Po;r.userSnippylyId=e.uid,r.type="signedIn",this.mergeUserWithProvidedUserData(r,t)}catch(r){this.loggingService.catch("Error in initializeSignedInUser: ",r)}}mergeUserWithProvidedUserData(e,t){return Q(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({userIds:[e.userId],organizationId:this.providedUser?.organizationId||e.organizationId,skipUserCheck:!0});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?.color||this.providedUser?.color||this.getUserAvatarColor(e.userId),e.textColor=r?.textColor||this.providedUser?.textColor||this.getUserTextColor(e.userId),e.initial=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 Q(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: updateUserInternally","color: green;");try{let t=Object.assign({},e);delete t.contacts,this.analyticsService.identifyUser(e.userSnippylyId,t,{forceReset:this.userOptions$.value?.forceReset}),this.getPlanDetailsCalled||(yield this.getPlanDetailsFromDb()),this.afAuth.currentUser&&(this.user$.next(e),this.updateUserToFirebase(e))}catch(t){this.loggingService.catch("Error in updateUserInternally: ",t)}})}updateUserToFirebase(e){this.loggingService.log("%c[WB] Calling FUNCTION: updateUserToFirebase","color: green;");try{let t=JSON.parse(JSON.stringify(e)),r=T(I({},t),{lastUpdated:new Date})}catch(t){this.loggingService.catch("Error in updateUserToFirebase: ",t)}}getPlanDetailsFromDb(){return Q(this,null,function*(){try{this.getPlanDetailsCalled=!0;let t=yield br(this.functions,Er({url:oi.cloudFunction.getPlanDetails,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:20*60*1e3})({apiKey:this.configService.getApiKey(),sdkVersion:ia(),sdkType:this.configService.getSdkType()});return t?.data?.isPlanExpired&&(this.analyticsService.trackEvent(Z.Events.Core.SDK_PLAN_EXPIRED),this.configService.getSF()||console.warn("Velt SDK plan has expired.")),this.planDetails$.next(t?.data||{planInfo:null,isPlanExpired:!1}),t}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(Le(e=>!!e),ce(e=>!!e?.isPlanExpired))}isPlanExpired(){return this.planDetails$.getValue()?.isPlanExpired}addPreSignOutFuction(e,t){try{this.preSignOutFunctions.set(e,t)}catch(r){this.loggingService.catch("Error in addPreSignOutFuction: ",r)}}setUserOrganization(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setUserOrganization","color: green;");let t=JSON.parse(JSON.stringify(this.userOrganization$.value||{}));this.getUser()?.organizationId===e?.organizationId?(t.metadata=e,this.userOrganization$.next(t)):this.userOrganization$.next(null)}catch(t){this.loggingService.catch("Error in setUserOrganization: ",t)}}setOrganizationUserGroups(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setUserOrganizationGroups","color: green;");let t=JSON.parse(JSON.stringify(this.userOrganization$.value||{}));this.getUser()?.organizationId===t?.metadata?.organizationId&&(t.groups=e,this.userOrganization$.next(t))}catch(t){this.loggingService.catch("Error in setUserOrganizationGroups: ",t)}}getUserOrganization$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getUserOrganization$","color: green;"),this.getUser$().pipe(he(e=>e?this.userOrganization$.asObservable().pipe(ce(t=>t?.metadata?.organizationId===e.organizationId?t:null)):se(null)))}signOutUser(e="internal"){return Q(this,null,function*(){try{e==="external"&&this.onRetrySubscription?.unsubscribe(),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 t=yield ei(this.afAuth).pipe(st(1)).toPromise().catch(r=>null);if(t){this.resetServicesCache(),this.user$.next(null);for(let[r,a]of this.preSignOutFunctions)try{yield a(t)}catch(s){this.loggingService.catch(`Error in signOutUser ${r} function: `,s)}return this.user$.next(null),yield Pd(1e3),Aee(this.afAuth).catch(r=>{this.loggingService.catch("Error in signOutUser:",r)})}else return Promise.resolve()}catch(t){this.loggingService.catch("Error in signOutUser: ",t)}})}isFeatureAllowed(e){return ro(this.config,this.user$.value,e)}getUserWithoutContacts(e){try{if(e){let t=JSON.parse(JSON.stringify(e));return delete t.contacts,t}else return null}catch(t){return this.loggingService.catch("Error in getUserWithoutContacts: ",t),null}}getUserForClient(e){try{return _a(e)}catch(t){return this.loggingService.catch("Error in getUserForClient: ",t),null}}getUserAvatarColor(e){try{return e?this.avatarService.generateUserColor(En(e)):"#625DF5"}catch{return"#625DF5"}}getUserTextColor(e){try{return"#FFFFFF"}catch{return"#FFFFFF"}}setOptionalPropertiesToUsers(e){try{e.forEach(t=>{try{t?.color||(t.color=this.getUserAvatarColor(t?.userId)),t?.textColor||(t.textColor=this.getUserTextColor(t?.userId)),!t?.initial&&(t?.name||t?.email)&&(t.initial=t.name?.charAt(0).toUpperCase()||t.email?.charAt(0).toUpperCase())}catch{}})}catch{}}};o.\u0275fac=function(t){return new(t||o)(ee(Di),ee(Ft),ee(Bd),ee(Vd),ee(Be),ee(Wo),ee(et),ee(y))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var Ud=class{constructor({apiKey:o,documentId:n,organizationId:e,folderId:t,veltFolderId:r,clientDocumentId:a,clientOrganizationId:s}){this.paths={},this.apiKey=o,this.documentId=n,this.organizationId=e,this.folderId=t,this.veltFolderId=r,this.clientDocumentId=a,this.clientOrganizationId=s,a&&(this.documentId=na(a)),s&&(this.organizationId=La(s)),t&&(this.folderId=t,this.veltFolderId=Fi(t)),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=`${this.apiKey}`;this.organizationId&&(o=`${o}/${j.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${this.paths.organizationId}`),this.documentId&&(this.paths.docs=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/`,this.paths.folder=`${o}/${j.FIREBASE_PARTIAL_PATH_FOLDERS}/`,this.paths.presence=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_PRESENCE}/`,this.paths.cursor=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_CURSOR}/`,this.paths.comment=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_COMMENT}/`,this.paths.multiThread=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_MULTI_THREAD}/`,this.paths.tag=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_TAG}/`,this.paths.area=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_AREA}/`,this.paths.arrow=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_ARROW}/`,this.paths.selection=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_SELECTION}/`,this.paths.audioHuddle=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_AUDIO_HUDDLE}/`,this.paths.huddle=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_HUDDLE}/`,this.paths.recorder=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_RECORDER}/`,this.paths.flock=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_FOLLOW_ALONG}/`,this.paths.syncVideoPlayer=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_SYNC_VIDEO_PLAYER}/`,this.paths.liveState=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_LIVE_STATE}/`,this.paths.liveStateSingleEditorMode=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_LIVE_STATE}/default/singleEditorMode`,this.paths.reaction=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_REACTION}/`,this.paths.crdt=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_CRDT}/`,this.paths.views=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_VIEWS}/`,this.paths.notifications=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_NOTIFICATIONS}/`,this.paths.metadata=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_METADATA}/`,this.paths.users=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_USERS}/`,this.paths.documentIam=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_IAM}/`,this.paths.userConfig=`${o}/${j.FIREBASE_PARTIAL_PATH_USERS}`),this.paths.customerMetadata=`${o}/${j.FIREBASE_PARTIAL_PATH_CUSTOMER_METADATA}/`,this.paths.groupContacts=`${o}/${j.FIREBASE_PARTIAL_PATH_CONTACTS}/${j.FIREBASE_PARTIAL_PATH_GROUPS}/`,this.paths.globalContacts=`${o}/${j.FIREBASE_PARTIAL_PATH_CONTACTS}/${j.FIREBASE_PARTIAL_PATH_GLOBAL}/`,this.paths.logins=`${o}/${j.FIREBASE_PARTIAL_PATH_CONTACTS}/${j.FIREBASE_PARTIAL_PATH_LOGINS}/`,this.paths.userFeedback=`${o}/${j.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${j.FIREBASE_PARTIAL_PATH_FEEDBACK}/`,this.paths.userReportBugs=`${o}/${j.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${j.FIREBASE_PARTIAL_PATH_BUGS}/`,this.paths.userContactUs=`${o}/${j.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${j.FIREBASE_PARTIAL_PATH_CONTACT_US}/`,this.organizationId&&(this.paths.organizationMetadata=`${o}/${j.FIREBASE_PARTIAL_PATH_ORGANIZATION_METADATA}/`,this.paths.organizationIam=`${o}/${j.FIREBASE_PARTIAL_PATH_IAM}/`,this.paths.organizationGroups=`${o}/${j.FIREBASE_PARTIAL_PATH_ORGANIZATION_GROUPS}/`,this.paths.organizationNotifications=`${o}/${j.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/`,this.documentId&&(this.paths.organizationNotificationsWithDocumentId=`${o}/${j.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/`),this.paths.organizationNotificationsLastNotificationTimestamp=`${o}/${j.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${j.FIREBASE_PARTIAL_PATH_LAST_NOTIFICATION_TIMESTAMP}/${j.FIREBASE_PARTIAL_PATH_DOCS}/`,this.paths.organizationNotificationsUsers=`${o}/${j.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${j.FIREBASE_PARTIAL_PATH_USERS}/`),this.paths.workspaceIam=`${this.apiKey}/${j.FIREBASE_PARTIAL_PATH_IAM}/`}}catch{}}get folder(){return this.paths.folder?this.paths.folder:this.throwError("Folder path is not available.")}get userConfig(){return this.paths.userConfig?this.paths.userConfig:this.throwError("User config path is not available.")}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 crdt(){return this.paths.crdt?this.paths.crdt:this.throwError("CRDT 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 Ok=class{constructor({apiKey:o,documentId:n,organizationId:e,clientDocumentId:t,clientOrganizationId:r,folderId:a,veltFolderId:s}){this.paths={},this.apiKey=o,this.documentId=n,this.organizationId=e,this.veltFolderId=s,t&&(this.documentId=na(t)),r&&(this.organizationId=La(r)),a&&(this.folderId=a,this.veltFolderId=Fi(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}/${j.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${this.paths.organizationId}`,this.paths.organization=o,this.paths.folder=`${o}/${j.FIREBASE_PARTIAL_PATH_FOLDERS}`,this.paths.organizationUsers=`${o}/${j.FIREBASE_PARTIAL_PATH_ORGANIZATION_USERS}`,this.paths.users=`${o}/${j.FIREBASE_PARTIAL_PATH_CENTRAL_USERS}`,this.paths.notificationDocs=`${o}/${j.FIREBASE_PARTIAL_PATH_NOTIFICATION_DOCS}`,this.paths.notificationUsers=`${o}/${j.FIREBASE_PARTIAL_PATH_NOTIFICATION_USERS}`,this.paths.organizationGroups=`${o}/${j.FIREBASE_PARTIAL_PATH_GROUPS}`,this.paths.lastNotificationTimestamp=`${o}/${j.FIREBASE_PARTIAL_PATH_LAST_NOTIFICATION_TIMESTAMP}`,this.paths.userConfig=`${o}/${j.FIREBASE_PARTIAL_PATH_USERS}`,this.paths.permissionsUsers=`${o}/${j.FIREBASE_PARTIAL_PATH_PERMISSIONS_USERS}`),this.veltFolderId&&(this.paths.folderUsers=`${o}/${j.FIREBASE_PARTIAL_PATH_FOLDERS}/${this.veltFolderId}/${j.FIREBASE_PARTIAL_PATH_FOLDER_USERS}`),this.documentId&&(this.paths.document=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}`,this.paths.comment=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_COMMENT}`,this.paths.location=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_LOCATION}`,this.paths.multiThread=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_MULTI_THREAD}`,this.paths.area=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_AREA}`,this.paths.recorder=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_RECORDER}`,this.paths.reaction=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_REACTION}`,this.paths.crdt=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_CRDT}`,this.paths.notificationViews=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_NOTIFICATION_VIEWS}`,this.paths.documentViews=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_DOCUMENT_VIEWS}`,this.paths.locationViews=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_LOCATION_VIEWS}`,this.paths.documentUsers=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_DOCUMENT_USERS}`,this.paths.docNotification=`${this.paths.notificationDocs}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_DOC_NOTIFICATION}`)}}catch{}}get permissionsUsers(){return this.paths.permissionsUsers?this.paths.permissionsUsers:this.throwError("PermissionsUsers path is not available.")}get users(){return this.paths.users?this.paths.users:this.throwError("Users path is not available.")}get userConfig(){return this.paths.userConfig?this.paths.userConfig:this.throwError("UserConfig path is not available.")}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 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.")}get crdt(){return this.paths.crdt?this.paths.crdt:this.throwError("CRDT path is not available.")}throwError(o){throw{type:"DocumentPaths",message:o,metadata:{apiKey:this.apiKey,documentId:this.documentId,organizationId:this.organizationId}}}};var Ak=class{};var Dn=(()=>{let o=class o{constructor(e,t){this.authService=e,this.loggingService=t,this.db$=new ve(null);try{this.authService.getFirebaseConfig$().subscribe(r=>{r&&this.db$.next(L6(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()}getDbValue(){return this.db$.getValue()}};o.\u0275fac=function(t){return new(t||o)(ee(Ve),ee(y))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var Rs=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.analyticsService=t,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 ve(null),this.commentAnnotationById$=new ve({}),this.fieldsToRemove=[],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),r.config?.fieldsToRemove&&(this.fieldsToRemove=r.config.fieldsToRemove))})}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 Q(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling CommentAnnotationsResolverService FUNCTION: resolveCommentAnnotations","color: green;"),!this.commentAnnotationDataProviderAvailable())return{};let t,r=!1,a=!1,s=()=>{t&&(clearTimeout(t),t=void 0,a=!0)};return new Promise((c,p)=>{t=setTimeout(()=>{a||(r=!0,s(),p(new Error("Comment annotation resolution timeout")))},this.commentAnnotationDataProvider$.value?.config?.resolveTimeout||this.resolveTimeout);let u=this.getProvider();if(!u)return s(),c({});let C={},E=[...new Set(e.commentAnnotationIds||[])],D=T(I({},e),{commentAnnotationIds:E});Q(this,null,function*(){try{if(E.length>0||e.documentIds?.length||e.folderId){let z=Pc(()=>u?.get(D)||Promise.resolve(void 0),"getCommentAnnotations",this.retryGetConfig).then(W=>r?{}:(s(),W&&W.statusCode!==200?(this.loggingService.catch(W?.message??"Error in CommentAnnotationsResolverService resolveCommentAnnotations:"),{}):W?.data)).catch(W=>{throw s(),W});try{C=(yield z)||{},this.analyticsService.trackEvent(Z.Events.Resolver.COMMENT_RESOLVER_GET,{sourceMethod:"resolveCommentAnnotations",source:"sdk",commentAnnotationIds:E});let W={};Object.entries(C).forEach(([J,ue])=>{let ye=this.commentAnnotationById$.value?.[J];ye?ye&&JSON.stringify(ye)!==JSON.stringify(ue)&&(W[J]=ue):W[J]=ue}),Object.keys(W).length>0&&this.commentAnnotationById$.next(I(I({},this.commentAnnotationById$.getValue()),W)),c(W)}catch(W){r||p(W),c(C)}}else s(),c({})}catch(z){s(),p(z)}})})}catch(t){return this.loggingService.catch("Error in CommentAnnotationsResolverService resolveCommentAnnotations:",t),{}}})}saveCommentAnnotation(e){return Q(this,null,function*(){try{this.loggingService.log("%c[WB] Calling CommentAnnotationsResolverService FUNCTION: saveCommentAnnotation","color: green;");let t=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 Pc(()=>t?.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(t){return this.loggingService.warn("Error in CommentAnnotationsResolverService saveCommentAnnotation:",t),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0}}})}deleteCommentAnnotation(e,t){return Q(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 Pc(()=>r?.delete({commentAnnotationId:e.toString(),metadata:t,event:os.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()):se(void 0)}catch(e){return this.loggingService.catch("Error in CommentAnnotationsResolverService getCommentAnnotationsById$:",e),se(void 0)}}getAnnotationById(e){try{return this.commentAnnotationDataProviderAvailable()?this.commentAnnotationById$.getValue()?.[e]:void 0}catch(t){this.loggingService.catch("Error in CommentAnnotationsResolverService getAnnotationById:",t);return}}getFieldsToRemove(){try{return this.fieldsToRemove}catch(e){return this.loggingService.catch("Error in CommentAnnotationsResolverService getFieldsToRemove:",e),this.fieldsToRemove}}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(t){this.loggingService.catch("Error in CommentAnnotationsResolverService setCommentAnnotationDataProvider:",t)}}commentAnnotationDataProviderAvailable(){try{return!!this.commentAnnotationDataProvider$.getValue()}catch(e){return this.loggingService.catch("Error in CommentAnnotationsResolverService commentAnnotationDataProviderAvailable:",e),!1}}};o.\u0275fac=function(t){return new(t||o)(ee(y),ee(et))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var jd=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.analyticsService=t,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 ve(null),this.reactionAnnotationById$=new ve({}),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 Q(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling ReactionAnnotationsResolverService FUNCTION: resolveReactionAnnotations","color: green;"),!this.reactionAnnotationDataProviderAvailable())return{};let t,r=!1,a=!1,s=()=>{t&&(clearTimeout(t),t=void 0,a=!0)};return new Promise((c,p)=>{t=setTimeout(()=>{a||(r=!0,s(),p(new Error("Reaction annotation resolution timeout")))},this.reactionAnnotationDataProvider$.value?.config?.resolveTimeout||this.resolveTimeout);let u=this.getProvider();if(!u)return s(),c({});let C={},E=[...new Set(e.reactionAnnotationIds||[])],D=T(I({},e),{reactionAnnotationIds:E});Q(this,null,function*(){try{if(E.length>0||e.documentIds?.length||e.folderId){let z=Pc(()=>u?.get(D)||Promise.resolve(void 0),"getReactionAnnotations",this.retryGetConfig).then(W=>r?{}:(s(),W&&W.statusCode!==200?(this.loggingService.catch(W?.message??"Error in ReactionAnnotationsResolverService resolveReactionAnnotations:"),{}):W?.data)).catch(W=>{throw s(),W});try{C=(yield z)||{},this.analyticsService.trackEvent(Z.Events.Resolver.REACTION_RESOLVER_GET,{sourceMethod:"resolveReactionAnnotations",source:"sdk",reactionAnnotationIds:E});let W={};Object.entries(C).forEach(([J,ue])=>{let ye=this.reactionAnnotationById$.value?.[J];ye?ye&&JSON.stringify(ye)!==JSON.stringify(ue)&&(W[J]=ue):W[J]=ue}),Object.keys(W).length>0&&this.reactionAnnotationById$.next(I(I({},this.reactionAnnotationById$.getValue()),W)),c(W)}catch(W){r||p(W),c(C)}}else s(),c({})}catch(z){s(),p(z)}})})}catch(t){return this.loggingService.catch("Error in ReactionAnnotationsResolverService resolveReactionAnnotations:",t),{}}})}saveReactionAnnotation(e){return Q(this,null,function*(){try{this.loggingService.log("%c[WB] Calling ReactionAnnotationsResolverService FUNCTION: saveReactionAnnotation","color: green;");let t=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:os.REACTION_ADD,metadata:Object.values(e??{})?.[0]?.metadata},s=yield Pc(()=>t?.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(t){return this.loggingService.warn("Error in ReactionAnnotationsResolverService saveReactionAnnotation:",t),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0}}})}deleteReactionAnnotation(e,t){return Q(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 Pc(()=>r?.delete({reactionAnnotationId:e.toString(),metadata:t,event:os.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()):se(void 0)}catch(e){return this.loggingService.catch("Error in ReactionAnnotationsResolverService getReactionAnnotationsById$:",e),se(void 0)}}getAnnotationById(e){try{return this.reactionAnnotationDataProviderAvailable()?this.reactionAnnotationById$.getValue()?.[e]:void 0}catch(t){this.loggingService.catch("Error in ReactionAnnotationsResolverService getAnnotationById:",t);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(t){this.loggingService.catch("Error in ReactionAnnotationsResolverService setReactionAnnotationDataProvider:",t)}}reactionAnnotationDataProviderAvailable(){try{return!!this.reactionAnnotationDataProvider$.getValue()}catch(e){return this.loggingService.catch("Error in ReactionAnnotationsResolverService reactionAnnotationDataProviderAvailable:",e),!1}}};o.\u0275fac=function(t){return new(t||o)(ee(y),ee(et))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var at=(()=>{let o=class o{constructor(e,t,r,a,s,c,p,u,C){this.analyticsService=e,this.authService=t,this.databaseService=r,this.domService=a,this.configService=s,this.loggingService=c,this.commentResolverService=p,this.reactionResolverService=u,this.coreActionsService=C,this.documentPaths$=new ve(null),this.documentIds$=new ve([]),this.organizationConfig$=new ve(null),this.firestorePaths$=new ve(null),this.location$=new ve(null),this.excludedLocationIds$=new ve([]),this.organizationMetadata$=new ve(null),this.documentMetadata$=new ve(null),this.locationMetadata$=new ve(null),this.customerMetadata$=new ve(null),this.currentDocumentId=null,this.isCustomDocId=!1,this.locations$=new ve({}),this.preDocumentIdChangeFunctions=new Map,this.draftDocuments=[],this.clientDocumentMetadataMap={},this.uiState=new ve({}),this.lastSetDocumentIdExecutionTime=0,this.lastSetDocumentIdCallTime=0,this.setDocumentIdSubject=new tt,this.DEBOUNCE_TIME=5e3,this.MAX_QUEUE_SIZE=100,this.queueSize=0,this.isDocumentIdInDebounceQueue=!1,this.draftLocationMap={locations:[],options:void 0};try{this.loggingService.log("%c[WB] Creating CLASS: DocService","color: blue;"),this.domService.setDocService(this),this.authService.setDocService(this),this.setDocumentIdSubject.pipe(lr(this.DEBOUNCE_TIME)).subscribe({next:E=>Q(this,null,function*(){try{yield this.setDocumentIdImpl(E.documentId,E.clientOrganizationId,E.options),this.lastSetDocumentIdExecutionTime=Date.now(),this.isDocumentIdInDebounceQueue=!1,this.draftLocationMap.locations.length&&(yield this.setLocations({locations:this.draftLocationMap.locations,options:this.draftLocationMap.options,source:"internal"})),this.draftLocationMap={locations:[],options:void 0}}finally{this.queueSize--}}),error:E=>{this.loggingService.catch("Error in setDocumentId subscription:",E),this.queueSize--}}),this.databaseService.getDb().pipe(Le(E=>!!E),st(1)).subscribe(E=>{E&&(this.db=E)}),this.configService.getApiKey$().subscribe(E=>{if(this.apiKey=E,this.apiKey){if(!this.isCustomDocId){let D=XP(window.location.href);this.currentUrl=D}this.analyticsService.updateDefaultProperties({apiKey:E})}}),this.authService.getUser$().subscribe(E=>Q(this,null,function*(){E&&(this.analyticsService.updateDefaultProperties({organizationId:E?.organizationId,clientOrganizationId:E?.clientOrganizationId}),this.draftDocuments?.length?(yield this.setDocuments({documents:this.draftDocuments,options:this.draftOptions??void 0,source:"internal"}),this.draftDocuments=[],this.draftOptions=void 0,this.draftLocationMap.locations.length&&(yield this.setLocations({locations:this.draftLocationMap.locations,options:this.draftLocationMap.options,source:"internal"}).then(()=>this.draftLocationMap={locations:[],options:void 0}))):this.documentPaths$?.value&&E?.organizationId&&this.documentPaths$.value?.organizationId!==E?.organizationId&&(yield this.setDocuments({documents:this.documentIds$.value.length?this.documentIds$.value.map(D=>({id:D.clientDocumentId})):[{id:this.documentPaths$.value?.clientDocumentId}],options:void 0,source:"internal"})),setTimeout(()=>{this.documentPaths$.value||this.loggingService.catch("Error in DocService constructor:","Please set document id to continue.")},1e4),E?.organizationId&&E?.clientOrganizationId&&(this.organizationConfig$.next({organizationId:E?.organizationId,clientOrganizationId:E?.clientOrganizationId}),yield this.updateOrganizationMetadata()))})),this.documentPaths$.subscribe(E=>{let D={documentId:E?.documentId,clientDocumentId:E?.clientDocumentId,folderId:E?.folderId,allDocuments:E?.allDocuments,veltFolderId:E?.veltFolderId};E?.organizationId&&(D.organizationId=E.organizationId,D.clientOrganizationId=E.clientOrganizationId),this.analyticsService.updateDefaultProperties(D),this.domService.resetSelectedAnnotationsMap()}),this.location$.subscribe(E=>{this.analyticsService.updateDefaultProperties({clientLocation:E?.location,locationId:E?.locationId})}),this.organizationMetadata$.subscribe(E=>{this.authService.setUserOrganization(E?.[this.documentPaths$.value?.organizationId])}),this.documentPaths$.pipe(Le(E=>!!E),st(1)).subscribe(()=>{try{this.subscribeToCustomerMetadata()}catch(E){this.loggingService.catch("Error in DocService subscribeToCustomerMetadata:",E)}},E=>{this.loggingService.catch("Error in DocService subscribeToCustomerMetadata:",E)}),this.loggingService.log("%c[WB] Creating CLASS: DocService 2","color: blue;"),this.onWindowPopstate(),this.onWindowClick()}catch(E){this.loggingService.catch("Error in DocService constructor:",E)}}getOptionsFromDocumentPaths(){try{return this.documentPaths$.value?{folderId:this.documentPaths$.value?.folderId,allDocuments:this.documentPaths$.value?.allDocuments,locationId:this.documentPaths$.value?.locationId,organizationId:this.documentPaths$.value?.clientOrganizationId}:null}catch(e){return this.loggingService.catch("Error in getOptionsFromDocumentPaths:",e),null}}clearCacheOnUserCascade(){this.loggingService.log("%c[WB] Calling FUNCTION: clearCacheOnUserCascade in DocService","color: green;");try{this.organizationConfig$.next(null),this.organizationMetadata$.next(null),this.customerMetadata$.next(null),this.customerMetadataSubscription?.unsubscribe(),this.documentPaths$.value&&(this.draftOptions=this.getOptionsFromDocumentPaths(),this.draftLocationMap={locations:[this.location$.value?.location??null,...Object.values(this.locations$.value||{}).map(e=>e.location)].filter(e=>e!==null),options:{rootLocationId:this.location$.value?.location?.id}},this.currentDocumentId=null,this.documentPaths$.next(null),this.firestorePaths$.next(null)),this.unsetDocuments({source:"internal"})}catch(e){this.loggingService.catch("Error in DocService clearCacheOnUserCascade: ",e)}}setCommonDbService(e){try{this.commonDbService=e}catch(t){this.loggingService.catch("Error in setCommonDbService:",t)}}setUserPermissionService(e){try{this.userPermissionService=e}catch(t){this.loggingService.catch("Error in setUserPermissionService:",t)}}setCommentService(e){try{this.commentService=e}catch(t){this.loggingService.catch("Error in setCommentService:",t)}}onWindowPopstate(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowPopstate","color: green;");try{this.domService.onWindowPopState$().subscribe(()=>{this.loggingService.log("location",location.href);let e=XP(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=XP(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(s){return Q(this,arguments,function*({documentId:e,documentMetadata:t,options:r,source:a="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocument","color: green;"),a==="internal"&&this.analyticsService.trackEvent(Z.Events.Core.SET_DOCUMENTS_TRIGGERED,{payload:{id:e,documentMetadata:t,methodName:"setDocument",source:a}}),this.coreActionsService.triggerAction($i.INIT_UPDATE,{event:Z.Events.Core.SET_DOCUMENTS_TRIGGERED,methodName:"setDocument",source:a,payload:{documentId:e,documentMetadata:t,options:r}}),yield this.setDocumentsImpl({documents:[{id:e,metadata:t}],options:I({organizationId:t?.organizationId},r??{}),source:a})}catch(c){this.loggingService.catch("Error in DocService setDocument:",c)}})}shouldSetDocumentsAgain(e,t={}){try{this.loggingService.log("%c[WB] Calling FUNCTION: shouldSetDocumentsAgain","color: green;");let r=this.documentPaths$.value?.clientDocumentId,a=t?.rootDocumentId??e[0]?.id,s=this.documentIds$.value.map(u=>u.clientDocumentId),c=Mj(this.getOptionsFromDocumentPaths()??{})??{};return!e.every(u=>s.includes(u.id))||!wi(c,t)||r!==a}catch(r){return this.loggingService.catch("Error in DocService shouldSetDocumentsAgain:",r),!0}}getDocumentIdsFromDocuments({documents:e,setClientDocumentMetadataMap:t=!1}){try{let r=[];return e.forEach(a=>{let s=a.id,c=`${En(s)}`;t&&a?.metadata&&typeof a.metadata=="object"&&(this.clientDocumentMetadataMap[s]=a.metadata),r.push({documentId:c,clientDocumentId:s})}),r}catch(r){return this.loggingService.catch("Error in DocService getDocumentIdsFromDocuments:",r),[]}}setDocuments(a){return Q(this,arguments,function*({documents:e,options:t,source:r="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocuments","color: green;"),r==="internal"&&this.analyticsService.trackEvent(Z.Events.Core.SET_DOCUMENTS_TRIGGERED,{payload:{documents:e,options:t,methodName:"setDocuments",source:r}}),this.coreActionsService.triggerAction($i.INIT_UPDATE,{event:Z.Events.Core.SET_DOCUMENTS_TRIGGERED,methodName:"setDocuments",source:r,payload:{documents:e,options:t}}),yield this.setDocumentsImpl({documents:e,options:t??{},source:r})}catch(s){this.loggingService.catch("Error in DocService setDocuments:",s)}})}setRootDocument(r){return Q(this,arguments,function*({document:e,source:t="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setRootDocument","color: green;"),this.coreActionsService.triggerAction($i.INIT_UPDATE,{event:Z.Events.Core.SET_ROOT_DOCUMENT_TRIGGERED,methodName:"setRootDocument",source:t,payload:{document:e}});let a=this.getOptionsFromDocumentPaths()??{},s=this.documentIds$.value.map(c=>c.clientDocumentId);if(!s.includes(e.id)){let c=[...s.map(u=>({id:u})),{id:e.id}],p=this.getDocumentIdsFromDocuments({documents:c,setClientDocumentMetadataMap:!0});this.documentIds$.next(p)}yield this.setDocumentIdImpl(e.id,this.documentPaths$.value?.clientOrganizationId,a)}catch(a){this.loggingService.catch("Error in DocService setRootDocument:",a)}})}setDocumentsImpl(a){return Q(this,arguments,function*({documents:e,options:t,source:r}){try{let s=t?.organizationId??this.documentPaths$.value?.clientOrganizationId;if(!this.shouldSetDocumentsAgain(e,Mj(T(I({},t),{organizationId:s})))){r==="external"&&this.loggingService.catch("setDocuments called with previous request");return}let c=this.getDocumentIdsFromDocuments({documents:e,setClientDocumentMetadataMap:!0});if(c?.length===0){this.loggingService.warn("Minimum one document must be set in setDocuments");return}if(!this.authService.getUser()){this.draftDocuments=e,this.draftOptions=t;return}if(this.documentPaths$.value?.organizationId&&t?.organizationId&&this.documentPaths$.value?.organizationId!==t?.organizationId?this.authService.resetServicesCache():this.unsetDocuments({source:"internal",unsetDocumentPaths:!1}),this.documentIds$.next(c),e?.length){let u=e[0]?.id;t?.rootDocumentId&&e.find(C=>C.id===t?.rootDocumentId)&&(u=t?.rootDocumentId),yield this.debounceSetDocuments({documentId:u,clientOrganizationId:t?.organizationId,options:t})}return}catch(s){this.loggingService.catch("Error in DocService setDocumentsImpl:",s)}})}setDocumentId(a){return Q(this,arguments,function*({documentId:e,clientOrganizationId:t,source:r="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocumentId","color: green;"),r==="internal"&&this.analyticsService.trackEvent(Z.Events.Core.SET_DOCUMENTS_TRIGGERED,{payload:{id:e,clientOrganizationId:t,methodName:"setDocumentId",source:r}}),this.coreActionsService.triggerAction($i.INIT_UPDATE,{event:Z.Events.Core.SET_DOCUMENTS_TRIGGERED,methodName:"setDocumentId",source:r,payload:{documentId:e,clientOrganizationId:t}}),yield this.setDocumentsImpl({documents:[{id:e}],options:{organizationId:t},source:r})}catch(s){this.loggingService.catch("Error in setDocumentId:",s);return}})}debounceSetDocuments(a){return Q(this,arguments,function*({documentId:e,clientOrganizationId:t,options:r}){try{this.loggingService.log("%c[WB] Calling FUNCTION: debounceSetDocuments","color: green;");let s=Date.now(),c=s-this.lastSetDocumentIdCallTime,p=s-this.lastSetDocumentIdExecutionTime;if(this.lastSetDocumentIdCallTime=s,this.queueSize>=this.MAX_QUEUE_SIZE){this.loggingService.warn("SetDocumentId queue size exceeded limit");return}if(!this.documentPaths$.value&&!this.isDocumentIdInDebounceQueue||c>this.DEBOUNCE_TIME&&p>this.DEBOUNCE_TIME){yield this.setDocumentIdImpl(e,t,r),this.lastSetDocumentIdExecutionTime=s;return}this.documentPaths$.next(null),this.isDocumentIdInDebounceQueue=!0,this.draftLocationMap={locations:[],options:void 0},this.queueSize++,this.setDocumentIdSubject.next({documentId:e,clientOrganizationId:t,options:r??void 0});return}catch(s){this.loggingService.catch("Error in debounceSetDocuments:",s)}})}setDocumentIdImpl(e,t,r){return Q(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: setDocumentIdImpl","color: green;");try{let a=this.authService.getUser();if(!a)return;this.currentDocumentId&&this.documentPaths$.value&&(yield this.callPreDocumentIdChangeFunctions(this.documentPaths$.value));let s=this.currentDocumentId;if(this.apiKey){let c=`${En(e)}`,p=r?.folderId,u=r?.folderId?Fi(r?.folderId):void 0,C=r?.locationId,E=r?.allDocuments,D=a?.organizationId?t?bt(t):a?.organizationId:void 0;if(yield Promise.allSettled([this.commentResolverService.resolveCommentAnnotations({documentIds:this.documentIds$.value.map(L=>L.clientDocumentId),organizationId:t??a?.clientOrganizationId??""}),this.reactionResolverService.resolveReactionAnnotations({documentIds:this.documentIds$.value.map(L=>L.clientDocumentId),organizationId:t??a?.clientOrganizationId??""})]),this.currentDocumentId!==c||this.documentPaths$.value?.organizationId!==D){this.loggingService.log("setting new docid"),this.currentDocumentId=c;let L=new gk,z=new Ak;L.clientDocumentId=e,z.clientDocumentId=e,L.folderId=p,z.folderId=p,L.locationId=C,z.locationId=C,L.allDocuments=E,z.allDocuments=E,L.veltFolderId=u,z.veltFolderId=u,L.documentId=c,z.documentId=c,D&&(L.organizationId=D,L.clientOrganizationId=t??a?.clientOrganizationId,z.organizationId=D,z.clientOrganizationId=t??a?.clientOrganizationId);let W=`${this.apiKey}`,J=`apiKey/${this.apiKey}`;D&&(W=`${W}/${j.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${L.organizationId}`,J=`${J}/${j.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${L.organizationId}`),z.organization=`apiKey/${this.apiKey}/${j.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}`,z.document=`${J}/${j.FIREBASE_PARTIAL_PATH_DOCS}`,L.presence=`${W}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${j.FIREBASE_PARTIAL_PATH_PRESENCE}/`,L.cursor=`${W}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${j.FIREBASE_PARTIAL_PATH_CURSOR}/`,L.comment=`${W}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${j.FIREBASE_PARTIAL_PATH_COMMENT}/`,z.comment=`${J}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${j.FIREBASE_PARTIAL_PATH_COMMENT}`,L.multiThread=`${W}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${j.FIREBASE_PARTIAL_PATH_MULTI_THREAD}/`,z.multiThread=`${J}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${j.FIREBASE_PARTIAL_PATH_MULTI_THREAD}`,L.tag=`${W}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${j.FIREBASE_PARTIAL_PATH_TAG}/`,L.area=`${W}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${j.FIREBASE_PARTIAL_PATH_AREA}/`,z.area=`${J}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${j.FIREBASE_PARTIAL_PATH_AREA}`,L.arrow=`${W}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${j.FIREBASE_PARTIAL_PATH_ARROW}/`,L.selection=`${W}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${j.FIREBASE_PARTIAL_PATH_SELECTION}/`,L.audioHuddle=`${W}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${j.FIREBASE_PARTIAL_PATH_AUDIO_HUDDLE}/`,L.huddle=`${W}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${j.FIREBASE_PARTIAL_PATH_HUDDLE}/`,L.recorder=`${W}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${j.FIREBASE_PARTIAL_PATH_RECORDER}/`,z.recorder=`${J}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${j.FIREBASE_PARTIAL_PATH_RECORDER}`,L.flock=`${W}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${j.FIREBASE_PARTIAL_PATH_FOLLOW_ALONG}/`,L.syncVideoPlayer=`${W}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${j.FIREBASE_PARTIAL_PATH_SYNC_VIDEO_PLAYER}/`,L.liveState=`${W}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${j.FIREBASE_PARTIAL_PATH_LIVE_STATE}/`,L.liveStateSingleEditorMode=`${W}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${j.FIREBASE_PARTIAL_PATH_LIVE_STATE}/default/singleEditorMode`,L.reaction=`${W}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${j.FIREBASE_PARTIAL_PATH_REACTION}/`,z.reaction=`${J}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${j.FIREBASE_PARTIAL_PATH_REACTION}`,L.crdt=`${W}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${j.FIREBASE_PARTIAL_PATH_CRDT}/`,z.crdt=`${J}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${j.FIREBASE_PARTIAL_PATH_CRDT}`,L.customerMetadata=`${this.apiKey}/${j.FIREBASE_PARTIAL_PATH_CUSTOMER_METADATA}/`,L.views=`${W}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${j.FIREBASE_PARTIAL_PATH_VIEWS}/`,z.notificationViews=`${J}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${j.FIREBASE_PARTIAL_PATH_NOTIFICATION_VIEWS}`,z.documentViews=`${J}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${j.FIREBASE_PARTIAL_PATH_DOCUMENT_VIEWS}`,z.locationViews=`${J}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${j.FIREBASE_PARTIAL_PATH_LOCATION_VIEWS}`,L.notifications=`${W}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${j.FIREBASE_PARTIAL_PATH_NOTIFICATIONS}/`,L.metadata=`${W}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${j.FIREBASE_PARTIAL_PATH_METADATA}/`,L.users=`${W}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${j.FIREBASE_PARTIAL_PATH_USERS}/`,L.documentIam=`${W}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${j.FIREBASE_PARTIAL_PATH_IAM}/`,L.workspaceIam=`${this.apiKey}/${j.FIREBASE_PARTIAL_PATH_IAM}/`,L.groupContacts=`${W}/${j.FIREBASE_PARTIAL_PATH_CONTACTS}/${j.FIREBASE_PARTIAL_PATH_GROUPS}/`,L.globalContacts=`${W}/${j.FIREBASE_PARTIAL_PATH_CONTACTS}/${j.FIREBASE_PARTIAL_PATH_GLOBAL}/`,L.logins=`${W}/${j.FIREBASE_PARTIAL_PATH_CONTACTS}/${j.FIREBASE_PARTIAL_PATH_LOGINS}/`,L.userFeedback=`${W}/${j.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${j.FIREBASE_PARTIAL_PATH_FEEDBACK}/`,L.userReportBugs=`${W}/${j.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${j.FIREBASE_PARTIAL_PATH_BUGS}/`,L.userContactUs=`${W}/${j.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${j.FIREBASE_PARTIAL_PATH_CONTACT_US}/`,D&&(L.organizationMetadata=`${W}/${j.FIREBASE_PARTIAL_PATH_ORGANIZATION_METADATA}/`,L.organizationIam=`${W}/${j.FIREBASE_PARTIAL_PATH_IAM}/`,L.organizationGroups=`${W}/${j.FIREBASE_PARTIAL_PATH_ORGANIZATION_GROUPS}/`,L.organizationNotifications=`${W}/${j.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/`,c&&(L.organizationNotificationsWithDocumentId=`${W}/${j.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${c}/`),L.organizationNotificationsLastNotificationTimestamp=`${W}/${j.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${j.FIREBASE_PARTIAL_PATH_LAST_NOTIFICATION_TIMESTAMP}/${j.FIREBASE_PARTIAL_PATH_DOCS}/`,L.organizationNotificationsUsers=`${W}/${j.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${j.FIREBASE_PARTIAL_PATH_USERS}/`),z.organizationUsers=`${J}/${j.FIREBASE_PARTIAL_PATH_ORGANIZATION_USERS}`,z.users=`${J}/${j.FIREBASE_PARTIAL_PATH_CENTRAL_USERS}`,z.documentUsers=`${J}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${j.FIREBASE_PARTIAL_PATH_DOCUMENT_USERS}`,z.notificationDocs=`${J}/${j.FIREBASE_PARTIAL_PATH_NOTIFICATION_DOCS}`,z.notificationUsers=`${J}/${j.FIREBASE_PARTIAL_PATH_NOTIFICATION_USERS}`,this.documentPaths$.next(L),this.firestorePaths$.next(z),L?.clientOrganizationId&&L?.organizationId&&!(L?.clientOrganizationId===this.organizationConfig$?.value?.clientOrganizationId&&L?.organizationId===this.organizationConfig$?.value?.organizationId)&&this.organizationConfig$.next({organizationId:L?.organizationId,clientOrganizationId:L?.clientOrganizationId}),yield this.userPermissionService?.getUserPermissions(),yield Promise.allSettled([this.updateFolderMetadata(),this.updateDocumentMetadata(),this.fetchLocationMetadata(),this.updateOrganizationMetadata()]),s&&this.location$.value&&this.removeLocation({}),this.coreActionsService.triggerAction($i.INIT_UPDATE,{event:Z.Events.Doc.SET_DOCUMENTS_SUCCESS,payload:{documentId:c,clientDocumentId:e}}),this.analyticsService.trackEvent(Z.Events.Doc.SET_DOCUMENTS_SUCCESS,{documentId:c,clientDocumentId:e},!0,this.getUserIdForAnalytics())}}else this.loggingService.catch("Error in setDocumentIdImpl: API key is not provided.")}catch(a){this.loggingService.catch("Error in setDocumentIdImpl: ",a)}})}unsetDocumentId({source:e,unsetDocumentPaths:t}){this.loggingService.log("%c[WB] Calling FUNCTION: unsetDocumentId","color: green;");try{e==="internal"&&this.analyticsService.trackEvent(Z.Events.Core.UNSET_DOCUMENTS_TRIGGERED,{payload:{methodName:"unsetDocumentId",source:e}}),this.coreActionsService.triggerAction($i.INIT_UPDATE,{event:Z.Events.Doc.UNSET_DOCUMENTS_TRIGGERED,methodName:"unsetDocumentId",source:e}),this.unsetDocumentImpl({source:e,unsetDocumentPaths:t})}catch(r){this.loggingService.catch("Error in unsetDocumentId: ",r)}}unsetDocumentImpl({source:e,unsetDocumentPaths:t}){this.loggingService.log("%c[WB] Calling FUNCTION: unsetDocumentImpl","color: green;");try{this.currentDocumentId&&this.documentPaths$.value&&this.callPreDocumentIdChangeFunctions(this.documentPaths$.value),t&&(this.documentPaths$.next(null),this.firestorePaths$.next(null)),this.currentDocumentId=null,this.location$.next(null),this.excludedLocationIds$.next([]),this.documentMetadata$.next(null),this.locationMetadata$.next(null),this.clientDocumentMetadata=void 0,this.clientDocumentMetadataMap={},this.locations$.next({}),this.documentIds$.next([]),this.coreActionsService.triggerAction($i.INIT_UPDATE,{event:Z.Events.Doc.UNSET_DOCUMENTS_SUCCESS,source:e}),this.analyticsService.trackEvent(Z.Events.Doc.UNSET_DOCUMENTS_SUCCESS,{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())}catch(r){this.loggingService.catch("Error in unsetDocumentImpl: ",r)}}unsetDocuments({source:e,unsetDocumentPaths:t=!0}){this.loggingService.log("%c[WB] Calling FUNCTION: unsetDocuments","color: green;");try{e==="internal"&&this.analyticsService.trackEvent(Z.Events.Core.UNSET_DOCUMENTS_TRIGGERED,{payload:{methodName:"unsetDocuments",source:e}}),this.coreActionsService.triggerAction($i.INIT_UPDATE,{event:Z.Events.Doc.UNSET_DOCUMENTS_TRIGGERED,source:e,methodName:"unsetDocuments"}),this.unsetDocumentImpl({source:e,unsetDocumentPaths:t})}catch(r){this.loggingService.catch("Error in unsetDocuments: ",r)}}addPreDocumentIdChangeFunction(e,t){try{this.loggingService.log("%c[WB] Calling FUNCTION: addPreDocumentIdChangeFunction","color: green;"),this.preDocumentIdChangeFunctions.set(e,t)}catch(r){this.loggingService.catch("Error in addPreDocumentIdChangeFunction: ",r)}}callPreDocumentIdChangeFunctions(e){return Q(this,null,function*(){try{this.loggingService.log("%c[WB] Calling FUNCTION: callPreDocumentIdChangeFunctions","color: green;");for(let[t,r]of this.preDocumentIdChangeFunctions)try{yield r(e)}catch(a){this.loggingService.catch("Error in callPreDocumentIdChangeFunctions: ",a)}}catch(t){this.loggingService.catch("Error in callPreDocumentIdChangeFunctions: ",t)}})}fetchOrganizationMetadata(){return Q(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: fetchOrganizationMetadata","color: green;");try{if(this.db&&this.organizationConfig$.value?.organizationId){let e=this.organizationConfig$.value?.organizationId;yield this.commonDbService?.getData({feature:"organizationMetadata",properties:{apiKey:this.apiKey??"",organizationId:e,field:"metadata"}}).then(t=>{t&&!t?.errorCode&&this.organizationMetadata$.next(T(I({},this.organizationMetadata$.value),{[e]:t}))}).catch(t=>{this.loggingService.catch("Error in fetchOrganizationMetadata: ",t)})}}catch(e){this.loggingService.catch("Error in fetchOrganizationMetadata: ",e)}})}fetchDocumentMetadata(e){return Q(this,null,function*(){try{if(this.db&&this.authService.getUser()){let t=this.documentPaths$.value,r=this.documentMetadata$.value;if(e=e.filter(a=>!r?.[a.documentId]),e?.some(a=>!a?.documentId||!a?.clientDocumentId)||!t)return;if(this.commonDbService?.shouldUseFirestore()){let a=t?.folderId,s=t?.allDocuments,c=[],p={organizationId:t?.clientOrganizationId,folderId:a,allDocuments:s};if(a&&s)c.push(this.fetchDocuments(p));else{let C=[];for(let D=0;D<e.length;D+=20)C.push(e.slice(D,D+20));C.forEach(D=>{let L=JSON.parse(JSON.stringify(p));L.documentIds=D.map(z=>z.clientDocumentId),c.push(this.fetchDocuments(L))})}let u={};c.length>0&&(yield Promise.all(c).then(C=>{C?.forEach(E=>{E?.forEach(D=>{D?.metadata?.documentId&&(u[D.metadata.documentId]=D.metadata)})}),this.documentMetadata$.next(I(I({},this.documentMetadata$.value),u))}).catch(C=>{this.loggingService.catch("Error in fetchDocumentMetadata: ",C)}))}else r?.[t?.documentId??e?.[0]?.documentId]||this.commonDbService?.queryData({feature:"allDocuments",properties:{apiKey:this.apiKey??"",organizationId:t?.organizationId,documentId:t?.documentId??e?.[0]?.documentId,skipObjectValues:!0}}).then(a=>{a?.documentId&&this.documentMetadata$.next({[a.documentId]:a})}).catch(a=>{this.loggingService.catch("Error in fetchDocumentMetadata: ",a)})}}catch(t){this.loggingService.catch("Error in fetchDocumentMetadata: ",t)}})}fetchLocationMetadata(){return Q(this,null,function*(){try{if(this.db&&this.authService.getUser()){let e=this.documentPaths$.value,t=this.documentIds$.value,r=e?.folderId,a=e?.allDocuments,s=[],c={organizationId:e?.clientOrganizationId,folderId:r,allDocuments:a};if(r&&a)s.push(this.fetchLocations(c));else{let u=[];for(let E=0;E<t.length;E+=20)u.push(t.slice(E,E+20));u.forEach(E=>{let D=JSON.parse(JSON.stringify(c));D.documentIds=E.map(L=>L.clientDocumentId),s.push(this.fetchLocations(D))})}let p=this.locationMetadata$.value??{};s.length>0&&Promise.all(s).then(u=>{u?.forEach(C=>{C?.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(u=>{this.loggingService.catch("Error in fetchLocationMetadata: ",u)})}}catch(e){this.loggingService.catch("Error in fetchLocationMetadata: ",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(kn(t=>se(null))).subscribe(t=>{this.customerMetadata$.next(t?.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()))}getDocumentIds(){return this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentIds","color: green;"),this.documentIds$.value?.slice()}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`${En(e)}`}catch(t){return this.loggingService.catch("Error in generateDocumentId: ",t),""}}generateOrganizationId(e){try{return`${bt(e)}`}catch(t){return this.loggingService.catch("Error in generateOrganizationId: ",t),""}}getFirestorePaths(){return this.loggingService.log("%c[WB] Calling FUNCTION: getFirestorePaths","color: green;"),this.firestorePaths$.value}setLocation(r){return Q(this,arguments,function*({location:e,source:t="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setLocation","color: green;"),t==="internal"&&this.analyticsService.trackEvent(Z.Events.Core.SET_LOCATIONS_TRIGGERED,{payload:{locations:[e],options:void 0,methodName:"setLocation",source:t}}),this.coreActionsService.triggerAction($i.INIT_UPDATE,{event:Z.Events.Core.SET_LOCATIONS_TRIGGERED,source:t,methodName:"setLocation",payload:{locations:[e],options:void 0}}),this.setLocationsImpl({locations:[e]})}catch(a){this.loggingService.catch("Error in setLocation: ",a)}})}setLocations(a){return Q(this,arguments,function*({locations:e,options:t,source:r="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setLocations","color: green;"),r==="internal"&&this.analyticsService.trackEvent(Z.Events.Core.SET_LOCATIONS_TRIGGERED,{payload:{locations:e,options:t,methodName:"setLocations",source:r}}),this.coreActionsService.triggerAction($i.INIT_UPDATE,{event:Z.Events.Core.SET_LOCATIONS_TRIGGERED,methodName:"setLocations",source:r,payload:{locations:e,options:t}}),this.setLocationsImpl({locations:e,options:t})}catch(s){this.loggingService.catch("Error in setLocations: ",s)}})}getValidLocations(e){try{let t=[];return e&&Array.isArray(e)&&e.forEach(r=>{if(r&&typeof r=="object"){let a=!0;r?.version&&(!r?.version?.id||!r?.version?.name)&&(this.loggingService.catch(`Error in setting location for locationId: ${r?.id}, If you're setting version then add id and name fields to version object.`),a=!1),a&&t.push(r)}}),t}catch(t){this.loggingService.catch("Error in getValidLocations: ",t)}return e}setRootLocation(r){return Q(this,arguments,function*({location:e,source:t="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setRootLocation","color: green;"),t==="internal"&&this.analyticsService.trackEvent(Z.Events.Core.SET_ROOT_LOCATION_TRIGGERED,{payload:{location:e,methodName:"setRootLocation",source:t}}),this.coreActionsService.triggerAction($i.INIT_UPDATE,{event:Z.Events.Core.SET_ROOT_LOCATION_TRIGGERED,methodName:"setRootLocation",source:t,payload:{location:e}});let a=Object.values(this.locations$.value).map(s=>s.location).filter(s=>String(s.id)!==String(e.id));this.setLocationsImpl({locations:[e,...a],options:{rootLocationId:e.id}})}catch(a){this.loggingService.catch("Error in DocService setRootLocation:",a)}})}setLocationsImpl({locations:e,options:t}){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: setLocationsImpl","color: green;"),e.length===0)return;if(!this.authService.getUser()){!t?.appendLocation&&e.length>0&&(this.draftLocationMap.options=T(I(I({},this.draftLocationMap.options??{}),t??{}),{rootLocationId:e[0].id})),this.draftLocationMap.locations=[...this.draftLocationMap.locations,...e],this.draftLocationMap.options=I(I({},this.draftLocationMap.options),t);return}let a=this.getValidLocations(e),s=[],c=[];this.location$.value?.location.id&&c.push(this.location$.value?.location.id),c=[...c,...Object.values(this.locations$.value).map(C=>C.location.id)].filter(C=>C!==void 0);let p;if(t?.rootLocationId&&t?.rootLocationId!==this.location$.value?.location.id&&(p=a.find(C=>C.id===t?.rootLocationId),!p)){this.loggingService.catch(`Error in setting locations, rootLocationId: ${t?.rootLocationId} not found in locations.`);return}if(t?.appendLocation){if(p){let C=Yo(p),E=En(JSON.stringify(C));C.id&&s.push({locationId:E,location:C}),this.location$.next({locationId:E,location:C})}}else{p||(p=a[0]);let C=Yo(p),E=En(JSON.stringify(C));C.id&&s.push({locationId:E,location:C}),this.location$.next({locationId:E,location:C})}let u=[];return a.slice(t?.appendLocation?0:1).forEach(C=>{if(C.id!==this.location$.value?.location.id){let E=I({},C),D=this.locations$.value;C?.id&&Object.keys(D).forEach(J=>{let ue=D[J];ue.location?.id===C.id&&(E=I(I({},ue.location),C),delete D?.[J])});let L=this.genarateLocationId(E),z={locationId:L,location:E};E.id&&s.push({locationId:L,location:E}),u.push(z);let W=T(I({},D),{[L]:z});this.locations$.next(W)}}),this.updateDocumentLocationMetadata(s),this.coreActionsService.triggerAction($i.INIT_UPDATE,{event:Z.Events.Doc.SET_LOCATIONS_SUCCESS,methodName:"setLocations",payload:{locations:a,options:t}}),this.analyticsService.trackEvent(Z.Events.Doc.SET_LOCATIONS_SUCCESS,{locations:a,options:t},!0,this.getUserIdForAnalytics()),u}catch(r){this.loggingService.catch("Error in setLocationImpl: ",r);return}}addLocation({location:e,source:t="internal"}){try{return this.loggingService.log("%c[WB] Calling FUNCTION: addLocation","color: green;"),t==="internal"&&this.analyticsService.trackEvent(Z.Events.Core.SET_LOCATIONS_TRIGGERED,{payload:{locations:[e],options:{appendLocation:!0},methodName:"addLocation",source:t}}),this.coreActionsService.triggerAction($i.INIT_UPDATE,{event:Z.Events.Core.SET_LOCATIONS_TRIGGERED,methodName:"addLocation",source:t,payload:{locations:[e],options:{appendLocation:!0}}}),this.setLocationsImpl({locations:[e],options:{appendLocation:!0}})}catch(r){this.loggingService.catch("Error in DocService addLocation:",r);return}}removeLocation({location:e,source:t="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: removeLocation","color: green;"),t==="internal"&&this.analyticsService.trackEvent(Z.Events.Core.REMOVE_LOCATIONS_TRIGGERED,{payload:{locations:[e],methodName:"removeLocation",source:t}}),this.coreActionsService.triggerAction($i.INIT_UPDATE,{event:Z.Events.Core.REMOVE_LOCATIONS_TRIGGERED,source:t,methodName:"removeLocation",payload:{locations:[e]}}),e&&this.removeLocationsImpl([e],t)}catch(r){this.loggingService.catch("Error in removeLocation: ",r)}}removeLocations({locations:e,source:t="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: removeLocations","color: green;"),t==="internal"&&this.analyticsService.trackEvent(Z.Events.Core.REMOVE_LOCATIONS_TRIGGERED,{payload:{locations:e,methodName:"removeLocations",source:t}}),this.coreActionsService.triggerAction($i.INIT_UPDATE,{event:Z.Events.Core.REMOVE_LOCATIONS_TRIGGERED,methodName:"removeLocations",source:t,payload:{locations:e}}),this.removeLocationsImpl(e,t)}catch(r){this.loggingService.catch("Error in removeLocations: ",r)}}removeLocationsImpl(e,t="internal"){try{this.loggingService.log("%c[WB] Calling FUNCTION: removeLocations","color: green;"),t==="internal"&&this.analyticsService.trackEvent(Z.Events.Core.REMOVE_LOCATIONS_TRIGGERED,{payload:{locations:e},methodName:"removeLocations",message:"System removed locations",source:t},!0,this.getUserIdForAnalytics()),e?e.forEach(r=>{let a=this.genarateLocationId(r);this.getLocation()?.locationId===a&&(this.location$.next(null),t!=="internal"&&(this.draftLocationMap.locations=this.draftLocationMap.locations.filter(s=>s.id!==r.id))),this.removeCustomLocation(r)}):(this.location$.next(null),this.locations$.next({}),t!=="internal"&&(this.draftLocationMap.options=void 0,this.draftLocationMap.locations=[])),this.analyticsService.trackEvent(Z.Events.Doc.REMOVE_LOCATIONS_SUCCESS,{payload:{locations:e},source:t},!0,this.getUserIdForAnalytics())}catch(r){this.loggingService.catch("Error in removeLocation: ",r)}}unsetLocationIds(e,t="internal"){try{this.loggingService.log("%c[WB] Calling FUNCTION: unsetLocationIds","color: green;"),this.coreActionsService.triggerAction($i.INIT_UPDATE,{event:Z.Events.Core.UNSET_LOCATIONS_TRIGGERED,methodName:"unsetLocationIds",source:t,payload:{locationIds:e}}),t==="internal"&&this.analyticsService.trackEvent(Z.Events.Core.UNSET_LOCATIONS_TRIGGERED,{payload:{locationIds:e},methodName:"unsetLocationIds",message:"System unset location ids",source:t},!0,this.getUserIdForAnalytics()),e?.length?e.forEach(r=>{this.getLocation()?.location.id===r&&(this.location$.next(null),t!=="internal"&&(this.draftLocationMap.locations=this.draftLocationMap.locations.filter(a=>a.id!==r))),this.removeCustomLocationId(r)}):(this.location$.next(null),this.locations$.next({}),t!=="internal"&&(this.draftLocationMap.options=void 0,this.draftLocationMap.locations=[])),this.coreActionsService.triggerAction($i.INIT_UPDATE,{event:Z.Events.Doc.REMOVE_LOCATIONS_SUCCESS,methodName:"removeLocationsSuccess",source:t,payload:{locationIds:e}}),this.analyticsService.trackEvent(Z.Events.Doc.REMOVE_LOCATIONS_SUCCESS,{payload:{locationIds:e},source:t},!0,this.getUserIdForAnalytics())}catch(r){this.loggingService.catch("Error in unsetLocationIds: ",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(t){this.loggingService.catch("Error in excludeLocationIds: ",t)}}getExcludedLocationIds$(){try{return this.excludedLocationIds$.asObservable()}catch(e){return this.loggingService.catch("Error in getExcludedLocationIds$: ",e),se([])}}updateOrganizationMetadata(){return Q(this,null,function*(){try{let e=this.organizationConfig$.value?.organizationId,t=this.documentPaths$.value;if(this.db&&e&&t?.documentId){if(this.organizationMetadata$.value?.[e])return;let a=new Ek;a.apiKey=this.configService?.getApiKey()??"",a.organizationId=e,a.clientOrganizationId=this.organizationConfig$.value?.clientOrganizationId,this.userPermissionService?.hasEditAccess({organizationId:e})&&(yield this.commonDbService?.updateData({feature:"organizationMetadata",data:JSON.parse(JSON.stringify(a)),properties:{organizationId:e,documentId:t?.documentId??""}})),yield this.fetchOrganizationMetadata()}}catch(e){this.loggingService.catch("Error in updateOrganizationMetadata: ",e)}})}updateFolderMetadata(){return Q(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: updateFolderMetadata","color: green;"),this.db&&this.authService.getUser()&&this.documentPaths$.value?.folderId){let e=this.documentPaths$.value;if(!e?.veltFolderId||!e?.organizationId)return;if(!(yield this.commonDbService?.getData({feature:"folderMetadata",properties:{organizationId:e?.organizationId??"",folderId:e?.veltFolderId??""}}))?.metadata){let r={folderId:this.documentPaths$.value?.folderId,veltFolderId:this.documentPaths$.value?.veltFolderId,apiKey:this.configService?.getApiKey()??"",organizationId:e?.organizationId,clientOrganizationId:e?.clientOrganizationId,createdAt:Date.now(),lastUpdated:Date.now(),parentFolderId:"root",veltParentFolderId:"root"};this.userPermissionService?.hasEditAccess({folderId:this.documentPaths$.value?.veltFolderId??""})&&this.commonDbService?.updateData({feature:"folderMetadata",data:JSON.parse(JSON.stringify({metadata:r})),properties:{organizationId:e?.organizationId??"",folderId:this.documentPaths$.value?.veltFolderId??""}})}}}catch(e){this.loggingService.catch("Error in updateFolderMetadata: ",e)}})}updateDocumentMetadata(){return Q(this,null,function*(){try{if(this.db&&this.authService.getUser()){let e=this.documentPaths$.value;if(e){let t=this.getDocumentIds();t.find(a=>a.documentId===e.documentId)||t.push({documentId:e.documentId??"",clientDocumentId:e.clientDocumentId??""});let r=t.map(a=>Q(this,null,function*(){let s=new pk;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=Oi();let c=e?.folderId,p=e?.veltFolderId;s?.pageInfo?.deviceInfo&&delete s?.pageInfo?.deviceInfo;let u=!0,C=this.documentMetadata$.value?.[a.documentId];if(c&&p){let E=yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:a?.documentId??"",organizationId:e?.organizationId??"",field:"metadata"}});E?.clientDocumentId&&!E?.errorCode?E?.folderId&&(E?.folderId!==c||E?.veltFolderId!==p)?(this.loggingService.catch(`Folder id mismatch for document ${a?.clientDocumentId??""}`),u=!1):E?.folderId===c?(c&&(s.folderId=c),p&&(s.veltFolderId=p)):(this.loggingService.catch(`Document ${a?.clientDocumentId??""} is not in the folder ${c??""}`),u=!1):(c&&(s.folderId=c),p&&(s.veltFolderId=p))}if(C){let E={};Object.entries(s).forEach(([D,L])=>{E[D]=L}),wi(E,C)&&(u=!1)}u&&this.userPermissionService?.hasEditAccess({documentId:a?.documentId??"",folderId:e?.allDocuments&&e?.veltFolderId?e?.veltFolderId:void 0})&&(yield this.commonDbService?.updateData({feature:"documentMetadata",data:JSON.parse(JSON.stringify(s)),properties:{organizationId:e?.organizationId??"",documentId:a?.documentId??""}}))}));yield Promise.allSettled(r),yield this.fetchDocumentMetadata(t)}}}catch(e){this.loggingService.catch("Error in updateDocumentMetadata: ",e)}})}updateDocumentLocationMetadata(e){return Q(this,null,function*(){try{if(this.db&&this.authService.getUser()){let t=this.documentPaths$.value;if(t){let r=this.getDocumentIds();r.find(a=>a.documentId===t.documentId)||r.push({documentId:t.documentId??"",clientDocumentId:t.clientDocumentId??""});for(let a of r){let s=yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:a?.documentId??"",organizationId:t?.organizationId??"",field:"metadata"}});s?.errorCode&&(s={});let c=[];for(let p of e){let u=new vk;u.locationId=p?.locationId,u.veltLocationId=wj(p?.location?.id??""),u.location=p?.location,u.pageInfo=Oi(),u?.pageInfo?.deviceInfo&&delete u?.pageInfo?.deviceInfo;let C=T(I({},s),{[j.FIREBASE_PARTIAL_PATH_LOCATIONS]:T(I({},s[j.FIREBASE_PARTIAL_PATH_LOCATIONS]??{}),{[p?.locationId]:u})});this.commonDbService?.shouldUseFirestore()||this.userPermissionService?.hasEditAccess({documentId:a?.documentId??"",folderId:t?.allDocuments&&t?.veltFolderId?t?.veltFolderId:void 0})&&c.push(this.commonDbService?.updateData({feature:"documentMetadata",data:JSON.parse(JSON.stringify(C)),properties:{documentId:a?.documentId??"",organizationId:t?.organizationId??""}}));let E=this.locationMetadata$.value;if(E||(E={}),p?.location?.id){let D=E?.[a.documentId],L=D?.[p?.location?.id??""];E&&(D||(E[a.documentId]={}),L||(E[a.documentId][p?.location?.id??""]={}),E[a.documentId][p?.location?.id??""]=T(I({},L),{location:p?.location})),Object.keys(E||{}).length>0&&this.locationMetadata$.next(E)}}yield Promise.allSettled(c)}}}}catch(t){this.loggingService.catch("Error in updateDocumentLocationMetadata: ",t)}})}genarateLocationId(e){try{return e&&typeof e=="object"?En(JSON.stringify(Yo(e))):0}catch(t){return this.loggingService.catch("Error in genarateLocationId: ",t),0}}removeCustomLocation(e,t="internal"){try{let r=this.genarateLocationId(e),a=this.locations$.value;a[r]&&(delete a[r],this.locations$.next(I({},a)),t!=="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)}}removeCustomLocationId(e,t="internal"){try{this.loggingService.log("%c[WB] Calling FUNCTION: removeCustomLocationId","color: green;");let r=this.locations$.value;Object.entries(r).forEach(([a,s])=>{s.location.id===e&&(delete r[a],this.locations$.next(I({},r)),t!=="internal"&&this.isDocumentIdInDebounceQueue&&(this.draftLocationMap.locations=this.draftLocationMap.locations.filter(c=>c.id!==e)))})}catch(r){this.loggingService.catch("Error in DocService removeCustomLocationId:",r)}}getLocationByClientLocationId(e){try{let t=this.getLocation()?.location;if(t?.id===e)return t;{let r=this.getLocations();Object.keys(r).forEach(a=>{let s=r[a];s.location?.id===e&&(t=s.location)})}return t}catch(t){this.loggingService.catch("Error in DocService getLocationByClientLocationId:",t);return}}removeLocationIfNotInDom(){try{let e=this.locations$.value,t=document.querySelectorAll(`[${j.ATTRIBUTES.VELT_LOCATION}]`),r=[];t.forEach(a=>{let s=a.getAttribute(j.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),se({})}}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 t=null;if(e?.getAttribute(j.ATTRIBUTES.VELT_LOCATION)?t=e:t=e.closest(`[${j.ATTRIBUTES.VELT_LOCATION}]`),t){let r=t?.getAttribute(j.ATTRIBUTES.VELT_LOCATION);if(r){let a=JSON.parse(r);return{locationId:this.genarateLocationId(a),location:a}}}return null}catch(t){return this.loggingService.catch("Error in DocService getLocationFromElement:",t),null}}getElementMapWithLocation(){try{this.loggingService.log("%c[WB] Calling FUNCTION: getElementMapWithLocation","color: green;");let e={};return document.querySelectorAll(`[${j.ATTRIBUTES.VELT_LOCATION}], [${j.ATTRIBUTES.VELT_LOCATION_ID}]`).forEach(r=>{if(r.getAttribute(j.ATTRIBUTES.VELT_LOCATION)){let a=this.getLocationFromElement(r);a?.locationId&&(e[a.locationId]={element:r,location:a})}else if(r.getAttribute(j.ATTRIBUTES.VELT_LOCATION_ID)){let a=r.getAttribute(j.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 t;if(t=e?.closest(`[${j.ATTRIBUTES.VELT_LOCATION}], [${j.ATTRIBUTES.VELT_LOCATION_ID}]`),t){if(t?.getAttribute(j.ATTRIBUTES.VELT_LOCATION)){let r=t?.getAttribute(j.ATTRIBUTES.VELT_LOCATION);if(r)return JSON.parse(r)}else if(t?.getAttribute(j.ATTRIBUTES.VELT_LOCATION_ID)){let r=t?.getAttribute(j.ATTRIBUTES.VELT_LOCATION_ID);if(r)return{id:r}}}return null}catch(t){return this.loggingService.catch("Error in DocService getAdditionLocationFromElement:",t),null}}getAdditionalDocumentIdFromElement(e){try{return e?.closest(`[${j.ATTRIBUTES.VELT_DOCUMENT_ID}]`)?.getAttribute(j.ATTRIBUTES.VELT_DOCUMENT_ID)||null}catch(t){return this.loggingService.catch("Error in DocService getAdditionalDocumentIdFromElement:",t),null}}getDocumentMetadata(e){try{return e?this.documentMetadata$.value?.[e]||null:this.documentMetadata$.value?.[this.documentPaths$.value?.documentId??""]||null}catch(t){return this.loggingService.catch("Error in DocService getDocumentMetadata:",t),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||{},t={},r=this.documentPaths$.value?.veltFolderId,a=this.documentPaths$.value?.allDocuments;if(r&&a)Object.values(e).forEach(s=>{s?.documentId&&s?.veltFolderId===r&&(t[s.documentId]=s)});else{let s=this.documentIds$.value;if(s?.length)s.forEach(c=>{let p=e?.[c.documentId];p&&(t[c.documentId]=p)});else if(this.documentPaths$.value?.documentId){let c=e?.[this.documentPaths$.value?.documentId];c&&(t[this.documentPaths$.value?.documentId]=c)}}return Object.values(t)}catch(e){return this.loggingService.catch("Error in DocService getDocumentMetadataOfAvailableDocuments:",e),[]}}getDocumentMetadata$(e){return this.documentMetadata$.asObservable().pipe(ce(t=>t?.[e??this.documentPaths$.value?.documentId??""]||null))}getOrganizationMetadata(e){return this.organizationMetadata$.value?.[e]||null}getOrganizationMetadata$(e){return this.organizationMetadata$.asObservable().pipe(ce(t=>t?.[e]||null))}getCustomerMetadata(){return this.customerMetadata$.value}getCustomerMetadata$(){return this.customerMetadata$.asObservable()}getOrganizationConfig$(){return this.organizationConfig$.asObservable().pipe(Et(mn))}getOrganizationConfig(){return this.organizationConfig$.value}getMetadataFromType(e,t){try{switch(e){case"area":return;case"comment":return t?.multiThreadAnnotationId?this.commentService?.getMultiThreadAnnotationById(t.multiThreadAnnotationId)?.metadata:void 0;case"reaction":case"recorder":return t?.commentAnnotationId?this.commentService?.getAnnotationById(t.commentAnnotationId)?.metadata:void 0;default:return}}catch(r){this.loggingService.catch("Error in DocService getMetadataFromType:",r);return}}getDefaultMetadata({clientDocumentId:e,documentId:t}){try{let r=this.documentPaths$.value;if(!r)return;let a=e||r.clientDocumentId,s=t||r.documentId,c=this.getDocumentMetadata(s);if(!c)return;let p=c?.folderId,u=c?.veltFolderId;return I(I({apiKey:this.configService.getApiKey()??void 0,clientDocumentId:a,clientOrganizationId:r.clientOrganizationId,documentId:s,organizationId:r.organizationId},p?{folderId:p}:{}),u?{veltFolderId:u}:{})}catch(r){this.loggingService.catch("Error in DocService getDefaultMetadata:",r);return}}getBaseMetadata(e,t){try{let r,a;t?.element?r=this.getAdditionalDocumentIdFromElement(t.element)||void 0:t?.clientDocumentId&&(r=t.clientDocumentId),r&&(a=this.generateDocumentId(r));let s=this.getMetadataFromType(e,t),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:t}){try{return e&&(e=this.generateDocumentId(e)),t&&(t=this.generateOrganizationId(t)),{documentId:e,organizationId:t}}catch(r){return this.loggingService.catch("Error in DocService getServerId:",r),null}}fetchDocuments(e){return Q(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=Fi(e?.folderId);r.push(lt("metadata.veltFolderId","==",s))}return e?.documentIds?.length&&!e?.allDocuments&&r.push(lt("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(t){return this.loggingService.catch("Error in DocService fetchDocuments:",t),[]}})}fetchLocations(e){return Q(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.commonDbService?.shouldUseFirestore()&&this.loggingService.catch("Error in fetchLocations: organizationId is required"),[];if(e?.folderId){let s=Fi(e?.folderId);r.push(lt("metadata.veltFolderId","==",s))}return e?.documentIds?.length&&!e?.allDocuments&&r.push(lt("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(t){return this.loggingService.catch("Error in DocService fetchLocations:",t),[]}})}updateDocuments(e){return Q(this,null,function*(){try{if(typeof e=="object"&&(e=JSON.parse(JSON.stringify(e??{}))),!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,folderId:s}=e;if(!r&&(r=this.documentPaths$.value?.clientOrganizationId,!r))return this.loggingService.catch("Error in updateDocuments: organizationId is required"),[];let c=La(r);if(!a||a.length===0)return this.loggingService.catch("Error in updateDocuments: documents is required"),[];let p=[],u=this.documentMetadata$.value??{};for(let C of a)if(C?.documentId){C.organizationId=c,C.clientOrganizationId=r,C.clientDocumentId=C.documentId;let E=na(C.documentId);C.documentId=E,C.apiKey=this.configService.getApiKey()??void 0,(s||this.documentPaths$.value?.folderId)&&(C.folderId=s||this.documentPaths$.value?.folderId,C.veltFolderId=Fi(s||this.documentPaths$.value?.folderId||""));let D=()=>{if(s&&this.documentPaths$.value?.folderId&&s!==this.documentPaths$.value?.folderId)return;let z=u?.[E];z?u[E]=I(I({},z),C):u[E]=C},L=yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:E,organizationId:c,field:"metadata"}});if(L?.errorCode&&(L={}),L&&L.apiKey&&L.folderId&&s&&L.folderId!=C.folderId){this.loggingService.catch(`Error in updateDocuments: document ${C.clientDocumentId} already exists with different folderId: ${L.folderId}`);continue}if(L&&L.apiKey&&!L.folderId&&C.folderId){this.loggingService.catch(`Error in updateDocuments: document ${C.clientDocumentId} already exists, move this document to folder with REST API`);continue}D(),C&&this.commonDbService&&this.userPermissionService?.hasEditAccess({documentId:C?.documentId??""})&&p.push(this.commonDbService.updateData({feature:"documentMetadata",data:JSON.parse(JSON.stringify(C)),properties:{organizationId:c,documentId:E}}))}yield Promise.all(p),this.documentMetadata$.next(u)}catch(t){return this.loggingService.catch("Error in DocService updateDocuments:",t),[]}})}updateLocations(e){return Q(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(C=>C.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(C=>na(C)),p=[],u=this.locationMetadata$.value;u||(u={}),c.forEach(C=>{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 L=wj(E.id),z=u?.[C],W=z?.[E.id];u&&(z||(u[C]={}),W||(u[C][E.id]={}),u[C][E.id]=T(I({},W),{location:E})),E&&this.commonDbService&&p.push(this.commonDbService.updateData({feature:"locationMetadata",data:JSON.parse(JSON.stringify({location:E})),properties:{organizationId:La(r),documentId:C,id:L}}))}})}),yield Promise.all(p),Object.keys(u||{}).length>0&&this.locationMetadata$.next(u)}catch(t){return this.loggingService.catch("Error in DocService updateLocations:",t),[]}})}fetchFolders(e){return Q(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=Fi(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:[lt("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(t){return this.loggingService.catch("Error in DocService getFoldersRequest:",t),{data:[],parentFolders:[]}}})}getDocumentIam$(){return this.authService.getUser$().pipe(he(e=>e?this.documentPaths$.pipe(he(t=>t?.documentIam?this.commonDbService?.dbListener({feature:"documentIam",properties:{documentId:t.documentId,organizationId:t.organizationId,isCollection:!1}}).pipe(ce(r=>r?.data?.docIamConfig??r?.data),Et((r,a)=>JSON.stringify(r??{})===JSON.stringify(a??{}))):se(null))):se(null)))}getDocumentAccessType(e){try{return e&&e.features&&e.features.all?e.features.all.restricted?yi.RESTRICTED:yi.PUBLIC:e&&e.documentAccessType?e.documentAccessType:yi.PUBLIC}catch(t){return this.loggingService.catch("Error in DocService getDocumentAccessType:",t),yi.PUBLIC}}changeDocumentAccessType(e){return Q(this,null,function*(){try{let t=this.documentPaths$.value;if(t){let r=yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:t?.documentId??"",organizationId:t?.organizationId??"",field:"docIamConfig"}});if(r?.errorCode)return;switch(delete r.documentAccessType,r.features||(r.features={}),r.features.all||(r.features.all={}),e){case yi.PUBLIC:r.features.all.restricted=!1;break;case yi.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:t?.documentId??"",organizationId:t?.organizationId??""}})}}catch(t){this.loggingService.catch("Error in DocService changeDocumentAccessType:",t)}})}getUserIdForAnalytics(){try{return this.authService?.getAuthUser()?.uid||""}catch(e){return this.loggingService.catch("Error in DocService getUserIdForAnalytics:",e),""}}setUIState(e){try{this.uiState.next(I(I({},this.uiState.value),e))}catch(t){this.loggingService.catch("Error in DocService setUIState:",t)}}getUIState$(){return this.uiState.asObservable()}};o.\u0275fac=function(t){return new(t||o)(ee(et),ee(Ve),ee(Dn),ee(Be),ee(Ft),ee(y),ee(Rs),ee(jd),ee(Vd))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var Vn=(()=>{let o=class o{constructor(e,t,r,a){this.analyticsService=e,this.authService=t,this.docService=r,this.loggingService=a,this.resolveOrganizationUsers=new ve(!0),this.resolveFolderUsers=new ve(!0),this.resolveDocumentUsers=new ve(!0),this.resolveTimeout=1*60*1e3,this.resolveAttempts=new Map,this.subscriptions=new yn,this.userDataProvider$=new ve(null),this.userById$=new ve({}),this.userByIdCalled$=new ve({}),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)}}setCommonDbService(e){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setCommonDbService","color: green;"),this.commonDbService=e}catch(t){this.loggingService.catch("Error in UsersService setCommonDbService:",t)}}ngOnDestroy(){try{this.subscriptions.unsubscribe(),this.pendingResolutions.clear(),this.resolveAttempts.clear()}catch(e){this.loggingService.catch("Error in UsersService ngOnDestroy:",e)}}isResolverForFeatureDisabled(e){let t=this.userDataProvider$.getValue();try{switch(e){case"allOrganizationUsers":return t?!this.resolveOrganizationUsers.value:!0;case"allFolderUsers":return t?!this.resolveFolderUsers.value:!0;case"allDocumentUsers":return t?!this.resolveDocumentUsers.value:!0;default:return!1}}catch(r){return this.loggingService.catch("Error in UsersService isResolverForFeatureDisabled:",r),!1}}resolveUsers(c){return Q(this,arguments,function*({userIds:e,forceResolve:t,feature:r,organizationId:a,skipUserCheck:s=!1}){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: resolveUsers","color: green;");let p=!1;if(r&&(p=this.isResolverForFeatureDisabled(r)),p)return{};{let u={},C=[],E={};if(e?.forEach(D=>{let L=this.getUserById(D);L?u[D]=L:this.userByIdCalled$.getValue()[D]?t&&C.push(D):(C.push(D),this.userByIdCalled$.next(T(I({},this.userByIdCalled$.getValue()),{[D]:!0})))}),C.length>0){let D={};try{let L,z=new Promise((W,J)=>{L=setTimeout(()=>{J(new Error("User resolution timeout"))},this.userDataProvider$.getValue()?.config?.resolveTimeout||this.userDataProvider$.getValue()?.resolveTimeout||this.resolveTimeout)});D=yield Promise.race([this.getUsersFromDB({userIds:C,organizationId:a,skipUserCheck:s}).finally(()=>{clearTimeout(L)}),z]),this.analyticsService.trackEvent(Z.Events.Resolver.USER_RESOLVER_GET,{sourceMethod:"resolveUsers",source:"sdk",userIds:C})}catch(L){this.loggingService.catch("Error in UsersService resolveUsers getUsers:",L,{userIds:C})}finally{C?.forEach(L=>{D[L]||(D[L]={userId:L,name:`User ${L}`})})}Object.entries(D).forEach(([L,z])=>{z&&(u[L]=D?.[L],E[L]=D?.[L])})}return Object.keys(E).length>0&&(this.authService.setOptionalPropertiesToUsers(Object.values(E)),this.userById$.next(I(I({},this.userById$.getValue()),E))),u}}catch(p){return this.loggingService.catch("Error in UsersService resolveUsers:",p),{}}})}getUsersFromDB(a){return Q(this,arguments,function*({userIds:e,organizationId:t,skipUserCheck:r=!1}){this.loggingService.log("%c[WB] Calling UsersService FUNCTION: getUsersFromDB","color: green;");try{let s=this.userDataProvider$.getValue();if(s)return s.get(e);if(t||(t=this.docService.getOrganizationConfig()?.organizationId),!t)return{};let c=(yield this.getUsersFromDBWithBatching({userIds:e,organizationId:t,skipUserCheck:r}))??[],p={};return c.forEach(u=>{u.forEach(C=>{C?.user?.userId&&(p[C.user.userId]=C.user)})}),p}catch(s){return this.loggingService.catch("Error in UsersService getUsersFromDB:",s),{}}})}getUsersFromDBWithBatching(a){return Q(this,arguments,function*({userIds:e,organizationId:t,skipUserCheck:r=!1}){try{if(!e?.length)return[];let s=[];for(let u=0;u<e.length;u+=30)s.push(e.slice(u,u+30));let c=s.map((u,C)=>Q(this,null,function*(){try{return(yield this.commonDbService?.queryData({feature:"allOrganizationUsers",properties:{organizationId:t,useCollectionGroup:!1,isCollection:!0,firestoreQuery:[lt("user.userId","in",u)],skipUserCheck:r}}))||[]}catch(E){return this.loggingService.catch(`Error in batch ${C+1}:`,E),[]}}));return yield Promise.all(c)}catch(s){return this.loggingService.catch("Error in getUsersFromDBWithBatching:",s),[]}})}getTemporaryUsersFromDBWithBatching(a){return Q(this,arguments,function*({userIds:e,organizationId:t,resourceIds:r}){try{if(!e?.length||!r?.length)return[];let s=[];for(let z=0;z<e.length;z+=30)s.push(e.slice(z,z+30));let c=[];for(let z=0;z<r.length;z+=30)c.push(r.slice(z,z+30));let p=[],u=0,C=(z,W)=>Q(this,null,function*(){try{return((yield this.commonDbService?.queryData({feature:"allPermissionsUsers",properties:{organizationId:t,useCollectionGroup:!1,isCollection:!0,firestoreQuery:[Zn(lt("userId","in",z),lt("veltResourceId","in",W))]}}))??[])||[]}catch(J){return this.loggingService.catch(`Error in batch ${u+1}:`,J),[]}});for(let z of s)for(let W of c)p.push(C(z,W)),u++;return(yield Promise.all(p)).flat().filter((z,W,J)=>W===J.findIndex(ue=>ue.userId===z.userId&&ue.resourceId===z.resourceId))}catch(s){return this.loggingService.catch("Error in getTemporaryUsersFromDBWithBatching:",s),[]}})}getResolveOrganizationUsers$(){return this.resolveOrganizationUsers.asObservable()}getResolveFolderUsers$(){return this.resolveFolderUsers.asObservable()}getResolveDocumentUsers$(){return this.resolveDocumentUsers.asObservable()}getUserById$(){try{return this.loggingService.log("%c[WB] Calling UsersService FUNCTION: getUserById$","color: green;"),this.userById$.asObservable().pipe(Et(mn))}catch(e){return this.loggingService.catch("Error in UsersService getUserById$:",e),se({})}}setUserByIds(e){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setUserByIds","color: green;");let t=this.userById$.getValue();e.forEach(r=>{t[r.userId]=I(I({},t?.[r.userId]??{}),r)}),this.userById$.next(t)}catch(t){this.loggingService.catch("Error in UsersService setUserByIds:",t)}}setUserDataProvider(e){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setUserDataProvider","color: green;"),this.userDataProvider$.next(e),e.config?.resolveUsersConfig?.organization===!1?this.resolveOrganizationUsers.next(!1):this.resolveOrganizationUsers.next(!0),e.config?.resolveUsersConfig?.folder===!1?this.resolveFolderUsers.next(!1):this.resolveFolderUsers.next(!0),e.config?.resolveUsersConfig?.document===!1?this.resolveDocumentUsers.next(!1):this.resolveDocumentUsers.next(!0)}catch(t){this.loggingService.catch("Error in UsersService setUserDataProvider:",t)}}userDataProviderAvailable(){try{return this.loggingService.log("%c[WB] Calling UsersService FUNCTION: userDataProviderAvailable","color: green;"),!!this.commonDbService?.shouldUseFirestore()}catch(e){return this.loggingService.catch("Error in UsersService userDataProviderAvailable:",e),!1}}};o.\u0275fac=function(t){return new(t||o)(ee(et),ee(Ve),ee(at),ee(y))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var Rce=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.usersService=t}getUserIdsToResolveFromAreaAnnotations(e){try{this.loggingService.log("%c[WB] Calling AreaUtilsService FUNCTION: getUserIdsToResolveFromAreaAnnotations","color: green;");let t=new Set;for(let r of e)r?.from?.userId&&t.add(r?.from?.userId);return Array.from(t)}catch(t){return this.loggingService.catch("Error in AreaUtilsService getUserIdsToResolveFromAreaAnnotations:",t),[]}}mergeAreaWithUser(e){try{if(this.loggingService.log("%c[WB] Calling AreaUtilsService FUNCTION: mergeAreaWithUser","color: green;"),e?.from?.userId){let t=this.usersService.getUserById(e?.from?.userId);t&&(e.from=t)}return e}catch(t){return this.loggingService.catch("Error in AreaUtilsService mergeAreaWithUser:",t),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(t){return this.loggingService.catch("Error in AreaUtilsService formatAreaData:",t),e}}};o.\u0275fac=function(t){return new(t||o)(ee(y),ee(Vn))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var Nce=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.usersService=t}getUserIdsToResolveFromArrowAnnotations(e){try{this.loggingService.log("%c[WB] Calling ArrowUtilsService FUNCTION: getUserIdsToResolveFromArrowAnnotations","color: green;");let t=new Set;for(let r of e)r?.from?.userId&&t.add(r?.from?.userId);return Array.from(t)}catch(t){return this.loggingService.catch("Error in ArrowUtilsService getUserIdsToResolveFromArrowAnnotations:",t),[]}}mergeArrowWithUser(e){try{if(this.loggingService.log("%c[WB] Calling ArrowUtilsService FUNCTION: mergeArrowWithUser","color: green;"),e?.from?.userId){let t=this.usersService.getUserById(e?.from?.userId);t&&(e.from=t)}return e}catch(t){return this.loggingService.catch("Error in ArrowUtilsService mergeArrowWithUser:",t),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(t){return this.loggingService.catch("Error in ArrowUtilsService formatArrowData:",t),e}}};o.\u0275fac=function(t){return new(t||o)(ee(y),ee(Vn))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var og=class{static getFirestoreProdDbName(o,n){return n?.storeDbId??(this.isTestingDb(n?.databaseURL??"")?"sdktest":`apikey${o.toLowerCase()}`)}static isTestingDb(o){try{return o.includes("-test")}catch(n){return ot.error("Error in isTestingDb:",n),!1}}};var rg=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.analyticsService=t,this.retrySaveConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.retryDeleteConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.attachmentDataProvider$=new ve(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 Q(this,null,function*(){try{this.loggingService.log("%c[WB] Calling AttachmentResolverService FUNCTION: saveAttachment","color: green;");let t=this.getProvider();if(!this.attachmentDataProviderAvailable())throw new Error("Attachment save data provider not available");let r=yield Pc(()=>t?.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(t){this.loggingService.warn("Error in AttachmentResolverService saveAttachment:",t);return}})}deleteAttachment(r){return Q(this,arguments,function*({attachmentId:e,metadata:t}){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 Pc(()=>a?.delete({attachmentId:e,metadata:t,event:os.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(t){this.loggingService.catch("Error in AttachmentResolverService setAttachmentDataProvider:",t)}}attachmentDataProviderAvailable(){try{return!!this.attachmentDataProvider$.getValue()}catch(e){return this.loggingService.catch("Error in AttachmentResolverService attachmentDataProviderAvailable:",e),!1}}};o.\u0275fac=function(t){return new(t||o)(ee(y),ee(et))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var f0=(()=>{let o=class o{constructor(e,t,r,a,s,c,p){this.loggingService=e,this.usersService=t,this.authService=r,this.functions=a,this.configService=s,this.commentAnnotationsResolverService=c,this.attachmentResolverService=p,this.notificationActionTypeMap={[$t.NEWLY_ADDED]:os.COMMENT_ANNOTATION_ADD,[$t.ADDED]:os.COMMENT_ADD,[$t.UPDATED]:os.COMMENT_UPDATE,[$t.DELETED]:os.COMMENT_DELETE}}setNotificationService(e){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: setNotificationService","color: green;"),this.notificationService=e}catch(t){this.loggingService.catch("Error in CommentUtilsService setNotificationService: ",t)}}getUserIdsToResolveFromComments(e){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: getUserIdsToResolveFromComments","color: green;");let t=new Set;for(let r of e){if(r?.from?.userId&&t.add(r?.from?.userId),r?.comments)for(let a of r?.comments){if(a?.from?.userId&&t.add(a?.from?.userId),a?.to)for(let s of a?.to)s?.userId&&t.add(s?.userId);if(a?.taggedUserContacts)for(let s of a?.taggedUserContacts)s?.userId&&t.add(s?.userId)}if(r?.assignedTo?.userId&&t.add(r?.assignedTo?.userId),r?.subscribedUsers)for(let a of Object.values(r?.subscribedUsers))a.user.userId&&t.add(a.user.userId);if(r?.unsubscribedUsers)for(let a of Object.values(r?.unsubscribedUsers))a.user.userId&&t.add(a.user.userId)}return Array.from(t)}catch(t){return this.loggingService.catch("Error in CommentUtilsService getUserIdsToResolveFromComments:",t),[]}}mergeCommentWithUser(e){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: mergeCommentWithUser","color: green;"),e?.from?.userId){let t=this.usersService.getUserById(e?.from?.userId);t&&(e.from=t)}if(e?.comments)for(let t of e?.comments){if(t?.from?.userId){let a=this.usersService.getUserById(t?.from?.userId);a&&(t.from=a)}t?.to&&(t.to=t?.to?.map(a=>{if(a?.userId){let s=this.usersService.getUserById(a?.userId);if(s)return I(I({},a),s)}return a})),t?.taggedUserContacts&&(t.taggedUserContacts=t?.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})),(t?.taggedUserContacts?.filter((a,s,c)=>c.findIndex(p=>p.text===a.text)===s)||[]).forEach(a=>{if(a?.text){let s=new RegExp(Od(`{{${a.userId}}}`),"g");t.commentText=t.commentText?.replaceAll(s,a.text),t.commentHtml=t.commentHtml?.replaceAll(s,a.text)}})}if(e?.assignedTo?.userId){let t=this.usersService.getUserById(e?.assignedTo?.userId);t&&(e.assignedTo=t)}if(e?.subscribedUsers)for(let t of Object.values(e?.subscribedUsers)){let r=this.usersService.getUserById(t.user.userId);r&&e?.subscribedUsers?.id?.user&&(e.subscribedUsers.id.user=r)}if(e?.unsubscribedUsers)for(let t of Object.values(e?.unsubscribedUsers)){let r=this.usersService.getUserById(t.user.userId);r&&e?.unsubscribedUsers?.id?.user&&(e.unsubscribedUsers.id.user=r)}return e}catch(t){return this.loggingService.catch("Error in CommentUtilsService mergeCommentWithUser:",t),e}}formatCommentData(e){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: formatCommentData","color: green;"),e?.comments?.forEach(t=>{t?.commentText&&t?.commentText?.length>0&&(t.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 t of Object.keys(e?.subscribedUsers))e.subscribedUsers[t].user={userId:e?.subscribedUsers[t].user.userId};if(e?.unsubscribedUsers)for(let t of Object.keys(e?.unsubscribedUsers))e.unsubscribedUsers[t].user={userId:e?.unsubscribedUsers[t].user.userId}}return e?.comments&&(e.comments=e?.comments?.map(t=>this.formatCommentThreadData(t))),e}catch(t){return this.loggingService.catch("Error in CommentUtilsService formatCommentData:",t),e}}mergeStrippedDataWithCommentAnnotations(e){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: mergeStrippedDataWithCommentAnnotations","color: green;"),!this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())return e;let t=this.commentAnnotationsResolverService.getAnnotationById(e?.annotationId),r=this.attachmentResolverService.attachmentDataProviderAvailable(),a=this.commentAnnotationsResolverService.getFieldsToRemove();return t&&(e?.comments?.forEach(s=>{let c=t?.comments?.[s?.commentId];if(c){s.commentHtml=c?.commentHtml,s.commentText=c?.commentText;let p=c?.attachments;r&&p&&s.attachments?.forEach(u=>{let C=u?.attachmentId;p?.[C]&&(u.name=p?.[C]?.name,u.url=p?.[C]?.url)})}}),t?.targetTextRange?.text&&e?.targetTextRange&&(e.targetTextRange.text=t?.targetTextRange?.text),a?.length>0&&a.forEach(s=>{t?.[s]&&(e[s]=t[s])})),e}catch(t){return this.loggingService.catch("Error in CommentUtilsService mergeStrippedDataWithCommentAnnotations:",t),e}}mergeLocationWithCommentAnnotations(e,t){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=t?.[a]?.[r];return s&&(e.location=s?.location),e}catch(r){return this.loggingService.catch("Error in CommentUtilsService mergeLocationWithCommentAnnotations:",r),e}}isCommentsDataChanged(e,t){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: isCommentsDataChanged","color: green;");let r=this.commentAnnotationsResolverService.getCommentAnnotationById(t);return r?!wi(e,r):!0}catch(r){return this.loggingService.catch("Error in CommentUtilsService isCommentsDataChanged:",r),!0}}stripCommentsFromAnnotationData({comment:e}){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: stripCommentsFromAnnotationData","color: green;");let t=this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable();if(!t)return e;let r=this.attachmentResolverService.attachmentDataProviderAvailable(),a=new Nc;if(Object.assign(a,e),a.isCommentResolverUsed=t,r){let s=a.attachments?.map(c=>(c.isAttachmentResolverUsed=!0,delete c?.name,delete c?.url,c));a.attachments=s}return delete a?.commentHtml,delete a?.commentText,a}catch(t){return this.loggingService.catch("Error in CommentUtilsService stripCommentsFromAnnotationData:",t),e}}stripCommentAnnotationData({data:e,actionType:t}){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: stripCommentAnnotationData","color: green;"),!this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable()||!t)return{originalData:e,strippedData:null};let r=this.attachmentResolverService.attachmentDataProviderAvailable(),a=this.commentAnnotationsResolverService.getFieldsToRemove(),s=this.notificationActionTypeMap?.[t],c={},p=null,u=!1;if(e&&e.annotationId){let C=e.annotationId;c[C]=I(I(I(I({annotationId:C,metadata:Rv(e.metadata??{}),comments:{}},e?.from&&{from:e?.from}),e?.assignedTo&&{assignedTo:e?.assignedTo}),e?.resolvedByUserId&&{resolvedByUserId:e?.resolvedByUserId}),e?.targetTextRange?.text&&{targetTextRange:{text:e?.targetTextRange?.text}}),delete e?.targetTextRange?.text,a?.length>0&&a.forEach(D=>{e?.[D]&&(c[C][D]=e[D],delete e[D])}),e.comments?.forEach(D=>{if(D.commentId){let L;r&&(L={},D.attachments?.forEach(z=>{L[z.attachmentId]={attachmentId:z.attachmentId,name:z.name,url:z.url}})),c[C].comments[D.commentId]=I(I(I(I(I(I({commentId:D.commentId},D?.commentHtml&&{commentHtml:D?.commentHtml}),D?.commentText&&{commentText:D?.commentText}),L&&{attachments:L}),D?.from&&{from:D?.from}),D?.to&&{to:D?.to}),D?.taggedUserContacts&&{taggedUserContacts:D?.taggedUserContacts})}}),u=this.isCommentsDataChanged(c[C],C);let E=new Bo;Object.assign(E,e),E.comments=e.comments?.map(D=>this.stripCommentsFromAnnotationData({comment:D}))||[],p=E}return{strippedData:u?c:null,originalData:p,eventType:s}}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 t=e?.taggedUserContacts?.filter((r,a,s)=>s.findIndex(c=>c.text===r.text)===a)||[];t.forEach(r=>{if(r?.text){let a=new RegExp(Od(r.text),"g");e.commentText=e.commentText?.replaceAll(a,s=>`{{${r.userId}}}`),e.commentHtml=e.commentHtml?.replaceAll(a,s=>`{{${r.userId}}}`)}}),t.forEach(r=>{r?.text&&(r.text="")})}return e}catch(t){return this.loggingService.catch("Error in CommentUtilsService formatCommentThreadData:",t),e}}handleCommentEncryption(c){return Q(this,arguments,function*({data:e,firestorePath:t,extraData:r,eventType:a,metadata:s}){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: handleCommentEncryption","color: green;");let p=WP(this.authService.getFirebaseConfig()?.firebaseOptions),u=br(this.functions,Er({url:oi.cloudFunction?.[p]?.setEncryptedData,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:20*60*1e3});if(r){r=this.notificationService?.processNotificationData(r),r.annotationData=e;let L=r?.targetAnnotationData?.commentId;if(L){let z=e?.comments?.find(W=>W?.commentId===L);z&&(r.targetAnnotationData=z)}try{let z=this.stripCommentAnnotationData({data:r.annotationData,actionType:r?.actionType??$t.NEWLY_ADDED});z?.originalData&&(r.annotationData=this.formatCommentData(z.originalData)),r?.targetAnnotationData&&(r.targetAnnotationData=this.formatCommentThreadData(this.stripCommentsFromAnnotationData({comment:r.targetAnnotationData})))}catch(z){this.loggingService.warn("Error in CommentUtilsService handleCommentEncryption:",z)}}let C=og.getFirestoreProdDbName(this.configService.getApiKey()??"",this.authService.getFirebaseConfig()?.firebaseOptions),E={path:t??"",data:e??{},dbId:C??"",notificationData:r||void 0,notificationURL:oi.firebaseNotificationsDatabaseURL,feature:"comment",eventType:a??"PATCH",sdkVersion:ia(),metadata:s},D=yield Gp(E,this.authService.getUser()?.userId??"");yield u({veltData:D})}catch(p){this.loggingService.catch("Error in CommentUtilsService handleCommentEncryption:",p)}})}};o.\u0275fac=function(t){return new(t||o)(ee(y),ee(Vn),ee(Ve),ee(Wo),ee(Ft),ee(Rs),ee(rg))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var Fce=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.usersService=t}getUserIdsToResolveFromUserIamData(e){try{this.loggingService.log("%c[WB] Calling ContactUtilsService FUNCTION: getUserIdsToResolveFromUserIamData","color: green;");let t=new Set;if(e?.length)for(let r of e)r?.user?.userId&&t.add(r?.user?.userId);return Array.from(t)}catch(t){return this.loggingService.catch("Error in ContactUtilsService getUserIdsToResolveFromUserIamData: ",t),[]}}mergeUserIamWithUser(e){try{if(this.loggingService.log("%c[WB] Calling ContactUtilsService FUNCTION: mergeUserIamWithUser","color: green;"),e?.user?.userId){let t=this.usersService.getUserById(e?.user?.userId);if(t){let r=t;e?.user&&typeof e.user=="object"&&(r=I(I({},r),e.user)),e=T(I({},e),{user:r})}}return e}catch(t){return this.loggingService.catch("Error in ContactUtilsService mergeUserIamWithUser: ",t),e}}};o.\u0275fac=function(t){return new(t||o)(ee(y),ee(Vn))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var Lce=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.usersService=t}getUserIdsToResolveFromCursorUsers(e){try{this.loggingService.log("%c[WB] Calling CursorUtilsService FUNCTION: getUserIdsToResolveFromCursorUsers","color: green;");let t=new Set;for(let r of e)r?.userId&&t.add(r?.userId);return Array.from(t)}catch(t){return this.loggingService.catch("Error in CursorUtilsService getUserIdsToResolveFromCursorUsers:",t),[]}}mergeCursorUserWithUser(e){try{if(this.loggingService.log("%c[WB] Calling CursorUtilsService FUNCTION: mergeCursorUserWithUser","color: green;"),this.usersService.userDataProviderAvailable()&&e?.userId){let t=this.usersService.getUserById(e?.userId);t&&(e=I(I({},e),t))}return e}catch(t){return this.loggingService.catch("Error in CursorUtilsService mergeCursorUserWithUser:",t),e}}formatCursorUserData(e){try{if(this.loggingService.log("%c[WB] Calling CursorUtilsService FUNCTION: formatCursorUserData","color: green;"),this.usersService.userDataProviderAvailable()){let t=["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=>{t.includes(r)||(e[r]=null)})}return e}catch(t){return this.loggingService.catch("Error in CursorUtilsService formatCursorUserData:",t),e}}};o.\u0275fac=function(t){return new(t||o)(ee(y),ee(Vn))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var Mk=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.usersService=t}getUserIdsToResolveFromHuddleAttendees(e){try{this.loggingService.log("%c[WB] Calling HuddleUtilsService FUNCTION: getUserIdsToResolveFromHuddleAttendees","color: green;");let t=new Set;for(let r of e)r?.userId&&t.add(r?.userId);return Array.from(t)}catch(t){return this.loggingService.catch("Error in HuddleUtilsService getUserIdsToResolveFromHuddleAttendees:",t),[]}}mergeHuddleAttendeeWithUser(e){try{if(this.loggingService.log("%c[WB] Calling HuddleUtilsService FUNCTION: mergeHuddleAttendeeWithUser","color: green;"),e?.userId){let t=this.usersService.getUserById(e?.userId);t&&(e=I(I({},e),t))}return e}catch(t){return this.loggingService.catch("Error in HuddleUtilsService mergeHuddleAttendeeWithUser:",t),e}}formatHuddleAttendeeData(e){try{if(this.usersService.userDataProviderAvailable()){let t=["userId","userSnippylyId","state","timestamp","initialHuddleMode","streamMetadata","initialHuddleType","huddleOnCursorMode"];Object.keys(e).forEach(r=>{t.includes(r)||(e[r]=null)})}return e}catch(t){return this.loggingService.catch("Error in HuddleUtilsService formatHuddleAttendeeData:",t),e}}getUserIdsToResolveFromHuddleMessages(e){try{this.loggingService.log("%c[WB] Calling HuddleUtilsService FUNCTION: getUserIdsToResolveFromHuddleMessages","color: green;");let t=new Set;for(let r of e)r?.from?.userId&&t.add(r?.from?.userId);return Array.from(t)}catch(t){return this.loggingService.catch("Error in HuddleUtilsService getUserIdsToResolveFromHuddleMessages:",t),[]}}mergeHuddleMessageWithUser(e){try{if(this.loggingService.log("%c[WB] Calling HuddleUtilsService FUNCTION: mergeHuddleMessageWithUser","color: green;"),e?.from?.userId){let t=this.usersService.getUserById(e?.from?.userId);t&&(e.from=t)}return e}catch(t){return this.loggingService.catch("Error in HuddleUtilsService mergeHuddleMessageWithUser:",t),e}}resolveUsersFromHuddleMessages(e){return Q(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling HuddleUtilsService FUNCTION: resolveUsersFromHuddleMessages","color: green;"),this.usersService.userDataProviderAvailable()){let t=this.getUserIdsToResolveFromHuddleMessages(e),r=yield this.usersService.resolveUsers({userIds:t});for(let a of e)a?.from?.userId&&r[a.from.userId]&&(a.from=r[a.from.userId])}return e}catch(t){return this.loggingService.catch("Error in HuddleUtilsService resolveUsersFromHuddleMessages:",t),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(t){return this.loggingService.catch("Error in HuddleUtilsService formatHuddleMessageData:",t),e}}};o.\u0275fac=function(t){return new(t||o)(ee(y),ee(Vn))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var kk=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.usersService=t}getUserIdsToResolveFromLiveStateCustom(e){try{let t=new Set;return e?.updatedBy&&t.add(e?.updatedBy?.userId),Array.from(t)}catch(t){return this.loggingService.catch("Error in LiveStateUtilsService getUserIdsToResolveFromLiveStateCustom:",t),[]}}mergeLiveStateCustomWithUser(e){try{if(e?.updatedBy?.userId){let t=this.usersService.getUserById(e?.updatedBy?.userId);t&&(e.updatedBy=t)}return e}catch(t){return this.loggingService.catch("Error in LiveStateUtilsService mergeLiveStateCustomWithUser:",t),e}}formatLiveStateCustomData(e){try{return this.usersService.userDataProviderAvailable()&&e?.updatedBy&&(e.updatedBy={userId:e.updatedBy.userId}),e}catch(t){return this.loggingService.catch("Error in LiveStateUtilsService formatLiveStateCustomData:",t),e}}getUserIdsToResolveFromLiveStateCustoms(e){try{let t=new Set;for(let r of e)r?.updatedBy?.userId&&t.add(r?.updatedBy?.userId);return Array.from(t)}catch(t){return this.loggingService.catch("Error in LiveStateUtilsService getUserIdsToResolveFromLiveStateCustoms:",t),[]}}getUserIdsToResolveFromLiveStates(e){try{let t=new Set;return e?.default?.singleEditorMode?.editor?.userId&&t.add(e?.default?.singleEditorMode?.editor?.userId),Array.from(t)}catch(t){return this.loggingService.catch("Error in LiveStateUtilsService getUserIdsToResolveFromLiveStates:",t),[]}}mergeLiveStateWithUser(e){try{if(e?.default?.singleEditorMode?.editor?.userId){let t=this.usersService.getUserById(e?.default?.singleEditorMode?.editor?.userId);t&&(e.default.singleEditorMode.editor=t)}if(e?.default?.singleEditorMode?.requestEditorAccess?.user?.userId){let t=this.usersService.getUserById(e?.default?.singleEditorMode?.requestEditorAccess?.user?.userId);t&&(e.default.singleEditorMode.requestEditorAccess.user=t)}return e}catch(t){return this.loggingService.catch("Error in LiveStateUtilsService mergeLiveStateWithUser:",t),e}}mergeSingleEditorLiveStateDataWithUser(e){try{if(e?.editor?.userId){let t=this.usersService.getUserById(e?.editor?.userId);t&&(e.editor=t)}if(e?.requestEditorAccess?.user?.userId){let t=this.usersService.getUserById(e?.requestEditorAccess?.user?.userId);t&&(e.requestEditorAccess.user=t)}return e}catch(t){return this.loggingService.catch("Error in LiveStateUtilsService mergeSingleEditorLiveStateDataWithUser:",t),e}}resolveAndMergeSingleEditorLiveStateDataWithUser(e){return Q(this,null,function*(){try{let t=this.getUserIdsToResolveFromLiveStates({default:{singleEditorMode:e}});return t.length?(yield this.usersService.resolveUsers({userIds:t}),this.mergeSingleEditorLiveStateDataWithUser(e)):e}catch(t){return this.loggingService.catch("Error in LiveStateUtilsService resolveAndMergeSingleEditorLiveStateDataWithUser:",t),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(t){return this.loggingService.catch("Error in LiveStateUtilsService formatLiveStateSingleEditorModeData:",t),e}}mergeLiveStateCustomsWithUsers(e){try{for(let t of e)if(t?.updatedBy?.userId){let r=this.usersService.getUserById(t?.updatedBy?.userId);r&&(t.updatedBy=r)}return e}catch(t){return this.loggingService.catch("Error in mergeLiveStateCustomsWithUsers:",t),e}}};o.\u0275fac=function(t){return new(t||o)(ee(y),ee(Vn))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var Uce=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.usersService=t}getUserIdsToResolveFromMultiThreads(e){try{let t=new Set;for(let r of e)r?.from?.userId&&t.add(r?.from?.userId);return Array.from(t)}catch(t){return this.loggingService.catch("Error in MultiThreadUtilsService getUserIdsToResolveFromMultiThreads:",t),[]}}mergeMultiThreadWithUser(e){try{if(e?.from?.userId){let t=this.usersService.getUserById(e?.from?.userId);t&&(e.from=t)}return e}catch(t){return this.loggingService.catch("Error in MultiThreadUtilsService mergeMultiThreadWithUser:",t),e}}formatMultiThreadData(e){try{return this.usersService.userDataProviderAvailable()&&(e?.from?.userId&&(e.from={userId:e.from.userId}),e?.commentAnnotationsMap&&(e.commentAnnotationsMap=null)),e}catch(t){return this.loggingService.catch("Error in MultiThreadUtilsService formatMultiThreadData:",t),e}}};o.\u0275fac=function(t){return new(t||o)(ee(y),ee(Vn))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var v0=(()=>{let o=class o{constructor(e,t,r){this.authService=e,this.loggingService=t,this.usersService=r}getUserIdsToResolveFromRecorders(e){try{let t=new Set;for(let r of e)r?.from?.userId&&t.add(r?.from?.userId),r?.transcription?.from?.userId&&t.add(r?.transcription?.from?.userId);return Array.from(t)}catch(t){return this.loggingService.catch("Error in RecorderUtilsService getUserIdsToResolveFromRecorders:",t),[]}}mergeRecorderWithUser(e){try{if(e?.from?.userId){let t=this.usersService.getUserById(e?.from?.userId);t&&(e.from=t)}if(e?.transcription?.from?.userId){let t=this.usersService.getUserById(e?.transcription?.from?.userId);t&&(e.transcription.from=t)}return e}catch(t){return this.loggingService.catch("Error in RecorderUtilsService mergeRecorderWithUser:",t),e}}formatRecorderData(e,t){try{return e.transcription=e?.transcription?T(I({},e.transcription),{lastUpdated:t}):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(t){return this.loggingService.catch("Error in RecorderUtilsService formatRecorderDataForWhisperTranscription:",t),e}}encryptRecorderAnnotation(e){return Q(this,null,function*(){try{return yield Gp(e,this.authService.getUser()?.userId??"")}catch(t){this.loggingService.catch("Error in RecorderUtilsService encryptRecorderAnnotation:",t);return}})}};o.\u0275fac=function(t){return new(t||o)(ee(Ve),ee(y),ee(Vn))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var Rk=(()=>{let o=class o{constructor(e,t,r,a,s,c){this.commentUtilsService=e,this.recorderUtilsService=t,this.loggingService=r,this.usersService=a,this.authService=s,this.commentAnnotationsResolverService=c}getUserIdsToResolveFromNotifications(e){try{let t=new Set;for(let r of e){let{notification:a}=r;switch(a?.actionUser?.userId&&t.add(a?.actionUser?.userId),a?.displayHeadlineMessageTemplateData?.actionUser?.userId&&t.add(a?.displayHeadlineMessageTemplateData?.actionUser?.userId),a?.displayHeadlineMessageTemplateData?.recipientUser?.userId&&t.add(a?.displayHeadlineMessageTemplateData?.recipientUser?.userId),a?.notificationSource){case"comment":if(a?.notificationSourceData){let s=this.commentUtilsService.getUserIdsToResolveFromComments([a?.notificationSourceData]);for(let c of s)t.add(c)}break}}return Array.from(t)}catch(t){return this.loggingService.catch("Error in ReactionUtilsService getUserIdsToResolveFromRecorders:",t),[]}}mergeStrippedDataWithNotification(e){try{if(this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: mergeStrippedDataWithNotification","color: green;"),!this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())return e;let t=this.commentAnnotationsResolverService.getAnnotationById(e?.notification?.targetAnnotationId),r=e?.raw?.targetAnnotationData?.commentId,a=t?.comments?.[r]?.commentText,s=t?.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(t){return this.loggingService.catch("Error in NotificationUtilsService mergeStrippedDataWithNotification:",t),e}}mergeLocationWithNotification(e,t){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=t?.[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:t}=e;if(t?.actionUser?.userId){let r=this.usersService.getUserById(t?.actionUser?.userId);r&&(t.actionUser=r)}if(t?.displayHeadlineMessageTemplateData?.actionUser?.userId){let r=this.usersService.getUserById(t?.displayHeadlineMessageTemplateData?.actionUser?.userId);r&&(t.displayHeadlineMessageTemplateData.actionUser=r)}if(t?.displayHeadlineMessageTemplateData?.recipientUser?.userId){let r=this.usersService.getUserById(t?.displayHeadlineMessageTemplateData?.recipientUser?.userId);r&&(t.displayHeadlineMessageTemplateData.recipientUser=r)}switch(t?.notificationSource){case"comment":t?.notificationSourceData&&this.commentUtilsService.mergeCommentWithUser(t?.notificationSourceData);break}return e}catch(t){return this.loggingService.catch("Error in NotificationUtilsService mergeNotificationWithUser:",t),e}}formatNotification(e,t){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,t);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 t=[];return Object.values(e).forEach(r=>{r?.notification?.targetAnnotationId&&r?.raw?.notificationSource==="comment"&&t.push(r.notification.targetAnnotationId)}),t}catch(t){return this.loggingService.catch("Error in NotificationUtilsService getTargetAnnotationIdsFromNotifications:",t),[]}}handleNotificationEncryption(t){return Q(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 Gp(e,r)}catch(r){return this.loggingService.catch("Error in NotificationUtilsService handleNotificationEncryption:",r),e}})}};o.\u0275fac=function(t){return new(t||o)(ee(f0),ee(v0),ee(y),ee(Vn),ee(Ve),ee(Rs))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var $ce=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.usersService=t}getUserIdsToResolveFromPresenceUsers(e){try{let t=new Set;for(let r of e)r?.userId&&t.add(r?.userId);return Array.from(t)}catch(t){return this.loggingService.catch("Error in PresenceUtilsService getUserIdsToResolveFromPresenceUsers:",t),[]}}mergePresenceUserWithUser(e){try{if(this.usersService.userDataProviderAvailable()&&e?.userId){let t=this.usersService.getUserById(e?.userId);t&&(e=I(I({},e),t))}return e}catch(t){return this.loggingService.catch("Error in PresenceUtilsService mergePresenceUserWithUser:",t),e}}formatPresenceUserData(e){try{if(this.usersService.userDataProviderAvailable()){let t=["userId","onlineStatus","userSnippylyId","color","textColor","timestamp","type","selections","documentParamsId","documentParams","locationId","location","isReadOnly","isAnonymous","pageInfo"];Object.keys(e).forEach(r=>{t.includes(r)||(e[r]=null)})}return e}catch(t){return this.loggingService.catch("Error in PresenceUtilsService formatPresenceUserData:",t),e}}};o.\u0275fac=function(t){return new(t||o)(ee(y),ee(Vn))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var Hce=(()=>{let o=class o{constructor(e,t,r,a,s,c){this.loggingService=e,this.usersService=t,this.authService=r,this.functions=a,this.configService=s,this.reactionAnnotationsResolverService=c}getUserIdsToResolveFromReactions(e){try{let t=new Set;for(let r of e)if(r?.from?.userId&&t.add(r?.from?.userId),r?.reactions?.length)for(let a of r?.reactions)a?.from?.userId&&t.add(a?.from?.userId);return Array.from(t)}catch(t){return this.loggingService.catch("Error in ReactionUtilsService getUserIdsToResolveFromRecorders:",t),[]}}handleReactionEncryption(a){return Q(this,arguments,function*({data:e,firestorePath:t,eventType:r}){try{let s=WP(this.authService.getFirebaseConfig()?.firebaseOptions),c=br(this.functions,Er({url:oi.cloudFunction?.[s]?.setEncryptedData,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:20*60*1e3}),p=og.getFirestoreProdDbName(this.configService.getApiKey()??"",this.authService.getFirebaseConfig()?.firebaseOptions),u=this.authService.getUser()?.userId??"",C={path:t??"",data:e??{},dbId:p??"",feature:"reaction",eventType:r??"PATCH",sdkVersion:ia()},E=yield Gp(C,u);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 t=this.usersService.getUserById(e?.from?.userId);t&&(e.from=t)}if(e?.reactions?.length){for(let t of e?.reactions)if(t?.from?.userId){let r=this.usersService.getUserById(t?.from?.userId);r&&(t.from=r)}}}return e}catch(t){return this.loggingService.catch("Error in ReactionUtilsService mergeReactionWithUser:",t),e}}formatReactionData(e){try{return this.usersService.userDataProviderAvailable()&&e?.from?.userId&&(e.from={userId:e.from.userId}),e.reactions=e?.reactions?.map(t=>(this.usersService.userDataProviderAvailable()&&t?.from?.userId&&(t.from={userId:t.from.userId}),t)),e}catch(t){return this.loggingService.catch("Error in ReactionUtilsService formatReactionData:",t),e}}isReactionDataChanged(e,t){try{this.loggingService.log("%c[WB] Calling ReactionUtilsService FUNCTION: isReactionDataChanged","color: green;");let r=this.reactionAnnotationsResolverService.getReactionAnnotationById(t);return r?!wi(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 t={};if(e&&e.annotationId){let r=e.annotationId;if(t[r]=I({annotationId:r,metadata:Rv(e.metadata??{}),icon:e.icon},e?.from&&{from:e?.from}),!this.isReactionDataChanged(t[r],r))return{strippedData:null,originalData:e};delete e?.icon,e.isReactionResolverUsed=!0}return{strippedData:t,originalData:e}}catch(t){return this.loggingService.catch("Error in ReactionUtilsService stripReactionAnnotationData:",t),{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 t=this.reactionAnnotationsResolverService.getReactionAnnotationById(e?.annotationId);return t&&t.icon&&(e.icon=t.icon),e}catch(t){return this.loggingService.catch("Error in ReactionUtilsService mergeStrippedDataWithReactionAnnotations:",t),e}}};o.\u0275fac=function(t){return new(t||o)(ee(y),ee(Vn),ee(Ve),ee(Wo),ee(Ft),ee(jd))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var zce=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.usersService=t}getUserIdsToResolveFromSelections(e){try{let t=new Set;for(let r of e)r?.user?.userId&&t.add(r.user.userId);return Array.from(t)}catch(t){return this.loggingService.catch("Error in SelectionUtilsService getUserIdsToResolveFromSelections:",t),[]}}mergeSelectionWithUser(e){try{if(e?.user?.userId){let t=this.usersService.getUserById(e?.user?.userId);t&&(e.user=t)}return e}catch(t){return this.loggingService.catch("Error in SelectionUtilsService mergeSelectionWithUser:",t),e}}formatSelectionData(e){try{return this.usersService.userDataProviderAvailable()&&e?.user?.userId&&(e.user={userId:e.user.userId}),e}catch(t){return this.loggingService.catch("Error in SelectionUtilsService formatSelectionData:",t),e}}};o.\u0275fac=function(t){return new(t||o)(ee(y),ee(Vn))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var Gce=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.usersService=t}getUserIdsToResolveFromTags(e){try{let t=new Set;for(let r of e)if(r?.from?.userId&&t.add(r.from.userId),r?.to?.length)for(let a of r.to)a?.userId&&t.add(a.userId);return Array.from(t)}catch(t){return this.loggingService.catch("Error in TagUtilsService getUserIdsToResolveFromTags:",t),[]}}mergeTagWithUser(e){try{if(e?.from?.userId){let t=this.usersService.getUserById(e?.from?.userId);t&&(e.from=t)}return e?.to?.length&&(e.to=e.to.map(t=>{if(t?.userId){let r=this.usersService.getUserById(t?.userId);r&&(t=r)}return t})),e}catch(t){return this.loggingService.catch("Error in TagUtilsService mergeTagWithUser:",t),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(t=>(t?.userId&&(t={userId:t.userId}),t)))),e}catch(t){return this.loggingService.catch("Error in TagUtilsService formatTagData:",t),e}}};o.\u0275fac=function(t){return new(t||o)(ee(y),ee(Vn))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var ag=(()=>{let o=class o{constructor(e,t,r,a,s,c,p,u,C,E,D,L,z,W,J,ue,ye,Ae,He){this.areaUtilsService=e,this.arrowUtilsService=t,this.commentUtilsService=r,this.contactUtilsService=a,this.cursorUtilsService=s,this.huddleUtilsService=c,this.liveStateUtilsService=p,this.loggingService=u,this.multiThreadUtilsService=C,this.notificationUtilsService=E,this.presenceUtilsService=D,this.reactionUtilsService=L,this.recorderUtilsService=z,this.selectionUtilsService=W,this.tagUtilsService=J,this.usersService=ue,this.docService=ye,this.commentAnnotationsResolverService=Ae,this.reactionAnnotationsResolverService=He}getErrorForGetRequests({feature:e,error:t}){try{switch(e){case"organizationMetadata":case"documentMetadata":case"folderMetadata":return(t?.message??"")?.includes("Missing or insufficient permissions.")?{errorCode:"PERMISSION_DENIED"}:null;default:return null}}catch(r){return this.loggingService.catch("Error in CommonDbUtilsService getErrorForGetRequests:",r),null}}getFirestorePath({feature:e,properties:t,documentPaths:r,apiKey:a}){try{if(!a)return;let{documentId:s,organizationId:c,folderId:p}=t;c||(c=r?.organizationId);let u=new Ok({apiKey:a,documentId:s?`${s}`:"",organizationId:c?`${c}`:"",veltFolderId:p?`${p}`:void 0});switch(e){case"userConfig":return t?.userId&&t?.documentId&&u?.userConfig?`${u?.userConfig}/${t?.userId}/${j.FIREBASE_PARTIAL_PATH_DOCUMENT_CONFIGURATIONS}/${t?.documentId}`:void 0;case"allPermissionsUsers":return u?.permissionsUsers?`${u?.permissionsUsers}`:void 0;case"comment":return t?.documentId&&t?.id&&u?.comment?`${u?.comment}/${t?.id}`:void 0;case"allComments":return t?.documentId&&u?.comment?`${u?.comment}`:void 0;case"multiThread":return t?.documentId&&t?.id&&u?.multiThread?`${u?.multiThread}/${t?.id}`:void 0;case"allMultiThreads":return t?.documentId&&u?.multiThread?`${u?.multiThread}`:void 0;case"crdt":return t?.documentId&&u?.crdt&&t?.id?`${u?.crdt}/${t?.id}`:void 0;case"allLastNotificationTimestamp":return u?.lastNotificationTimestamp?`${u?.lastNotificationTimestamp}`:void 0;case"lastNotificationTimestamp":return t?.id&&u?.lastNotificationTimestamp?`${u?.lastNotificationTimestamp}/${t?.id}`:void 0;case"area":return t?.documentId&&t?.id&&u?.area?`${u?.area}/${t?.id}`:void 0;case"allAreas":return t?.documentId&&u?.area?`${u?.area}`:void 0;case"allDocuments":return u?.document?`${u?.document}`:void 0;case"allLocations":return u?.location?`${u?.location}`:void 0;case"allFolders":return u?.folder?`${u?.folder}`:void 0;case"folder":return u?.folder&&t.folderId?`${u?.folder}/${t.folderId}`:void 0;case"documentUserAccess":return t?.documentId&&t?.id&&u?.documentUsers?`${u?.documentUsers}/${t?.id}`:void 0;case"reaction":return t?.documentId&&t?.id&&u?.reaction?`${u?.reaction}/${t?.id}`:void 0;case"allReactions":return t?.documentId&&u?.reaction?`${u?.reaction}`:void 0;case"recorder":return t?.documentId&&t?.id&&u?.recorder?`${u?.recorder}/${t?.id}`:void 0;case"allRecorders":return t?.documentId&&u?.recorder?`${u?.recorder}`:void 0;case"documentAccessType":return t?.documentId&&u?.document?`${u?.document}/${t?.documentId}`:void 0;case"organizationMetadata":return u?.organization?`${u?.organization}`:void 0;case"documentIam":case"documentMetadata":return t?.documentId&&u?.document?`${u?.document}/${t?.documentId}`:void 0;case"folderMetadata":return t?.folderId&&u?.folder?`${u?.folder}/${t?.folderId}`:void 0;case"locationMetadata":return t?.documentId&&u?.location&&t?.id?`${u?.location}/${t?.id}`:void 0;case"documentUser":return t?.documentId&&t?.id&&u?.documentUsers?`${u?.documentUsers}/${t?.id}`:void 0;case"allDocumentUsers":return u?.users?`${u?.users}`:void 0;case"allFolderUsers":return u?.users?`${u?.users}`:void 0;case"allOrganizationGroups":return u?.organizationGroups?`${u?.organizationGroups}`:void 0;case"allOrganizationUsers":return u?.users?`${u?.users}`:void 0;case"notificationViewsTimestamp":return t?.documentId&&t?.id&&u?.notificationViews?`${u?.notificationViews}/${t?.id}`:void 0;case"allDocumentViews":return t?.documentId&&u?.documentViews?`${u?.documentViews}`:void 0;case"documentViews":case"documentMetadataViews":case"documentDayViews":case"documentUsersViews":return t?.documentId&&t?.id&&u?.documentViews?`${u?.documentViews}/${t?.id}`:void 0;case"locationDayViews":case"locationUsersViews":case"locationViews":case"locationMetadataViews":case"location":return t?.documentId&&t?.id&&u?.locationViews?`${u?.locationViews}/${t?.id}`:void 0;case"allLocationViews":return t?.documentId&&u?.locationViews?`${u?.locationViews}`:void 0;case"allDocNotifications":return t?.documentId&&u?.docNotification?`${u?.docNotification}`:void 0;case"docNotificationViews":case"docNotification":return t?.documentId&&t?.id&&u?.docNotification?`${u?.docNotification}/${t?.id}`:void 0;case"userNotificationViews":case"userNotification":return t?.userId&&t?.id&&u?.notificationUsers?`${u?.notificationUsers}/${t?.userId}/${j.FIREBASE_PARTIAL_PATH_USER_NOTIFICATION}/${t?.id}`:void 0;case"allDocNotifications":return t?.documentId&&u?.docNotification?`${u?.docNotification}`:void 0;case"allUserNotifications":return t?.userId&&u?.notificationUsers?`${u?.notificationUsers}/${t?.userId}/${j.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 j.FIREBASE_PARTIAL_PATH_COMMENT;case"allDocuments":return j.FIREBASE_PARTIAL_PATH_DOCS;case"allLocations":return j.FIREBASE_PARTIAL_PATH_LOCATION;case"allMultiThreads":return j.FIREBASE_PARTIAL_PATH_MULTI_THREAD;case"allAreas":return j.FIREBASE_PARTIAL_PATH_AREA;case"allReactions":return j.FIREBASE_PARTIAL_PATH_REACTION;case"allRecorders":return j.FIREBASE_PARTIAL_PATH_RECORDER;case"allDocumentViews":return j.FIREBASE_PARTIAL_PATH_DOCUMENT_VIEWS;case"allLocationViews":return j.FIREBASE_PARTIAL_PATH_LOCATION_VIEWS;case"allDocumentUsers":return j.FIREBASE_PARTIAL_PATH_DOCUMENT_USERS;case"allFolderUsers":return j.FIREBASE_PARTIAL_PATH_FOLDER_USERS;default:throw new Error(`Unknown feature: ${e}`)}}catch(t){this.loggingService.catch("Error in CommonDbUtilsService getFirestoreCollectionGroupPath:",t);return}}getDocumentPath({feature:e,properties:t,defaultDocumentPaths:r,apiKey:a,useFirestore:s}){try{if(!a)return;let{documentId:c,organizationId:p}=t;p||(p=r?.organizationId);let u=new Ud({apiKey:a,documentId:c?`${c}`:"",organizationId:p?`${p}`:""});switch(e){case"userConfig":return t?.userId&&t?.documentId&&u?.userConfig?`${u?.userConfig}/${t?.userId}/${j.FIREBASE_PARTIAL_PATH_DOCUMENT_CONFIGURATIONS}/${t?.documentId}`:void 0;case"allComments":return!s&&t?.documentId&&u?.comment?`${u?.comment}`:void 0;case"allGlobalContacts":return t?.documentId&&u?.globalContacts?`${u?.globalContacts}`:void 0;case"globalContacts":return t?.documentId&&t?.userId&&u?.globalContacts?`${u?.globalContacts}${t?.userId}`:void 0;case"groupContacts":return t?.documentId&&t?.groupId&&u?.groupContacts?`${u?.groupContacts}${t?.groupId}`:void 0;case"groupContactsUser":return t?.documentId&&t?.groupId&&t?.userId&&u?.groupContacts?`${u?.groupContacts}${t?.groupId}/${t?.userId}`:void 0;case"allLoginContacts":return t?.documentId&&t?.userId&&u?.logins?`${u?.logins}${t?.userId}/contacts`:void 0;case"allLogins":return t?.documentId&&u?.logins?`${u?.logins}`:void 0;case"logins":return t?.documentId&&t?.userId&&u?.logins?`${u?.logins}${t?.userId}`:void 0;case"customerMetadata":return u?.customerMetadata?`${u?.customerMetadata}`:void 0;case"allArrows":return t?.documentId&&u?.arrow?`${u?.arrow}`:void 0;case"arrow":return t?.documentId&&u?.arrow&&t.id?`${u?.arrow}${t.id}`:void 0;case"allCursors":return t?.documentId&&u?.cursor?`${u?.cursor}`:void 0;case"cursor":return t?.documentId&&u?.cursor&&t.id?`${u?.cursor}${t.id}`:void 0;case"flockUser":return t?.documentId&&u?.flock&&t.id?`${u?.flock}users/${t.id}`:void 0;case"flockSession":return t?.documentId&&u?.flock&&t.id?`${u?.flock}sessions/${t.id}`:void 0;case"allHuddleAttendees":return t?.documentId&&u?.huddle?`${u?.huddle}attendees`:void 0;case"huddleAttendee":return t?.documentId&&u?.huddle&&t.id?`${u?.huddle}attendees/${t.id}`:void 0;case"huddleAttendeeState":return t?.documentId&&u?.huddle&&t.id?`${u?.huddle}attendees/${t.id}/state`:void 0;case"allHuddleInvitees":return t?.documentId&&u?.huddle?`${u?.huddle}invitees`:void 0;case"huddleConnection":return t?.documentId&&u?.huddle&&t.id?`${u?.huddle}connections/${t.id}`:void 0;case"huddleIceCandidate":return t?.documentId&&u?.huddle&&t.id?`${u?.huddle}iceCandidates/${t.id}`:void 0;case"allHuddleIceCandidates":return t?.documentId&&u?.huddle?`${u?.huddle}iceCandidates`:void 0;case"allHuddleMessages":return t?.documentId&&u?.huddle?`${u?.huddle}messages`:void 0;case"huddleMessage":return t?.documentId&&u?.huddle&&t.id?`${u?.huddle}messages/${t.id}`:void 0;case"allLiveStates":return t?.documentId&&u?.liveState?`${u?.liveState}`:void 0;case"allLiveStateCustoms":return t?.documentId&&u?.liveState?`${u?.liveState}custom`:void 0;case"liveStateCustom":return t?.documentId&&u?.liveState&&t?.id?`${u?.liveState}custom/${t.id}`:void 0;case"liveStateSingleEditorMode":return t?.documentId&&u?.liveStateSingleEditorMode?`${u?.liveStateSingleEditorMode}`:void 0;case"liveStateAutoSyncStateCurrent":return t?.documentId&&u?.liveState?`${u?.liveState}default/autoSyncState/current`:void 0;case"liveStateAutoSyncStateHistoryId":return t?.documentId&&u?.liveState&&t?.id?`${u?.liveState}default/autoSyncState/history/${t.id}`:void 0;case"presence":return t?.documentId&&u?.presence&&t?.userId?`${u?.presence}${t?.userId}`:void 0;case"allPresence":return t?.documentId&&u?.presence?`${u?.presence}`:void 0;case"workspaceIam":return u?.workspaceIam?`${u?.workspaceIam}`:void 0;case"selection":return t?.documentId&&u?.selection&&t?.userId?`${u?.selection}${t?.userId}`:void 0;case"allSelections":return t?.documentId&&u?.selection?`${u?.selection}`:void 0;case"syncVideoPlayer":return t?.documentId&&u?.syncVideoPlayer?`${u?.syncVideoPlayer}`:void 0;case"allTags":return t?.documentId&&u?.tag?`${u?.tag}`:void 0;case"tag":return t?.documentId&&u?.tag&&t?.id?`${u?.tag}${t?.id}`:void 0;case"userContactUs":return t?.documentId&&u?.userContactUs?`${u?.userContactUs}`:void 0;case"userFeedback":return t?.documentId&&u?.userFeedback?`${u?.userFeedback}`:void 0;case"userReportBug":return t?.documentId&&u?.userReportBugs?`${u?.userReportBugs}`:void 0;case"comment":return!s&&t?.documentId&&t?.id&&u?.comment?`${u?.comment}${t?.id}`:void 0;case"allMultiThreads":return!s&&t?.documentId&&u?.multiThread?`${u?.multiThread}`:void 0;case"crdt":return!s&&t?.documentId&&u?.crdt?`${u?.crdt}`:void 0;case"crdtData":return t?.documentId&&u?.crdt&&t?.id?`${u?.crdt}/${t?.id}/data`:void 0;case"crdtSyncState":return t?.documentId&&u?.crdt&&t?.id?`${u?.crdt}/${t?.id}/sync/state`:void 0;case"crdtSyncPresence":return t?.documentId&&t.userId&&u?.crdt&&t?.id?`${u?.crdt}/${t?.id}/sync/presence/${t.userId}`:void 0;case"allCrdtSyncPresence":return t?.documentId&&u?.crdt&&t?.id?`${u?.crdt}/${t?.id}/sync/presence`:void 0;case"crdtPresence":return t?.documentId&&t.userId&&u?.crdt&&t?.id?`${u?.crdt}/${t?.id}/presence/${t.userId}`:void 0;case"allCrdtPresence":return t?.documentId&&u?.crdt&&t?.id?`${u?.crdt}/${t?.id}/presence`:void 0;case"crdtVersion":return t?.documentId&&u?.crdt&&t?.id&&t?.versionId?`${u?.crdt}/${t?.id}/versions/${t?.versionId}`:void 0;case"crdtVersions":return t?.documentId&&u?.crdt&&t?.id?`${u?.crdt}/${t?.id}/versions`:void 0;case"multiThread":return!s&&t?.documentId&&t?.id&&u?.multiThread?`${u?.multiThread}${t?.id}`:void 0;case"allLastNotificationTimestamp":return!s&&u?.organizationNotificationsLastNotificationTimestamp?`${u?.organizationNotificationsLastNotificationTimestamp}`:void 0;case"lastNotificationTimestamp":return!s&&t?.id&&u?.organizationNotificationsLastNotificationTimestamp?`${u?.organizationNotificationsLastNotificationTimestamp}${t?.id}`:void 0;case"documentIam":return!s&&t?.documentId&&u?.documentIam?`${u?.documentIam}`:void 0;case"documentMetadata":return!s&&t?.documentId&&u?.metadata?`${u?.metadata}`:void 0;case"allDocuments":return!s&&u?.docs&&t?.documentId?`${u?.docs}/${t?.documentId}/${j.FIREBASE_PARTIAL_PATH_METADATA}`:void 0;case"allAreas":return!s&&t?.documentId&&u?.area?`${u?.area}`:void 0;case"area":return!s&&t?.id&&u?.area?`${u?.area}${t?.id}`:void 0;case"folder":return!s&&t?.folderId&&u?.folder?`${u?.folder}${t?.folderId}`:void 0;case"documentUserAccess":return!s&&t?.id&&u?.documentIam?`${u?.documentIam}users/${t?.id}`:void 0;case"documentUser":return!s&&t?.documentId&&t?.id&&u?.documentIam?`${u?.documentIam}users/${t?.id}`:void 0;case"allDocumentUsers":return!s&&t?.documentId&&u?.documentIam?`${u?.documentIam}users/`:void 0;case"allOrganizationGroups":return!s&&u?.organizationGroups?`${u?.organizationGroups}`:void 0;case"allOrganizationUsers":return!s&&u?.organizationIam?`${u?.organizationIam}users/`:void 0;case"reaction":return!s&&t?.id&&u?.reaction?`${u?.reaction}${t?.id}`:void 0;case"allReactions":return!s&&t?.documentId&&u?.reaction?`${u?.reaction}`:void 0;case"recorder":return!s&&t?.documentId&&t?.id&&u?.recorder?`${u?.recorder}${t?.id}`:void 0;case"allRecorders":return!s&&t?.documentId&&u?.recorder?`${u?.recorder}`:void 0;case"organizationMetadata":return!s&&u?.organizationMetadata?`${u?.organizationMetadata}`:void 0;case"documentAccessType":return!s&&u?.documentIam?`${u?.documentIam}`:void 0;case"documentIam":return!s&&u?.documentIam?`${u?.documentIam}`:void 0;case"documentMetadata":return!s&&t?.documentId&&u?.metadata?`${u?.metadata}`:void 0;case"allDocumentViews":return!s&&t?.documentId&&u?.views?`${u?.views}documentViews/`:void 0;case"documentViews":return!s&&t?.documentId&&t?.id&&u?.views?`${u?.views}documentViews/${t?.id}`:void 0;case"allLocationViews":return!s&&t?.documentId&&u?.views?`${u?.views}locationViews/`:void 0;case"notificationViewsTimestamp":return!s&&t?.id&&t?.user&&u?.views?`${u?.views}notification/${t?.id}/views/${t?.user}`:void 0;case"documentUsersViews":return!s&&t?.id&&t?.user&&t?.date&&u?.views?`${u?.views}documentViews/${t?.id}/users/${t?.user}/${t?.date}`:void 0;case"documentMetadataViews":return!s&&t?.id&&u?.views?`${u?.views}documentViews/${t?.id}/metadata`:void 0;case"documentDayViews":return!s&&t?.id&&t?.date&&t?.user&&u?.views?`${u?.views}documentViews/${t?.id}/day/${t?.date}/${t?.user}`:void 0;case"locationViews":return!s&&t?.id&&u?.views?`${u?.views}locationViews/${t?.id}/location`:void 0;case"location":return!s&&t?.id&&u?.views?`${u?.views}locationViews/${t?.id}`:void 0;case"locationUsersViews":return!s&&t?.id&&t?.user&&t?.date&&u?.views?`${u?.views}locationViews/${t?.id}/users/${t?.user}/${t?.date}`:void 0;case"locationMetadataViews":return!s&&t?.id&&u?.views?`${u?.views}locationViews/${t?.id}/metadata`:void 0;case"locationDayViews":return!s&&t?.id&&t?.date&&t?.user&&u?.views?`${u?.views}locationViews/${t?.id}/day/${t?.date}/${t?.user}`:void 0;case"docNotificationViews":case"docNotification":return t?.documentId&&t?.id&&u?.organizationNotificationsWithDocumentId?`${u?.organizationNotificationsWithDocumentId}${t?.id}`:void 0;case"allDocNotifications":return t?.documentId&&u?.organizationNotificationsWithDocumentId?`${u?.organizationNotificationsWithDocumentId}`:void 0;case"allUserNotifications":return t?.userId&&u?.organizationNotificationsUsers?`${u?.organizationNotificationsUsers}${t?.userId}`:void 0;case"userNotificationViews":case"userNotification":return t?.userId&&t?.id&&u?.organizationNotificationsUsers?`${u?.organizationNotificationsUsers}${t?.userId}/${t?.id}`:void 0;case"locationMetadata":return;case"allLocations":return;case"folderMetadata":return;case"allPermissionsUsers":return;default:throw new Error(`Unknown feature: ${e}`)}}catch(c){this.loggingService.catch("Error in CommonDbUtilsService getDocumentPath:",c);return}}resolveAnnotations(r){return Q(this,arguments,function*({data:e,feature:t}){try{if(e&&e?.length>0)switch(t){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: ${t}`,a)}})}formatResponse(c){return Q(this,arguments,function*({feature:e,data:t,shouldAwait:r=!1,forceResolve:a=!1,shouldCommentAnnotationsResolverAwait:s=!1}){try{if(this.usersService.userDataProviderAvailable()){let p=[];switch(e){case"allAreas":{t&&typeof t=="object"&&!Array.isArray(t)&&(p=this.areaUtilsService.getUserIdsToResolveFromAreaAnnotations(Object.values(t)));break}case"allArrows":{t&&typeof t=="object"&&!Array.isArray(t)&&(p=this.arrowUtilsService.getUserIdsToResolveFromArrowAnnotations(Object.values(t)));break}case"allCursors":{t&&typeof t=="object"&&!Array.isArray(t)&&(p=this.cursorUtilsService.getUserIdsToResolveFromCursorUsers(Object.values(t)));break}case"allComments":{t&&typeof t=="object"&&!Array.isArray(t)&&(p=this.commentUtilsService.getUserIdsToResolveFromComments(Object.values(t)));break}case"allDocumentUsers":{t&&typeof t=="object"&&!Array.isArray(t)&&(p=this.contactUtilsService.getUserIdsToResolveFromUserIamData(Object.values(t)));break}case"allFolderUsers":{t&&typeof t=="object"&&!Array.isArray(t)&&(p=this.contactUtilsService.getUserIdsToResolveFromUserIamData(Object.values(t)));break}case"allOrganizationUsers":{t&&typeof t=="object"&&!Array.isArray(t)&&(p=this.contactUtilsService.getUserIdsToResolveFromUserIamData(Object.values(t)));break}case"allMultiThreads":{t&&typeof t=="object"&&!Array.isArray(t)&&(p=this.multiThreadUtilsService.getUserIdsToResolveFromMultiThreads(Object.values(t)));break}case"allDocNotifications":{t&&typeof t=="object"&&(p=this.notificationUtilsService.getUserIdsToResolveFromNotifications(Array.isArray(t)?t:Object.values(t)));break}case"allUserNotifications":{t&&typeof t=="object"&&!Array.isArray(t)&&(p=this.notificationUtilsService.getUserIdsToResolveFromNotifications(Object.values(t)));break}case"allPresence":{t&&typeof t=="object"&&!Array.isArray(t)&&(p=this.presenceUtilsService.getUserIdsToResolveFromPresenceUsers(Object.values(t)));break}case"allRecorders":{t&&typeof t=="object"&&!Array.isArray(t)&&(p=this.recorderUtilsService.getUserIdsToResolveFromRecorders(Object.values(t)));break}case"allReactions":{t&&typeof t=="object"&&!Array.isArray(t)&&(p=this.reactionUtilsService.getUserIdsToResolveFromReactions(Object.values(t)));break}case"allTags":{t&&typeof t=="object"&&!Array.isArray(t)&&(p=this.tagUtilsService.getUserIdsToResolveFromTags(Object.values(t)));break}case"allHuddleAttendees":{t&&typeof t=="object"&&!Array.isArray(t)&&(p=this.huddleUtilsService.getUserIdsToResolveFromHuddleAttendees(Object.values(t)));break}case"liveStateCustom":{t&&typeof t=="object"&&!Array.isArray(t)&&(p=this.liveStateUtilsService.getUserIdsToResolveFromLiveStateCustom(t));break}case"allLiveStateCustoms":{t&&typeof t=="object"&&!Array.isArray(t)&&(p=this.liveStateUtilsService.getUserIdsToResolveFromLiveStateCustoms(Object.values(t)));break}case"allLiveStates":{t&&typeof t=="object"&&(p=this.liveStateUtilsService.getUserIdsToResolveFromLiveStates(t));break}case"allSelections":{t&&typeof t=="object"&&!Array.isArray(t)&&(p=this.selectionUtilsService.getUserIdsToResolveFromSelections(Object.values(t)));break}default:p=[]}p?.length&&(r?yield this.usersService.resolveUsers({userIds:p,forceResolve:a,feature:e}):this.usersService.resolveUsers({userIds:p,forceResolve:a,feature:e}))}if(this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable()){let p=[];switch(e){case"allDocNotifications":{if(t&&typeof t=="object"){let u=this.notificationUtilsService.getTargetAnnotationIdsFromNotifications(t);p=[...p,...u],p=p.filter(C=>!this.commentAnnotationsResolverService.getCommentAnnotationById(C))}break}case"allUserNotifications":{if(t&&typeof t=="object"&&!Array.isArray(t)){let u=this.notificationUtilsService.getTargetAnnotationIdsFromNotifications(t);p=[...p,...u],p=p.filter(C=>!this.commentAnnotationsResolverService.getCommentAnnotationById(C))}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 t}catch(p){return this.loggingService.catch("Error in CommonDbUtilsService formatResponse:",p),t}})}mergeCommentAnnotationsWithData({data:e,feature:t}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeCommentAnnotationsWithData","color: green;"),this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())switch(t){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:t}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeReactionAnnotationsWithData","color: green;"),this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable())switch(t){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:t,locationMetadata:r}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeLocationMetadataWithData","color: green;"),r&&typeof r=="object"&&!Array.isArray(r))switch(t){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:t}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeUsersWithData","color: green;"),this.usersService.userDataProviderAvailable())switch(e){case"allAreas":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((r,[a,s])=>(r[a]=this.areaUtilsService.mergeAreaWithUser(s),r),{}):t;case"allArrows":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((r,[a,s])=>(r[a]=this.arrowUtilsService.mergeArrowWithUser(s),r),{}):t;case"allCursors":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((r,[a,s])=>(r[a]=this.cursorUtilsService.mergeCursorUserWithUser(s),r),{}):t;case"allComments":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((r,[a,s])=>(r[a]=this.commentUtilsService.mergeCommentWithUser(s),r),{}):t;case"allDocumentUsers":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((r,[a,s])=>(r[a]=this.contactUtilsService.mergeUserIamWithUser(s),r),{}):t;case"allFolderUsers":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((r,[a,s])=>(r[a]=this.contactUtilsService.mergeUserIamWithUser(s),r),{}):t;case"allOrganizationUsers":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((r,[a,s])=>(r[a]=this.contactUtilsService.mergeUserIamWithUser(s),r),{}):t;case"allMultiThreads":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((r,[a,s])=>(r[a]=this.multiThreadUtilsService.mergeMultiThreadWithUser(s),r),{}):t;case"allDocNotifications":return t&&typeof t=="object"?t?.map(r=>this.notificationUtilsService.mergeNotificationWithUser(r)):t;case"allUserNotifications":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((r,[a,s])=>(r[a]=this.notificationUtilsService.mergeNotificationWithUser(s),r),{}):t;case"allPresence":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((r,[a,s])=>(r[a]=this.presenceUtilsService.mergePresenceUserWithUser(s),r),{}):t;case"allRecorders":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((r,[a,s])=>(r[a]=this.recorderUtilsService.mergeRecorderWithUser(s),r),{}):t;case"allReactions":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((r,[a,s])=>(r[a]=this.reactionUtilsService.mergeReactionWithUser(s),r),{}):t;case"allTags":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((r,[a,s])=>(r[a]=this.tagUtilsService.mergeTagWithUser(s),r),{}):t;case"allHuddleAttendees":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((r,[a,s])=>(r[a]=this.huddleUtilsService.mergeHuddleAttendeeWithUser(s),r),{}):t;case"liveStateCustom":return t&&typeof t=="object"&&!Array.isArray(t)?this.liveStateUtilsService.mergeLiveStateCustomWithUser(t):t;case"allLiveStateCustoms":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((r,[a,s])=>(r[a]=this.liveStateUtilsService.mergeLiveStateCustomWithUser(s),r),{}):t;case"allLiveStates":return t&&typeof t=="object"?this.liveStateUtilsService.mergeLiveStateWithUser(t):t;case"allSelections":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((r,[a,s])=>(r[a]=this.selectionUtilsService.mergeSelectionWithUser(s),r),{}):t;default:return t}return t}catch(r){return this.loggingService.catch("Error in CommonDbUtilsService mergeUsersWithData:",r),t}}mergeCommentAnnotationsWithData$({data:e,feature:t}){try{return this.commentAnnotationsResolverService.getCommentAnnotationsById$().pipe(ce(()=>{let r=this.mergeCommentAnnotationsWithData({data:e?.data??{},feature:t}),a=this.mergeUsersWithData({feature:t,data:r??{}});return typeof a=="object"?{data:JSON.parse(JSON.stringify(a)),operation:e?.operation??null}:{data:a,operation:e?.operation??null}}),Et(mn))}catch(r){return this.loggingService.catch("Error in mergeCommentAnnotationsWithData:",r),se(e)}}mergeReactionAnnotationsWithData$({data:e,feature:t}){try{return this.reactionAnnotationsResolverService.getReactionAnnotationsById$().pipe(ce(()=>{let r=this.mergeReactionAnnotationsWithData({data:e?.data??{},feature:t}),a=this.mergeUsersWithData({feature:t,data:r??{}});return typeof a=="object"?{data:JSON.parse(JSON.stringify(a)),operation:e?.operation??null}:{data:a,operation:e?.operation??null}}),Et(mn))}catch(r){return this.loggingService.catch("Error in mergeReactionAnnotationsWithData:",r),se(e)}}mergeUsersWithData$({feature:e,data:t}){try{return this.usersService.getUserById$().pipe(ce(()=>{let r=this.mergeUsersWithData({feature:e,data:t?.data??{}});return typeof r=="object"?{data:JSON.parse(JSON.stringify(r)),operation:t?.operation??null}:{data:r,operation:t?.operation??null}}),Et(mn))}catch(r){return this.loggingService.catch(`Error in mergeUsersWithData for ${e}:`,r),se(t)}}mergeLocationMetadataWithData$({data:e,feature:t}){try{return this.docService.getLocationMetadata$().pipe(ce(r=>{let a=this.mergeLocationMetadataWithData({data:e?.data??{},feature:t,locationMetadata:r});return typeof a=="object"?{data:JSON.parse(JSON.stringify(a)),operation:e?.operation??null}:{data:a,operation:e?.operation??null}}),Et(mn))}catch(r){return this.loggingService.catch(`Error in mergeLocationMetadataWithData for ${t}:`,r),se(e)}}handleDataStripping({feature:e,data:t,actionType:r}){try{switch(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: handleDataStripping","color: green;"),e){case"comment":return this.commentUtilsService.stripCommentAnnotationData({data:t,actionType:r});case"reaction":return this.reactionUtilsService.stripReactionAnnotationData(t);default:return{originalData:t,strippedData:null}}}catch(a){return this.loggingService.catch("Error in CommonDbUtilsService handleDataStripping:",a),{originalData:t,strippedData:null}}}formatData({feature:e,data:t,properties:r,offset:a,isRealtimeDb:s}){try{this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: formatData","color: green;"),typeof t=="object"&&(t=JSON.parse(JSON.stringify(t)));let c=new Date().getTime()+a;switch(e){case"documentAccessType":return delete t?.users,{docIamConfig:t};case"organizationMetadata":case"documentMetadata":return s?t:{metadata:t};case"documentCommentMetadata":return t;case"cursor":return this.cursorUtilsService.formatCursorUserData(t);case"comment":return this.commentUtilsService.formatCommentData(t);case"area":return this.areaUtilsService.formatAreaData(t);case"arrow":return this.arrowUtilsService.formatArrowData(t);case"liveStateCustom":return this.liveStateUtilsService.formatLiveStateCustomData(t);case"liveStateSingleEditorMode":return this.liveStateUtilsService.formatLiveStateSingleEditorModeData(t);case"multiThread":return this.multiThreadUtilsService.formatMultiThreadData(t);case"reaction":return this.reactionUtilsService.formatReactionData(t);case"recorder":return this.recorderUtilsService.formatRecorderData(t,c);case"notificationViewsTimestamp":return{views:{[r.user??""]:t}};case"documentUsersViews":return s?t:{users:{[r.user??""]:{[r.date??""]:t}}};case"documentDayViews":return s?t:{day:{[r.date??""]:{[r.user??""]:t}}};case"documentMetadataViews":return s?t:{metadata:t};case"huddleMessage":return this.huddleUtilsService.formatHuddleMessageData(t);case"locationMetadataViews":return s?t:{metadata:t};case"locationUsersViews":return s?t:{users:{[r.user??""]:{[r.date??""]:t}}};case"locationDayViews":return s?t:{day:{[r.date??""]:{[r.user??""]:t}}};case"locationViews":return s?t:{location:t};case"docNotificationViews":return s?t:{views:t.views};case"userNotificationViews":return s?t:{views:t.views};case"presence":return this.presenceUtilsService.formatPresenceUserData(t);case"selection":return this.selectionUtilsService.formatSelectionData(t);case"tag":return this.tagUtilsService.formatTagData(t);default:return t}}catch(c){return this.loggingService.catch("Error in CommonDbUtilsService formatData:",c),t}}modifyAndSetData(s){return Q(this,arguments,function*({feature:e,data:t,subscriber:r,operation:a=null}){try{let c=yield this.modifyData({feature:e,data:t});r.next({data:c,operation:a})}catch(c){this.loggingService.catch("Error in CommonDbUtilsService modifyAndSetData:",c)}})}isDataAlreadyProcessedInLocalCache({feature:e,change:t,cache:r}){try{if(e==="allReactions"||e==="allComments"){if(t.type==="removed")return!Object.keys(r??{}).includes(t.doc.id);if(r?.[t.doc.id]){let a=t.doc.data(),s=r?.[t.doc.id];return a?.lastUpdated===s?.lastUpdated}}return!1}catch(a){return this.loggingService.catch("Error in CommonDbUtilsService isDataAlreadyProcessedInLocalCache:",a),!1}}modifyData(r){return Q(this,arguments,function*({feature:e,data:t}){try{return yield this.formatResponse({feature:e,data:t})}catch(a){return this.loggingService.catch("Error in CommonDbUtilsService modifyData:",a),t}})}addMetadata(e,t){try{return e&&typeof e=="object"&&!Array.isArray(e)?T(I({},e),{metadata:e?.metadata??{documentId:t?.documentId,organizationId:t?.organizationId,apiKey:t?.apiKey}}):e}catch(r){return this.loggingService.catch("Error in CommonDbUtilsService addMetadata:",r),e}}setDataInLocal(p){return Q(this,arguments,function*({feature:e,data:t,observablesCache:r,eventType:a,id:s,operation:c=null}){try{let C={comment:"allComments",reaction:"allReactions"}[e];if(!C)return null;let E=t?.metadata?.documentId,D=t?.metadata?.veltFolderId;return Object.keys(r).filter(L=>L.includes(C)&&(!E||L.includes(E)||D&&L.includes(D))).forEach(L=>{let z=r[L]?.subject?.getValue()??{};a==="DELETE"?s&&z?.data?.[s]&&(delete z?.data?.[s],r[L]?.subject&&r[L].subject.next({data:z?.data,operation:c})):r[L]?.subject?.next({data:T(I({},z?.data),{[t?.annotationId]:t}),operation:c})}),null}catch(u){return this.loggingService.catch("Error in CommonDbUtilsService setDataInLocal:",u),null}})}handleCommentEncryption(c){return Q(this,arguments,function*({data:e,firestorePath:t,extraData:r,eventType:a,metadata:s}){try{return yield this.commentUtilsService.handleCommentEncryption({data:e,firestorePath:t,extraData:r,eventType:a,metadata:s})}catch(p){return this.loggingService.catch("Error in CommonDbUtilsService handleCommentEncryption:",p),e}})}handleReactionEncryption(a){return Q(this,arguments,function*({data:e,firestorePath:t,eventType:r}){try{return yield this.reactionUtilsService.handleReactionEncryption({data:e,firestorePath:t,eventType:r})}catch(s){return this.loggingService.catch("Error in CommonDbUtilsService handleReactionEncryption:",s),e}})}rtdbDefaultTransactionCallback(e,t){try{let r=I({},e||{});return Object.entries(t).forEach(([a,s])=>{s==null?delete r[a]:r[a]=s}),r}catch(r){return this.loggingService.catch("Error in CommonDbUtilsService rtdbDefaultTransactionCallback:",r),e}}};o.\u0275fac=function(t){return new(t||o)(ee(Rce),ee(Nce),ee(f0),ee(Fce),ee(Lce),ee(Mk),ee(kk),ee(y),ee(Uce),ee(Rk),ee($ce),ee(Hce),ee(v0),ee(zce),ee(Gce),ee(Vn),ee(at),ee(Rs),ee(jd))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var Wce=(()=>{let o=class o{constructor(e,t,r){this.configService=e,this.authService=t,this.loggingService=r,this.firestore$=new ve(null);try{Sn([this.authService.getFirebaseConfig$(),this.configService.getApiKey$()]).pipe(Le(([a,s])=>!!a&&!!s),st(1)).subscribe(([a,s])=>{a&&s&&a?.firebaseOptions?.storeDbId&&this.firestore$.next(ik(og.getFirestoreProdDbName(s,a.firebaseOptions)))},a=>{})}catch{}}getFirestore(){return this.firestore$.asObservable()}getFirestoreValue(){return this.firestore$.value}generateFirestoreDocumentId(){try{let e=this.getFirestoreValue()||ik("DocumentIdDb");if(e){let t=_b(e,"generateDocumentId");return l0(t).id}return}catch(e){this.loggingService.catch("Error in FirestoreService generateFirestoreDocumentId: ",e);return}}};o.\u0275fac=function(t){return new(t||o)(ee(Ft),ee(Ve),ee(y))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var pn=(()=>{let o=class o{constructor(e,t,r,a,s,c,p,u,C,E){this.authService=e,this.commonDbUtilsService=t,this.loggingService=r,this.firestoreService=a,this.databaseService=s,this.configService=c,this.docService=p,this.usersService=u,this.commentAnnotationsResolverService=C,this.reactionAnnotationsResolverService=E,this.offset=0,this.db=null,this.firestore=null,this.subscriptions=[],this.offsetListener=null,this.observablesCache={},this.firestoreSubscriptions={},this.rtdbSubscriptions={},this.loggingService.log("%c[WB] Creating CLASS: CommonDbService","color: blue;"),this.docService.setCommonDbService(this),this.authService.setCommonDbService(this),this.usersService.setCommonDbService(this),this.subscriptions.push(this.databaseService.getDb().subscribe(D=>{if(D){this.db=D;let L=qi(D,".info/serverTimeOffset");this.offsetListener=Np(L,z=>{let W=z.val();this.offset=W})}})),this.subscriptions.push(this.firestoreService.getFirestore().subscribe(D=>{D&&(this.firestore=D)}))}unsubscribeFromObservables(){try{Object.values(this.firestoreSubscriptions??{}).forEach(e=>{e?.unsubscribe()}),Object.values(this.rtdbSubscriptions??{}).forEach(e=>{e?.unsubscribe()}),Object.entries(this.observablesCache??{}).forEach(([e,t])=>{t?.subject?.complete(),t?.subject?.unsubscribe()}),this.observablesCache={},this.firestoreSubscriptions={},this.rtdbSubscriptions={}}catch(e){this.loggingService.catch("Error in unsubscribeFromObservables:",e)}}ngOnDestroy(){this.subscriptions.forEach(e=>e.unsubscribe()),this.offsetListener&&this.offsetListener(),this.unsubscribeFromObservables()}setupOnDisconnect(e,t){return Q(this,null,function*(){try{if(this.db){let r=qi(this.db,e);return bd(r).update(t)}return Promise.resolve()}catch(r){return this.loggingService.catch("Error in setupOnDisconnect:",r),Promise.resolve()}})}getOffset(){return this.offset}getServerTimestamp(){return new Date().getTime()+this.getOffset()}subscribeToServices(e){Sn([this.databaseService.getDb(),this.firestoreService.getFirestore()]).pipe(Le(([t,r])=>!!t),st(1),dn(([t,r])=>{e({db:t,firestore:r})})).subscribe({error:t=>{this.loggingService.catch("Error in CommonDbService subscription: ",t)}})}performDatabaseOperation(e,t,r,a,s,c){return Q(this,null,function*(){try{if(!t){this.loggingService.warn(`%c[WB] No properties found for ${e}`,"color: red;");return}return this.subscribeToServices(C=>Q(this,[C],function*({db:p,firestore:u}){let E;t?.skipFirestore||(E=this.commonDbUtilsService.getFirestorePath({feature:e,properties:t,documentPaths:this.docService.getDocumentPaths(),apiKey:t.apiKey??this.configService.getApiKey()}));let D=this.commonDbUtilsService.getDocumentPath({feature:e,properties:t,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:t.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 L,z;try{D&&(L=qi(p,`${D}`))}catch{this.loggingService.catch("Error in dbRef")}try{E?.includes("/organizations")&&u&&E&&(z=l0(u,`${E}`))}catch{this.loggingService.catch("Error in docRef")}if(!this.authService.getUser())return;yield r({dbRef:L,firestoreRef:z,data:a,firestorePath:E}),c&&c({firestoreAvailable:!!u})}catch(L){this.loggingService.catch(`Error in ${e} operation: `,L),s&&s(L)}}))}catch(p){this.loggingService.catch("Error in performDatabaseOperation:",p)}})}setData(p){return Q(this,arguments,function*({feature:e,data:t,properties:r,callback:a,errorCallback:s,extraData:c}){try{return this.loggingService.log(`%c[WB] Calling FUNCTION: setData for ${e}`,"color: green;"),this.shouldUseFirestore()&&t?.metadata&&!t?.metadata?.apiKey?void 0:(this.commonDbUtilsService.setDataInLocal({feature:e,data:t,observablesCache:this.observablesCache,operation:null}),this.performDatabaseOperation(e,r,u=>Q(this,null,function*(){if(u.dbRef){let C=this.commonDbUtilsService.formatData({feature:e,data:u.data,properties:r,offset:this.getOffset(),isRealtimeDb:!0});r?.rtdbTransaction?yield Bu(u.dbRef,()=>JSON.parse(JSON.stringify(C))):yield nv(u.dbRef,JSON.parse(JSON.stringify(C)))}try{if(u.firestoreRef&&u.data&&!r?.skipFirestore){let C=this.commonDbUtilsService.formatData({feature:e,data:u.data,properties:r,offset:this.getOffset()});typeof C=="object"&&(C=JSON.parse(JSON.stringify(C)));let{strippedData:E,originalData:D,eventType:L}=this.commonDbUtilsService.handleDataStripping({feature:e,data:C,actionType:c?.actionType});if(e==="comment"){let z=null;E&&(z=yield this.commentAnnotationsResolverService.saveCommentAnnotation({commentAnnotation:E,eventType:L,commentId:c?.targetAnnotationData?.commentId})),D&&(z?.isSuccess||z===null)&&(yield this.commonDbUtilsService.handleCommentEncryption({data:D,firestorePath:u.firestorePath??"",extraData:c,metadata:r?.metadata}))}else if(e==="reaction"){let z=null;E&&(z=yield this.reactionAnnotationsResolverService.saveReactionAnnotation(E)),D&&(z?.isSuccess||z===null)&&(yield this.commonDbUtilsService.handleReactionEncryption({data:D,firestorePath:u.firestorePath??""}))}else e==="recorder"?this.firestore&&(yield hce(this.firestore,z=>Q(this,null,function*(){z.set(u.firestoreRef,C)}))):yield hz(u.firestoreRef,C)}}catch(C){this.authService.getUser()&&this.loggingService.catch(`Error in setData for ${e}`,C)}}),t,s,a))}catch(u){this.loggingService.catch(`Error in setData for ${e}`,u)}})}updateData(p){return Q(this,arguments,function*({feature:e,data:t,properties:r,callback:a,errorCallback:s,extraData:c}){try{return this.loggingService.log(`%c[WB] Calling FUNCTION: updateData for ${e}`,"color: green;"),this.shouldUseFirestore()&&t?.metadata&&!t?.metadata?.apiKey?void 0:(this.commonDbUtilsService.setDataInLocal({feature:e,data:t,observablesCache:this.observablesCache,operation:null}),this.performDatabaseOperation(e,r,u=>Q(this,null,function*(){if(u.dbRef&&!r?.skipRtdb){let C=this.commonDbUtilsService.formatData({feature:e,data:u.data,properties:r,offset:this.getOffset(),isRealtimeDb:!0});r?.rtdbTransaction?yield Bu(u.dbRef,E=>{let D;return r?.rtdbTransactionCallback?D=r.rtdbTransactionCallback(E,C):D=this.commonDbUtilsService.rtdbDefaultTransactionCallback(E,C),JSON.parse(JSON.stringify(D))}):yield H6(u.dbRef,JSON.parse(JSON.stringify(C)))}try{if(u.firestoreRef&&u.data&&!r?.skipFirestore){let C=this.commonDbUtilsService.formatData({feature:e,data:u.data,properties:r,offset:this.getOffset()});typeof C=="object"&&(C=JSON.parse(JSON.stringify(C)));let{strippedData:E,originalData:D,eventType:L}=this.commonDbUtilsService.handleDataStripping({feature:e,data:C,actionType:c?.actionType});if(e==="comment"){let z=null;E&&(z=yield this.commentAnnotationsResolverService.saveCommentAnnotation({commentAnnotation:E,eventType:L,commentId:c?.targetAnnotationData?.commentId})),D&&(z?.isSuccess||z===null)&&(yield this.commonDbUtilsService.handleCommentEncryption({data:D,firestorePath:u.firestorePath??"",extraData:c,metadata:r?.metadata}))}else if(e==="reaction"){let z=null;E&&(z=yield this.reactionAnnotationsResolverService.saveReactionAnnotation(E)),D&&(z?.isSuccess||z===null)&&(yield this.commonDbUtilsService.handleReactionEncryption({data:D,firestorePath:u.firestorePath??""}))}else yield hz(u.firestoreRef,C,{merge:!0})}}catch(C){this.authService.getUser()&&this.loggingService.catch(`Error in updateDoc for ${e}`,C)}}),t,s,a))}catch(u){this.loggingService.catch(`Error in updateData for ${e}`,u)}})}deleteData(s){return Q(this,arguments,function*({feature:e,properties:t,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:t?.id,operation:{type:"removed",ids:[t?.id]}}),this.performDatabaseOperation(e,t,c=>Q(this,null,function*(){c.dbRef&&(yield $6(c.dbRef));try{if(c.firestoreRef&&!t?.skipFirestore)if(e==="comment"){let p=null;p=yield this.commentAnnotationsResolverService.deleteCommentAnnotation(t?.id??""),(p?.isSuccess||p===null)&&(yield this.commonDbUtilsService.handleCommentEncryption({firestorePath:c.firestorePath??"",eventType:"DELETE",metadata:t?.metadata}))}else if(e==="reaction"){let p=null;p=yield this.reactionAnnotationsResolverService.deleteReactionAnnotation(t?.id??""),(p?.isSuccess||p===null)&&(yield this.commonDbUtilsService.handleReactionEncryption({firestorePath:c.firestorePath??"",eventType:"DELETE"}))}else yield dce(c.firestoreRef)}catch(p){this.authService.getUser()&&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 Q(this,arguments,function*({feature:e,properties:t}){try{let a=this.shouldUseFirestore();return!e||!t?(this.loggingService.warn("[WB] Missing required parameters in queryData"),[]):a?yield this.handleFirestoreQuery(e,t):yield this.handleRtdbQuery(e,t)}catch(a){return this.loggingService.catch(`Error in queryData for ${e}`,a),[]}})}handleFirestoreQuery(e,t){return Q(this,null,function*(){try{if(!this.firestore)return this.loggingService.warn("[WB] Firestore not initialized"),[];let r=t?.useCollectionGroup?this.commonDbUtilsService.getFirestoreCollectionGroupPath(e):this.commonDbUtilsService.getFirestorePath({feature:e,properties:t,documentPaths:this.docService.getDocumentPaths(),apiKey:t.apiKey??this.configService.getApiKey()});if(!r)return this.loggingService.warn(`[WB] No firestore path found for ${e}`),[];try{let a=_b(this.firestore,r);t?.useCollectionGroup&&(a=pz(this.firestore,r));let s=t?.firestoreQuery??[],c=uz(a,...s);if(!this.authService.getUser()&&!t?.skipUserCheck)return[];if(t?.getCount){let p=yield pce(c).catch(u=>(this.authService.getUser()&&this.loggingService.catch(`Error in getCountFromServer for ${e}`,u),null));return p?p.data().count:0}else{let p=yield uce(c).catch(E=>(this.authService.getUser()&&this.loggingService.catch(`Error in getDocs for ${e}`,E),null));if(!p)return[];let u=p.docs.map(E=>E.data());return yield this.commonDbUtilsService.modifyData({feature:e,data:u})}}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,t){return Q(this,null,function*(){if(!this.db)return this.loggingService.warn("[WB] Realtime Database not initialized"),[];let r=this.commonDbUtilsService.getDocumentPath({feature:e,properties:t,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:t.apiKey??this.configService.getApiKey()});if(!r)return this.loggingService.warn(`[WB] No database path found for ${e}`),[];try{let a=qi(this.db,r),s=t?.rtdbQuery??[],c=BV(a,...s);if(!this.authService.getUser()&&!t?.skipUserCheck)return[];let p=yield FV(c).catch(C=>(this.authService.getUser()&&this.loggingService.catch(`Error in get for ${e}`,C),null));if(!p)return[];let u=p.val();return u?t?.skipObjectValues?u:Object.values(u??{}):[]}catch(a){return this.loggingService.catch(`Error in RTDB query for ${e}:`,a),[]}})}getData(r){return Q(this,arguments,function*({feature:e,properties:t}){try{let a=this.shouldUseFirestore();if(t?.skipFirestore&&(a=!1),!e||!t)return this.loggingService.warn("[WB] Missing required parameters in getData"),{};if(a&&this.firestore){let s=this.commonDbUtilsService.getFirestorePath({feature:e,properties:t,documentPaths:this.docService.getDocumentPaths(),apiKey:t.apiKey??this.configService.getApiKey()});if(!s)return this.loggingService.warn(`[WB] No firestore path found for ${e}`),{};try{if(!this.authService.getUser())return{};let c=yield gce(l0(this.firestore,s)).catch(u=>(this.authService.getUser()&&this.loggingService.catch(`Error in getDoc for ${e}`,u),this.commonDbUtilsService.getErrorForGetRequests({feature:e,error:u})));if(c){if(c?.errorCode)return c}else return this.loggingService.warn(`[WB] No document found at ${s}`),{};let p=c.data();return t?.field?p?.[t.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:t,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:t.apiKey??this.configService.getApiKey()});if(!s)return this.loggingService.warn(`[WB] No database path found for ${e}`),{};try{if(!this.authService.getUser())return{};let c=yield FV(qi(this.db,s)).catch(u=>(this.authService.getUser()&&this.loggingService.catch(`Error in get for ${e}`,u),this.commonDbUtilsService.getErrorForGetRequests({feature:e,error:u})));if(c){if(c?.errorCode)return c}else return this.loggingService.warn(`[WB] No data found at ${s}`),{};let p=c.val();return t?.field?p?.[t.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:t}){let r=this.shouldUseFirestore();t?.skipFirestore&&(r=!1);let a=`${e}-${JSON.stringify(t)}`;return Sn([this.databaseService.getDb(),this.firestoreService.getFirestore(),this.authService.getUser$().pipe(Le(s=>!!s))]).pipe(Le(([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)),he(([s,c])=>{try{if(r&&c){if(!!!this.observablesCache[a]){this.observablesCache[a]={subject:new ve({}),count:0};let C=this.handleFirestoreListener(e,t,c).subscribe(E=>{this.observablesCache[a]?.subject?.next(E)},E=>this.observablesCache[a]?.subject?.error(E));this.firestoreSubscriptions[a]=C}return new Ut(u=>{let C=this.observablesCache[a]?.subject?.subscribe(E=>u.next(E),E=>u.error(E),()=>u.complete());return this.observablesCache[a].count+=1,()=>{C?.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){if(!!!this.observablesCache[a]){this.observablesCache[a]={subject:new ve({}),count:0};let C=this.handleRealtimeDbListener(e,t,s).subscribe(E=>{this.observablesCache[a]?.subject?.next(E)},E=>this.observablesCache[a]?.subject?.error(E));this.rtdbSubscriptions[a]=C}return new Ut(u=>{let C=this.observablesCache[a]?.subject?.subscribe(E=>u.next(E),E=>u.error(E),()=>u.complete());return this.observablesCache[a].count+=1,()=>{C?.unsubscribe(),this.observablesCache[a]&&(this.observablesCache[a].count-=1,this.observablesCache[a].count<=0&&(this.rtdbSubscriptions[a]?.unsubscribe(),delete this.rtdbSubscriptions?.[a],this.observablesCache[a]?.subject?.complete(),delete this.observablesCache?.[a]))}})}return se({})}catch(p){return this.loggingService.catch(`Error setting up listener for ${e}:`,p),se({})}}),Yg(()=>{this.loggingService.log(`[WB] Cleaning up listener for ${e} and key ${a}`)}))}handleFirestoreListener(e,t,r){let a=t?.useCollectionGroup?this.commonDbUtilsService.getFirestoreCollectionGroupPath(e):this.commonDbUtilsService.getFirestorePath({feature:e,properties:t,documentPaths:this.docService.getDocumentPaths(),apiKey:t.apiKey??this.configService.getApiKey()}),s=`${e}-${JSON.stringify(t)}`;return a?new Ut(c=>{let p=t.isCollection?this.setupCollectionListener(r,a,e,c,t):this.setupDocumentListener(r,a,e,c,t);return()=>{c.complete(),c.unsubscribe(),p(),this.observablesCache[s]?.subject?.complete(),this.observablesCache[s]?.subject?.unsubscribe(),delete this.observablesCache[s]}}).pipe(he(c=>this.commonDbUtilsService.mergeUsersWithData$({feature:e,data:c})),he(c=>["allComments","allUserNotifications"].includes(e)?this.commonDbUtilsService.mergeCommentAnnotationsWithData$({data:c,feature:e}):se(c)),he(c=>["allReactions"].includes(e)?this.commonDbUtilsService.mergeReactionAnnotationsWithData$({data:c,feature:e}):se(c)),Et(mn)):(this.loggingService.warn(`[WB] No firestore path found for ${e} and key ${s}`),se({}))}setupCollectionListener(e,t,r,a,s){let c=`${r}-${JSON.stringify(s)}`,p=_b(e,t);if(s?.useCollectionGroup&&(p=pz(e,t)),s?.useQuery&&s?.firestoreQuery){let E=s?.firestoreQuery??[];p=uz(p,...E)}let u=!0,C=[];return gz(p,E=>{try{let D=JSON.parse(JSON.stringify(this.observablesCache[c]?.subject?.getValue()?.data??{})),L=null,z=!1;E?.docChanges()?.length?E.docChanges().forEach(W=>{["allComments","allReactions"].includes(r)&&!u&&W.type!=="removed"&&C.push(W.doc.id),this.commonDbUtilsService.isDataAlreadyProcessedInLocalCache({feature:r,change:W,cache:this.observablesCache[c]?.subject?.getValue()?.data??{}})||(z=!0,Object.assign(D,this.handleCollectionChange(W,D)),W.type==="removed"&&(L||(L={type:W.type,ids:[]}),L.ids.push(W.doc.id)))}):z=!0,z&&(["allComments","allReactions"].includes(r)&&C?.length&&(this.commonDbUtilsService.resolveAnnotations({data:C,feature:r}),C=[]),this.commonDbUtilsService.modifyAndSetData({feature:r,data:D,subscriber:a,operation:L})),u=!1}catch(D){this.handleListenerError(D,r,a)}},E=>this.handleListenerError(E,r,a))}handleCollectionChange(e,t){switch(e.type){case"added":case"modified":t[e.doc.id]=e.doc.data();break;case"removed":delete t?.[e.doc.id];break}return t}setupDocumentListener(e,t,r,a,s){let c=l0(e,t);return gz(c,p=>{try{let u=p.data()||{};s?.field&&(u=u?.[s?.field]??{}),this.commonDbUtilsService.modifyAndSetData({feature:r,data:u,subscriber:a,operation:null})}catch(u){this.handleListenerError(u,r,a)}},p=>this.handleListenerError(p,r,a))}handleListenerError(e,t,r){this.loggingService.catch(`Firestore listener error for ${t}:`,e),r.error(e)}handleRealtimeDbListener(e,t,r){let a=this.commonDbUtilsService.getDocumentPath({feature:e,properties:t,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:t.apiKey??this.configService.getApiKey()});if(!a)return this.loggingService.warn(`[WB] No database path found for ${e}`),se({});let s=qi(r,a);if(t?.useQuery&&t?.rtdbQuery){let c=t?.rtdbQuery??[];s=BV(s,...c)}return this.objectValFromChildEvents(s,e).pipe(kn(c=>(this.loggingService.catch(`RTDB listener error for ${e}:`,c),se({}))),ce(c=>(c===null&&(c={}),c&&typeof c=="object"?Object.entries(c??{}).reduce((u,[C,E])=>(u[C]=this.commonDbUtilsService.addMetadata(E,t),u),{}):this.commonDbUtilsService.addMetadata(c,t))),he(c=>this.commonDbUtilsService.modifyData({feature:e,data:c})),he(c=>this.usersService.getUserById$().pipe(ce(()=>({data:this.commonDbUtilsService.mergeUsersWithData({feature:e,data:c}),operation:null})))))}objectValFromChildEvents(e,t){return new Ut(r=>{let a={},s=!1,c=null,p=W=>{try{this.loggingService.catch(`Realtime DB listener error for ${t}:`,W),r.error(W)}catch{}},u=W=>{try{if(!wi(W,c)){let J=JSON.parse(JSON.stringify(W));c=J,r.next(J)}}catch{}},C=W=>{try{W.key&&(a[W.key]=W.val(),s&&u(I({},a)))}catch{}},E=W=>{try{W.key&&(a[W.key]=W.val(),s&&u(I({},a)))}catch{}},D=W=>{try{W.key&&(delete a[W.key],s&&u(I({},a)))}catch{}},L=W=>{try{if(!s){let J=a&&typeof a=="object"?JSON.parse(JSON.stringify(a)):{};c=J,r.next(J),s=!0}}catch{}};Mne(e,C,p),kne(e,E,p),Rne(e,D,p);let z=Np(e,L,p,{onlyOnce:!0});return()=>{try{z&&typeof z=="function"&&z(),j6(e,"child_added",C),j6(e,"child_changed",E),j6(e,"child_removed",D)}catch{}}})}};o.\u0275fac=function(t){return new(t||o)(ee(Ve),ee(ag),ee(y),ee(Wce),ee(Dn),ee(Ft),ee(at),ee(Vn),ee(Rs),ee(jd))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var xi=(()=>{let o=class o{constructor(e,t,r,a,s,c,p,u){this.analyticsService=e,this.authService=t,this.configService=r,this.databaseService=a,this.docService=s,this.loggingService=c,this.commonDbService=p,this.usersService=u,this.db=ts(),this.internalUserContacts$=new ve([]),this.userGlobalContact$=new ve(!1),this.userGroupContact$=new ve(null),this.users$=new ve([]),this.userPersonalContacts=[],this.userGroupContacts=[],this.userGlobalContacts=[],this.users=[],this.documentPaths=null,this.userOrganizationContacts$=new ve([]),this.userFolderContacts$=new ve([]),this.userDocumentContacts$=new ve([]),this.userOrganizationGroups$=new ve([]),this.onContactSelectedSubject$=new tt,this.documentAccessType=null,this.atHereEnabled$=new ve(!1),this.atHereLabel$=new ve("here"),this.atHereDescription$=new ve(null),this.contactListScopeForOrganizationUsers$=new ve([Hi.ALL]),this.customUserContacts$=new ve(null),this.customUserContactsConfig$=new ve({merge:!1}),this.currentOrganizationUserIAM$=new ve(null),this.userContacts$=new ve([]),this.userSnippylyIdContacts$=new ve(null),this.usersByOrganizationId$=new ve({}),this.temporaryUserIds$=new ve([]),this.usersByOrganizationIdAndDocumentId$=new ve({}),this.usersByOrganizationIdAndFolderId$=new ve({}),this.userById$=new ve({}),this.authService.setContactService(this),this.authService.getUser$().pipe(he(C=>this.docService.getDocumentPaths$().pipe(dn(E=>{this.documentPaths=E}),ce(()=>C)))).subscribe(C=>Q(this,null,function*(){this.user=C,C&&this.documentPaths?C?.organizationId?(this.getOrganizationContactsFromDb$(),this.getFolderContactsFromDb$(),this.getDocumentContactsFromDb$(),this.getOrganizationGroupsFromDb$(),this.getTemporaryUsers()):(this.getLoggedInUsers$().subscribe(),this.getUserContactsFromDb$(),yield this.migrateLoggedInUserFromEmailToUserIdPath(C),this.setLoggedInUser(C),yield this.moveGlobalContactUserFromEmailToUserIdPath(C),this.updateUserInGlobalContactsIfAvailable(C),C?.groupId&&(yield this.migrateGroupContactsFromEmailToUserIdPath(C?.groupId)),this.checkToSetLoggedInUserInGroupContacts()):(this.getUserContactSubscription?.unsubscribe(),this.getUserContactSubscription=void 0,this.getLoggedInUsersSubscription?.unsubscribe(),this.getLoggedInUsersSubscription=void 0,this.getOrganizationContactsSubscription?.unsubscribe(),this.getOrganizationContactsSubscription=void 0,this.getFolderContactsSubscription?.unsubscribe(),this.getFolderContactsSubscription=void 0,this.getDocumentContactsSubscription?.unsubscribe(),this.getDocumentContactsSubscription=void 0,this.getOrganizationGroupsSubscription?.unsubscribe(),this.getOrganizationGroupsSubscription=void 0)}),C=>{this.loggingService.catch("Error in ContactService constructor getUser$: ",C)}),this.databaseService.getDb().pipe(Le(C=>!!C),st(1)).subscribe(C=>{C&&(this.db=C)},C=>{this.loggingService.catch("Error in ContactService constructor getDb: ",C)}),this.getOrganizationGroups$().subscribe(C=>{this.authService.setOrganizationUserGroups(C)}),Sn([this.getInternalUserContacts$(),this.getCustomUserContacts$(),this.getCustomUserContactsConfig$()]).subscribe(([C,E,D])=>{E?D?.merge?this.userContacts$.next([...C||[],...E||[]]):this.userContacts$.next(E||[]):this.userContacts$.next(C||[])}),this.getUserContacts$().subscribe(C=>{try{C?.forEach(E=>{let D=E?.userSnippylyId||Av(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.temporaryUserIds$.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(t){this.loggingService.catch("Error in ContactService setDocumentAccessType: ",t)}}checkIfUserGlobalContact(e){return Q(this,null,function*(){try{if(e?.userId&&this.documentPaths?.globalContacts){let t=yield this.commonDbService?.getData({feature:"globalContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:bt(e?.userId),skipFirestore:!0}});if(Object.keys(t??{}).length>0)return!0}if(e?.email&&this.documentPaths?.globalContacts){let t=yield this.commonDbService?.getData({feature:"globalContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:bt(e?.email),skipFirestore:!0}});if(Object.keys(t??{}).length>0)return!0}return!1}catch(t){return this.loggingService.catch("Error in ContactService isUserGlobalContact: ",t),!1}})}setLoggedInUser(e){try{e?.userId&&this.documentPaths?.logins&&(this.commonDbService.updateData({feature:"logins",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:bt(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(T(I({},e),{contacts:void 0})))}),this.setLoggedInUserPrivateContacts(e,e?.contacts))}catch(t){this.loggingService.catch("Error in ContactService setLoggedInUser: ",t)}}migrateLoggedInUserFromEmailToUserIdPath(e){return Q(this,null,function*(){try{if(e?.email&&this.documentPaths?.logins){let t=yield this.commonDbService?.getData({feature:"logins",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:bt(e?.email),skipFirestore:!0}});if(Object.keys(t??{}).length>0){let r=t;if(r){if(r?.contacts){let a={};Object.keys(r?.contacts??{})?.forEach(s=>{let c=r.contacts[s];if(c?.userId){let p=bt(c?.userId);a[p]=c}}),r.contacts=a}yield this.commonDbService.updateData({feature:"logins",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:bt(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:bt(e?.email),skipFirestore:!0}})}}}}catch(t){this.loggingService.catch("Error in ContactService migrateLoggedInUserFromEmailToUserIdPath: ",t)}})}addGlobalContact(e){try{e?.userId&&this.documentPaths?.globalContacts&&this.commonDbService.updateData({feature:"globalContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:bt(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(e))})}catch(t){this.loggingService.catch("Error in ContactService addGlobalContact: ",t)}}updateUserInGlobalContactsIfAvailable(e){return Q(this,null,function*(){try{if(e?.userId&&this.documentPaths?.globalContacts&&(yield this.checkIfUserGlobalContact(e))){let r=new Po;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:bt(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(r))})}}catch(t){this.loggingService.catch("Error in ContactService updateUserInGlobalContactsIfAvailable: ",t)}})}moveGlobalContactUserFromEmailToUserIdPath(e){return Q(this,null,function*(){try{if(e?.email&&e?.userId&&this.documentPaths?.globalContacts){let t=yield this.commonDbService?.getData({feature:"globalContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:bt(e?.email),skipFirestore:!0}});if(Object.keys(t??{}).length>0){let r=t;r&&(yield this.commonDbService.updateData({feature:"globalContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:bt(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:bt(e?.email),skipFirestore:!0}}))}}}catch(t){this.loggingService.catch("Error in ContactService removeUserFromGlobalContactsByEmail: ",t)}})}setLoggedInUserPrivateContacts(e,t){try{if(e?.userId&&this.documentPaths?.logins){let r,a=t?.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=bt(c?.userId);r[p]=c}}),s?this.commonDbService.setData({feature:"allLoginContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:bt(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:bt(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:bt(e?.userId),skipFirestore:!0}})}}catch(r){this.loggingService.catch("Error in ContactService setLoggedInUserPrivateContacts: ",r)}}migrateGroupContactsFromEmailToUserIdPath(e){return Q(this,null,function*(){try{if(this.documentPaths?.groupContacts&&e){let t=yield this.commonDbService?.getData({feature:"groupContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",groupId:e,skipFirestore:!0}});t&&Object.keys(t??{}).forEach(r=>Q(this,null,function*(){let a=t[r];a?.email&&a?.userId&&bt(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:bt(a?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(a))}))}))}}catch(t){this.loggingService.catch("Error in ContactService migrateGroupContacts: ",t)}})}checkToSetLoggedInUserInGroupContacts(){return Q(this,null,function*(){try{this.user?.groupId&&this.user?.userId&&((yield this.checkIfUserGlobalContact(this.user))||this.docService.getDocumentIam$().pipe(st(1)).subscribe(t=>Q(this,null,function*(){if(this.user?.groupId&&this.user?.userId){let r=!1,a=this.docService.getDocumentAccessType(t);if(!a||a===yi.PUBLIC)r=!0;else if(a===yi.RESTRICTED){let s=bt(this.user?.userId);if(t?.users?.[s]&&(r=!0),this.user?.email){let c=bt(this.user?.email);t?.users?.[c]&&(r=!0)}}if(r){let s=new ig;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,t){try{let r=t?.filter(a=>a?.visibility==="group");r?.length&&r.forEach(a=>Q(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:bt(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:bt(a?.email),skipFirestore:!0}}))}}))}catch(r){this.loggingService.catch("Error in ContactService setLoggedInUserGroupContacts: ",r)}}removeGroupContacts(e){return Q(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(t){this.loggingService.catch("Error in ContactService removeGroupContacts: ",t)}})}mergeUserContacts(){try{let e=[];this.userPersonalContacts&&e.push(...this.userPersonalContacts),this.userGroupContacts&&e.push(...this.userGroupContacts),this.userGlobalContacts&&e.push(...this.userGlobalContacts);let t={};e.forEach(r=>{r?.userId?(!r?.email||!t[r.email])&&(t[r.userId]=r):r?.email&&(!r?.userId||!t[r.userId])&&(t[r.email]=r)}),e=Object.values(t??{}),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:t,documentId:r,veltFolderId:a}=e||{};return t&&r?Sn([this.usersByOrganizationId$,this.usersByOrganizationIdAndFolderId$,this.usersByOrganizationIdAndDocumentId$,this.userById$,this.customUserContacts$,this.customUserContactsConfig$,this.getContactListScopeForOrganizationUsers$(),this.temporaryUserIds$]).pipe(ce(([s,c,p,u,C,E,D,L])=>{let z={},W=!1;E&&!E?.merge&&(W=!0);let J=Fe=>D.some(xe=>Fe.includes(xe)),ue=J([Hi.ALL,Hi.ORGANIZATION])?Object.keys(s?.[t]||{}):[],ye=a?J([Hi.ALL,Hi.FOLDER])?Object.keys(c?.[t]?.[a]||{}):[]:[],Ae=J([Hi.ALL,Hi.DOCUMENT])?Object.keys(p?.[t]?.[r]||{}):[];if([...ue,...ye||[],...Ae,...L].forEach(Fe=>{let xe=u?.[Fe];xe&&(z[Fe]=xe)}),C){let{merge:Fe,options:xe}=E||{},{organizationId:Se,documentId:we,folderId:_e}=xe||{},fe=_e?Fi(_e):void 0;(!Se||Se===t)&&(!we||we===r)&&(!fe||fe===a)&&(Fe||(z={}),C.forEach(Oe=>{Oe?.userId&&(z[Oe.userId]=Oe)}))}return Object.values(z??{})})):this.userContacts$.asObservable().pipe(ce(s=>s))}catch(t){return this.loggingService.catch("Error in ContactService getUserContacts$ metadata: ",t),se([])}}getUserContactsBySnippylyId$(){return this.userSnippylyIdContacts$.asObservable()}getAtHereLabel(){return this.atHereLabel$.asObservable()}getAtHereDescription(){return this.atHereDescription$.asObservable()}getUserContactsFromDb$(){this.getUserContactSubscription||(this.getUserContactSubscription=this.authService.getUser$().pipe(Le(e=>!!e),he(e=>this.docService.getDocumentPaths$().pipe(Le(t=>!!t),dn(t=>{this.documentPaths=t}),ce(()=>e))),he(e=>{if(this.userGroupContacts=[],this.userPersonalContacts=[],!e)return se();if(!this.documentPaths)return se();let t=[];return t.push(this.commonDbService.dbListener({feature:"allGlobalContacts",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,skipFirestore:!0}}).pipe(ce(r=>r?.data),dn(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))}))),t.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),dn(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))}))),t.push(this.commonDbService.dbListener({feature:"allLoginContacts",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,skipFirestore:!0,userId:bt(e?.userId)}}).pipe(ce(r=>r?.data),dn(r=>{r?this.userPersonalContacts=Object.values(r??{}):this.userPersonalContacts=[]}))),co(...t).pipe(mo(this.authService.getUser$().pipe(Le(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(t){this.loggingService.catch("Error in ContactService addUserContact: ",t)}}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(he(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(t=>t?.data),dn(t=>{t?this.users=Object.values(t??{}):this.users=[]})):(this.users=[],se()):se():se())).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(he(e=>e?.organizationId?this.userById$.pipe(ce(t=>{let r={};return Object.values(t||{}).forEach(a=>{a?.userSnippylyId&&(r[a?.userSnippylyId]=a)}),r})):this.users$.pipe(ce(t=>{let r={};return t.forEach(a=>{r[a.userSnippylyId]=a}),r}))))}getUserByEmail$(e){return this.users$.pipe(ce(t=>t.find(r=>r.email===e)))}getUserByEmail(e){return this.users?.find(t=>t.email===e)}getContactByEmail(e){return this.getInternalUserContacts().find(t=>t.email===e)}getUserByUserId$(e){return this.users$.pipe(ce(t=>t.find(r=>r.userId===e)))}getUserGroupContacts(){return this.userGroupContacts}getTemporaryUsers(){try{let e=this.authService.getUser();this.docService.getOrganizationConfig$().pipe(Le(t=>!!t),ce(t=>t?.organizationId)).subscribe(t=>Q(this,null,function*(){if(t&&e){let r=((yield this.commonDbService?.queryData({feature:"allPermissionsUsers",properties:{organizationId:t,useCollectionGroup:!1,isCollection:!0,firestoreQuery:[lt("expiresAt",">",new Date().getTime())]}}))??[]).filter(a=>a?.userId!==e?.userId);if(r?.length){let a=yield this.usersService.resolveUsers({userIds:r.map(s=>s?.userId)});if(a){let s={};Object.entries(a).forEach(([p,u])=>{s[p]=u}),this.userById$.next(I(I({},this.userById$.value),s));let c=new Set([...this.temporaryUserIds$.value,...Object.keys(s)]);this.temporaryUserIds$.next(Array.from(c))}}}}))}catch(e){this.loggingService.catch("Error in ContactService getTemporaryUsers: ",e)}}getOrganizationContactsFromDb$(){try{this.getOrganizationContactsSubscription||(this.getOrganizationContactsSubscription=this.authService.getUser$().pipe(he(e=>e?.organizationId?se(e).pipe(he(t=>this.docService.getOrganizationConfig$().pipe(Le(r=>!!r),ce(()=>t))),he(t=>this.usersService.getResolveOrganizationUsers$().pipe(Le(r=>r),ce(()=>t))),he(t=>{let r=this.docService.getOrganizationConfig()?.organizationId;return this.setUserOrganizationContacts([],r),t?r?this.commonDbService.dbListener({feature:"allOrganizationUsers",properties:{organizationId:r,isCollection:!0,useQuery:!0,firestoreQuery:[Zn(ak(lt("organizationIds","array-contains-any",[r]),lt("viewerOrganizationIds","array-contains-any",[r]))),fi("id")]}}).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)})):se():se()}),he(()=>this.getContactListScopeForOrganizationUsers$())):(this.setUserOrganizationContacts([]),se()))).subscribe(()=>{this.mergeOrganizationAndDocumentContacts()},e=>{this.loggingService.catch("Error in ContactService getOrganizationContactsFromDb$ subscription: ",e)}))}catch{}}getFolderContactsFromDb$(){try{this.getFolderContactsSubscription||(this.getFolderContactsSubscription=this.authService.getUser$().pipe(he(e=>e?se(e).pipe(he(t=>this.docService.getOrganizationConfig$().pipe(Le(r=>!!r),ce(()=>t))),he(t=>this.usersService.getResolveFolderUsers$().pipe(Le(r=>r),ce(()=>t))),he(t=>{let r=this.docService.getOrganizationConfig()?.organizationId;if(this.setUserFolderContacts([]),!t)return se();if(!this.commonDbService.shouldUseFirestore())return se();if(!this.documentPaths?.veltFolderId)return se();let a=se([]);return a=this.commonDbService.dbListener({feature:"allFolderUsers",properties:{organizationId:r,folderId:this.documentPaths?.veltFolderId,isCollection:!0,useQuery:!0,firestoreQuery:[Zn(ak(lt("folderIds","array-contains-any",[this.documentPaths?.veltFolderId]),lt("viewerFolderIds","array-contains-any",[this.documentPaths?.veltFolderId]))),fi("id")]}}).pipe(ce(s=>s?.data)),a.pipe(ce(s=>{if(s){typeof s=="object"&&(s?.undefined&&delete s.undefined,s?.null&&delete s.null);let c=Object.values(s??{});this.setUserFolderContacts(c)}else this.setUserFolderContacts([])}))}),he(()=>this.getContactListScopeForOrganizationUsers$())):(this.setUserFolderContacts([]),se()))).subscribe(()=>{this.mergeOrganizationAndDocumentContacts()},e=>{this.loggingService.catch("Error in ContactService getFolderContactsFromDb$ subscription: ",e)}))}catch{}}getDocumentContactsFromDb$(){try{this.getDocumentContactsSubscription||(this.getDocumentContactsSubscription=this.authService.getUser$().pipe(he(e=>e?se(e).pipe(he(t=>this.docService.getDocumentPaths$().pipe(Le(r=>!!r),dn(r=>{this.documentPaths=r}),ce(()=>t))),he(t=>this.usersService.getResolveDocumentUsers$().pipe(Le(r=>r),ce(()=>t))),he(t=>(this.setUserDocumentContacts([]),t?this.documentPaths?this.docService.getDocumentIds$().pipe(he(r=>{let a=r?.length>0?r.map(u=>u.documentId):[this.documentPaths?.documentId??""];if(a.some(u=>!u)||!this.documentPaths)return se();let s=se([]),c={isCollection:!0,useQuery:!0};this.commonDbService.shouldUseFirestore()||(c.documentId=a?.length?a[0]:void 0,c.organizationId=this.documentPaths?.organizationId);let p=[];for(let u=0;u<a.length;u+=j.LISTENER_BATCH_SIZE)p.push(a.slice(u,u+j.LISTENER_BATCH_SIZE));return s=Sn(p.map(u=>this.commonDbService.dbListener({feature:"allDocumentUsers",properties:T(I({},c),{firestoreQuery:[Zn(ak(lt("documentIds","array-contains-any",u),lt("viewerDocumentIds","array-contains-any",u))),fi("id")]})}).pipe(da()))).pipe(ce(u=>Ba(u)?.data)),s.pipe(ce(u=>{if(u){typeof u=="object"&&(u?.undefined&&delete u.undefined,u?.null&&delete u.null);let C=Object.values(u??{});this.setUserDocumentContacts(C)}else this.setUserDocumentContacts([])}))})):se():se())),he(()=>this.getContactListScopeForOrganizationUsers$())):(this.setUserDocumentContacts([]),se()))).subscribe(()=>{this.mergeOrganizationAndDocumentContacts()},e=>{this.loggingService.catch("Error in ContactService getDocumentContactsFromDb$ subscription: ",e)}))}catch{}}setUserOrganizationContacts(e,t){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),this.usersService.setUserByIds(a),t){let s={};s[t]={};let c={};e.forEach(p=>{s[t][p.user.userId]=p,c[p.user.userId]=p.user}),this.userById$.next(I(I({},this.userById$.value),c)),this.usersByOrganizationId$.next(T(I({},this.usersByOrganizationId$.value),{[t]:s[t]}))}else this.usersByOrganizationId$.next({})}catch(r){this.loggingService.catch("Error in ContactService setUserOrganizationContacts: ",r)}}getUserOrganizationContacts$(){return this.getContactListScopeForOrganizationUsers$().pipe(he(()=>this.checkContactListScopeForOrganizationUsers([Hi.ALL,Hi.ORGANIZATION])?this.userOrganizationContacts$.asObservable():se([])))}getUserOrganizationContacts(){return this.checkContactListScopeForOrganizationUsers([Hi.ALL,Hi.ORGANIZATION])?this.userOrganizationContacts$.value:[]}setUserFolderContacts(e){try{let t=e?.map(s=>s?.user);this.userFolderContacts$.next(t),this.usersService.setUserByIds(t);let r={},a={};e?.forEach(s=>{let{organizationId:c}=s?.metadata||{};c&&(r[c]||(r[c]={}),s.folderIds?.forEach(p=>{r[c][p]||(r[c][p]={}),r[c][p][s.user.userId]=s,a[s.user.userId]=s.user}))}),this.userById$.next(I(I({},this.userById$.value),a)),this.usersByOrganizationIdAndFolderId$.next(r)}catch(t){this.loggingService.catch("Error in ContactService updateUserFolderContacts: ",t)}}getUserFolderContacts$(){return this.getContactListScopeForOrganizationUsers$().pipe(he(()=>this.checkContactListScopeForOrganizationUsers([Hi.ALL,Hi.FOLDER])?this.userFolderContacts$.asObservable():se([])))}getUserFolderContacts(){return this.checkContactListScopeForOrganizationUsers([Hi.ALL,Hi.FOLDER])?this.userFolderContacts$.value:[]}setUserDocumentContacts(e){try{let t=e?.map(s=>s?.user);this.userDocumentContacts$.next(t),this.usersService.setUserByIds(t);let r={},a={};e?.forEach(s=>{let{organizationId:c}=s?.metadata||{};c&&(r[c]||(r[c]={}),s.documentIds?.forEach(p=>{r[c][p]||(r[c][p]={}),r[c][p][s.user.userId]=s,a[s.user.userId]=s.user}))}),this.userById$.next(I(I({},this.userById$.value),a)),this.usersByOrganizationIdAndDocumentId$.next(r)}catch(t){this.loggingService.catch("Error in ContactService updateUserDocumentContacts: ",t)}}getUserDocumentContacts$(){return this.getContactListScopeForOrganizationUsers$().pipe(he(()=>this.checkContactListScopeForOrganizationUsers([Hi.ALL,Hi.DOCUMENT])?this.userDocumentContacts$.asObservable():se([])))}getUserDocumentContacts(){return this.checkContactListScopeForOrganizationUsers([Hi.ALL,Hi.DOCUMENT])?this.userDocumentContacts$.value:[]}getCurrentOrganizationUserIAM$(){return this.currentOrganizationUserIAM$.asObservable()}getCurrentOrganizationUserIAM(){return this.currentOrganizationUserIAM$.value}mergeOrganizationAndDocumentContacts(){try{let e=[];this.getContactListScopeForOrganizationUsers().includes(Hi.ALL)?e=[...this.getUserOrganizationContacts(),...this.getUserFolderContacts(),...this.getUserDocumentContacts()]:this.getContactListScopeForOrganizationUsers().includes(Hi.ORGANIZATION)?e=[...this.getUserOrganizationContacts()]:this.getContactListScopeForOrganizationUsers().includes(Hi.FOLDER)?e=[...this.getUserFolderContacts()]:this.getContactListScopeForOrganizationUsers().includes(Hi.DOCUMENT)&&(e=[...this.getUserDocumentContacts()]);let t=[...new Map(e.filter(r=>r?.userId).map(r=>[r.userId,r])).values()];this.internalUserContacts$.next(t)}catch(e){this.loggingService.catch("Error in ContactService mergeOrganizationAndDocumentContacts: ",e)}}getOrganizationGroupsFromDb$(){try{this.getOrganizationGroupsSubscription||(this.getOrganizationGroupsSubscription=this.authService.getUser$().pipe(he(e=>e?.organizationId?se(e).pipe(he(t=>this.docService.getOrganizationConfig$().pipe(Le(r=>!!r),ce(()=>t))),he(t=>{if(this.setUserOrganizationGroups([]),!t)return se();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([])})):se()})):(this.setUserOrganizationGroups([]),se()))).subscribe(()=>{},e=>{this.loggingService.catch("Error in ContactService getOrganizationGroupsFromDb$ subscription: ",e)}))}catch{}}setUserOrganizationGroups(e){try{this.userOrganizationGroups$.next(e)}catch(t){this.loggingService.catch("Error in ContactService setUserOrganizationGroups: ",t)}}onContactSelected(e){try{if(e?.userId){let t=!!this.getUserDocumentContacts().find(a=>a.userId===e.userId),r=!!this.getUserOrganizationContacts().find(a=>a.userId===e.userId);switch(this.documentAccessType){case yi.RESTRICTED:if(!t){let a={contact:e,isOrganizationContact:r,isDocumentContact:t,documentAccessType:this.documentAccessType};this.onContactSelectedSubject$.next(a)}break}}else{let t={contact:e,isOrganizationContact:!1,isDocumentContact:!1,documentAccessType:this.documentAccessType};this.onContactSelectedSubject$.next(t)}}catch(t){this.loggingService.catch("Error in ContactService onContactSelected: ",t)}}onContactSelected$(){return this.onContactSelectedSubject$.asObservable()}getOrganizationGroups$(){return this.getContactListScopeForOrganizationUsers$().pipe(he(()=>this.checkContactListScopeForOrganizationUsers([Hi.ALL,Hi.ORGANIZATION_USER_GROUP])?this.userOrganizationGroups$.asObservable():se([])))}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(t){this.loggingService.catch("Error in ContactService setAtHereLabel: ",t)}}setAtHereDescription(e){try{this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{atHereDescription:e}}),e&&this.atHereDescription$.next(e)}catch(t){this.loggingService.catch("Error in ContactService setAtHereDescription: ",t)}}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(he(()=>this.checkContactListScopeForOrganizationUsers([Hi.ALL,Hi.DOCUMENT])?this.atHereEnabled$.asObservable():se(!1)))}getAtHereEnabled(){return this.checkContactListScopeForOrganizationUsers([Hi.ALL,Hi.DOCUMENT])?this.atHereEnabled$.value:!1}updateContactListScopeForOrganizationUsers(e){try{this.contactListScopeForOrganizationUsers$.next(e)}catch(t){this.loggingService.catch("Error in ContactService updateContactListScopeForOrganizationUsers: ",t)}}getContactListScopeForOrganizationUsers$(){return this.contactListScopeForOrganizationUsers$.asObservable()}getContactListScopeForOrganizationUsers(){return this.contactListScopeForOrganizationUsers$.value}checkContactListScopeForOrganizationUsers(e){return this.getContactListScopeForOrganizationUsers().some(t=>e.includes(t))}updateContactList(e,t){return Q(this,null,function*(){try{if(this.analyticsService.trackEvent(Z.Events.Contact.UPDATE_CONTACT_LIST_TRIGGERED,{contactsCount:e?.length,config:t}),this.usersService?.userDataProviderAvailable()){let r=e.map(s=>s?.userId).filter(s=>s);yield this.usersService.resolveUsers({userIds: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(t)}catch(r){this.loggingService.catch("Error in CommentService updateContactList: ",r)}})}convert(e){try{if(e?.options){let{documentId:t,organizationId:r}=this.docService.getServerId(e?.options);e.options=T(I({},e?.options),{documentId:t,organizationId:r})}return this}catch(t){return this.loggingService.catch("Error in ContactService convert: ",t),this}}getContactList$(){try{return this.authService.getUser$().pipe(he(e=>e?Sn([this.userOrganizationContacts$.asObservable(),this.userFolderContacts$.asObservable(),this.userDocumentContacts$.asObservable(),this.userOrganizationGroups$.asObservable(),this.customUserContacts$.asObservable()]).pipe(ce(([t,r,a,s,c])=>{let p={};p.organizationUsers=t?.map(C=>this.convertToClientUser(C)),p.folderUsers=r?.map(C=>this.convertToClientUser(C)),p.documentUsers=a?.map(C=>this.convertToClientUser(C)),p.updatedContactList=c?.map(C=>this.convertToClientUser(C));let u=[];return s?.forEach(C=>{let E=this.convertToClientUserGroup(C,p.organizationUsers||[]);E&&u.push(E)}),p.userGroups=u,p}),Et(mn)):se(null)),kn(e=>(this.loggingService.catch("Error in ContactService getContactList$: ",e),se(null))))}catch(e){return this.loggingService.catch("Error in ContactService getContactList$: ",e),se(null)}}convertToClientUserGroup(e,t){try{let r={groupId:e?.metadata?.clientGroupId,groupName:e?.metadata?.groupName,users:[]},a={};return t?.forEach(s=>{if(s?.userId){let c=bt(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(t){return this.loggingService.catch("Error in ContactService convertToClientUser: ",t),e}}getCustomUserContacts(){return this.customUserContacts$.value}getCustomUserContacts$(){return this.customUserContacts$.asObservable()}getCustomUserContactsConfig(){return this.customUserContactsConfig$.value}getCustomUserContactsConfig$(){return this.customUserContactsConfig$.asObservable()}};o.\u0275fac=function(t){return new(t||o)(ee(et),ee(Ve),ee(Ft),ee(Dn),ee(at),ee(y),ee(pn),ee(Vn))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var qce=i=>{try{return i.name.split(".").slice(0,-1).join(".")}catch(o){ot.catch("Error in File utils getFileName: ",o);return}},Dz=i=>{try{return/(?:\.([^.]+))?$/.exec(i?.name)[1]}catch(o){ot.catch("Error in File utils getFileExtension: ",o);return}},Yce=(i,o)=>{try{let n=i.slice(0,-1,i.type);return new File([n],o+"."+Dz(i),{type:i.type})}catch(n){ot.catch("Error in File utils updateFile: ",n);return}},Kce=i=>new Promise((o,n)=>{let e=new FileReader;e.readAsDataURL(i),e.onload=()=>{o(e.result)},e.onerror=t=>{n(t)}}),Zce={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 sg=(()=>{let o=class o{constructor(e,t,r,a){this.authService=e,this.configService=t,this.loggingService=r,this.attachmentResolverService=a,this.storage=mS();try{this.configService.getApiKey$().subscribe(s=>{this.apiKey=s}),this.authService.getFirebaseConfig$().subscribe(s=>{s&&s.firebaseOptions?.storageBucket&&(this.storage=mS(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:t}){try{let r=new d0;r.name=t.name;let a=Yce(t,`${r.attachmentId}_${qce(t)}`),s=`${this.apiKey}/${e}/${a?.name}`;return r.bucketPath=s,r.size=t.size,r.type=Dz(t),r?.type&&(r.mimeType=Zce[r?.type]),r}catch(r){return this.loggingService.catch("Error in StorageService createAttachment: ",r),null}}uploadAttachmentToStorage({attachment:e,file:t,resolve:r,reject:a}){try{let s=pS(this.storage,e.bucketPath),c=dU(s,t,{cacheControl:"public,max-age=3600"});c.on("state_changed",p=>{let u=p.bytesTransferred/p.totalBytes*100},p=>{a(p)},()=>{cU(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 Q(this,arguments,function*({file:e,attachment:t,metadata:r,resolve:a,reject:s}){try{r.attachmentId=t.attachmentId;let p={attachmentId:t.attachmentId,name:t.name,file:e,metadata:r,mimeType:t.mimeType},u=yield this.attachmentResolverService.saveAttachment({attachment:p,eventType:os.ATTACHMENT_ADD});u&&u.data?.url?(t.url=u.data?.url,a(t)):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:t,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:t});if(!p)throw new Error("Attachment not created");r?this.uploadToResolver({file:t,attachment:p,metadata:a,resolve:s,reject:c}):this.uploadAttachmentToStorage({attachment:p,file:t,resolve:s,reject:c})}catch(p){this.loggingService.catch("Error in StorageService uploadFile:",p),c(p)}})}uploadChunk(e,t,r){return new Promise((a,s)=>{try{if(this.apiKey){let c=`${this.apiKey}/${e}/${t.name}`,p=pS(this.storage,c),u=dU(p,t,{cacheControl:"public,max-age=3600"});u.on("state_changed",C=>{let E=C.bytesTransferred/C.totalBytes*100},C=>{s(C)},()=>{cU(u.snapshot.ref).then(C=>{a(C)}).catch(C=>{this.loggingService.catch(`[uploadChunk] Error getting download URL for chunk ${r}:`,C),s(C)})})}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 t=new XMLHttpRequest;t.responseType="blob",t.onload=()=>{let r=t.response,a=document.createElement("a"),s=window.URL.createObjectURL(r);a.setAttribute("type","hidden"),a.setAttribute(j.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()},t.onerror=()=>{window.open(e.url,"_blank")},t.open("GET",e.url),t.send()}}catch(t){this.loggingService.catch("Error in StorageService downloadAttachment: ",t)}}deleteAttachment({attachment:e,metadata:t,useAttachmentResolver:r}){return new Promise((a,s)=>{if(r)this.attachmentResolverService.deleteAttachment({attachmentId:e.attachmentId,metadata:t}).then(()=>{a(null)}).catch(c=>{s(c)});else{let c=pS(this.storage,e.bucketPath);lU(c).then(()=>{a(null)}).catch(p=>{a(null)})}})}deleteFileFromPath(e){return new Promise((t,r)=>{let a=pS(this.storage,e);lU(a).then(()=>{t(null)}).catch(s=>{r(s)})})}};o.\u0275fac=function(t){return new(t||o)(ee(Ve),ee(Ft),ee(y),ee(rg))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var vn=(()=>{let o=class o{constructor(e,t,r,a,s,c,p,u){this.analyticsService=e,this.authService=t,this.contactService=r,this.databaseService=a,this.docService=s,this.configService=c,this.loggingService=p,this.commonDbService=u,this.documentIAM$=new ve(null),this.workspaceIAM$=new ve(null),this.roles$=new ve([]),this.getDocumentIamSubscription=null,this.getOrganizationIamSubscription=null,this.getWorkspaceIamSubscription=null;try{this.authService.setIamService(this),this.databaseService.getDb().pipe(Le(C=>!!C),st(1)).subscribe(C=>{C&&(this.getUser(),this.getDocumentPaths())},C=>{this.loggingService.catch("Error in CommentService getDb subscription: ",C)}),this.getRole$().pipe(st(1)).subscribe(C=>{this.authService?.getUser()&&!C&&this.analyticsService.trackEvent(Z.Events.Iam.USER_ACCESS_DENIED)}),this.documentIAM$.subscribe(C=>{C?.accessType&&this.contactService.setDocumentAccessType(C.accessType)})}catch(C){this.loggingService.catch("Error in IamService constructor: ",C)}}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(Le(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(Le(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 t=e||new mk;this.documentIAM$.next(t)},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(kn(e=>se(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),Et())}getDocumentIAM$(){return this.documentIAM$.asObservable()}getRoles$(){return this.roles$.asObservable().pipe(ce(e=>e?.length?e:j.WorkspaceRoles))}getFeaturesAccessLevel$(){return this.documentIAM$.asObservable().pipe(ce(e=>e?.features),he(e=>this.getRole$().pipe(ce(t=>(t===vo.ADMIN&&(e=e&&JSON.parse(JSON.stringify(e||{})),e?.all?.disabled&&(e.all.disabled=!1)),e)))))}hasRole(e){try{return e===this.getRole()}catch(t){return this.loggingService.catch("Error in IamService hasRole: ",t),!1}}hasRoleAny(e=[]){try{return e?.includes(this.getRole()||"")}catch(t){return this.loggingService.catch("Error in IamService hasRoleAny: ",t),!1}}hasRole$(e){try{return this.authService.getUser$().pipe(he(()=>this.documentIAM$.pipe(Le(t=>!!t),he(()=>this.workspaceIAM$.pipe(ce(()=>e===this.getRole()))))))}catch(t){return this.loggingService.catch("Error in IamService hasRole$: ",t),se(!1)}}getRole$(){try{return this.authService.getUser$().pipe(he(()=>this.configService.getSF$()),he(()=>this.configService.getSF()?this.contactService.isUserGlobalContact$():se(null)),he(()=>this.documentIAM$.pipe(Le(e=>!!e))),he(()=>this.workspaceIAM$),ce(()=>this.getRole()))}catch(e){return this.loggingService.catch("Error in IamService getRole$: ",e),se(null)}}getRole(){try{let e=this.configService.getSF();if(e&&this.contactService.isUserGlobalContact())return vo.ADMIN;if(!e&&this.user?.isAdmin)return vo.ADMIN;let t=null,r;if(this.user)switch((this.documentIAM$.value?this.documentIAM$.value?.features?.all?.restricted:!1)?yi.RESTRICTED:this.documentIAM$.value?this.documentIAM$.value?.documentAccessType||yi.PUBLIC:null){case yi.PUBLIC:r=this.getUserFromDocumentIAM(this.user?.email,this.user?.userId),r||(r=this.getUserFromWorkspaceIAM(this.user?.email,this.user?.userId)),t=r?.role?.name||vo.COMMENTER;break;case yi.RESTRICTED:r=this.getUserFromDocumentIAM(this.user?.email,this.user?.userId),r||(r=this.getUserFromWorkspaceIAM(this.user?.email,this.user?.userId)),t=r?.role?.name||null;break;default:break}return t}catch(e){this.loggingService.catch("Error in IamService getRole: ",e)}return null}isUserAdmin$(){return this.getRole$().pipe(ce(e=>e===vo.ADMIN),Et())}isUserAdmin(){try{return this.getRole()===vo.ADMIN}catch(e){return this.loggingService.catch("Error in IamService isUserAdmin: ",e),!1}}getUserFromDocumentIAM(e,t){try{if(e||t){let r;return e&&(r=this.documentIAM$.value?.users?.[bt(e)]),!r&&t&&(r=this.documentIAM$.value?.users?.[bt(t)]),r}else return}catch(r){this.loggingService.catch("Error in IamService getUserFromDocumentIAM: ",r)}}getUserFromWorkspaceIAM(e,t){try{if(e||t){let r;return e&&(r=this.workspaceIAM$.value?.users?.[bt(e)]),!r&&t&&(r=this.workspaceIAM$.value?.users?.[bt(t)]),r}else return}catch(r){this.loggingService.catch("Error in IamService getUserFromWorkspaceIAM: ",r)}}};o.\u0275fac=function(t){return new(t||o)(ee(et),ee(Ve),ee(xi),ee(Dn),ee(at),ee(Ft),ee(y),ee(pn))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var gn=(()=>{let o=class o{constructor(e,t,r,a,s,c,p,u,C,E,D,L,z,W,J,ue){this.afAuth=e,this.analyticsService=t,this.authService=r,this.configService=a,this.commonDbService=s,this.commonDbUtilsService=c,this.commentUtilsService=p,this.commentAnnotationsResolverService=u,this.databaseService=C,this.docService=E,this.domService=D,this.iamService=L,this.loggingService=z,this.notificationUtilsService=W,this.usersService=J,this.functions=ue,this.db=ts(),this.notificationsDb=ts(void 0,oi.firebaseNotificationsDatabaseURL),this.documentPaths=null,this.notifications$=new ve([]),this.rawNotificationsByIdMap$=new ve(new Map),this.processedNotifications$=new ve([]),this.readNotificationsOnForYouTab$=new ve(!1),this.notificationViews$=new ve({}),this.notificationsByIdMap$=new ve(new Map),this.historyPanelVisible$=new ve(!1),this.notificationsForYou$=new ve(null),this.notificationsByDocumentIdMap$=new ve(null),this.notificationsByDocumentIdSubscription={},this.allowedDocumentMetadataMap$=new ve(null),this.maxNotificationDays$=new ve(15),this.tabConfig$=new ve({people:{enable:!1}}),this.settingsConfig$=new ve(null),this.muteAllNotifications$=new ve(!1),this.enableSettings$=new ve(!1),this.selfNotifications$=new ve(!1),this.settingsInitialConfig$=new ve([{name:"Inbox",id:"inbox",default:"ALL",enable:!0,values:[{name:"All",id:"ALL"},{name:"Only Involved",id:"MINE"},{name:"None",id:"NONE"}]},{name:"Email",id:"email",default:"MINE",enable:!0,values:[{name:"All",id:"ALL"},{name:"Only Involved",id:"MINE"},{name:"None",id:"NONE"}]}]),this.notificationsPanelVisible$=new ve(!1);try{this.subscribeNotificationsData().subscribe(),this.commentUtilsService.setNotificationService(this),this.databaseService.getDb().pipe(Le(ye=>!!ye),st(1)).subscribe(ye=>{ye&&(this.db=ye,this.getDocumentIds(),this.subscribeGetNotificationsForYou())},ye=>{this.loggingService.catch("Error in NotificationService getDb subscription: ",ye)}),this.authService.getUser$().subscribe(ye=>{ye?(this.subscribeGetNotificationsForYou(),this.getDocumentIds(),this.subscribeToUserSettings()):(Object.keys(this.notificationsByDocumentIdSubscription).forEach(Ae=>{this.notificationsByDocumentIdSubscription[Ae]?.unsubscribe()}),this.notificationForYouSubscription?.unsubscribe(),this.documentIdsSubscription?.unsubscribe(),this.resetCacheData())}),this.docService.getLocationMetadata$().subscribe(ye=>{if(ye){let Ae=this.notificationsByDocumentIdMap$.getValue()?JSON.parse(JSON.stringify(this.notificationsByDocumentIdMap$.getValue())):null;Object.keys(ye||{}).forEach(He=>{let Fe=Ae?.[He]?.notifications;Fe?.length&&Fe.forEach(xe=>{this.notificationUtilsService.mergeLocationWithNotification({notification:xe},ye)?.notification})}),this.notificationsByDocumentIdMap$.next(Ae)}})}catch(ye){this.loggingService.catch("Error in NotificationService constructor: ",ye)}}setDBConfigDataToInitialConfig(e){try{let t=JSON.parse(JSON.stringify(this.settingsConfig$.getValue()??{}));Object.entries(e||{}).forEach(([r,a])=>{t[r]=a}),this.settingsConfig$.next(t)}catch(t){this.loggingService.catch("Error in NotificationService setDBConfigDataToInitialConfig: ",t)}}getInitialConfigFromDB(e){return Q(this,null,function*(){try{this.loggingService.log("%c[WB] Calling NotificationService FUNCTION: getInitialConfigFromDB","color: green;");let t=bt(this.authService.getUser()?.userId??""),r=yield this.commonDbService.getData({feature:"userConfig",properties:{useCollectionGroup:!1,isCollection:!1,documentId:e?.documentId,userId:t}});if(r?.notificationsConfig)this.setDBConfigDataToInitialConfig(r?.notificationsConfig);else{this.setSettingsInitialConfig(this.settingsInitialConfig$.getValue());let a={};this.settingsInitialConfig$.getValue().forEach(c=>{if(c.enable){let p=c?.values?.find(u=>u.id===c.default);a[c.id]=p||c?.values?.[0]||{id:"NONE",name:"None"}}});let s={};Object.keys(a).forEach(c=>{s[c]=a[c].id}),yield this.updateSettingsConfigToDb(s)}}catch(t){this.loggingService.catch("Error in NotificationService getInitialConfigFromDB: ",t)}})}subscribeToUserSettings(){try{this.loggingService.log("%c[WB] Calling NotificationService FUNCTION: subscribeToUserSettings","color: green;"),this.userSettingsSubscription&&this.userSettingsSubscription.unsubscribe();let e=bt(this.authService.getUser()?.userId??"");this.userSettingsSubscription=this.enableSettings$.pipe(Le(t=>t===!0),he(()=>this.docService.getDocumentPaths$().pipe(Le(t=>!!t),he(t=>Zi(this.getInitialConfigFromDB(t)).pipe(he(()=>this.commonDbService.dbListener({feature:"userConfig",properties:{useCollectionGroup:!1,isCollection:!1,documentId:t?.documentId,userId:e}}).pipe(ce(r=>{r?.data?.notificationsConfig&&!wi(r?.data?.notificationsConfig??{},this.settingsConfig$.getValue()??{})&&this.setDBConfigDataToInitialConfig(r?.data?.notificationsConfig)})))))))).subscribe()}catch(e){this.loggingService.catch("Error in NotificationService subscribeToUserSettings: ",e)}}resetCacheData(){try{this.loggingService.log("%c[WB] Calling NotificationService FUNCTION: resetCacheData","color: green;"),this.notificationsByDocumentIdMap$.next(null),this.notificationsForYou$.next(null),this.settingsConfig$.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(t){this.loggingService.catch("Error in NotificationService setCommentService: ",t)}}getDocumentIds(){try{this.documentIdsSubscription&&this.documentIdsSubscription.unsubscribe(),this.documentIdsSubscription=this.selfNotifications$.pipe(dn(()=>{this.notificationsByDocumentIdMap$.next(null)}),he(()=>this.getDocumentIdsByLastNotificationTimestamp().pipe(Bi(),ce(([e,t])=>{let r=e?.map(u=>u.documentId),a=t?.map(u=>u.documentId),s=r?.filter(u=>!a?.includes(u)),c=a?.map(u=>({documentId:u,timestamp:t?.find(C=>C.documentId===u)?.timestamp})).filter(u=>!r?.includes(u.documentId)),p=a?.map(u=>{let C=t?.find(E=>E.documentId===u)?.timestamp;return{documentId:u,timestamp:C}}).filter(u=>{let C=e?.find(E=>E.documentId===u.documentId)?.timestamp;return C&&u.timestamp&&C!==u.timestamp});c?.length&&this.fetchNotificationsForDocumentIds(c),p?.length&&this.fetchNotificationsForDocumentIds(p,1),s?.forEach(u=>{this.removeNotificationsForDocumentId(u)}),t&&!t?.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(he(t=>this.docService.getOrganizationConfig$().pipe(ce(r=>{let a=null,s=this.configService.getApiKey(),c=r?.organizationId||t?.organizationId;return s&&c&&(a=new Ud({apiKey:s,organizationId:c})),{user:t,documentPaths:a}}))),he(t=>{let{user:r,documentPaths:a}=t;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:[Zn(lt("timestamp",">=",p)),fi("timestamp","desc"),c0(e)]}}).pipe(ce(u=>u?.data),ce(u=>{let C=[];return Object.keys(u||{}).forEach(E=>{let D=this.commonDbService.shouldUseFirestore()?u[E]?.timestamp??0:u[E],L=this.commonDbService.shouldUseFirestore()?u[E]?.deletedNotification??!1:!1;if(L&&L.id&&L?.timestamp===D){let z=L.id,W=u[E]?.metadata?.documentId,J=JSON.parse(JSON.stringify(this.notificationsByDocumentIdMap$.getValue()??{})),ue=J?.[W]??{documentMetadata:null,notifications:[]},ye=ue.notifications??[],Ae=ye?.findIndex(He=>He.id===z);Ae!==-1&&(ye.splice(Ae,1),this.notificationsByDocumentIdMap$.next(T(I({},J),{[W]:T(I({},ue),{notifications:ye})})))}C.push({documentId:E,timestamp:D})}),C}),kn(u=>(this.loggingService.catch("Error in NotificationService getDocumentIdsByLastNotificationTimestamp: ",u),se([]))))}return se(null)}))}catch(t){return this.loggingService.catch("Error in NotificationService getDocumentIdsByLastNotificationTimestamp: ",t),se([])}}fetchNotificationsForDocumentIds(e,t=15){return Q(this,null,function*(){try{if(e?.length){let r=br(this.functions,Er({url:oi.cloudFunction.getNotificationsForDocuments,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:12e5}),a=this.docService.getOrganizationConfig()?.organizationId??"",s=this.getStartAtTimestamp(),c={};e.forEach(L=>{if(L?.documentId){let z=this.getAllowedDocumentMetadataByDocumentId(L.documentId);z&&(c[L.documentId]=z)}});let p={organizationId:a,documentIds:e,timestamp:s,limitToLast:t,documentMetadataByDocumentId:c,selfNotifications:this.selfNotifications$.value},u=yield this.notificationUtilsService.handleNotificationEncryption({data:p}),C=(yield r({veltData:u}))?.data?.data?.veltData||{},E="notificationwithdocumentidstoencryptanddecryptonsdk"+(this.authService.getUser()?.userId??""),D=yield Qre(C,E);if(D&&typeof D=="object"){let L=this.usersService.userDataProviderAvailable(),z=this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable(),W=[],J=[];Object.keys(D).forEach((ue,ye)=>{let Ae=D[ue].documentMetadata;if(Ae){let Fe=this.allowedDocumentMetadataMap$.value||{};(!Fe?.[ue]||!wi(Fe?.[ue],Ae))&&this.allowedDocumentMetadataMap$.next(T(I({},Fe),{[ue]:Ae}))}let He=D[ue].notifications||[];He.forEach(Fe=>{Fe.notification=this.getClientNotificationObject(Fe)}),this.setNotificationForDocumentIdInCache(ue,Ae,He),L&&W.push(this.commonDbUtilsService.formatResponse({feature:"allDocNotifications",data:He,shouldAwait:!0,forceResolve:!0})),z&&J.push(this.commonDbUtilsService.formatResponse({feature:"allDocNotifications",data:He,shouldCommentAnnotationsResolverAwait:!0}))}),L&&Promise.all(W).then(()=>{Object.keys(D).forEach(ue=>{let ye=D?.[ue]?.documentMetadata||{},Ae=this.commonDbUtilsService.mergeUsersWithData({feature:"allDocNotifications",data:D?.[ue]?.notifications||[]});Ae.forEach(He=>{He.notification=this.getClientNotificationObject(He)}),this.setNotificationForDocumentIdInCache(ue,ye,Ae)})}),z&&Promise.all(J).then(()=>{Object.keys(D).forEach(ue=>{let ye=D?.[ue]?.documentMetadata||{},Ae=D?.[ue]?.notifications?.reduce((He,Fe)=>(He[Fe.notificationId]=Fe,He),{});Ae=this.commonDbUtilsService.mergeCommentAnnotationsWithData({feature:"allDocNotifications",data:Ae}),Ae=Object.values(Ae??{}),Ae.forEach(He=>{He.notification=this.getClientNotificationObject(He)}),this.setNotificationForDocumentIdInCache(ue,ye,Ae)})})}}}catch(r){return this.loggingService.catch("Error in NotificationService fetchNotificationsForDocumentIds: ",r),[]}})}setNotificationForDocumentIdInCache(e,t,r,a){try{let s=this.docService.getOrganizationConfig()?.organizationId??"",c=this.docService.getOrganizationMetadata(s);t||(t=JSON.parse(JSON.stringify(this.docService.getDocumentMetadata()||{}))),c||(c=JSON.parse(JSON.stringify(this.docService.getOrganizationMetadata(s)||{})));let p=this.notificationsByDocumentIdMap$.getValue(),u=p?.[e]?.notifications||[],C=this.docService.getLocationMetadatas(),E=r?.map(z=>{let W=z.notification;return W.metadata&&(W.metadata.documentName=t?.documentName||W.metadata.documentName,W.metadata.organizationMetadata=c||W.metadata.organizationMetadata,W.metadata.documentMetadata=t||W.metadata.documentMetadata),C&&(W=this.notificationUtilsService.mergeLocationWithNotification({notification:W},C)?.notification),W})?.filter(z=>!!z)||[],D=new Map(u.map(z=>[z.id,z]));E.forEach(z=>{D.set(z.id,z)});let L=Array.from(D.values()).sort((z,W)=>(W.timestamp||0)-(z.timestamp||0));this.notificationsByDocumentIdMap$.next(T(I({},p),{[e]:{notifications:L,documentMetadata:t}}))}catch(s){this.loggingService.catch("Error in NotificationService setNotificationForDocumentIdInCache: ",s)}}removeNotificationsForDocumentId(e){try{this.notificationsByDocumentIdSubscription[e]&&this.notificationsByDocumentIdSubscription[e].unsubscribe();let t=this.notificationsByDocumentIdMap$.getValue();delete t?.[e],this.notificationsByDocumentIdMap$.next(t)}catch(t){this.loggingService.catch("Error in NotificationService removeNotificationsForDocumentId: ",t)}}getNotificationsForDocumentId$(e,t=50){try{return this.authService.getUser$().pipe(ce(r=>({user:r})),he(r=>this.maxNotificationDays$.pipe(ce(()=>r))),he(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 u=c.getTime();return Zi(this.commonDbService.queryData({feature:"allDocNotifications",properties:{rtdbQuery:[Lu("timestamp"),Vu(u),LV(t)],firestoreQuery:[fi("timestamp","desc"),lt("timestamp",">=",u),lt("notification.actionUser.userId","!=",a.userId),c0(t)],apiKey:s,organizationId:this.docService?.getDocumentPaths()?.organizationId||a?.organizationId,documentId:e}})).pipe(he(C=>this.commonDbUtilsService.mergeUsersWithData$({feature:"allDocNotifications",data:{data:C,operation:null}})),ce(C=>C?.data??[]),ce(C=>(C.sort((E,D)=>D.timestamp-E.timestamp),C)),kn(C=>(this.loggingService.catch("Error in NotificationService getNotificationsForDocumentId: ",C),se([]))),ce(C=>(C.forEach(E=>{E.notification=this.getClientNotificationObject(E)}),C)))}return se([])}))}catch(r){return this.loggingService.catch("Error in NotificationService getNotificationsForDocumentId: ",r),se([])}}getStartAtTimestamp(){try{let e=new Date,t=this.maxNotificationDays$.getValue()>0?this.maxNotificationDays$.getValue():15;return e.setDate(e.getDate()-t),e.getTime()}catch(e){return this.loggingService.catch("Error in NotificationService getStartAtTimestamp: ",e),0}}getNotificationsForYou(){try{return this.databaseService.getDb().pipe(he(e=>this.authService.getUser$().pipe(ce(t=>({db:e,user:t})))),he(e=>this.maxNotificationDays$.pipe(ce(()=>e))),he(e=>{let{db:t,user:r}=e,a=this.configService.getApiKey();if(t&&r?.organizationId&&a){let s=bt(r?.userId),c=new Date,p=this.maxNotificationDays$.getValue()>0?this.maxNotificationDays$.getValue():15;c.setDate(c.getDate()-p);let u=c.getTime();return this.commonDbService.dbListener({feature:"allUserNotifications",properties:{useQuery:!0,isCollection:!0,rtdbQuery:[Lu("timestamp"),Vu(u),LV(50)],firestoreQuery:[fi("timestamp","desc"),lt("timestamp",">=",u),lt("notification.actionUser.userId","!=",r.userId),c0(50)],apiKey:a,organizationId:this.docService?.getDocumentPaths()?.organizationId||r?.organizationId,documentId:this.docService.getDocumentPaths()?.documentId,userId:s}}).pipe(he(C=>C?.data?se(C).pipe(ce(E=>E?.data),ce(E=>{let D=Object.values(E||{});return D.forEach(z=>{z.notification=this.getClientNotificationObject(z)}),D.sort((z,W)=>W.timestamp-z.timestamp),D.map(z=>z.notification).filter(z=>!!z)}),he(E=>{let D={data:E?.reduce((L,z)=>(L[z.id]={notification:z},L),{}),operation:null};return this.commonDbUtilsService.mergeLocationMetadataWithData$({data:D,feature:"allUserNotifications"}).pipe(ce(L=>Object.values(L?.data||{}).map(z=>z?.notification)))})):se(null)))}return se(null)}),he(e=>{let t=this.docService.getOrganizationConfig()?.organizationId??"";return this.docService.getOrganizationMetadata$(t).pipe(ce(()=>e))}),he(e=>this.allowedDocumentMetadataMap$.pipe(ce(()=>e))),ce(e=>(e?.length&&(e=e.map(t=>{if(t?.metadata){let r=this.docService.getOrganizationConfig()?.organizationId??"",a=this.getAllowedDocumentMetadataByDocumentId(t.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)||{}))),t.metadata.documentName=a?.documentName||t.metadata.documentName,t.metadata.organizationMetadata=s||t.metadata.organizationMetadata,t.metadata.documentMetadata=a||t.metadata.documentMetadata}return t})),e===null?this.notificationsForYou$.next(null):e?.length?this.notificationsForYou$.next(JSON.parse(JSON.stringify(e))):this.notificationsForYou$.next([]),se(e))))}catch(e){return this.loggingService.catch("Error in NotificationService getNotificationsForYou: ",e),se({})}}subscribeNotificationsData(e,t){this.loggingService.log("%c[WB] Calling FUNCTION: subscribeViewsData","color: green;");let r,a;try{if(e&&(a=En(e)),t&&typeof t=="object"){let s=Yo(t);r=En(JSON.stringify(s))}}catch(s){this.loggingService.catch("Error in ViewsService subscribeViewsData: ",s)}return ei(this.afAuth).pipe(Le(s=>!!s),he(s=>this.isFeatureAllowed({firebaseUser:s})),he(s=>s.featureAllowed?this.iamService.isUserAllowed$().pipe(ce(c=>(s.featureAllowed=c,s))):se(s)),he(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(),se([])):se(s).pipe(he(c=>this.docService.getDocumentPaths$().pipe(ce(p=>(this.documentPaths=p,c.documentPaths=p,c)))),he(c=>this.getDataFromDocumentId(a)))))}isFeatureAllowed(e){return this.configService.getConfig$().pipe(Le(t=>!!t),ce(t=>T(I({},e),{config:t})),he(t=>this.authService.getUser$().pipe(ce(r=>T(I({},t),{user:r})))),he(t=>ro(t.config,t.user,Re.NOTIFICATION)?se(T(I({},t),{featureAllowed:!0})):(this.loggingService.warn("Notification feature is not allowed."),se(T(I({},t),{featureAllowed:!1})))))}getDataFromDocumentId(e){return this.databaseService.getDb().pipe(Le(t=>!!t),he(t=>{if(this.db=t,this.loggingService.log(this.db),this.configService?.getApiKey()&&this.documentPaths?.views){let r=`${this.configService.getApiKey()}`;this.documentPaths?.organizationId&&(r+=`/${j.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${this.documentPaths.organizationId}`);let a=qi(this.db,`${e?r+"/"+j.FIREBASE_PARTIAL_PATH_DOCS+"/"+e+"/"+j.FIREBASE_PARTIAL_PATH_VIEWS+"/":this.documentPaths?.notifications}`);return U6(a).pipe(kn(s=>(this.loggingService.catch("Error in NotificationService getDataFromDocumentId: ",s),se(null))),ce(s=>{let c=[],p=new Map;s?.raw&&(Object.keys(s?.raw||{}).forEach(C=>{let E=s?.raw[C];E?.id&&c.push(E)}),c.forEach(C=>{C.id&&p.set(C.id,C)})),this.notifications$.next(c),this.rawNotificationsByIdMap$.next(p);let u=[];s?.processed&&Object.keys(s?.processed||{}).forEach(C=>{let E=s?.processed[C];E?.id&&u.push(E)}),this.processedNotifications$.next(u),this.setNotificationsByIdMap()}))}else return se(null)}))}setNotificationsByIdMap(){try{let e=this.authService.getUser();if(e){let t=this.notificationViews$.getValue(),r;e?.email&&(r=bt(e?.email));let a;e?.userId&&(a=bt(e?.userId));let s=new Map;this.processedNotifications$.getValue().forEach(p=>{if(p.id&&p?.displayHeadlineMessageTemplate){let u=!1;(r&&p.notifyUsers?.[r]||a&&p.notifyUsers?.[a])&&(u=!0);let C={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:u,notificationSourceData:p.notificationSourceData},E=this.getRawNotificationById(C.id);if(E?.metadata&&(C.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}),C?.notificationSource==="comment"&&C?.targetAnnotationId){let D=this.commentService?.getAnnotationById(C.targetAnnotationId);D||E?.annotationData&&(D=E.annotationData),D&&(C.notificationSourceData=Gn(D))}s.set(p.id,C)}}),s.forEach((p,u)=>{p.isUnread=p?.actionUser?.userSnippylyId!==e?.userSnippylyId&&!t?.notification?.[u]?.views?.[e?.userSnippylyId],s.set(u,p)}),this.notificationsByIdMap$.next(s)}}catch(e){this.loggingService.catch("Error in NotificationService setNotificationsByIdMap: ",e)}}getClientNotificationObject({processed:e,raw:t,metadata:r,views:a,notification:s}){try{let c=this.authService.getUser(),p=s||e;if(p.id&&p?.displayHeadlineMessageTemplate&&c){let u=null;c?.email&&(u=bt(c?.email));let C=null;c?.userId&&(C=bt(c?.userId));let E=!1,D=!0;(u&&p.notifyUsers?.[u]||C&&p.notifyUsersByUserId?.[C])&&(E=!0),C&&a?.[C]&&(D=!1);let L={id:p.id};if(s?L=T(I(I({},L),s),{displayHeadlineMessage:this.getNotificationHeadlineMessage(s),displayBodyMessage:this.getNotificationBodyMessage(s),forYou:E,isUnread:D}):L={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},L?.notificationSource==="comment"&&L?.targetAnnotationId){let z=this.commentService?.getAnnotationById(L.targetAnnotationId);z||s?.notificationSourceData&&(z=s?.notificationSourceData),z||t?.annotationData&&(z=t.annotationData),z&&(L.notificationSourceData=Gn(z))}return t?.targetAnnotationData?.isCommentResolverUsed&&(L.isCommentResolverUsed=t?.targetAnnotationData?.isCommentResolverUsed),L}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(t=>{let r=e[t].notifications||[],a=r.filter(c=>c.isUnread).length,s=r.length>0&&r[0]?.timestamp||0;return{documentId:t,notifications:e[t]?.notifications,unreadNotificationsCount:a,latestNotificationTimestamp:s,documentMetadata:e[t]?.documentMetadata}}).filter(t=>t.notifications?.length>0).sort((t,r)=>r.latestNotificationTimestamp-t.latestNotificationTimestamp):null))}getAllNotifications$(){return this.getNotificationsByDocumentId$().pipe(ce(e=>{let t=null;return e?(t=[],e.forEach(r=>{r.notifications.forEach(a=>{t?.push(a)})}),t?.sort((r,a)=>a.timestamp-r.timestamp)):null}))}processNotificationData(e){try{let t=e?.annotationData?.metadata,r=this.docService.getOrganizationConfig()?.organizationId;e.metadata=JSON.parse(JSON.stringify(this.docService.getDocumentMetadata(t?.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(t?.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=t?.documentId?new Ud({apiKey:a,documentId:t.documentId,organizationId:t?.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(),u=this.notificationUtilsService.formatNotification(e,p);return JSON.parse(JSON.stringify(u))}catch(t){return this.loggingService.catch("Error in NotificationService processNotificationData: ",t),null}}updateNotificationDatabase(e){try{let t=qi(this.notificationsDb),r=this.processNotificationData(e);A6(t,JSON.parse(JSON.stringify(r)))}catch(t){this.loggingService.catch("Error in NotificationService updateNotificationDatabase: ",t)}}getRawNotifications$(){return this.notifications$.asObservable()}getProcessedNotifications$(){return this.processedNotifications$.asObservable()}getNotifications$(e){return this.authService.getUser$().pipe(he(t=>t?t.organizationId?this.getAllNotifications$().pipe(he(r=>this.notificationsForYou$.pipe(ce(a=>{if(r||a){let s=new Map;return(!e?.type||["all","documents"].includes(e.type))&&(r||[]).forEach(c=>{c.id&&s.set(c.id,c)}),(!e?.type||["all","forYou"].includes(e.type))&&(a||[]).forEach(c=>{c.id&&!s.has(c.id)&&s.set(c.id,c)}),Array.from(s.values()).sort((c,p)=>(p.timestamp||0)-(c.timestamp||0))}else return null})))):this.notificationsByIdMap$.asObservable().pipe(ce(r=>Array.from(r.values())),ce(r=>r.sort((a,s)=>s.timestamp-a.timestamp)),Kg()):se(null)),Et(mn))}getRawNotificationById(e){try{return this.rawNotificationsByIdMap$.getValue()?.get(e)}catch(t){this.loggingService.catch("Error in NotificationService getRawNotificationById: ",t);return}}setNotificationViews(e){try{this.notificationViews$.next(e),this.setNotificationsByIdMap()}catch(t){this.loggingService.catch("Error in NotificationService setNotificationViews: ",t)}}getNotificationHeadlineMessage(e){try{let t=this.authService.getUser();if(e?.displayHeadlineMessageTemplate&&e?.displayHeadlineMessageTemplateData){let r=e.displayHeadlineMessageTemplate,a=e.displayHeadlineMessageTemplateData,s=/\{(\w+)\}/g,c=r.replace(s,(p,u)=>(u==="actionUser"||u==="recipientUser")&&a[u]?t?.email&&a[u].email===t?.email||t?.userId&&a[u]?.userId===t?.userId?"You":a[u].name||a[u].email||' <velt-skeleton-loader width="50px" height="20px" border-radius="4px"></velt-skeleton-loader> ':a[u]?a[u]:p);return this.domService.sanitizeHtml(c)}return this.domService.sanitizeHtml(e.displayHeadlineMessageTemplate||"")}catch(t){return this.loggingService.catch("Error in NotificationService getNotificationHeadlineMessage: ",t),""}}getNotificationBodyMessage(e){try{if(e?.displayBodyMessageTemplate&&e?.displayBodyMessageTemplateData){let t=e?.displayBodyMessageTemplate;return e?.displayBodyMessageTemplateData&&e?.displayBodyMessageTemplateData?.users?.forEach(r=>{if(r?.userId){let a=this.usersService.getUserById(r?.userId);t=t?.replaceAll(`{{${r.userId}}}`,a?.name||a?.email||'<velt-skeleton-loader width="50px" height="20px" border-radius="4px"></velt-skeleton-loader>')}}),this.domService.sanitizeHtml(t)}return this.domService.sanitizeHtml(e.displayBodyMessage||"")}catch(t){return this.loggingService.catch("Error in NotificationService getNotificationBodyMessage: ",t),""}}setHistoryPanelVisibility(e,t=!1,r=!1){try{e?document.querySelector(j.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL)?this.historyPanelVisible$.next(e):this.loggingService.catch("Error in NotificationService setHistoryPanelVisibility: ",`<${j.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: ",`<${j.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`)}}toggleHistoryPanelVisibility(e=!1,t=!1){try{this.historyPanelVisible$.value?this.historyPanelVisible$.next(!this.historyPanelVisible$.value):document.querySelector(j.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: ",`<${j.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`)}catch{this.loggingService.catch("Error in NotificationService toggleHistoryPanelVisibility: ",`<${j.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`)}}getHistoryPanelVisibility$(){return this.historyPanelVisible$.asObservable()}setNotificationsAsRead(e){return Q(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(u=>u.id===a.id);p&&(p.isUnread=!1),r[s].notifications=c}}),this.notificationsByDocumentIdMap$.next(r)}}catch(t){this.loggingService.catch("Error in NotificationService setNotificationsAsRead: ",t)}})}setAllNotificationsAsRead(e){return Q(this,null,function*(){try{if(e?.tabId==="for-you"){let t=this.notificationsForYou$.value||[];this.setNotificationsAsRead(t)}else this.getNotifications$().pipe(st(1)).subscribe(t=>{t&&this.setNotificationsAsRead(t)})}catch(t){this.loggingService.catch("Error in NotificationService setAllNotificationsAsRead: ",t)}})}getUnreadNotificationsCount$(){try{return this.notificationsForYou$.pipe(ce(e=>e?.filter(r=>r?.isUnread)?.length??null),he(e=>this.getNotifications$().pipe(ce(t=>{let r=t?.filter(a=>a?.isUnread)?.length??null;return{forYou:e,all:r}}))))}catch(e){return this.loggingService.catch("Error in NotificationService getUnreadNotificationsCount$: ",e),se({forYou:null,all:null})}}setNotificationAsRead(e){return Q(this,null,function*(){try{let t=this.authService.getUser();if(t&&e?.id){let r=bt(t?.userId),{metadata:a}=e;if(a){let{apiKey:s,organizationId:c,documentId:p}=a;if(s&&c&&p&&r){let u=yield this.commonDbService.getData({feature:"docNotification",properties:{id:e.id,organizationId:c,documentId:p,apiKey:s}});u?.notificationId&&(u?.views?.[r]||(u.views||(u.views={}),u.views[r]={timestamp:Date.now()},this.commonDbService.updateData({feature:"docNotificationViews",properties:{id:e.id,organizationId:c,documentId:p,apiKey:s},data:u})));let C=yield this.commonDbService.getData({feature:"userNotification",properties:{id:e.id,userId:r,documentId:p,organizationId:c}});C?.notificationId&&(this.getReadNotificationsOnForYouTab()?C?.views?.[r]||(C.views||(C.views={}),C.views[r]={timestamp:Date.now()},this.commonDbService.updateData({feature:"userNotificationViews",properties:{id:e.id,userId:r,documentId:p,organizationId:c},data:C})):yield this.commonDbService.deleteData({feature:"userNotification",properties:{id:e.id,userId:r,documentId:p,organizationId:c}}))}}}}catch(t){this.loggingService.catch("Error in NotificationService setNotificationAsRead: ",t)}})}setMaxDays(e){try{e>0?this.maxNotificationDays$.next(e):this.maxNotificationDays$.next(15)}catch(t){this.loggingService.catch("Error in NotificationService setMaxDays: ",t)}}setTabConfig(e){try{e&&this.tabConfig$.next(e)}catch(t){this.loggingService.catch("Error in NotificationService setTabConfig: ",t)}}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 Q(this,null,function*(){try{this.getNotifications$().pipe(st(1)).subscribe(t=>{if(t){let r=t.filter(a=>a.id===e);this.setNotificationsAsRead(r)}})}catch(t){this.loggingService.catch("Error in NotificationService markNotificationAsReadById: ",t)}})}getAllowedDocumentMetadataByDocumentId(e){try{return this.allowedDocumentMetadataMap$.value?.[e]||null}catch(t){return this.loggingService.catch("Error in NotificationService getAllowedDocumentMetadataByDocumentId: ",t),null}}setSettingsConfig(e){try{this.enableSettings$.value&&this.settingsConfig$.next(e)}catch(t){this.loggingService.catch("Error in NotificationService setSettingsConfig: ",t)}}setSettingsConfigWithDB(e){try{this.enableSettings$.value&&(this.settingsConfig$.next(e),this.updateSettingsConfigToDb())}catch(t){this.loggingService.catch("Error in NotificationService setSettingsConfigWithDB: ",t)}}getSettingsConfig$(){return this.settingsConfig$.asObservable()}getSettingsConfig(){return this.settingsConfig$.value}setMuteAllNotifications(){try{this.muteAllNotifications$.value!==!0&&this.muteAllNotifications$.next(!0)}catch(e){this.loggingService.catch("Error in NotificationService setSettingsMuteAll: ",e)}}getMuteAllNotifications$(){return this.muteAllNotifications$.asObservable()}getMuteAllNotifications(){return this.muteAllNotifications$.value}enableSettings(){try{this.enableSettings$.value!==!0&&this.enableSettings$.next(!0)}catch(e){this.loggingService.catch("Error in NotificationService enableSettings: ",e)}}enableSelfNotifications(){try{this.selfNotifications$.value!==!0&&this.selfNotifications$.next(!0)}catch(e){this.loggingService.catch("Error in NotificationService enableSelfNotifications: ",e)}}disableSelfNotifications(){try{this.selfNotifications$.value!==!1&&this.selfNotifications$.next(!1)}catch(e){this.loggingService.catch("Error in NotificationService disableSelfNotifications: ",e)}}disableSettings(){try{this.enableSettings$.value!==!1&&this.enableSettings$.next(!1)}catch(e){this.loggingService.catch("Error in NotificationService disableSettings: ",e)}}getEnableSettings$(){return this.enableSettings$.asObservable()}getEnableSettings(){return this.enableSettings$.value}setSettingsInitialConfig(e){try{let t=!1;if(e.forEach(r=>{["email","inbox"].includes(r.id)&&(t=!r.values?.every(a=>["ALL","NONE","MINE"].includes(a.id)))}),t){this.loggingService.catch("Invalid config values for email or inbox, It should have only ALL, NONE, MINE values");return}this.settingsInitialConfig$.next(e)}catch(t){this.loggingService.catch("Error in NotificationService setSettingsInitialConfig: ",t)}}getSettingsInitialConfig$(){return this.settingsInitialConfig$.asObservable()}getSettingsInitialConfig(){return this.settingsInitialConfig$.value}updateSettingsConfigToDb(e){return Q(this,null,function*(){try{let t=bt(this.authService.getUser()?.userId??""),r=this.docService.getDocumentPaths(),a={apiKey:this.configService.getApiKey(),organizationId:r?.organizationId,documentId:r?.documentId,clientOrganizationId:r?.clientOrganizationId,clientDocumentId:r?.clientDocumentId,userId:t,clientUserId:this.authService.getUser()?.userId};t&&r?.documentId&&this.getEnableSettings()&&this.enableSettings$.value&&(yield this.commonDbService.updateData({feature:"userConfig",properties:{documentId:r.documentId,userId:t},data:{id:r.documentId,notificationsConfig:e||this.settingsConfig$.getValue(),metadata:a}}))}catch(t){this.loggingService.catch("Error in NotificationService updateSettingsConfigToDb: ",t)}})}openNotificationsPanel(){try{this.notificationsPanelVisible$.next(!0)}catch(e){this.loggingService.catch("Error in NotificationService openNotificationsPanel: ",e)}}closeNotificationsPanel(){try{this.notificationsPanelVisible$.next(!1)}catch(e){this.loggingService.catch("Error in NotificationService closeNotificationsPanel: ",e)}}getNotificationsPanelVisible$(){return this.notificationsPanelVisible$.asObservable()}getNotificationsPanelVisible(){return this.notificationsPanelVisible$.value}};o.\u0275fac=function(t){return new(t||o)(ee(Di),ee(et),ee(Ve),ee(Ft),ee(pn),ee(ag),ee(f0),ee(Rs),ee(Dn),ee(at),ee(Be),ee(vn),ee(y),ee(Rk),ee(Vn),ee(Wo))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var Zo=(()=>{let o=class o{constructor(e){this.loggingService=e,this._customStatusMap=new ve(j.CommentAnnotationStatusMap),this._customPriorityMap=new ve(j.CommentAnnotationPriorityMap),this._customCategoryMap=new ve(j.CommentCategoryMap);try{let t=sessionStorage.getItem(j.SESSION_STORAGE.VELT_CUSTOM_PRIORITY_MAP);t&&this._customPriorityMap.next(JSON.parse(t));let r=sessionStorage.getItem(j.SESSION_STORAGE.VELT_CUSTOM_STATUS_MAP);r&&this._customStatusMap.next(JSON.parse(r));let a=sessionStorage.getItem(j.SESSION_STORAGE.VELT_CUSTOM_CATEGORY_MAP);a&&this._customCategoryMap.next(JSON.parse(a))}catch(t){this.loggingService.catch("Error in CustomFilterService constructor: ",t)}}setCustomStatusFilters(e){try{if(e.length<2){this._customStatusMap.next(j.CommentAnnotationStatusMap),sessionStorage.setItem(j.SESSION_STORAGE.VELT_CUSTOM_STATUS_MAP,JSON.stringify(j.CommentAnnotationStatusMap)),this.loggingService.catch("Custom status filters must have at least 2 filters");return}let t={};e.forEach(r=>{t[r.id]=r,r.type||(r.type="ongoing")}),this._customStatusMap.next(t),sessionStorage.setItem(j.SESSION_STORAGE.VELT_CUSTOM_STATUS_MAP,JSON.stringify(t))}catch(t){this.loggingService.catch("Error in CustomFilterService setCustomStatusFilters: ",t)}}setCustomPriorityFilters(e){try{if(e.length<2){this._customPriorityMap.next(j.CommentAnnotationPriorityMap),sessionStorage.setItem(j.SESSION_STORAGE.VELT_CUSTOM_PRIORITY_MAP,JSON.stringify(j.CommentAnnotationPriorityMap)),this.loggingService.catch("Custom priority filters must have at least 2 filters");return}let t={};e.forEach(r=>{t[r.id]=r}),this._customPriorityMap.next(t),sessionStorage.setItem(j.SESSION_STORAGE.VELT_CUSTOM_PRIORITY_MAP,JSON.stringify(t))}catch(t){this.loggingService.catch("Error in CustomFilterService setCustomPriorityFilters: ",t)}}setCustomCategories(e){try{let t={};e.forEach(r=>{t[r.id]=r}),this._customCategoryMap.next(t),sessionStorage.setItem(j.SESSION_STORAGE.VELT_CUSTOM_CATEGORY_MAP,JSON.stringify(t))}catch(t){this.loggingService.catch("Error in CustomFilterService setCustomCategories: ",t)}}get customStatusMap$(){return this._customStatusMap.asObservable()}get customPriorityMap$(){return this._customPriorityMap.asObservable()}get customCategoryMap$(){return this._customCategoryMap.asObservable()}get defaultStatus(){try{let t=Object.entries(this._customStatusMap.value).find(([r,a])=>a.type==="default");if(t)return t[1]}catch(e){this.loggingService.catch("Error in CustomFilterService defaultStatus: ",e)}return j.CommentAnnotationStatusMap.OPEN}get resolvedStatus(){try{let t=Object.entries(this._customStatusMap.value).find(([r,a])=>a.type==="terminal");if(t)return t[1]}catch(e){this.loggingService.catch("Error in CustomFilterService resolvedStatus: ",e)}return j.CommentAnnotationStatusMap.OPEN}get ongoingStatuses(){try{let t=Object.entries(this._customStatusMap.value).filter(([r,a])=>a.type==="ongoing");if(t)return t.map(r=>r[1])}catch(e){this.loggingService.catch("Error in CustomFilterService ongoingStatuses: ",e)}return[j.CommentAnnotationStatusMap.IN_PROGRESS]}convertLegacyAnnotationStatus(e){try{if(typeof e.status=="string"||e.status===void 0){let t=Object.entries(this._customStatusMap.value),r=t.find(([a,s])=>s.type==="default");switch(e.status){case"open":r&&(e.status=r[1]);break;case"inProgress":let a=t.find(([c,p])=>p.type==="ongoing");a&&(e.status=a[1]);break;case"resolved":let s=t.find(([c,p])=>p.type==="terminal");s&&(e.status=s[1]);break;default:r&&(e.status=r[1]);break}}return e}catch(t){return this.loggingService.catch("Error in CustomFilterService convertLegacyAnnotation: ",t),e}}convertLegacyPriority(e){try{typeof e.priority=="string"&&(e.priority=j.CommentAnnotationPriorityMap[e.priority])}catch(t){this.loggingService.catch("Error in CustomFilterService convertLegacyPriority: ",t)}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(t=>j.CommentCategoryMap[t]))}catch(t){this.loggingService.catch("Error in CustomFilterService convertLegacyCategory: ",t)}return e}};o.\u0275fac=function(t){return new(t||o)(ee(y))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var Bc=(()=>{let o=class o{constructor(e,t,r){this.domService=e,this.loggingService=t,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,t){try{let r=`<span class="velt-emoji-icon velt-emoji-icon--emoji">${e}</span>`;return t&&(r=`<span class="velt-emoji-icon velt-emoji-icon--emoji" emoji-id=${t}>${e}</span>`),this.sanitizer.bypassSecurityTrustHtml(this.domService.sanitizeHtml(r))}catch{return""}}setEmojiList(e){try{this.emojis={},Object.keys(e).forEach(t=>{let r=e[t];if(r.svg)this.emojis[t]=this.sanitizer.bypassSecurityTrustHtml(this.domService.sanitizeSvg(r.svg));else if(r.url){let a=`<img src="${r.url}" alt="${t}" />`;this.emojis[t]=this.sanitizer.bypassSecurityTrustHtml(this.domService.sanitizeHtml(a))}else r.emoji&&(this.emojis[t]=this.getEmojiFromIconEmoji(this.domService.sanitizeHtml(r.emoji)))})}catch(t){this.loggingService.catch("Error in EmojiService setEmojiList: ",t)}}};o.Icons={RAISED_HANDS:`<svg width="58" height="57" viewBox="0 0 58 57" fill="none" xmlns="http://www.w3.org/2000/svg">
195
+ `}};var tg=class{constructor(){this.type="recorder",this.recordingType="audio",this.mode="floating",this.attachment=null,this.attachments=[],this.pageInfo=new oo}};var Sk=class{constructor(){this.type="rewriter",this.rewriterType="copywriter",this.pageInfo=new oo}};var bb=class{constructor(){this.screenWidth=0,this.screenHeight=0,this.screenScrollHeight=0}};var ng=class{constructor(){this.pageInfo=new oo}},Ib=function(i){return i.Start="start",i.End="end",i}(Ib||{}),u0=function(i){return i.Avatar="avatar",i.Label="label",i}(u0||{});var bk=class{constructor(){this.sources=[],this.playerState=new Eb}},Eb=class{constructor(){this.volume=1}};var xb=class{constructor(){this.to=[],this.resolved=!1,this.type="tag",this.pageInfo=new oo}};var ig=class{constructor(){this.visibility="private"}};var Ik=class{constructor(){this.reactions=[],this.type="reaction",this.pageInfo=new oo,this.isReactionResolverUsed=!1}};var Ek=class{};var ks=function(i){return i.EDITOR="editor",i.VIEWER="viewer",i}(ks||{}),wr=function(i){return i.DOES_NOT_EXIST="does_not_exist",i.PERMISSION_DENIED="permission_denied",i.SOMETHING_WENT_WRONG="something_went_wrong",i}(wr||{});var Ft=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.analyticsService=t,this.config$=new ve(null),this.disableLogsConfig$=new ve({warnings:!0,suppressAll:!1}),this.apiKey$=new ve(""),this.baseFeatureAllowList=[],this.sf$=new ve(!1),this.sdkType$=new ve("core"),this.logsEnabled$=new ve(!0),this.safeEval$=new ve(!1),this.encryptionProvider$=new ve(null);try{this.analyticsService.setConfigService(this),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(),ot.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(t){this.loggingService.catch("Error in ConfigService initConfig: ",t)}}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 t=this.config$.value;t&&(e?.length?t.featureAllowList=this.baseFeatureAllowList.filter(r=>!e.includes(r)):t.featureAllowList=this.baseFeatureAllowList.slice()),this.config$.next(t)}catch(t){this.loggingService.catch("Error in ConfigService disableFeatures: ",t)}}setSF(e){try{this.sf$.next(e),this.analyticsService.setSF(e)}catch(t){this.loggingService.catch("Error in ConfigService setSF: ",t)}}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),se(!1)}}setSdkType(e){try{this.sdkType$.next(e)}catch(t){this.loggingService.catch("Error in ConfigService setSdkType: ",t)}}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),se("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(t){this.loggingService.catch("Error in ConfigService disableLogs: ",t)}}getDisableLogsConfig(){return this.disableLogsConfig$.value}getDisableLogsConfig$(){return this.disableLogsConfig$.asObservable()}getApiProxyDomain(){try{return this.config$.value?.apiProxyDomain}catch(e){this.loggingService.catch("Error in ConfigService getApiProxyDomain: ",e);return}}enableSafeEval(){try{this.safeEval$.next(!0)}catch(e){this.loggingService.catch("Error in ConfigService enableSafeEval: ",e)}}disableSafeEval(){try{this.safeEval$.next(!1)}catch(e){this.loggingService.catch("Error in ConfigService disableSafeEval: ",e)}}getSafeEval(){try{return this.safeEval$.value}catch(e){return this.loggingService.catch("Error in ConfigService getSafeEval: ",e),!1}}getSafeEval$(){try{return this.safeEval$.asObservable()}catch(e){return this.loggingService.catch("Error in ConfigService getSafeEval$: ",e),se(!1)}}setEncryptionProvider(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setEncryptionProvider","color: green;"),this.encryptionProvider$.next(e)}catch(t){this.loggingService.catch("Error in ConfigService setEncryptionProvider: ",t)}}getEncryptionProvider(){try{return this.encryptionProvider$.value}catch(e){return this.loggingService.catch("Error in ConfigService getEncryptionProvider: ",e),null}}getEncryptionProvider$(){try{return this.encryptionProvider$.asObservable()}catch(e){return this.loggingService.catch("Error in ConfigService getEncryptionProvider$: ",e),se(null)}}};o.\u0275fac=function(t){return new(t||o)(ee(y),ee(et))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var Cce=(()=>{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(j.LOCALSTORAGE_DATA_ID);if(e)return JSON.parse(e);{let t=new vh;return this.setLocalStorageData(t),t}}catch(e){return this.loggingService.catch("Error in getLocalStorageData:",e),new vh}}setLocalStorageData(e){this.loggingService.log("%c[WB] Calling FUNCTION: setLocalStorageData","color: green;");try{if(e){let t=JSON.stringify(e);localStorage?.setItem(j.LOCALSTORAGE_DATA_ID,t)}}catch(t){this.loggingService.catch("Error in setLocalStorageData:",t)}}deleteLocalStorageData(){this.loggingService.log("%c[WB] Calling FUNCTION: deleteLocalStorageData","color: green;"),localStorage?.removeItem(j.LOCALSTORAGE_DATA_ID)}getSessionStorageData(){this.loggingService.log("%c[WB] Calling FUNCTION: getSessionStorageData","color: green;");try{let e=sessionStorage?.getItem(j.LOCALSTORAGE_DATA_ID);if(e)return JSON.parse(e);{let t=new vh;return this.setSessionStorageData(t),t}}catch(e){return this.loggingService.catch("Error in getSessionStorageData:",e),new vh}}setSessionStorageData(e){this.loggingService.log("%c[WB] Calling FUNCTION: setSessionStorageData","color: green;");try{if(e){let t=JSON.stringify(e);sessionStorage?.setItem(j.LOCALSTORAGE_DATA_ID,t)}}catch(t){this.loggingService.catch("Error in setSessionStorageData:",t)}}deleteSessionStorageData(){this.loggingService.log("%c[WB] Calling FUNCTION: deleteSessionStorageData","color: green;");try{sessionStorage?.removeItem(j.LOCALSTORAGE_DATA_ID)}catch(e){this.loggingService.catch("Error in deleteSessionStorageData:",e)}}};o.\u0275fac=function(t){return new(t||o)(ee(y))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var Bd=(()=>{let o=class o{constructor(e,t){this.localStorageService=e,this.loggingService=t,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 Po,t=this.localStorageService.getSessionStorageData();if(t.snippylyAvatar)e=t.snippylyAvatar;else{let r=this.generateUserAvatar();t.snippylyAvatar=r,this.localStorageService.setSessionStorageData(t)}return e}catch(e){return this.loggingService.catch("Error in getSessionAvatar:",e),new Po}}generateUserAvatar(){this.loggingService.log("%c[WB] Calling FUNCTION: generateUserAvatar","color: green;");try{let e=Math.floor(Math.random()*this.avatarList.length),t=this.avatarList[e];return t.color=this.generateUserColor(),t}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 j.AVATAR_COLOR_LIST[e%j.AVATAR_COLOR_LIST.length];let t=Math.floor(Math.random()*j.AVATAR_COLOR_LIST.length);return j.AVATAR_COLOR_LIST[t]}catch(t){return this.loggingService.catch("Error in generateUserColor:",t),""}}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(t){return new(t||o)(ee(Cce),ee(y))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var Vd=(()=>{let o=class o{constructor(e){this.loggingService=e,this.actionSubjects=new Map,this.subscriptions=[]}triggerAction(e,t){try{this.actionSubjects.has(e)||this.actionSubjects.set(e,new tt),this.actionSubjects.get(e)?.next(t)}catch(r){this.loggingService.catch("Error in CoreActionsService triggerAction: ",r)}}onAction(e){try{return this.actionSubjects.has(e)||this.actionSubjects.set(e,new tt),this.actionSubjects.get(e)?.asObservable()}catch(t){return this.loggingService.catch("Error in CoreActionsService onAction: ",t),se(null)}}};o.\u0275fac=function(t){return new(t||o)(ee(y))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var{entries:wce,setPrototypeOf:_ce,isFrozen:g8e,getPrototypeOf:u8e,getOwnPropertyDescriptor:h8e}=Object,{freeze:as,seal:Vl,create:Oce}=Object,{apply:Sz,construct:bz}=typeof Reflect<"u"&&Reflect;as||(as=function(o){return o});Vl||(Vl=function(o){return o});Sz||(Sz=function(o,n,e){return o.apply(n,e)});bz||(bz=function(o,n){return new o(...n)});var Tk=ss(Array.prototype.forEach),f8e=ss(Array.prototype.lastIndexOf),yce=ss(Array.prototype.pop),Db=ss(Array.prototype.push),v8e=ss(Array.prototype.splice),wk=ss(String.prototype.toLowerCase),fz=ss(String.prototype.toString),Sce=ss(String.prototype.match),wb=ss(String.prototype.replace),C8e=ss(String.prototype.indexOf),_8e=ss(String.prototype.trim),Fc=ss(Object.prototype.hasOwnProperty),rs=ss(RegExp.prototype.test),Ob=y8e(TypeError);function ss(i){return function(o){o instanceof RegExp&&(o.lastIndex=0);for(var n=arguments.length,e=new Array(n>1?n-1:0),t=1;t<n;t++)e[t-1]=arguments[t];return Sz(i,o,e)}}function y8e(i){return function(){for(var o=arguments.length,n=new Array(o),e=0;e<o;e++)n[e]=arguments[e];return bz(i,n)}}function di(i,o){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:wk;_ce&&_ce(i,null);let e=o.length;for(;e--;){let t=o[e];if(typeof t=="string"){let r=n(t);r!==t&&(g8e(o)||(o[e]=r),t=r)}i[t]=!0}return i}function S8e(i){for(let o=0;o<i.length;o++)Fc(i,o)||(i[o]=null);return i}function Ch(i){let o=Oce(null);for(let[n,e]of wce(i))Fc(i,n)&&(Array.isArray(e)?o[n]=S8e(e):e&&typeof e=="object"&&e.constructor===Object?o[n]=Ch(e):o[n]=e);return o}function Ab(i,o){for(;i!==null;){let e=h8e(i,o);if(e){if(e.get)return ss(e.get);if(typeof e.value=="function")return ss(e.value)}i=u8e(i)}function n(){return null}return n}var bce=as(["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"]),vz=as(["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"]),Cz=as(["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"]),b8e=as(["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"]),_z=as(["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"]),I8e=as(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),Ice=as(["#text"]),Ece=as(["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"]),yz=as(["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"]),xce=as(["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"]),Dk=as(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),E8e=Vl(/\{\{[\w\W]*|[\w\W]*\}\}/gm),x8e=Vl(/<%[\w\W]*|[\w\W]*%>/gm),T8e=Vl(/\$\{[\w\W]*/gm),D8e=Vl(/^data-[\-\w.\u00B7-\uFFFF]+$/),w8e=Vl(/^aria-[\-\w]+$/),Ace=Vl(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),O8e=Vl(/^(?:\w+script|data):/i),A8e=Vl(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),Pce=Vl(/^html$/i),P8e=Vl(/^[a-z][.\w]*(-[.\w]+)+$/i),Tce=Object.freeze({__proto__:null,ARIA_ATTR:w8e,ATTR_WHITESPACE:A8e,CUSTOM_ELEMENT:P8e,DATA_ATTR:D8e,DOCTYPE_NAME:Pce,ERB_EXPR:x8e,IS_ALLOWED_URI:Ace,IS_SCRIPT_OR_DATA:O8e,MUSTACHE_EXPR:E8e,TMPLIT_EXPR:T8e}),Pb={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,progressingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},M8e=function(){return typeof window>"u"?null:window},k8e=function(o,n){if(typeof o!="object"||typeof o.createPolicy!="function")return null;let e=null,t="data-tt-policy-suffix";n&&n.hasAttribute(t)&&(e=n.getAttribute(t));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}},Dce=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function Mce(){let i=arguments.length>0&&arguments[0]!==void 0?arguments[0]:M8e(),o=Qt=>Mce(Qt);if(o.version="3.2.5",o.removed=[],!i||!i.document||i.document.nodeType!==Pb.document||!i.Element)return o.isSupported=!1,o;let{document:n}=i,e=n,t=e.currentScript,{DocumentFragment:r,HTMLTemplateElement:a,Node:s,Element:c,NodeFilter:p,NamedNodeMap:u=i.NamedNodeMap||i.MozNamedAttrMap,HTMLFormElement:C,DOMParser:E,trustedTypes:D}=i,L=c.prototype,z=Ab(L,"cloneNode"),W=Ab(L,"remove"),J=Ab(L,"nextSibling"),ue=Ab(L,"childNodes"),ye=Ab(L,"parentNode");if(typeof a=="function"){let Qt=n.createElement("template");Qt.content&&Qt.content.ownerDocument&&(n=Qt.content.ownerDocument)}let Ae,He="",{implementation:Fe,createNodeIterator:xe,createDocumentFragment:Se,getElementsByTagName:we}=n,{importNode:_e}=e,fe=Dce();o.isSupported=typeof wce=="function"&&typeof ye=="function"&&Fe&&Fe.createHTMLDocument!==void 0;let{MUSTACHE_EXPR:Oe,ERB_EXPR:Ne,TMPLIT_EXPR:Ct,DATA_ATTR:On,ARIA_ATTR:yt,IS_SCRIPT_OR_DATA:Rt,ATTR_WHITESPACE:Bt,CUSTOM_ELEMENT:In}=Tce,{IS_ALLOWED_URI:Zt}=Tce,Yt=null,Ai=di({},[...bce,...vz,...Cz,..._z,...Ice]),Xt=null,Qn=di({},[...Ece,...yz,...xce,...Dk]),zi=Object.seal(Oce(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}})),em=null,yo=null,gl=!0,zr=!0,ul=!1,Kl=!0,zc=!1,Ag=!0,Zl=!1,Pg=!1,Ah=!1,tm=!1,Ph=!1,Mg=!1,P_=!0,Mh=!1,sO="user-content-",M_=!0,nm=!1,Gc={},Wc=null,Pr=di({},["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"]),Gr=null,kg=di({},["audio","video","img","source","image","track"]),kh=null,k_=di({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Rh="http://www.w3.org/1998/Math/MathML",qc="http://www.w3.org/2000/svg",hl="http://www.w3.org/1999/xhtml",im=hl,Rg=!1,R_=null,w7=di({},[Rh,qc,hl],fz),Zm=di({},["mi","mo","mn","ms","mtext"]),Ng=di({},["annotation-xml"]),lO=di({},["title","style","font","a","script"]),Xl=null,N_=["application/xhtml+xml","text/html"],F_="text/html",So=null,om=null,Nh=n.createElement("form"),L_=function($e){return $e instanceof RegExp||$e instanceof Function},rm=function(){let $e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(om&&om===$e)){if((!$e||typeof $e!="object")&&($e={}),$e=Ch($e),Xl=N_.indexOf($e.PARSER_MEDIA_TYPE)===-1?F_:$e.PARSER_MEDIA_TYPE,So=Xl==="application/xhtml+xml"?fz:wk,Yt=Fc($e,"ALLOWED_TAGS")?di({},$e.ALLOWED_TAGS,So):Ai,Xt=Fc($e,"ALLOWED_ATTR")?di({},$e.ALLOWED_ATTR,So):Qn,R_=Fc($e,"ALLOWED_NAMESPACES")?di({},$e.ALLOWED_NAMESPACES,fz):w7,kh=Fc($e,"ADD_URI_SAFE_ATTR")?di(Ch(k_),$e.ADD_URI_SAFE_ATTR,So):k_,Gr=Fc($e,"ADD_DATA_URI_TAGS")?di(Ch(kg),$e.ADD_DATA_URI_TAGS,So):kg,Wc=Fc($e,"FORBID_CONTENTS")?di({},$e.FORBID_CONTENTS,So):Pr,em=Fc($e,"FORBID_TAGS")?di({},$e.FORBID_TAGS,So):{},yo=Fc($e,"FORBID_ATTR")?di({},$e.FORBID_ATTR,So):{},Gc=Fc($e,"USE_PROFILES")?$e.USE_PROFILES:!1,gl=$e.ALLOW_ARIA_ATTR!==!1,zr=$e.ALLOW_DATA_ATTR!==!1,ul=$e.ALLOW_UNKNOWN_PROTOCOLS||!1,Kl=$e.ALLOW_SELF_CLOSE_IN_ATTR!==!1,zc=$e.SAFE_FOR_TEMPLATES||!1,Ag=$e.SAFE_FOR_XML!==!1,Zl=$e.WHOLE_DOCUMENT||!1,tm=$e.RETURN_DOM||!1,Ph=$e.RETURN_DOM_FRAGMENT||!1,Mg=$e.RETURN_TRUSTED_TYPE||!1,Ah=$e.FORCE_BODY||!1,P_=$e.SANITIZE_DOM!==!1,Mh=$e.SANITIZE_NAMED_PROPS||!1,M_=$e.KEEP_CONTENT!==!1,nm=$e.IN_PLACE||!1,Zt=$e.ALLOWED_URI_REGEXP||Ace,im=$e.NAMESPACE||hl,Zm=$e.MATHML_TEXT_INTEGRATION_POINTS||Zm,Ng=$e.HTML_INTEGRATION_POINTS||Ng,zi=$e.CUSTOM_ELEMENT_HANDLING||{},$e.CUSTOM_ELEMENT_HANDLING&&L_($e.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(zi.tagNameCheck=$e.CUSTOM_ELEMENT_HANDLING.tagNameCheck),$e.CUSTOM_ELEMENT_HANDLING&&L_($e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(zi.attributeNameCheck=$e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),$e.CUSTOM_ELEMENT_HANDLING&&typeof $e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(zi.allowCustomizedBuiltInElements=$e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),zc&&(zr=!1),Ph&&(tm=!0),Gc&&(Yt=di({},Ice),Xt=[],Gc.html===!0&&(di(Yt,bce),di(Xt,Ece)),Gc.svg===!0&&(di(Yt,vz),di(Xt,yz),di(Xt,Dk)),Gc.svgFilters===!0&&(di(Yt,Cz),di(Xt,yz),di(Xt,Dk)),Gc.mathMl===!0&&(di(Yt,_z),di(Xt,xce),di(Xt,Dk))),$e.ADD_TAGS&&(Yt===Ai&&(Yt=Ch(Yt)),di(Yt,$e.ADD_TAGS,So)),$e.ADD_ATTR&&(Xt===Qn&&(Xt=Ch(Xt)),di(Xt,$e.ADD_ATTR,So)),$e.ADD_URI_SAFE_ATTR&&di(kh,$e.ADD_URI_SAFE_ATTR,So),$e.FORBID_CONTENTS&&(Wc===Pr&&(Wc=Ch(Wc)),di(Wc,$e.FORBID_CONTENTS,So)),M_&&(Yt["#text"]=!0),Zl&&di(Yt,["html","head","body"]),Yt.table&&(di(Yt,["tbody"]),delete em.tbody),$e.TRUSTED_TYPES_POLICY){if(typeof $e.TRUSTED_TYPES_POLICY.createHTML!="function")throw Ob('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof $e.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw Ob('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');Ae=$e.TRUSTED_TYPES_POLICY,He=Ae.createHTML("")}else Ae===void 0&&(Ae=k8e(D,t)),Ae!==null&&typeof He=="string"&&(He=Ae.createHTML(""));as&&as($e),om=$e}},B_=di({},[...vz,...Cz,...b8e]),Wr=di({},[..._z,...I8e]),cO=function($e){let Dt=ye($e);(!Dt||!Dt.tagName)&&(Dt={namespaceURI:im,tagName:"template"});let qt=wk($e.tagName),so=wk(Dt.tagName);return R_[$e.namespaceURI]?$e.namespaceURI===qc?Dt.namespaceURI===hl?qt==="svg":Dt.namespaceURI===Rh?qt==="svg"&&(so==="annotation-xml"||Zm[so]):!!B_[qt]:$e.namespaceURI===Rh?Dt.namespaceURI===hl?qt==="math":Dt.namespaceURI===qc?qt==="math"&&Ng[so]:!!Wr[qt]:$e.namespaceURI===hl?Dt.namespaceURI===qc&&!Ng[so]||Dt.namespaceURI===Rh&&!Zm[so]?!1:!Wr[qt]&&(lO[qt]||!B_[qt]):!!(Xl==="application/xhtml+xml"&&R_[$e.namespaceURI]):!1},Ea=function($e){Db(o.removed,{element:$e});try{ye($e).removeChild($e)}catch{W($e)}},Yc=function($e,Dt){try{Db(o.removed,{attribute:Dt.getAttributeNode($e),from:Dt})}catch{Db(o.removed,{attribute:null,from:Dt})}if(Dt.removeAttribute($e),$e==="is")if(tm||Ph)try{Ea(Dt)}catch{}else try{Dt.setAttribute($e,"")}catch{}},dO=function($e){let Dt=null,qt=null;if(Ah)$e="<remove></remove>"+$e;else{let kr=Sce($e,/^[\r\n\t ]+/);qt=kr&&kr[0]}Xl==="application/xhtml+xml"&&im===hl&&($e='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+$e+"</body></html>");let so=Ae?Ae.createHTML($e):$e;if(im===hl)try{Dt=new E().parseFromString(so,Xl)}catch{}if(!Dt||!Dt.documentElement){Dt=Fe.createDocument(im,"template",null);try{Dt.documentElement.innerHTML=Rg?He:so}catch{}}let Mr=Dt.body||Dt.documentElement;return $e&&qt&&Mr.insertBefore(n.createTextNode(qt),Mr.childNodes[0]||null),im===hl?we.call(Dt,Zl?"html":"body")[0]:Zl?Dt.documentElement:Mr},mO=function($e){return xe.call($e.ownerDocument||$e,$e,p.SHOW_ELEMENT|p.SHOW_COMMENT|p.SHOW_TEXT|p.SHOW_PROCESSING_INSTRUCTION|p.SHOW_CDATA_SECTION,null)},Kc=function($e){return $e instanceof C&&(typeof $e.nodeName!="string"||typeof $e.textContent!="string"||typeof $e.removeChild!="function"||!($e.attributes instanceof u)||typeof $e.removeAttribute!="function"||typeof $e.setAttribute!="function"||typeof $e.namespaceURI!="string"||typeof $e.insertBefore!="function"||typeof $e.hasChildNodes!="function")},pO=function($e){return typeof s=="function"&&$e instanceof s};function Ql(Qt,$e,Dt){Tk(Qt,qt=>{qt.call(o,$e,Dt,om)})}let Fg=function($e){let Dt=null;if(Ql(fe.beforeSanitizeElements,$e,null),Kc($e))return Ea($e),!0;let qt=So($e.nodeName);if(Ql(fe.uponSanitizeElement,$e,{tagName:qt,allowedTags:Yt}),$e.hasChildNodes()&&!pO($e.firstElementChild)&&rs(/<[/\w!]/g,$e.innerHTML)&&rs(/<[/\w!]/g,$e.textContent)||$e.nodeType===Pb.progressingInstruction||Ag&&$e.nodeType===Pb.comment&&rs(/<[/\w]/g,$e.data))return Ea($e),!0;if(!Yt[qt]||em[qt]){if(!em[qt]&&Fh(qt)&&(zi.tagNameCheck instanceof RegExp&&rs(zi.tagNameCheck,qt)||zi.tagNameCheck instanceof Function&&zi.tagNameCheck(qt)))return!1;if(M_&&!Wc[qt]){let so=ye($e)||$e.parentNode,Mr=ue($e)||$e.childNodes;if(Mr&&so){let kr=Mr.length;for(let Rr=kr-1;Rr>=0;--Rr){let js=z(Mr[Rr],!0);js.__removalCount=($e.__removalCount||0)+1,so.insertBefore(js,J($e))}}}return Ea($e),!0}return $e instanceof c&&!cO($e)||(qt==="noscript"||qt==="noembed"||qt==="noframes")&&rs(/<\/no(script|embed|frames)/i,$e.innerHTML)?(Ea($e),!0):(zc&&$e.nodeType===Pb.text&&(Dt=$e.textContent,Tk([Oe,Ne,Ct],so=>{Dt=wb(Dt,so," ")}),$e.textContent!==Dt&&(Db(o.removed,{element:$e.cloneNode()}),$e.textContent=Dt)),Ql(fe.afterSanitizeElements,$e,null),!1)},V_=function($e,Dt,qt){if(P_&&(Dt==="id"||Dt==="name")&&(qt in n||qt in Nh))return!1;if(!(zr&&!yo[Dt]&&rs(On,Dt))){if(!(gl&&rs(yt,Dt))){if(!Xt[Dt]||yo[Dt]){if(!(Fh($e)&&(zi.tagNameCheck instanceof RegExp&&rs(zi.tagNameCheck,$e)||zi.tagNameCheck instanceof Function&&zi.tagNameCheck($e))&&(zi.attributeNameCheck instanceof RegExp&&rs(zi.attributeNameCheck,Dt)||zi.attributeNameCheck instanceof Function&&zi.attributeNameCheck(Dt))||Dt==="is"&&zi.allowCustomizedBuiltInElements&&(zi.tagNameCheck instanceof RegExp&&rs(zi.tagNameCheck,qt)||zi.tagNameCheck instanceof Function&&zi.tagNameCheck(qt))))return!1}else if(!kh[Dt]){if(!rs(Zt,wb(qt,Bt,""))){if(!((Dt==="src"||Dt==="xlink:href"||Dt==="href")&&$e!=="script"&&C8e(qt,"data:")===0&&Gr[$e])){if(!(ul&&!rs(Rt,wb(qt,Bt,"")))){if(qt)return!1}}}}}}return!0},Fh=function($e){return $e!=="annotation-xml"&&Sce($e,In)},Lg=function($e){Ql(fe.beforeSanitizeAttributes,$e,null);let{attributes:Dt}=$e;if(!Dt||Kc($e))return;let qt={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:Xt,forceKeepAttr:void 0},so=Dt.length;for(;so--;){let Mr=Dt[so],{name:kr,namespaceURI:Rr,value:js}=Mr,am=So(kr),sr=kr==="value"?js:_8e(js);if(qt.attrName=am,qt.attrValue=sr,qt.keepAttr=!0,qt.forceKeepAttr=void 0,Ql(fe.uponSanitizeAttribute,$e,qt),sr=qt.attrValue,Mh&&(am==="id"||am==="name")&&(Yc(kr,$e),sr=sO+sr),Ag&&rs(/((--!?|])>)|<\/(style|title)/i,sr)){Yc(kr,$e);continue}if(qt.forceKeepAttr||(Yc(kr,$e),!qt.keepAttr))continue;if(!Kl&&rs(/\/>/i,sr)){Yc(kr,$e);continue}zc&&Tk([Oe,Ne,Ct],Lh=>{sr=wb(sr,Lh," ")});let Xc=So($e.nodeName);if(V_(Xc,am,sr)){if(Ae&&typeof D=="object"&&typeof D.getAttributeType=="function"&&!Rr)switch(D.getAttributeType(Xc,am)){case"TrustedHTML":{sr=Ae.createHTML(sr);break}case"TrustedScriptURL":{sr=Ae.createScriptURL(sr);break}}try{Rr?$e.setAttributeNS(Rr,kr,sr):$e.setAttribute(kr,sr),Kc($e)?Ea($e):yce(o.removed)}catch{}}}Ql(fe.afterSanitizeAttributes,$e,null)},Zc=function Qt($e){let Dt=null,qt=mO($e);for(Ql(fe.beforeSanitizeShadowDOM,$e,null);Dt=qt.nextNode();)Ql(fe.uponSanitizeShadowNode,Dt,null),Fg(Dt),Lg(Dt),Dt.content instanceof r&&Qt(Dt.content);Ql(fe.afterSanitizeShadowDOM,$e,null)};return o.sanitize=function(Qt){let $e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},Dt=null,qt=null,so=null,Mr=null;if(Rg=!Qt,Rg&&(Qt="<!-->"),typeof Qt!="string"&&!pO(Qt))if(typeof Qt.toString=="function"){if(Qt=Qt.toString(),typeof Qt!="string")throw Ob("dirty is not a string, aborting")}else throw Ob("toString is not a function");if(!o.isSupported)return Qt;if(Pg||rm($e),o.removed=[],typeof Qt=="string"&&(nm=!1),nm){if(Qt.nodeName){let js=So(Qt.nodeName);if(!Yt[js]||em[js])throw Ob("root node is forbidden and cannot be sanitized in-place")}}else if(Qt instanceof s)Dt=dO("<!---->"),qt=Dt.ownerDocument.importNode(Qt,!0),qt.nodeType===Pb.element&&qt.nodeName==="BODY"||qt.nodeName==="HTML"?Dt=qt:Dt.appendChild(qt);else{if(!tm&&!zc&&!Zl&&Qt.indexOf("<")===-1)return Ae&&Mg?Ae.createHTML(Qt):Qt;if(Dt=dO(Qt),!Dt)return tm?null:Mg?He:""}Dt&&Ah&&Ea(Dt.firstChild);let kr=mO(nm?Qt:Dt);for(;so=kr.nextNode();)Fg(so),Lg(so),so.content instanceof r&&Zc(so.content);if(nm)return Qt;if(tm){if(Ph)for(Mr=Se.call(Dt.ownerDocument);Dt.firstChild;)Mr.appendChild(Dt.firstChild);else Mr=Dt;return(Xt.shadowroot||Xt.shadowrootmode)&&(Mr=_e.call(e,Mr,!0)),Mr}let Rr=Zl?Dt.outerHTML:Dt.innerHTML;return Zl&&Yt["!doctype"]&&Dt.ownerDocument&&Dt.ownerDocument.doctype&&Dt.ownerDocument.doctype.name&&rs(Pce,Dt.ownerDocument.doctype.name)&&(Rr="<!DOCTYPE "+Dt.ownerDocument.doctype.name+`>
196
+ `+Rr),zc&&Tk([Oe,Ne,Ct],js=>{Rr=wb(Rr,js," ")}),Ae&&Mg?Ae.createHTML(Rr):Rr},o.setConfig=function(){let Qt=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};rm(Qt),Pg=!0},o.clearConfig=function(){om=null,Pg=!1},o.isValidAttribute=function(Qt,$e,Dt){om||rm({});let qt=So(Qt),so=So($e);return V_(qt,so,Dt)},o.addHook=function(Qt,$e){typeof $e=="function"&&Db(fe[Qt],$e)},o.removeHook=function(Qt,$e){if($e!==void 0){let Dt=f8e(fe[Qt],$e);return Dt===-1?void 0:v8e(fe[Qt],Dt,1)[0]}return yce(fe[Qt])},o.removeHooks=function(Qt){fe[Qt]=[]},o.removeAllHooks=function(){fe=Dce()},o}var Iz=Mce();var kce={ADD_TAGS:["velt-skeleton-loader"],ADD_ATTR:["border-radius"]},Be=(()=>{let o=class o{constructor(e,t,r,a){this.analyticsService=e,this.rendererFactory2=t,this.loggingService=r,this.sanitizer=a,this.isVideoEditorHandlingDelete=!1,this.pageScrollHeight=0,this.enableRectSelectionSubject$=new ve(!1),this.enableRectSelection$=this.enableRectSelectionSubject$.asObservable(),this.scrollableElementsIds$=new ve([]),this.mousedown=!1,this.windowMouseDown$=new tt,this.windowPointerMove$=new ve(null),this.windowPointerUp$=new ve(null),this.documentSelectionChange$=new ve(null),this.windowClick$=new ve(null),this.windowScroll$=new ve(null),this.windowResize$=new ve(null),this.windowKeyupBackspace$=new ve(null),this.windowKeyupDelete$=new ve(null),this.windowKeyupEsc$=new ve(null),this.windowPopState$=new ve(null),this.documentClick$=new ve(null),this.documentClickSubject$=new tt,this.documentFocus$=new ve(null),this.windowKeydownShift$=new ve(null),this.windowKeyupShift$=new ve(null),this.mutation$=new ve(null),this.childListMutation$=new ve(null),this.networkStatus$=new ve(!1),this.xpathCache=new Map,this.xpathCacheId=new Map,this.selectedAnnotationsMap$=new ve({}),this.selectedAnnotationsLocationMap$=new ve({}),this.recordingInProgress$=new ve({}),this.deleteAnnotations$=new ve([]),this.pinHighlighterClass$=new ve(null),this.dialogOpenedInSidebar$=new ve(!1),this.textHighlighterClass$=new ve(null),this.commentPinHighlighter$=new ve(!1),this.deviceInfo$=new ve(new zn),this.customCss$=new ve(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=s=>{try{let c=[];return s.forEach(p=>{if(!Xi(p))if(p instanceof HTMLElement){if(p.className.includes("cdk-overlay-container")||p.className.includes("cdk-overlay-connected-position-bounding-box"))return;if(p.className.includes("cdk-overlay")){let u=!1;p.childNodes.forEach(C=>{Xi(C)&&(u=!0)}),u||c.push(p)}else c.push(p)}else c.push(p)}),c}catch(c){return this.loggingService.catch("Error in DomService filterSnippylyNodes: ",c),[]}},this.loggingService.log("%c[WB] Creating CLASS: DomService","color: blue;");try{this.analyticsService.setDomService(this),this.renderer=this.rendererFactory2.createRenderer(null,null);let s=this.calculateScreenSize();this.currentScreenSize$=new ve(s),this.currentMousePosition$=new ve(this.currentMousePosition),this.detectNetworkStatusChange(),this.getScrollableElementsIds$().pipe(Bi(),dn(([c,p])=>{try{let u=p.filter(E=>!c.includes(E)),C=c.filter(E=>!p.includes(E));C.length&&C.map(D=>document.getElementById(D)).filter(D=>D).forEach(D=>{this.unlistenElementScroll&&this.unlistenElementScroll[D.id]&&this.unlistenElementScroll[D.id]()}),u.length&&u.map(D=>document.getElementById(D)).filter(D=>D).forEach(D=>{this.unlistenElementScroll[D.id]=this.renderer.listen(D,"scroll",L=>{let z=this.calculateScreenSize();this.currentScreenSize$.next(z)})})}catch(u){this.loggingService.catch("Error in DomService getScrollableElementsIds subscription: ",u)}})).subscribe(()=>{},c=>{this.loggingService.catch("Error in DomService getScrollableElementsIds subscription: ",c)}),this.getSelectedAnnotationsMap$().subscribe(c=>{Object.keys(c||{})?.length?cae("snippylyUserScalableNo","viewport","width=device-width, user-scalable=no"):dae("snippylyUserScalableNo")},c=>{this.loggingService.catch("Error in DomService getSelectedAnnotationsMap$ subscription: ",c)})}catch(s){this.loggingService.catch("Error in DomService constructor: ",s)}}setDocService(e){try{this.docService=e,this.subscribeToDomEvents()}catch(t){this.loggingService.catch("Error in DomService setDocService: ",t)}}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.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.unsubscribeFromDocumentFocus(),this.unsetMutationObserver())})).subscribe(),Sn([this.docService?.getOrganizationConfig$(),this.docService?.getDocumentPaths$()]).pipe(ce(([e,t])=>!!e||!!t),Et(),ce(e=>{e?this.onDocumentClick():this.unsubscribeFromDocumentClick()})).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(t){this.loggingService.catch("Error in DomService setScrollableElementsIds: ",t)}}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(t=>{try{if(t?.find(a=>a?.attributeName===j.VELT_IGNORE_CHANGE_DETECTION))return;let r=t.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 u=p.getAttribute(j.ATTRIBUTES.VELT_ELEMENT_CACHE_ID);if(u!==null&&u!==""){let C=this.xpathCacheId.get(u);C!==void 0&&(this.xpathCacheId.delete(u),this.xpathCache.delete(C))}}}),Xi(s)?!1:!!(this.filterSnippylyNodes(a.addedNodes).length||this.filterSnippylyNodes(a.removedNodes).length)});this.childListMutation$.next(r),r.push(...t.filter(a=>a.type==="attributes").filter(a=>!Xi(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(j.VELT_IGNORE_CHANGE_DETECTION):!0}return!0})),r=r.filter(a=>{let s=!0;return Object.keys(j.INGNORE_MUTATION_OBSERVER_CHANGE_TAGS).forEach(c=>{a.target?.closest(c)&&(s=!1)}),s}),r=r.filter(a=>a.target&&Ao(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(t){this.loggingService.catch("Error in DomService change detection: ",t)}}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{co(pi(window,"offline").pipe(ce(()=>!1)),pi(window,"online").pipe(ce(()=>!0)),new Ut(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 t=this.calculateScreenSize();this.deviceInfo$.next(new zn),this.currentScreenSize$.next(t)})}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 t=this.calculateScreenSize();this.currentScreenSize$.next(t)})}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()!==j.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 pi(window,"keydown")}catch(e){return this.loggingService.catch("Error in DomService onWindowKeydown$: ",e),Gg}}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 t=this.getXPath(e.target),r=e.target;if(t?.includes("name()='svg'")){let C=this.getXPath(t);C&&(r=C.iterateNext()||e.target)}let a=r.getBoundingClientRect(),s=e.clientX-a.x,c=e.clientY-a.y,p=s*100/(a.width||1),u=c*100/(a.height||1);this.currentMousePosition.element={xpath:t,topPercentage:u,leftPercentage:p}}else this.currentMousePosition.element=null;this.currentMousePosition$.next(this.currentMousePosition)}catch(t){this.loggingService.catch("Error in DomService updateCurrentMousePosition: ",t)}}getTargetElementForCursorPosition(e,t=!0,r=!1,a=!0,s){try{let c=e,p=c?.touches?.length?c.touches[0]?.clientX:c.clientX,u=c?.touches?.length?c.touches[0]?.clientY:c.clientY,C=this.getBackgroundElement(p,u,t,r);if(C&&s&&typeof s=="function"&&(C=s(C)),C){let E=this.getXPath(C),D=this.getXPath(C,!0),L=C.getBoundingClientRect(),z=p-L.x,W=u-L.y,J=z*100/(L.width||1),ue=W*100/(L.height||1),ye={xpath:E,fXpath:D,leftPercentage:J,topPercentage:ue};if(a){let Ae=this.getXPath(C,!0,!0);ye.cfXpath=Ae}return ye}else return null}catch(c){return this.loggingService.catch("Error in DomService getTargetElementForCommentPinAnnotation: ",c),null}}getBackgroundElement(e,t,r=!0,a=!1){try{let s=document.elementsFromPoint(e,t),c=[];s.forEach(u=>{Xi(u)?c=[]:Ao(u)&&c.push(u)}),a&&(c=c.filter(u=>this.isElementVisibleOnScreen(u)));let p=0;return r||c?.forEach((u,C)=>{u.tagName.toLowerCase()==="svg"&&(p=C)}),c[p]}catch(s){return this.loggingService.catch("Error in DomService getBackgroundElement: ",s),null}}getBackgroundVeltElement(e,t){try{let r=document.elementsFromPoint(e,t),a=[];return r.forEach(s=>{Xi(s)&&Ao(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(t){this.loggingService.catch("Error in DomService setPointerPosition: ",t)}}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(),t=this.currentMousePosition?.pageX||e.x+200,r=Math.min(t,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,t,r){if(e){if(!r&&this.getCommentPinHighlighter()&&(this.pinHighlighterClass$.value?this.addClassToElement(e,this.pinHighlighterClass$.value):this.addClassToElement(e,j.SNIPPYLY_HIGHLIGHT)),t&&!e.hasAttribute(j.ATTRIBUTES.DEFAULT_CURSOR)){let a=e.style.getPropertyValue("cursor"),s=e.style.getPropertyPriority("cursor"),c=a?{defaultCursorValue:a,defaultCursorPriority:s}:"";e.setAttribute(j.ATTRIBUTES.DEFAULT_CURSOR,c?JSON.stringify(c):""),e.style.setProperty("cursor",t,"important")}e.setAttribute(j.SNIPPYLY_HIGHLIGHT,"true"),e.setAttribute(j.VELT_IGNORE_CHANGE_DETECTION,"true")}}removeHighlightFromElement(e){if(e&&(this.pinHighlighterClass$.value&&this.removeClassFromElement(e,this.pinHighlighterClass$.value),this.removeClassFromElement(e,j.SNIPPYLY_HIGHLIGHT),e.removeAttribute(j.SNIPPYLY_HIGHLIGHT),e.removeAttribute(j.VELT_IGNORE_CHANGE_DETECTION),e.hasAttribute(j.ATTRIBUTES.DEFAULT_CURSOR))){try{if(e.style.removeProperty("cursor"),e.getAttribute(j.ATTRIBUTES.DEFAULT_CURSOR)){let t=JSON.parse(e.getAttribute(j.ATTRIBUTES.DEFAULT_CURSOR));e.style.setProperty("cursor",t.defaultCursorValue,t.defaultCursorPriority)}}catch{}e.removeAttribute(j.ATTRIBUTES.DEFAULT_CURSOR)}}highlightUserElement(e,t,r,a=!1){try{e&&(this.addClassToElement(e,j.VELT_LIVE_SELECTION_ON_ELEMENT),a&&this.addClassToElement(e,j.VELT_LIVE_SELECTION_ON_ELEMENT_DEFAULT),e.setAttribute(j.SNIPPYLY_HIGHLIGHT,"true"),e.setAttribute(j.VELT_IGNORE_CHANGE_DETECTION,"true"),t&&!e.style.getPropertyValue(j.VELT_SELECTION_COLOR)&&e.style.setProperty(j.VELT_SELECTION_COLOR,t),r&&e.setAttribute(j.SNIPPYLY_HIGHLIGHT_USER_NAME,r))}catch(s){this.loggingService.catch("Error in DomService highlightUserElement: ",s)}}removeHighlightUserFromElement(e){try{e&&(this.removeClassFromElement(e,j.VELT_LIVE_SELECTION_ON_ELEMENT),this.removeClassFromElement(e,j.VELT_LIVE_SELECTION_ON_ELEMENT_DEFAULT),e.removeAttribute(j.SNIPPYLY_HIGHLIGHT),e.removeAttribute(j.VELT_IGNORE_CHANGE_DETECTION),e.removeAttribute(j.VELT_SELECTION_COLOR),e.removeAttribute(j.SNIPPYLY_HIGHLIGHT_USER_NAME),e.style.removeProperty(j.VELT_SELECTION_COLOR))}catch(t){this.loggingService.catch("Error in DomService removeHighlightUserFromElement: ",t)}}previewHighlightElement(e){e&&e.setAttribute(j.SNIPPYLY_HIGHLIGHT_PREVIEW,"true")}removePreviewHighlightFromElement(e){e&&e.removeAttribute(j.SNIPPYLY_HIGHLIGHT_PREVIEW)}getXPath(e,t=!1,r=!1,a){try{let s=this.calculateXPath(e,t,r,a);if(s&&typeof s=="string"&&s.includes("/svg")){let c=s.split("/"),p=!1;c.forEach((u,C)=>{u.includes("svg")&&(p=!0),p&&(c[C]="svg:"+u)}),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,t,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&&!t)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,t,r,a)+"/"+e.tagName.toLowerCase(),u=Array.from(e.parentNode?.children||[]).filter(C=>C.nodeType===1&&C.tagName===e.tagName?C.className?.split(" ")?.filter(D=>D?.includes("snippyly")||D?.includes("velt")||["show-pin-cursor"].includes(D))[0]===c:!1);if(u.length>1){let C=u.indexOf(e)+1;p+=`[contains(concat(' ', normalize-space(@class), ' '), ' ${c} ')][${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,t,r)+"/"+e.tagName.toLowerCase()+(s.length>1?"["+([].indexOf.call(s,e)+1)+"]":"")}}catch(s){this.loggingService.catch("Error in DomService calculateXPath:",s)}}getElementFromXPath(e,t=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,t);if(r){let a=r?.iterateNext();if(a!==null&&typeof a.setAttribute=="function"){let s=xn();a.setAttribute(j.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],t=[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 bb;return r.screenWidth=Math.max(...t),r.screenHeight=Math.max(...e),r.screenScrollHeight=this.pageScrollHeight,r}catch(e){return this.loggingService.catch("Error in DomService calculateScreenSize:",e),new bb}}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),u;for(;u=p.nextNode();)u?.remove();return this.mergeAdjacentTextNodes(r.body),this.sanitizeHtml(r.body.innerHTML)}catch(t){return this.loggingService.catch("Error in DomService removeSnippylyContent: ",t),e}}mergeAdjacentTextNodes(e){try{let t=e.firstChild;for(;t;){if(t.nodeType===Node.TEXT_NODE){let r=t.nextSibling;for(;r&&r.nodeType===Node.TEXT_NODE;)t.textContent+=r.textContent,r.remove(),r=t.nextSibling}t=t.nextSibling}}catch(t){this.loggingService.catch("Error in DomService mergeAdjacentTextNodes: ",t)}}findLongestNode(e){try{for(let t=e.length-1;t>=0;t--){if(e[t]?.scrollHeight&&e[t]?.clientHeight){let r=Math.max(e[t]?.scrollHeight,e[t]?.clientHeight);this.pageScrollHeight=Math.max(r,this.pageScrollHeight),this.nodeMap[r]=e[t]}e[t]?.childNodes?.length&&this.findLongestNode(e[t]?.childNodes)}}catch(t){this.loggingService.catch("Error in DomService findLongestNode: ",t)}}resetSelectedAnnotationsMap(e=!0,t){try{let r=Array.from(document.querySelectorAll(`[${j.ATTRIBUTES.VELT_ANNOTATION_DRAFT}]`)),a=this.getDraftCommentAnnotationDialogs()||[];r.push(...a),r=Array.from(new Set(r));let s=r.map(C=>C.classList.contains("velt-annotation-draft-checked")?(C.classList.remove("velt-annotation-draft-checked"),null):(this.removeClassFromElement(C,"velt-comment-dialog-shake"),setTimeout(()=>{this.addClassToElement(C,"velt-comment-dialog-shake"),C.getAttribute(j.ATTRIBUTES.VELT_ANNOTATION_EDIT_COMMENT)||C.classList.contains("velt-annotation-draft-checked")||this.addClassToElement(C,"velt-annotation-draft-checked")},100),C.getAttribute(j.ATTRIBUTES.VELT_ANNOTATION_DRAFT))).filter(C=>C),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 C=[];Object.keys(p).forEach(E=>{if(p[E]?.type==="tag"){let D=p[E];D?.to?.length||s.includes(E)||C.push(D)}else p[E]?.comments?.length||s.includes(E)||C.push(p[E])}),this.deleteAnnotations$.next(C),this.deleteAnnotations$.next([])}let u={};Object.keys(p).forEach(C=>{if(s.includes(C)&&(u[C]=p[C]),t)switch(t){case"comment":["comment","videoPin"].includes(p[C]?.type)||(u[C]=p[C]);break;default:p[C]?.type!==t&&(u[C]=p[C]);break}}),Object.keys(u).forEach(C=>{let E=u[C]?.multiThreadAnnotationId;E&&!u[E]&&(u[E]={annotationId:E,type:"multiThread"})}),JSON.stringify(this.selectedAnnotationsMap$.value)!==JSON.stringify(u)&&this.selectedAnnotationsMap$.next(u),this.setDialogOpenedInSidebar(!1)}catch(r){this.loggingService.catch("Error in DomService resetSelectedAnnotationsMap: ",r)}}setRecordingInProgress(e,t){try{if(t)this.recordingInProgress$.next(T(I({},this.recordingInProgress$.value),{[e]:t}));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(`${j.TAGS.SNIPPYLY_COMMENT_DIALOG}`)).forEach(r=>{if(r?.shadowRoot){let a=r.shadowRoot.querySelector(`[${j.ATTRIBUTES.VELT_ANNOTATION_DRAFT}]`);a&&e.push(a)}else{let a=r.querySelector(`${j.TAGS.VELT_SHADOW_DOM_INTERNAL}`);if(a?.shadowRoot){let s=a.shadowRoot?.querySelector(`[${j.ATTRIBUTES.VELT_ANNOTATION_DRAFT}]`);s&&e.push(s)}else{let s=r.querySelector(`[${j.ATTRIBUTES.VELT_ANNOTATION_DRAFT}]`);s&&e.push(s)}}}),e}catch(e){return this.loggingService.catch("Error in DomService getDraftCommentAnnotationDialogs: ",e),[]}}getSelectedAnnotationsMap(e){try{let t=this.selectedAnnotationsMap$.value;if(e){let r={};return Object.keys(t).forEach(a=>{switch(e){case"comment":["comment","videoPin"].includes(t[a].type)&&(r[a]=t[a]);break;default:t[a].type===e&&(r[a]=t[a]);break}}),r}else return t}catch(t){return this.loggingService.catch("Error in DomService getSelectedAnnotationsMap: ",t),{}}}getSelectedAnnotationsMap$(e){return this.selectedAnnotationsMap$.asObservable().pipe(ce(t=>{if(e){let r={};return Object.keys(t).forEach(a=>{t[a].type===e&&(r[a]=t[a])}),r}else return t}))}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,t,r,a=!1,s){try{r==="sidebarShowReplies"?this.setDialogOpenedInSidebar(!0):this.setDialogOpenedInSidebar(!1);let c=JSON.parse(JSON.stringify(this.selectedAnnotationsMap$.value||{})),p=JSON.parse(JSON.stringify(this.selectedAnnotationsLocationMap$.value||{}));c[e.annotationId]&&!a?delete c[e.annotationId]:((!this.windowKeydownShift$.value||a)&&(c={}),c[e.annotationId]=e,p[e.annotationId]=t,s=e?.multiThreadAnnotationId||s,s&&(c[s]={annotationId:s,type:"multiThread"},p[s]=t)),this.selectedAnnotationsMap$.next(c),Object.keys(p).forEach(u=>{c[u]||delete p[u]}),this.selectedAnnotationsLocationMap$.next(p)}catch(c){this.loggingService.catch("Error in DomService toggleAnnotationSelection: ",c)}}setSelectedAnnotationLocation(e,t){try{let r=JSON.parse(JSON.stringify(this.getSelectedAnnotationsLocationMap()||{}));r?.[e]!==t&&(r[e]=t,this.selectedAnnotationsLocationMap$.next(r))}catch(r){this.loggingService.catch("Error in DomService setSelectedAnnotationLocation: ",r)}}updateSelectedAnnotationInMap(e){try{let t=this.selectedAnnotationsMap$.value;e.forEach(r=>{t[r.annotationId]&&(t[r.annotationId]=r)}),this.selectedAnnotationsMap$.next(t)}catch(t){this.loggingService.catch("Error in DomService updateSelectedAnnotationInMap: ",t)}}getDeleteCommmentAnnotations$(){try{return this.deleteAnnotations$.asObservable()}catch(e){return this.loggingService.catch("Error in DomService getDeleteCommmentAnnotations$: ",e),se([])}}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(t){return this.loggingService.catch("Error in DomService onDomChange$: ",t),se([])}}getChildListMutation$(){return this.childListMutation$.asObservable()}onNetworkStatusChange$(){return this.networkStatus$.asObservable()}getNetworkStatus(){return this.networkStatus$.value}getElementOffset(e,t){try{let r={offsetTop:0,offsetLeft:0},a=e;if(a===t){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!==t)if(e?.closest("svg"))for(;a&&a!==t;){let c=window.getComputedStyle(a);if(a.tagName.toLowerCase()==="svg"||a instanceof SVGElement){let p=a.parentElement;if(p){let u=p.getBoundingClientRect(),C=a.getBoundingClientRect();r.offsetLeft+=C.left-u.left,r.offsetTop+=C.top-u.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===t){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:t,height:r,top:a,bottom:s}=e?.getBoundingClientRect();return t>0||r>0||a<window.innerHeight&&s>0}else return!1}catch(t){return this.loggingService.catch("Error in DomService isElementVisible: ",t),!1}}isElementVisibleOnScreen(e){try{if(e){if(!(e instanceof Element))return!1;let t=e,r=window.getComputedStyle(t);return!(r.display==="none"||r.visibility==="hidden"||parseFloat(r.opacity)===0)}return!1}catch(t){return this.loggingService.catch("Error in DomService isElementVisibleOnScreen: ",t),!1}}getClickAndDragPointsObservable(){return new Ut(e=>{let t=pi(document,"mousedown").pipe(ce(p=>({type:p.type,x:p.clientX+window.scrollX,y:p.clientY+window.scrollY,event:p}))),r=pi(document,"mousemove").pipe(ce(p=>({type:p.type,x:p.clientX+window.scrollX,y:p.clientY+window.scrollY,event:p}))),a=pi(document,"mouseup").pipe(ce(p=>({type:p.type,x:p.clientX+window.scrollX,y:p.clientY+window.scrollY,event:p}))),c=t.pipe(he(p=>r.pipe(Bi(),ce(([u,C])=>({startPoint:p,prevPoint:u,curPoint:C})),mo(a)))).subscribe(e);return()=>c.unsubscribe()})}drawRectangle(e,t){let r=document.querySelector(".rectangle");r||(r=document.createElement("div"),this.addClassToElement(r,"rectangle"),r.setAttribute(j.ATTRIBUTES.VELT_COMMENT_DISABLED,"true"),r.setAttribute(j.VELT_IGNORE_CHANGE_DETECTION,"true"),document.body.appendChild(r));let a=Math.abs(t.x-e.x),s=Math.abs(t.y-e.y),c=Math.min(e.x,t.x),p=Math.min(e.y,t.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 t={},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),t.commonAncestorContainer=this.getTextXPath(a),t.commonAncestorContainer){let c=this.getElementFromXPath(t.commonAncestorContainer);c&&(t.commonAncestorContainerFXpath=this.getXPath(c,!0),t.commonAncestorContainerCFXpath=this.getXPath(c,!0,!0))}return t.text=e.toString(),t.occurrence=th(a,0,e.startContainer,e.startOffset,e.toString())+1,t}catch(t){this.loggingService.catch("Error in DomService getTargetTextRangeFromSelectionRange: ",t);return}}getTextXPath(e){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: getTextXPath","color: green;"),e.nodeType===Node.TEXT_NODE){let t=1,r=e.previousSibling;for(;r;)r.nodeType===Node.TEXT_NODE&&t++,r=r.previousSibling;return this.getXPath(e.parentElement)}else return this.getXPath(e)}catch(t){this.loggingService.catch("Error in DomService getTextXPath: ",t);return}}getHostElement(e){try{if(j.NON_NESTABLE_ELEMENTS[e?.tagName?.toLowerCase()]){let r=e?.closest("picture");return r?r?.parentElement:e.parentElement}let t=e.closest("svg");return t?t?.parentElement:e}catch(t){return this.loggingService.catch("Error in DomService getHostElement: ",t),e}}isElementInsideAdditionalLocationContainer(e){try{return!!e?.closest(`[${j.ATTRIBUTES.VELT_LOCATION}], [${j.ATTRIBUTES.VELT_LOCATION_ID}]`)}catch(t){return this.loggingService.catch("Error in DomService isElementInsideAdditionalLocationContainer: ",t),!1}}getAdditionalLocationContainer(e){try{return e?.closest(`[${j.ATTRIBUTES.VELT_LOCATION}], [${j.ATTRIBUTES.VELT_LOCATION_ID}]`)||null}catch(t){return this.loggingService.catch("Error in DomService getAdditionalLocationContainer: ",t),null}}isXpathWithId(e){try{return typeof e=="string"?!!e?.includes("[@id="):!1}catch(t){return this.loggingService.catch("Error in DomService isXpathWithId: ",t),!1}}getListedElements({elementIds:e,elementClassNames:t,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(t?.length)for(let s=0;s<t.length;s++){let c=document.getElementsByClassName(t[s]);for(let p=0;p<c.length;p++){let u=c[p];u&&u instanceof HTMLElement&&a.push(u)}}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 u=c[p];u&&u instanceof HTMLElement&&a.push(u)}}return a}catch(a){return this.loggingService.catch("Error in DomService getListedElements: ",a),[]}}isElementInsideListedElementIds(e,t){try{if(t?.length){for(let r=0;r<t.length;r++){let a=document.getElementById(t[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,t){try{if(t?.length){for(let r=0;r<t.length;r++){let a=document.getElementsByClassName(t[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,t){try{if(t?.length){for(let r=0;r<t.length;r++){let a=document.querySelectorAll(t[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,t){try{this.loggingService.log("%c[WB] Calling FUNCTION: addClassToElement","color: green;"),e&&(e.classList?.contains(t)||e.classList?.add(t))}catch(r){this.loggingService.catch("Error in DomService addClassToElement: ",r)}}removeClassFromElement(e,t){try{this.loggingService.log("%c[WB] Calling FUNCTION: removeClassFromElement","color: green;"),e&&e.classList?.contains(t)&&e.classList?.remove(t)}catch(r){this.loggingService.catch("Error in DomService removeClassFromElement: ",r)}}isElementInsideParentWithAttribute(e,t,r){try{let a=e;for(;a&&a!==document.body;){if(a?.getAttribute&&a?.getAttribute(t)===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(t){this.loggingService.catch("Error in DomService setVideoEditorHandlingDelete: ",t)}}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(t){this.loggingService.catch("Error in DomService setCustomCss: ",t)}}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),se(null)}}injectCustomCss(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: injectCustomCss","color: green;");let t=this.customCss$.value;if(t){let r=e?.shadowRoot?.querySelector(`[${j.VELT_CUSTOM_CSS}]`);if(r&&r.remove(),t?.type==="link"){let a=document.createElement("link");a.href=t?.value,a.rel="stylesheet",a.setAttribute(j.VELT_CUSTOM_CSS,"true"),e?.shadowRoot?.appendChild(a)}else{let a=document.createElement("style");a.innerHTML=this.sanitizeHtml(t?.value),a.setAttribute(j.VELT_CUSTOM_CSS,"true"),e?.shadowRoot?.appendChild(a)}}}catch(t){this.loggingService.catch("Error in DomService injectCustomCss: ",t)}}trimCommentHtml(e){try{let t=document.createElement("div");t.innerHTML=e,this.removeEmptyElements(t);let r=t.innerHTML;return r=r.replace(o.MULTIPLE_NBSP_REGEX," ").replace(o.TRIM_NBSP_REGEX,"").trim(),r}catch(t){return this.loggingService.catch("Error in DomService trimCommentHtml: ",t),e}}removeEmptyElements(e){try{let a=function(s){return r.test(s.innerHTML)};var t=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(t=>{t.nodeType===Node.TEXT_NODE?t.nodeValue=t.nodeValue?.replace(/\s+/g," ").trim()??"":t.nodeType===Node.ELEMENT_NODE&&this.normalizeWhitespace(t)})}catch(t){this.loggingService.catch("Error in DomService normalizeWhitespace: ",t)}}sanitizeHtml(e){try{return this.loggingService.log("%c[WB] Calling FUNCTION: sanitizeHtml","color: green;"),Iz.sanitize(e,kce)}catch(t){return this.loggingService.catch("Error in DomService sanitizeHtml: ",t),""}}sanitizeSvg(e){try{return Iz.sanitize(e,kce)}catch(t){return this.loggingService.catch("Error in DomService sanitizeSvg: ",t),e}}setDeviceInfo(){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDeviceInfo","color: green;");let e=new zn;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),se(new zn)}}getTabId(){try{let e=sessionStorage.getItem(j.SESSION_STORAGE.VELT_TAB_ID),t=this.getTabIdFromWindowName();return(!e||e!==t)&&(e=xn(),sessionStorage.setItem(j.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(t){this.loggingService.catch("Error in DomService setTabIdToWindowName: ",t)}}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 zn}}isMobileDevice(){try{return new zn().getDeviceType()===ir.MOBILE}catch(e){return this.loggingService.catch("Error in DomService isMobileDevice: ",e),!1}}isTabletDevice(){try{return new zn().getDeviceType()===ir.TABLET}catch(e){return this.loggingService.catch("Error in DomService isTabletDevice: ",e),!1}}isDesktopDevice(){try{return new zn().getDeviceType()===ir.DESKTOP}catch(e){return this.loggingService.catch("Error in DomService isDesktopDevice: ",e),!1}}deepCloneElement(e){try{var t=document.createElement(e?.tagName);return Array.from(e.attributes).forEach(r=>{t.setAttribute(r.nodeName,r.nodeValue)}),e.childNodes.forEach(r=>{r.nodeType===Node.ELEMENT_NODE?t.appendChild(this.deepCloneElement(r)):r.nodeType===Node.TEXT_NODE&&t.appendChild(document.createTextNode(r.nodeValue))}),t}catch(r){return this.loggingService.catch("Error in DomService deepCloneElement: ",r),e}}setRandomNumberToElementRecursive(e){try{if(!e)return;let t=Math.random().toString(36).substring(7);e&&e.setAttribute&&typeof e.setAttribute=="function"&&(e.getAttribute("velt-wireframe-id")||e.setAttribute("velt-wireframe-id",t)),Array.from(e.children).forEach(a=>{this.setRandomNumberToElementRecursive(a)})}catch(t){this.loggingService.catch("Error in DomService setRandomNumberToElementRecursive: ",t)}}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 zn().getDeviceType()===ir.MONITOR}catch(e){return this.loggingService.catch("Error in DomService isMonitorDevice: ",e),!1}}};o.MULTIPLE_NBSP_REGEX=/(?:&nbsp;\s*){2,}/g,o.TRIM_NBSP_REGEX=/^(?:&nbsp;\s*)+|(?:&nbsp;\s*)+$/g,o.\u0275fac=function(t){return new(t||o)(ee(et),ee(er),ee(y),ee(Ys))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var Ve=(()=>{let o=class o{constructor(e,t,r,a,s,c,p,u){this.afAuth=e,this.configService=t,this.avatarService=r,this.coreActionsService=a,this.domService=s,this.functions=c,this.analyticsService=p,this.loggingService=u,this.user$=new ve(null),this.userOptions$=new ve(null),this.userContacts$=new ve(null),this.userOrganization$=new ve(null),this.providedUser=new Po,this.firebaseConfig$=new ve(null),this.advancedQueries$=new ve(null),this.planDetails$=new ve(null),this.signOutPreviousUser$=new ve(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.onRetrySubscription=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(C=>{this.config=C}),this.forceReLoggedIn=localStorage.getItem(j.LOCAL_STORAGE.VELT_USER_FORCE_RE_LOGGED_IN)==="true",this.sessionReLoginSubscription=ei(this.afAuth).pipe(bo(this.afAuth.currentUser),Bi(),he(([C,E])=>this.domService.onNetworkStatusChange$().pipe(Le(D=>D),st(1),ce(()=>({previousUser:C,currentUser:E}))))).subscribe(D=>Q(this,[D],function*({previousUser:C,currentUser:E}){if(!E&&C){let L=C?.stsTokenManager?.expirationTime,z=new Date().getTime(),W=L-z;z>L&&(this.analyticsService.trackEvent(Z.Events.Core.SDK_SESSION_TOKEN_EXPIRED,{apiKey:this.apiKey,user:this.user$.value,lastLoggedInUserData:this.lastLoggedInUserData,timeLeft:W,forceReset:this.userOptions$.value?.forceReset,sessionReLoginCount:this.sessionReLoginCount},!0,this.user$.value?.userSnippylyId),this.user$.value&&C?.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:W,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:W,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"))))}}),C=>{this.loggingService.catch("Error in AuthService sessionReLoginSubscription: ",C)}),this.getUser$().pipe(Et(mn)).subscribe(C=>{let E=_a(C);this.coreActionsService.triggerAction($i.USER_UPDATE,E),this.coreActionsService.triggerAction($i.INIT_UPDATE,{event:$i.USER_UPDATE,payload:{user:E}})})}catch(C){this.loggingService.catch("Error in AuthService constructor: ",C)}}setApiKey(e,t){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),t||(t=new dk),this.configService.initConfig(t),t.debugMode?sessionStorage.setItem("debugMode","true"):sessionStorage.removeItem("debugMode"),this.autoLoginCalled||ei(this.afAuth).pipe(st(1)).subscribe(r=>Q(this,null,function*(){if(this.autoLoginCalled=!0,r){let a=yield Mm(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(t){this.loggingService.catch("Error in setUsersService: ",t)}}setDocService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocService","color: green;"),this.docService=e}catch(t){this.loggingService.catch("Error in setDocService: ",t)}}setContactService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setContactService","color: green;"),this.contactService=e}catch(t){this.loggingService.catch("Error in setContactService: ",t)}}setIamService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setIamService","color: green;"),this.iamService=e}catch(t){this.loggingService.catch("Error in setIamService: ",t)}}setAreaService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setAreaService","color: green;"),this.areaService=e}catch(t){this.loggingService.catch("Error in setAreaService: ",t)}}setCommentService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setCommentService","color: green;"),this.commentService=e}catch(t){this.loggingService.catch("Error in setCommentService: ",t)}}setReactionService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setReactionService","color: green;"),this.reactionService=e}catch(t){this.loggingService.catch("Error in setReactionService: ",t)}}setRecorderAnnotationService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setRecorderAnnotationService","color: green;"),this.recorderAnnotationService=e}catch(t){this.loggingService.catch("Error in setRecorderAnnotationService: ",t)}}setViewsService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setViewsService","color: green;"),this.viewsService=e}catch(t){this.loggingService.catch("Error in setViewsService: ",t)}}setCommonDbService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setCommonDbService","color: green;"),this.commonDbService=e}catch(t){this.loggingService.catch("Error in setCommonDbService: ",t)}}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")}setVeltAuthProvider(e){return Q(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: setVeltAuthProvider","color: green;");try{this.onRetrySubscription?.unsubscribe();let t=null;e.generateToken&&typeof e.generateToken=="function"&&(t=yield e.generateToken());let r=yield jj(()=>window.Velt.identify(e.user,I(I({},e.options||{}),t&&{authToken:t}),{fromProvider:!0}),e.retryConfig||{retryCount:0,retryDelay:0});return r&&e.generateToken&&typeof e.generateToken=="function"&&(this.onRetrySubscription=this.coreActionsService.onAction($i.ERROR).pipe(Le(a=>a.code==="token_expired"),st(10)).subscribe(a=>Q(this,null,function*(){if(a.code==="token_expired"){let s=this.docService?.getDocumentIds()?.map(D=>({id:D.clientDocumentId}))??[],c=this.docService?.getOptionsFromDocumentPaths()??void 0,p=[],u=this.docService?.getLocation();u&&p.push(u.location);let C=this.docService?.getLocations();C&&Object.values(C).forEach(D=>{p.push(D.location)}),(yield jj(()=>Q(this,null,function*(){try{let D=yield e.generateToken?.();return D?window.Velt.identify(e.user,I(I({},e.options||{}),D&&{authToken:D}),{fromProvider:!0}):!0}catch{return!1}}),e.retryConfig||{retryCount:0,retryDelay:0}))&&(yield this.docService?.setDocuments({documents:s,options:c,source:"internal"}),yield this.docService?.setLocations({locations:p,source:"internal",options:{appendLocation:!u}}))}}))),r}catch(t){return this.loggingService.catch("Error in setVeltAuthProvider: ",t),null}})}initializeClient(e,t,r,a,s){return Q(this,null,function*(){try{if(this.autoLoginRequired=!1,this.userOptions$.next(t),this.initializeClientToken)this.pendingUserLogin=e,this.pendingUserLoginSource=s;else{e.userSnippylyId=Av(this.configService.getApiKey(),e.userId),this.pendingUserLogin=void 0,this.pendingUserLoginSource=void 0,this.initializeClientToken=r;let c=yield ei(this.afAuth).pipe(st(1)).toPromise().catch(u=>null),p=!0;if(this.providedUser=JSON.parse(JSON.stringify(e)),c){let u=yield Mm(c,!0).catch(D=>null);if(!u)return;let{user:C,firebaseConfig:E}=u.claims;if(c?.uid!==e?.userSnippylyId||e?.groupId!==C?.groupId||e?.organizationId!==C?.organizationId||t?.forceReset||!a&&e?.organizationId&&!this.forceReLoggedIn||this.forceReLoginRequiredForAdvancedQueries(e)||this.forceReLoginRequiredForRegion(e,E)||this.forceReLoginRequiredForCommentViews(e))localStorage.setItem(j.LOCAL_STORAGE.VELT_USER_FORCE_RE_LOGGED_IN,"true"),localStorage.setItem(j.LOCAL_STORAGE.VELT_COMMENT_VIEWS_MIGRATED,"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 Mm(c,!0).catch(J=>null);if(!D)return;let{firebaseConfig:L,user:z,advancedQueries:W}=D.claims;this.validateOrganizationId(e),this.setFirebaseConfig(L),this.setAdvancedQueries(W),z&&(this.providedUser.isAdmin=!!z.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,e.userId);let u=br(this.functions,Er({url:oi.cloudFunction.validateClient,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:20*60*1e3}),C=ia(),E=(yield u({apiKey:this.apiKey,user:e,version:C,authToken:t?.authToken}))?.data;if(E.error){if(this.analyticsService.trackEvent(Z.Events.Core.SDK_VALIDATE_CLIENT_FAILED,T(I({apiKey:this.apiKey,clientUserId:e.userId,snippylyUserId:e.userSnippylyId,message:E.error,forceReset:this.userOptions$.value?.forceReset,user:this.getUserWithoutContacts(e)},E),{source:s}),!0,e.userSnippylyId,e.userId),E.error&&typeof E.error=="string")if(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",error:E?.error,source:E?.source};this.coreActionsService.triggerAction($i.ERROR,D)}else{let D={code:"too_many_retries",message:"Token expired. Too many retries.",error:E?.error,source:E?.source};this.coreActionsService.triggerAction($i.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,e.userId)}else{let D=E;this.coreActionsService.triggerAction($i.ERROR,D)}throw E}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,e.userId),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 Mm(this.afAuth.currentUser,!0).catch(W=>null);if(!D)return;let{user:L,advancedQueries:z}=D.claims;this.setAdvancedQueries(z),this.providedUser.isAdmin=!!L?.isAdmin,this.initializeSignedInUser(this.afAuth.currentUser,a)}}this.initializeClientToken=0,this.lastLoggedInUserData={user:e,userOptions:t,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=ia();return(e?parseInt(e.split(".")?.[0]||"0"):0)>=4}catch(e){return this.loggingService.catch("Error in isVersionGreaterThanOrEqualTo4: ",e),!1}}isVersion4Point5(){try{let e=ia();if(e){let t=e.split("."),r=parseInt(t[0]||"0"),a=parseInt(t[1]||"0"),s=parseInt(t[2]||"0");if(r>=4&&a>=5)return r===4&&a===5&&s===0?!e.toLowerCase().includes("beta"):!0}return!1}catch(e){return this.loggingService.catch("Error in isVersion4Point5: ",e),!1}}forceReLoginRequiredForAdvancedQueries(e){try{let t=this.isVersionGreaterThanOrEqualTo4(),r=!1;try{let a=localStorage.getItem(j.LOCAL_STORAGE.VELT_ADVANCED_QUERIES);a&&(r=JSON.parse(a)?.advancedQueriesEnabled)}catch(a){this.loggingService.catch("Error in forceReLoginRequiredForAdvancedQueries: ",a)}return!!(t&&e.organizationId&&!r)}catch(t){return this.loggingService.catch("Error in forceReLoginRequiredForAdvancedQueries: ",t),!1}}forceReLoginRequiredForCommentViews(e){try{let t=this.isVersion4Point5(),r=!1;try{let a=localStorage.getItem(j.LOCAL_STORAGE.VELT_COMMENT_VIEWS_MIGRATED);a&&(r=JSON.parse(a))}catch(a){this.loggingService.catch("Error in forceReLoginRequiredForCommentViews: ",a)}return!!(t&&e.organizationId&&!r)}catch(t){return this.loggingService.catch("Error in forceReLoginRequiredForCommentViews: ",t),!1}}forceReLoginRequiredForRegion(e,t){try{return!!(this.isVersionGreaterThanOrEqualTo4()&&e.organizationId&&!t?.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({},oi.firebaseConfig),e)})}catch(t){this.loggingService.catch("Error in setFirebaseConfig: ",t)}}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(j.LOCAL_STORAGE.VELT_ADVANCED_QUERIES,JSON.stringify(e)),this.advancedQueries$.next(e)}catch(t){this.loggingService.catch("Error in setAdvancedQueries: ",t)}}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 Sn([this.configService.getConfig$(),this.getAdvancedQueries$()]).pipe(ce(()=>this.getAdvancedQueriesEnabled()),kn(()=>se(!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;"),ei(this.afAuth).pipe(he(e=>e?this.user$.asObservable():se(null)),Et(mn))}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 t=this.user$.value;if(e.userId&&e.userId!==t?.userId||e?.groupId&&e?.groupId!==t?.groupId||e?.organizationId&&e?.organizationId!==t?.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),t){let r=I(I({},t),e);this.updateUserInternally(r)}}catch(t){this.loggingService.catch("Error in updateUser: ",t)}}signInWithCustomToken(e,t,r="manual"){this.loggingService.log("%c[WB] Calling FUNCTION: signInWithCustomToken","color: green;");try{return Oee(this.afAuth,t).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?.clearCacheOnUserCascade(),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,t){this.loggingService.log("%c[WB] Calling FUNCTION: initializeSignedInUser","color: green;");try{let r=new Po;r.userSnippylyId=e.uid,r.type="signedIn",this.mergeUserWithProvidedUserData(r,t)}catch(r){this.loggingService.catch("Error in initializeSignedInUser: ",r)}}mergeUserWithProvidedUserData(e,t){return Q(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({userIds:[e.userId],organizationId:this.providedUser?.organizationId||e.organizationId,skipUserCheck:!0});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?.color||this.providedUser?.color||this.getUserAvatarColor(e.userId),e.textColor=r?.textColor||this.providedUser?.textColor||this.getUserTextColor(e.userId),e.initial=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 Q(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: updateUserInternally","color: green;");try{let t=Object.assign({},e);delete t.contacts,this.analyticsService.identifyUser(e.userSnippylyId,t,{forceReset:this.userOptions$.value?.forceReset}),this.getPlanDetailsCalled||(yield this.getPlanDetailsFromDb()),this.afAuth.currentUser&&(this.user$.next(e),this.updateUserToFirebase(e))}catch(t){this.loggingService.catch("Error in updateUserInternally: ",t)}})}updateUserToFirebase(e){this.loggingService.log("%c[WB] Calling FUNCTION: updateUserToFirebase","color: green;");try{let t=JSON.parse(JSON.stringify(e)),r=T(I({},t),{lastUpdated:new Date})}catch(t){this.loggingService.catch("Error in updateUserToFirebase: ",t)}}getPlanDetailsFromDb(){return Q(this,null,function*(){try{this.getPlanDetailsCalled=!0;let t=yield br(this.functions,Er({url:oi.cloudFunction.getPlanDetails,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:20*60*1e3})({apiKey:this.configService.getApiKey(),sdkVersion:ia(),sdkType:this.configService.getSdkType()});return t?.data?.isPlanExpired&&(this.analyticsService.trackEvent(Z.Events.Core.SDK_PLAN_EXPIRED),this.configService.getSF()||console.warn("Velt SDK plan has expired.")),this.planDetails$.next(t?.data||{planInfo:null,isPlanExpired:!1}),t}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(Le(e=>!!e),ce(e=>!!e?.isPlanExpired))}isPlanExpired(){return this.planDetails$.getValue()?.isPlanExpired}addPreSignOutFuction(e,t){try{this.preSignOutFunctions.set(e,t)}catch(r){this.loggingService.catch("Error in addPreSignOutFuction: ",r)}}setUserOrganization(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setUserOrganization","color: green;");let t=JSON.parse(JSON.stringify(this.userOrganization$.value||{}));this.getUser()?.organizationId===e?.organizationId?(t.metadata=e,this.userOrganization$.next(t)):this.userOrganization$.next(null)}catch(t){this.loggingService.catch("Error in setUserOrganization: ",t)}}setOrganizationUserGroups(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setUserOrganizationGroups","color: green;");let t=JSON.parse(JSON.stringify(this.userOrganization$.value||{}));this.getUser()?.organizationId===t?.metadata?.organizationId&&(t.groups=e,this.userOrganization$.next(t))}catch(t){this.loggingService.catch("Error in setUserOrganizationGroups: ",t)}}getUserOrganization$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getUserOrganization$","color: green;"),this.getUser$().pipe(he(e=>e?this.userOrganization$.asObservable().pipe(ce(t=>t?.metadata?.organizationId===e.organizationId?t:null)):se(null)))}signOutUser(e="internal"){return Q(this,null,function*(){try{e==="external"&&this.onRetrySubscription?.unsubscribe(),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 t=yield ei(this.afAuth).pipe(st(1)).toPromise().catch(r=>null);if(t){this.resetServicesCache(),this.user$.next(null);for(let[r,a]of this.preSignOutFunctions)try{yield a(t)}catch(s){this.loggingService.catch(`Error in signOutUser ${r} function: `,s)}return this.user$.next(null),yield Pd(1e3),Aee(this.afAuth).catch(r=>{this.loggingService.catch("Error in signOutUser:",r)})}else return Promise.resolve()}catch(t){this.loggingService.catch("Error in signOutUser: ",t)}})}isFeatureAllowed(e){return ro(this.config,this.user$.value,e)}getUserWithoutContacts(e){try{if(e){let t=JSON.parse(JSON.stringify(e));return delete t.contacts,t}else return null}catch(t){return this.loggingService.catch("Error in getUserWithoutContacts: ",t),null}}getUserForClient(e){try{return _a(e)}catch(t){return this.loggingService.catch("Error in getUserForClient: ",t),null}}getUserAvatarColor(e){try{return e?this.avatarService.generateUserColor(En(e)):"#625DF5"}catch{return"#625DF5"}}getUserTextColor(e){try{return"#FFFFFF"}catch{return"#FFFFFF"}}setOptionalPropertiesToUsers(e){try{e.forEach(t=>{try{t?.color||(t.color=this.getUserAvatarColor(t?.userId)),t?.textColor||(t.textColor=this.getUserTextColor(t?.userId)),!t?.initial&&(t?.name||t?.email)&&(t.initial=t.name?.charAt(0).toUpperCase()||t.email?.charAt(0).toUpperCase())}catch{}})}catch{}}};o.\u0275fac=function(t){return new(t||o)(ee(Di),ee(Ft),ee(Bd),ee(Vd),ee(Be),ee(Wo),ee(et),ee(y))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var Ud=class{constructor({apiKey:o,documentId:n,organizationId:e,folderId:t,veltFolderId:r,clientDocumentId:a,clientOrganizationId:s}){this.paths={},this.apiKey=o,this.documentId=n,this.organizationId=e,this.folderId=t,this.veltFolderId=r,this.clientDocumentId=a,this.clientOrganizationId=s,a&&(this.documentId=na(a)),s&&(this.organizationId=La(s)),t&&(this.folderId=t,this.veltFolderId=Fi(t)),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=`${this.apiKey}`;this.organizationId&&(o=`${o}/${j.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${this.paths.organizationId}`),this.documentId&&(this.paths.docs=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/`,this.paths.folder=`${o}/${j.FIREBASE_PARTIAL_PATH_FOLDERS}/`,this.paths.presence=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_PRESENCE}/`,this.paths.cursor=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_CURSOR}/`,this.paths.comment=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_COMMENT}/`,this.paths.multiThread=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_MULTI_THREAD}/`,this.paths.tag=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_TAG}/`,this.paths.area=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_AREA}/`,this.paths.arrow=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_ARROW}/`,this.paths.selection=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_SELECTION}/`,this.paths.audioHuddle=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_AUDIO_HUDDLE}/`,this.paths.huddle=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_HUDDLE}/`,this.paths.recorder=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_RECORDER}/`,this.paths.flock=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_FOLLOW_ALONG}/`,this.paths.syncVideoPlayer=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_SYNC_VIDEO_PLAYER}/`,this.paths.liveState=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_LIVE_STATE}/`,this.paths.liveStateSingleEditorMode=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_LIVE_STATE}/default/singleEditorMode`,this.paths.reaction=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_REACTION}/`,this.paths.crdt=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_CRDT}/`,this.paths.views=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_VIEWS}/`,this.paths.notifications=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_NOTIFICATIONS}/`,this.paths.metadata=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_METADATA}/`,this.paths.users=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_USERS}/`,this.paths.documentIam=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_IAM}/`,this.paths.userConfig=`${o}/${j.FIREBASE_PARTIAL_PATH_USERS}`),this.paths.customerMetadata=`${o}/${j.FIREBASE_PARTIAL_PATH_CUSTOMER_METADATA}/`,this.paths.groupContacts=`${o}/${j.FIREBASE_PARTIAL_PATH_CONTACTS}/${j.FIREBASE_PARTIAL_PATH_GROUPS}/`,this.paths.globalContacts=`${o}/${j.FIREBASE_PARTIAL_PATH_CONTACTS}/${j.FIREBASE_PARTIAL_PATH_GLOBAL}/`,this.paths.logins=`${o}/${j.FIREBASE_PARTIAL_PATH_CONTACTS}/${j.FIREBASE_PARTIAL_PATH_LOGINS}/`,this.paths.userFeedback=`${o}/${j.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${j.FIREBASE_PARTIAL_PATH_FEEDBACK}/`,this.paths.userReportBugs=`${o}/${j.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${j.FIREBASE_PARTIAL_PATH_BUGS}/`,this.paths.userContactUs=`${o}/${j.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${j.FIREBASE_PARTIAL_PATH_CONTACT_US}/`,this.organizationId&&(this.paths.organizationMetadata=`${o}/${j.FIREBASE_PARTIAL_PATH_ORGANIZATION_METADATA}/`,this.paths.organizationIam=`${o}/${j.FIREBASE_PARTIAL_PATH_IAM}/`,this.paths.organizationGroups=`${o}/${j.FIREBASE_PARTIAL_PATH_ORGANIZATION_GROUPS}/`,this.paths.organizationNotifications=`${o}/${j.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/`,this.documentId&&(this.paths.organizationNotificationsWithDocumentId=`${o}/${j.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/`),this.paths.organizationNotificationsLastNotificationTimestamp=`${o}/${j.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${j.FIREBASE_PARTIAL_PATH_LAST_NOTIFICATION_TIMESTAMP}/${j.FIREBASE_PARTIAL_PATH_DOCS}/`,this.paths.organizationNotificationsUsers=`${o}/${j.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${j.FIREBASE_PARTIAL_PATH_USERS}/`),this.paths.workspaceIam=`${this.apiKey}/${j.FIREBASE_PARTIAL_PATH_IAM}/`}}catch{}}get folder(){return this.paths.folder?this.paths.folder:this.throwError("Folder path is not available.")}get userConfig(){return this.paths.userConfig?this.paths.userConfig:this.throwError("User config path is not available.")}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 crdt(){return this.paths.crdt?this.paths.crdt:this.throwError("CRDT 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 Ok=class{constructor({apiKey:o,documentId:n,organizationId:e,clientDocumentId:t,clientOrganizationId:r,folderId:a,veltFolderId:s}){this.paths={},this.apiKey=o,this.documentId=n,this.organizationId=e,this.veltFolderId=s,t&&(this.documentId=na(t)),r&&(this.organizationId=La(r)),a&&(this.folderId=a,this.veltFolderId=Fi(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}/${j.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${this.paths.organizationId}`,this.paths.organization=o,this.paths.folder=`${o}/${j.FIREBASE_PARTIAL_PATH_FOLDERS}`,this.paths.organizationUsers=`${o}/${j.FIREBASE_PARTIAL_PATH_ORGANIZATION_USERS}`,this.paths.users=`${o}/${j.FIREBASE_PARTIAL_PATH_CENTRAL_USERS}`,this.paths.notificationDocs=`${o}/${j.FIREBASE_PARTIAL_PATH_NOTIFICATION_DOCS}`,this.paths.notificationUsers=`${o}/${j.FIREBASE_PARTIAL_PATH_NOTIFICATION_USERS}`,this.paths.organizationGroups=`${o}/${j.FIREBASE_PARTIAL_PATH_GROUPS}`,this.paths.lastNotificationTimestamp=`${o}/${j.FIREBASE_PARTIAL_PATH_LAST_NOTIFICATION_TIMESTAMP}`,this.paths.userConfig=`${o}/${j.FIREBASE_PARTIAL_PATH_USERS}`,this.paths.permissionsUsers=`${o}/${j.FIREBASE_PARTIAL_PATH_PERMISSIONS_USERS}`),this.veltFolderId&&(this.paths.folderUsers=`${o}/${j.FIREBASE_PARTIAL_PATH_FOLDERS}/${this.veltFolderId}/${j.FIREBASE_PARTIAL_PATH_FOLDER_USERS}`),this.documentId&&(this.paths.document=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}`,this.paths.comment=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_COMMENT}`,this.paths.location=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_LOCATION}`,this.paths.multiThread=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_MULTI_THREAD}`,this.paths.area=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_AREA}`,this.paths.recorder=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_RECORDER}`,this.paths.reaction=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_REACTION}`,this.paths.crdt=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_CRDT}`,this.paths.notificationViews=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_NOTIFICATION_VIEWS}`,this.paths.documentViews=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_DOCUMENT_VIEWS}`,this.paths.locationViews=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_LOCATION_VIEWS}`,this.paths.documentUsers=`${o}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_DOCUMENT_USERS}`,this.paths.docNotification=`${this.paths.notificationDocs}/${this.documentId}/${j.FIREBASE_PARTIAL_PATH_DOC_NOTIFICATION}`)}}catch{}}get permissionsUsers(){return this.paths.permissionsUsers?this.paths.permissionsUsers:this.throwError("PermissionsUsers path is not available.")}get users(){return this.paths.users?this.paths.users:this.throwError("Users path is not available.")}get userConfig(){return this.paths.userConfig?this.paths.userConfig:this.throwError("UserConfig path is not available.")}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 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.")}get crdt(){return this.paths.crdt?this.paths.crdt:this.throwError("CRDT path is not available.")}throwError(o){throw{type:"DocumentPaths",message:o,metadata:{apiKey:this.apiKey,documentId:this.documentId,organizationId:this.organizationId}}}};var Ak=class{};var Dn=(()=>{let o=class o{constructor(e,t){this.authService=e,this.loggingService=t,this.db$=new ve(null);try{this.authService.getFirebaseConfig$().subscribe(r=>{r&&this.db$.next(L6(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()}getDbValue(){return this.db$.getValue()}};o.\u0275fac=function(t){return new(t||o)(ee(Ve),ee(y))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var Rs=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.analyticsService=t,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 ve(null),this.commentAnnotationById$=new ve({}),this.fieldsToRemove=[],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),r.config?.fieldsToRemove&&(this.fieldsToRemove=r.config.fieldsToRemove))})}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 Q(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling CommentAnnotationsResolverService FUNCTION: resolveCommentAnnotations","color: green;"),!this.commentAnnotationDataProviderAvailable())return{};let t,r=!1,a=!1,s=()=>{t&&(clearTimeout(t),t=void 0,a=!0)};return new Promise((c,p)=>{t=setTimeout(()=>{a||(r=!0,s(),p(new Error("Comment annotation resolution timeout")))},this.commentAnnotationDataProvider$.value?.config?.resolveTimeout||this.resolveTimeout);let u=this.getProvider();if(!u)return s(),c({});let C={},E=[...new Set(e.commentAnnotationIds||[])],D=T(I({},e),{commentAnnotationIds:E});Q(this,null,function*(){try{if(E.length>0||e.documentIds?.length||e.folderId){let z=Pc(()=>u?.get(D)||Promise.resolve(void 0),"getCommentAnnotations",this.retryGetConfig).then(W=>r?{}:(s(),W&&W.statusCode!==200?(this.loggingService.catch(W?.message??"Error in CommentAnnotationsResolverService resolveCommentAnnotations:"),{}):W?.data)).catch(W=>{throw s(),W});try{C=(yield z)||{},this.analyticsService.trackEvent(Z.Events.Resolver.COMMENT_RESOLVER_GET,{sourceMethod:"resolveCommentAnnotations",source:"sdk",commentAnnotationIds:E});let W={};Object.entries(C).forEach(([J,ue])=>{let ye=this.commentAnnotationById$.value?.[J];ye?ye&&JSON.stringify(ye)!==JSON.stringify(ue)&&(W[J]=ue):W[J]=ue}),Object.keys(W).length>0&&this.commentAnnotationById$.next(I(I({},this.commentAnnotationById$.getValue()),W)),c(W)}catch(W){r||p(W),c(C)}}else s(),c({})}catch(z){s(),p(z)}})})}catch(t){return this.loggingService.catch("Error in CommentAnnotationsResolverService resolveCommentAnnotations:",t),{}}})}saveCommentAnnotation(e){return Q(this,null,function*(){try{this.loggingService.log("%c[WB] Calling CommentAnnotationsResolverService FUNCTION: saveCommentAnnotation","color: green;");let t=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 Pc(()=>t?.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(t){return this.loggingService.warn("Error in CommentAnnotationsResolverService saveCommentAnnotation:",t),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0}}})}deleteCommentAnnotation(e,t){return Q(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 Pc(()=>r?.delete({commentAnnotationId:e.toString(),metadata:t,event:os.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()):se(void 0)}catch(e){return this.loggingService.catch("Error in CommentAnnotationsResolverService getCommentAnnotationsById$:",e),se(void 0)}}getAnnotationById(e){try{return this.commentAnnotationDataProviderAvailable()?this.commentAnnotationById$.getValue()?.[e]:void 0}catch(t){this.loggingService.catch("Error in CommentAnnotationsResolverService getAnnotationById:",t);return}}getFieldsToRemove(){try{return this.fieldsToRemove}catch(e){return this.loggingService.catch("Error in CommentAnnotationsResolverService getFieldsToRemove:",e),this.fieldsToRemove}}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(t){this.loggingService.catch("Error in CommentAnnotationsResolverService setCommentAnnotationDataProvider:",t)}}commentAnnotationDataProviderAvailable(){try{return!!this.commentAnnotationDataProvider$.getValue()}catch(e){return this.loggingService.catch("Error in CommentAnnotationsResolverService commentAnnotationDataProviderAvailable:",e),!1}}};o.\u0275fac=function(t){return new(t||o)(ee(y),ee(et))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var jd=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.analyticsService=t,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 ve(null),this.reactionAnnotationById$=new ve({}),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 Q(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling ReactionAnnotationsResolverService FUNCTION: resolveReactionAnnotations","color: green;"),!this.reactionAnnotationDataProviderAvailable())return{};let t,r=!1,a=!1,s=()=>{t&&(clearTimeout(t),t=void 0,a=!0)};return new Promise((c,p)=>{t=setTimeout(()=>{a||(r=!0,s(),p(new Error("Reaction annotation resolution timeout")))},this.reactionAnnotationDataProvider$.value?.config?.resolveTimeout||this.resolveTimeout);let u=this.getProvider();if(!u)return s(),c({});let C={},E=[...new Set(e.reactionAnnotationIds||[])],D=T(I({},e),{reactionAnnotationIds:E});Q(this,null,function*(){try{if(E.length>0||e.documentIds?.length||e.folderId){let z=Pc(()=>u?.get(D)||Promise.resolve(void 0),"getReactionAnnotations",this.retryGetConfig).then(W=>r?{}:(s(),W&&W.statusCode!==200?(this.loggingService.catch(W?.message??"Error in ReactionAnnotationsResolverService resolveReactionAnnotations:"),{}):W?.data)).catch(W=>{throw s(),W});try{C=(yield z)||{},this.analyticsService.trackEvent(Z.Events.Resolver.REACTION_RESOLVER_GET,{sourceMethod:"resolveReactionAnnotations",source:"sdk",reactionAnnotationIds:E});let W={};Object.entries(C).forEach(([J,ue])=>{let ye=this.reactionAnnotationById$.value?.[J];ye?ye&&JSON.stringify(ye)!==JSON.stringify(ue)&&(W[J]=ue):W[J]=ue}),Object.keys(W).length>0&&this.reactionAnnotationById$.next(I(I({},this.reactionAnnotationById$.getValue()),W)),c(W)}catch(W){r||p(W),c(C)}}else s(),c({})}catch(z){s(),p(z)}})})}catch(t){return this.loggingService.catch("Error in ReactionAnnotationsResolverService resolveReactionAnnotations:",t),{}}})}saveReactionAnnotation(e){return Q(this,null,function*(){try{this.loggingService.log("%c[WB] Calling ReactionAnnotationsResolverService FUNCTION: saveReactionAnnotation","color: green;");let t=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:os.REACTION_ADD,metadata:Object.values(e??{})?.[0]?.metadata},s=yield Pc(()=>t?.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(t){return this.loggingService.warn("Error in ReactionAnnotationsResolverService saveReactionAnnotation:",t),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0}}})}deleteReactionAnnotation(e,t){return Q(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 Pc(()=>r?.delete({reactionAnnotationId:e.toString(),metadata:t,event:os.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()):se(void 0)}catch(e){return this.loggingService.catch("Error in ReactionAnnotationsResolverService getReactionAnnotationsById$:",e),se(void 0)}}getAnnotationById(e){try{return this.reactionAnnotationDataProviderAvailable()?this.reactionAnnotationById$.getValue()?.[e]:void 0}catch(t){this.loggingService.catch("Error in ReactionAnnotationsResolverService getAnnotationById:",t);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(t){this.loggingService.catch("Error in ReactionAnnotationsResolverService setReactionAnnotationDataProvider:",t)}}reactionAnnotationDataProviderAvailable(){try{return!!this.reactionAnnotationDataProvider$.getValue()}catch(e){return this.loggingService.catch("Error in ReactionAnnotationsResolverService reactionAnnotationDataProviderAvailable:",e),!1}}};o.\u0275fac=function(t){return new(t||o)(ee(y),ee(et))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var at=(()=>{let o=class o{constructor(e,t,r,a,s,c,p,u,C){this.analyticsService=e,this.authService=t,this.databaseService=r,this.domService=a,this.configService=s,this.loggingService=c,this.commentResolverService=p,this.reactionResolverService=u,this.coreActionsService=C,this.documentPaths$=new ve(null),this.documentIds$=new ve([]),this.organizationConfig$=new ve(null),this.firestorePaths$=new ve(null),this.location$=new ve(null),this.excludedLocationIds$=new ve([]),this.organizationMetadata$=new ve(null),this.documentMetadata$=new ve(null),this.locationMetadata$=new ve(null),this.customerMetadata$=new ve(null),this.currentDocumentId=null,this.isCustomDocId=!1,this.locations$=new ve({}),this.preDocumentIdChangeFunctions=new Map,this.draftDocuments=[],this.clientDocumentMetadataMap={},this.uiState=new ve({}),this.lastSetDocumentIdExecutionTime=0,this.lastSetDocumentIdCallTime=0,this.setDocumentIdSubject=new tt,this.DEBOUNCE_TIME=5e3,this.MAX_QUEUE_SIZE=100,this.queueSize=0,this.isDocumentIdInDebounceQueue=!1,this.draftLocationMap={locations:[],options:void 0};try{this.loggingService.log("%c[WB] Creating CLASS: DocService","color: blue;"),this.domService.setDocService(this),this.authService.setDocService(this),this.setDocumentIdSubject.pipe(lr(this.DEBOUNCE_TIME)).subscribe({next:E=>Q(this,null,function*(){try{yield this.setDocumentIdImpl(E.documentId,E.clientOrganizationId,E.options),this.lastSetDocumentIdExecutionTime=Date.now(),this.isDocumentIdInDebounceQueue=!1,this.draftLocationMap.locations.length&&(yield this.setLocations({locations:this.draftLocationMap.locations,options:this.draftLocationMap.options,source:"internal"})),this.draftLocationMap={locations:[],options:void 0}}finally{this.queueSize--}}),error:E=>{this.loggingService.catch("Error in setDocumentId subscription:",E),this.queueSize--}}),this.databaseService.getDb().pipe(Le(E=>!!E),st(1)).subscribe(E=>{E&&(this.db=E)}),this.configService.getApiKey$().subscribe(E=>{if(this.apiKey=E,this.apiKey){if(!this.isCustomDocId){let D=XP(window.location.href);this.currentUrl=D}this.analyticsService.updateDefaultProperties({apiKey:E})}}),this.authService.getUser$().subscribe(E=>Q(this,null,function*(){E&&(this.analyticsService.updateDefaultProperties({organizationId:E?.organizationId,clientOrganizationId:E?.clientOrganizationId}),this.draftDocuments?.length?(yield this.setDocuments({documents:this.draftDocuments,options:this.draftOptions??void 0,source:"internal"}),this.draftDocuments=[],this.draftOptions=void 0,this.draftLocationMap.locations.length&&(yield this.setLocations({locations:this.draftLocationMap.locations,options:this.draftLocationMap.options,source:"internal"}).then(()=>this.draftLocationMap={locations:[],options:void 0}))):this.documentPaths$?.value&&E?.organizationId&&this.documentPaths$.value?.organizationId!==E?.organizationId&&(yield this.setDocuments({documents:this.documentIds$.value.length?this.documentIds$.value.map(D=>({id:D.clientDocumentId})):[{id:this.documentPaths$.value?.clientDocumentId}],options:void 0,source:"internal"})),setTimeout(()=>{this.documentPaths$.value||this.loggingService.catch("Error in DocService constructor:","Please set document id to continue.")},1e4),E?.organizationId&&E?.clientOrganizationId&&(this.organizationConfig$.next({organizationId:E?.organizationId,clientOrganizationId:E?.clientOrganizationId}),yield this.updateOrganizationMetadata()))})),this.documentPaths$.subscribe(E=>{let D={documentId:E?.documentId,clientDocumentId:E?.clientDocumentId,folderId:E?.folderId,allDocuments:E?.allDocuments,veltFolderId:E?.veltFolderId};E?.organizationId&&(D.organizationId=E.organizationId,D.clientOrganizationId=E.clientOrganizationId),this.analyticsService.updateDefaultProperties(D),this.domService.resetSelectedAnnotationsMap()}),this.location$.subscribe(E=>{this.analyticsService.updateDefaultProperties({clientLocation:E?.location,locationId:E?.locationId})}),this.organizationMetadata$.subscribe(E=>{this.authService.setUserOrganization(E?.[this.documentPaths$.value?.organizationId])}),this.documentPaths$.pipe(Le(E=>!!E),st(1)).subscribe(()=>{try{this.subscribeToCustomerMetadata()}catch(E){this.loggingService.catch("Error in DocService subscribeToCustomerMetadata:",E)}},E=>{this.loggingService.catch("Error in DocService subscribeToCustomerMetadata:",E)}),this.loggingService.log("%c[WB] Creating CLASS: DocService 2","color: blue;"),this.onWindowPopstate(),this.onWindowClick()}catch(E){this.loggingService.catch("Error in DocService constructor:",E)}}getOptionsFromDocumentPaths(){try{return this.documentPaths$.value?{folderId:this.documentPaths$.value?.folderId,allDocuments:this.documentPaths$.value?.allDocuments,locationId:this.documentPaths$.value?.locationId,organizationId:this.documentPaths$.value?.clientOrganizationId}:null}catch(e){return this.loggingService.catch("Error in getOptionsFromDocumentPaths:",e),null}}clearCacheOnUserCascade(){this.loggingService.log("%c[WB] Calling FUNCTION: clearCacheOnUserCascade in DocService","color: green;");try{this.organizationConfig$.next(null),this.organizationMetadata$.next(null),this.customerMetadata$.next(null),this.customerMetadataSubscription?.unsubscribe(),this.documentPaths$.value&&(this.draftOptions=this.getOptionsFromDocumentPaths(),this.draftLocationMap={locations:[this.location$.value?.location??null,...Object.values(this.locations$.value||{}).map(e=>e.location)].filter(e=>e!==null),options:{rootLocationId:this.location$.value?.location?.id}},this.currentDocumentId=null,this.documentPaths$.next(null),this.firestorePaths$.next(null)),this.unsetDocuments({source:"internal"})}catch(e){this.loggingService.catch("Error in DocService clearCacheOnUserCascade: ",e)}}setCommonDbService(e){try{this.commonDbService=e}catch(t){this.loggingService.catch("Error in setCommonDbService:",t)}}setUserPermissionService(e){try{this.userPermissionService=e}catch(t){this.loggingService.catch("Error in setUserPermissionService:",t)}}setCommentService(e){try{this.commentService=e}catch(t){this.loggingService.catch("Error in setCommentService:",t)}}onWindowPopstate(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowPopstate","color: green;");try{this.domService.onWindowPopState$().subscribe(()=>{this.loggingService.log("location",location.href);let e=XP(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=XP(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(s){return Q(this,arguments,function*({documentId:e,documentMetadata:t,options:r,source:a="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocument","color: green;"),a==="internal"&&this.analyticsService.trackEvent(Z.Events.Core.SET_DOCUMENTS_TRIGGERED,{payload:{id:e,documentMetadata:t,methodName:"setDocument",source:a}}),this.coreActionsService.triggerAction($i.INIT_UPDATE,{event:Z.Events.Core.SET_DOCUMENTS_TRIGGERED,methodName:"setDocument",source:a,payload:{documentId:e,documentMetadata:t,options:r}}),yield this.setDocumentsImpl({documents:[{id:e,metadata:t}],options:I({organizationId:t?.organizationId},r??{}),source:a})}catch(c){this.loggingService.catch("Error in DocService setDocument:",c)}})}shouldSetDocumentsAgain(e,t={}){try{this.loggingService.log("%c[WB] Calling FUNCTION: shouldSetDocumentsAgain","color: green;");let r=this.documentPaths$.value?.clientDocumentId,a=t?.rootDocumentId??e[0]?.id,s=this.documentIds$.value.map(u=>u.clientDocumentId),c=Mj(this.getOptionsFromDocumentPaths()??{})??{};return!e.every(u=>s.includes(u.id))||!wi(c,t)||r!==a}catch(r){return this.loggingService.catch("Error in DocService shouldSetDocumentsAgain:",r),!0}}getDocumentIdsFromDocuments({documents:e,setClientDocumentMetadataMap:t=!1}){try{let r=[];return e.forEach(a=>{let s=a.id,c=`${En(s)}`;t&&a?.metadata&&typeof a.metadata=="object"&&(this.clientDocumentMetadataMap[s]=a.metadata),r.push({documentId:c,clientDocumentId:s})}),r}catch(r){return this.loggingService.catch("Error in DocService getDocumentIdsFromDocuments:",r),[]}}setDocuments(a){return Q(this,arguments,function*({documents:e,options:t,source:r="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocuments","color: green;"),r==="internal"&&this.analyticsService.trackEvent(Z.Events.Core.SET_DOCUMENTS_TRIGGERED,{payload:{documents:e,options:t,methodName:"setDocuments",source:r}}),this.coreActionsService.triggerAction($i.INIT_UPDATE,{event:Z.Events.Core.SET_DOCUMENTS_TRIGGERED,methodName:"setDocuments",source:r,payload:{documents:e,options:t}}),yield this.setDocumentsImpl({documents:e,options:t??{},source:r})}catch(s){this.loggingService.catch("Error in DocService setDocuments:",s)}})}setRootDocument(r){return Q(this,arguments,function*({document:e,source:t="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setRootDocument","color: green;"),this.coreActionsService.triggerAction($i.INIT_UPDATE,{event:Z.Events.Core.SET_ROOT_DOCUMENT_TRIGGERED,methodName:"setRootDocument",source:t,payload:{document:e}});let a=this.getOptionsFromDocumentPaths()??{},s=this.documentIds$.value.map(c=>c.clientDocumentId);if(!s.includes(e.id)){let c=[...s.map(u=>({id:u})),{id:e.id}],p=this.getDocumentIdsFromDocuments({documents:c,setClientDocumentMetadataMap:!0});this.documentIds$.next(p)}yield this.setDocumentIdImpl(e.id,this.documentPaths$.value?.clientOrganizationId,a)}catch(a){this.loggingService.catch("Error in DocService setRootDocument:",a)}})}setDocumentsImpl(a){return Q(this,arguments,function*({documents:e,options:t,source:r}){try{let s=t?.organizationId??this.documentPaths$.value?.clientOrganizationId;if(!this.shouldSetDocumentsAgain(e,Mj(T(I({},t),{organizationId:s})))){r==="external"&&this.loggingService.catch("setDocuments called with previous request");return}let c=this.getDocumentIdsFromDocuments({documents:e,setClientDocumentMetadataMap:!0});if(c?.length===0){this.loggingService.warn("Minimum one document must be set in setDocuments");return}if(!this.authService.getUser()){this.draftDocuments=e,this.draftOptions=t;return}if(this.documentPaths$.value?.organizationId&&t?.organizationId&&this.documentPaths$.value?.organizationId!==t?.organizationId?this.authService.resetServicesCache():this.unsetDocuments({source:"internal",unsetDocumentPaths:!1}),this.documentIds$.next(c),e?.length){let u=e[0]?.id;t?.rootDocumentId&&e.find(C=>C.id===t?.rootDocumentId)&&(u=t?.rootDocumentId),yield this.debounceSetDocuments({documentId:u,clientOrganizationId:t?.organizationId,options:t})}return}catch(s){this.loggingService.catch("Error in DocService setDocumentsImpl:",s)}})}setDocumentId(a){return Q(this,arguments,function*({documentId:e,clientOrganizationId:t,source:r="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocumentId","color: green;"),r==="internal"&&this.analyticsService.trackEvent(Z.Events.Core.SET_DOCUMENTS_TRIGGERED,{payload:{id:e,clientOrganizationId:t,methodName:"setDocumentId",source:r}}),this.coreActionsService.triggerAction($i.INIT_UPDATE,{event:Z.Events.Core.SET_DOCUMENTS_TRIGGERED,methodName:"setDocumentId",source:r,payload:{documentId:e,clientOrganizationId:t}}),yield this.setDocumentsImpl({documents:[{id:e}],options:{organizationId:t},source:r})}catch(s){this.loggingService.catch("Error in setDocumentId:",s);return}})}debounceSetDocuments(a){return Q(this,arguments,function*({documentId:e,clientOrganizationId:t,options:r}){try{this.loggingService.log("%c[WB] Calling FUNCTION: debounceSetDocuments","color: green;");let s=Date.now(),c=s-this.lastSetDocumentIdCallTime,p=s-this.lastSetDocumentIdExecutionTime;if(this.lastSetDocumentIdCallTime=s,this.queueSize>=this.MAX_QUEUE_SIZE){this.loggingService.warn("SetDocumentId queue size exceeded limit");return}if(!this.documentPaths$.value&&!this.isDocumentIdInDebounceQueue||c>this.DEBOUNCE_TIME&&p>this.DEBOUNCE_TIME){yield this.setDocumentIdImpl(e,t,r),this.lastSetDocumentIdExecutionTime=s;return}this.documentPaths$.next(null),this.isDocumentIdInDebounceQueue=!0,this.draftLocationMap={locations:[],options:void 0},this.queueSize++,this.setDocumentIdSubject.next({documentId:e,clientOrganizationId:t,options:r??void 0});return}catch(s){this.loggingService.catch("Error in debounceSetDocuments:",s)}})}setDocumentIdImpl(e,t,r){return Q(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: setDocumentIdImpl","color: green;");try{let a=this.authService.getUser();if(!a)return;this.currentDocumentId&&this.documentPaths$.value&&(yield this.callPreDocumentIdChangeFunctions(this.documentPaths$.value));let s=this.currentDocumentId;if(this.apiKey){let c=`${En(e)}`,p=r?.folderId,u=r?.folderId?Fi(r?.folderId):void 0,C=r?.locationId,E=r?.allDocuments,D=a?.organizationId?t?bt(t):a?.organizationId:void 0;if(yield Promise.allSettled([this.commentResolverService.resolveCommentAnnotations({documentIds:this.documentIds$.value.map(L=>L.clientDocumentId),organizationId:t??a?.clientOrganizationId??""}),this.reactionResolverService.resolveReactionAnnotations({documentIds:this.documentIds$.value.map(L=>L.clientDocumentId),organizationId:t??a?.clientOrganizationId??""})]),this.currentDocumentId!==c||this.documentPaths$.value?.organizationId!==D){this.loggingService.log("setting new docid"),this.currentDocumentId=c;let L=new gk,z=new Ak;L.clientDocumentId=e,z.clientDocumentId=e,L.folderId=p,z.folderId=p,L.locationId=C,z.locationId=C,L.allDocuments=E,z.allDocuments=E,L.veltFolderId=u,z.veltFolderId=u,L.documentId=c,z.documentId=c,D&&(L.organizationId=D,L.clientOrganizationId=t??a?.clientOrganizationId,z.organizationId=D,z.clientOrganizationId=t??a?.clientOrganizationId);let W=`${this.apiKey}`,J=`apiKey/${this.apiKey}`;D&&(W=`${W}/${j.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${L.organizationId}`,J=`${J}/${j.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${L.organizationId}`),z.organization=`apiKey/${this.apiKey}/${j.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}`,z.document=`${J}/${j.FIREBASE_PARTIAL_PATH_DOCS}`,L.presence=`${W}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${j.FIREBASE_PARTIAL_PATH_PRESENCE}/`,L.cursor=`${W}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${j.FIREBASE_PARTIAL_PATH_CURSOR}/`,L.comment=`${W}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${j.FIREBASE_PARTIAL_PATH_COMMENT}/`,z.comment=`${J}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${j.FIREBASE_PARTIAL_PATH_COMMENT}`,L.multiThread=`${W}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${j.FIREBASE_PARTIAL_PATH_MULTI_THREAD}/`,z.multiThread=`${J}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${j.FIREBASE_PARTIAL_PATH_MULTI_THREAD}`,L.tag=`${W}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${j.FIREBASE_PARTIAL_PATH_TAG}/`,L.area=`${W}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${j.FIREBASE_PARTIAL_PATH_AREA}/`,z.area=`${J}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${j.FIREBASE_PARTIAL_PATH_AREA}`,L.arrow=`${W}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${j.FIREBASE_PARTIAL_PATH_ARROW}/`,L.selection=`${W}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${j.FIREBASE_PARTIAL_PATH_SELECTION}/`,L.audioHuddle=`${W}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${j.FIREBASE_PARTIAL_PATH_AUDIO_HUDDLE}/`,L.huddle=`${W}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${j.FIREBASE_PARTIAL_PATH_HUDDLE}/`,L.recorder=`${W}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${j.FIREBASE_PARTIAL_PATH_RECORDER}/`,z.recorder=`${J}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${j.FIREBASE_PARTIAL_PATH_RECORDER}`,L.flock=`${W}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${j.FIREBASE_PARTIAL_PATH_FOLLOW_ALONG}/`,L.syncVideoPlayer=`${W}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${j.FIREBASE_PARTIAL_PATH_SYNC_VIDEO_PLAYER}/`,L.liveState=`${W}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${j.FIREBASE_PARTIAL_PATH_LIVE_STATE}/`,L.liveStateSingleEditorMode=`${W}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${j.FIREBASE_PARTIAL_PATH_LIVE_STATE}/default/singleEditorMode`,L.reaction=`${W}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${j.FIREBASE_PARTIAL_PATH_REACTION}/`,z.reaction=`${J}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${j.FIREBASE_PARTIAL_PATH_REACTION}`,L.crdt=`${W}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${j.FIREBASE_PARTIAL_PATH_CRDT}/`,z.crdt=`${J}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${j.FIREBASE_PARTIAL_PATH_CRDT}`,L.customerMetadata=`${this.apiKey}/${j.FIREBASE_PARTIAL_PATH_CUSTOMER_METADATA}/`,L.views=`${W}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${j.FIREBASE_PARTIAL_PATH_VIEWS}/`,z.notificationViews=`${J}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${j.FIREBASE_PARTIAL_PATH_NOTIFICATION_VIEWS}`,z.documentViews=`${J}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${j.FIREBASE_PARTIAL_PATH_DOCUMENT_VIEWS}`,z.locationViews=`${J}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${j.FIREBASE_PARTIAL_PATH_LOCATION_VIEWS}`,L.notifications=`${W}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${j.FIREBASE_PARTIAL_PATH_NOTIFICATIONS}/`,L.metadata=`${W}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${j.FIREBASE_PARTIAL_PATH_METADATA}/`,L.users=`${W}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${j.FIREBASE_PARTIAL_PATH_USERS}/`,L.documentIam=`${W}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${j.FIREBASE_PARTIAL_PATH_IAM}/`,L.workspaceIam=`${this.apiKey}/${j.FIREBASE_PARTIAL_PATH_IAM}/`,L.groupContacts=`${W}/${j.FIREBASE_PARTIAL_PATH_CONTACTS}/${j.FIREBASE_PARTIAL_PATH_GROUPS}/`,L.globalContacts=`${W}/${j.FIREBASE_PARTIAL_PATH_CONTACTS}/${j.FIREBASE_PARTIAL_PATH_GLOBAL}/`,L.logins=`${W}/${j.FIREBASE_PARTIAL_PATH_CONTACTS}/${j.FIREBASE_PARTIAL_PATH_LOGINS}/`,L.userFeedback=`${W}/${j.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${j.FIREBASE_PARTIAL_PATH_FEEDBACK}/`,L.userReportBugs=`${W}/${j.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${j.FIREBASE_PARTIAL_PATH_BUGS}/`,L.userContactUs=`${W}/${j.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${j.FIREBASE_PARTIAL_PATH_CONTACT_US}/`,D&&(L.organizationMetadata=`${W}/${j.FIREBASE_PARTIAL_PATH_ORGANIZATION_METADATA}/`,L.organizationIam=`${W}/${j.FIREBASE_PARTIAL_PATH_IAM}/`,L.organizationGroups=`${W}/${j.FIREBASE_PARTIAL_PATH_ORGANIZATION_GROUPS}/`,L.organizationNotifications=`${W}/${j.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/`,c&&(L.organizationNotificationsWithDocumentId=`${W}/${j.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${c}/`),L.organizationNotificationsLastNotificationTimestamp=`${W}/${j.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${j.FIREBASE_PARTIAL_PATH_LAST_NOTIFICATION_TIMESTAMP}/${j.FIREBASE_PARTIAL_PATH_DOCS}/`,L.organizationNotificationsUsers=`${W}/${j.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${j.FIREBASE_PARTIAL_PATH_USERS}/`),z.organizationUsers=`${J}/${j.FIREBASE_PARTIAL_PATH_ORGANIZATION_USERS}`,z.users=`${J}/${j.FIREBASE_PARTIAL_PATH_CENTRAL_USERS}`,z.documentUsers=`${J}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${j.FIREBASE_PARTIAL_PATH_DOCUMENT_USERS}`,z.notificationDocs=`${J}/${j.FIREBASE_PARTIAL_PATH_NOTIFICATION_DOCS}`,z.notificationUsers=`${J}/${j.FIREBASE_PARTIAL_PATH_NOTIFICATION_USERS}`,this.documentPaths$.next(L),this.firestorePaths$.next(z),L?.clientOrganizationId&&L?.organizationId&&!(L?.clientOrganizationId===this.organizationConfig$?.value?.clientOrganizationId&&L?.organizationId===this.organizationConfig$?.value?.organizationId)&&this.organizationConfig$.next({organizationId:L?.organizationId,clientOrganizationId:L?.clientOrganizationId}),yield this.userPermissionService?.getUserPermissions(),yield Promise.allSettled([this.updateFolderMetadata(),this.updateDocumentMetadata(),this.fetchLocationMetadata(),this.updateOrganizationMetadata()]),s&&this.location$.value&&this.removeLocation({}),this.coreActionsService.triggerAction($i.INIT_UPDATE,{event:Z.Events.Doc.SET_DOCUMENTS_SUCCESS,payload:{documentId:c,clientDocumentId:e}}),this.analyticsService.trackEvent(Z.Events.Doc.SET_DOCUMENTS_SUCCESS,{documentId:c,clientDocumentId:e},!0,this.getUserIdForAnalytics())}}else this.loggingService.catch("Error in setDocumentIdImpl: API key is not provided.")}catch(a){this.loggingService.catch("Error in setDocumentIdImpl: ",a)}})}unsetDocumentId({source:e,unsetDocumentPaths:t}){this.loggingService.log("%c[WB] Calling FUNCTION: unsetDocumentId","color: green;");try{e==="internal"&&this.analyticsService.trackEvent(Z.Events.Core.UNSET_DOCUMENTS_TRIGGERED,{payload:{methodName:"unsetDocumentId",source:e}}),this.coreActionsService.triggerAction($i.INIT_UPDATE,{event:Z.Events.Doc.UNSET_DOCUMENTS_TRIGGERED,methodName:"unsetDocumentId",source:e}),this.unsetDocumentImpl({source:e,unsetDocumentPaths:t})}catch(r){this.loggingService.catch("Error in unsetDocumentId: ",r)}}unsetDocumentImpl({source:e,unsetDocumentPaths:t}){this.loggingService.log("%c[WB] Calling FUNCTION: unsetDocumentImpl","color: green;");try{this.currentDocumentId&&this.documentPaths$.value&&this.callPreDocumentIdChangeFunctions(this.documentPaths$.value),t&&(this.documentPaths$.next(null),this.firestorePaths$.next(null)),this.currentDocumentId=null,this.location$.next(null),this.excludedLocationIds$.next([]),this.documentMetadata$.next(null),this.locationMetadata$.next(null),this.clientDocumentMetadata=void 0,this.clientDocumentMetadataMap={},this.locations$.next({}),this.documentIds$.next([]),this.coreActionsService.triggerAction($i.INIT_UPDATE,{event:Z.Events.Doc.UNSET_DOCUMENTS_SUCCESS,source:e}),this.analyticsService.trackEvent(Z.Events.Doc.UNSET_DOCUMENTS_SUCCESS,{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())}catch(r){this.loggingService.catch("Error in unsetDocumentImpl: ",r)}}unsetDocuments({source:e,unsetDocumentPaths:t=!0}){this.loggingService.log("%c[WB] Calling FUNCTION: unsetDocuments","color: green;");try{e==="internal"&&this.analyticsService.trackEvent(Z.Events.Core.UNSET_DOCUMENTS_TRIGGERED,{payload:{methodName:"unsetDocuments",source:e}}),this.coreActionsService.triggerAction($i.INIT_UPDATE,{event:Z.Events.Doc.UNSET_DOCUMENTS_TRIGGERED,source:e,methodName:"unsetDocuments"}),this.unsetDocumentImpl({source:e,unsetDocumentPaths:t})}catch(r){this.loggingService.catch("Error in unsetDocuments: ",r)}}addPreDocumentIdChangeFunction(e,t){try{this.loggingService.log("%c[WB] Calling FUNCTION: addPreDocumentIdChangeFunction","color: green;"),this.preDocumentIdChangeFunctions.set(e,t)}catch(r){this.loggingService.catch("Error in addPreDocumentIdChangeFunction: ",r)}}callPreDocumentIdChangeFunctions(e){return Q(this,null,function*(){try{this.loggingService.log("%c[WB] Calling FUNCTION: callPreDocumentIdChangeFunctions","color: green;");for(let[t,r]of this.preDocumentIdChangeFunctions)try{yield r(e)}catch(a){this.loggingService.catch("Error in callPreDocumentIdChangeFunctions: ",a)}}catch(t){this.loggingService.catch("Error in callPreDocumentIdChangeFunctions: ",t)}})}fetchOrganizationMetadata(){return Q(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: fetchOrganizationMetadata","color: green;");try{if(this.db&&this.organizationConfig$.value?.organizationId){let e=this.organizationConfig$.value?.organizationId;yield this.commonDbService?.getData({feature:"organizationMetadata",properties:{apiKey:this.apiKey??"",organizationId:e,field:"metadata"}}).then(t=>{t&&!t?.errorCode&&this.organizationMetadata$.next(T(I({},this.organizationMetadata$.value),{[e]:t}))}).catch(t=>{this.loggingService.catch("Error in fetchOrganizationMetadata: ",t)})}}catch(e){this.loggingService.catch("Error in fetchOrganizationMetadata: ",e)}})}fetchDocumentMetadata(e){return Q(this,null,function*(){try{if(this.db&&this.authService.getUser()){let t=this.documentPaths$.value,r=this.documentMetadata$.value;if(e=e.filter(a=>!r?.[a.documentId]),e?.some(a=>!a?.documentId||!a?.clientDocumentId)||!t)return;if(this.commonDbService?.shouldUseFirestore()){let a=t?.folderId,s=t?.allDocuments,c=[],p={organizationId:t?.clientOrganizationId,folderId:a,allDocuments:s};if(a&&s)c.push(this.fetchDocuments(p));else{let C=[];for(let D=0;D<e.length;D+=20)C.push(e.slice(D,D+20));C.forEach(D=>{let L=JSON.parse(JSON.stringify(p));L.documentIds=D.map(z=>z.clientDocumentId),c.push(this.fetchDocuments(L))})}let u={};c.length>0&&(yield Promise.all(c).then(C=>{C?.forEach(E=>{E?.forEach(D=>{D?.metadata?.documentId&&(u[D.metadata.documentId]=D.metadata)})}),this.documentMetadata$.next(I(I({},this.documentMetadata$.value),u))}).catch(C=>{this.loggingService.catch("Error in fetchDocumentMetadata: ",C)}))}else r?.[t?.documentId??e?.[0]?.documentId]||this.commonDbService?.queryData({feature:"allDocuments",properties:{apiKey:this.apiKey??"",organizationId:t?.organizationId,documentId:t?.documentId??e?.[0]?.documentId,skipObjectValues:!0}}).then(a=>{a?.documentId&&this.documentMetadata$.next({[a.documentId]:a})}).catch(a=>{this.loggingService.catch("Error in fetchDocumentMetadata: ",a)})}}catch(t){this.loggingService.catch("Error in fetchDocumentMetadata: ",t)}})}fetchLocationMetadata(){return Q(this,null,function*(){try{if(this.db&&this.authService.getUser()){let e=this.documentPaths$.value,t=this.documentIds$.value,r=e?.folderId,a=e?.allDocuments,s=[],c={organizationId:e?.clientOrganizationId,folderId:r,allDocuments:a};if(r&&a)s.push(this.fetchLocations(c));else{let u=[];for(let E=0;E<t.length;E+=20)u.push(t.slice(E,E+20));u.forEach(E=>{let D=JSON.parse(JSON.stringify(c));D.documentIds=E.map(L=>L.clientDocumentId),s.push(this.fetchLocations(D))})}let p=this.locationMetadata$.value??{};s.length>0&&Promise.all(s).then(u=>{u?.forEach(C=>{C?.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(u=>{this.loggingService.catch("Error in fetchLocationMetadata: ",u)})}}catch(e){this.loggingService.catch("Error in fetchLocationMetadata: ",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(kn(t=>se(null))).subscribe(t=>{this.customerMetadata$.next(t?.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()))}getDocumentIds(){return this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentIds","color: green;"),this.documentIds$.value?.slice()}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`${En(e)}`}catch(t){return this.loggingService.catch("Error in generateDocumentId: ",t),""}}generateOrganizationId(e){try{return`${bt(e)}`}catch(t){return this.loggingService.catch("Error in generateOrganizationId: ",t),""}}getFirestorePaths(){return this.loggingService.log("%c[WB] Calling FUNCTION: getFirestorePaths","color: green;"),this.firestorePaths$.value}setLocation(r){return Q(this,arguments,function*({location:e,source:t="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setLocation","color: green;"),t==="internal"&&this.analyticsService.trackEvent(Z.Events.Core.SET_LOCATIONS_TRIGGERED,{payload:{locations:[e],options:void 0,methodName:"setLocation",source:t}}),this.coreActionsService.triggerAction($i.INIT_UPDATE,{event:Z.Events.Core.SET_LOCATIONS_TRIGGERED,source:t,methodName:"setLocation",payload:{locations:[e],options:void 0}}),this.setLocationsImpl({locations:[e]})}catch(a){this.loggingService.catch("Error in setLocation: ",a)}})}setLocations(a){return Q(this,arguments,function*({locations:e,options:t,source:r="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setLocations","color: green;"),r==="internal"&&this.analyticsService.trackEvent(Z.Events.Core.SET_LOCATIONS_TRIGGERED,{payload:{locations:e,options:t,methodName:"setLocations",source:r}}),this.coreActionsService.triggerAction($i.INIT_UPDATE,{event:Z.Events.Core.SET_LOCATIONS_TRIGGERED,methodName:"setLocations",source:r,payload:{locations:e,options:t}}),this.setLocationsImpl({locations:e,options:t})}catch(s){this.loggingService.catch("Error in setLocations: ",s)}})}getValidLocations(e){try{let t=[];return e&&Array.isArray(e)&&e.forEach(r=>{if(r&&typeof r=="object"){let a=!0;r?.version&&(!r?.version?.id||!r?.version?.name)&&(this.loggingService.catch(`Error in setting location for locationId: ${r?.id}, If you're setting version then add id and name fields to version object.`),a=!1),a&&t.push(r)}}),t}catch(t){this.loggingService.catch("Error in getValidLocations: ",t)}return e}setRootLocation(r){return Q(this,arguments,function*({location:e,source:t="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setRootLocation","color: green;"),t==="internal"&&this.analyticsService.trackEvent(Z.Events.Core.SET_ROOT_LOCATION_TRIGGERED,{payload:{location:e,methodName:"setRootLocation",source:t}}),this.coreActionsService.triggerAction($i.INIT_UPDATE,{event:Z.Events.Core.SET_ROOT_LOCATION_TRIGGERED,methodName:"setRootLocation",source:t,payload:{location:e}});let a=Object.values(this.locations$.value).map(s=>s.location).filter(s=>String(s.id)!==String(e.id));this.setLocationsImpl({locations:[e,...a],options:{rootLocationId:e.id}})}catch(a){this.loggingService.catch("Error in DocService setRootLocation:",a)}})}setLocationsImpl({locations:e,options:t}){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: setLocationsImpl","color: green;"),e.length===0)return;if(!this.authService.getUser()){!t?.appendLocation&&e.length>0&&(this.draftLocationMap.options=T(I(I({},this.draftLocationMap.options??{}),t??{}),{rootLocationId:e[0].id})),this.draftLocationMap.locations=[...this.draftLocationMap.locations,...e],this.draftLocationMap.options=I(I({},this.draftLocationMap.options),t);return}let a=this.getValidLocations(e),s=[],c=[];this.location$.value?.location.id&&c.push(this.location$.value?.location.id),c=[...c,...Object.values(this.locations$.value).map(C=>C.location.id)].filter(C=>C!==void 0);let p;if(t?.rootLocationId&&t?.rootLocationId!==this.location$.value?.location.id&&(p=a.find(C=>C.id===t?.rootLocationId),!p)){this.loggingService.catch(`Error in setting locations, rootLocationId: ${t?.rootLocationId} not found in locations.`);return}if(t?.appendLocation){if(p){let C=Yo(p),E=En(JSON.stringify(C));C.id&&s.push({locationId:E,location:C}),this.location$.next({locationId:E,location:C})}}else{p||(p=a[0]);let C=Yo(p),E=En(JSON.stringify(C));C.id&&s.push({locationId:E,location:C}),this.location$.next({locationId:E,location:C})}let u=[];return a.slice(t?.appendLocation?0:1).forEach(C=>{if(C.id!==this.location$.value?.location.id){let E=I({},C),D=this.locations$.value;C?.id&&Object.keys(D).forEach(J=>{let ue=D[J];ue.location?.id===C.id&&(E=I(I({},ue.location),C),delete D?.[J])});let L=this.genarateLocationId(E),z={locationId:L,location:E};E.id&&s.push({locationId:L,location:E}),u.push(z);let W=T(I({},D),{[L]:z});this.locations$.next(W)}}),this.updateDocumentLocationMetadata(s),this.coreActionsService.triggerAction($i.INIT_UPDATE,{event:Z.Events.Doc.SET_LOCATIONS_SUCCESS,methodName:"setLocations",payload:{locations:a,options:t}}),this.analyticsService.trackEvent(Z.Events.Doc.SET_LOCATIONS_SUCCESS,{locations:a,options:t},!0,this.getUserIdForAnalytics()),u}catch(r){this.loggingService.catch("Error in setLocationImpl: ",r);return}}addLocation({location:e,source:t="internal"}){try{return this.loggingService.log("%c[WB] Calling FUNCTION: addLocation","color: green;"),t==="internal"&&this.analyticsService.trackEvent(Z.Events.Core.SET_LOCATIONS_TRIGGERED,{payload:{locations:[e],options:{appendLocation:!0},methodName:"addLocation",source:t}}),this.coreActionsService.triggerAction($i.INIT_UPDATE,{event:Z.Events.Core.SET_LOCATIONS_TRIGGERED,methodName:"addLocation",source:t,payload:{locations:[e],options:{appendLocation:!0}}}),this.setLocationsImpl({locations:[e],options:{appendLocation:!0}})}catch(r){this.loggingService.catch("Error in DocService addLocation:",r);return}}removeLocation({location:e,source:t="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: removeLocation","color: green;"),t==="internal"&&this.analyticsService.trackEvent(Z.Events.Core.REMOVE_LOCATIONS_TRIGGERED,{payload:{locations:[e],methodName:"removeLocation",source:t}}),this.coreActionsService.triggerAction($i.INIT_UPDATE,{event:Z.Events.Core.REMOVE_LOCATIONS_TRIGGERED,source:t,methodName:"removeLocation",payload:{locations:[e]}}),e&&this.removeLocationsImpl([e],t)}catch(r){this.loggingService.catch("Error in removeLocation: ",r)}}removeLocations({locations:e,source:t="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: removeLocations","color: green;"),t==="internal"&&this.analyticsService.trackEvent(Z.Events.Core.REMOVE_LOCATIONS_TRIGGERED,{payload:{locations:e,methodName:"removeLocations",source:t}}),this.coreActionsService.triggerAction($i.INIT_UPDATE,{event:Z.Events.Core.REMOVE_LOCATIONS_TRIGGERED,methodName:"removeLocations",source:t,payload:{locations:e}}),this.removeLocationsImpl(e,t)}catch(r){this.loggingService.catch("Error in removeLocations: ",r)}}removeLocationsImpl(e,t="internal"){try{this.loggingService.log("%c[WB] Calling FUNCTION: removeLocations","color: green;"),t==="internal"&&this.analyticsService.trackEvent(Z.Events.Core.REMOVE_LOCATIONS_TRIGGERED,{payload:{locations:e},methodName:"removeLocations",message:"System removed locations",source:t},!0,this.getUserIdForAnalytics()),e?e.forEach(r=>{let a=this.genarateLocationId(r);this.getLocation()?.locationId===a&&(this.location$.next(null),t!=="internal"&&(this.draftLocationMap.locations=this.draftLocationMap.locations.filter(s=>s.id!==r.id))),this.removeCustomLocation(r)}):(this.location$.next(null),this.locations$.next({}),t!=="internal"&&(this.draftLocationMap.options=void 0,this.draftLocationMap.locations=[])),this.analyticsService.trackEvent(Z.Events.Doc.REMOVE_LOCATIONS_SUCCESS,{payload:{locations:e},source:t},!0,this.getUserIdForAnalytics())}catch(r){this.loggingService.catch("Error in removeLocation: ",r)}}unsetLocationIds(e,t="internal"){try{this.loggingService.log("%c[WB] Calling FUNCTION: unsetLocationIds","color: green;"),this.coreActionsService.triggerAction($i.INIT_UPDATE,{event:Z.Events.Core.UNSET_LOCATIONS_TRIGGERED,methodName:"unsetLocationIds",source:t,payload:{locationIds:e}}),t==="internal"&&this.analyticsService.trackEvent(Z.Events.Core.UNSET_LOCATIONS_TRIGGERED,{payload:{locationIds:e},methodName:"unsetLocationIds",message:"System unset location ids",source:t},!0,this.getUserIdForAnalytics()),e?.length?e.forEach(r=>{this.getLocation()?.location.id===r&&(this.location$.next(null),t!=="internal"&&(this.draftLocationMap.locations=this.draftLocationMap.locations.filter(a=>a.id!==r))),this.removeCustomLocationId(r)}):(this.location$.next(null),this.locations$.next({}),t!=="internal"&&(this.draftLocationMap.options=void 0,this.draftLocationMap.locations=[])),this.coreActionsService.triggerAction($i.INIT_UPDATE,{event:Z.Events.Doc.REMOVE_LOCATIONS_SUCCESS,methodName:"removeLocationsSuccess",source:t,payload:{locationIds:e}}),this.analyticsService.trackEvent(Z.Events.Doc.REMOVE_LOCATIONS_SUCCESS,{payload:{locationIds:e},source:t},!0,this.getUserIdForAnalytics())}catch(r){this.loggingService.catch("Error in unsetLocationIds: ",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(t){this.loggingService.catch("Error in excludeLocationIds: ",t)}}getExcludedLocationIds$(){try{return this.excludedLocationIds$.asObservable()}catch(e){return this.loggingService.catch("Error in getExcludedLocationIds$: ",e),se([])}}updateOrganizationMetadata(){return Q(this,null,function*(){try{let e=this.organizationConfig$.value?.organizationId,t=this.documentPaths$.value;if(this.db&&e&&t?.documentId){if(this.organizationMetadata$.value?.[e])return;let a=new Ek;a.apiKey=this.configService?.getApiKey()??"",a.organizationId=e,a.clientOrganizationId=this.organizationConfig$.value?.clientOrganizationId,this.userPermissionService?.hasEditAccess({organizationId:e})&&(yield this.commonDbService?.updateData({feature:"organizationMetadata",data:JSON.parse(JSON.stringify(a)),properties:{organizationId:e,documentId:t?.documentId??""}})),yield this.fetchOrganizationMetadata()}}catch(e){this.loggingService.catch("Error in updateOrganizationMetadata: ",e)}})}updateFolderMetadata(){return Q(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: updateFolderMetadata","color: green;"),this.db&&this.authService.getUser()&&this.documentPaths$.value?.folderId){let e=this.documentPaths$.value;if(!e?.veltFolderId||!e?.organizationId)return;if(!(yield this.commonDbService?.getData({feature:"folderMetadata",properties:{organizationId:e?.organizationId??"",folderId:e?.veltFolderId??""}}))?.metadata){let r={folderId:this.documentPaths$.value?.folderId,veltFolderId:this.documentPaths$.value?.veltFolderId,apiKey:this.configService?.getApiKey()??"",organizationId:e?.organizationId,clientOrganizationId:e?.clientOrganizationId,createdAt:Date.now(),lastUpdated:Date.now(),parentFolderId:"root",veltParentFolderId:"root"};this.userPermissionService?.hasEditAccess({folderId:this.documentPaths$.value?.veltFolderId??""})&&this.commonDbService?.updateData({feature:"folderMetadata",data:JSON.parse(JSON.stringify({metadata:r})),properties:{organizationId:e?.organizationId??"",folderId:this.documentPaths$.value?.veltFolderId??""}})}}}catch(e){this.loggingService.catch("Error in updateFolderMetadata: ",e)}})}updateDocumentMetadata(){return Q(this,null,function*(){try{if(this.db&&this.authService.getUser()){let e=this.documentPaths$.value;if(e){let t=this.getDocumentIds();t.find(a=>a.documentId===e.documentId)||t.push({documentId:e.documentId??"",clientDocumentId:e.clientDocumentId??""});let r=t.map(a=>Q(this,null,function*(){let s=new pk;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=Oi();let c=e?.folderId,p=e?.veltFolderId;s?.pageInfo?.deviceInfo&&delete s?.pageInfo?.deviceInfo;let u=!0,C=this.documentMetadata$.value?.[a.documentId];if(c&&p){let E=yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:a?.documentId??"",organizationId:e?.organizationId??"",field:"metadata"}});E?.clientDocumentId&&!E?.errorCode?E?.folderId&&(E?.folderId!==c||E?.veltFolderId!==p)?(this.loggingService.catch(`Folder id mismatch for document ${a?.clientDocumentId??""}`),u=!1):E?.folderId===c?(c&&(s.folderId=c),p&&(s.veltFolderId=p)):(this.loggingService.catch(`Document ${a?.clientDocumentId??""} is not in the folder ${c??""}`),u=!1):(c&&(s.folderId=c),p&&(s.veltFolderId=p))}if(C){let E={};Object.entries(s).forEach(([D,L])=>{E[D]=L}),wi(E,C)&&(u=!1)}u&&this.userPermissionService?.hasEditAccess({documentId:a?.documentId??"",folderId:e?.allDocuments&&e?.veltFolderId?e?.veltFolderId:void 0})&&(yield this.commonDbService?.updateData({feature:"documentMetadata",data:JSON.parse(JSON.stringify(s)),properties:{organizationId:e?.organizationId??"",documentId:a?.documentId??""}}))}));yield Promise.allSettled(r),yield this.fetchDocumentMetadata(t)}}}catch(e){this.loggingService.catch("Error in updateDocumentMetadata: ",e)}})}updateDocumentLocationMetadata(e){return Q(this,null,function*(){try{if(this.db&&this.authService.getUser()){let t=this.documentPaths$.value;if(t){let r=this.getDocumentIds();r.find(a=>a.documentId===t.documentId)||r.push({documentId:t.documentId??"",clientDocumentId:t.clientDocumentId??""});for(let a of r){let s=yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:a?.documentId??"",organizationId:t?.organizationId??"",field:"metadata"}});s?.errorCode&&(s={});let c=[];for(let p of e){let u=new vk;u.locationId=p?.locationId,u.veltLocationId=wj(p?.location?.id??""),u.location=p?.location,u.pageInfo=Oi(),u?.pageInfo?.deviceInfo&&delete u?.pageInfo?.deviceInfo;let C=T(I({},s),{[j.FIREBASE_PARTIAL_PATH_LOCATIONS]:T(I({},s[j.FIREBASE_PARTIAL_PATH_LOCATIONS]??{}),{[p?.locationId]:u})});this.commonDbService?.shouldUseFirestore()||c.push(this.commonDbService?.updateData({feature:"documentMetadata",data:JSON.parse(JSON.stringify(C)),properties:{documentId:a?.documentId??"",organizationId:t?.organizationId??""}}));let E=this.locationMetadata$.value;if(E||(E={}),p?.location?.id){let D=E?.[a.documentId],L=D?.[p?.location?.id??""];E&&(D||(E[a.documentId]={}),L||(E[a.documentId][p?.location?.id??""]={}),E[a.documentId][p?.location?.id??""]=T(I({},L),{location:p?.location})),Object.keys(E||{}).length>0&&this.locationMetadata$.next(E)}}yield Promise.allSettled(c)}}}}catch(t){this.loggingService.catch("Error in updateDocumentLocationMetadata: ",t)}})}genarateLocationId(e){try{return e&&typeof e=="object"?En(JSON.stringify(Yo(e))):0}catch(t){return this.loggingService.catch("Error in genarateLocationId: ",t),0}}removeCustomLocation(e,t="internal"){try{let r=this.genarateLocationId(e),a=this.locations$.value;a[r]&&(delete a[r],this.locations$.next(I({},a)),t!=="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)}}removeCustomLocationId(e,t="internal"){try{this.loggingService.log("%c[WB] Calling FUNCTION: removeCustomLocationId","color: green;");let r=this.locations$.value;Object.entries(r).forEach(([a,s])=>{s.location.id===e&&(delete r[a],this.locations$.next(I({},r)),t!=="internal"&&this.isDocumentIdInDebounceQueue&&(this.draftLocationMap.locations=this.draftLocationMap.locations.filter(c=>c.id!==e)))})}catch(r){this.loggingService.catch("Error in DocService removeCustomLocationId:",r)}}getLocationByClientLocationId(e){try{let t=this.getLocation()?.location;if(t?.id===e)return t;{let r=this.getLocations();Object.keys(r).forEach(a=>{let s=r[a];s.location?.id===e&&(t=s.location)})}return t}catch(t){this.loggingService.catch("Error in DocService getLocationByClientLocationId:",t);return}}removeLocationIfNotInDom(){try{let e=this.locations$.value,t=document.querySelectorAll(`[${j.ATTRIBUTES.VELT_LOCATION}]`),r=[];t.forEach(a=>{let s=a.getAttribute(j.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),se({})}}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 t=null;if(e?.getAttribute(j.ATTRIBUTES.VELT_LOCATION)?t=e:t=e.closest(`[${j.ATTRIBUTES.VELT_LOCATION}]`),t){let r=t?.getAttribute(j.ATTRIBUTES.VELT_LOCATION);if(r){let a=JSON.parse(r);return{locationId:this.genarateLocationId(a),location:a}}}return null}catch(t){return this.loggingService.catch("Error in DocService getLocationFromElement:",t),null}}getElementMapWithLocation(){try{this.loggingService.log("%c[WB] Calling FUNCTION: getElementMapWithLocation","color: green;");let e={};return document.querySelectorAll(`[${j.ATTRIBUTES.VELT_LOCATION}], [${j.ATTRIBUTES.VELT_LOCATION_ID}]`).forEach(r=>{if(r.getAttribute(j.ATTRIBUTES.VELT_LOCATION)){let a=this.getLocationFromElement(r);a?.locationId&&(e[a.locationId]={element:r,location:a})}else if(r.getAttribute(j.ATTRIBUTES.VELT_LOCATION_ID)){let a=r.getAttribute(j.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 t;if(t=e?.closest(`[${j.ATTRIBUTES.VELT_LOCATION}], [${j.ATTRIBUTES.VELT_LOCATION_ID}]`),t){if(t?.getAttribute(j.ATTRIBUTES.VELT_LOCATION)){let r=t?.getAttribute(j.ATTRIBUTES.VELT_LOCATION);if(r)return JSON.parse(r)}else if(t?.getAttribute(j.ATTRIBUTES.VELT_LOCATION_ID)){let r=t?.getAttribute(j.ATTRIBUTES.VELT_LOCATION_ID);if(r)return{id:r}}}return null}catch(t){return this.loggingService.catch("Error in DocService getAdditionLocationFromElement:",t),null}}getAdditionalDocumentIdFromElement(e){try{return e?.closest(`[${j.ATTRIBUTES.VELT_DOCUMENT_ID}]`)?.getAttribute(j.ATTRIBUTES.VELT_DOCUMENT_ID)||null}catch(t){return this.loggingService.catch("Error in DocService getAdditionalDocumentIdFromElement:",t),null}}getDocumentMetadata(e){try{return e?this.documentMetadata$.value?.[e]||null:this.documentMetadata$.value?.[this.documentPaths$.value?.documentId??""]||null}catch(t){return this.loggingService.catch("Error in DocService getDocumentMetadata:",t),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||{},t={},r=this.documentPaths$.value?.veltFolderId,a=this.documentPaths$.value?.allDocuments;if(r&&a)Object.values(e).forEach(s=>{s?.documentId&&s?.veltFolderId===r&&(t[s.documentId]=s)});else{let s=this.documentIds$.value;if(s?.length)s.forEach(c=>{let p=e?.[c.documentId];p&&(t[c.documentId]=p)});else if(this.documentPaths$.value?.documentId){let c=e?.[this.documentPaths$.value?.documentId];c&&(t[this.documentPaths$.value?.documentId]=c)}}return Object.values(t)}catch(e){return this.loggingService.catch("Error in DocService getDocumentMetadataOfAvailableDocuments:",e),[]}}getDocumentMetadata$(e){return this.documentMetadata$.asObservable().pipe(ce(t=>t?.[e??this.documentPaths$.value?.documentId??""]||null))}getOrganizationMetadata(e){return this.organizationMetadata$.value?.[e]||null}getOrganizationMetadata$(e){return this.organizationMetadata$.asObservable().pipe(ce(t=>t?.[e]||null))}getCustomerMetadata(){return this.customerMetadata$.value}getCustomerMetadata$(){return this.customerMetadata$.asObservable()}getOrganizationConfig$(){return this.organizationConfig$.asObservable().pipe(Et(mn))}getOrganizationConfig(){return this.organizationConfig$.value}getMetadataFromType(e,t){try{switch(e){case"area":return;case"comment":return t?.multiThreadAnnotationId?this.commentService?.getMultiThreadAnnotationById(t.multiThreadAnnotationId)?.metadata:void 0;case"reaction":case"recorder":return t?.commentAnnotationId?this.commentService?.getAnnotationById(t.commentAnnotationId)?.metadata:void 0;default:return}}catch(r){this.loggingService.catch("Error in DocService getMetadataFromType:",r);return}}getDefaultMetadata({clientDocumentId:e,documentId:t}){try{let r=this.documentPaths$.value;if(!r)return;let a=e||r.clientDocumentId,s=t||r.documentId,c=this.getDocumentMetadata(s);if(!c)return;let p=c?.folderId,u=c?.veltFolderId;return I(I({apiKey:this.configService.getApiKey()??void 0,clientDocumentId:a,clientOrganizationId:r.clientOrganizationId,documentId:s,organizationId:r.organizationId},p?{folderId:p}:{}),u?{veltFolderId:u}:{})}catch(r){this.loggingService.catch("Error in DocService getDefaultMetadata:",r);return}}getBaseMetadata(e,t){try{let r,a;t?.element?r=this.getAdditionalDocumentIdFromElement(t.element)||void 0:t?.clientDocumentId&&(r=t.clientDocumentId),r&&(a=this.generateDocumentId(r));let s=this.getMetadataFromType(e,t),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:t}){try{return e&&(e=this.generateDocumentId(e)),t&&(t=this.generateOrganizationId(t)),{documentId:e,organizationId:t}}catch(r){return this.loggingService.catch("Error in DocService getServerId:",r),null}}fetchDocuments(e){return Q(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=Fi(e?.folderId);r.push(lt("metadata.veltFolderId","==",s))}return e?.documentIds?.length&&!e?.allDocuments&&r.push(lt("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(t){return this.loggingService.catch("Error in DocService fetchDocuments:",t),[]}})}fetchLocations(e){return Q(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.commonDbService?.shouldUseFirestore()&&this.loggingService.catch("Error in fetchLocations: organizationId is required"),[];if(e?.folderId){let s=Fi(e?.folderId);r.push(lt("metadata.veltFolderId","==",s))}return e?.documentIds?.length&&!e?.allDocuments&&r.push(lt("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(t){return this.loggingService.catch("Error in DocService fetchLocations:",t),[]}})}updateDocuments(e){return Q(this,null,function*(){try{if(typeof e=="object"&&(e=JSON.parse(JSON.stringify(e??{}))),!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,folderId:s}=e;if(!r&&(r=this.documentPaths$.value?.clientOrganizationId,!r))return this.loggingService.catch("Error in updateDocuments: organizationId is required"),[];let c=La(r);if(!a||a.length===0)return this.loggingService.catch("Error in updateDocuments: documents is required"),[];let p=[],u=this.documentMetadata$.value??{};for(let C of a)if(C?.documentId){C.organizationId=c,C.clientOrganizationId=r,C.clientDocumentId=C.documentId;let E=na(C.documentId);C.documentId=E,C.apiKey=this.configService.getApiKey()??void 0,(s||this.documentPaths$.value?.folderId)&&(C.folderId=s||this.documentPaths$.value?.folderId,C.veltFolderId=Fi(s||this.documentPaths$.value?.folderId||""));let D=()=>{if(s&&this.documentPaths$.value?.folderId&&s!==this.documentPaths$.value?.folderId)return;let z=u?.[E];z?u[E]=I(I({},z),C):u[E]=C},L=yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:E,organizationId:c,field:"metadata"}});if(L?.errorCode&&(L={}),L&&L.apiKey&&L.folderId&&s&&L.folderId!=C.folderId){this.loggingService.catch(`Error in updateDocuments: document ${C.clientDocumentId} already exists with different folderId: ${L.folderId}`);continue}if(L&&L.apiKey&&!L.folderId&&C.folderId){this.loggingService.catch(`Error in updateDocuments: document ${C.clientDocumentId} already exists, move this document to folder with REST API`);continue}D(),C&&this.commonDbService&&this.userPermissionService?.hasEditAccess({documentId:C?.documentId??""})&&p.push(this.commonDbService.updateData({feature:"documentMetadata",data:JSON.parse(JSON.stringify(C)),properties:{organizationId:c,documentId:E}}))}yield Promise.all(p),this.documentMetadata$.next(u)}catch(t){return this.loggingService.catch("Error in DocService updateDocuments:",t),[]}})}updateLocations(e){return Q(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(C=>C.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(C=>na(C)),p=[],u=this.locationMetadata$.value;u||(u={}),c.forEach(C=>{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 L=wj(E.id),z=u?.[C],W=z?.[E.id];u&&(z||(u[C]={}),W||(u[C][E.id]={}),u[C][E.id]=T(I({},W),{location:E})),E&&this.commonDbService&&p.push(this.commonDbService.updateData({feature:"locationMetadata",data:JSON.parse(JSON.stringify({location:E})),properties:{organizationId:La(r),documentId:C,id:L}}))}})}),yield Promise.all(p),Object.keys(u||{}).length>0&&this.locationMetadata$.next(u)}catch(t){return this.loggingService.catch("Error in DocService updateLocations:",t),[]}})}fetchFolders(e){return Q(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=Fi(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:[lt("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(t){return this.loggingService.catch("Error in DocService getFoldersRequest:",t),{data:[],parentFolders:[]}}})}getDocumentIam$(){return this.authService.getUser$().pipe(he(e=>e?this.documentPaths$.pipe(he(t=>t?.documentIam?this.commonDbService?.dbListener({feature:"documentIam",properties:{documentId:t.documentId,organizationId:t.organizationId,isCollection:!1}}).pipe(ce(r=>r?.data?.docIamConfig??r?.data),Et((r,a)=>JSON.stringify(r??{})===JSON.stringify(a??{}))):se(null))):se(null)))}getDocumentAccessType(e){try{return e&&e.features&&e.features.all?e.features.all.restricted?yi.RESTRICTED:yi.PUBLIC:e&&e.documentAccessType?e.documentAccessType:yi.PUBLIC}catch(t){return this.loggingService.catch("Error in DocService getDocumentAccessType:",t),yi.PUBLIC}}changeDocumentAccessType(e){return Q(this,null,function*(){try{let t=this.documentPaths$.value;if(t){let r=yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:t?.documentId??"",organizationId:t?.organizationId??"",field:"docIamConfig"}});if(r?.errorCode)return;switch(delete r.documentAccessType,r.features||(r.features={}),r.features.all||(r.features.all={}),e){case yi.PUBLIC:r.features.all.restricted=!1;break;case yi.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:t?.documentId??"",organizationId:t?.organizationId??""}})}}catch(t){this.loggingService.catch("Error in DocService changeDocumentAccessType:",t)}})}getUserIdForAnalytics(){try{return this.authService?.getAuthUser()?.uid||""}catch(e){return this.loggingService.catch("Error in DocService getUserIdForAnalytics:",e),""}}setUIState(e){try{this.uiState.next(I(I({},this.uiState.value),e))}catch(t){this.loggingService.catch("Error in DocService setUIState:",t)}}getUIState$(){return this.uiState.asObservable()}};o.\u0275fac=function(t){return new(t||o)(ee(et),ee(Ve),ee(Dn),ee(Be),ee(Ft),ee(y),ee(Rs),ee(jd),ee(Vd))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var Vn=(()=>{let o=class o{constructor(e,t,r,a){this.analyticsService=e,this.authService=t,this.docService=r,this.loggingService=a,this.resolveOrganizationUsers=new ve(!0),this.resolveFolderUsers=new ve(!0),this.resolveDocumentUsers=new ve(!0),this.resolveTimeout=1*60*1e3,this.resolveAttempts=new Map,this.subscriptions=new yn,this.userDataProvider$=new ve(null),this.userById$=new ve({}),this.userByIdCalled$=new ve({}),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)}}setCommonDbService(e){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setCommonDbService","color: green;"),this.commonDbService=e}catch(t){this.loggingService.catch("Error in UsersService setCommonDbService:",t)}}ngOnDestroy(){try{this.subscriptions.unsubscribe(),this.pendingResolutions.clear(),this.resolveAttempts.clear()}catch(e){this.loggingService.catch("Error in UsersService ngOnDestroy:",e)}}isResolverForFeatureDisabled(e){let t=this.userDataProvider$.getValue();try{switch(e){case"allOrganizationUsers":return t?!this.resolveOrganizationUsers.value:!0;case"allFolderUsers":return t?!this.resolveFolderUsers.value:!0;case"allDocumentUsers":return t?!this.resolveDocumentUsers.value:!0;default:return!1}}catch(r){return this.loggingService.catch("Error in UsersService isResolverForFeatureDisabled:",r),!1}}resolveUsers(c){return Q(this,arguments,function*({userIds:e,forceResolve:t,feature:r,organizationId:a,skipUserCheck:s=!1}){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: resolveUsers","color: green;");let p=!1;if(r&&(p=this.isResolverForFeatureDisabled(r)),p)return{};{let u={},C=[],E={};if(e?.forEach(D=>{let L=this.getUserById(D);L?u[D]=L:this.userByIdCalled$.getValue()[D]?t&&C.push(D):(C.push(D),this.userByIdCalled$.next(T(I({},this.userByIdCalled$.getValue()),{[D]:!0})))}),C.length>0){let D={};try{let L,z=new Promise((W,J)=>{L=setTimeout(()=>{J(new Error("User resolution timeout"))},this.userDataProvider$.getValue()?.config?.resolveTimeout||this.userDataProvider$.getValue()?.resolveTimeout||this.resolveTimeout)});D=yield Promise.race([this.getUsersFromDB({userIds:C,organizationId:a,skipUserCheck:s}).finally(()=>{clearTimeout(L)}),z]),this.analyticsService.trackEvent(Z.Events.Resolver.USER_RESOLVER_GET,{sourceMethod:"resolveUsers",source:"sdk",userIds:C})}catch(L){this.loggingService.catch("Error in UsersService resolveUsers getUsers:",L,{userIds:C})}finally{C?.forEach(L=>{D[L]||(D[L]={userId:L,name:`User ${L}`})})}Object.entries(D).forEach(([L,z])=>{z&&(u[L]=D?.[L],E[L]=D?.[L])})}return Object.keys(E).length>0&&(this.authService.setOptionalPropertiesToUsers(Object.values(E)),this.userById$.next(I(I({},this.userById$.getValue()),E))),u}}catch(p){return this.loggingService.catch("Error in UsersService resolveUsers:",p),{}}})}getUsersFromDB(a){return Q(this,arguments,function*({userIds:e,organizationId:t,skipUserCheck:r=!1}){this.loggingService.log("%c[WB] Calling UsersService FUNCTION: getUsersFromDB","color: green;");try{let s=this.userDataProvider$.getValue();if(s)return s.get(e);if(t||(t=this.docService.getOrganizationConfig()?.organizationId),!t)return{};let c=(yield this.getUsersFromDBWithBatching({userIds:e,organizationId:t,skipUserCheck:r}))??[],p={};return c.forEach(u=>{u.forEach(C=>{C?.user?.userId&&(p[C.user.userId]=C.user)})}),p}catch(s){return this.loggingService.catch("Error in UsersService getUsersFromDB:",s),{}}})}getUsersFromDBWithBatching(a){return Q(this,arguments,function*({userIds:e,organizationId:t,skipUserCheck:r=!1}){try{if(!e?.length)return[];let s=[];for(let u=0;u<e.length;u+=30)s.push(e.slice(u,u+30));let c=s.map((u,C)=>Q(this,null,function*(){try{return(yield this.commonDbService?.queryData({feature:"allOrganizationUsers",properties:{organizationId:t,useCollectionGroup:!1,isCollection:!0,firestoreQuery:[lt("user.userId","in",u)],skipUserCheck:r}}))||[]}catch(E){return this.loggingService.catch(`Error in batch ${C+1}:`,E),[]}}));return yield Promise.all(c)}catch(s){return this.loggingService.catch("Error in getUsersFromDBWithBatching:",s),[]}})}getTemporaryUsersFromDBWithBatching(a){return Q(this,arguments,function*({userIds:e,organizationId:t,resourceIds:r}){try{if(!e?.length||!r?.length)return[];let s=[];for(let z=0;z<e.length;z+=30)s.push(e.slice(z,z+30));let c=[];for(let z=0;z<r.length;z+=30)c.push(r.slice(z,z+30));let p=[],u=0,C=(z,W)=>Q(this,null,function*(){try{return((yield this.commonDbService?.queryData({feature:"allPermissionsUsers",properties:{organizationId:t,useCollectionGroup:!1,isCollection:!0,firestoreQuery:[Zn(lt("userId","in",z),lt("veltResourceId","in",W))]}}))??[])||[]}catch(J){return this.loggingService.catch(`Error in batch ${u+1}:`,J),[]}});for(let z of s)for(let W of c)p.push(C(z,W)),u++;return(yield Promise.all(p)).flat().filter((z,W,J)=>W===J.findIndex(ue=>ue.userId===z.userId&&ue.resourceId===z.resourceId))}catch(s){return this.loggingService.catch("Error in getTemporaryUsersFromDBWithBatching:",s),[]}})}getResolveOrganizationUsers$(){return this.resolveOrganizationUsers.asObservable()}getResolveFolderUsers$(){return this.resolveFolderUsers.asObservable()}getResolveDocumentUsers$(){return this.resolveDocumentUsers.asObservable()}getUserById$(){try{return this.loggingService.log("%c[WB] Calling UsersService FUNCTION: getUserById$","color: green;"),this.userById$.asObservable().pipe(Et(mn))}catch(e){return this.loggingService.catch("Error in UsersService getUserById$:",e),se({})}}setUserByIds(e){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setUserByIds","color: green;");let t=this.userById$.getValue();e.forEach(r=>{t[r.userId]=I(I({},t?.[r.userId]??{}),r)}),this.userById$.next(t)}catch(t){this.loggingService.catch("Error in UsersService setUserByIds:",t)}}setUserDataProvider(e){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setUserDataProvider","color: green;"),this.userDataProvider$.next(e),e.config?.resolveUsersConfig?.organization===!1?this.resolveOrganizationUsers.next(!1):this.resolveOrganizationUsers.next(!0),e.config?.resolveUsersConfig?.folder===!1?this.resolveFolderUsers.next(!1):this.resolveFolderUsers.next(!0),e.config?.resolveUsersConfig?.document===!1?this.resolveDocumentUsers.next(!1):this.resolveDocumentUsers.next(!0)}catch(t){this.loggingService.catch("Error in UsersService setUserDataProvider:",t)}}userDataProviderAvailable(){try{return this.loggingService.log("%c[WB] Calling UsersService FUNCTION: userDataProviderAvailable","color: green;"),!!this.commonDbService?.shouldUseFirestore()}catch(e){return this.loggingService.catch("Error in UsersService userDataProviderAvailable:",e),!1}}};o.\u0275fac=function(t){return new(t||o)(ee(et),ee(Ve),ee(at),ee(y))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var Rce=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.usersService=t}getUserIdsToResolveFromAreaAnnotations(e){try{this.loggingService.log("%c[WB] Calling AreaUtilsService FUNCTION: getUserIdsToResolveFromAreaAnnotations","color: green;");let t=new Set;for(let r of e)r?.from?.userId&&t.add(r?.from?.userId);return Array.from(t)}catch(t){return this.loggingService.catch("Error in AreaUtilsService getUserIdsToResolveFromAreaAnnotations:",t),[]}}mergeAreaWithUser(e){try{if(this.loggingService.log("%c[WB] Calling AreaUtilsService FUNCTION: mergeAreaWithUser","color: green;"),e?.from?.userId){let t=this.usersService.getUserById(e?.from?.userId);t&&(e.from=t)}return e}catch(t){return this.loggingService.catch("Error in AreaUtilsService mergeAreaWithUser:",t),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(t){return this.loggingService.catch("Error in AreaUtilsService formatAreaData:",t),e}}};o.\u0275fac=function(t){return new(t||o)(ee(y),ee(Vn))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var Nce=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.usersService=t}getUserIdsToResolveFromArrowAnnotations(e){try{this.loggingService.log("%c[WB] Calling ArrowUtilsService FUNCTION: getUserIdsToResolveFromArrowAnnotations","color: green;");let t=new Set;for(let r of e)r?.from?.userId&&t.add(r?.from?.userId);return Array.from(t)}catch(t){return this.loggingService.catch("Error in ArrowUtilsService getUserIdsToResolveFromArrowAnnotations:",t),[]}}mergeArrowWithUser(e){try{if(this.loggingService.log("%c[WB] Calling ArrowUtilsService FUNCTION: mergeArrowWithUser","color: green;"),e?.from?.userId){let t=this.usersService.getUserById(e?.from?.userId);t&&(e.from=t)}return e}catch(t){return this.loggingService.catch("Error in ArrowUtilsService mergeArrowWithUser:",t),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(t){return this.loggingService.catch("Error in ArrowUtilsService formatArrowData:",t),e}}};o.\u0275fac=function(t){return new(t||o)(ee(y),ee(Vn))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var og=class{static getFirestoreProdDbName(o,n){return n?.storeDbId??(this.isTestingDb(n?.databaseURL??"")?"sdktest":`apikey${o.toLowerCase()}`)}static isTestingDb(o){try{return o.includes("-test")}catch(n){return ot.error("Error in isTestingDb:",n),!1}}};var rg=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.analyticsService=t,this.retrySaveConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.retryDeleteConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.attachmentDataProvider$=new ve(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 Q(this,null,function*(){try{this.loggingService.log("%c[WB] Calling AttachmentResolverService FUNCTION: saveAttachment","color: green;");let t=this.getProvider();if(!this.attachmentDataProviderAvailable())throw new Error("Attachment save data provider not available");let r=yield Pc(()=>t?.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(t){this.loggingService.warn("Error in AttachmentResolverService saveAttachment:",t);return}})}deleteAttachment(r){return Q(this,arguments,function*({attachmentId:e,metadata:t}){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 Pc(()=>a?.delete({attachmentId:e,metadata:t,event:os.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(t){this.loggingService.catch("Error in AttachmentResolverService setAttachmentDataProvider:",t)}}attachmentDataProviderAvailable(){try{return!!this.attachmentDataProvider$.getValue()}catch(e){return this.loggingService.catch("Error in AttachmentResolverService attachmentDataProviderAvailable:",e),!1}}};o.\u0275fac=function(t){return new(t||o)(ee(y),ee(et))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var f0=(()=>{let o=class o{constructor(e,t,r,a,s,c,p){this.loggingService=e,this.usersService=t,this.authService=r,this.functions=a,this.configService=s,this.commentAnnotationsResolverService=c,this.attachmentResolverService=p,this.notificationActionTypeMap={[$t.NEWLY_ADDED]:os.COMMENT_ANNOTATION_ADD,[$t.ADDED]:os.COMMENT_ADD,[$t.UPDATED]:os.COMMENT_UPDATE,[$t.DELETED]:os.COMMENT_DELETE}}setNotificationService(e){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: setNotificationService","color: green;"),this.notificationService=e}catch(t){this.loggingService.catch("Error in CommentUtilsService setNotificationService: ",t)}}getUserIdsToResolveFromComments(e){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: getUserIdsToResolveFromComments","color: green;");let t=new Set;for(let r of e){if(r?.from?.userId&&t.add(r?.from?.userId),r?.comments)for(let a of r?.comments){if(a?.from?.userId&&t.add(a?.from?.userId),a?.to)for(let s of a?.to)s?.userId&&t.add(s?.userId);if(a?.taggedUserContacts)for(let s of a?.taggedUserContacts)s?.userId&&t.add(s?.userId)}if(r?.assignedTo?.userId&&t.add(r?.assignedTo?.userId),r?.subscribedUsers)for(let a of Object.values(r?.subscribedUsers))a.user.userId&&t.add(a.user.userId);if(r?.unsubscribedUsers)for(let a of Object.values(r?.unsubscribedUsers))a.user.userId&&t.add(a.user.userId)}return Array.from(t)}catch(t){return this.loggingService.catch("Error in CommentUtilsService getUserIdsToResolveFromComments:",t),[]}}mergeCommentWithUser(e){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: mergeCommentWithUser","color: green;"),e?.from?.userId){let t=this.usersService.getUserById(e?.from?.userId);t&&(e.from=t)}if(e?.comments)for(let t of e?.comments){if(t?.from?.userId){let a=this.usersService.getUserById(t?.from?.userId);a&&(t.from=a)}t?.to&&(t.to=t?.to?.map(a=>{if(a?.userId){let s=this.usersService.getUserById(a?.userId);if(s)return I(I({},a),s)}return a})),t?.taggedUserContacts&&(t.taggedUserContacts=t?.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})),(t?.taggedUserContacts?.filter((a,s,c)=>c.findIndex(p=>p.text===a.text)===s)||[]).forEach(a=>{if(a?.text){let s=new RegExp(Od(`{{${a.userId}}}`),"g");t.commentText=t.commentText?.replaceAll(s,a.text),t.commentHtml=t.commentHtml?.replaceAll(s,a.text)}})}if(e?.assignedTo?.userId){let t=this.usersService.getUserById(e?.assignedTo?.userId);t&&(e.assignedTo=t)}if(e?.subscribedUsers)for(let t of Object.values(e?.subscribedUsers)){let r=this.usersService.getUserById(t.user.userId);r&&e?.subscribedUsers?.id?.user&&(e.subscribedUsers.id.user=r)}if(e?.unsubscribedUsers)for(let t of Object.values(e?.unsubscribedUsers)){let r=this.usersService.getUserById(t.user.userId);r&&e?.unsubscribedUsers?.id?.user&&(e.unsubscribedUsers.id.user=r)}return e}catch(t){return this.loggingService.catch("Error in CommentUtilsService mergeCommentWithUser:",t),e}}formatCommentData(e){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: formatCommentData","color: green;"),e?.comments?.forEach(t=>{t?.commentText&&t?.commentText?.length>0&&(t.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 t of Object.keys(e?.subscribedUsers))e.subscribedUsers[t].user={userId:e?.subscribedUsers[t].user.userId};if(e?.unsubscribedUsers)for(let t of Object.keys(e?.unsubscribedUsers))e.unsubscribedUsers[t].user={userId:e?.unsubscribedUsers[t].user.userId}}return e?.comments&&(e.comments=e?.comments?.map(t=>this.formatCommentThreadData(t))),e}catch(t){return this.loggingService.catch("Error in CommentUtilsService formatCommentData:",t),e}}mergeStrippedDataWithCommentAnnotations(e){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: mergeStrippedDataWithCommentAnnotations","color: green;"),!this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())return e;let t=this.commentAnnotationsResolverService.getAnnotationById(e?.annotationId),r=this.attachmentResolverService.attachmentDataProviderAvailable(),a=this.commentAnnotationsResolverService.getFieldsToRemove();return t&&(e?.comments?.forEach(s=>{let c=t?.comments?.[s?.commentId];if(c){s.commentHtml=c?.commentHtml,s.commentText=c?.commentText;let p=c?.attachments;r&&p&&s.attachments?.forEach(u=>{let C=u?.attachmentId;p?.[C]&&(u.name=p?.[C]?.name,u.url=p?.[C]?.url)})}}),t?.targetTextRange?.text&&e?.targetTextRange&&(e.targetTextRange.text=t?.targetTextRange?.text),a?.length>0&&a.forEach(s=>{t?.[s]&&(e[s]=t[s])})),e}catch(t){return this.loggingService.catch("Error in CommentUtilsService mergeStrippedDataWithCommentAnnotations:",t),e}}mergeLocationWithCommentAnnotations(e,t){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=t?.[a]?.[r];return s&&(e.location=s?.location),e}catch(r){return this.loggingService.catch("Error in CommentUtilsService mergeLocationWithCommentAnnotations:",r),e}}isCommentsDataChanged(e,t){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: isCommentsDataChanged","color: green;");let r=this.commentAnnotationsResolverService.getCommentAnnotationById(t);return r?!wi(e,r):!0}catch(r){return this.loggingService.catch("Error in CommentUtilsService isCommentsDataChanged:",r),!0}}stripCommentsFromAnnotationData({comment:e}){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: stripCommentsFromAnnotationData","color: green;");let t=this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable();if(!t)return e;let r=this.attachmentResolverService.attachmentDataProviderAvailable(),a=new Nc;if(Object.assign(a,e),a.isCommentResolverUsed=t,r){let s=a.attachments?.map(c=>(c.isAttachmentResolverUsed=!0,delete c?.name,delete c?.url,c));a.attachments=s}return delete a?.commentHtml,delete a?.commentText,a}catch(t){return this.loggingService.catch("Error in CommentUtilsService stripCommentsFromAnnotationData:",t),e}}stripCommentAnnotationData({data:e,actionType:t}){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: stripCommentAnnotationData","color: green;"),!this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable()||!t)return{originalData:e,strippedData:null};let r=this.attachmentResolverService.attachmentDataProviderAvailable(),a=this.commentAnnotationsResolverService.getFieldsToRemove(),s=this.notificationActionTypeMap?.[t],c={},p=null,u=!1;if(e&&e.annotationId){let C=e.annotationId;c[C]=I(I(I(I({annotationId:C,metadata:Rv(e.metadata??{}),comments:{}},e?.from&&{from:e?.from}),e?.assignedTo&&{assignedTo:e?.assignedTo}),e?.resolvedByUserId&&{resolvedByUserId:e?.resolvedByUserId}),e?.targetTextRange?.text&&{targetTextRange:{text:e?.targetTextRange?.text}}),delete e?.targetTextRange?.text,a?.length>0&&a.forEach(D=>{e?.[D]&&(c[C][D]=e[D],delete e[D])}),e.comments?.forEach(D=>{if(D.commentId){let L;r&&(L={},D.attachments?.forEach(z=>{L[z.attachmentId]={attachmentId:z.attachmentId,name:z.name,url:z.url}})),c[C].comments[D.commentId]=I(I(I(I(I(I({commentId:D.commentId},D?.commentHtml&&{commentHtml:D?.commentHtml}),D?.commentText&&{commentText:D?.commentText}),L&&{attachments:L}),D?.from&&{from:D?.from}),D?.to&&{to:D?.to}),D?.taggedUserContacts&&{taggedUserContacts:D?.taggedUserContacts})}}),u=this.isCommentsDataChanged(c[C],C);let E=new Bo;Object.assign(E,e),E.comments=e.comments?.map(D=>this.stripCommentsFromAnnotationData({comment:D}))||[],p=E}return{strippedData:u?c:null,originalData:p,eventType:s}}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 t=e?.taggedUserContacts?.filter((r,a,s)=>s.findIndex(c=>c.text===r.text)===a)||[];t.forEach(r=>{if(r?.text){let a=new RegExp(Od(r.text),"g");e.commentText=e.commentText?.replaceAll(a,s=>`{{${r.userId}}}`),e.commentHtml=e.commentHtml?.replaceAll(a,s=>`{{${r.userId}}}`)}}),t.forEach(r=>{r?.text&&(r.text="")})}return e}catch(t){return this.loggingService.catch("Error in CommentUtilsService formatCommentThreadData:",t),e}}handleCommentEncryption(c){return Q(this,arguments,function*({data:e,firestorePath:t,extraData:r,eventType:a,metadata:s}){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: handleCommentEncryption","color: green;");let p=WP(this.authService.getFirebaseConfig()?.firebaseOptions),u=br(this.functions,Er({url:oi.cloudFunction?.[p]?.setEncryptedData,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:20*60*1e3});if(r){r=this.notificationService?.processNotificationData(r),r.annotationData=e;let L=r?.targetAnnotationData?.commentId;if(L){let z=e?.comments?.find(W=>W?.commentId===L);z&&(r.targetAnnotationData=z)}try{let z=this.stripCommentAnnotationData({data:r.annotationData,actionType:r?.actionType??$t.NEWLY_ADDED});z?.originalData&&(r.annotationData=this.formatCommentData(z.originalData)),r?.targetAnnotationData&&(r.targetAnnotationData=this.formatCommentThreadData(this.stripCommentsFromAnnotationData({comment:r.targetAnnotationData})))}catch(z){this.loggingService.warn("Error in CommentUtilsService handleCommentEncryption:",z)}}let C=og.getFirestoreProdDbName(this.configService.getApiKey()??"",this.authService.getFirebaseConfig()?.firebaseOptions),E={path:t??"",data:e??{},dbId:C??"",notificationData:r||void 0,notificationURL:oi.firebaseNotificationsDatabaseURL,feature:"comment",eventType:a??"PATCH",sdkVersion:ia(),metadata:s},D=yield Gp(E,this.authService.getUser()?.userId??"");yield u({veltData:D})}catch(p){this.loggingService.catch("Error in CommentUtilsService handleCommentEncryption:",p)}})}};o.\u0275fac=function(t){return new(t||o)(ee(y),ee(Vn),ee(Ve),ee(Wo),ee(Ft),ee(Rs),ee(rg))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var Fce=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.usersService=t}getUserIdsToResolveFromUserIamData(e){try{this.loggingService.log("%c[WB] Calling ContactUtilsService FUNCTION: getUserIdsToResolveFromUserIamData","color: green;");let t=new Set;if(e?.length)for(let r of e)r?.user?.userId&&t.add(r?.user?.userId);return Array.from(t)}catch(t){return this.loggingService.catch("Error in ContactUtilsService getUserIdsToResolveFromUserIamData: ",t),[]}}mergeUserIamWithUser(e){try{if(this.loggingService.log("%c[WB] Calling ContactUtilsService FUNCTION: mergeUserIamWithUser","color: green;"),e?.user?.userId){let t=this.usersService.getUserById(e?.user?.userId);if(t){let r=t;e?.user&&typeof e.user=="object"&&(r=I(I({},r),e.user)),e=T(I({},e),{user:r})}}return e}catch(t){return this.loggingService.catch("Error in ContactUtilsService mergeUserIamWithUser: ",t),e}}};o.\u0275fac=function(t){return new(t||o)(ee(y),ee(Vn))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var Lce=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.usersService=t}getUserIdsToResolveFromCursorUsers(e){try{this.loggingService.log("%c[WB] Calling CursorUtilsService FUNCTION: getUserIdsToResolveFromCursorUsers","color: green;");let t=new Set;for(let r of e)r?.userId&&t.add(r?.userId);return Array.from(t)}catch(t){return this.loggingService.catch("Error in CursorUtilsService getUserIdsToResolveFromCursorUsers:",t),[]}}mergeCursorUserWithUser(e){try{if(this.loggingService.log("%c[WB] Calling CursorUtilsService FUNCTION: mergeCursorUserWithUser","color: green;"),this.usersService.userDataProviderAvailable()&&e?.userId){let t=this.usersService.getUserById(e?.userId);t&&(e=I(I({},e),t))}return e}catch(t){return this.loggingService.catch("Error in CursorUtilsService mergeCursorUserWithUser:",t),e}}formatCursorUserData(e){try{if(this.loggingService.log("%c[WB] Calling CursorUtilsService FUNCTION: formatCursorUserData","color: green;"),this.usersService.userDataProviderAvailable()){let t=["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=>{t.includes(r)||(e[r]=null)})}return e}catch(t){return this.loggingService.catch("Error in CursorUtilsService formatCursorUserData:",t),e}}};o.\u0275fac=function(t){return new(t||o)(ee(y),ee(Vn))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var Mk=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.usersService=t}getUserIdsToResolveFromHuddleAttendees(e){try{this.loggingService.log("%c[WB] Calling HuddleUtilsService FUNCTION: getUserIdsToResolveFromHuddleAttendees","color: green;");let t=new Set;for(let r of e)r?.userId&&t.add(r?.userId);return Array.from(t)}catch(t){return this.loggingService.catch("Error in HuddleUtilsService getUserIdsToResolveFromHuddleAttendees:",t),[]}}mergeHuddleAttendeeWithUser(e){try{if(this.loggingService.log("%c[WB] Calling HuddleUtilsService FUNCTION: mergeHuddleAttendeeWithUser","color: green;"),e?.userId){let t=this.usersService.getUserById(e?.userId);t&&(e=I(I({},e),t))}return e}catch(t){return this.loggingService.catch("Error in HuddleUtilsService mergeHuddleAttendeeWithUser:",t),e}}formatHuddleAttendeeData(e){try{if(this.usersService.userDataProviderAvailable()){let t=["userId","userSnippylyId","state","timestamp","initialHuddleMode","streamMetadata","initialHuddleType","huddleOnCursorMode"];Object.keys(e).forEach(r=>{t.includes(r)||(e[r]=null)})}return e}catch(t){return this.loggingService.catch("Error in HuddleUtilsService formatHuddleAttendeeData:",t),e}}getUserIdsToResolveFromHuddleMessages(e){try{this.loggingService.log("%c[WB] Calling HuddleUtilsService FUNCTION: getUserIdsToResolveFromHuddleMessages","color: green;");let t=new Set;for(let r of e)r?.from?.userId&&t.add(r?.from?.userId);return Array.from(t)}catch(t){return this.loggingService.catch("Error in HuddleUtilsService getUserIdsToResolveFromHuddleMessages:",t),[]}}mergeHuddleMessageWithUser(e){try{if(this.loggingService.log("%c[WB] Calling HuddleUtilsService FUNCTION: mergeHuddleMessageWithUser","color: green;"),e?.from?.userId){let t=this.usersService.getUserById(e?.from?.userId);t&&(e.from=t)}return e}catch(t){return this.loggingService.catch("Error in HuddleUtilsService mergeHuddleMessageWithUser:",t),e}}resolveUsersFromHuddleMessages(e){return Q(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling HuddleUtilsService FUNCTION: resolveUsersFromHuddleMessages","color: green;"),this.usersService.userDataProviderAvailable()){let t=this.getUserIdsToResolveFromHuddleMessages(e),r=yield this.usersService.resolveUsers({userIds:t});for(let a of e)a?.from?.userId&&r[a.from.userId]&&(a.from=r[a.from.userId])}return e}catch(t){return this.loggingService.catch("Error in HuddleUtilsService resolveUsersFromHuddleMessages:",t),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(t){return this.loggingService.catch("Error in HuddleUtilsService formatHuddleMessageData:",t),e}}};o.\u0275fac=function(t){return new(t||o)(ee(y),ee(Vn))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var kk=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.usersService=t}getUserIdsToResolveFromLiveStateCustom(e){try{let t=new Set;return e?.updatedBy&&t.add(e?.updatedBy?.userId),Array.from(t)}catch(t){return this.loggingService.catch("Error in LiveStateUtilsService getUserIdsToResolveFromLiveStateCustom:",t),[]}}mergeLiveStateCustomWithUser(e){try{if(e?.updatedBy?.userId){let t=this.usersService.getUserById(e?.updatedBy?.userId);t&&(e.updatedBy=t)}return e}catch(t){return this.loggingService.catch("Error in LiveStateUtilsService mergeLiveStateCustomWithUser:",t),e}}formatLiveStateCustomData(e){try{return this.usersService.userDataProviderAvailable()&&e?.updatedBy&&(e.updatedBy={userId:e.updatedBy.userId}),e}catch(t){return this.loggingService.catch("Error in LiveStateUtilsService formatLiveStateCustomData:",t),e}}getUserIdsToResolveFromLiveStateCustoms(e){try{let t=new Set;for(let r of e)r?.updatedBy?.userId&&t.add(r?.updatedBy?.userId);return Array.from(t)}catch(t){return this.loggingService.catch("Error in LiveStateUtilsService getUserIdsToResolveFromLiveStateCustoms:",t),[]}}getUserIdsToResolveFromLiveStates(e){try{let t=new Set;return e?.default?.singleEditorMode?.editor?.userId&&t.add(e?.default?.singleEditorMode?.editor?.userId),Array.from(t)}catch(t){return this.loggingService.catch("Error in LiveStateUtilsService getUserIdsToResolveFromLiveStates:",t),[]}}mergeLiveStateWithUser(e){try{if(e?.default?.singleEditorMode?.editor?.userId){let t=this.usersService.getUserById(e?.default?.singleEditorMode?.editor?.userId);t&&(e.default.singleEditorMode.editor=t)}if(e?.default?.singleEditorMode?.requestEditorAccess?.user?.userId){let t=this.usersService.getUserById(e?.default?.singleEditorMode?.requestEditorAccess?.user?.userId);t&&(e.default.singleEditorMode.requestEditorAccess.user=t)}return e}catch(t){return this.loggingService.catch("Error in LiveStateUtilsService mergeLiveStateWithUser:",t),e}}mergeSingleEditorLiveStateDataWithUser(e){try{if(e?.editor?.userId){let t=this.usersService.getUserById(e?.editor?.userId);t&&(e.editor=t)}if(e?.requestEditorAccess?.user?.userId){let t=this.usersService.getUserById(e?.requestEditorAccess?.user?.userId);t&&(e.requestEditorAccess.user=t)}return e}catch(t){return this.loggingService.catch("Error in LiveStateUtilsService mergeSingleEditorLiveStateDataWithUser:",t),e}}resolveAndMergeSingleEditorLiveStateDataWithUser(e){return Q(this,null,function*(){try{let t=this.getUserIdsToResolveFromLiveStates({default:{singleEditorMode:e}});return t.length?(yield this.usersService.resolveUsers({userIds:t}),this.mergeSingleEditorLiveStateDataWithUser(e)):e}catch(t){return this.loggingService.catch("Error in LiveStateUtilsService resolveAndMergeSingleEditorLiveStateDataWithUser:",t),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(t){return this.loggingService.catch("Error in LiveStateUtilsService formatLiveStateSingleEditorModeData:",t),e}}mergeLiveStateCustomsWithUsers(e){try{for(let t of e)if(t?.updatedBy?.userId){let r=this.usersService.getUserById(t?.updatedBy?.userId);r&&(t.updatedBy=r)}return e}catch(t){return this.loggingService.catch("Error in mergeLiveStateCustomsWithUsers:",t),e}}};o.\u0275fac=function(t){return new(t||o)(ee(y),ee(Vn))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var Uce=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.usersService=t}getUserIdsToResolveFromMultiThreads(e){try{let t=new Set;for(let r of e)r?.from?.userId&&t.add(r?.from?.userId);return Array.from(t)}catch(t){return this.loggingService.catch("Error in MultiThreadUtilsService getUserIdsToResolveFromMultiThreads:",t),[]}}mergeMultiThreadWithUser(e){try{if(e?.from?.userId){let t=this.usersService.getUserById(e?.from?.userId);t&&(e.from=t)}return e}catch(t){return this.loggingService.catch("Error in MultiThreadUtilsService mergeMultiThreadWithUser:",t),e}}formatMultiThreadData(e){try{return this.usersService.userDataProviderAvailable()&&(e?.from?.userId&&(e.from={userId:e.from.userId}),e?.commentAnnotationsMap&&(e.commentAnnotationsMap=null)),e}catch(t){return this.loggingService.catch("Error in MultiThreadUtilsService formatMultiThreadData:",t),e}}};o.\u0275fac=function(t){return new(t||o)(ee(y),ee(Vn))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var v0=(()=>{let o=class o{constructor(e,t,r){this.authService=e,this.loggingService=t,this.usersService=r}getUserIdsToResolveFromRecorders(e){try{let t=new Set;for(let r of e)r?.from?.userId&&t.add(r?.from?.userId),r?.transcription?.from?.userId&&t.add(r?.transcription?.from?.userId);return Array.from(t)}catch(t){return this.loggingService.catch("Error in RecorderUtilsService getUserIdsToResolveFromRecorders:",t),[]}}mergeRecorderWithUser(e){try{if(e?.from?.userId){let t=this.usersService.getUserById(e?.from?.userId);t&&(e.from=t)}if(e?.transcription?.from?.userId){let t=this.usersService.getUserById(e?.transcription?.from?.userId);t&&(e.transcription.from=t)}return e}catch(t){return this.loggingService.catch("Error in RecorderUtilsService mergeRecorderWithUser:",t),e}}formatRecorderData(e,t){try{return e.transcription=e?.transcription?T(I({},e.transcription),{lastUpdated:t}):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(t){return this.loggingService.catch("Error in RecorderUtilsService formatRecorderDataForWhisperTranscription:",t),e}}encryptRecorderAnnotation(e){return Q(this,null,function*(){try{return yield Gp(e,this.authService.getUser()?.userId??"")}catch(t){this.loggingService.catch("Error in RecorderUtilsService encryptRecorderAnnotation:",t);return}})}};o.\u0275fac=function(t){return new(t||o)(ee(Ve),ee(y),ee(Vn))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var Rk=(()=>{let o=class o{constructor(e,t,r,a,s,c){this.commentUtilsService=e,this.recorderUtilsService=t,this.loggingService=r,this.usersService=a,this.authService=s,this.commentAnnotationsResolverService=c}getUserIdsToResolveFromNotifications(e){try{let t=new Set;for(let r of e){let{notification:a}=r;switch(a?.actionUser?.userId&&t.add(a?.actionUser?.userId),a?.displayHeadlineMessageTemplateData?.actionUser?.userId&&t.add(a?.displayHeadlineMessageTemplateData?.actionUser?.userId),a?.displayHeadlineMessageTemplateData?.recipientUser?.userId&&t.add(a?.displayHeadlineMessageTemplateData?.recipientUser?.userId),a?.notificationSource){case"comment":if(a?.notificationSourceData){let s=this.commentUtilsService.getUserIdsToResolveFromComments([a?.notificationSourceData]);for(let c of s)t.add(c)}break}}return Array.from(t)}catch(t){return this.loggingService.catch("Error in ReactionUtilsService getUserIdsToResolveFromRecorders:",t),[]}}mergeStrippedDataWithNotification(e){try{if(this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: mergeStrippedDataWithNotification","color: green;"),!this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())return e;let t=this.commentAnnotationsResolverService.getAnnotationById(e?.notification?.targetAnnotationId),r=e?.raw?.targetAnnotationData?.commentId,a=t?.comments?.[r]?.commentText,s=t?.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(t){return this.loggingService.catch("Error in NotificationUtilsService mergeStrippedDataWithNotification:",t),e}}mergeLocationWithNotification(e,t){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=t?.[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:t}=e;if(t?.actionUser?.userId){let r=this.usersService.getUserById(t?.actionUser?.userId);r&&(t.actionUser=r)}if(t?.displayHeadlineMessageTemplateData?.actionUser?.userId){let r=this.usersService.getUserById(t?.displayHeadlineMessageTemplateData?.actionUser?.userId);r&&(t.displayHeadlineMessageTemplateData.actionUser=r)}if(t?.displayHeadlineMessageTemplateData?.recipientUser?.userId){let r=this.usersService.getUserById(t?.displayHeadlineMessageTemplateData?.recipientUser?.userId);r&&(t.displayHeadlineMessageTemplateData.recipientUser=r)}switch(t?.notificationSource){case"comment":t?.notificationSourceData&&this.commentUtilsService.mergeCommentWithUser(t?.notificationSourceData);break}return e}catch(t){return this.loggingService.catch("Error in NotificationUtilsService mergeNotificationWithUser:",t),e}}formatNotification(e,t){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,t);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 t=[];return Object.values(e).forEach(r=>{r?.notification?.targetAnnotationId&&r?.raw?.notificationSource==="comment"&&t.push(r.notification.targetAnnotationId)}),t}catch(t){return this.loggingService.catch("Error in NotificationUtilsService getTargetAnnotationIdsFromNotifications:",t),[]}}handleNotificationEncryption(t){return Q(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 Gp(e,r)}catch(r){return this.loggingService.catch("Error in NotificationUtilsService handleNotificationEncryption:",r),e}})}};o.\u0275fac=function(t){return new(t||o)(ee(f0),ee(v0),ee(y),ee(Vn),ee(Ve),ee(Rs))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var $ce=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.usersService=t}getUserIdsToResolveFromPresenceUsers(e){try{let t=new Set;for(let r of e)r?.userId&&t.add(r?.userId);return Array.from(t)}catch(t){return this.loggingService.catch("Error in PresenceUtilsService getUserIdsToResolveFromPresenceUsers:",t),[]}}mergePresenceUserWithUser(e){try{if(this.usersService.userDataProviderAvailable()&&e?.userId){let t=this.usersService.getUserById(e?.userId);t&&(e=I(I({},e),t))}return e}catch(t){return this.loggingService.catch("Error in PresenceUtilsService mergePresenceUserWithUser:",t),e}}formatPresenceUserData(e){try{if(this.usersService.userDataProviderAvailable()){let t=["userId","onlineStatus","userSnippylyId","color","textColor","timestamp","type","selections","documentParamsId","documentParams","locationId","location","isReadOnly","isAnonymous","pageInfo"];Object.keys(e).forEach(r=>{t.includes(r)||(e[r]=null)})}return e}catch(t){return this.loggingService.catch("Error in PresenceUtilsService formatPresenceUserData:",t),e}}};o.\u0275fac=function(t){return new(t||o)(ee(y),ee(Vn))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var Hce=(()=>{let o=class o{constructor(e,t,r,a,s,c){this.loggingService=e,this.usersService=t,this.authService=r,this.functions=a,this.configService=s,this.reactionAnnotationsResolverService=c}getUserIdsToResolveFromReactions(e){try{let t=new Set;for(let r of e)if(r?.from?.userId&&t.add(r?.from?.userId),r?.reactions?.length)for(let a of r?.reactions)a?.from?.userId&&t.add(a?.from?.userId);return Array.from(t)}catch(t){return this.loggingService.catch("Error in ReactionUtilsService getUserIdsToResolveFromRecorders:",t),[]}}handleReactionEncryption(a){return Q(this,arguments,function*({data:e,firestorePath:t,eventType:r}){try{let s=WP(this.authService.getFirebaseConfig()?.firebaseOptions),c=br(this.functions,Er({url:oi.cloudFunction?.[s]?.setEncryptedData,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:20*60*1e3}),p=og.getFirestoreProdDbName(this.configService.getApiKey()??"",this.authService.getFirebaseConfig()?.firebaseOptions),u=this.authService.getUser()?.userId??"",C={path:t??"",data:e??{},dbId:p??"",feature:"reaction",eventType:r??"PATCH",sdkVersion:ia()},E=yield Gp(C,u);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 t=this.usersService.getUserById(e?.from?.userId);t&&(e.from=t)}if(e?.reactions?.length){for(let t of e?.reactions)if(t?.from?.userId){let r=this.usersService.getUserById(t?.from?.userId);r&&(t.from=r)}}}return e}catch(t){return this.loggingService.catch("Error in ReactionUtilsService mergeReactionWithUser:",t),e}}formatReactionData(e){try{return this.usersService.userDataProviderAvailable()&&e?.from?.userId&&(e.from={userId:e.from.userId}),e.reactions=e?.reactions?.map(t=>(this.usersService.userDataProviderAvailable()&&t?.from?.userId&&(t.from={userId:t.from.userId}),t)),e}catch(t){return this.loggingService.catch("Error in ReactionUtilsService formatReactionData:",t),e}}isReactionDataChanged(e,t){try{this.loggingService.log("%c[WB] Calling ReactionUtilsService FUNCTION: isReactionDataChanged","color: green;");let r=this.reactionAnnotationsResolverService.getReactionAnnotationById(t);return r?!wi(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 t={};if(e&&e.annotationId){let r=e.annotationId;if(t[r]=I({annotationId:r,metadata:Rv(e.metadata??{}),icon:e.icon},e?.from&&{from:e?.from}),!this.isReactionDataChanged(t[r],r))return{strippedData:null,originalData:e};delete e?.icon,e.isReactionResolverUsed=!0}return{strippedData:t,originalData:e}}catch(t){return this.loggingService.catch("Error in ReactionUtilsService stripReactionAnnotationData:",t),{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 t=this.reactionAnnotationsResolverService.getReactionAnnotationById(e?.annotationId);return t&&t.icon&&(e.icon=t.icon),e}catch(t){return this.loggingService.catch("Error in ReactionUtilsService mergeStrippedDataWithReactionAnnotations:",t),e}}};o.\u0275fac=function(t){return new(t||o)(ee(y),ee(Vn),ee(Ve),ee(Wo),ee(Ft),ee(jd))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var zce=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.usersService=t}getUserIdsToResolveFromSelections(e){try{let t=new Set;for(let r of e)r?.user?.userId&&t.add(r.user.userId);return Array.from(t)}catch(t){return this.loggingService.catch("Error in SelectionUtilsService getUserIdsToResolveFromSelections:",t),[]}}mergeSelectionWithUser(e){try{if(e?.user?.userId){let t=this.usersService.getUserById(e?.user?.userId);t&&(e.user=t)}return e}catch(t){return this.loggingService.catch("Error in SelectionUtilsService mergeSelectionWithUser:",t),e}}formatSelectionData(e){try{return this.usersService.userDataProviderAvailable()&&e?.user?.userId&&(e.user={userId:e.user.userId}),e}catch(t){return this.loggingService.catch("Error in SelectionUtilsService formatSelectionData:",t),e}}};o.\u0275fac=function(t){return new(t||o)(ee(y),ee(Vn))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var Gce=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.usersService=t}getUserIdsToResolveFromTags(e){try{let t=new Set;for(let r of e)if(r?.from?.userId&&t.add(r.from.userId),r?.to?.length)for(let a of r.to)a?.userId&&t.add(a.userId);return Array.from(t)}catch(t){return this.loggingService.catch("Error in TagUtilsService getUserIdsToResolveFromTags:",t),[]}}mergeTagWithUser(e){try{if(e?.from?.userId){let t=this.usersService.getUserById(e?.from?.userId);t&&(e.from=t)}return e?.to?.length&&(e.to=e.to.map(t=>{if(t?.userId){let r=this.usersService.getUserById(t?.userId);r&&(t=r)}return t})),e}catch(t){return this.loggingService.catch("Error in TagUtilsService mergeTagWithUser:",t),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(t=>(t?.userId&&(t={userId:t.userId}),t)))),e}catch(t){return this.loggingService.catch("Error in TagUtilsService formatTagData:",t),e}}};o.\u0275fac=function(t){return new(t||o)(ee(y),ee(Vn))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var ag=(()=>{let o=class o{constructor(e,t,r,a,s,c,p,u,C,E,D,L,z,W,J,ue,ye,Ae,He){this.areaUtilsService=e,this.arrowUtilsService=t,this.commentUtilsService=r,this.contactUtilsService=a,this.cursorUtilsService=s,this.huddleUtilsService=c,this.liveStateUtilsService=p,this.loggingService=u,this.multiThreadUtilsService=C,this.notificationUtilsService=E,this.presenceUtilsService=D,this.reactionUtilsService=L,this.recorderUtilsService=z,this.selectionUtilsService=W,this.tagUtilsService=J,this.usersService=ue,this.docService=ye,this.commentAnnotationsResolverService=Ae,this.reactionAnnotationsResolverService=He}getErrorForGetRequests({feature:e,error:t}){try{switch(e){case"organizationMetadata":case"documentMetadata":case"folderMetadata":return(t?.message??"")?.includes("Missing or insufficient permissions.")?{errorCode:"PERMISSION_DENIED"}:null;default:return null}}catch(r){return this.loggingService.catch("Error in CommonDbUtilsService getErrorForGetRequests:",r),null}}getFirestorePath({feature:e,properties:t,documentPaths:r,apiKey:a}){try{if(!a)return;let{documentId:s,organizationId:c,folderId:p}=t;c||(c=r?.organizationId);let u=new Ok({apiKey:a,documentId:s?`${s}`:"",organizationId:c?`${c}`:"",veltFolderId:p?`${p}`:void 0});switch(e){case"userConfig":return t?.userId&&t?.documentId&&u?.userConfig?`${u?.userConfig}/${t?.userId}/${j.FIREBASE_PARTIAL_PATH_DOCUMENT_CONFIGURATIONS}/${t?.documentId}`:void 0;case"allPermissionsUsers":return u?.permissionsUsers?`${u?.permissionsUsers}`:void 0;case"comment":return t?.documentId&&t?.id&&u?.comment?`${u?.comment}/${t?.id}`:void 0;case"allComments":return t?.documentId&&u?.comment?`${u?.comment}`:void 0;case"multiThread":return t?.documentId&&t?.id&&u?.multiThread?`${u?.multiThread}/${t?.id}`:void 0;case"allMultiThreads":return t?.documentId&&u?.multiThread?`${u?.multiThread}`:void 0;case"crdt":return t?.documentId&&u?.crdt&&t?.id?`${u?.crdt}/${t?.id}`:void 0;case"allLastNotificationTimestamp":return u?.lastNotificationTimestamp?`${u?.lastNotificationTimestamp}`:void 0;case"lastNotificationTimestamp":return t?.id&&u?.lastNotificationTimestamp?`${u?.lastNotificationTimestamp}/${t?.id}`:void 0;case"area":return t?.documentId&&t?.id&&u?.area?`${u?.area}/${t?.id}`:void 0;case"allAreas":return t?.documentId&&u?.area?`${u?.area}`:void 0;case"allDocuments":return u?.document?`${u?.document}`:void 0;case"allLocations":return u?.location?`${u?.location}`:void 0;case"allFolders":return u?.folder?`${u?.folder}`:void 0;case"folder":return u?.folder&&t.folderId?`${u?.folder}/${t.folderId}`:void 0;case"documentUserAccess":return t?.documentId&&t?.id&&u?.documentUsers?`${u?.documentUsers}/${t?.id}`:void 0;case"reaction":return t?.documentId&&t?.id&&u?.reaction?`${u?.reaction}/${t?.id}`:void 0;case"allReactions":return t?.documentId&&u?.reaction?`${u?.reaction}`:void 0;case"recorder":return t?.documentId&&t?.id&&u?.recorder?`${u?.recorder}/${t?.id}`:void 0;case"allRecorders":return t?.documentId&&u?.recorder?`${u?.recorder}`:void 0;case"documentAccessType":return t?.documentId&&u?.document?`${u?.document}/${t?.documentId}`:void 0;case"organizationMetadata":return u?.organization?`${u?.organization}`:void 0;case"documentIam":case"documentMetadata":return t?.documentId&&u?.document?`${u?.document}/${t?.documentId}`:void 0;case"folderMetadata":return t?.folderId&&u?.folder?`${u?.folder}/${t?.folderId}`:void 0;case"locationMetadata":return t?.documentId&&u?.location&&t?.id?`${u?.location}/${t?.id}`:void 0;case"documentUser":return t?.documentId&&t?.id&&u?.documentUsers?`${u?.documentUsers}/${t?.id}`:void 0;case"allDocumentUsers":return u?.users?`${u?.users}`:void 0;case"allFolderUsers":return u?.users?`${u?.users}`:void 0;case"allOrganizationGroups":return u?.organizationGroups?`${u?.organizationGroups}`:void 0;case"allOrganizationUsers":return u?.users?`${u?.users}`:void 0;case"notificationViewsTimestamp":return t?.documentId&&t?.id&&u?.notificationViews?`${u?.notificationViews}/${t?.id}`:void 0;case"allDocumentViews":return t?.documentId&&u?.documentViews?`${u?.documentViews}`:void 0;case"documentViews":case"documentMetadataViews":case"documentDayViews":case"documentUsersViews":return t?.documentId&&t?.id&&u?.documentViews?`${u?.documentViews}/${t?.id}`:void 0;case"locationDayViews":case"locationUsersViews":case"locationViews":case"locationMetadataViews":case"location":return t?.documentId&&t?.id&&u?.locationViews?`${u?.locationViews}/${t?.id}`:void 0;case"allLocationViews":return t?.documentId&&u?.locationViews?`${u?.locationViews}`:void 0;case"allDocNotifications":return t?.documentId&&u?.docNotification?`${u?.docNotification}`:void 0;case"docNotificationViews":case"docNotification":return t?.documentId&&t?.id&&u?.docNotification?`${u?.docNotification}/${t?.id}`:void 0;case"userNotificationViews":case"userNotification":return t?.userId&&t?.id&&u?.notificationUsers?`${u?.notificationUsers}/${t?.userId}/${j.FIREBASE_PARTIAL_PATH_USER_NOTIFICATION}/${t?.id}`:void 0;case"allDocNotifications":return t?.documentId&&u?.docNotification?`${u?.docNotification}`:void 0;case"allUserNotifications":return t?.userId&&u?.notificationUsers?`${u?.notificationUsers}/${t?.userId}/${j.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 j.FIREBASE_PARTIAL_PATH_COMMENT;case"allDocuments":return j.FIREBASE_PARTIAL_PATH_DOCS;case"allLocations":return j.FIREBASE_PARTIAL_PATH_LOCATION;case"allMultiThreads":return j.FIREBASE_PARTIAL_PATH_MULTI_THREAD;case"allAreas":return j.FIREBASE_PARTIAL_PATH_AREA;case"allReactions":return j.FIREBASE_PARTIAL_PATH_REACTION;case"allRecorders":return j.FIREBASE_PARTIAL_PATH_RECORDER;case"allDocumentViews":return j.FIREBASE_PARTIAL_PATH_DOCUMENT_VIEWS;case"allLocationViews":return j.FIREBASE_PARTIAL_PATH_LOCATION_VIEWS;case"allDocumentUsers":return j.FIREBASE_PARTIAL_PATH_DOCUMENT_USERS;case"allFolderUsers":return j.FIREBASE_PARTIAL_PATH_FOLDER_USERS;default:throw new Error(`Unknown feature: ${e}`)}}catch(t){this.loggingService.catch("Error in CommonDbUtilsService getFirestoreCollectionGroupPath:",t);return}}getDocumentPath({feature:e,properties:t,defaultDocumentPaths:r,apiKey:a,useFirestore:s}){try{if(!a)return;let{documentId:c,organizationId:p}=t;p||(p=r?.organizationId);let u=new Ud({apiKey:a,documentId:c?`${c}`:"",organizationId:p?`${p}`:""});switch(e){case"userConfig":return t?.userId&&t?.documentId&&u?.userConfig?`${u?.userConfig}/${t?.userId}/${j.FIREBASE_PARTIAL_PATH_DOCUMENT_CONFIGURATIONS}/${t?.documentId}`:void 0;case"allComments":return!s&&t?.documentId&&u?.comment?`${u?.comment}`:void 0;case"allGlobalContacts":return t?.documentId&&u?.globalContacts?`${u?.globalContacts}`:void 0;case"globalContacts":return t?.documentId&&t?.userId&&u?.globalContacts?`${u?.globalContacts}${t?.userId}`:void 0;case"groupContacts":return t?.documentId&&t?.groupId&&u?.groupContacts?`${u?.groupContacts}${t?.groupId}`:void 0;case"groupContactsUser":return t?.documentId&&t?.groupId&&t?.userId&&u?.groupContacts?`${u?.groupContacts}${t?.groupId}/${t?.userId}`:void 0;case"allLoginContacts":return t?.documentId&&t?.userId&&u?.logins?`${u?.logins}${t?.userId}/contacts`:void 0;case"allLogins":return t?.documentId&&u?.logins?`${u?.logins}`:void 0;case"logins":return t?.documentId&&t?.userId&&u?.logins?`${u?.logins}${t?.userId}`:void 0;case"customerMetadata":return u?.customerMetadata?`${u?.customerMetadata}`:void 0;case"allArrows":return t?.documentId&&u?.arrow?`${u?.arrow}`:void 0;case"arrow":return t?.documentId&&u?.arrow&&t.id?`${u?.arrow}${t.id}`:void 0;case"allCursors":return t?.documentId&&u?.cursor?`${u?.cursor}`:void 0;case"cursor":return t?.documentId&&u?.cursor&&t.id?`${u?.cursor}${t.id}`:void 0;case"flockUser":return t?.documentId&&u?.flock&&t.id?`${u?.flock}users/${t.id}`:void 0;case"flockSession":return t?.documentId&&u?.flock&&t.id?`${u?.flock}sessions/${t.id}`:void 0;case"allHuddleAttendees":return t?.documentId&&u?.huddle?`${u?.huddle}attendees`:void 0;case"huddleAttendee":return t?.documentId&&u?.huddle&&t.id?`${u?.huddle}attendees/${t.id}`:void 0;case"huddleAttendeeState":return t?.documentId&&u?.huddle&&t.id?`${u?.huddle}attendees/${t.id}/state`:void 0;case"allHuddleInvitees":return t?.documentId&&u?.huddle?`${u?.huddle}invitees`:void 0;case"huddleConnection":return t?.documentId&&u?.huddle&&t.id?`${u?.huddle}connections/${t.id}`:void 0;case"huddleIceCandidate":return t?.documentId&&u?.huddle&&t.id?`${u?.huddle}iceCandidates/${t.id}`:void 0;case"allHuddleIceCandidates":return t?.documentId&&u?.huddle?`${u?.huddle}iceCandidates`:void 0;case"allHuddleMessages":return t?.documentId&&u?.huddle?`${u?.huddle}messages`:void 0;case"huddleMessage":return t?.documentId&&u?.huddle&&t.id?`${u?.huddle}messages/${t.id}`:void 0;case"allLiveStates":return t?.documentId&&u?.liveState?`${u?.liveState}`:void 0;case"allLiveStateCustoms":return t?.documentId&&u?.liveState?`${u?.liveState}custom`:void 0;case"liveStateCustom":return t?.documentId&&u?.liveState&&t?.id?`${u?.liveState}custom/${t.id}`:void 0;case"liveStateSingleEditorMode":return t?.documentId&&u?.liveStateSingleEditorMode?`${u?.liveStateSingleEditorMode}`:void 0;case"liveStateAutoSyncStateCurrent":return t?.documentId&&u?.liveState?`${u?.liveState}default/autoSyncState/current`:void 0;case"liveStateAutoSyncStateHistoryId":return t?.documentId&&u?.liveState&&t?.id?`${u?.liveState}default/autoSyncState/history/${t.id}`:void 0;case"presence":return t?.documentId&&u?.presence&&t?.userId?`${u?.presence}${t?.userId}`:void 0;case"allPresence":return t?.documentId&&u?.presence?`${u?.presence}`:void 0;case"workspaceIam":return u?.workspaceIam?`${u?.workspaceIam}`:void 0;case"selection":return t?.documentId&&u?.selection&&t?.userId?`${u?.selection}${t?.userId}`:void 0;case"allSelections":return t?.documentId&&u?.selection?`${u?.selection}`:void 0;case"syncVideoPlayer":return t?.documentId&&u?.syncVideoPlayer?`${u?.syncVideoPlayer}`:void 0;case"allTags":return t?.documentId&&u?.tag?`${u?.tag}`:void 0;case"tag":return t?.documentId&&u?.tag&&t?.id?`${u?.tag}${t?.id}`:void 0;case"userContactUs":return t?.documentId&&u?.userContactUs?`${u?.userContactUs}`:void 0;case"userFeedback":return t?.documentId&&u?.userFeedback?`${u?.userFeedback}`:void 0;case"userReportBug":return t?.documentId&&u?.userReportBugs?`${u?.userReportBugs}`:void 0;case"comment":return!s&&t?.documentId&&t?.id&&u?.comment?`${u?.comment}${t?.id}`:void 0;case"allMultiThreads":return!s&&t?.documentId&&u?.multiThread?`${u?.multiThread}`:void 0;case"crdt":return!s&&t?.documentId&&u?.crdt?`${u?.crdt}`:void 0;case"crdtData":return t?.documentId&&u?.crdt&&t?.id?`${u?.crdt}/${t?.id}/data`:void 0;case"crdtSyncState":return t?.documentId&&u?.crdt&&t?.id?`${u?.crdt}/${t?.id}/sync/state`:void 0;case"crdtSyncPresence":return t?.documentId&&t.userId&&u?.crdt&&t?.id?`${u?.crdt}/${t?.id}/sync/presence/${t.userId}`:void 0;case"allCrdtSyncPresence":return t?.documentId&&u?.crdt&&t?.id?`${u?.crdt}/${t?.id}/sync/presence`:void 0;case"crdtPresence":return t?.documentId&&t.userId&&u?.crdt&&t?.id?`${u?.crdt}/${t?.id}/presence/${t.userId}`:void 0;case"allCrdtPresence":return t?.documentId&&u?.crdt&&t?.id?`${u?.crdt}/${t?.id}/presence`:void 0;case"crdtVersion":return t?.documentId&&u?.crdt&&t?.id&&t?.versionId?`${u?.crdt}/${t?.id}/versions/${t?.versionId}`:void 0;case"crdtVersions":return t?.documentId&&u?.crdt&&t?.id?`${u?.crdt}/${t?.id}/versions`:void 0;case"multiThread":return!s&&t?.documentId&&t?.id&&u?.multiThread?`${u?.multiThread}${t?.id}`:void 0;case"allLastNotificationTimestamp":return!s&&u?.organizationNotificationsLastNotificationTimestamp?`${u?.organizationNotificationsLastNotificationTimestamp}`:void 0;case"lastNotificationTimestamp":return!s&&t?.id&&u?.organizationNotificationsLastNotificationTimestamp?`${u?.organizationNotificationsLastNotificationTimestamp}${t?.id}`:void 0;case"documentIam":return!s&&t?.documentId&&u?.documentIam?`${u?.documentIam}`:void 0;case"documentMetadata":return!s&&t?.documentId&&u?.metadata?`${u?.metadata}`:void 0;case"allDocuments":return!s&&u?.docs&&t?.documentId?`${u?.docs}/${t?.documentId}/${j.FIREBASE_PARTIAL_PATH_METADATA}`:void 0;case"allAreas":return!s&&t?.documentId&&u?.area?`${u?.area}`:void 0;case"area":return!s&&t?.id&&u?.area?`${u?.area}${t?.id}`:void 0;case"folder":return!s&&t?.folderId&&u?.folder?`${u?.folder}${t?.folderId}`:void 0;case"documentUserAccess":return!s&&t?.id&&u?.documentIam?`${u?.documentIam}users/${t?.id}`:void 0;case"documentUser":return!s&&t?.documentId&&t?.id&&u?.documentIam?`${u?.documentIam}users/${t?.id}`:void 0;case"allDocumentUsers":return!s&&t?.documentId&&u?.documentIam?`${u?.documentIam}users/`:void 0;case"allOrganizationGroups":return!s&&u?.organizationGroups?`${u?.organizationGroups}`:void 0;case"allOrganizationUsers":return!s&&u?.organizationIam?`${u?.organizationIam}users/`:void 0;case"reaction":return!s&&t?.id&&u?.reaction?`${u?.reaction}${t?.id}`:void 0;case"allReactions":return!s&&t?.documentId&&u?.reaction?`${u?.reaction}`:void 0;case"recorder":return!s&&t?.documentId&&t?.id&&u?.recorder?`${u?.recorder}${t?.id}`:void 0;case"allRecorders":return!s&&t?.documentId&&u?.recorder?`${u?.recorder}`:void 0;case"organizationMetadata":return!s&&u?.organizationMetadata?`${u?.organizationMetadata}`:void 0;case"documentAccessType":return!s&&u?.documentIam?`${u?.documentIam}`:void 0;case"documentIam":return!s&&u?.documentIam?`${u?.documentIam}`:void 0;case"documentMetadata":return!s&&t?.documentId&&u?.metadata?`${u?.metadata}`:void 0;case"allDocumentViews":return!s&&t?.documentId&&u?.views?`${u?.views}documentViews/`:void 0;case"documentViews":return!s&&t?.documentId&&t?.id&&u?.views?`${u?.views}documentViews/${t?.id}`:void 0;case"allLocationViews":return!s&&t?.documentId&&u?.views?`${u?.views}locationViews/`:void 0;case"notificationViewsTimestamp":return!s&&t?.id&&t?.user&&u?.views?`${u?.views}notification/${t?.id}/views/${t?.user}`:void 0;case"documentUsersViews":return!s&&t?.id&&t?.user&&t?.date&&u?.views?`${u?.views}documentViews/${t?.id}/users/${t?.user}/${t?.date}`:void 0;case"documentMetadataViews":return!s&&t?.id&&u?.views?`${u?.views}documentViews/${t?.id}/metadata`:void 0;case"documentDayViews":return!s&&t?.id&&t?.date&&t?.user&&u?.views?`${u?.views}documentViews/${t?.id}/day/${t?.date}/${t?.user}`:void 0;case"locationViews":return!s&&t?.id&&u?.views?`${u?.views}locationViews/${t?.id}/location`:void 0;case"location":return!s&&t?.id&&u?.views?`${u?.views}locationViews/${t?.id}`:void 0;case"locationUsersViews":return!s&&t?.id&&t?.user&&t?.date&&u?.views?`${u?.views}locationViews/${t?.id}/users/${t?.user}/${t?.date}`:void 0;case"locationMetadataViews":return!s&&t?.id&&u?.views?`${u?.views}locationViews/${t?.id}/metadata`:void 0;case"locationDayViews":return!s&&t?.id&&t?.date&&t?.user&&u?.views?`${u?.views}locationViews/${t?.id}/day/${t?.date}/${t?.user}`:void 0;case"docNotificationViews":case"docNotification":return t?.documentId&&t?.id&&u?.organizationNotificationsWithDocumentId?`${u?.organizationNotificationsWithDocumentId}${t?.id}`:void 0;case"allDocNotifications":return t?.documentId&&u?.organizationNotificationsWithDocumentId?`${u?.organizationNotificationsWithDocumentId}`:void 0;case"allUserNotifications":return t?.userId&&u?.organizationNotificationsUsers?`${u?.organizationNotificationsUsers}${t?.userId}`:void 0;case"userNotificationViews":case"userNotification":return t?.userId&&t?.id&&u?.organizationNotificationsUsers?`${u?.organizationNotificationsUsers}${t?.userId}/${t?.id}`:void 0;case"locationMetadata":return;case"allLocations":return;case"folderMetadata":return;case"allPermissionsUsers":return;default:throw new Error(`Unknown feature: ${e}`)}}catch(c){this.loggingService.catch("Error in CommonDbUtilsService getDocumentPath:",c);return}}resolveAnnotations(r){return Q(this,arguments,function*({data:e,feature:t}){try{if(e&&e?.length>0)switch(t){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: ${t}`,a)}})}formatResponse(c){return Q(this,arguments,function*({feature:e,data:t,shouldAwait:r=!1,forceResolve:a=!1,shouldCommentAnnotationsResolverAwait:s=!1}){try{if(this.usersService.userDataProviderAvailable()){let p=[];switch(e){case"allAreas":{t&&typeof t=="object"&&!Array.isArray(t)&&(p=this.areaUtilsService.getUserIdsToResolveFromAreaAnnotations(Object.values(t)));break}case"allArrows":{t&&typeof t=="object"&&!Array.isArray(t)&&(p=this.arrowUtilsService.getUserIdsToResolveFromArrowAnnotations(Object.values(t)));break}case"allCursors":{t&&typeof t=="object"&&!Array.isArray(t)&&(p=this.cursorUtilsService.getUserIdsToResolveFromCursorUsers(Object.values(t)));break}case"allComments":{t&&typeof t=="object"&&!Array.isArray(t)&&(p=this.commentUtilsService.getUserIdsToResolveFromComments(Object.values(t)));break}case"allDocumentUsers":{t&&typeof t=="object"&&!Array.isArray(t)&&(p=this.contactUtilsService.getUserIdsToResolveFromUserIamData(Object.values(t)));break}case"allFolderUsers":{t&&typeof t=="object"&&!Array.isArray(t)&&(p=this.contactUtilsService.getUserIdsToResolveFromUserIamData(Object.values(t)));break}case"allOrganizationUsers":{t&&typeof t=="object"&&!Array.isArray(t)&&(p=this.contactUtilsService.getUserIdsToResolveFromUserIamData(Object.values(t)));break}case"allMultiThreads":{t&&typeof t=="object"&&!Array.isArray(t)&&(p=this.multiThreadUtilsService.getUserIdsToResolveFromMultiThreads(Object.values(t)));break}case"allDocNotifications":{t&&typeof t=="object"&&(p=this.notificationUtilsService.getUserIdsToResolveFromNotifications(Array.isArray(t)?t:Object.values(t)));break}case"allUserNotifications":{t&&typeof t=="object"&&!Array.isArray(t)&&(p=this.notificationUtilsService.getUserIdsToResolveFromNotifications(Object.values(t)));break}case"allPresence":{t&&typeof t=="object"&&!Array.isArray(t)&&(p=this.presenceUtilsService.getUserIdsToResolveFromPresenceUsers(Object.values(t)));break}case"allRecorders":{t&&typeof t=="object"&&!Array.isArray(t)&&(p=this.recorderUtilsService.getUserIdsToResolveFromRecorders(Object.values(t)));break}case"allReactions":{t&&typeof t=="object"&&!Array.isArray(t)&&(p=this.reactionUtilsService.getUserIdsToResolveFromReactions(Object.values(t)));break}case"allTags":{t&&typeof t=="object"&&!Array.isArray(t)&&(p=this.tagUtilsService.getUserIdsToResolveFromTags(Object.values(t)));break}case"allHuddleAttendees":{t&&typeof t=="object"&&!Array.isArray(t)&&(p=this.huddleUtilsService.getUserIdsToResolveFromHuddleAttendees(Object.values(t)));break}case"liveStateCustom":{t&&typeof t=="object"&&!Array.isArray(t)&&(p=this.liveStateUtilsService.getUserIdsToResolveFromLiveStateCustom(t));break}case"allLiveStateCustoms":{t&&typeof t=="object"&&!Array.isArray(t)&&(p=this.liveStateUtilsService.getUserIdsToResolveFromLiveStateCustoms(Object.values(t)));break}case"allLiveStates":{t&&typeof t=="object"&&(p=this.liveStateUtilsService.getUserIdsToResolveFromLiveStates(t));break}case"allSelections":{t&&typeof t=="object"&&!Array.isArray(t)&&(p=this.selectionUtilsService.getUserIdsToResolveFromSelections(Object.values(t)));break}default:p=[]}p?.length&&(r?yield this.usersService.resolveUsers({userIds:p,forceResolve:a,feature:e}):this.usersService.resolveUsers({userIds:p,forceResolve:a,feature:e}))}if(this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable()){let p=[];switch(e){case"allDocNotifications":{if(t&&typeof t=="object"){let u=this.notificationUtilsService.getTargetAnnotationIdsFromNotifications(t);p=[...p,...u],p=p.filter(C=>!this.commentAnnotationsResolverService.getCommentAnnotationById(C))}break}case"allUserNotifications":{if(t&&typeof t=="object"&&!Array.isArray(t)){let u=this.notificationUtilsService.getTargetAnnotationIdsFromNotifications(t);p=[...p,...u],p=p.filter(C=>!this.commentAnnotationsResolverService.getCommentAnnotationById(C))}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 t}catch(p){return this.loggingService.catch("Error in CommonDbUtilsService formatResponse:",p),t}})}mergeCommentAnnotationsWithData({data:e,feature:t}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeCommentAnnotationsWithData","color: green;"),this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())switch(t){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:t}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeReactionAnnotationsWithData","color: green;"),this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable())switch(t){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:t,locationMetadata:r}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeLocationMetadataWithData","color: green;"),r&&typeof r=="object"&&!Array.isArray(r))switch(t){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:t}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeUsersWithData","color: green;"),this.usersService.userDataProviderAvailable())switch(e){case"allAreas":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((r,[a,s])=>(r[a]=this.areaUtilsService.mergeAreaWithUser(s),r),{}):t;case"allArrows":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((r,[a,s])=>(r[a]=this.arrowUtilsService.mergeArrowWithUser(s),r),{}):t;case"allCursors":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((r,[a,s])=>(r[a]=this.cursorUtilsService.mergeCursorUserWithUser(s),r),{}):t;case"allComments":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((r,[a,s])=>(r[a]=this.commentUtilsService.mergeCommentWithUser(s),r),{}):t;case"allDocumentUsers":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((r,[a,s])=>(r[a]=this.contactUtilsService.mergeUserIamWithUser(s),r),{}):t;case"allFolderUsers":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((r,[a,s])=>(r[a]=this.contactUtilsService.mergeUserIamWithUser(s),r),{}):t;case"allOrganizationUsers":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((r,[a,s])=>(r[a]=this.contactUtilsService.mergeUserIamWithUser(s),r),{}):t;case"allMultiThreads":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((r,[a,s])=>(r[a]=this.multiThreadUtilsService.mergeMultiThreadWithUser(s),r),{}):t;case"allDocNotifications":return t&&typeof t=="object"?t?.map(r=>this.notificationUtilsService.mergeNotificationWithUser(r)):t;case"allUserNotifications":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((r,[a,s])=>(r[a]=this.notificationUtilsService.mergeNotificationWithUser(s),r),{}):t;case"allPresence":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((r,[a,s])=>(r[a]=this.presenceUtilsService.mergePresenceUserWithUser(s),r),{}):t;case"allRecorders":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((r,[a,s])=>(r[a]=this.recorderUtilsService.mergeRecorderWithUser(s),r),{}):t;case"allReactions":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((r,[a,s])=>(r[a]=this.reactionUtilsService.mergeReactionWithUser(s),r),{}):t;case"allTags":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((r,[a,s])=>(r[a]=this.tagUtilsService.mergeTagWithUser(s),r),{}):t;case"allHuddleAttendees":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((r,[a,s])=>(r[a]=this.huddleUtilsService.mergeHuddleAttendeeWithUser(s),r),{}):t;case"liveStateCustom":return t&&typeof t=="object"&&!Array.isArray(t)?this.liveStateUtilsService.mergeLiveStateCustomWithUser(t):t;case"allLiveStateCustoms":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((r,[a,s])=>(r[a]=this.liveStateUtilsService.mergeLiveStateCustomWithUser(s),r),{}):t;case"allLiveStates":return t&&typeof t=="object"?this.liveStateUtilsService.mergeLiveStateWithUser(t):t;case"allSelections":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((r,[a,s])=>(r[a]=this.selectionUtilsService.mergeSelectionWithUser(s),r),{}):t;default:return t}return t}catch(r){return this.loggingService.catch("Error in CommonDbUtilsService mergeUsersWithData:",r),t}}mergeCommentAnnotationsWithData$({data:e,feature:t}){try{return this.commentAnnotationsResolverService.getCommentAnnotationsById$().pipe(ce(()=>{let r=this.mergeCommentAnnotationsWithData({data:e?.data??{},feature:t}),a=this.mergeUsersWithData({feature:t,data:r??{}});return typeof a=="object"?{data:JSON.parse(JSON.stringify(a)),operation:e?.operation??null}:{data:a,operation:e?.operation??null}}),Et(mn))}catch(r){return this.loggingService.catch("Error in mergeCommentAnnotationsWithData:",r),se(e)}}mergeReactionAnnotationsWithData$({data:e,feature:t}){try{return this.reactionAnnotationsResolverService.getReactionAnnotationsById$().pipe(ce(()=>{let r=this.mergeReactionAnnotationsWithData({data:e?.data??{},feature:t}),a=this.mergeUsersWithData({feature:t,data:r??{}});return typeof a=="object"?{data:JSON.parse(JSON.stringify(a)),operation:e?.operation??null}:{data:a,operation:e?.operation??null}}),Et(mn))}catch(r){return this.loggingService.catch("Error in mergeReactionAnnotationsWithData:",r),se(e)}}mergeUsersWithData$({feature:e,data:t}){try{return this.usersService.getUserById$().pipe(ce(()=>{let r=this.mergeUsersWithData({feature:e,data:t?.data??{}});return typeof r=="object"?{data:JSON.parse(JSON.stringify(r)),operation:t?.operation??null}:{data:r,operation:t?.operation??null}}),Et(mn))}catch(r){return this.loggingService.catch(`Error in mergeUsersWithData for ${e}:`,r),se(t)}}mergeLocationMetadataWithData$({data:e,feature:t}){try{return this.docService.getLocationMetadata$().pipe(ce(r=>{let a=this.mergeLocationMetadataWithData({data:e?.data??{},feature:t,locationMetadata:r});return typeof a=="object"?{data:JSON.parse(JSON.stringify(a)),operation:e?.operation??null}:{data:a,operation:e?.operation??null}}),Et(mn))}catch(r){return this.loggingService.catch(`Error in mergeLocationMetadataWithData for ${t}:`,r),se(e)}}handleDataStripping({feature:e,data:t,actionType:r}){try{switch(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: handleDataStripping","color: green;"),e){case"comment":return this.commentUtilsService.stripCommentAnnotationData({data:t,actionType:r});case"reaction":return this.reactionUtilsService.stripReactionAnnotationData(t);default:return{originalData:t,strippedData:null}}}catch(a){return this.loggingService.catch("Error in CommonDbUtilsService handleDataStripping:",a),{originalData:t,strippedData:null}}}formatData({feature:e,data:t,properties:r,offset:a,isRealtimeDb:s}){try{this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: formatData","color: green;"),typeof t=="object"&&(t=JSON.parse(JSON.stringify(t)));let c=new Date().getTime()+a;switch(e){case"documentAccessType":return delete t?.users,{docIamConfig:t};case"organizationMetadata":case"documentMetadata":return s?t:{metadata:t};case"documentCommentMetadata":return t;case"cursor":return this.cursorUtilsService.formatCursorUserData(t);case"comment":return this.commentUtilsService.formatCommentData(t);case"area":return this.areaUtilsService.formatAreaData(t);case"arrow":return this.arrowUtilsService.formatArrowData(t);case"liveStateCustom":return this.liveStateUtilsService.formatLiveStateCustomData(t);case"liveStateSingleEditorMode":return this.liveStateUtilsService.formatLiveStateSingleEditorModeData(t);case"multiThread":return this.multiThreadUtilsService.formatMultiThreadData(t);case"reaction":return this.reactionUtilsService.formatReactionData(t);case"recorder":return this.recorderUtilsService.formatRecorderData(t,c);case"notificationViewsTimestamp":return{views:{[r.user??""]:t}};case"documentUsersViews":return s?t:{users:{[r.user??""]:{[r.date??""]:t}}};case"documentDayViews":return s?t:{day:{[r.date??""]:{[r.user??""]:t}}};case"documentMetadataViews":return s?t:{metadata:t};case"huddleMessage":return this.huddleUtilsService.formatHuddleMessageData(t);case"locationMetadataViews":return s?t:{metadata:t};case"locationUsersViews":return s?t:{users:{[r.user??""]:{[r.date??""]:t}}};case"locationDayViews":return s?t:{day:{[r.date??""]:{[r.user??""]:t}}};case"locationViews":return s?t:{location:t};case"docNotificationViews":return s?t:{views:t.views};case"userNotificationViews":return s?t:{views:t.views};case"presence":return this.presenceUtilsService.formatPresenceUserData(t);case"selection":return this.selectionUtilsService.formatSelectionData(t);case"tag":return this.tagUtilsService.formatTagData(t);default:return t}}catch(c){return this.loggingService.catch("Error in CommonDbUtilsService formatData:",c),t}}modifyAndSetData(s){return Q(this,arguments,function*({feature:e,data:t,subscriber:r,operation:a=null}){try{let c=yield this.modifyData({feature:e,data:t});r.next({data:c,operation:a})}catch(c){this.loggingService.catch("Error in CommonDbUtilsService modifyAndSetData:",c)}})}isDataAlreadyProcessedInLocalCache({feature:e,change:t,cache:r}){try{if(e==="allReactions"||e==="allComments"){if(t.type==="removed")return!Object.keys(r??{}).includes(t.doc.id);if(r?.[t.doc.id]){let a=t.doc.data(),s=r?.[t.doc.id];return a?.lastUpdated===s?.lastUpdated}}return!1}catch(a){return this.loggingService.catch("Error in CommonDbUtilsService isDataAlreadyProcessedInLocalCache:",a),!1}}modifyData(r){return Q(this,arguments,function*({feature:e,data:t}){try{return yield this.formatResponse({feature:e,data:t})}catch(a){return this.loggingService.catch("Error in CommonDbUtilsService modifyData:",a),t}})}addMetadata(e,t){try{return e&&typeof e=="object"&&!Array.isArray(e)?T(I({},e),{metadata:e?.metadata??{documentId:t?.documentId,organizationId:t?.organizationId,apiKey:t?.apiKey}}):e}catch(r){return this.loggingService.catch("Error in CommonDbUtilsService addMetadata:",r),e}}setDataInLocal(p){return Q(this,arguments,function*({feature:e,data:t,observablesCache:r,eventType:a,id:s,operation:c=null}){try{let C={comment:"allComments",reaction:"allReactions"}[e];if(!C)return null;let E=t?.metadata?.documentId,D=t?.metadata?.veltFolderId;return Object.keys(r).filter(L=>L.includes(C)&&(!E||L.includes(E)||D&&L.includes(D))).forEach(L=>{let z=r[L]?.subject?.getValue()??{};a==="DELETE"?s&&z?.data?.[s]&&(delete z?.data?.[s],r[L]?.subject&&r[L].subject.next({data:z?.data,operation:c})):r[L]?.subject?.next({data:T(I({},z?.data),{[t?.annotationId]:t}),operation:c})}),null}catch(u){return this.loggingService.catch("Error in CommonDbUtilsService setDataInLocal:",u),null}})}handleCommentEncryption(c){return Q(this,arguments,function*({data:e,firestorePath:t,extraData:r,eventType:a,metadata:s}){try{return yield this.commentUtilsService.handleCommentEncryption({data:e,firestorePath:t,extraData:r,eventType:a,metadata:s})}catch(p){return this.loggingService.catch("Error in CommonDbUtilsService handleCommentEncryption:",p),e}})}handleReactionEncryption(a){return Q(this,arguments,function*({data:e,firestorePath:t,eventType:r}){try{return yield this.reactionUtilsService.handleReactionEncryption({data:e,firestorePath:t,eventType:r})}catch(s){return this.loggingService.catch("Error in CommonDbUtilsService handleReactionEncryption:",s),e}})}rtdbDefaultTransactionCallback(e,t){try{let r=I({},e||{});return Object.entries(t).forEach(([a,s])=>{s==null?delete r[a]:r[a]=s}),r}catch(r){return this.loggingService.catch("Error in CommonDbUtilsService rtdbDefaultTransactionCallback:",r),e}}};o.\u0275fac=function(t){return new(t||o)(ee(Rce),ee(Nce),ee(f0),ee(Fce),ee(Lce),ee(Mk),ee(kk),ee(y),ee(Uce),ee(Rk),ee($ce),ee(Hce),ee(v0),ee(zce),ee(Gce),ee(Vn),ee(at),ee(Rs),ee(jd))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var Wce=(()=>{let o=class o{constructor(e,t,r){this.configService=e,this.authService=t,this.loggingService=r,this.firestore$=new ve(null);try{Sn([this.authService.getFirebaseConfig$(),this.configService.getApiKey$()]).pipe(Le(([a,s])=>!!a&&!!s),st(1)).subscribe(([a,s])=>{a&&s&&a?.firebaseOptions?.storeDbId&&this.firestore$.next(ik(og.getFirestoreProdDbName(s,a.firebaseOptions)))},a=>{})}catch{}}getFirestore(){return this.firestore$.asObservable()}getFirestoreValue(){return this.firestore$.value}generateFirestoreDocumentId(){try{let e=this.getFirestoreValue()||ik("DocumentIdDb");if(e){let t=_b(e,"generateDocumentId");return l0(t).id}return}catch(e){this.loggingService.catch("Error in FirestoreService generateFirestoreDocumentId: ",e);return}}};o.\u0275fac=function(t){return new(t||o)(ee(Ft),ee(Ve),ee(y))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var pn=(()=>{let o=class o{constructor(e,t,r,a,s,c,p,u,C,E){this.authService=e,this.commonDbUtilsService=t,this.loggingService=r,this.firestoreService=a,this.databaseService=s,this.configService=c,this.docService=p,this.usersService=u,this.commentAnnotationsResolverService=C,this.reactionAnnotationsResolverService=E,this.offset=0,this.db=null,this.firestore=null,this.subscriptions=[],this.offsetListener=null,this.observablesCache={},this.firestoreSubscriptions={},this.rtdbSubscriptions={},this.loggingService.log("%c[WB] Creating CLASS: CommonDbService","color: blue;"),this.docService.setCommonDbService(this),this.authService.setCommonDbService(this),this.usersService.setCommonDbService(this),this.subscriptions.push(this.databaseService.getDb().subscribe(D=>{if(D){this.db=D;let L=qi(D,".info/serverTimeOffset");this.offsetListener=Np(L,z=>{let W=z.val();this.offset=W})}})),this.subscriptions.push(this.firestoreService.getFirestore().subscribe(D=>{D&&(this.firestore=D)}))}unsubscribeFromObservables(){try{Object.values(this.firestoreSubscriptions??{}).forEach(e=>{e?.unsubscribe()}),Object.values(this.rtdbSubscriptions??{}).forEach(e=>{e?.unsubscribe()}),Object.entries(this.observablesCache??{}).forEach(([e,t])=>{t?.subject?.complete(),t?.subject?.unsubscribe()}),this.observablesCache={},this.firestoreSubscriptions={},this.rtdbSubscriptions={}}catch(e){this.loggingService.catch("Error in unsubscribeFromObservables:",e)}}ngOnDestroy(){this.subscriptions.forEach(e=>e.unsubscribe()),this.offsetListener&&this.offsetListener(),this.unsubscribeFromObservables()}setupOnDisconnect(e,t){return Q(this,null,function*(){try{if(this.db){let r=qi(this.db,e);return bd(r).update(t)}return Promise.resolve()}catch(r){return this.loggingService.catch("Error in setupOnDisconnect:",r),Promise.resolve()}})}getOffset(){return this.offset}getServerTimestamp(){return new Date().getTime()+this.getOffset()}subscribeToServices(e){Sn([this.databaseService.getDb(),this.firestoreService.getFirestore()]).pipe(Le(([t,r])=>!!t),st(1),dn(([t,r])=>{e({db:t,firestore:r})})).subscribe({error:t=>{this.loggingService.catch("Error in CommonDbService subscription: ",t)}})}performDatabaseOperation(e,t,r,a,s,c){return Q(this,null,function*(){try{if(!t){this.loggingService.warn(`%c[WB] No properties found for ${e}`,"color: red;");return}return this.subscribeToServices(C=>Q(this,[C],function*({db:p,firestore:u}){let E;t?.skipFirestore||(E=this.commonDbUtilsService.getFirestorePath({feature:e,properties:t,documentPaths:this.docService.getDocumentPaths(),apiKey:t.apiKey??this.configService.getApiKey()}));let D=this.commonDbUtilsService.getDocumentPath({feature:e,properties:t,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:t.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 L,z;try{D&&(L=qi(p,`${D}`))}catch{this.loggingService.catch("Error in dbRef")}try{E?.includes("/organizations")&&u&&E&&(z=l0(u,`${E}`))}catch{this.loggingService.catch("Error in docRef")}if(!this.authService.getUser())return;yield r({dbRef:L,firestoreRef:z,data:a,firestorePath:E}),c&&c({firestoreAvailable:!!u})}catch(L){this.loggingService.catch(`Error in ${e} operation: `,L),s&&s(L)}}))}catch(p){this.loggingService.catch("Error in performDatabaseOperation:",p)}})}setData(p){return Q(this,arguments,function*({feature:e,data:t,properties:r,callback:a,errorCallback:s,extraData:c}){try{return this.loggingService.log(`%c[WB] Calling FUNCTION: setData for ${e}`,"color: green;"),this.shouldUseFirestore()&&t?.metadata&&!t?.metadata?.apiKey?void 0:(this.commonDbUtilsService.setDataInLocal({feature:e,data:t,observablesCache:this.observablesCache,operation:null}),this.performDatabaseOperation(e,r,u=>Q(this,null,function*(){if(u.dbRef){let C=this.commonDbUtilsService.formatData({feature:e,data:u.data,properties:r,offset:this.getOffset(),isRealtimeDb:!0});r?.rtdbTransaction?yield Bu(u.dbRef,()=>JSON.parse(JSON.stringify(C))):yield nv(u.dbRef,JSON.parse(JSON.stringify(C)))}try{if(u.firestoreRef&&u.data&&!r?.skipFirestore){let C=this.commonDbUtilsService.formatData({feature:e,data:u.data,properties:r,offset:this.getOffset()});typeof C=="object"&&(C=JSON.parse(JSON.stringify(C)));let{strippedData:E,originalData:D,eventType:L}=this.commonDbUtilsService.handleDataStripping({feature:e,data:C,actionType:c?.actionType});if(e==="comment"){let z=null;E&&(z=yield this.commentAnnotationsResolverService.saveCommentAnnotation({commentAnnotation:E,eventType:L,commentId:c?.targetAnnotationData?.commentId})),D&&(z?.isSuccess||z===null)&&(yield this.commonDbUtilsService.handleCommentEncryption({data:D,firestorePath:u.firestorePath??"",extraData:c,metadata:r?.metadata}))}else if(e==="reaction"){let z=null;E&&(z=yield this.reactionAnnotationsResolverService.saveReactionAnnotation(E)),D&&(z?.isSuccess||z===null)&&(yield this.commonDbUtilsService.handleReactionEncryption({data:D,firestorePath:u.firestorePath??""}))}else e==="recorder"?this.firestore&&(yield hce(this.firestore,z=>Q(this,null,function*(){z.set(u.firestoreRef,C)}))):yield hz(u.firestoreRef,C)}}catch(C){this.authService.getUser()&&this.loggingService.catch(`Error in setData for ${e}`,C)}}),t,s,a))}catch(u){this.loggingService.catch(`Error in setData for ${e}`,u)}})}updateData(p){return Q(this,arguments,function*({feature:e,data:t,properties:r,callback:a,errorCallback:s,extraData:c}){try{return this.loggingService.log(`%c[WB] Calling FUNCTION: updateData for ${e}`,"color: green;"),this.shouldUseFirestore()&&t?.metadata&&!t?.metadata?.apiKey?void 0:(this.commonDbUtilsService.setDataInLocal({feature:e,data:t,observablesCache:this.observablesCache,operation:null}),this.performDatabaseOperation(e,r,u=>Q(this,null,function*(){if(u.dbRef&&!r?.skipRtdb){let C=this.commonDbUtilsService.formatData({feature:e,data:u.data,properties:r,offset:this.getOffset(),isRealtimeDb:!0});r?.rtdbTransaction?yield Bu(u.dbRef,E=>{let D;return r?.rtdbTransactionCallback?D=r.rtdbTransactionCallback(E,C):D=this.commonDbUtilsService.rtdbDefaultTransactionCallback(E,C),JSON.parse(JSON.stringify(D))}):yield H6(u.dbRef,JSON.parse(JSON.stringify(C)))}try{if(u.firestoreRef&&u.data&&!r?.skipFirestore){let C=this.commonDbUtilsService.formatData({feature:e,data:u.data,properties:r,offset:this.getOffset()});typeof C=="object"&&(C=JSON.parse(JSON.stringify(C)));let{strippedData:E,originalData:D,eventType:L}=this.commonDbUtilsService.handleDataStripping({feature:e,data:C,actionType:c?.actionType});if(e==="comment"){let z=null;E&&(z=yield this.commentAnnotationsResolverService.saveCommentAnnotation({commentAnnotation:E,eventType:L,commentId:c?.targetAnnotationData?.commentId})),D&&(z?.isSuccess||z===null)&&(yield this.commonDbUtilsService.handleCommentEncryption({data:D,firestorePath:u.firestorePath??"",extraData:c,metadata:r?.metadata}))}else if(e==="reaction"){let z=null;E&&(z=yield this.reactionAnnotationsResolverService.saveReactionAnnotation(E)),D&&(z?.isSuccess||z===null)&&(yield this.commonDbUtilsService.handleReactionEncryption({data:D,firestorePath:u.firestorePath??""}))}else yield hz(u.firestoreRef,C,{merge:!0})}}catch(C){this.authService.getUser()&&this.loggingService.catch(`Error in updateDoc for ${e}`,C)}}),t,s,a))}catch(u){this.loggingService.catch(`Error in updateData for ${e}`,u)}})}deleteData(s){return Q(this,arguments,function*({feature:e,properties:t,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:t?.id,operation:{type:"removed",ids:[t?.id]}}),this.performDatabaseOperation(e,t,c=>Q(this,null,function*(){c.dbRef&&(yield $6(c.dbRef));try{if(c.firestoreRef&&!t?.skipFirestore)if(e==="comment"){let p=null;p=yield this.commentAnnotationsResolverService.deleteCommentAnnotation(t?.id??""),(p?.isSuccess||p===null)&&(yield this.commonDbUtilsService.handleCommentEncryption({firestorePath:c.firestorePath??"",eventType:"DELETE",metadata:t?.metadata}))}else if(e==="reaction"){let p=null;p=yield this.reactionAnnotationsResolverService.deleteReactionAnnotation(t?.id??""),(p?.isSuccess||p===null)&&(yield this.commonDbUtilsService.handleReactionEncryption({firestorePath:c.firestorePath??"",eventType:"DELETE"}))}else yield dce(c.firestoreRef)}catch(p){this.authService.getUser()&&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 Q(this,arguments,function*({feature:e,properties:t}){try{let a=this.shouldUseFirestore();return!e||!t?(this.loggingService.warn("[WB] Missing required parameters in queryData"),[]):a?yield this.handleFirestoreQuery(e,t):yield this.handleRtdbQuery(e,t)}catch(a){return this.loggingService.catch(`Error in queryData for ${e}`,a),[]}})}handleFirestoreQuery(e,t){return Q(this,null,function*(){try{if(!this.firestore)return this.loggingService.warn("[WB] Firestore not initialized"),[];let r=t?.useCollectionGroup?this.commonDbUtilsService.getFirestoreCollectionGroupPath(e):this.commonDbUtilsService.getFirestorePath({feature:e,properties:t,documentPaths:this.docService.getDocumentPaths(),apiKey:t.apiKey??this.configService.getApiKey()});if(!r)return this.loggingService.warn(`[WB] No firestore path found for ${e}`),[];try{let a=_b(this.firestore,r);t?.useCollectionGroup&&(a=pz(this.firestore,r));let s=t?.firestoreQuery??[],c=uz(a,...s);if(!this.authService.getUser()&&!t?.skipUserCheck)return[];if(t?.getCount){let p=yield pce(c).catch(u=>(this.authService.getUser()&&this.loggingService.catch(`Error in getCountFromServer for ${e}`,u),null));return p?p.data().count:0}else{let p=yield uce(c).catch(E=>(this.authService.getUser()&&this.loggingService.catch(`Error in getDocs for ${e}`,E),null));if(!p)return[];let u=p.docs.map(E=>E.data());return yield this.commonDbUtilsService.modifyData({feature:e,data:u})}}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,t){return Q(this,null,function*(){if(!this.db)return this.loggingService.warn("[WB] Realtime Database not initialized"),[];let r=this.commonDbUtilsService.getDocumentPath({feature:e,properties:t,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:t.apiKey??this.configService.getApiKey()});if(!r)return this.loggingService.warn(`[WB] No database path found for ${e}`),[];try{let a=qi(this.db,r),s=t?.rtdbQuery??[],c=BV(a,...s);if(!this.authService.getUser()&&!t?.skipUserCheck)return[];let p=yield FV(c).catch(C=>(this.authService.getUser()&&this.loggingService.catch(`Error in get for ${e}`,C),null));if(!p)return[];let u=p.val();return u?t?.skipObjectValues?u:Object.values(u??{}):[]}catch(a){return this.loggingService.catch(`Error in RTDB query for ${e}:`,a),[]}})}getData(r){return Q(this,arguments,function*({feature:e,properties:t}){try{let a=this.shouldUseFirestore();if(t?.skipFirestore&&(a=!1),!e||!t)return this.loggingService.warn("[WB] Missing required parameters in getData"),{};if(a&&this.firestore){let s=this.commonDbUtilsService.getFirestorePath({feature:e,properties:t,documentPaths:this.docService.getDocumentPaths(),apiKey:t.apiKey??this.configService.getApiKey()});if(!s)return this.loggingService.warn(`[WB] No firestore path found for ${e}`),{};try{if(!this.authService.getUser())return{};let c=yield gce(l0(this.firestore,s)).catch(u=>(this.authService.getUser()&&this.loggingService.catch(`Error in getDoc for ${e}`,u),this.commonDbUtilsService.getErrorForGetRequests({feature:e,error:u})));if(c){if(c?.errorCode)return c}else return this.loggingService.warn(`[WB] No document found at ${s}`),{};let p=c.data();return t?.field?p?.[t.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:t,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:t.apiKey??this.configService.getApiKey()});if(!s)return this.loggingService.warn(`[WB] No database path found for ${e}`),{};try{if(!this.authService.getUser())return{};let c=yield FV(qi(this.db,s)).catch(u=>(this.authService.getUser()&&this.loggingService.catch(`Error in get for ${e}`,u),this.commonDbUtilsService.getErrorForGetRequests({feature:e,error:u})));if(c){if(c?.errorCode)return c}else return this.loggingService.warn(`[WB] No data found at ${s}`),{};let p=c.val();return t?.field?p?.[t.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:t}){let r=this.shouldUseFirestore();t?.skipFirestore&&(r=!1);let a=`${e}-${JSON.stringify(t)}`;return Sn([this.databaseService.getDb(),this.firestoreService.getFirestore(),this.authService.getUser$().pipe(Le(s=>!!s))]).pipe(Le(([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)),he(([s,c])=>{try{if(r&&c){if(!!!this.observablesCache[a]){this.observablesCache[a]={subject:new ve({}),count:0};let C=this.handleFirestoreListener(e,t,c).subscribe(E=>{this.observablesCache[a]?.subject?.next(E)},E=>this.observablesCache[a]?.subject?.error(E));this.firestoreSubscriptions[a]=C}return new Ut(u=>{let C=this.observablesCache[a]?.subject?.subscribe(E=>u.next(E),E=>u.error(E),()=>u.complete());return this.observablesCache[a].count+=1,()=>{C?.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){if(!!!this.observablesCache[a]){this.observablesCache[a]={subject:new ve({}),count:0};let C=this.handleRealtimeDbListener(e,t,s).subscribe(E=>{this.observablesCache[a]?.subject?.next(E)},E=>this.observablesCache[a]?.subject?.error(E));this.rtdbSubscriptions[a]=C}return new Ut(u=>{let C=this.observablesCache[a]?.subject?.subscribe(E=>u.next(E),E=>u.error(E),()=>u.complete());return this.observablesCache[a].count+=1,()=>{C?.unsubscribe(),this.observablesCache[a]&&(this.observablesCache[a].count-=1,this.observablesCache[a].count<=0&&(this.rtdbSubscriptions[a]?.unsubscribe(),delete this.rtdbSubscriptions?.[a],this.observablesCache[a]?.subject?.complete(),delete this.observablesCache?.[a]))}})}return se({})}catch(p){return this.loggingService.catch(`Error setting up listener for ${e}:`,p),se({})}}),Yg(()=>{this.loggingService.log(`[WB] Cleaning up listener for ${e} and key ${a}`)}))}handleFirestoreListener(e,t,r){let a=t?.useCollectionGroup?this.commonDbUtilsService.getFirestoreCollectionGroupPath(e):this.commonDbUtilsService.getFirestorePath({feature:e,properties:t,documentPaths:this.docService.getDocumentPaths(),apiKey:t.apiKey??this.configService.getApiKey()}),s=`${e}-${JSON.stringify(t)}`;return a?new Ut(c=>{let p=t.isCollection?this.setupCollectionListener(r,a,e,c,t):this.setupDocumentListener(r,a,e,c,t);return()=>{c.complete(),c.unsubscribe(),p(),this.observablesCache[s]?.subject?.complete(),this.observablesCache[s]?.subject?.unsubscribe(),delete this.observablesCache[s]}}).pipe(he(c=>this.commonDbUtilsService.mergeUsersWithData$({feature:e,data:c})),he(c=>["allComments","allUserNotifications"].includes(e)?this.commonDbUtilsService.mergeCommentAnnotationsWithData$({data:c,feature:e}):se(c)),he(c=>["allReactions"].includes(e)?this.commonDbUtilsService.mergeReactionAnnotationsWithData$({data:c,feature:e}):se(c)),Et(mn)):(this.loggingService.warn(`[WB] No firestore path found for ${e} and key ${s}`),se({}))}setupCollectionListener(e,t,r,a,s){let c=`${r}-${JSON.stringify(s)}`,p=_b(e,t);if(s?.useCollectionGroup&&(p=pz(e,t)),s?.useQuery&&s?.firestoreQuery){let E=s?.firestoreQuery??[];p=uz(p,...E)}let u=!0,C=[];return gz(p,E=>{try{let D=JSON.parse(JSON.stringify(this.observablesCache[c]?.subject?.getValue()?.data??{})),L=null,z=!1;E?.docChanges()?.length?E.docChanges().forEach(W=>{["allComments","allReactions"].includes(r)&&!u&&W.type!=="removed"&&C.push(W.doc.id),this.commonDbUtilsService.isDataAlreadyProcessedInLocalCache({feature:r,change:W,cache:this.observablesCache[c]?.subject?.getValue()?.data??{}})||(z=!0,Object.assign(D,this.handleCollectionChange(W,D)),W.type==="removed"&&(L||(L={type:W.type,ids:[]}),L.ids.push(W.doc.id)))}):z=!0,z&&(["allComments","allReactions"].includes(r)&&C?.length&&(this.commonDbUtilsService.resolveAnnotations({data:C,feature:r}),C=[]),this.commonDbUtilsService.modifyAndSetData({feature:r,data:D,subscriber:a,operation:L})),u=!1}catch(D){this.handleListenerError(D,r,a)}},E=>this.handleListenerError(E,r,a))}handleCollectionChange(e,t){switch(e.type){case"added":case"modified":t[e.doc.id]=e.doc.data();break;case"removed":delete t?.[e.doc.id];break}return t}setupDocumentListener(e,t,r,a,s){let c=l0(e,t);return gz(c,p=>{try{let u=p.data()||{};s?.field&&(u=u?.[s?.field]??{}),this.commonDbUtilsService.modifyAndSetData({feature:r,data:u,subscriber:a,operation:null})}catch(u){this.handleListenerError(u,r,a)}},p=>this.handleListenerError(p,r,a))}handleListenerError(e,t,r){this.loggingService.catch(`Firestore listener error for ${t}:`,e),r.error(e)}handleRealtimeDbListener(e,t,r){let a=this.commonDbUtilsService.getDocumentPath({feature:e,properties:t,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:t.apiKey??this.configService.getApiKey()});if(!a)return this.loggingService.warn(`[WB] No database path found for ${e}`),se({});let s=qi(r,a);if(t?.useQuery&&t?.rtdbQuery){let c=t?.rtdbQuery??[];s=BV(s,...c)}return this.objectValFromChildEvents(s,e).pipe(kn(c=>(this.loggingService.catch(`RTDB listener error for ${e}:`,c),se({}))),ce(c=>(c===null&&(c={}),c&&typeof c=="object"?Object.entries(c??{}).reduce((u,[C,E])=>(u[C]=this.commonDbUtilsService.addMetadata(E,t),u),{}):this.commonDbUtilsService.addMetadata(c,t))),he(c=>this.commonDbUtilsService.modifyData({feature:e,data:c})),he(c=>this.usersService.getUserById$().pipe(ce(()=>({data:this.commonDbUtilsService.mergeUsersWithData({feature:e,data:c}),operation:null})))))}objectValFromChildEvents(e,t){return new Ut(r=>{let a={},s=!1,c=null,p=W=>{try{this.loggingService.catch(`Realtime DB listener error for ${t}:`,W),r.error(W)}catch{}},u=W=>{try{if(!wi(W,c)){let J=JSON.parse(JSON.stringify(W));c=J,r.next(J)}}catch{}},C=W=>{try{W.key&&(a[W.key]=W.val(),s&&u(I({},a)))}catch{}},E=W=>{try{W.key&&(a[W.key]=W.val(),s&&u(I({},a)))}catch{}},D=W=>{try{W.key&&(delete a[W.key],s&&u(I({},a)))}catch{}},L=W=>{try{if(!s){let J=a&&typeof a=="object"?JSON.parse(JSON.stringify(a)):{};c=J,r.next(J),s=!0}}catch{}};Mne(e,C,p),kne(e,E,p),Rne(e,D,p);let z=Np(e,L,p,{onlyOnce:!0});return()=>{try{z&&typeof z=="function"&&z(),j6(e,"child_added",C),j6(e,"child_changed",E),j6(e,"child_removed",D)}catch{}}})}};o.\u0275fac=function(t){return new(t||o)(ee(Ve),ee(ag),ee(y),ee(Wce),ee(Dn),ee(Ft),ee(at),ee(Vn),ee(Rs),ee(jd))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var xi=(()=>{let o=class o{constructor(e,t,r,a,s,c,p,u){this.analyticsService=e,this.authService=t,this.configService=r,this.databaseService=a,this.docService=s,this.loggingService=c,this.commonDbService=p,this.usersService=u,this.db=ts(),this.internalUserContacts$=new ve([]),this.userGlobalContact$=new ve(!1),this.userGroupContact$=new ve(null),this.users$=new ve([]),this.userPersonalContacts=[],this.userGroupContacts=[],this.userGlobalContacts=[],this.users=[],this.documentPaths=null,this.userOrganizationContacts$=new ve([]),this.userFolderContacts$=new ve([]),this.userDocumentContacts$=new ve([]),this.userOrganizationGroups$=new ve([]),this.onContactSelectedSubject$=new tt,this.documentAccessType=null,this.atHereEnabled$=new ve(!1),this.atHereLabel$=new ve("here"),this.atHereDescription$=new ve(null),this.contactListScopeForOrganizationUsers$=new ve([Hi.ALL]),this.customUserContacts$=new ve(null),this.customUserContactsConfig$=new ve({merge:!1}),this.currentOrganizationUserIAM$=new ve(null),this.userContacts$=new ve([]),this.userSnippylyIdContacts$=new ve(null),this.usersByOrganizationId$=new ve({}),this.temporaryUserIds$=new ve([]),this.usersByOrganizationIdAndDocumentId$=new ve({}),this.usersByOrganizationIdAndFolderId$=new ve({}),this.userById$=new ve({}),this.authService.setContactService(this),this.authService.getUser$().pipe(he(C=>this.docService.getDocumentPaths$().pipe(dn(E=>{this.documentPaths=E}),ce(()=>C)))).subscribe(C=>Q(this,null,function*(){this.user=C,C&&this.documentPaths?C?.organizationId?(this.getOrganizationContactsFromDb$(),this.getFolderContactsFromDb$(),this.getDocumentContactsFromDb$(),this.getOrganizationGroupsFromDb$(),this.getTemporaryUsers()):(this.getLoggedInUsers$().subscribe(),this.getUserContactsFromDb$(),yield this.migrateLoggedInUserFromEmailToUserIdPath(C),this.setLoggedInUser(C),yield this.moveGlobalContactUserFromEmailToUserIdPath(C),this.updateUserInGlobalContactsIfAvailable(C),C?.groupId&&(yield this.migrateGroupContactsFromEmailToUserIdPath(C?.groupId)),this.checkToSetLoggedInUserInGroupContacts()):(this.getUserContactSubscription?.unsubscribe(),this.getUserContactSubscription=void 0,this.getLoggedInUsersSubscription?.unsubscribe(),this.getLoggedInUsersSubscription=void 0,this.getOrganizationContactsSubscription?.unsubscribe(),this.getOrganizationContactsSubscription=void 0,this.getFolderContactsSubscription?.unsubscribe(),this.getFolderContactsSubscription=void 0,this.getDocumentContactsSubscription?.unsubscribe(),this.getDocumentContactsSubscription=void 0,this.getOrganizationGroupsSubscription?.unsubscribe(),this.getOrganizationGroupsSubscription=void 0)}),C=>{this.loggingService.catch("Error in ContactService constructor getUser$: ",C)}),this.databaseService.getDb().pipe(Le(C=>!!C),st(1)).subscribe(C=>{C&&(this.db=C)},C=>{this.loggingService.catch("Error in ContactService constructor getDb: ",C)}),this.getOrganizationGroups$().subscribe(C=>{this.authService.setOrganizationUserGroups(C)}),Sn([this.getInternalUserContacts$(),this.getCustomUserContacts$(),this.getCustomUserContactsConfig$()]).subscribe(([C,E,D])=>{E?D?.merge?this.userContacts$.next([...C||[],...E||[]]):this.userContacts$.next(E||[]):this.userContacts$.next(C||[])}),this.getUserContacts$().subscribe(C=>{try{C?.forEach(E=>{let D=E?.userSnippylyId||Av(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.temporaryUserIds$.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(t){this.loggingService.catch("Error in ContactService setDocumentAccessType: ",t)}}checkIfUserGlobalContact(e){return Q(this,null,function*(){try{if(e?.userId&&this.documentPaths?.globalContacts){let t=yield this.commonDbService?.getData({feature:"globalContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:bt(e?.userId),skipFirestore:!0}});if(Object.keys(t??{}).length>0)return!0}if(e?.email&&this.documentPaths?.globalContacts){let t=yield this.commonDbService?.getData({feature:"globalContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:bt(e?.email),skipFirestore:!0}});if(Object.keys(t??{}).length>0)return!0}return!1}catch(t){return this.loggingService.catch("Error in ContactService isUserGlobalContact: ",t),!1}})}setLoggedInUser(e){try{e?.userId&&this.documentPaths?.logins&&(this.commonDbService.updateData({feature:"logins",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:bt(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(T(I({},e),{contacts:void 0})))}),this.setLoggedInUserPrivateContacts(e,e?.contacts))}catch(t){this.loggingService.catch("Error in ContactService setLoggedInUser: ",t)}}migrateLoggedInUserFromEmailToUserIdPath(e){return Q(this,null,function*(){try{if(e?.email&&this.documentPaths?.logins){let t=yield this.commonDbService?.getData({feature:"logins",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:bt(e?.email),skipFirestore:!0}});if(Object.keys(t??{}).length>0){let r=t;if(r){if(r?.contacts){let a={};Object.keys(r?.contacts??{})?.forEach(s=>{let c=r.contacts[s];if(c?.userId){let p=bt(c?.userId);a[p]=c}}),r.contacts=a}yield this.commonDbService.updateData({feature:"logins",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:bt(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:bt(e?.email),skipFirestore:!0}})}}}}catch(t){this.loggingService.catch("Error in ContactService migrateLoggedInUserFromEmailToUserIdPath: ",t)}})}addGlobalContact(e){try{e?.userId&&this.documentPaths?.globalContacts&&this.commonDbService.updateData({feature:"globalContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:bt(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(e))})}catch(t){this.loggingService.catch("Error in ContactService addGlobalContact: ",t)}}updateUserInGlobalContactsIfAvailable(e){return Q(this,null,function*(){try{if(e?.userId&&this.documentPaths?.globalContacts&&(yield this.checkIfUserGlobalContact(e))){let r=new Po;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:bt(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(r))})}}catch(t){this.loggingService.catch("Error in ContactService updateUserInGlobalContactsIfAvailable: ",t)}})}moveGlobalContactUserFromEmailToUserIdPath(e){return Q(this,null,function*(){try{if(e?.email&&e?.userId&&this.documentPaths?.globalContacts){let t=yield this.commonDbService?.getData({feature:"globalContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:bt(e?.email),skipFirestore:!0}});if(Object.keys(t??{}).length>0){let r=t;r&&(yield this.commonDbService.updateData({feature:"globalContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:bt(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:bt(e?.email),skipFirestore:!0}}))}}}catch(t){this.loggingService.catch("Error in ContactService removeUserFromGlobalContactsByEmail: ",t)}})}setLoggedInUserPrivateContacts(e,t){try{if(e?.userId&&this.documentPaths?.logins){let r,a=t?.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=bt(c?.userId);r[p]=c}}),s?this.commonDbService.setData({feature:"allLoginContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:bt(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:bt(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:bt(e?.userId),skipFirestore:!0}})}}catch(r){this.loggingService.catch("Error in ContactService setLoggedInUserPrivateContacts: ",r)}}migrateGroupContactsFromEmailToUserIdPath(e){return Q(this,null,function*(){try{if(this.documentPaths?.groupContacts&&e){let t=yield this.commonDbService?.getData({feature:"groupContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",groupId:e,skipFirestore:!0}});t&&Object.keys(t??{}).forEach(r=>Q(this,null,function*(){let a=t[r];a?.email&&a?.userId&&bt(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:bt(a?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(a))}))}))}}catch(t){this.loggingService.catch("Error in ContactService migrateGroupContacts: ",t)}})}checkToSetLoggedInUserInGroupContacts(){return Q(this,null,function*(){try{this.user?.groupId&&this.user?.userId&&((yield this.checkIfUserGlobalContact(this.user))||this.docService.getDocumentIam$().pipe(st(1)).subscribe(t=>Q(this,null,function*(){if(this.user?.groupId&&this.user?.userId){let r=!1,a=this.docService.getDocumentAccessType(t);if(!a||a===yi.PUBLIC)r=!0;else if(a===yi.RESTRICTED){let s=bt(this.user?.userId);if(t?.users?.[s]&&(r=!0),this.user?.email){let c=bt(this.user?.email);t?.users?.[c]&&(r=!0)}}if(r){let s=new ig;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,t){try{let r=t?.filter(a=>a?.visibility==="group");r?.length&&r.forEach(a=>Q(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:bt(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:bt(a?.email),skipFirestore:!0}}))}}))}catch(r){this.loggingService.catch("Error in ContactService setLoggedInUserGroupContacts: ",r)}}removeGroupContacts(e){return Q(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(t){this.loggingService.catch("Error in ContactService removeGroupContacts: ",t)}})}mergeUserContacts(){try{let e=[];this.userPersonalContacts&&e.push(...this.userPersonalContacts),this.userGroupContacts&&e.push(...this.userGroupContacts),this.userGlobalContacts&&e.push(...this.userGlobalContacts);let t={};e.forEach(r=>{r?.userId?(!r?.email||!t[r.email])&&(t[r.userId]=r):r?.email&&(!r?.userId||!t[r.userId])&&(t[r.email]=r)}),e=Object.values(t??{}),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:t,documentId:r,veltFolderId:a}=e||{};return t&&r?Sn([this.usersByOrganizationId$,this.usersByOrganizationIdAndFolderId$,this.usersByOrganizationIdAndDocumentId$,this.userById$,this.customUserContacts$,this.customUserContactsConfig$,this.getContactListScopeForOrganizationUsers$(),this.temporaryUserIds$]).pipe(ce(([s,c,p,u,C,E,D,L])=>{let z={},W=!1;E&&!E?.merge&&(W=!0);let J=Fe=>D.some(xe=>Fe.includes(xe)),ue=J([Hi.ALL,Hi.ORGANIZATION])?Object.keys(s?.[t]||{}):[],ye=a?J([Hi.ALL,Hi.FOLDER])?Object.keys(c?.[t]?.[a]||{}):[]:[],Ae=J([Hi.ALL,Hi.DOCUMENT])?Object.keys(p?.[t]?.[r]||{}):[];if([...ue,...ye||[],...Ae,...L].forEach(Fe=>{let xe=u?.[Fe];xe&&(z[Fe]=xe)}),C){let{merge:Fe,options:xe}=E||{},{organizationId:Se,documentId:we,folderId:_e}=xe||{},fe=_e?Fi(_e):void 0;(!Se||Se===t)&&(!we||we===r)&&(!fe||fe===a)&&(Fe||(z={}),C.forEach(Oe=>{Oe?.userId&&(z[Oe.userId]=Oe)}))}return Object.values(z??{})})):this.userContacts$.asObservable().pipe(ce(s=>s))}catch(t){return this.loggingService.catch("Error in ContactService getUserContacts$ metadata: ",t),se([])}}getUserContactsBySnippylyId$(){return this.userSnippylyIdContacts$.asObservable()}getAtHereLabel(){return this.atHereLabel$.asObservable()}getAtHereDescription(){return this.atHereDescription$.asObservable()}getUserContactsFromDb$(){this.getUserContactSubscription||(this.getUserContactSubscription=this.authService.getUser$().pipe(Le(e=>!!e),he(e=>this.docService.getDocumentPaths$().pipe(Le(t=>!!t),dn(t=>{this.documentPaths=t}),ce(()=>e))),he(e=>{if(this.userGroupContacts=[],this.userPersonalContacts=[],!e)return se();if(!this.documentPaths)return se();let t=[];return t.push(this.commonDbService.dbListener({feature:"allGlobalContacts",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,skipFirestore:!0}}).pipe(ce(r=>r?.data),dn(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))}))),t.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),dn(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))}))),t.push(this.commonDbService.dbListener({feature:"allLoginContacts",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,skipFirestore:!0,userId:bt(e?.userId)}}).pipe(ce(r=>r?.data),dn(r=>{r?this.userPersonalContacts=Object.values(r??{}):this.userPersonalContacts=[]}))),co(...t).pipe(mo(this.authService.getUser$().pipe(Le(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(t){this.loggingService.catch("Error in ContactService addUserContact: ",t)}}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(he(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(t=>t?.data),dn(t=>{t?this.users=Object.values(t??{}):this.users=[]})):(this.users=[],se()):se():se())).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(he(e=>e?.organizationId?this.userById$.pipe(ce(t=>{let r={};return Object.values(t||{}).forEach(a=>{a?.userSnippylyId&&(r[a?.userSnippylyId]=a)}),r})):this.users$.pipe(ce(t=>{let r={};return t.forEach(a=>{r[a.userSnippylyId]=a}),r}))))}getUserByEmail$(e){return this.users$.pipe(ce(t=>t.find(r=>r.email===e)))}getUserByEmail(e){return this.users?.find(t=>t.email===e)}getContactByEmail(e){return this.getInternalUserContacts().find(t=>t.email===e)}getUserByUserId$(e){return this.users$.pipe(ce(t=>t.find(r=>r.userId===e)))}getUserGroupContacts(){return this.userGroupContacts}getTemporaryUsers(){try{let e=this.authService.getUser();this.docService.getOrganizationConfig$().pipe(Le(t=>!!t),ce(t=>t?.organizationId)).subscribe(t=>Q(this,null,function*(){if(t&&e){let r=((yield this.commonDbService?.queryData({feature:"allPermissionsUsers",properties:{organizationId:t,useCollectionGroup:!1,isCollection:!0,firestoreQuery:[lt("expiresAt",">",new Date().getTime())]}}))??[]).filter(a=>a?.userId!==e?.userId);if(r?.length){let a=yield this.usersService.resolveUsers({userIds:r.map(s=>s?.userId)});if(a){let s={};Object.entries(a).forEach(([p,u])=>{s[p]=u}),this.userById$.next(I(I({},this.userById$.value),s));let c=new Set([...this.temporaryUserIds$.value,...Object.keys(s)]);this.temporaryUserIds$.next(Array.from(c))}}}}))}catch(e){this.loggingService.catch("Error in ContactService getTemporaryUsers: ",e)}}getOrganizationContactsFromDb$(){try{this.getOrganizationContactsSubscription||(this.getOrganizationContactsSubscription=this.authService.getUser$().pipe(he(e=>e?.organizationId?se(e).pipe(he(t=>this.docService.getOrganizationConfig$().pipe(Le(r=>!!r),ce(()=>t))),he(t=>this.usersService.getResolveOrganizationUsers$().pipe(Le(r=>r),ce(()=>t))),he(t=>{let r=this.docService.getOrganizationConfig()?.organizationId;return this.setUserOrganizationContacts([],r),t?r?this.commonDbService.dbListener({feature:"allOrganizationUsers",properties:{organizationId:r,isCollection:!0,useQuery:!0,firestoreQuery:[Zn(ak(lt("organizationIds","array-contains-any",[r]),lt("viewerOrganizationIds","array-contains-any",[r]))),fi("id")]}}).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)})):se():se()}),he(()=>this.getContactListScopeForOrganizationUsers$())):(this.setUserOrganizationContacts([]),se()))).subscribe(()=>{this.mergeOrganizationAndDocumentContacts()},e=>{this.loggingService.catch("Error in ContactService getOrganizationContactsFromDb$ subscription: ",e)}))}catch{}}getFolderContactsFromDb$(){try{this.getFolderContactsSubscription||(this.getFolderContactsSubscription=this.authService.getUser$().pipe(he(e=>e?se(e).pipe(he(t=>this.docService.getOrganizationConfig$().pipe(Le(r=>!!r),ce(()=>t))),he(t=>this.usersService.getResolveFolderUsers$().pipe(Le(r=>r),ce(()=>t))),he(t=>{let r=this.docService.getOrganizationConfig()?.organizationId;if(this.setUserFolderContacts([]),!t)return se();if(!this.commonDbService.shouldUseFirestore())return se();if(!this.documentPaths?.veltFolderId)return se();let a=se([]);return a=this.commonDbService.dbListener({feature:"allFolderUsers",properties:{organizationId:r,folderId:this.documentPaths?.veltFolderId,isCollection:!0,useQuery:!0,firestoreQuery:[Zn(ak(lt("folderIds","array-contains-any",[this.documentPaths?.veltFolderId]),lt("viewerFolderIds","array-contains-any",[this.documentPaths?.veltFolderId]))),fi("id")]}}).pipe(ce(s=>s?.data)),a.pipe(ce(s=>{if(s){typeof s=="object"&&(s?.undefined&&delete s.undefined,s?.null&&delete s.null);let c=Object.values(s??{});this.setUserFolderContacts(c)}else this.setUserFolderContacts([])}))}),he(()=>this.getContactListScopeForOrganizationUsers$())):(this.setUserFolderContacts([]),se()))).subscribe(()=>{this.mergeOrganizationAndDocumentContacts()},e=>{this.loggingService.catch("Error in ContactService getFolderContactsFromDb$ subscription: ",e)}))}catch{}}getDocumentContactsFromDb$(){try{this.getDocumentContactsSubscription||(this.getDocumentContactsSubscription=this.authService.getUser$().pipe(he(e=>e?se(e).pipe(he(t=>this.docService.getDocumentPaths$().pipe(Le(r=>!!r),dn(r=>{this.documentPaths=r}),ce(()=>t))),he(t=>this.usersService.getResolveDocumentUsers$().pipe(Le(r=>r),ce(()=>t))),he(t=>(this.setUserDocumentContacts([]),t?this.documentPaths?this.docService.getDocumentIds$().pipe(he(r=>{let a=r?.length>0?r.map(u=>u.documentId):[this.documentPaths?.documentId??""];if(a.some(u=>!u)||!this.documentPaths)return se();let s=se([]),c={isCollection:!0,useQuery:!0};this.commonDbService.shouldUseFirestore()||(c.documentId=a?.length?a[0]:void 0,c.organizationId=this.documentPaths?.organizationId);let p=[];for(let u=0;u<a.length;u+=j.LISTENER_BATCH_SIZE)p.push(a.slice(u,u+j.LISTENER_BATCH_SIZE));return s=Sn(p.map(u=>this.commonDbService.dbListener({feature:"allDocumentUsers",properties:T(I({},c),{firestoreQuery:[Zn(ak(lt("documentIds","array-contains-any",u),lt("viewerDocumentIds","array-contains-any",u))),fi("id")]})}).pipe(da()))).pipe(ce(u=>Ba(u)?.data)),s.pipe(ce(u=>{if(u){typeof u=="object"&&(u?.undefined&&delete u.undefined,u?.null&&delete u.null);let C=Object.values(u??{});this.setUserDocumentContacts(C)}else this.setUserDocumentContacts([])}))})):se():se())),he(()=>this.getContactListScopeForOrganizationUsers$())):(this.setUserDocumentContacts([]),se()))).subscribe(()=>{this.mergeOrganizationAndDocumentContacts()},e=>{this.loggingService.catch("Error in ContactService getDocumentContactsFromDb$ subscription: ",e)}))}catch{}}setUserOrganizationContacts(e,t){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),this.usersService.setUserByIds(a),t){let s={};s[t]={};let c={};e.forEach(p=>{s[t][p.user.userId]=p,c[p.user.userId]=p.user}),this.userById$.next(I(I({},this.userById$.value),c)),this.usersByOrganizationId$.next(T(I({},this.usersByOrganizationId$.value),{[t]:s[t]}))}else this.usersByOrganizationId$.next({})}catch(r){this.loggingService.catch("Error in ContactService setUserOrganizationContacts: ",r)}}getUserOrganizationContacts$(){return this.getContactListScopeForOrganizationUsers$().pipe(he(()=>this.checkContactListScopeForOrganizationUsers([Hi.ALL,Hi.ORGANIZATION])?this.userOrganizationContacts$.asObservable():se([])))}getUserOrganizationContacts(){return this.checkContactListScopeForOrganizationUsers([Hi.ALL,Hi.ORGANIZATION])?this.userOrganizationContacts$.value:[]}setUserFolderContacts(e){try{let t=e?.map(s=>s?.user);this.userFolderContacts$.next(t),this.usersService.setUserByIds(t);let r={},a={};e?.forEach(s=>{let{organizationId:c}=s?.metadata||{};c&&(r[c]||(r[c]={}),s.folderIds?.forEach(p=>{r[c][p]||(r[c][p]={}),r[c][p][s.user.userId]=s,a[s.user.userId]=s.user}))}),this.userById$.next(I(I({},this.userById$.value),a)),this.usersByOrganizationIdAndFolderId$.next(r)}catch(t){this.loggingService.catch("Error in ContactService updateUserFolderContacts: ",t)}}getUserFolderContacts$(){return this.getContactListScopeForOrganizationUsers$().pipe(he(()=>this.checkContactListScopeForOrganizationUsers([Hi.ALL,Hi.FOLDER])?this.userFolderContacts$.asObservable():se([])))}getUserFolderContacts(){return this.checkContactListScopeForOrganizationUsers([Hi.ALL,Hi.FOLDER])?this.userFolderContacts$.value:[]}setUserDocumentContacts(e){try{let t=e?.map(s=>s?.user);this.userDocumentContacts$.next(t),this.usersService.setUserByIds(t);let r={},a={};e?.forEach(s=>{let{organizationId:c}=s?.metadata||{};c&&(r[c]||(r[c]={}),s.documentIds?.forEach(p=>{r[c][p]||(r[c][p]={}),r[c][p][s.user.userId]=s,a[s.user.userId]=s.user}))}),this.userById$.next(I(I({},this.userById$.value),a)),this.usersByOrganizationIdAndDocumentId$.next(r)}catch(t){this.loggingService.catch("Error in ContactService updateUserDocumentContacts: ",t)}}getUserDocumentContacts$(){return this.getContactListScopeForOrganizationUsers$().pipe(he(()=>this.checkContactListScopeForOrganizationUsers([Hi.ALL,Hi.DOCUMENT])?this.userDocumentContacts$.asObservable():se([])))}getUserDocumentContacts(){return this.checkContactListScopeForOrganizationUsers([Hi.ALL,Hi.DOCUMENT])?this.userDocumentContacts$.value:[]}getCurrentOrganizationUserIAM$(){return this.currentOrganizationUserIAM$.asObservable()}getCurrentOrganizationUserIAM(){return this.currentOrganizationUserIAM$.value}mergeOrganizationAndDocumentContacts(){try{let e=[];this.getContactListScopeForOrganizationUsers().includes(Hi.ALL)?e=[...this.getUserOrganizationContacts(),...this.getUserFolderContacts(),...this.getUserDocumentContacts()]:this.getContactListScopeForOrganizationUsers().includes(Hi.ORGANIZATION)?e=[...this.getUserOrganizationContacts()]:this.getContactListScopeForOrganizationUsers().includes(Hi.FOLDER)?e=[...this.getUserFolderContacts()]:this.getContactListScopeForOrganizationUsers().includes(Hi.DOCUMENT)&&(e=[...this.getUserDocumentContacts()]);let t=[...new Map(e.filter(r=>r?.userId).map(r=>[r.userId,r])).values()];this.internalUserContacts$.next(t)}catch(e){this.loggingService.catch("Error in ContactService mergeOrganizationAndDocumentContacts: ",e)}}getOrganizationGroupsFromDb$(){try{this.getOrganizationGroupsSubscription||(this.getOrganizationGroupsSubscription=this.authService.getUser$().pipe(he(e=>e?.organizationId?se(e).pipe(he(t=>this.docService.getOrganizationConfig$().pipe(Le(r=>!!r),ce(()=>t))),he(t=>{if(this.setUserOrganizationGroups([]),!t)return se();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([])})):se()})):(this.setUserOrganizationGroups([]),se()))).subscribe(()=>{},e=>{this.loggingService.catch("Error in ContactService getOrganizationGroupsFromDb$ subscription: ",e)}))}catch{}}setUserOrganizationGroups(e){try{this.userOrganizationGroups$.next(e)}catch(t){this.loggingService.catch("Error in ContactService setUserOrganizationGroups: ",t)}}onContactSelected(e){try{if(e?.userId){let t=!!this.getUserDocumentContacts().find(a=>a.userId===e.userId),r=!!this.getUserOrganizationContacts().find(a=>a.userId===e.userId);switch(this.documentAccessType){case yi.RESTRICTED:if(!t){let a={contact:e,isOrganizationContact:r,isDocumentContact:t,documentAccessType:this.documentAccessType};this.onContactSelectedSubject$.next(a)}break}}else{let t={contact:e,isOrganizationContact:!1,isDocumentContact:!1,documentAccessType:this.documentAccessType};this.onContactSelectedSubject$.next(t)}}catch(t){this.loggingService.catch("Error in ContactService onContactSelected: ",t)}}onContactSelected$(){return this.onContactSelectedSubject$.asObservable()}getOrganizationGroups$(){return this.getContactListScopeForOrganizationUsers$().pipe(he(()=>this.checkContactListScopeForOrganizationUsers([Hi.ALL,Hi.ORGANIZATION_USER_GROUP])?this.userOrganizationGroups$.asObservable():se([])))}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(t){this.loggingService.catch("Error in ContactService setAtHereLabel: ",t)}}setAtHereDescription(e){try{this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{atHereDescription:e}}),e&&this.atHereDescription$.next(e)}catch(t){this.loggingService.catch("Error in ContactService setAtHereDescription: ",t)}}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(he(()=>this.checkContactListScopeForOrganizationUsers([Hi.ALL,Hi.DOCUMENT])?this.atHereEnabled$.asObservable():se(!1)))}getAtHereEnabled(){return this.checkContactListScopeForOrganizationUsers([Hi.ALL,Hi.DOCUMENT])?this.atHereEnabled$.value:!1}updateContactListScopeForOrganizationUsers(e){try{this.contactListScopeForOrganizationUsers$.next(e)}catch(t){this.loggingService.catch("Error in ContactService updateContactListScopeForOrganizationUsers: ",t)}}getContactListScopeForOrganizationUsers$(){return this.contactListScopeForOrganizationUsers$.asObservable()}getContactListScopeForOrganizationUsers(){return this.contactListScopeForOrganizationUsers$.value}checkContactListScopeForOrganizationUsers(e){return this.getContactListScopeForOrganizationUsers().some(t=>e.includes(t))}updateContactList(e,t){return Q(this,null,function*(){try{if(this.analyticsService.trackEvent(Z.Events.Contact.UPDATE_CONTACT_LIST_TRIGGERED,{contactsCount:e?.length,config:t}),this.usersService?.userDataProviderAvailable()){let r=e.map(s=>s?.userId).filter(s=>s);yield this.usersService.resolveUsers({userIds: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(t)}catch(r){this.loggingService.catch("Error in CommentService updateContactList: ",r)}})}convert(e){try{if(e?.options){let{documentId:t,organizationId:r}=this.docService.getServerId(e?.options);e.options=T(I({},e?.options),{documentId:t,organizationId:r})}return this}catch(t){return this.loggingService.catch("Error in ContactService convert: ",t),this}}getContactList$(){try{return this.authService.getUser$().pipe(he(e=>e?Sn([this.userOrganizationContacts$.asObservable(),this.userFolderContacts$.asObservable(),this.userDocumentContacts$.asObservable(),this.userOrganizationGroups$.asObservable(),this.customUserContacts$.asObservable()]).pipe(ce(([t,r,a,s,c])=>{let p={};p.organizationUsers=t?.map(C=>this.convertToClientUser(C)),p.folderUsers=r?.map(C=>this.convertToClientUser(C)),p.documentUsers=a?.map(C=>this.convertToClientUser(C)),p.updatedContactList=c?.map(C=>this.convertToClientUser(C));let u=[];return s?.forEach(C=>{let E=this.convertToClientUserGroup(C,p.organizationUsers||[]);E&&u.push(E)}),p.userGroups=u,p}),Et(mn)):se(null)),kn(e=>(this.loggingService.catch("Error in ContactService getContactList$: ",e),se(null))))}catch(e){return this.loggingService.catch("Error in ContactService getContactList$: ",e),se(null)}}convertToClientUserGroup(e,t){try{let r={groupId:e?.metadata?.clientGroupId,groupName:e?.metadata?.groupName,users:[]},a={};return t?.forEach(s=>{if(s?.userId){let c=bt(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(t){return this.loggingService.catch("Error in ContactService convertToClientUser: ",t),e}}getCustomUserContacts(){return this.customUserContacts$.value}getCustomUserContacts$(){return this.customUserContacts$.asObservable()}getCustomUserContactsConfig(){return this.customUserContactsConfig$.value}getCustomUserContactsConfig$(){return this.customUserContactsConfig$.asObservable()}};o.\u0275fac=function(t){return new(t||o)(ee(et),ee(Ve),ee(Ft),ee(Dn),ee(at),ee(y),ee(pn),ee(Vn))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var qce=i=>{try{return i.name.split(".").slice(0,-1).join(".")}catch(o){ot.catch("Error in File utils getFileName: ",o);return}},Dz=i=>{try{return/(?:\.([^.]+))?$/.exec(i?.name)[1]}catch(o){ot.catch("Error in File utils getFileExtension: ",o);return}},Yce=(i,o)=>{try{let n=i.slice(0,-1,i.type);return new File([n],o+"."+Dz(i),{type:i.type})}catch(n){ot.catch("Error in File utils updateFile: ",n);return}},Kce=i=>new Promise((o,n)=>{let e=new FileReader;e.readAsDataURL(i),e.onload=()=>{o(e.result)},e.onerror=t=>{n(t)}}),Zce={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 sg=(()=>{let o=class o{constructor(e,t,r,a){this.authService=e,this.configService=t,this.loggingService=r,this.attachmentResolverService=a,this.storage=mS();try{this.configService.getApiKey$().subscribe(s=>{this.apiKey=s}),this.authService.getFirebaseConfig$().subscribe(s=>{s&&s.firebaseOptions?.storageBucket&&(this.storage=mS(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:t}){try{let r=new d0;r.name=t.name;let a=Yce(t,`${r.attachmentId}_${qce(t)}`),s=`${this.apiKey}/${e}/${a?.name}`;return r.bucketPath=s,r.size=t.size,r.type=Dz(t),r?.type&&(r.mimeType=Zce[r?.type]),r}catch(r){return this.loggingService.catch("Error in StorageService createAttachment: ",r),null}}uploadAttachmentToStorage({attachment:e,file:t,resolve:r,reject:a}){try{let s=pS(this.storage,e.bucketPath),c=dU(s,t,{cacheControl:"public,max-age=3600"});c.on("state_changed",p=>{let u=p.bytesTransferred/p.totalBytes*100},p=>{a(p)},()=>{cU(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 Q(this,arguments,function*({file:e,attachment:t,metadata:r,resolve:a,reject:s}){try{r.attachmentId=t.attachmentId;let p={attachmentId:t.attachmentId,name:t.name,file:e,metadata:r,mimeType:t.mimeType},u=yield this.attachmentResolverService.saveAttachment({attachment:p,eventType:os.ATTACHMENT_ADD});u&&u.data?.url?(t.url=u.data?.url,a(t)):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:t,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:t});if(!p)throw new Error("Attachment not created");r?this.uploadToResolver({file:t,attachment:p,metadata:a,resolve:s,reject:c}):this.uploadAttachmentToStorage({attachment:p,file:t,resolve:s,reject:c})}catch(p){this.loggingService.catch("Error in StorageService uploadFile:",p),c(p)}})}uploadChunk(e,t,r){return new Promise((a,s)=>{try{if(this.apiKey){let c=`${this.apiKey}/${e}/${t.name}`,p=pS(this.storage,c),u=dU(p,t,{cacheControl:"public,max-age=3600"});u.on("state_changed",C=>{let E=C.bytesTransferred/C.totalBytes*100},C=>{s(C)},()=>{cU(u.snapshot.ref).then(C=>{a(C)}).catch(C=>{this.loggingService.catch(`[uploadChunk] Error getting download URL for chunk ${r}:`,C),s(C)})})}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 t=new XMLHttpRequest;t.responseType="blob",t.onload=()=>{let r=t.response,a=document.createElement("a"),s=window.URL.createObjectURL(r);a.setAttribute("type","hidden"),a.setAttribute(j.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()},t.onerror=()=>{window.open(e.url,"_blank")},t.open("GET",e.url),t.send()}}catch(t){this.loggingService.catch("Error in StorageService downloadAttachment: ",t)}}deleteAttachment({attachment:e,metadata:t,useAttachmentResolver:r}){return new Promise((a,s)=>{if(r)this.attachmentResolverService.deleteAttachment({attachmentId:e.attachmentId,metadata:t}).then(()=>{a(null)}).catch(c=>{s(c)});else{let c=pS(this.storage,e.bucketPath);lU(c).then(()=>{a(null)}).catch(p=>{a(null)})}})}deleteFileFromPath(e){return new Promise((t,r)=>{let a=pS(this.storage,e);lU(a).then(()=>{t(null)}).catch(s=>{r(s)})})}};o.\u0275fac=function(t){return new(t||o)(ee(Ve),ee(Ft),ee(y),ee(rg))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var vn=(()=>{let o=class o{constructor(e,t,r,a,s,c,p,u){this.analyticsService=e,this.authService=t,this.contactService=r,this.databaseService=a,this.docService=s,this.configService=c,this.loggingService=p,this.commonDbService=u,this.documentIAM$=new ve(null),this.workspaceIAM$=new ve(null),this.roles$=new ve([]),this.getDocumentIamSubscription=null,this.getOrganizationIamSubscription=null,this.getWorkspaceIamSubscription=null;try{this.authService.setIamService(this),this.databaseService.getDb().pipe(Le(C=>!!C),st(1)).subscribe(C=>{C&&(this.getUser(),this.getDocumentPaths())},C=>{this.loggingService.catch("Error in CommentService getDb subscription: ",C)}),this.getRole$().pipe(st(1)).subscribe(C=>{this.authService?.getUser()&&!C&&this.analyticsService.trackEvent(Z.Events.Iam.USER_ACCESS_DENIED)}),this.documentIAM$.subscribe(C=>{C?.accessType&&this.contactService.setDocumentAccessType(C.accessType)})}catch(C){this.loggingService.catch("Error in IamService constructor: ",C)}}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(Le(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(Le(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 t=e||new mk;this.documentIAM$.next(t)},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(kn(e=>se(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),Et())}getDocumentIAM$(){return this.documentIAM$.asObservable()}getRoles$(){return this.roles$.asObservable().pipe(ce(e=>e?.length?e:j.WorkspaceRoles))}getFeaturesAccessLevel$(){return this.documentIAM$.asObservable().pipe(ce(e=>e?.features),he(e=>this.getRole$().pipe(ce(t=>(t===vo.ADMIN&&(e=e&&JSON.parse(JSON.stringify(e||{})),e?.all?.disabled&&(e.all.disabled=!1)),e)))))}hasRole(e){try{return e===this.getRole()}catch(t){return this.loggingService.catch("Error in IamService hasRole: ",t),!1}}hasRoleAny(e=[]){try{return e?.includes(this.getRole()||"")}catch(t){return this.loggingService.catch("Error in IamService hasRoleAny: ",t),!1}}hasRole$(e){try{return this.authService.getUser$().pipe(he(()=>this.documentIAM$.pipe(Le(t=>!!t),he(()=>this.workspaceIAM$.pipe(ce(()=>e===this.getRole()))))))}catch(t){return this.loggingService.catch("Error in IamService hasRole$: ",t),se(!1)}}getRole$(){try{return this.authService.getUser$().pipe(he(()=>this.configService.getSF$()),he(()=>this.configService.getSF()?this.contactService.isUserGlobalContact$():se(null)),he(()=>this.documentIAM$.pipe(Le(e=>!!e))),he(()=>this.workspaceIAM$),ce(()=>this.getRole()))}catch(e){return this.loggingService.catch("Error in IamService getRole$: ",e),se(null)}}getRole(){try{let e=this.configService.getSF();if(e&&this.contactService.isUserGlobalContact())return vo.ADMIN;if(!e&&this.user?.isAdmin)return vo.ADMIN;let t=null,r;if(this.user)switch((this.documentIAM$.value?this.documentIAM$.value?.features?.all?.restricted:!1)?yi.RESTRICTED:this.documentIAM$.value?this.documentIAM$.value?.documentAccessType||yi.PUBLIC:null){case yi.PUBLIC:r=this.getUserFromDocumentIAM(this.user?.email,this.user?.userId),r||(r=this.getUserFromWorkspaceIAM(this.user?.email,this.user?.userId)),t=r?.role?.name||vo.COMMENTER;break;case yi.RESTRICTED:r=this.getUserFromDocumentIAM(this.user?.email,this.user?.userId),r||(r=this.getUserFromWorkspaceIAM(this.user?.email,this.user?.userId)),t=r?.role?.name||null;break;default:break}return t}catch(e){this.loggingService.catch("Error in IamService getRole: ",e)}return null}isUserAdmin$(){return this.getRole$().pipe(ce(e=>e===vo.ADMIN),Et())}isUserAdmin(){try{return this.getRole()===vo.ADMIN}catch(e){return this.loggingService.catch("Error in IamService isUserAdmin: ",e),!1}}getUserFromDocumentIAM(e,t){try{if(e||t){let r;return e&&(r=this.documentIAM$.value?.users?.[bt(e)]),!r&&t&&(r=this.documentIAM$.value?.users?.[bt(t)]),r}else return}catch(r){this.loggingService.catch("Error in IamService getUserFromDocumentIAM: ",r)}}getUserFromWorkspaceIAM(e,t){try{if(e||t){let r;return e&&(r=this.workspaceIAM$.value?.users?.[bt(e)]),!r&&t&&(r=this.workspaceIAM$.value?.users?.[bt(t)]),r}else return}catch(r){this.loggingService.catch("Error in IamService getUserFromWorkspaceIAM: ",r)}}};o.\u0275fac=function(t){return new(t||o)(ee(et),ee(Ve),ee(xi),ee(Dn),ee(at),ee(Ft),ee(y),ee(pn))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var gn=(()=>{let o=class o{constructor(e,t,r,a,s,c,p,u,C,E,D,L,z,W,J,ue){this.afAuth=e,this.analyticsService=t,this.authService=r,this.configService=a,this.commonDbService=s,this.commonDbUtilsService=c,this.commentUtilsService=p,this.commentAnnotationsResolverService=u,this.databaseService=C,this.docService=E,this.domService=D,this.iamService=L,this.loggingService=z,this.notificationUtilsService=W,this.usersService=J,this.functions=ue,this.db=ts(),this.notificationsDb=ts(void 0,oi.firebaseNotificationsDatabaseURL),this.documentPaths=null,this.notifications$=new ve([]),this.rawNotificationsByIdMap$=new ve(new Map),this.processedNotifications$=new ve([]),this.readNotificationsOnForYouTab$=new ve(!1),this.notificationViews$=new ve({}),this.notificationsByIdMap$=new ve(new Map),this.historyPanelVisible$=new ve(!1),this.notificationsForYou$=new ve(null),this.notificationsByDocumentIdMap$=new ve(null),this.notificationsByDocumentIdSubscription={},this.allowedDocumentMetadataMap$=new ve(null),this.maxNotificationDays$=new ve(15),this.tabConfig$=new ve({people:{enable:!1}}),this.settingsConfig$=new ve(null),this.muteAllNotifications$=new ve(!1),this.enableSettings$=new ve(!1),this.selfNotifications$=new ve(!1),this.settingsInitialConfig$=new ve([{name:"Inbox",id:"inbox",default:"ALL",enable:!0,values:[{name:"All",id:"ALL"},{name:"Only Involved",id:"MINE"},{name:"None",id:"NONE"}]},{name:"Email",id:"email",default:"MINE",enable:!0,values:[{name:"All",id:"ALL"},{name:"Only Involved",id:"MINE"},{name:"None",id:"NONE"}]}]),this.notificationsPanelVisible$=new ve(!1);try{this.subscribeNotificationsData().subscribe(),this.commentUtilsService.setNotificationService(this),this.databaseService.getDb().pipe(Le(ye=>!!ye),st(1)).subscribe(ye=>{ye&&(this.db=ye,this.getDocumentIds(),this.subscribeGetNotificationsForYou())},ye=>{this.loggingService.catch("Error in NotificationService getDb subscription: ",ye)}),this.authService.getUser$().subscribe(ye=>{ye?(this.subscribeGetNotificationsForYou(),this.getDocumentIds(),this.subscribeToUserSettings()):(Object.keys(this.notificationsByDocumentIdSubscription).forEach(Ae=>{this.notificationsByDocumentIdSubscription[Ae]?.unsubscribe()}),this.notificationForYouSubscription?.unsubscribe(),this.documentIdsSubscription?.unsubscribe(),this.resetCacheData())}),this.docService.getLocationMetadata$().subscribe(ye=>{if(ye){let Ae=this.notificationsByDocumentIdMap$.getValue()?JSON.parse(JSON.stringify(this.notificationsByDocumentIdMap$.getValue())):null;Object.keys(ye||{}).forEach(He=>{let Fe=Ae?.[He]?.notifications;Fe?.length&&Fe.forEach(xe=>{this.notificationUtilsService.mergeLocationWithNotification({notification:xe},ye)?.notification})}),this.notificationsByDocumentIdMap$.next(Ae)}})}catch(ye){this.loggingService.catch("Error in NotificationService constructor: ",ye)}}setDBConfigDataToInitialConfig(e){try{let t=JSON.parse(JSON.stringify(this.settingsConfig$.getValue()??{}));Object.entries(e||{}).forEach(([r,a])=>{t[r]=a}),this.settingsConfig$.next(t)}catch(t){this.loggingService.catch("Error in NotificationService setDBConfigDataToInitialConfig: ",t)}}getInitialConfigFromDB(e){return Q(this,null,function*(){try{this.loggingService.log("%c[WB] Calling NotificationService FUNCTION: getInitialConfigFromDB","color: green;");let t=bt(this.authService.getUser()?.userId??""),r=yield this.commonDbService.getData({feature:"userConfig",properties:{useCollectionGroup:!1,isCollection:!1,documentId:e?.documentId,userId:t}});if(r?.notificationsConfig)this.setDBConfigDataToInitialConfig(r?.notificationsConfig);else{this.setSettingsInitialConfig(this.settingsInitialConfig$.getValue());let a={};this.settingsInitialConfig$.getValue().forEach(c=>{if(c.enable){let p=c?.values?.find(u=>u.id===c.default);a[c.id]=p||c?.values?.[0]||{id:"NONE",name:"None"}}});let s={};Object.keys(a).forEach(c=>{s[c]=a[c].id}),yield this.updateSettingsConfigToDb(s)}}catch(t){this.loggingService.catch("Error in NotificationService getInitialConfigFromDB: ",t)}})}subscribeToUserSettings(){try{this.loggingService.log("%c[WB] Calling NotificationService FUNCTION: subscribeToUserSettings","color: green;"),this.userSettingsSubscription&&this.userSettingsSubscription.unsubscribe();let e=bt(this.authService.getUser()?.userId??"");this.userSettingsSubscription=this.enableSettings$.pipe(Le(t=>t===!0),he(()=>this.docService.getDocumentPaths$().pipe(Le(t=>!!t),he(t=>Zi(this.getInitialConfigFromDB(t)).pipe(he(()=>this.commonDbService.dbListener({feature:"userConfig",properties:{useCollectionGroup:!1,isCollection:!1,documentId:t?.documentId,userId:e}}).pipe(ce(r=>{r?.data?.notificationsConfig&&!wi(r?.data?.notificationsConfig??{},this.settingsConfig$.getValue()??{})&&this.setDBConfigDataToInitialConfig(r?.data?.notificationsConfig)})))))))).subscribe()}catch(e){this.loggingService.catch("Error in NotificationService subscribeToUserSettings: ",e)}}resetCacheData(){try{this.loggingService.log("%c[WB] Calling NotificationService FUNCTION: resetCacheData","color: green;"),this.notificationsByDocumentIdMap$.next(null),this.notificationsForYou$.next(null),this.settingsConfig$.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(t){this.loggingService.catch("Error in NotificationService setCommentService: ",t)}}getDocumentIds(){try{this.documentIdsSubscription&&this.documentIdsSubscription.unsubscribe(),this.documentIdsSubscription=this.selfNotifications$.pipe(dn(()=>{this.notificationsByDocumentIdMap$.next(null)}),he(()=>this.getDocumentIdsByLastNotificationTimestamp().pipe(Bi(),ce(([e,t])=>{let r=e?.map(u=>u.documentId),a=t?.map(u=>u.documentId),s=r?.filter(u=>!a?.includes(u)),c=a?.map(u=>({documentId:u,timestamp:t?.find(C=>C.documentId===u)?.timestamp})).filter(u=>!r?.includes(u.documentId)),p=a?.map(u=>{let C=t?.find(E=>E.documentId===u)?.timestamp;return{documentId:u,timestamp:C}}).filter(u=>{let C=e?.find(E=>E.documentId===u.documentId)?.timestamp;return C&&u.timestamp&&C!==u.timestamp});c?.length&&this.fetchNotificationsForDocumentIds(c),p?.length&&this.fetchNotificationsForDocumentIds(p,1),s?.forEach(u=>{this.removeNotificationsForDocumentId(u)}),t&&!t?.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(he(t=>this.docService.getOrganizationConfig$().pipe(ce(r=>{let a=null,s=this.configService.getApiKey(),c=r?.organizationId||t?.organizationId;return s&&c&&(a=new Ud({apiKey:s,organizationId:c})),{user:t,documentPaths:a}}))),he(t=>{let{user:r,documentPaths:a}=t;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:[Zn(lt("timestamp",">=",p)),fi("timestamp","desc"),c0(e)]}}).pipe(ce(u=>u?.data),ce(u=>{let C=[];return Object.keys(u||{}).forEach(E=>{let D=this.commonDbService.shouldUseFirestore()?u[E]?.timestamp??0:u[E],L=this.commonDbService.shouldUseFirestore()?u[E]?.deletedNotification??!1:!1;if(L&&L.id&&L?.timestamp===D){let z=L.id,W=u[E]?.metadata?.documentId,J=JSON.parse(JSON.stringify(this.notificationsByDocumentIdMap$.getValue()??{})),ue=J?.[W]??{documentMetadata:null,notifications:[]},ye=ue.notifications??[],Ae=ye?.findIndex(He=>He.id===z);Ae!==-1&&(ye.splice(Ae,1),this.notificationsByDocumentIdMap$.next(T(I({},J),{[W]:T(I({},ue),{notifications:ye})})))}C.push({documentId:E,timestamp:D})}),C}),kn(u=>(this.loggingService.catch("Error in NotificationService getDocumentIdsByLastNotificationTimestamp: ",u),se([]))))}return se(null)}))}catch(t){return this.loggingService.catch("Error in NotificationService getDocumentIdsByLastNotificationTimestamp: ",t),se([])}}fetchNotificationsForDocumentIds(e,t=15){return Q(this,null,function*(){try{if(e?.length){let r=br(this.functions,Er({url:oi.cloudFunction.getNotificationsForDocuments,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:12e5}),a=this.docService.getOrganizationConfig()?.organizationId??"",s=this.getStartAtTimestamp(),c={};e.forEach(L=>{if(L?.documentId){let z=this.getAllowedDocumentMetadataByDocumentId(L.documentId);z&&(c[L.documentId]=z)}});let p={organizationId:a,documentIds:e,timestamp:s,limitToLast:t,documentMetadataByDocumentId:c,selfNotifications:this.selfNotifications$.value},u=yield this.notificationUtilsService.handleNotificationEncryption({data:p}),C=(yield r({veltData:u}))?.data?.data?.veltData||{},E="notificationwithdocumentidstoencryptanddecryptonsdk"+(this.authService.getUser()?.userId??""),D=yield Qre(C,E);if(D&&typeof D=="object"){let L=this.usersService.userDataProviderAvailable(),z=this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable(),W=[],J=[];Object.keys(D).forEach((ue,ye)=>{let Ae=D[ue].documentMetadata;if(Ae){let Fe=this.allowedDocumentMetadataMap$.value||{};(!Fe?.[ue]||!wi(Fe?.[ue],Ae))&&this.allowedDocumentMetadataMap$.next(T(I({},Fe),{[ue]:Ae}))}let He=D[ue].notifications||[];He.forEach(Fe=>{Fe.notification=this.getClientNotificationObject(Fe)}),this.setNotificationForDocumentIdInCache(ue,Ae,He),L&&W.push(this.commonDbUtilsService.formatResponse({feature:"allDocNotifications",data:He,shouldAwait:!0,forceResolve:!0})),z&&J.push(this.commonDbUtilsService.formatResponse({feature:"allDocNotifications",data:He,shouldCommentAnnotationsResolverAwait:!0}))}),L&&Promise.all(W).then(()=>{Object.keys(D).forEach(ue=>{let ye=D?.[ue]?.documentMetadata||{},Ae=this.commonDbUtilsService.mergeUsersWithData({feature:"allDocNotifications",data:D?.[ue]?.notifications||[]});Ae.forEach(He=>{He.notification=this.getClientNotificationObject(He)}),this.setNotificationForDocumentIdInCache(ue,ye,Ae)})}),z&&Promise.all(J).then(()=>{Object.keys(D).forEach(ue=>{let ye=D?.[ue]?.documentMetadata||{},Ae=D?.[ue]?.notifications?.reduce((He,Fe)=>(He[Fe.notificationId]=Fe,He),{});Ae=this.commonDbUtilsService.mergeCommentAnnotationsWithData({feature:"allDocNotifications",data:Ae}),Ae=Object.values(Ae??{}),Ae.forEach(He=>{He.notification=this.getClientNotificationObject(He)}),this.setNotificationForDocumentIdInCache(ue,ye,Ae)})})}}}catch(r){return this.loggingService.catch("Error in NotificationService fetchNotificationsForDocumentIds: ",r),[]}})}setNotificationForDocumentIdInCache(e,t,r,a){try{let s=this.docService.getOrganizationConfig()?.organizationId??"",c=this.docService.getOrganizationMetadata(s);t||(t=JSON.parse(JSON.stringify(this.docService.getDocumentMetadata()||{}))),c||(c=JSON.parse(JSON.stringify(this.docService.getOrganizationMetadata(s)||{})));let p=this.notificationsByDocumentIdMap$.getValue(),u=p?.[e]?.notifications||[],C=this.docService.getLocationMetadatas(),E=r?.map(z=>{let W=z.notification;return W.metadata&&(W.metadata.documentName=t?.documentName||W.metadata.documentName,W.metadata.organizationMetadata=c||W.metadata.organizationMetadata,W.metadata.documentMetadata=t||W.metadata.documentMetadata),C&&(W=this.notificationUtilsService.mergeLocationWithNotification({notification:W},C)?.notification),W})?.filter(z=>!!z)||[],D=new Map(u.map(z=>[z.id,z]));E.forEach(z=>{D.set(z.id,z)});let L=Array.from(D.values()).sort((z,W)=>(W.timestamp||0)-(z.timestamp||0));this.notificationsByDocumentIdMap$.next(T(I({},p),{[e]:{notifications:L,documentMetadata:t}}))}catch(s){this.loggingService.catch("Error in NotificationService setNotificationForDocumentIdInCache: ",s)}}removeNotificationsForDocumentId(e){try{this.notificationsByDocumentIdSubscription[e]&&this.notificationsByDocumentIdSubscription[e].unsubscribe();let t=this.notificationsByDocumentIdMap$.getValue();delete t?.[e],this.notificationsByDocumentIdMap$.next(t)}catch(t){this.loggingService.catch("Error in NotificationService removeNotificationsForDocumentId: ",t)}}getNotificationsForDocumentId$(e,t=50){try{return this.authService.getUser$().pipe(ce(r=>({user:r})),he(r=>this.maxNotificationDays$.pipe(ce(()=>r))),he(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 u=c.getTime();return Zi(this.commonDbService.queryData({feature:"allDocNotifications",properties:{rtdbQuery:[Lu("timestamp"),Vu(u),LV(t)],firestoreQuery:[fi("timestamp","desc"),lt("timestamp",">=",u),lt("notification.actionUser.userId","!=",a.userId),c0(t)],apiKey:s,organizationId:this.docService?.getDocumentPaths()?.organizationId||a?.organizationId,documentId:e}})).pipe(he(C=>this.commonDbUtilsService.mergeUsersWithData$({feature:"allDocNotifications",data:{data:C,operation:null}})),ce(C=>C?.data??[]),ce(C=>(C.sort((E,D)=>D.timestamp-E.timestamp),C)),kn(C=>(this.loggingService.catch("Error in NotificationService getNotificationsForDocumentId: ",C),se([]))),ce(C=>(C.forEach(E=>{E.notification=this.getClientNotificationObject(E)}),C)))}return se([])}))}catch(r){return this.loggingService.catch("Error in NotificationService getNotificationsForDocumentId: ",r),se([])}}getStartAtTimestamp(){try{let e=new Date,t=this.maxNotificationDays$.getValue()>0?this.maxNotificationDays$.getValue():15;return e.setDate(e.getDate()-t),e.getTime()}catch(e){return this.loggingService.catch("Error in NotificationService getStartAtTimestamp: ",e),0}}getNotificationsForYou(){try{return this.databaseService.getDb().pipe(he(e=>this.authService.getUser$().pipe(ce(t=>({db:e,user:t})))),he(e=>this.maxNotificationDays$.pipe(ce(()=>e))),he(e=>{let{db:t,user:r}=e,a=this.configService.getApiKey();if(t&&r?.organizationId&&a){let s=bt(r?.userId),c=new Date,p=this.maxNotificationDays$.getValue()>0?this.maxNotificationDays$.getValue():15;c.setDate(c.getDate()-p);let u=c.getTime();return this.commonDbService.dbListener({feature:"allUserNotifications",properties:{useQuery:!0,isCollection:!0,rtdbQuery:[Lu("timestamp"),Vu(u),LV(50)],firestoreQuery:[fi("timestamp","desc"),lt("timestamp",">=",u),lt("notification.actionUser.userId","!=",r.userId),c0(50)],apiKey:a,organizationId:this.docService?.getDocumentPaths()?.organizationId||r?.organizationId,documentId:this.docService.getDocumentPaths()?.documentId,userId:s}}).pipe(he(C=>C?.data?se(C).pipe(ce(E=>E?.data),ce(E=>{let D=Object.values(E||{});return D.forEach(z=>{z.notification=this.getClientNotificationObject(z)}),D.sort((z,W)=>W.timestamp-z.timestamp),D.map(z=>z.notification).filter(z=>!!z)}),he(E=>{let D={data:E?.reduce((L,z)=>(L[z.id]={notification:z},L),{}),operation:null};return this.commonDbUtilsService.mergeLocationMetadataWithData$({data:D,feature:"allUserNotifications"}).pipe(ce(L=>Object.values(L?.data||{}).map(z=>z?.notification)))})):se(null)))}return se(null)}),he(e=>{let t=this.docService.getOrganizationConfig()?.organizationId??"";return this.docService.getOrganizationMetadata$(t).pipe(ce(()=>e))}),he(e=>this.allowedDocumentMetadataMap$.pipe(ce(()=>e))),ce(e=>(e?.length&&(e=e.map(t=>{if(t?.metadata){let r=this.docService.getOrganizationConfig()?.organizationId??"",a=this.getAllowedDocumentMetadataByDocumentId(t.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)||{}))),t.metadata.documentName=a?.documentName||t.metadata.documentName,t.metadata.organizationMetadata=s||t.metadata.organizationMetadata,t.metadata.documentMetadata=a||t.metadata.documentMetadata}return t})),e===null?this.notificationsForYou$.next(null):e?.length?this.notificationsForYou$.next(JSON.parse(JSON.stringify(e))):this.notificationsForYou$.next([]),se(e))))}catch(e){return this.loggingService.catch("Error in NotificationService getNotificationsForYou: ",e),se({})}}subscribeNotificationsData(e,t){this.loggingService.log("%c[WB] Calling FUNCTION: subscribeViewsData","color: green;");let r,a;try{if(e&&(a=En(e)),t&&typeof t=="object"){let s=Yo(t);r=En(JSON.stringify(s))}}catch(s){this.loggingService.catch("Error in ViewsService subscribeViewsData: ",s)}return ei(this.afAuth).pipe(Le(s=>!!s),he(s=>this.isFeatureAllowed({firebaseUser:s})),he(s=>s.featureAllowed?this.iamService.isUserAllowed$().pipe(ce(c=>(s.featureAllowed=c,s))):se(s)),he(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(),se([])):se(s).pipe(he(c=>this.docService.getDocumentPaths$().pipe(ce(p=>(this.documentPaths=p,c.documentPaths=p,c)))),he(c=>this.getDataFromDocumentId(a)))))}isFeatureAllowed(e){return this.configService.getConfig$().pipe(Le(t=>!!t),ce(t=>T(I({},e),{config:t})),he(t=>this.authService.getUser$().pipe(ce(r=>T(I({},t),{user:r})))),he(t=>ro(t.config,t.user,Re.NOTIFICATION)?se(T(I({},t),{featureAllowed:!0})):(this.loggingService.warn("Notification feature is not allowed."),se(T(I({},t),{featureAllowed:!1})))))}getDataFromDocumentId(e){return this.databaseService.getDb().pipe(Le(t=>!!t),he(t=>{if(this.db=t,this.loggingService.log(this.db),this.configService?.getApiKey()&&this.documentPaths?.views){let r=`${this.configService.getApiKey()}`;this.documentPaths?.organizationId&&(r+=`/${j.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${this.documentPaths.organizationId}`);let a=qi(this.db,`${e?r+"/"+j.FIREBASE_PARTIAL_PATH_DOCS+"/"+e+"/"+j.FIREBASE_PARTIAL_PATH_VIEWS+"/":this.documentPaths?.notifications}`);return U6(a).pipe(kn(s=>(this.loggingService.catch("Error in NotificationService getDataFromDocumentId: ",s),se(null))),ce(s=>{let c=[],p=new Map;s?.raw&&(Object.keys(s?.raw||{}).forEach(C=>{let E=s?.raw[C];E?.id&&c.push(E)}),c.forEach(C=>{C.id&&p.set(C.id,C)})),this.notifications$.next(c),this.rawNotificationsByIdMap$.next(p);let u=[];s?.processed&&Object.keys(s?.processed||{}).forEach(C=>{let E=s?.processed[C];E?.id&&u.push(E)}),this.processedNotifications$.next(u),this.setNotificationsByIdMap()}))}else return se(null)}))}setNotificationsByIdMap(){try{let e=this.authService.getUser();if(e){let t=this.notificationViews$.getValue(),r;e?.email&&(r=bt(e?.email));let a;e?.userId&&(a=bt(e?.userId));let s=new Map;this.processedNotifications$.getValue().forEach(p=>{if(p.id&&p?.displayHeadlineMessageTemplate){let u=!1;(r&&p.notifyUsers?.[r]||a&&p.notifyUsers?.[a])&&(u=!0);let C={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:u,notificationSourceData:p.notificationSourceData},E=this.getRawNotificationById(C.id);if(E?.metadata&&(C.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}),C?.notificationSource==="comment"&&C?.targetAnnotationId){let D=this.commentService?.getAnnotationById(C.targetAnnotationId);D||E?.annotationData&&(D=E.annotationData),D&&(C.notificationSourceData=Gn(D))}s.set(p.id,C)}}),s.forEach((p,u)=>{p.isUnread=p?.actionUser?.userSnippylyId!==e?.userSnippylyId&&!t?.notification?.[u]?.views?.[e?.userSnippylyId],s.set(u,p)}),this.notificationsByIdMap$.next(s)}}catch(e){this.loggingService.catch("Error in NotificationService setNotificationsByIdMap: ",e)}}getClientNotificationObject({processed:e,raw:t,metadata:r,views:a,notification:s}){try{let c=this.authService.getUser(),p=s||e;if(p.id&&p?.displayHeadlineMessageTemplate&&c){let u=null;c?.email&&(u=bt(c?.email));let C=null;c?.userId&&(C=bt(c?.userId));let E=!1,D=!0;(u&&p.notifyUsers?.[u]||C&&p.notifyUsersByUserId?.[C])&&(E=!0),C&&a?.[C]&&(D=!1);let L={id:p.id};if(s?L=T(I(I({},L),s),{displayHeadlineMessage:this.getNotificationHeadlineMessage(s),displayBodyMessage:this.getNotificationBodyMessage(s),forYou:E,isUnread:D}):L={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},L?.notificationSource==="comment"&&L?.targetAnnotationId){let z=this.commentService?.getAnnotationById(L.targetAnnotationId);z||s?.notificationSourceData&&(z=s?.notificationSourceData),z||t?.annotationData&&(z=t.annotationData),z&&(L.notificationSourceData=Gn(z))}return t?.targetAnnotationData?.isCommentResolverUsed&&(L.isCommentResolverUsed=t?.targetAnnotationData?.isCommentResolverUsed),L}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(t=>{let r=e[t].notifications||[],a=r.filter(c=>c.isUnread).length,s=r.length>0&&r[0]?.timestamp||0;return{documentId:t,notifications:e[t]?.notifications,unreadNotificationsCount:a,latestNotificationTimestamp:s,documentMetadata:e[t]?.documentMetadata}}).filter(t=>t.notifications?.length>0).sort((t,r)=>r.latestNotificationTimestamp-t.latestNotificationTimestamp):null))}getAllNotifications$(){return this.getNotificationsByDocumentId$().pipe(ce(e=>{let t=null;return e?(t=[],e.forEach(r=>{r.notifications.forEach(a=>{t?.push(a)})}),t?.sort((r,a)=>a.timestamp-r.timestamp)):null}))}processNotificationData(e){try{let t=e?.annotationData?.metadata,r=this.docService.getOrganizationConfig()?.organizationId;e.metadata=JSON.parse(JSON.stringify(this.docService.getDocumentMetadata(t?.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(t?.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=t?.documentId?new Ud({apiKey:a,documentId:t.documentId,organizationId:t?.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(),u=this.notificationUtilsService.formatNotification(e,p);return JSON.parse(JSON.stringify(u))}catch(t){return this.loggingService.catch("Error in NotificationService processNotificationData: ",t),null}}updateNotificationDatabase(e){try{let t=qi(this.notificationsDb),r=this.processNotificationData(e);A6(t,JSON.parse(JSON.stringify(r)))}catch(t){this.loggingService.catch("Error in NotificationService updateNotificationDatabase: ",t)}}getRawNotifications$(){return this.notifications$.asObservable()}getProcessedNotifications$(){return this.processedNotifications$.asObservable()}getNotifications$(e){return this.authService.getUser$().pipe(he(t=>t?t.organizationId?this.getAllNotifications$().pipe(he(r=>this.notificationsForYou$.pipe(ce(a=>{if(r||a){let s=new Map;return(!e?.type||["all","documents"].includes(e.type))&&(r||[]).forEach(c=>{c.id&&s.set(c.id,c)}),(!e?.type||["all","forYou"].includes(e.type))&&(a||[]).forEach(c=>{c.id&&!s.has(c.id)&&s.set(c.id,c)}),Array.from(s.values()).sort((c,p)=>(p.timestamp||0)-(c.timestamp||0))}else return null})))):this.notificationsByIdMap$.asObservable().pipe(ce(r=>Array.from(r.values())),ce(r=>r.sort((a,s)=>s.timestamp-a.timestamp)),Kg()):se(null)),Et(mn))}getRawNotificationById(e){try{return this.rawNotificationsByIdMap$.getValue()?.get(e)}catch(t){this.loggingService.catch("Error in NotificationService getRawNotificationById: ",t);return}}setNotificationViews(e){try{this.notificationViews$.next(e),this.setNotificationsByIdMap()}catch(t){this.loggingService.catch("Error in NotificationService setNotificationViews: ",t)}}getNotificationHeadlineMessage(e){try{let t=this.authService.getUser();if(e?.displayHeadlineMessageTemplate&&e?.displayHeadlineMessageTemplateData){let r=e.displayHeadlineMessageTemplate,a=e.displayHeadlineMessageTemplateData,s=/\{(\w+)\}/g,c=r.replace(s,(p,u)=>(u==="actionUser"||u==="recipientUser")&&a[u]?t?.email&&a[u].email===t?.email||t?.userId&&a[u]?.userId===t?.userId?"You":a[u].name||a[u].email||' <velt-skeleton-loader width="50px" height="20px" border-radius="4px"></velt-skeleton-loader> ':a[u]?a[u]:p);return this.domService.sanitizeHtml(c)}return this.domService.sanitizeHtml(e.displayHeadlineMessageTemplate||"")}catch(t){return this.loggingService.catch("Error in NotificationService getNotificationHeadlineMessage: ",t),""}}getNotificationBodyMessage(e){try{if(e?.displayBodyMessageTemplate&&e?.displayBodyMessageTemplateData){let t=e?.displayBodyMessageTemplate;return e?.displayBodyMessageTemplateData&&e?.displayBodyMessageTemplateData?.users?.forEach(r=>{if(r?.userId){let a=this.usersService.getUserById(r?.userId);t=t?.replaceAll(`{{${r.userId}}}`,a?.name||a?.email||'<velt-skeleton-loader width="50px" height="20px" border-radius="4px"></velt-skeleton-loader>')}}),this.domService.sanitizeHtml(t)}return this.domService.sanitizeHtml(e.displayBodyMessage||"")}catch(t){return this.loggingService.catch("Error in NotificationService getNotificationBodyMessage: ",t),""}}setHistoryPanelVisibility(e,t=!1,r=!1){try{e?document.querySelector(j.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL)?this.historyPanelVisible$.next(e):this.loggingService.catch("Error in NotificationService setHistoryPanelVisibility: ",`<${j.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: ",`<${j.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`)}}toggleHistoryPanelVisibility(e=!1,t=!1){try{this.historyPanelVisible$.value?this.historyPanelVisible$.next(!this.historyPanelVisible$.value):document.querySelector(j.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: ",`<${j.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`)}catch{this.loggingService.catch("Error in NotificationService toggleHistoryPanelVisibility: ",`<${j.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`)}}getHistoryPanelVisibility$(){return this.historyPanelVisible$.asObservable()}setNotificationsAsRead(e){return Q(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(u=>u.id===a.id);p&&(p.isUnread=!1),r[s].notifications=c}}),this.notificationsByDocumentIdMap$.next(r)}}catch(t){this.loggingService.catch("Error in NotificationService setNotificationsAsRead: ",t)}})}setAllNotificationsAsRead(e){return Q(this,null,function*(){try{if(e?.tabId==="for-you"){let t=this.notificationsForYou$.value||[];this.setNotificationsAsRead(t)}else this.getNotifications$().pipe(st(1)).subscribe(t=>{t&&this.setNotificationsAsRead(t)})}catch(t){this.loggingService.catch("Error in NotificationService setAllNotificationsAsRead: ",t)}})}getUnreadNotificationsCount$(){try{return this.notificationsForYou$.pipe(ce(e=>e?.filter(r=>r?.isUnread)?.length??null),he(e=>this.getNotifications$().pipe(ce(t=>{let r=t?.filter(a=>a?.isUnread)?.length??null;return{forYou:e,all:r}}))))}catch(e){return this.loggingService.catch("Error in NotificationService getUnreadNotificationsCount$: ",e),se({forYou:null,all:null})}}setNotificationAsRead(e){return Q(this,null,function*(){try{let t=this.authService.getUser();if(t&&e?.id){let r=bt(t?.userId),{metadata:a}=e;if(a){let{apiKey:s,organizationId:c,documentId:p}=a;if(s&&c&&p&&r){let u=yield this.commonDbService.getData({feature:"docNotification",properties:{id:e.id,organizationId:c,documentId:p,apiKey:s}});u?.notificationId&&(u?.views?.[r]||(u.views||(u.views={}),u.views[r]={timestamp:Date.now()},this.commonDbService.updateData({feature:"docNotificationViews",properties:{id:e.id,organizationId:c,documentId:p,apiKey:s},data:u})));let C=yield this.commonDbService.getData({feature:"userNotification",properties:{id:e.id,userId:r,documentId:p,organizationId:c}});C?.notificationId&&(this.getReadNotificationsOnForYouTab()?C?.views?.[r]||(C.views||(C.views={}),C.views[r]={timestamp:Date.now()},this.commonDbService.updateData({feature:"userNotificationViews",properties:{id:e.id,userId:r,documentId:p,organizationId:c},data:C})):yield this.commonDbService.deleteData({feature:"userNotification",properties:{id:e.id,userId:r,documentId:p,organizationId:c}}))}}}}catch(t){this.loggingService.catch("Error in NotificationService setNotificationAsRead: ",t)}})}setMaxDays(e){try{e>0?this.maxNotificationDays$.next(e):this.maxNotificationDays$.next(15)}catch(t){this.loggingService.catch("Error in NotificationService setMaxDays: ",t)}}setTabConfig(e){try{e&&this.tabConfig$.next(e)}catch(t){this.loggingService.catch("Error in NotificationService setTabConfig: ",t)}}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 Q(this,null,function*(){try{this.getNotifications$().pipe(st(1)).subscribe(t=>{if(t){let r=t.filter(a=>a.id===e);this.setNotificationsAsRead(r)}})}catch(t){this.loggingService.catch("Error in NotificationService markNotificationAsReadById: ",t)}})}getAllowedDocumentMetadataByDocumentId(e){try{return this.allowedDocumentMetadataMap$.value?.[e]||null}catch(t){return this.loggingService.catch("Error in NotificationService getAllowedDocumentMetadataByDocumentId: ",t),null}}setSettingsConfig(e){try{this.enableSettings$.value&&this.settingsConfig$.next(e)}catch(t){this.loggingService.catch("Error in NotificationService setSettingsConfig: ",t)}}setSettingsConfigWithDB(e){try{this.enableSettings$.value&&(this.settingsConfig$.next(e),this.updateSettingsConfigToDb())}catch(t){this.loggingService.catch("Error in NotificationService setSettingsConfigWithDB: ",t)}}getSettingsConfig$(){return this.settingsConfig$.asObservable()}getSettingsConfig(){return this.settingsConfig$.value}setMuteAllNotifications(){try{this.muteAllNotifications$.value!==!0&&this.muteAllNotifications$.next(!0)}catch(e){this.loggingService.catch("Error in NotificationService setSettingsMuteAll: ",e)}}getMuteAllNotifications$(){return this.muteAllNotifications$.asObservable()}getMuteAllNotifications(){return this.muteAllNotifications$.value}enableSettings(){try{this.enableSettings$.value!==!0&&this.enableSettings$.next(!0)}catch(e){this.loggingService.catch("Error in NotificationService enableSettings: ",e)}}enableSelfNotifications(){try{this.selfNotifications$.value!==!0&&this.selfNotifications$.next(!0)}catch(e){this.loggingService.catch("Error in NotificationService enableSelfNotifications: ",e)}}disableSelfNotifications(){try{this.selfNotifications$.value!==!1&&this.selfNotifications$.next(!1)}catch(e){this.loggingService.catch("Error in NotificationService disableSelfNotifications: ",e)}}disableSettings(){try{this.enableSettings$.value!==!1&&this.enableSettings$.next(!1)}catch(e){this.loggingService.catch("Error in NotificationService disableSettings: ",e)}}getEnableSettings$(){return this.enableSettings$.asObservable()}getEnableSettings(){return this.enableSettings$.value}setSettingsInitialConfig(e){try{let t=!1;if(e.forEach(r=>{["email","inbox"].includes(r.id)&&(t=!r.values?.every(a=>["ALL","NONE","MINE"].includes(a.id)))}),t){this.loggingService.catch("Invalid config values for email or inbox, It should have only ALL, NONE, MINE values");return}this.settingsInitialConfig$.next(e)}catch(t){this.loggingService.catch("Error in NotificationService setSettingsInitialConfig: ",t)}}getSettingsInitialConfig$(){return this.settingsInitialConfig$.asObservable()}getSettingsInitialConfig(){return this.settingsInitialConfig$.value}updateSettingsConfigToDb(e){return Q(this,null,function*(){try{let t=bt(this.authService.getUser()?.userId??""),r=this.docService.getDocumentPaths(),a={apiKey:this.configService.getApiKey(),organizationId:r?.organizationId,documentId:r?.documentId,clientOrganizationId:r?.clientOrganizationId,clientDocumentId:r?.clientDocumentId,userId:t,clientUserId:this.authService.getUser()?.userId};t&&r?.documentId&&this.getEnableSettings()&&this.enableSettings$.value&&(yield this.commonDbService.updateData({feature:"userConfig",properties:{documentId:r.documentId,userId:t},data:{id:r.documentId,notificationsConfig:e||this.settingsConfig$.getValue(),metadata:a}}))}catch(t){this.loggingService.catch("Error in NotificationService updateSettingsConfigToDb: ",t)}})}openNotificationsPanel(){try{this.notificationsPanelVisible$.next(!0)}catch(e){this.loggingService.catch("Error in NotificationService openNotificationsPanel: ",e)}}closeNotificationsPanel(){try{this.notificationsPanelVisible$.next(!1)}catch(e){this.loggingService.catch("Error in NotificationService closeNotificationsPanel: ",e)}}getNotificationsPanelVisible$(){return this.notificationsPanelVisible$.asObservable()}getNotificationsPanelVisible(){return this.notificationsPanelVisible$.value}};o.\u0275fac=function(t){return new(t||o)(ee(Di),ee(et),ee(Ve),ee(Ft),ee(pn),ee(ag),ee(f0),ee(Rs),ee(Dn),ee(at),ee(Be),ee(vn),ee(y),ee(Rk),ee(Vn),ee(Wo))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var Zo=(()=>{let o=class o{constructor(e){this.loggingService=e,this._customStatusMap=new ve(j.CommentAnnotationStatusMap),this._customPriorityMap=new ve(j.CommentAnnotationPriorityMap),this._customCategoryMap=new ve(j.CommentCategoryMap);try{let t=sessionStorage.getItem(j.SESSION_STORAGE.VELT_CUSTOM_PRIORITY_MAP);t&&this._customPriorityMap.next(JSON.parse(t));let r=sessionStorage.getItem(j.SESSION_STORAGE.VELT_CUSTOM_STATUS_MAP);r&&this._customStatusMap.next(JSON.parse(r));let a=sessionStorage.getItem(j.SESSION_STORAGE.VELT_CUSTOM_CATEGORY_MAP);a&&this._customCategoryMap.next(JSON.parse(a))}catch(t){this.loggingService.catch("Error in CustomFilterService constructor: ",t)}}setCustomStatusFilters(e){try{if(e.length<2){this._customStatusMap.next(j.CommentAnnotationStatusMap),sessionStorage.setItem(j.SESSION_STORAGE.VELT_CUSTOM_STATUS_MAP,JSON.stringify(j.CommentAnnotationStatusMap)),this.loggingService.catch("Custom status filters must have at least 2 filters");return}let t={};e.forEach(r=>{t[r.id]=r,r.type||(r.type="ongoing")}),this._customStatusMap.next(t),sessionStorage.setItem(j.SESSION_STORAGE.VELT_CUSTOM_STATUS_MAP,JSON.stringify(t))}catch(t){this.loggingService.catch("Error in CustomFilterService setCustomStatusFilters: ",t)}}setCustomPriorityFilters(e){try{if(e.length<2){this._customPriorityMap.next(j.CommentAnnotationPriorityMap),sessionStorage.setItem(j.SESSION_STORAGE.VELT_CUSTOM_PRIORITY_MAP,JSON.stringify(j.CommentAnnotationPriorityMap)),this.loggingService.catch("Custom priority filters must have at least 2 filters");return}let t={};e.forEach(r=>{t[r.id]=r}),this._customPriorityMap.next(t),sessionStorage.setItem(j.SESSION_STORAGE.VELT_CUSTOM_PRIORITY_MAP,JSON.stringify(t))}catch(t){this.loggingService.catch("Error in CustomFilterService setCustomPriorityFilters: ",t)}}setCustomCategories(e){try{let t={};e.forEach(r=>{t[r.id]=r}),this._customCategoryMap.next(t),sessionStorage.setItem(j.SESSION_STORAGE.VELT_CUSTOM_CATEGORY_MAP,JSON.stringify(t))}catch(t){this.loggingService.catch("Error in CustomFilterService setCustomCategories: ",t)}}get customStatusMap$(){return this._customStatusMap.asObservable()}get customPriorityMap$(){return this._customPriorityMap.asObservable()}get customCategoryMap$(){return this._customCategoryMap.asObservable()}get defaultStatus(){try{let t=Object.entries(this._customStatusMap.value).find(([r,a])=>a.type==="default");if(t)return t[1]}catch(e){this.loggingService.catch("Error in CustomFilterService defaultStatus: ",e)}return j.CommentAnnotationStatusMap.OPEN}get resolvedStatus(){try{let t=Object.entries(this._customStatusMap.value).find(([r,a])=>a.type==="terminal");if(t)return t[1]}catch(e){this.loggingService.catch("Error in CustomFilterService resolvedStatus: ",e)}return j.CommentAnnotationStatusMap.OPEN}get ongoingStatuses(){try{let t=Object.entries(this._customStatusMap.value).filter(([r,a])=>a.type==="ongoing");if(t)return t.map(r=>r[1])}catch(e){this.loggingService.catch("Error in CustomFilterService ongoingStatuses: ",e)}return[j.CommentAnnotationStatusMap.IN_PROGRESS]}convertLegacyAnnotationStatus(e){try{if(typeof e.status=="string"||e.status===void 0){let t=Object.entries(this._customStatusMap.value),r=t.find(([a,s])=>s.type==="default");switch(e.status){case"open":r&&(e.status=r[1]);break;case"inProgress":let a=t.find(([c,p])=>p.type==="ongoing");a&&(e.status=a[1]);break;case"resolved":let s=t.find(([c,p])=>p.type==="terminal");s&&(e.status=s[1]);break;default:r&&(e.status=r[1]);break}}return e}catch(t){return this.loggingService.catch("Error in CustomFilterService convertLegacyAnnotation: ",t),e}}convertLegacyPriority(e){try{typeof e.priority=="string"&&(e.priority=j.CommentAnnotationPriorityMap[e.priority])}catch(t){this.loggingService.catch("Error in CustomFilterService convertLegacyPriority: ",t)}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(t=>j.CommentCategoryMap[t]))}catch(t){this.loggingService.catch("Error in CustomFilterService convertLegacyCategory: ",t)}return e}};o.\u0275fac=function(t){return new(t||o)(ee(y))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var Bc=(()=>{let o=class o{constructor(e,t,r){this.domService=e,this.loggingService=t,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,t){try{let r=`<span class="velt-emoji-icon velt-emoji-icon--emoji">${e}</span>`;return t&&(r=`<span class="velt-emoji-icon velt-emoji-icon--emoji" emoji-id=${t}>${e}</span>`),this.sanitizer.bypassSecurityTrustHtml(this.domService.sanitizeHtml(r))}catch{return""}}setEmojiList(e){try{this.emojis={},Object.keys(e).forEach(t=>{let r=e[t];if(r.svg)this.emojis[t]=this.sanitizer.bypassSecurityTrustHtml(this.domService.sanitizeSvg(r.svg));else if(r.url){let a=`<img src="${r.url}" alt="${t}" />`;this.emojis[t]=this.sanitizer.bypassSecurityTrustHtml(this.domService.sanitizeHtml(a))}else r.emoji&&(this.emojis[t]=this.getEmojiFromIconEmoji(this.domService.sanitizeHtml(r.emoji)))})}catch(t){this.loggingService.catch("Error in EmojiService setEmojiList: ",t)}}};o.Icons={RAISED_HANDS:`<svg width="58" height="57" viewBox="0 0 58 57" fill="none" xmlns="http://www.w3.org/2000/svg">
197
197
  <path d="M35.8477 11.6603L40.4962 5.23427" stroke="#B0BEC5" stroke-width="1.92685" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/>
198
198
  <path d="M21.8298 11.617L17.4655 6.02428" stroke="#B0BEC5" stroke-width="1.92685" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/>
199
199
  <path d="M28.7568 9.77682L28.7761 1" stroke="#B0BEC5" stroke-width="1.92685" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/>
@@ -470,7 +470,7 @@ This typically indicates that your device does not have a healthy Internet conne
470
470
  <svg width="20" height="20" viewBox="0 0 20 20" fill="none" aria-hidden="true" focusable="false">
471
471
  <path d="M6 4.66685V15.3335C5.99997 15.4521 6.03158 15.5686 6.09159 15.6709C6.15159 15.7733 6.23781 15.8577 6.34135 15.9156C6.44489 15.9735 6.562 16.0027 6.68059 16.0002C6.79918 15.9978 6.91497 15.9637 7.016 15.9015L15.6827 10.5682C15.7797 10.5085 15.8599 10.425 15.9155 10.3256C15.9711 10.2261 16.0003 10.1141 16.0003 10.0002C16.0003 9.88626 15.9711 9.77423 15.9155 9.6748C15.8599 9.57536 15.7797 9.49183 15.6827 9.43219L7.016 4.09885C6.91497 4.0367 6.79918 4.00262 6.68059 4.00015C6.562 3.99767 6.44489 4.02688 6.34135 4.08476C6.23781 4.14265 6.15159 4.22711 6.09159 4.32943C6.03158 4.43175 5.99997 4.54823 6 4.66685Z" fill="currentColor"/>
472
472
  </svg>
473
- `;break}s.innerHTML=c.trim();let p=s.firstElementChild;return p&&a.appendChild(p),a.addEventListener("click",r),a.__cleanup=()=>{a.removeEventListener("click",r)},a}exitPictureInPicture(){return Q(this,null,function*(){try{if("documentPictureInPicture"in window&&(window.documentPictureInPicture.window||this.pipWindow)){this.pipWindow&&!this.pipWindow.closed&&this.pipWindow.close(),this.pipWindow=void 0,this.isPipActive$.next(!1);return}if(document.pictureInPictureElement){yield document.exitPictureInPicture(),this.isPipActive$.next(!1);return}this.isPipActive$.next(!1),this.pipWindow=void 0}catch(e){this.loggingService.catch("Error in PipService exitPictureInPicture:",e),this.isPipActive$.next(!1),this.pipWindow=void 0}})}togglePictureInPicture(e,t){return Q(this,null,function*(){try{this.isPipActive$.value||this.pipWindow||document.pictureInPictureElement?yield this.exitPictureInPicture():yield this.openPictureInPicture(e,t)}catch(r){this.loggingService.catch("Error in PipService togglePictureInPicture:",r),this.isPipActive$.next(!1),this.pipWindow=void 0}})}findVideoElement(){return Q(this,null,function*(){try{let e=['[data-testid*="velt-recorder-control-panel-video-video"]','[data-testid*="velt-recorder-control-panel-screen-screen"]','video[data-testid*="recorder"]'];for(let r of e){let a=document.querySelector(r);if(a&&a.srcObject)return a}let t=Array.from(document.querySelectorAll("video"));for(let r of t)if(r.srcObject)return r;return null}catch(e){return this.loggingService.catch("Error in PipService findVideoElement:",e),null}})}getIsPipActive$(){return this.isPipActive$.asObservable()}getIsPipActive(){return this.isPipActive$.value}getPipStopRecordingTriggered$(){return this.pipStopRecordingTriggered$.asObservable()}resetPipStopRecordingTriggered(){this.pipStopRecordingTriggered$.next(!1)}getPipPauseRecordingTriggered$(){return this.pipPauseRecordingTriggered$.asObservable()}resetPipPauseRecordingTriggered(){this.pipPauseRecordingTriggered$.next(!1)}enablePictureInPicture(){try{if(this.pictureInPicture$.value===!0)return;this.pictureInPicture$.next(!0),this.messageListener||(this.messageListener=e=>{try{if(e.origin!==window.location.origin){this.loggingService.warn("Received message from untrusted origin:",e.origin);return}if(e.source!==this.pipWindow&&e.source!==window.parent){this.loggingService.warn("Received message from untrusted source window");return}e.data?.type==="pip-stop-recording"?this.pipStopRecordingTriggered$.next(!0):e.data?.type==="pip-pause-recording"||e.data?.type==="pip-resume-recording"?this.pipPauseRecordingTriggered$.next(!0):e.data?.type==="pip-clear-recording"&&this.pipClearRecordingTriggered$.next(!0)}catch(t){this.loggingService.catch("Error in PipService enablePictureInPicture message listener:",t)}},window.addEventListener("message",this.messageListener))}catch(e){this.loggingService.catch("Error in PipService enablePictureInPicture: ",e)}}disablePictureInPicture(){try{if(this.pictureInPicture$.value===!1)return;this.pictureInPicture$.next(!1),this.messageListener&&(window.removeEventListener("message",this.messageListener),this.messageListener=void 0),this.pipStopRecordingTriggered$.next(!1),this.pipPauseRecordingTriggered$.next(!1),this.pipClearRecordingTriggered$.next(!1),this.isPipActive$.next(!1),this.pipWindow&&!this.pipWindow.closed&&this.pipWindow.close(),this.pipWindow=void 0}catch(e){this.loggingService.catch("Error in PipService disablePictureInPicture: ",e)}}getPictureInPicture$(){return this.pictureInPicture$.asObservable()}isPictureInPictureEnabled(){try{let e=new zn;return this.pictureInPicture$.value&&e.getBrowserName()==="Chrome"}catch(e){return this.loggingService.catch("Error in PipService isPictureInPictureEnabled: ",e),!1}}};o.\u0275fac=function(t){return new(t||o)(ee(y))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var bn=(()=>{let o=class o{constructor(e,t,r,a,s,c,p,u){this.analyticsService=e,this.loggingService=t,this.matDialog=r,this.storageService=a,this.docService=s,this.databaseService=c,this.domService=p,this.pipService=u,this.recorderStatusSubject$=new ve(null),this.recorderDurationSubject$=new ve(null),this.darkMode$=new ve(null),this.shadowDom$=new ve(null),this.recordingDurations=[],this.chunks=[],this.recordingCountdownEnabled$=new ve(!0),this.recorderInitData$=new tt,this.recordedRawData$=new tt,this.recordedData$=new tt,this.onInitRecording$=new ve(null),this.onRecordingAttributeRemovedFromBodySubject$=new tt,this.videoEditor$=new ve(!1),this.settingsEmbedded$=new ve(!1),this.autoOpenVideoEditor$=new ve(!1),this.playVideoInFullScreen$=new ve(void 0),this.recordedDataStream=[],this.documentPaths=null,this.uploadPromises=[],this.chunkUrls$=new ve({}),this.recordingQualityConstraints=new ve({safari:{audio:{sampleRate:48e3,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0},video:{width:{min:640,ideal:1280,max:1280},height:{min:360,ideal:720,max:720},frameRate:{min:15,ideal:20,max:30},aspectRatio:{ideal:1.777777778}}},other:{audio:{sampleRate:48e3,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0},video:{width:{min:640,ideal:1280,max:1280},height:{min:360,ideal:720,max:720},frameRate:{min:15,ideal:20,max:30},aspectRatio:{ideal:1.777777778}}}}),this.recordingEncodingOptions=new ve({safari:{videoBitsPerSecond:25e5,audioBitsPerSecond:128e3},other:{videoBitsPerSecond:1e6,audioBitsPerSecond:128e3}}),this.recordingMicEnabled$=new ve(null),this.onboardingTooltip$=new ve(!1),this.retakeOnVideoEditor$=new ve(!1),this.maxRecordingLength=null,this.screenStreamSubject$=new ve(null),this.onInitRecording$.subscribe(C=>{C?this.setRecordingAttributeAtBody():this.removeRecordingAttributeFromBody()}),this.pipService.getPipPauseRecordingTriggered$().subscribe(C=>{C&&(this.recorderStatusSubject$.value==="started"||this.recorderStatusSubject$.value==="resumed"?this.pauseRecording():this.recorderStatusSubject$.value==="paused"&&this.resumeRecording(),this.pipService.resetPipPauseRecordingTriggered())}),this.databaseService.getDb().pipe(Le(C=>!!C),st(1)).subscribe(C=>{C&&this.getDocumentPaths()},C=>{this.loggingService.catch("Error in RecorderAnnotationService getDb subscription: ",C)})}getDocumentPaths(){this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentPaths","color: green;");try{this.docService.getDocumentPaths$().pipe(dn(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(j.ATTRIBUTES.VELT_ONGOING_RECORDING,e.type),e?.isCommentRecording&&document.body.setAttribute(j.ATTRIBUTES.VELT_COMMENT_RECORDING,"true"))}catch(e){this.loggingService.catch("Error in RecorderService setRecordingAttributeAtBody: ",e)}}removeRecordingAttributeFromBody(){try{document.body.removeAttribute(j.ATTRIBUTES.VELT_ONGOING_RECORDING),document.body.removeAttribute(j.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,t,r,a,s,c,p,u,C){return Q(this,null,function*(){try{let E={};switch(e){case"audio":E.audio={enabled:!0};break;case"video":E.video={enabled:!0},E.audio={enabled:!0};break;case"screen":E.screen={enabled:!0,stream:C},E.video={enabled:!1},E.audio={enabled:!1};break;default:break}C&&e==="screen"&&(E.screen={enabled:!0,stream:C}),this.matDialog.open(Bk,{panelClass:"velt-mat-dialog-container",data:{type:e,mediaConfig:E,darkMode:[!0,!1].includes(a)?a:this.darkMode$.value,shadowDom:s,recordingCountdown:u}}).afterClosed().subscribe(D=>{if(D){let L={};switch(e){case"audio":L.audio={enabled:!0,deviceId:D.audio?.deviceId},L.audio=D.audio;break;case"video":L.video={enabled:!0,deviceId:D.video?.deviceId},L.audio={enabled:!0,deviceId:D.audio?.deviceId},L.video=D.video,L.audio=D.audio;break;case"screen":L.screen={enabled:!0},L.audio=D.audio,L.video=D.video,L.screen=D.screen;break;default:break}this.onInitRecording$.next({type:e,panelId:t,mediaConfig:L,isCommentRecording:r,darkMode:[!0,!1].includes(a)?a:!!this.darkMode$.value,shadowDom:s,commentAnnotationId:c,clientDocumentId:p})}},D=>{this.loggingService.catch("Error in RecorderService initRecording afterClosed: ",D)})}catch(E){this.loggingService.catch("Error in RecorderService initRecording: ",E)}})}startRecording(e,t){return Q(this,null,function*(){try{this.loggingService.log("[startRecording] Starting with config:",e,"mediaConfig:",t);let r=new MediaStream,a=yield this.getBrowserSpecificOptions();return yield this.collectMediaTracks(r,e,t),yield this.initializeMediaRecorder(r,a,e),this.setupRecorderData(e,r),r}catch(r){return this.loggingService.catch("Error in RecorderService startRecording: ",r),Promise.reject(r)}})}getBrowserSpecificOptions(){return Q(this,null,function*(){try{let e={videoBitsPerSecond:this.recordingEncodingOptions.value[this.isSafari()?"safari":"other"]?.videoBitsPerSecond,audioBitsPerSecond:this.recordingEncodingOptions.value[this.isSafari()?"safari":"other"]?.audioBitsPerSecond},t=this.getSupportedMimeTypes();if(t.length>0){let a=t.find(s=>s.includes("mp4")&&s.includes("h264"))||t.find(s=>s.includes("mp4"))||t[0];e.mimeType=a}return new zn().getBrowserName()==="Firefox"&&(t.includes("video/webm")&&(e.mimeType="video/webm"),e.videoBitsPerSecond=Math.min(e.videoBitsPerSecond||1e6,2e6),e.audioBitsPerSecond=Math.min(e.audioBitsPerSecond||128e3,256e3)),e}catch(e){return this.loggingService.catch("Error in RecorderService getBrowserSpecificOptions: ",e),{}}})}collectMediaTracks(e,t,r){return Q(this,null,function*(){try{if(t.type.screen&&r?.screen?.stream){let a=this.getCommonVideoQualityConstraints(!0);r.screen.stream.getTracks().forEach(s=>{e.addTrack(s),s.onended=()=>this.stopRecording(),s.applyConstraints(I({},a))})}if(t?.type.audio||t?.type.video)if(this.isFirefox()&&t.type.screen&&(r?.audio?.stream||r?.video?.stream)){let s=new Set;t.type.audio&&r?.audio?.stream&&r.audio.stream.getAudioTracks().forEach(c=>{s.has(c)||(e.addTrack(c),s.add(c))}),t.type.video&&r?.video?.stream&&r.video.stream.getVideoTracks().forEach(c=>{s.has(c)||(e.addTrack(c),s.add(c))})}else{let s=this.buildMediaConstraints(t,r),c=yield navigator.mediaDevices.getUserMedia(s);if(c)if(this.isSafari()){if(t?.type.audio&&(yield this.adjustSafariAudioTrack(e,c)),t?.type.video){let p=c.getVideoTracks();if(p.length>0){let u=p[0];u.enabled=!0;let C=u.clone();e.addTrack(C),r&&r.video&&(r.video.track=u)}}}else c.getTracks().forEach(p=>e.addTrack(p))}}catch(a){this.loggingService.catch("Error in RecorderService collectMediaTracks: ",a);return}})}buildMediaConstraints(e,t){try{let r=this.getCommonVideoQualityConstraints(!!e.type.video);return{audio:this.getCommonAudioConstraints(!!e.type.audio,t),video:e.type.video?T(I({deviceId:t?.video?.deviceId?{ideal:t.video.deviceId}:void 0},r),{facingMode:"user"}):!1}}catch(r){return this.loggingService.catch("Error in RecorderService buildMediaConstraints: ",r),{}}}getCommonAudioConstraints(e,t){try{if(!e)return!1;let r=this.recordingQualityConstraints.value[this.isSafari()?"safari":"other"]?.audio||{};return I({deviceId:t?.audio?.deviceId?{ideal:t.audio.deviceId}:void 0},r)}catch(r){return this.loggingService.catch("Error in RecorderService getCommonAudioConstraints: ",r),{}}}getCommonVideoQualityConstraints(e){try{return e?this.recordingQualityConstraints.value[this.isSafari()?"safari":"other"]?.video||{}:{}}catch(t){return this.loggingService.catch("Error in RecorderService getCommonVideoQualityConstraints: ",t),{}}}adjustSafariAudioTrack(e,t){return Q(this,null,function*(){try{let r=t.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,t,r){return Q(this,null,function*(){try{if(e.getTracks().length===0)throw new Error("MediaStream has no tracks");this.mediaRecorder=new MediaRecorder(e,t),this.chunks=[],this.chunkUrls$.next({}),this.uploadPromises=[];let a=0;if(this.isSafari()){let u=e.getVideoTracks();u.length>0&&u.forEach(C=>{C.contentHint="detail",C.enabled=!0})}let c=new zn().getBrowserName()==="Firefox";c&&e.getTracks().forEach(u=>{u.enabled=!0}),this.mediaRecorder.addEventListener("dataavailable",u=>{if(u.data?.size>0){let C=a++;this.chunks.push(u.data);let E=`recording_${new Date().getTime()}_${Math.random().toString(36).substring(2,9)}`,D=u.data,L=this.uploadChunk(D,E,C);this.uploadPromises||(this.uploadPromises=[]),this.uploadPromises.push({promise:L,index:C}),L.then(z=>{this.chunkUrls$.next(T(I({},this.chunkUrls$.value),{[C]:z}))}).catch(z=>{})}}),this.mediaRecorder.addEventListener("stop",()=>{c&&this.chunks.length===0&&this.attemptFirefoxCanvasRecording(e),this.onStopRecording()}),this.mediaRecorder.addEventListener("error",u=>{this.loggingService.catch("MediaRecorder error event:",u)});let p=4e3;c&&r.type.screen&&(p=void 0),p?this.mediaRecorder.start(p):this.mediaRecorder.start(),c&&setTimeout(()=>{if(this.chunks.length===0&&this.mediaRecorder.state==="recording")try{this.mediaRecorder.requestData&&this.mediaRecorder.requestData()}catch{}},2e3)}catch(a){throw this.loggingService.catch("Error in RecorderService initializeMediaRecorder: ",a),a}})}uploadChunk(e,t,r){return Q(this,null,function*(){try{let s=this.mediaRecorder.mimeType||"video/mp4",c=s.includes("webm")?"webm":"mp4",p=`chunk_${r}_${new Date().getTime()}.${c}`,u=new File([e],p,{type:s});return yield this.uploadChunkToStorage(u,t,r)}catch(a){throw a}})}uploadChunkToStorage(e,t,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=`${j.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${j.FIREBASE_PARTIAL_PATH_RECORDER}/${t}`;return a&&(c=`${j.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${a}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${j.FIREBASE_PARTIAL_PATH_RECORDER}/${t}`),this.storageService.uploadChunk(c,e,r)}catch(a){throw this.loggingService.catch("Error in RecorderService uploadChunkToStorage: ",a),a}}setupRecorderData(e,t){try{return this.recorderInitData=new _k,this.recorderStatusSubject$.next("started"),this.isSafari()&&e.type.video&&t.getVideoTracks().forEach(r=>{r.enabled=!0}),this.recorderInitData.stream=t,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.recorderActionsService?.onRecordingStarted(this.getRecorderDataFromInitData()),this.pipService.getIsPipActive()&&window.postMessage({type:"recording-status-update",status:"started"},"*"),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(t){return this.loggingService.catch("Error in RecorderService determineRecorderType: ",t),"audio"}}timeout(e){return new Promise(t=>setTimeout(t,e))}pauseRecording(){try{if(this.recorderStatusSubject$.next("paused"),this.mediaRecorder.pause(),this.firefoxFallbackRecorder?.state==="recording")try{this.firefoxFallbackRecorder.pause()}catch(e){this.loggingService.catch("Error pausing Firefox fallback recorder: ",e)}this.recordingDurations?.length&&(this.recordingDurations[this.recordingDurations.length-1].end=new Date().getTime()),this.stopTimer(),this.recorderActionsService?.onRecordingPaused(this.getRecorderDataFromInitData()),this.pipService.getIsPipActive()&&window.postMessage({type:"recording-status-update",status:"paused",recordingType:this.recorderInitData?.type||"video"},window.location.origin)}catch(e){this.loggingService.catch("Error in RecorderService pauseRecording: ",e)}}resumeRecording(){try{if(this.recorderStatusSubject$.next("resumed"),this.mediaRecorder.resume(),this.firefoxFallbackRecorder?.state==="paused")try{this.firefoxFallbackRecorder.resume()}catch(e){this.loggingService.catch("Error resuming Firefox fallback recorder: ",e)}this.recordingDurations.push({start:new Date().getTime()}),this.startTimer(),this.recorderActionsService?.onRecordingResumed(this.getRecorderDataFromInitData()),this.pipService.getIsPipActive()&&window.postMessage({type:"recording-status-update",status:"started",recordingType:this.recorderInitData?.type||"video"},"*")}catch(e){this.loggingService.catch("Error in RecorderService resumeRecording: ",e)}}stopRecording(){try{if(this.mediaRecorder?.state!=="inactive"?(this.mediaRecorder.stop(),this.removeRecordingAttributeFromBody()):this.clearRecording(),this.firefoxFallbackRecorder?.state==="recording")try{this.firefoxFallbackRecorder.stop()}catch(e){this.loggingService.catch("Error stopping Firefox fallback recorder: ",e)}this.recorderActionsService?.onRecordingStopped(this.getRecorderDataFromInitData())}catch(e){this.loggingService.catch("Error in RecorderService stopRecording: ",e)}}onStopRecording(){return Q(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(r=>{r.stop()}),yield this.timeout(100);let t=new Sb;if(this.chunks.length>0){let r=this.recorderInitData?.type==="audio"?"audio/mp4":"video/mp4";this.loggingService.log("[onStopRecording] Creating blob with type:",r),t.blob=new Blob(this.chunks,{type:r}),this.loggingService.log("[onStopRecording] Blob created, size:",t.blob.size);try{let a=yield this.getVideoDuration(t.blob);if(a&&isFinite(a)&&a>0){let s={};s.duration=a*1e3,s.display=this.convertMillisecondsToTime(a*1e3),this.recorderDurationSubject$.next(s),t.recordedTime=s}else{let s=this.recorderDurationSubject$.value;t.recordedTime=s}}catch(a){let s=this.recorderDurationSubject$.value;t.recordedTime=s,this.recorderInitData&&this.loggingService.catch("Error in RecorderService onStopRecording getVideoDuration: ",a)}if(t.blob.size===0)throw new Error("Recorded blob has zero size");if(t.url=URL.createObjectURL(t.blob),t.type=this.recorderInitData?.type,t.recordedTime=this.recorderDurationSubject$.value,t?.type!=="audio")try{yield this.timeout(200);let a=yield iae(t.blob,3);a&&(t.thumbnail=yield oae(a))}catch(a){this.recorderInitData&&this.loggingService.catch("Error in RecorderService onStopRecording getVideoCover: ",a)}this.recordedRawData$.next(t)}else throw new Error("No data chunks recorded")}catch(e){this.loggingService.catch("Error in RecorderService onStopRecording: ",e),this.recordedRawData$.error(e)}})}clearRecording(e){return Q(this,null,function*(){try{if(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.firefoxFallbackRecorder){try{this.firefoxFallbackRecorder.state==="recording"&&this.firefoxFallbackRecorder.stop()}catch(t){this.loggingService.catch("Error stopping Firefox fallback recorder during cleanup: ",t)}this.firefoxFallbackRecorder=void 0}this.recorderInitData?.stream?.getTracks()?.forEach(t=>{t.stop()}),e?.triggerEvent==="cancelled"&&this.recorderActionsService?.onRecordingCancelled(this.getRecorderDataFromInitData()),this.recorderInitData=null,this.recorderInitData$.next(null),this.chunks=[],this.chunkUrls$.next({}),this.stopTimer()}catch(t){this.loggingService.catch("Error in RecorderService clearRecording: ",t)}})}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(r=>{r.end?e+=r?.end-r.start:e+=new Date().getTime()-r.start});let t={};t.duration=e,t.display=this.convertMillisecondsToTime(e),this.recorderDurationSubject$.next(t),this.pipService.getIsPipActive()&&window.postMessage({type:"recording-timer-update",display:t.display},"*")}else this.recorderDurationSubject$.next(null)}catch(e){this.loggingService.catch("Error in RecorderService calculateRecordedTime: ",e)}}checkMaxLength(){try{if(!this.maxRecordingLength||!this.recordingDurations?.length)return!1;let e=0;this.recordingDurations.forEach(r=>{r.end?e+=r?.end-r.start:e+=new Date().getTime()-r.start});let t=e>=this.maxRecordingLength*1e3+500;return t&&this.loggingService.log("%c[WB] Max recording length reached. Duration: "+e+"ms, Target: "+this.maxRecordingLength+"s","color: orange;"),t}catch(e){return this.loggingService.catch("Error in RecorderService checkMaxLength: ",e),!1}}convertMillisecondsToTime(e){try{let t=Math.floor(e/1e3),r=Math.floor(t/60),a=Math.floor(r/60);return t=t%60,r=r%60,`${a.toString().padStart(2,"0")}:${r.toString().padStart(2,"0")}:${t.toString().padStart(2,"0")}`}catch(t){return this.loggingService.catch("Error in RecorderService convertMillisecondsToTime: ",t),""}}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}}isFirefox(){try{return new zn().getBrowserName()==="Firefox"}catch(e){return this.loggingService.catch("Error in RecorderService isFirefox: ",e),!1}}getSupportedMimeTypes(){try{return["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;codecs=vp9","video/webm;codecs=vp8","video/webm","audio/webm;codecs=opus","audio/webm"].filter(r=>MediaRecorder.isTypeSupported(r))}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 Q(this,null,function*(){try{if(this.uploadPromises.length===0)return{};let e=this.uploadPromises.map(t=>t.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(t){this.loggingService.catch("Error in RecorderAnnotationService setRecorderActionsService: ",t)}}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}setRecordingQualityConstraints(e){try{let t=this.recordingQualityConstraints.value;t={other:{audio:I(I({},t.other?.audio),e.other?.audio),video:I(I({},t.other?.video),e.other?.video)},safari:{audio:I(I({},t.safari?.audio),e.safari?.audio),video:I(I({},t.safari?.video),e.safari?.video)}},this.recordingQualityConstraints.next(t)}catch(t){this.loggingService.catch("Error in RecorderService setRecordingQualityConstraints: ",t)}}setRecordingEncodingOptions(e){try{let t=this.recordingEncodingOptions.value;t={other:I(I({},t.other),e.other),safari:I(I({},t.safari),e.safari)},this.recordingEncodingOptions.next(t)}catch(t){this.loggingService.catch("Error in RecorderService setRecordingEncodingOptions: ",t)}}getVideoDuration(e){return Q(this,null,function*(){return new Promise((t,r)=>{try{let a=URL.createObjectURL(e),s=document.createElement("video"),c=navigator.userAgent.includes("Firefox");c&&(s.preload="auto"),s.onloadedmetadata=()=>{let p=s.duration;c&&p>0&&p<10&&e.size>1e6?setTimeout(()=>{let u=s.duration;URL.revokeObjectURL(a),t(u)},1e3):(URL.revokeObjectURL(a),t(p))},s.onerror=p=>{URL.revokeObjectURL(a),r(p)},s.src=a,s.load()}catch(a){this.loggingService.catch("Error in RecorderService getVideoDuration: ",a),r(a)}})})}enableRecordingMic(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableRecordingMic","color: green;"),this.recordingMicEnabled$.value===!0)return;this.recordingMicEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in RecorderService enableRecordingMic: ",e)}}disableRecordingMic(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableRecordingMic","color: green;"),this.recordingMicEnabled$.value===!1)return;this.recordingMicEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in RecorderService disableRecordingMic: ",e)}}getRecordingMicEnabled$(){return this.recordingMicEnabled$.asObservable()}getRecordingMicEnabled(){return this.recordingMicEnabled$.value}setOnboardingTooltip(e){try{if(this.onboardingTooltip$.value===e)return;this.onboardingTooltip$.next(e)}catch(t){this.loggingService.catch("Error in RecorderService setOnboardingTooltip: ",t)}}enableOnboardingTooltip(){try{if(this.onboardingTooltip$.value===!0)return;this.onboardingTooltip$.next(!0)}catch(e){this.loggingService.catch("Error in RecorderService enableOnboardingTooltip: ",e)}}disableOnboardingTooltip(){try{if(this.onboardingTooltip$.value===!1)return;this.onboardingTooltip$.next(!1)}catch(e){this.loggingService.catch("Error in RecorderService disableOnboardingTooltip: ",e)}}getOnboardingTooltip$(){return this.onboardingTooltip$.asObservable()}getOnboardingTooltip(){return this.onboardingTooltip$.value}enableRetakeOnVideoEditor(){try{if(this.retakeOnVideoEditor$.value===!0)return;this.retakeOnVideoEditor$.next(!0)}catch(e){this.loggingService.catch("Error in RecorderService enableRetakeOnVideoEditor: ",e)}}disableRetakeOnVideoEditor(){try{if(this.retakeOnVideoEditor$.value===!1)return;this.retakeOnVideoEditor$.next(!1)}catch(e){this.loggingService.catch("Error in RecorderService disableRetakeOnVideoEditor: ",e)}}getRetakeOnVideoEditor$(){return this.retakeOnVideoEditor$.asObservable()}getRetakeOnVideoEditor(){return this.retakeOnVideoEditor$.value}getRecorderStream(){return this.recorderInitData?.stream}getScreenStream$(){return this.screenStreamSubject$.asObservable()}requestScreenPermission(){return Q(this,null,function*(){try{if(!navigator.mediaDevices||!navigator.mediaDevices.getDisplayMedia)throw new Error("Screen sharing is not supported in this browser");let e=yield navigator.mediaDevices.getDisplayMedia({video:!0});if(!e.getVideoTracks()[0])throw new Error("No video track available in screen share stream");return e.getTracks().forEach(r=>{r.onended=()=>{this.screenStreamSubject$.next(null),this.clearRecording()}}),this.screenStreamSubject$.next(e),e}catch(e){return e.name==="NotAllowedError"||e.name==="PermissionDeniedError"?this.loggingService.catch("Screen sharing permission denied by user"):e.name==="NotFoundError"?this.loggingService.catch("No screen sharing device found"):e.name==="NotReadableError"||e.name==="OverconstrainedError"?this.loggingService.catch("Could not access screen sharing device"):this.loggingService.catch("Error in RecorderService requestScreenPermission: ",e),null}})}setMaxRecordingLength(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setMaxRecordingLength","color: green;"),this.maxRecordingLength=e}catch(t){this.loggingService.catch("Error in RecorderService setMaxRecordingLength: ",t)}}getMaxRecordingLength(){return this.maxRecordingLength}attemptFirefoxCanvasRecording(e){return Q(this,null,function*(){try{let t=document.createElement("video");t.srcObject=e,t.muted=!0,t.autoplay=!0;let r=document.createElement("canvas"),a=r.getContext("2d");yield new Promise(u=>{t.onloadedmetadata=u}),r.width=t.videoWidth||1280,r.height=t.videoHeight||720;let s=r.captureStream(30);this.firefoxFallbackRecorder=new MediaRecorder(s,{mimeType:"video/webm;codecs=vp8",videoBitsPerSecond:this.recordingEncodingOptions.value.other?.videoBitsPerSecond||1e6});let c=[];this.firefoxFallbackRecorder.addEventListener("dataavailable",u=>{u.data.size>0&&c.push(u.data)}),this.firefoxFallbackRecorder.addEventListener("stop",()=>{if(c.length>0){let u=new Blob(c,{type:"video/webm"});this.chunks=c;let C=new Sb;C.blob=u,C.url=URL.createObjectURL(u),C.type=this.recorderInitData?.type,C.recordedTime=this.recorderDurationSubject$.value,this.recordedRawData$.next(C)}this.firefoxFallbackRecorder=void 0});let p=()=>{t.readyState>=2&&a&&a.drawImage(t,0,0,r.width,r.height),t.srcObject&&this.firefoxFallbackRecorder?.state==="recording"&&requestAnimationFrame(p)};this.firefoxFallbackRecorder.start(1e3),p()}catch(t){this.loggingService.catch("Error in RecorderService attemptFirefoxCanvasRecording: ",t)}})}getRecorderDataFromInitData(){return{type:this.recorderInitData?.type}}askDevicePermission(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: askDevicePermission","color: green;"),navigator.mediaDevices.getUserMedia({audio:e.audio??!1,video:e.video??!1}).then(t=>{t.getTracks().forEach(r=>{r.stop()})}).catch(t=>{this.loggingService.catch("Error in RecorderService askDevicePermission: ",t)})}catch(t){this.loggingService.catch("Error in RecorderService askDevicePermission: ",t)}}openPictureInPicture(){return Q(this,null,function*(){try{this.loggingService.log("%c[WB] Calling FUNCTION: openPictureInPicture","color: green;");let e=this.getRecorderStream();if(!e)return;yield this.pipService.openPictureInPicture(e,()=>this.stopRecording())}catch(e){this.loggingService.catch("Error in RecorderService openPictureInPicture: ",e)}})}};o.\u0275fac=function(t){return new(t||o)(ee(et),ee(y),ee(no),ee(sg),ee(at),ee(Dn),ee(Be),ee($a))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var y0=(()=>{let o=class o{constructor(e,t,r,a,s){this.authService=e,this.docService=t,this.loggingService=r,this.commonDbService=a,this.usersService=s,this.currentUserPermissions$=new ve(null);try{this.docService.setUserPermissionService(this)}catch(c){this.loggingService.catch("Error in UserPermissionService constructor:",c)}}organizationDetails(e){return Q(this,null,function*(){try{let t=yield this.commonDbService?.getData({feature:"organizationMetadata",properties:{organizationId:e}});return t&&t?.errorCode?{errorCode:wr.PERMISSION_DENIED,error:!0}:t&&!t?.metadata?{errorCode:wr.DOES_NOT_EXIST,error:!0}:{error:!1}}catch(t){return this.loggingService.catch("Error in UserPermissionService organizationDetails:",t),{errorCode:wr.DOES_NOT_EXIST,error:!0}}})}documentDetails(r){return Q(this,arguments,function*({documentId:e,organizationId:t}){try{let a=yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:e,organizationId:t}});return a&&a?.errorCode?{errorCode:wr.PERMISSION_DENIED,error:!0}:a&&!a?.metadata?{errorCode:wr.DOES_NOT_EXIST,error:!0}:{error:!1}}catch(a){return this.loggingService.catch("Error in UserPermissionService documentDetails:",a),{errorCode:wr.DOES_NOT_EXIST,error:!0}}})}folderDetails(r){return Q(this,arguments,function*({folderId:e,organizationId:t}){try{let a=yield this.commonDbService?.getData({feature:"folderMetadata",properties:{folderId:e,organizationId:t}});return a&&a?.errorCode?{errorCode:wr.PERMISSION_DENIED,error:!0}:a&&!a?.metadata?{errorCode:wr.DOES_NOT_EXIST,error:!0}:{error:!1}}catch(a){return this.loggingService.catch("Error in UserPermissionService folderDetails:",a),{errorCode:wr.DOES_NOT_EXIST,error:!0}}})}getUserPermissions(e){return Q(this,null,function*(){try{let t=this.extractResourceIds(e),r=yield this.validateResources(t),[a,s]=yield this.fetchUserPermissionsFromDB(t),c=this.buildPermissionsResponse(t,r,a,s);return!e&&Object.keys(c).length>0&&this.setCurrentUserPermissions(c),c}catch(t){return this.loggingService.catch("Error in UserPermissionService getUserPermissions:",t),{}}})}extractResourceIds(e){let t=this.docService.getDocumentPaths(),r=this.docService.getDocumentIds();return{folderIds:e?.folderIds?.length?e.folderIds:t?.folderId?[t.folderId]:[],documentIds:e?.documentIds?.length?e.documentIds:r.map(a=>a.clientDocumentId),clientOrganizationId:e?.organizationId??t?.clientOrganizationId??"",organizationId:La(e?.organizationId??t?.clientOrganizationId??"")}}validateResources(e){return Q(this,null,function*(){let{folderIds:t,documentIds:r,organizationId:a,clientOrganizationId:s}=e,c=[],p=[];a&&(c.push(this.organizationDetails(a)),p.push({id:s,type:"organization"})),t.forEach(C=>{c.push(this.folderDetails({folderId:Fi(C),organizationId:a})),p.push({id:C,type:"folder"})}),r.forEach(C=>{c.push(this.documentDetails({documentId:na(C),organizationId:a})),p.push({id:C,type:"document"})});let u=yield Promise.allSettled(c);return this.processValidationResults(u,p)})}processValidationResults(e,t){let r=[],a=[],s,c=e.map((p,u)=>({result:p,metadata:t[u]})).filter(({result:p})=>p.status==="rejected"||p.status==="fulfilled"&&p.value.error);for(let{result:p,metadata:u}of c){let C=p.status==="fulfilled"?p.value.errorCode??wr.DOES_NOT_EXIST:wr.DOES_NOT_EXIST,E={id:u.id,errorCode:C};switch(u.type){case"organization":if(s=E,C===wr.DOES_NOT_EXIST)throw new Error(`Organization with id '${u.id}' does not exist`);break;case"folder":r.push(E);break;case"document":a.push(E);break}}return{failedFolderIds:r,failedDocumentIds:a,failedOrganizationId:s}}fetchUserPermissionsFromDB(e){return Q(this,null,function*(){let{folderIds:t,documentIds:r,organizationId:a}=e,s=[this.authService.getUser()?.userId??""],c=[...t.map(C=>Fi(C)),...r.map(C=>na(C)),a],[p,u]=yield Promise.allSettled([this.usersService.getUsersFromDBWithBatching({userIds:s,organizationId:a}),this.usersService.getTemporaryUsersFromDBWithBatching({userIds:s,organizationId:a,resourceIds:c})]);return[p.status==="fulfilled"?p.value:[],u.status==="fulfilled"?u.value:[]]})}buildPermissionsResponse(e,t,r,a){let{folderIds:s,documentIds:c,clientOrganizationId:p,organizationId:u}=e,{failedFolderIds:C,failedDocumentIds:E,failedOrganizationId:D}=t,L={};return this.processRegularUserPermissions(L,r,s,c,p,u,C,E,D),this.processTemporaryUserPermissions(L,a),L}processRegularUserPermissions(e,t,r,a,s,c,p,u,C){for(let E of t)for(let D of E)D?.user?.userId&&(e[D.user.userId]=T(I({},r.length&&{folders:this.buildFolderPermissions(r,D,p)}),{documents:this.buildDocumentPermissions(a,D,u),organization:{[s]:this.buildOrganizationPermission(c,D,C)}}))}buildFolderPermissions(e,t,r){return e.reduce((a,s)=>{let c=r.find(p=>p.id===s);return c?a[s]={error:c.errorCode===wr.DOES_NOT_EXIST?"Folder does not exist":"User does not have access to folder",errorCode:c.errorCode}:a[s]={accessRole:t.viewerFolderIds?.includes(Fi(s))?ks.VIEWER:ks.EDITOR},a},{})}buildDocumentPermissions(e,t,r){return e.reduce((a,s)=>{let c=r.find(p=>p.id===s);return c?a[s]={error:c.errorCode===wr.DOES_NOT_EXIST?"Document does not exist":"User does not have access to document",errorCode:c.errorCode}:a[s]={accessRole:t.viewerDocumentIds?.includes(na(s))?ks.VIEWER:ks.EDITOR},a},{})}buildOrganizationPermission(e,t,r){return r?{error:r.errorCode===wr.DOES_NOT_EXIST?"Organization does not exist":"User does not have access to organization",errorCode:r.errorCode}:{accessRole:t.viewerOrganizationIds?.includes(e)?ks.VIEWER:ks.EDITOR}}processTemporaryUserPermissions(e,t){for(let r of t)if(r?.userId)switch(this.ensureUserPermissionStructure(e,r.userId),r.type){case"folder":this.addTemporaryFolderPermission(e,r);break;case"document":this.addTemporaryDocumentPermission(e,r);break;case"organization":this.addTemporaryOrganizationPermission(e,r);break}}ensureUserPermissionStructure(e,t){e[t]||(e[t]={})}addTemporaryFolderPermission(e,t){let{userId:r,resourceId:a,role:s,expiresAt:c}=t;e[r].folders||(e[r].folders={}),e[r].folders[a]||(e[r].folders[a]={accessRole:s??ks.EDITOR,expiresAt:c})}addTemporaryDocumentPermission(e,t){let{userId:r,resourceId:a,role:s,expiresAt:c}=t;e[r].documents||(e[r].documents={}),e[r].documents[a]={accessRole:s??ks.EDITOR,expiresAt:c}}addTemporaryOrganizationPermission(e,t){let{userId:r,resourceId:a,role:s,expiresAt:c}=t;e[r].organization||(e[r].organization={}),e[r].organization[a]={accessRole:s??ks.EDITOR,expiresAt:c}}hasEditAccess({organizationId:e,folderId:t,documentId:r}){try{let a=!0,s=this.getCurrentUserPermissionsWithServerIds(),c=this.authService.getUser()?.userId??"";return s&&(e&&typeof e=="string"&&s?.[c]?.organization?.[e]&&(s?.[c]?.organization?.[e]?.accessRole===ks.VIEWER||s?.[c]?.organization?.[e]?.errorCode===wr.PERMISSION_DENIED)&&(a=!1),t&&typeof t=="string"&&s?.[c]?.folders?.[t]&&(s?.[c]?.folders?.[t]?.accessRole===ks.VIEWER||s?.[c]?.folders?.[t]?.errorCode===wr.PERMISSION_DENIED)&&(a=!1),r&&typeof r=="string"&&s?.[c]?.documents?.[r]&&(s?.[c]?.documents?.[r]?.accessRole===ks.VIEWER||s?.[c]?.documents?.[r]?.errorCode===wr.PERMISSION_DENIED)&&(a=!1)),a}catch{return!0}}getCurrentUserPermissions$(){return this.currentUserPermissions$.asObservable().pipe(Et(mn))}refactorPermissionsWithServerIds(e){try{let t=JSON.parse(JSON.stringify(e??{})),r=this.authService.getUser()?.userId??"";if(t?.[r]){let a=this.docService.getDocumentPaths()?.clientOrganizationId??"";if(t?.[r]?.organization?.[a]){let s=La(a);t[r].organization&&(t[r].organization[s]=t[r].organization[a],delete t[r].organization[a])}t?.[r]?.folders&&(t[r].folders=Object.fromEntries(Object.entries(t?.[r]?.folders??{}).map(([s,c])=>[Fi(s),c]))),t?.[r]?.documents&&(t[r].documents=Object.fromEntries(Object.entries(t?.[r]?.documents??{}).map(([s,c])=>[na(s),c])))}return t}catch(t){return this.loggingService.catch("Error in UsersService refactorPermissionsWithServerIds:",t),e}}getCurrentUserPermissionsWithServerIds$(){return this.currentUserPermissions$.asObservable().pipe(ce(e=>this.refactorPermissionsWithServerIds(e)),Et(mn))}getCurrentUserPermissionsWithServerIds(){return this.refactorPermissionsWithServerIds(this.currentUserPermissions$.value)}setCurrentUserPermissions(e){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setCurrentUserPermissions","color: green;"),this.currentUserPermissions$.next(e)}catch(t){this.loggingService.catch("Error in UsersService setCurrentUserPermissions:",t)}}};o.\u0275fac=function(t){return new(t||o)(ee(Ve),ee(at),ee(y),ee(pn),ee(Vn))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var ds=(()=>{let o=class o{constructor(e,t,r,a,s,c,p,u,C,E){this.afAuth=e,this.authService=t,this.configService=r,this.databaseService=a,this.docService=s,this.commonDbService=c,this.iamService=p,this.loggingService=u,this.notificationService=C,this.userPermissionService=E,this.documentPaths=null,this.views$=new ve({}),this.commentViews$=new ve({}),this.documentViews$=new ve({}),this.locationViews$=new ve({}),this.commentViewsByOrganizationIdAndDocumentId$=new ve({}),this.documentViewsByOrganizationIdAndDocumentId$=new ve({}),this.locationViewsByOrganizationIdAndLocationId$=new ve({}),this.documentViewsEnabled$=new ve(!1),this.documentViewsSetByDocumentId={},this.loggingService.log("%c[WB] Creating CLASS: ViewsService","color: blue;");try{this.authService.setViewsService(this),this.databaseService.getDb().pipe(Le(D=>!!D),st(1)).subscribe(D=>{D&&(this.subscribeViewsData().subscribe(),this.getNotificationFeatureViews$().subscribe(L=>{this.notificationService.setNotificationViews(L)}),this.authService.getUser$().pipe(Le(L=>!!L),he(L=>this.documentViewsEnabled$.pipe(Le(z=>z),ce(()=>L))),he(L=>this.docService.getDocumentPaths$().pipe(bo(null),Bi(),ce(([z,W])=>(z?.documentId!==W?.documentId&&this.views$.next({}),W)),ce(z=>(this.documentPaths=z,this.setDocumentAsRead({documentId:this.documentPaths?.documentId??"",clientDocumentId:this.documentPaths?.clientDocumentId??""}),{_user:L,_documentPaths:z})),he(z=>this.docService.getDocumentIds$().pipe(he(W=>(W?.length&&(W.find(J=>J.documentId===this.documentPaths?.documentId)||W.push({documentId:this.documentPaths?.documentId??"",clientDocumentId:this.documentPaths?.clientDocumentId??""}),W.forEach(J=>{this.setDocumentAsRead({documentId:J.documentId,clientDocumentId:J.clientDocumentId})})),se(z))))))),he(L=>this.docService.getDocumentMetadata$().pipe(Le(z=>!!z),ce(z=>T(I({},L),{_documentMetadata:z}))))).subscribe(),this.authService.getUser$().pipe(Le(L=>!!L),he(L=>this.documentViewsEnabled$.pipe(Le(z=>z),ce(()=>L))),he(L=>this.docService.getLocation$().pipe(Le(z=>!!z))),he(L=>this.docService.getDocumentIds$().pipe(he(z=>(z.find(W=>W.documentId===this.documentPaths?.documentId)||z.push({documentId:this.documentPaths?.documentId??"",clientDocumentId:this.documentPaths?.clientDocumentId??""}),z.forEach(W=>{this.setLocationAsRead({documentId:W.documentId,clientDocumentId:W.clientDocumentId})}),se(L)))))).subscribe())},D=>{this.loggingService.catch("Error in ViewsService getDb subscription: ",D)})}catch(D){this.loggingService.catch("Error in ViewsService constructor: ",D)}}setCommentService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setCommentService","color: green;"),this.commentService=e}catch(t){this.loggingService.catch("Error in ViewsService setCommentService: ",t)}}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,t){this.loggingService.log("%c[WB] Calling FUNCTION: subscribeViewsData","color: green;");let r,a;try{if(e&&(a=En(e)),t&&typeof t=="object"){let s=Yo(t);r=En(JSON.stringify(s))}}catch(s){this.loggingService.catch("Error in ViewsService subscribeViewsData: ",s)}return ei(this.afAuth).pipe(Le(s=>!!s),he(s=>this.isFeatureAllowed({firebaseUser:s})),he(s=>s.featureAllowed?this.iamService.isUserAllowed$().pipe(ce(c=>(s.featureAllowed=c,s))):se(s)),he(s=>s.featureAllowed?se(s).pipe(he(c=>this.docService.getDocumentPaths$().pipe(ce(p=>(this.documentPaths=p,c.documentPaths=p,c)))),he(c=>a?this.getDataFromDocumentIds([a]):this.docService.getDocumentIds$().pipe(he(p=>{let u=p?.length>0?p.map(C=>C.documentId):[this.documentPaths?.documentId??""];return this.getDataFromDocumentIds(u)})))):se([])))}isFeatureAllowed(e){return this.configService.getConfig$().pipe(Le(t=>!!t),ce(t=>T(I({},e),{config:t})),he(t=>this.authService.getUser$().pipe(ce(r=>T(I({},t),{user:r})))),he(t=>t.user?se(T(I({},t),{featureAllowed:!0})):se(T(I({},t),{featureAllowed:!1}))),Et((t,r)=>t?.featureAllowed===r?.featureAllowed))}getDataFromDocumentIds(e,t){return this.getDataFromDocuments({documentIds:e,filters:t})}getCommentViewsById(e){try{return this.commentViews$.value?.[e]?this.commentViews$.value?.[e]:void 0}catch(t){this.loggingService.catch("Error in ViewsService getCommentViewsById: ",t);return}}getDocumentViewsById(e){try{return this.documentViews$.value?.[e]}catch(t){this.loggingService.catch("Error in ViewsService getDocumentViewsById: ",t);return}}getLocationViewsById(e){try{return this.locationViews$.value?.[e]}catch(t){this.loggingService.catch("Error in ViewsService getLocationViewsById: ",t);return}}getDataFromDocuments(e){if(this.configService?.getApiKey()){let{documentIds:t,filters:r}=e;return t?.some(a=>!a)||!this.documentPaths?se([]):this.documentViewsEnabled$.pipe(he(a=>a?Sn([this.getCommentViewsDataFromDocuments(),this.getDocumentViewsDataFromDocuments(t),this.getLocationViewsDataFromDocuments(t)]):Sn([this.getCommentViewsDataFromDocuments()])))}else return se(null)}getCommentViews(e){try{let t={};Object.entries(e??{}).forEach(([r,a])=>{let s=a.metadata?.documentId,c=a.views;!s||!c||(t[s]||(t[s]={}),t[s][a.annotationId]=c)}),Object.entries(t??{}).forEach(([r,a])=>{this.setCommentViewsByOrganizationIdAndDocumentId({organizationId:this.documentPaths?.organizationId,documentId:r,commentViews:a})})}catch(t){this.loggingService.catch("Error in ViewsService getCommentViews: ",t)}}getCommentViewsDataFromDocuments(){try{return this.commentService?this.commentService?.getAllCommentAnnotations({detectGhostComments:!0,addFilterCommentsOnDomCheck:!0,analytics:{enabled:!0,properties:{source:"internal",sourceId:"commentsContainer"}}}).pipe(Le(e=>!!e),dn(e=>{this.getCommentViews(e)})):se([])}catch(e){return this.loggingService.catch("Error in ViewsService getCommentViewsDataFromDocuments: ",e),se([])}}getDocumentViewsDataFromDocuments(e){let t=this.docService.getDocumentPaths()?.veltFolderId,r=this.docService.getDocumentPaths()?.allDocuments,a=se([]),s={useCollectionGroup:!0,isCollection:!0,useQuery:!0};if(this.commonDbService.shouldUseFirestore()||(s.documentId=e?.length?e[0]:void 0,s.organizationId=this.documentPaths?.organizationId),t&&r)a=this.commonDbService.dbListener({feature:"allDocumentViews",properties:T(I({},s),{firestoreQuery:[Zn(lt("metadata.apiKey","==",this.configService?.getApiKey()),lt("metadata.veltFolderId","==",t),lt("metadata.organizationId","==",this.documentPaths?.organizationId))]})});else{let c=[];for(let p=0;p<(e?.length??0);p+=j.LISTENER_BATCH_SIZE)c.push(e?.slice(p,p+j.LISTENER_BATCH_SIZE)??[]);a=Sn(c.map(p=>this.commonDbService.dbListener({feature:"allDocumentViews",properties:T(I({},s),{firestoreQuery:[Zn(lt("metadata.apiKey","==",this.configService?.getApiKey()),lt("metadata.documentId","in",p),lt("metadata.organizationId","==",this.documentPaths?.organizationId),...t?[lt("metadata.veltFolderId","==",t)]:[])]})}).pipe(da()))).pipe(ce(p=>Ba(p)))}return a.pipe(ce(c=>({data:c?.data,operation:c?.operation})),ce(({data:c,operation:p})=>{let u={};return e?(Object.entries(c??{}).forEach(([C,E])=>{let D=E.metadata?.documentId;D&&(u[D]||(u[D]={}),u[D][C]=E)}),{data:c,documentMap:u,operation:p}):{data:c,documentMap:u,operation:p}}),ce(({data:c,documentMap:p,operation:u})=>{if(u?.type==="removed"){if(u?.ids?.length){let C=this.documentViews$.value;u?.ids?.forEach(E=>{delete C?.[E]}),this.documentViews$.next(C)}}else Object.entries(p??{}).forEach(([C,E])=>{this.setDocumentViewsByOrganizationIdAndDocumentId({organizationId:this.documentPaths?.organizationId,documentId:C,documentViews:E})})}))}getLocationViewsDataFromDocuments(e){let t=this.docService.getDocumentPaths()?.veltFolderId,r=this.docService.getDocumentPaths()?.allDocuments,a=se([]),s={useCollectionGroup:!0,isCollection:!0,useQuery:!0};if(this.commonDbService.shouldUseFirestore()||(s.documentId=e?.length?e[0]:void 0,s.organizationId=this.documentPaths?.organizationId),t&&r)a=this.commonDbService.dbListener({feature:"allLocationViews",properties:T(I({},s),{firestoreQuery:[Zn(lt("metadata.apiKey","==",this.configService?.getApiKey()),lt("metadata.veltFolderId","==",t),lt("metadata.organizationId","==",this.documentPaths?.organizationId))]})});else{let c=[];for(let p=0;p<(e?.length??0);p+=j.LISTENER_BATCH_SIZE)c.push(e?.slice(p,p+j.LISTENER_BATCH_SIZE)??[]);a=Sn(c.map(p=>this.commonDbService.dbListener({feature:"allLocationViews",properties:T(I({},s),{firestoreQuery:[Zn(lt("metadata.apiKey","==",this.configService?.getApiKey()),lt("metadata.documentId","in",p),lt("metadata.organizationId","==",this.documentPaths?.organizationId),...t?[lt("metadata.veltFolderId","==",t)]:[])]})}).pipe(da()))).pipe(ce(p=>Ba(p)))}return a.pipe(ce(c=>({data:c?.data,operation:c?.operation})),ce(({data:c,operation:p})=>{let u={};return e?(Object.entries(c??{}).forEach(([C,E])=>{let D=E.metadata?.documentId;D&&(u[D]||(u[D]={}),u[D][C]=E)}),{data:c,documentMap:u,operation:p}):{data:c,documentMap:u,operation:p}}),ce(({data:c,documentMap:p,operation:u})=>{if(u?.type==="removed"){if(u?.ids?.length){let C=this.locationViews$.value;u?.ids?.forEach(E=>{delete C?.[E]}),this.locationViews$.next(C)}}else Object.entries(p??{}).forEach(([C,E])=>{this.setLocationViewsByOrganizationIdAndDocumentId({organizationId:this.documentPaths?.organizationId,documentId:C,locationViews:E})})}))}setViewsData(e){try{this.views$.next(I(I({},this.views$.getValue()),e||{}))}catch(t){this.loggingService.catch("Error in ViewsService setViewsData:",t)}}setCommentViewsByOrganizationIdAndDocumentId({organizationId:e,documentId:t,commentViews:r,queryHash:a}){try{if(r||(r={}),t){e||(e=j.NO_ORGANIZATION_ID),a||(a=j.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]),{[t]:T(I({},this.commentViewsByOrganizationIdAndDocumentId$.value[e]?.[t]),{[a]:r})})}))}}catch(s){this.loggingService.catch("Error in CommentService setCommentAnnotationsByOrganizationIdAndDocumentId:",s)}}setDocumentViewsByOrganizationIdAndDocumentId({organizationId:e,documentId:t,documentViews:r,queryHash:a}){try{if(r||(r={}),t){e||(e=j.NO_ORGANIZATION_ID),a||(a=j.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]),{[t]:T(I({},this.documentViewsByOrganizationIdAndDocumentId$.value[e]?.[t]),{[a]:r})})}))}}catch(s){this.loggingService.catch("Error in CommentService setCommentAnnotationsByOrganizationIdAndDocumentId:",s)}}setLocationViewsByOrganizationIdAndDocumentId({organizationId:e,documentId:t,locationViews:r,queryHash:a}){try{if(r||(r={}),t){e||(e=j.NO_ORGANIZATION_ID),a||(a=j.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]),{[t]:T(I({},this.locationViewsByOrganizationIdAndLocationId$.value[e]?.[t]),{[a]:r})})}))}}catch(s){this.loggingService.catch("Error in CommentService setCommentAnnotationsByOrganizationIdAndDocumentId:",s)}}getCommentFeatureViews$(){return this.commentViews$.pipe(Et((e,t)=>JSON.stringify(e||{})===JSON.stringify(t||{})))}setCommentAnnotationAsRead(e){return Q(this,null,function*(){try{if(this.authService.getUser()&&e?.annotationId){this.updateCommentAnnotationViews(e);let r=e?.metadata?.organizationId??this.documentPaths?.organizationId??"",a=e?.metadata?.documentId??this.documentPaths?.documentId??"";yield this.commonDbService.setData({feature:"comment",properties:{id:e.annotationId,documentId:a,organizationId:r,metadata:{apiKey:this.configService.getApiKey(),organizationId:r,veltFolderId:e?.metadata?.veltFolderId,documentId:a}},data:JSON.parse(JSON.stringify(e))})}}catch(t){this.loggingService.catch("Error in ViewsService setCommentAnnotationAsRead:",t)}})}updateCommentAnnotationViews(e){try{let t=this.authService.getUser(),r={views:{},comments:{}};if(t){let a={},s=e?.views?.comments||{},c=new Date().getTime()+this.commonDbService.getOffset();e.comments?.forEach(u=>{s[u.commentId]||(s[u.commentId]={views:{}}),s[u.commentId].views||(s[u.commentId].views={}),s[u.commentId].views[t.userSnippylyId]||(s[u.commentId].views[t.userSnippylyId]={timestamp:c})});let p=new Set(e.comments?.map(u=>u.commentId+""));if(Object.keys(s??{}).forEach(u=>{p.has(u)||delete s[u]}),e.comments?.length){let u=s[e.comments[0].commentId]?.views||{},C=Object.keys(u??{}).filter(E=>e.comments?.every(D=>s[D.commentId]?.views?.[E]));C.forEach(E=>{a[E]={timestamp:u[E].timestamp}}),e.viewedByUserIds=C}r.views=a,r.comments=s,e.views=r}return r}catch(t){return this.loggingService.catch("Error in ViewsService updateCommentAnnotationViews:",t),{views:{},comments:{}}}}getNotificationFeatureViews$(){return this.views$.pipe(Et((e,t)=>JSON.stringify(e?.notification||{})===JSON.stringify(t?.notification||{})))}setNotificationsAsRead(e){try{let t=this.authService.getUser();if(t){let r=new Date().getTime()+this.commonDbService.getOffset();e.forEach(a=>{this.commonDbService.updateData({feature:"notificationViewsTimestamp",properties:{id:a,user:t.userSnippylyId,documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??""},data:{timestamp:r}})})}}catch(t){this.loggingService.catch("Error in ViewsService setNotificationAsRead:",t)}}getDocumentViews$(){return this.views$.pipe(Et((e,t)=>JSON.stringify(e?.documentViews||{})===JSON.stringify(t?.documentViews||{})))}getUniqueViewsByUser(e){try{return this.enableDocumentViews(),this.docService.getDocumentPaths$().pipe(he(t=>(this.documentPaths=t,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||{}:{}})))),Et(mn))}catch(t){return this.loggingService.catch("Error in ViewsService getUniqueViewsByUser:",t),se({})}}getUniqueViewsByDate(e){try{return this.enableDocumentViews(),this.docService.getDocumentPaths$().pipe(he(t=>(this.documentPaths=t,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(t){return this.loggingService.catch("Error in ViewsService getUniqueViewsByDate:",t),se({})}}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 Q(this,arguments,function*({documentId:e,clientDocumentId:t}){try{let a=this.authService.getUser();if(a&&e&&this.userPermissionService?.hasEditAccess({documentId:e??"",folderId:this.documentPaths?.allDocuments&&this.documentPaths?.veltFolderId?this.documentPaths?.veltFolderId:void 0})){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 u=new Date().toISOString().split("T")[0];p?.users[a.userSnippylyId]||(p.users[a.userSnippylyId]={}),p.users[a.userSnippylyId][u]={timestamp:this.timestamp},p?.day[u]||(p.day[u]={}),p.day[u][a.userSnippylyId]={timestamp:this.timestamp},p.metadata=this.docService.getBaseMetadata("documentViews",{clientDocumentId:t}),this.commonDbService.updateData({feature:"documentViews",properties:{id:e,date:u,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:t})}),this.docService.getDocumentMetadata$(e).pipe(Le(u=>u!==null),st(1)).subscribe(()=>{let u={day:{[c]:{[a.userSnippylyId]:{timestamp:s}}},users:{[a.userSnippylyId]:{[c]:{timestamp:s}}},metadata:this.docService.getBaseMetadata("documentViews",{clientDocumentId:t})};this.commonDbService.updateData({feature:"documentViews",properties:{id:e,date:c,user:a.userSnippylyId,documentId:e,organizationId:this.documentPaths?.organizationId??"",skipRtdb:!0},data:u})});this.checkAndTriggerNotification(a)}}catch(a){this.loggingService.catch("Error in ViewsService setDocumentAsRead:",a)}})}checkAndTriggerNotification(e){try{this.getUniqueViewsByUser().pipe(st(1)).subscribe(t=>{if(Object.keys(t??{}).length===2){let r=this.docService.getDocumentMetadata();if(r?.creator?.email&&r?.creator?.email!==e.email){let a=[r.creator.email];this.updateNotificationsDatabase(xj.FIRST_VIEWED,{documentViews:{emails:a}})}}})}catch(t){this.loggingService.catch("Error in checkAndTriggerNotification:",t)}}setLocationAsRead(r){return Q(this,arguments,function*({documentId:e,clientDocumentId:t}){try{let a=this.authService.getUser(),s=this.docService.getLocation(),c=s?.locationId,p=s?.location;if(a&&c&&p){let u=new Date().getTime()+this.commonDbService.getOffset(),C=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:t}),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:C,documentId:e,organizationId:this.documentPaths?.organizationId??"",skipFirestore:!0},data:{timestamp:u}}),this.commonDbService.updateData({feature:"locationDayViews",properties:{id:c,date:C,user:a.userSnippylyId,documentId:e,organizationId:this.documentPaths?.organizationId??"",skipFirestore:!0},data:{timestamp:u}}),this.commonDbService.updateData({feature:"locationMetadataViews",properties:{id:c,documentId:e,organizationId:this.documentPaths?.organizationId??"",skipFirestore:!0},data:this.docService.getBaseMetadata("locationViews",{clientDocumentId:t})});let D={day:{[C]:{[a.userSnippylyId]:{timestamp:u}}},users:{[a.userSnippylyId]:{[C]:{timestamp:u}}},metadata:this.docService.getBaseMetadata("locationViews",{clientDocumentId:t}),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,t={}){try{let r=I({actionType:e,notificationSource:"documentViews"},t);this.notificationService.updateNotificationDatabase(r)}catch(r){this.loggingService.catch("Error in CommentService updateNotificationsDatabase: ",r)}}get timestamp(){return this.commonDbService.getServerTimestamp()}};o.\u0275fac=function(t){return new(t||o)(ee(Di),ee(Ve),ee(Ft),ee(Dn),ee(at),ee(pn),ee(vn),ee(y),ee(gn),ee(y0))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var Hd=(()=>{let o=class o{constructor(e,t,r){this.docService=e,this.loggingService=t,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 Q(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 t=this.docService.getOrganizationMetadata(this.docService.getOrganizationConfig()?.organizationId),r=this.docService.getDocumentMetadataOfAvailableDocuments(),a=this.docService.getLocation();t&&(t=JSON.parse(JSON.stringify(t)),delete t?.organizationId,t.organizationId=t?.clientOrganizationId,delete t?.clientOrganizationId,delete t?.pageInfo),r&&(r=JSON.parse(JSON.stringify(r)),r.forEach(C=>{delete C?.locations,delete C?.location,delete C?.locationId,delete C?.pageInfo,delete C?.documentId,C.documentId=C?.clientDocumentId,delete C?.clientDocumentId,delete C?.veltFolderId,C?.clientOrganizationId&&(C.organizationId=C?.clientOrganizationId,delete C?.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(C=>{C?.location&&s.push(C?.location)});let p=this.docService.getDocumentPaths()?.folderId;return{organization:t,documents:r,locations:s,folderId:p}}catch(e){return this.loggingService.catch("Error in MetadataService getGlobalMetadata: ",e),{}}})}};o.\u0275fac=function(t){return new(t||o)(ee(at),ee(y),ee(Ve))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var b0=(()=>{let o=class o{constructor(e,t,r){this.coreActionsService=e,this.loggingService=t,this.metadataService=r,this.buttonClickSubject$=new tt,this.buttonToggleMap$=new ve({}),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 Q(this,arguments,function*({id:e,type:t,groupId:r,contextData:a}){try{this.buttonToggle(e,void 0,t,r);let c=this.extractButtonData(a),p=this.createButtonContext(e,t,r),u=yield this.metadataService.getGlobalMetadata(),C=T(I({buttonContext:p},c),{metadata:u});this.buttonClickSubject$.next(C),this.coreActionsService.triggerAction($i.VELT_BUTTON_CLICK,C)}catch(c){this.loggingService.catch("Error in ButtonService buttonClick: ",c)}})}buttonActive({id:e,type:t,groupId:r,contextData:a}){try{let s=this.buttonToggleMap$.value?.[r||"ungrouped"]?.[e]||!0;this.buttonToggle(e,s,t,r)}catch(s){this.loggingService.catch("Error in ButtonService buttonClick: ",s)}}buttonToggle(e,t,r,a){try{let s=this.buttonToggleMap$.value,c=this.createNewToggleMap(s,e,t,r,a);this.buttonToggleMap$.next(c)}catch(s){this.loggingService.catch("Error in ButtonService buttonToggle: ",s)}}extractButtonData(e){try{let t={};return Object.entries(this.contextDataMapping).forEach(([r,a])=>{let s=this.getNestedValue(e,a.source);s!==void 0&&(t[a.target]=s)}),t}catch(t){return this.loggingService.catch("Error in ButtonService extractContextData: ",t),{}}}getNestedValue(e,t){try{let r=e;for(let a of t){if(r?.[a]===void 0)return;Gi(r[a])?r=r[a]():r=r[a]}return r}catch(r){this.loggingService.catch("Error in ButtonService getNestedValue: ",r);return}}createButtonContext(e,t,r){try{let a={type:t,selections:this.buttonToggleMap$.value,clickedButtonId:e};return(t==="single-select"||t==="multi-select")&&r?T(I({},a),{groupId:r}):a}catch(a){return this.loggingService.catch("Error in ButtonService createButtonMetadata: ",a),{}}}createNewToggleMap(e,t,r,a,s){try{let c=I({},e);return a==="button-toggle"?T(I({},c),{ungrouped:T(I({},c.ungrouped),{[t]:r??!c.ungrouped?.[t]})}):a==="single-select"&&s?T(I({},c),{[s]:{[t]:r??!0}}):a==="multi-select"&&s?T(I({},c),{[s]:T(I({},c[s]),{[t]:r??!c[s]?.[t]})}):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 Q(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(u=>{Object.keys(p[u]).forEach(C=>{C===s&&delete p?.[u]?.[C]})}),this.buttonToggleMap$.next(p)}else this.buttonToggleMap$.next({});let t={selections:this.buttonToggleMap$.value},r=yield this.metadataService.getGlobalMetadata(),a={buttonContext:t,metadata:r};this.coreActionsService.triggerAction($i.VELT_BUTTON_CLICK,a)}catch(t){this.loggingService.catch("Error in ButtonService resetVeltButtonState: ",t)}})}buttonToggleMapValue(){return this.buttonToggleMap$.value}};o.\u0275fac=function(t){return new(t||o)(ee(Vd),ee(y),ee(Hd))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var De=(()=>{let o=class o{constructor(e,t,r,a,s,c,p,u,C,E,D,L,z,W,J,ue,ye,Ae,He,Fe,xe,Se,we,_e,fe,Oe,Ne){this.analyticsService=e,this.areaService=t,this.commonDbService=r,this.configService=a,this.docService=s,this.databaseService=c,this.authService=p,this.domService=u,this.afAuth=C,this.avatarService=E,this.contactService=D,this.storageService=L,this.functions=z,this.dialog=W,this.iamService=J,this.loggingService=ue,this.notificationService=ye,this.customFilterService=Ae,this.reactionService=He,this.hotkeyService=Fe,this.recorderService=xe,this.viewsService=Se,this.buttonService=we,this.metadataService=_e,this.commonDbUtilsService=fe,this.attachmentResolverService=Oe,this.userPermissionService=Ne,this.customPinsById=new Map,this.commentAdded$=new tt,this.commentUpdated$=new tt,this.commentAccepted$=new tt,this.commentRejected$=new tt,this.commentAnnotationDeleted$=new tt,this.multiThreadCommentAnnotationDeleted$=new tt,this.commentAnnotationById$=new ve(null),this.multiThreadCommentAnnotationById$=new ve(null),this.ghostCommentAnnotationMap$=new ve({}),this.unreadCommentsMap$=new ve(null),this.documentPaths=null,this.user=null,this.customCategoryMap=j.CommentCategoryMap,this.allowedElementIds$=new ve([]),this.allowedElementClassNames$=new ve([]),this.allowedElementQuerySelectors$=new ve([]),this.addCommentMode$=new ve(!1),this.persistentCommentMode$=new ve(!1),this.seenByUsers$=new ve(!0),this.deleteReplyConfirmation$=new ve(!1),this.persistentModeBanner$=new ve(!0),this.commentAddedEmitter=null,this.commentContextProvider=null,this.textCommentMode$=new ve(!0),this.sidebarVisible$=new ve(!1),this.sidebarOpenedByCustomTrigger$=new ve(!1),this.floatingCommentsEnabled$=new ve(!0),this.moderatorMode$=new ve(!1),this.streamMode$=new ve(!1),this.enableSignInButton$=new ve(!1),this.enableUpgradeButton$=new ve(!1),this.onSignInClick$=new tt,this.onUpgradeClick$=new tt,this.enableAttachment$=new ve(!0),this.enableReactions$=new ve(!0),this.allowedRecordings$=new ve(["audio","video","screen"]),this.openSidebar$=new tt,this.showScreenSizeInfo$=new ve(!1),this.showCommentIndex$=new ve(!1),this.popoverMode$=new ve(!1),this.popoverTriangleComponent$=new ve(!0),this.draftMode$=new ve(!0),this.enableDialogOnHover$=new ve(!0),this.enableDialogOnTargetElementClick$=new ve(!1),this.enablePriority$=new ve(!1),this.enableStatus$=new ve(!0),this.enableResolve$=new ve(!0),this.enableGhostComments$=new ve(!1),this.enableGhostCommentsMessage$=new ve(!0),this.inboxMode$=new ve(!1),this.enableAutoCategorize$=new ve(!1),this.commentContainerDarkMode$=new ve(!1),this.suggestionMode$=new ve(!1),this.mobileMode$=new ve(!0),this.inlineCommentMode$=new ve(!1),this.minimap$=new ve(!1),this.commentsOnDom$=new ve(!0),this.commentToolEnabled$=new ve(!0),this.totalMediaLength$=new ve(0),this.sidebarUrlNavigationEnabled$=new ve(!1),this.detectionStrategy$=new ve($P.DEFAULT),this.sidebarButtonOnCommentDialogVisible$=new ve(!1),this.sidebarButtonOnCommentDialogClick$=new tt,this.commentNavigationButtonClick$=new tt,this.deviceIndicatorOnCommentPins$=new ve(!1),this.sidebarCommentClick$=new tt,this.privateCommentMode$=new ve(!1),this.scrollToComment$=new ve(!0),this.userMentions$=new ve(!0),this.deleteOnBackspace$=new ve(!0),this.hotkeyEnabled$=new ve(!1),this.recordingSummaryEnabled$=new ve(!0),this.unreadIndicatorMode$=new ve(Ju.MINIMAL),this.composerMode$=new ve(eh.DEFAULT),this.enterKeyToSubmit$=new ve(!1),this.resolvedCommentsOnDom$=new ve(!1),this.bubbleOnPinEnabled$=new ve(!1),this.bubbleOnPinHoverEnabled$=new ve(!0),this.excludeLocationIdsFromSidebar$=new ve([]),this.multiThread$=new ve(!1),this.groupMatchedComments$=new ve(!1),this.shortUserName$=new ve(!0),this.collapsedComments$=new ve(!1),this.fullExpanded$=new ve(!1),this.queryParamsComments$=new ve(!1),this.resolveStatusAccessAdminOnly$=new ve(!1),this.linkCallback$=new ve(!1),this.svgAsImg$=new ve(!1),this.commentToNearestAllowedElement$=new ve(!1),this.filterCommentsOnDom$=new ve(!1),this.maxReplyAvatars$=new ve(3),this.replyAvatars$=new ve(!1),this.commentplaceholder$=new ve(void 0),this.replyplaceholder$=new ve(void 0),this.pinShadowDOM$=new ve(!0),this.dialogShadowDOM$=new ve(!0),this.textCommentToolShadowDOM$=new ve(!0),this.pinDarkMode$=new ve(null),this.textCommentToolDarkMode$=new ve(null),this.textCommentToolbarDarkMode$=new ve(null),this.textCommentToolbarShadowDOM$=new ve(!0),this.sidebarShadowDOM$=new ve(!0),this.changeDetectionInCommentMode$=new ve(!1),this.commentSelectionChange$=new tt,this.commentsFromSidebarMap$=new ve(null),this.sidebarButtonCountType$=new ve("default"),this.filterGhostCommentsInSidebar$=new ve(!1),this.commentSidebarFilters$=new ve({}),this.commentSidebarSystemFiltersOperator$=new ve(Dc.AND),this.bubbleCommentAnnotationIds$=new ve([]),this.updateCommentDialogPositionTriggerSubject$=new ve(void 0),this.areaCommentEnabled$=new ve(!0),this.commentPinCursorImage$=new ve(""),this.commentAnnotationsFromCommentsContainer$=new ve([]),this.customChipDropdownData$=new ve(null),this.originalCommentAnnotationsByDocumentId$=new ve({}),this.draftCommentAnnotationsByAnnotationId$=new ve(null),this.draftMultiThreadCommentAnnotationsByAnnotationId$=new ve({}),this.copyLink$=new ve(""),this.addCommentDragMode=!1,this.dragSubscriptions=[],this.hotkeySubscriptions=[],this.sidebarData$=new ve(null),this.sidebarCustomActionEventData$=new ve(null),this.sidebarCustomActionEventDataAllChanges$=new ve(null),this.sidebarCustomActionEventDataOnInit$=new ve(null),this.customActions$=new ve(!1),this.focusedThreadMode$=new ve(!1),this.customStatusesShown$=new ve(!1),this.readOnly$=new ve(!1),this.customAutocompleteSearch$=new ve(!1),this.deleteThreadWithFirstComment$=new ve(!0),this.transformContext$=new ve(null),this.expandMentionGroups$=new ve(!1),this.showMentionGroupsFirst$=new ve(!1),this.showMentionGroupsOnly$=new ve(!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.viewsService.setCommentService(this),this.docService.getDocumentPaths$().pipe(Bi()).subscribe(([Ct,On])=>{Ct?.documentId!==On?.documentId&&this.unreadCommentsMap$.next(null),On&&this.shouldEnableReadOnly()},Ct=>{this.loggingService.catch("Error in CommentService getDocumentPaths$ subscription: ",Ct)}),this.authService.getUser$().subscribe(Ct=>{Ct||this.resetCacheData()},Ct=>{this.loggingService.catch("Error in CommentService getUser$ subscription: ",Ct)}),this.databaseService.getDb().pipe(Le(Ct=>!!Ct),st(1)).subscribe(Ct=>{Ct&&this.getDocumentPaths()},Ct=>{this.loggingService.catch("Error in CommentService getDb subscription: ",Ct)}),this.domService.onWindowPointerMove$().subscribe(Ct=>{if(this.addCommentMode$.value){let On=!0;if(this.addCommentDragMode)this.domService.removeClassFromElement(document.body,"show-pin-cursor");else{let yt=this.domService.getBackgroundElement(Ct.clientX,Ct.clientY,!0,!0);if(yt)if(this.isElementInsideAllowedElements(yt))if(Vm(Ct.target))this.domService.removeClassFromElement(document.body,"show-pin-cursor");else{this.domService.addClassToElement(document.body,"show-pin-cursor"),this.hightlightElement&&this.hightlightElement!==yt&&this.domService.removeHighlightFromElement(this.hightlightElement),this.hightlightElement=yt;let Rt=this.domService.getSelectedAnnotationsMap("comment")||{},Bt=this.commentPinCursorImage$.value||j.CURSOR.COMMENT_PIN;this.domService.highlightElement(this.hightlightElement,Bt,!!Object.keys(Rt)?.length),On=!1}else this.domService.removeClassFromElement(document.body,"show-pin-cursor")}this.hightlightElement&&On&&(this.domService.removeHighlightFromElement(this.hightlightElement),this.hightlightElement=null)}},Ct=>{this.loggingService.catch("Error in CommentService onWindowPointerMove$ subscription: ",Ct)}),this.domService.onWindowKeyupEsc$().subscribe(Ct=>{if(this.addCommentMode$.value){let On=this.domService.getSelectedAnnotationsMap("comment")||{};Object.keys(On)?.length?this.domService.resetSelectedAnnotationsMap():this.disableAddCommentMode()}},Ct=>{this.loggingService.catch("Error in CommentService onWindowKeyupEsc$ subscription: ",Ct)}),this.domService.onDocumentClick$().subscribe(Ct=>{if(Ct?.target&&!Xi(Ct?.target)){let On=this.domService.getSelectedAnnotationsMap("comment")||{};if(On=I(I({},On),this.domService.getSelectedAnnotationsMap("multiThread")||{}),Object.keys(On)?.length&&(this.domService.resetSelectedAnnotationsMap(),this.persistentCommentMode$?.value)){this.addCommentMode$.value&&this.detectToAddAreaComment(),Ct.preventDefault(),Ct.stopPropagation();return}}if(Ct&&this.addCommentMode$.value&&!Vm(Ct.target)){let On=!1;if(this.addCommentDragMode)Ct.preventDefault(),Ct.stopPropagation(),this.addCommentDragMode=!1;else if(!this.domService.getDraftCommentAnnotationDialogs()?.length){let yt=this.domService.getBackgroundElement(Ct.clientX,Ct.clientY);if((this.persistentCommentMode$?.value&&this.domService.getBackgroundVeltElement(Ct.clientX,Ct.clientY)||Ct?.target&&Xi(Ct?.target))&&(yt=null),yt&&(this.isElementInsideAllowedElements(yt)||this.getCommentToNearestAllowedElement()&&this.getNearestAllowedElement(yt))&&(On=this.isElementInsideManualCommentContainer(yt),!On)){Ct.preventDefault(),Ct.stopPropagation();let Rt=this.freeStyleCommentContext&&typeof this.freeStyleCommentContext=="object"?JSON.parse(JSON.stringify(this.freeStyleCommentContext)):void 0;this.addComment(Ct,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,void 0,void 0,void 0,void 0,Rt)}}this.persistentCommentMode$?.value?this.detectToAddAreaComment():On||this.disableAddCommentMode()}},Ct=>{this.loggingService.catch("Error in CommentService onDocumentClick$ subscription: ",Ct)}),this.addCommentMode$.subscribe(Ct=>{this.hightlightElement&&this.domService.removeHighlightFromElement(this.hightlightElement),Ct?(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(On=>On.unsubscribe()),this.clearFreeStyleCommentContext())},Ct=>{this.loggingService.catch("Error in CommentService addCommentMode$ subscription: ",Ct)}),this.domService.onWindowKeyupBackspace$().subscribe(Ct=>{this.getDeleteOnBackspace()&&this.deleteCommentPinAnnotations("keyupBackspace")},Ct=>{this.loggingService.catch("Error in CommentService onWindowKeyupBackspace$ subscription: ",Ct)}),this.domService.onWindowKeyupDelete$().subscribe(Ct=>{this.deleteCommentPinAnnotations("keyupDelete")},Ct=>{this.loggingService.catch("Error in CommentService onWindowKeyupDelete$ subscription: ",Ct)}),this.domService.getDeleteCommmentAnnotations$().subscribe(Ct=>{Ct?.length&&(Ct?.filter(yt=>!["tag","recorder","rewriter","arrow","area","multiThread"].includes(yt.type))).forEach(yt=>Q(this,null,function*(){yield this.deleteCommentPinAnnotation(yt)}))},Ct=>{this.loggingService.catch("Error in CommentService onWindowKeyupDelete$ subscription: ",Ct)}),this.getPopoverMode$().subscribe(Ct=>{Ct?document?.body?.setAttribute(j.ATTRIBUTES.VELT_POPOVER_MODE,"true"):document?.body?.removeAttribute(j.ATTRIBUTES.VELT_POPOVER_MODE)},Ct=>{this.loggingService.catch("Error in CommentService getPopoverMode subscription: ",Ct)}),this.customFilterService.customCategoryMap$.subscribe(Ct=>{this.customCategoryMap=Ct},Ct=>{this.loggingService.catch("Error in CommentService customCategoryMap$ subscription: ",Ct)}),this.hotkeyEnabled$.subscribe(Ct=>{Ct?this.subscribeHotkeyEvents():this.unsubscribeHotkeyEvents()},Ct=>{this.loggingService.catch("Error in CommentService hotkeyEnabled$ subscription: ",Ct)}),this.domService.getSelectedAnnotationsMap$().pipe(Bi()).subscribe(([Ct,On])=>{try{let yt=Object.values(Ct||{}).filter(Bt=>!["tag","recorder","rewriter","arrow","area"].includes(Bt.type)),Rt=Object.values(On||{}).filter(Bt=>!["tag","recorder","rewriter","arrow","area"].includes(Bt.type));yt?.forEach(Bt=>{Rt?.find(In=>In.annotationId===Bt.annotationId)||this.commentSelectionChange$.next({annotation:Gn(Bt),selected:!1})}),Rt?.forEach(Bt=>{yt?.find(In=>In.annotationId===Bt.annotationId)||this.commentSelectionChange$.next({annotation:Gn(Bt),selected:!0})})}catch(yt){this.loggingService.catch("Error in CommentService getSelectedAnnotationsMap$: ",yt)}},Ct=>{this.loggingService.catch("Error in CommentService getSelectedAnnotationsMap$ subscription: ",Ct)})}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,this.commentsFromSidebarMap$.next(null)}catch(e){this.loggingService.catch("Error in CommentService clearCache: ",e)}}setCommentActionsService(e){try{this.commentActionsService=e}catch(t){this.loggingService.catch("Error in CommentService setCommentActionsService: ",t)}}detectToAddAreaComment(){try{let e=this.areaService.getAreaEnabled(),t=this.getAreaCommentEnabled();if(e&&t){let r,a,s,c=null,p=null;this.dragSubscriptions.forEach(u=>u.unsubscribe()),this.dragSubscriptions.push(this.domService.onWindowMouseDown$().pipe(Le(u=>!Xi(u?.target)),st(1)).subscribe(u=>{c=null,p=null,this.dragSubscriptions.push(this.domService.getClickAndDragPointsObservable().subscribe(C=>{if(c===null){let E=C?.startPoint?.event?.target,D=Xi(E),L=Vm(E),z=this.isElementInsideAllowedElements(E);c=!D&&!L&&z}if(c){this.addCommentDragMode=!0,r=C.startPoint,a=C.curPoint;let E=C?.curPoint?.event?.target,D=Xi(E),L=Vm(E),z=this.isElementInsideAllowedElements(E);p=!D&&!L&&z,p?s=this.domService.drawRectangle(r,a):s?.remove()}})),this.domService.onWindowPointerUp$().pipe(Hs(1),st(1)).subscribe(C=>{if(a={x:C.clientX,y:C.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}],D=this.freeStyleCommentContext&&typeof this.freeStyleCommentContext=="object"?JSON.parse(JSON.stringify(this.freeStyleCommentContext)):void 0;this.addComment(C,void 0,E,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,void 0,void 0,D)}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(j.TAGS.VELT_AREAS)||document.querySelector(j.TAGS.SNIPPYLY_AREAS))){let t=document.createElement(j.TAGS.VELT_AREAS);document.body.appendChild(t)}}catch(e){this.loggingService.catch("Error in CommentService addAreaContainerTag: ",e)}}addIframeContainerStaticAttribute(){try{document.querySelectorAll(`[${j.ATTRIBUTES.VELT_IFRAME_CONTAINER}]`).forEach(t=>{window.getComputedStyle(t).position==="static"&&t.setAttribute(j.ATTRIBUTES.VELT_IFRAME_CONTAINER_STATIC,"true")})}catch(e){this.loggingService.catch("Error in CommentService addIframeContainerStaticAttribute: ",e)}}removeIframeContainerStaticAttribute(){try{document.querySelectorAll(`[${j.ATTRIBUTES.VELT_IFRAME_CONTAINER_STATIC}]`).forEach(t=>{t.removeAttribute(j.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(t){this.loggingService.catch("Error in CommentService setCommentAddedEmitter: ",t)}}setContextProvider(e){try{this.commentContextProvider=e}catch(t){this.loggingService.catch("Error in CommentService setContextProvider: ",t)}}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(t){this.loggingService.catch("Error in CommentService setAllowedElementIds: ",t)}}getAllowedElementIds(){return this.allowedElementIds$.asObservable()}setAllowedElementClassNames(e){try{this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{allowedElementClassNames:e}}),this.allowedElementClassNames$.next(e||[])}catch(t){this.loggingService.catch("Error in CommentService setAllowedElementClassNames: ",t)}}getAllowedElementClassNames(){return this.allowedElementClassNames$.asObservable()}setAllowedElementQuerySelectors(e){try{this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{allowedElementQuerySelectors:e}}),this.allowedElementQuerySelectors$.next(e||[])}catch(t){this.loggingService.catch("Error in CommentService setAllowedElementQuerySelectors: ",t)}}getAllowedElementQuerySelectors(){return this.allowedElementQuerySelectors$.asObservable()}getAnnotationsCount(e){try{return ei(this.afAuth).pipe(Le(t=>!!t),he(t=>this.isFeatureAllowed({firebaseUser:t,annotations:[],filteredAnnotations:[]})),he(t=>t.featureAllowed?this.iamService.isUserAllowed$().pipe(ce(r=>(t.featureAllowed=r,t))):se(t)),he(t=>t.featureAllowed?se(t).pipe(he(r=>this.docService.getDocumentPaths$().pipe(ce(a=>(this.documentPaths=a,r.documentPaths=a,r)))),he(()=>e?.documentIds?.length?se(e?.documentIds.map(r=>({clientDocumentId:r,documentId:`${En(r)}`}))):this.docService.getDocumentIds$().pipe(ce(r=>r?.length>0?r:[{documentId:this.documentPaths?.documentId??"",clientDocumentId:this.documentPaths?.clientDocumentId||""}]))),he(r=>{let a=this.authService.getUser()?.userSnippylyId,s=this.documentPaths?.organizationId,c=r?.length>0?r.map(L=>L.documentId):[this.documentPaths?.documentId??""];if(c.some(L=>!L)||!this.documentPaths)return se();let p=this.docService.getDocumentPaths()?.veltFolderId,u=this.docService.getDocumentPaths()?.allDocuments,C=se(),E=se(),D={useCollectionGroup:!0,isCollection:!0,useQuery:!0};if(p&&u)C=this.commonDbService.dbListener({feature:"allComments",properties:T(I({},D),{firestoreQuery:[Zn(lt("metadata.apiKey","==",this.configService?.getApiKey()),lt("metadata.organizationId","==",s),lt("metadata.veltFolderId","==",p),...e?.statusIds?[lt("status.id","in",e.statusIds)]:[]),fi("lastUpdated","desc"),fi("createdAt","desc")]})}).pipe(ce(L=>L?.data)),E=this.commonDbService.dbListener({feature:"allCommentViews",properties:T(I({},D),{firestoreQuery:[Zn(lt("metadata.apiKey","==",this.configService?.getApiKey()),lt("metadata.organizationId","==",s),lt("metadata.veltFolderId","==",p))]})}).pipe(ce(L=>L?.data));else{let L=[];for(let z=0;z<(c?.length??0);z+=j.LISTENER_BATCH_SIZE)L.push(c?.slice(z,z+j.LISTENER_BATCH_SIZE)??[]);C=Sn(L.map(z=>this.commonDbService.dbListener({feature:"allComments",properties:T(I({},D),{firestoreQuery:[Zn(lt("metadata.apiKey","==",this.configService?.getApiKey()),lt("metadata.organizationId","==",s),lt("metadata.documentId","in",z),...e?.statusIds?[lt("status.id","in",e.statusIds)]:[],...p?[lt("metadata.veltFolderId","==",p)]:[]),fi("lastUpdated","desc"),fi("createdAt","desc")]})}).pipe(da()))).pipe(ce(z=>Ba(z)?.data)),E=Sn(L.map(z=>this.commonDbService.dbListener({feature:"allCommentViews",properties:T(I({},D),{firestoreQuery:[Zn(lt("metadata.apiKey","==",this.configService?.getApiKey()),lt("metadata.organizationId","==",s),lt("metadata.documentId","in",z),...p?[lt("metadata.veltFolderId","==",p)]:[])]})}).pipe(da()))).pipe(ce(z=>Ba(z)?.data))}return e?.filterGhostComments&&(C=C.pipe(he(L=>L?this.getGhostCommentAnnotationMap$().pipe(ce(z=>{if(z){let W={};return Object.values(L).forEach(J=>{J?.annotationId&&!z?.[J?.annotationId]&&(W[J?.annotationId]=J)}),W}return L})):se(L)))),Sn([C,E]).pipe(he(([L,z])=>!L||!z?se(null):se([L,z]).pipe(ce(([W,J])=>{let ue=Object.values(W||{});e?.locationIds?.length&&(ue=ue.filter(xe=>e.locationIds?.includes(xe.location?.id??"")));let ye={};ue.forEach(xe=>{ye[xe.annotationId]=xe});let Ae={};Object.entries(J||{}).forEach(([xe,Se])=>{ye[xe]&&(Se?.views?.[a]||(Ae[xe]=Se))});let He=ue.reduce((xe,Se)=>{let we=Se?.metadata?.clientDocumentId;return we&&(xe[we]||(xe[we]=[]),xe[we].push(Se)),xe},{}),Fe=Object.values(Ae).reduce((xe,Se)=>{let we=Se?.metadata?.clientDocumentId;return we&&(xe[we]||(xe[we]=[]),xe[we].push(Se)),xe},{});return r.reduce((xe,{clientDocumentId:Se})=>{xe?.data||(xe.data={});let we=He[Se]?.length??0,_e=Fe[Se]?.length??0;return xe.data[Se]={total:we,unread:_e},xe},{data:{}})}),kn(W=>(this.loggingService.catch("Error in CommentService getAnnotationsCount: ",W),se(null))))))})):se(null)),ce(t=>t||{data:null}),Et(mn))}catch(t){return this.loggingService.catch("Error in CommentService getAnnotationsCount: ",t),se({data:null})}}getAllCommentAnnotations({customClientDocumentId:e,params:t,excludeDomChanges:r,detectGhostComments:a,skipPositionCalculation:s,query:c,fromCommentSidebar:p,analytics:u,addFilterCommentsOnDomCheck:C}){this.loggingService.log("%c[WB] Calling FUNCTION: getAllCommentAnnotations","color: green;");let E,D,L;u?.enabled&&this.analyticsService.trackEvent(u?.eventName||Z.Events.Comments.GET_ALL_COMMENT_ANNOTATIONS_TRIGGERED_INTERNAL,u?.properties);try{if(e&&(L=`${En(e)}`),t&&typeof t=="object"){let z=Yo(t);D=z?.id,E=En(JSON.stringify(z))}}catch(z){this.loggingService.catch("Error in CommentService getAllCommentAnnotations: ",z)}return ei(this.afAuth).pipe(Le(z=>!!z),he(z=>this.isFeatureAllowed({firebaseUser:z,annotations:[],filteredAnnotations:[]})),he(z=>z.featureAllowed?this.iamService.isUserAllowed$().pipe(ce(W=>(z.featureAllowed=W,z))):se(z)),he(z=>z.featureAllowed?se(z).pipe(he(W=>this.docService.getDocumentPaths$().pipe(ce(J=>(this.documentPaths=J,W.documentPaths=J,W)))),he(W=>c?.documentIds?.length||L?this.getDataFromDocumentIds({documentIds:L?[L]:c?.documentIds?.map(J=>`${En(J)}`),organizationId:this.documentPaths?.organizationId,query:c}).pipe(ce(J=>({res:W,data:J}))):this.docService.getDocumentIds$().pipe(he(J=>{let ue=J?.length>0?J.map(ye=>ye.documentId):[this.documentPaths?.documentId??""];return this.getDataFromDocumentIds({documentIds:ue.length>0?ue:[L??""],organizationId:this.documentPaths?.organizationId,query:c}).pipe(ce(ye=>({res:W,data:ye})))}))),he(W=>W?.data?(W.res.annotations=W.data||[],se(W.res).pipe(he(J=>this.docService.getLocation$().pipe(ce(ue=>(J.location=ue,J)))),he(J=>this.docService.getLocations$().pipe(ce(ue=>(J.customLocations=ue,J)))),he(J=>this.docService.getExcludedLocationIds$().pipe(ce(ue=>(J.excludedLocationIds=ue,J)))),ce(J=>{if(J.filteredAnnotations=[],c)return J.filteredAnnotations=J.annotations?.slice(),J;if(L&&!E||p)return J.filteredAnnotations=J.annotations?.slice(),J?.excludedLocationIds?.length&&(J.filteredAnnotations=J.filteredAnnotations?.filter(ue=>ue?.location?.id?!J.excludedLocationIds.includes(ue.location.id):!0)),J;{let ue=[],ye=[];return E?(ue.push(E),D&&ye.push(D)):(ue.push(J?.location?.locationId),ue.push(...Object.values(J?.customLocations||[]).map(Ae=>Ae.locationId)),J?.location?.location?.id&&ye.push(J?.location?.location?.id),ye.push(...Object.values(J?.customLocations||{}).map(Ae=>Ae.location?.id).filter(Ae=>!!Ae))),J.filteredAnnotations=this.filterAnnotationsByLocationIds(J?.annotations,ue,ye),J?.excludedLocationIds?.length&&(J.filteredAnnotations=J.filteredAnnotations?.filter(Ae=>Ae?.location?.id?!J.excludedLocationIds.includes(Ae.location.id):!0)),J}}),he(J=>this.iamService.isUserAdmin$().pipe(ce(ue=>(ue||(J.filteredAnnotations=J.filteredAnnotations?.filter(ye=>ye?.iam?.accessMode!==io.PRIVATE)),J)))),he(J=>this.draftCommentAnnotationsByAnnotationId$.pipe(ce(ue=>(J.filteredAnnotations=J.filteredAnnotations?.filter(ye=>!ye.isDraft),ue&&J.filteredAnnotations.push(...Object.values(ue)),J)))),he(J=>r?se(J):J?.annotations?.length&&(!this.getPopoverMode()||this.getPopoverTriangleComponent())?this.domService.onWindowResize$().pipe(ce(()=>J)):se(J)),he(J=>r?se(J):this.addCommentMode$.pipe(he(ue=>ue&&!this.getChangeDetectionInCommentMode()?se(J):J?.annotations?.length&&(!this.getPopoverMode()||this.getPopoverTriangleComponent())?this.domService.onDomChange$("CommentService getAllCommentAnnotations").pipe(ce(()=>J)):se(J)))),ce(J=>{if(!s){(!this.getPopoverMode()||this.getPopoverTriangleComponent())&&(J.filteredAnnotations=J.filteredAnnotations?.map(ye=>{let Ae=Object.assign({},ye);return this.calculateCommentAnnotationPosition(Ae,a),Ae}));let ue={};J.filteredAnnotations?.forEach(ye=>{if(ye?.targetTextRange?.commonAncestorContainer){let Ae=this.domService.getElementFromXPath(ye?.targetTextRange?.commonAncestorContainer);ue[ye.annotationId]=!!Ae}}),J.textAnnotationsElementMap=ue}return J}),he(J=>J?.annotations?.length?this.viewsService.getCommentFeatureViews$().pipe(ce(ue=>(this.updateUnreadAnnotationsMap(J?.annotations,ue),J))):se(J)))):se(null))):se(null)),ce(z=>{try{return typeof z=="object"&&z?JSON.parse(JSON.stringify(z)):z}catch{return z}}),Et((z,W)=>mn(z?.filteredAnnotations,W?.filteredAnnotations)&&mn(z?.textAnnotationsElementMap,W?.textAnnotationsElementMap)),he(z=>z?z?.filteredAnnotations?se(z?.filteredAnnotations||[]):se([]):se(null)),he(z=>C?this.filterCommentsUsingSidebarSettings(z):se(z)))}getAllMultiThreadCommentAnnotations(e,t,r,a,s){this.loggingService.log("%c[WB] Calling FUNCTION: getAllMultiThreadCommentAnnotations","color: green;");let c,p;try{if(e&&(p=En(e)),t&&typeof t=="object"){let u=Yo(t);c=En(JSON.stringify(u))}}catch(u){this.loggingService.catch("Error in CommentService getAllMultiThreadCommentAnnotations: ",u)}return ei(this.afAuth).pipe(Le(u=>!!u),he(u=>this.isFeatureAllowed({firebaseUser:u,annotations:[],filteredAnnotations:[]})),he(u=>u.featureAllowed?this.iamService.isUserAllowed$().pipe(ce(C=>(u.featureAllowed=C,u))):se(u)),he(u=>u.featureAllowed?se(u).pipe(he(C=>this.docService.getDocumentPaths$().pipe(ce(E=>(this.documentPaths=E,C.documentPaths=E,C)))),he(C=>p?this.getMultiThreadDataFromDocumentIds([p]).pipe(ce(E=>({res:C,data:E}))):this.docService.getDocumentIds$().pipe(he(E=>{let D=E?.length>0?E.map(L=>L.documentId):[this.documentPaths?.documentId??""];return this.getMultiThreadDataFromDocumentIds(D.length>0?D:[`${p}`]).pipe(ce(L=>({res:C,data:L})))}))),he(({res:C,data:E})=>E?(C.annotations=E||[],se(C).pipe(he(D=>this.docService.getLocation$().pipe(ce(L=>(D.location=L,D)))),he(D=>this.docService.getLocations$().pipe(ce(L=>(D.customLocations=L,D)))),he(D=>this.docService.getExcludedLocationIds$().pipe(ce(L=>(D.excludedLocationIds=L,D)))),ce(D=>{if(D.filteredAnnotations=[],p&&!c)return D.filteredAnnotations=D.annotations?.slice(),D?.excludedLocationIds?.length&&(D.filteredAnnotations=D.filteredAnnotations?.filter(L=>L?.location?.id?!D.excludedLocationIds.includes(L.location.id):!0)),D;{let L=[],z=[];return c?L.push(c):(L.push(D?.location?.locationId),L.push(...Object.values(D?.customLocations||[]).map(W=>W.locationId)),D?.location?.location?.id&&z.push(D?.location?.location?.id),z.push(...Object.values(D?.customLocations||{}).map(W=>W.location?.id).filter(W=>!!W))),D.filteredAnnotations=this.filterAnnotationsByLocationIds(D?.annotations,L,z),D?.excludedLocationIds?.length&&(D.filteredAnnotations=D.filteredAnnotations?.filter(W=>W?.location?.id?!D.excludedLocationIds.includes(W.location.id):!0)),D}}),he(D=>this.draftMultiThreadCommentAnnotationsByAnnotationId$.pipe(ce(L=>(D.filteredAnnotations=D.filteredAnnotations?.filter(z=>!z.isDraft),L&&D.filteredAnnotations.push(...Object.values(L)),D)))),he(D=>r?se(D):D?.annotations?.length&&(!this.getPopoverMode()||this.getPopoverTriangleComponent())?this.domService.onWindowResize$().pipe(ce(()=>D)):se(D)),he(D=>r?se(D):this.addCommentMode$.pipe(he(L=>L&&!this.getChangeDetectionInCommentMode()?se(D):D?.annotations?.length&&(!this.getPopoverMode()||this.getPopoverTriangleComponent())?this.domService.onDomChange$("CommentService getAllMultiThreadCommentAnnotations").pipe(ce(()=>D)):se(D)))),ce(D=>(s||(!this.getPopoverMode()||this.getPopoverTriangleComponent())&&(D.filteredAnnotations=D.filteredAnnotations?.map(L=>{let z=Object.assign({},L);return this.calculateCommentAnnotationPosition(z,a),z})),D)),he(D=>D?.filteredAnnotations?se(D?.filteredAnnotations||[]):se([])))):se(null))):se(null)),Et(mn))}isFeatureAllowed(e){return this.configService.getConfig$().pipe(Le(t=>!!t),ce(t=>T(I({},e),{config:t})),he(t=>this.authService.getUser$().pipe(ce(r=>(this.user=r,T(I({},t),{user:r}))))),he(t=>ro(t.config,t.user,Re.COMMENT)?se(T(I({},t),{featureAllowed:!0})):(this.loggingService.warn("Comment feature is not allowed."),se(T(I({},t),{featureAllowed:!1})))),Et((t,r)=>t?.featureAllowed===r?.featureAllowed))}getDataFromDocuments(e){let{documentIds:t,organizationId:r,query:a}=e;if(!this.configService?.getApiKey())return se(null);if(t?.some(D=>!D)||!this.documentPaths)return se(null);let s,c,p,u=[];if(a)a?.folderId&&(s=Fi(a?.folderId)),c=a?.allDocuments,a?.locationId&&(u=[...u,a?.locationId]),a?.locationIds?.length&&(u=[...u,...a?.locationIds]),p=a?.statusIds;else{s=this.docService.getDocumentPaths()?.veltFolderId,c=this.docService.getDocumentPaths()?.allDocuments;let D=this.docService.getDocumentPaths()?.locationId;D&&(u=[...u,D])}let C=se([]),E={useCollectionGroup:!0,isCollection:!0,useQuery:!0};if(this.commonDbService.shouldUseFirestore()||(E.documentId=t?.length?t[0]:void 0,E.organizationId=this.documentPaths?.organizationId),c)C=this.commonDbService.dbListener({feature:"allComments",properties:T(I({},E),{firestoreQuery:[Zn(lt("metadata.apiKey","==",this.configService?.getApiKey()),lt("metadata.organizationId","==",r??this.documentPaths?.organizationId),...s?[lt("metadata.veltFolderId","==",s)]:[],...p?[lt("status.id","in",p)]:[],...u?.length?[lt("location.id","in",u)]:[]),fi("lastUpdated","desc"),fi("createdAt","desc")]})});else{let D=[];for(let L=0;L<(t?.length??0);L+=j.LISTENER_BATCH_SIZE)D.push(t?.slice(L,L+j.LISTENER_BATCH_SIZE)??[]);C=Sn(D.map(L=>this.commonDbService.dbListener({feature:"allComments",properties:T(I({},E),{firestoreQuery:[Zn(lt("metadata.apiKey","==",this.configService?.getApiKey()),lt("metadata.organizationId","==",r??this.documentPaths?.organizationId),lt("metadata.documentId","in",L),...p?[lt("status.id","in",p)]:[],...s?[lt("metadata.veltFolderId","==",s)]:[],...u?.length?[lt("location.id","in",u)]:[]),fi("lastUpdated","desc"),fi("createdAt","desc")]})}).pipe(da()))).pipe(ce(L=>Ba(JSON.parse(JSON.stringify(L)))))}return C.pipe(he(D=>D?.data?se(D).pipe(he(L=>this.commonDbUtilsService.mergeLocationMetadataWithData$({data:L,feature:"allComments"}).pipe(ce(z=>({data:Object.values(z?.data||{}).filter(W=>typeof W=="object"),operation:z?.operation})))),ce(({data:L,operation:z})=>{let W=L.reduce((J,ue)=>{let ye=ue.metadata?.documentId;return ye&&(J[ye]||(J[ye]=[]),J[ye].push(ue)),J},{});return{data:L,documentMap:W,operation:z}}),ce(({data:L,documentMap:z,operation:W})=>p?{data:L,documentMap:z,operation:W}:(L?.length&&(L?.forEach(J=>{this.sanitizeCommentAnnotation(J)}),this.setAnnotationIndex(L),this.updateAnnotationsForSelectAllContentMode(L),L.forEach(J=>{this.customFilterService.convertLegacyAnnotationStatus(J),this.customFilterService.convertLegacyPriority(J),this.customFilterService.convertLegacyCategory(J)})),{data:L,documentMap:z,operation:W})),kn(L=>(this.loggingService.catch("Error in CommentService getDataFromDocuments: ",L),se([]))),dn(({documentMap:L})=>{p||Object.entries(L??{}).forEach(([z,W])=>{this.setOriginalCommentAnnotationsByAnnotationId(JSON.parse(JSON.stringify(W)))})}),ce(({data:L,documentMap:z,operation:W})=>({data:this.filterUserDraftComments(L),documentMap:z,operation:W})),ce(({data:L,documentMap:z,operation:W})=>({data:this.removeDraftFlags(L),documentMap:z,operation:W})),he(({data:L,documentMap:z,operation:W})=>p?se({data:L,documentMap:z,operation:W}):this.mergeDraftAnnotations(L).pipe(ce(J=>({data:J,documentMap:z,operation:W})))),ce(({data:L,documentMap:z,operation:W})=>{if(!p)if(W?.type==="removed"){if(W?.ids?.length){let J=this.commentAnnotationById$.value??{};W?.ids?.forEach(ue=>{delete J?.[ue]}),this.commentAnnotationById$.next(J)}}else Object.entries(z??{}).length?Object.entries(z??{}).forEach(([ue,ye])=>{this.setCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:this.documentPaths?.organizationId,documentId:ue,annotations:ye})}):this.commentAnnotationById$.value||this.commentAnnotationById$.next({});return L})):se(null)))}fetchCommentAnnotations(e){return Q(this,null,function*(){try{let t=this.authService.getUser();if(!t)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??t?.clientOrganizationId,s=La(a??""),c=[];e?.allDocuments||(c=e?.documentIds?.map(z=>na(z??""))??this.docService.getDocumentIds()?.map(z=>z.documentId));let p=[];if(p.push(lt("metadata.organizationId","==",s)),p.push(lt("metadata.apiKey","==",r)),e?.folderId){let z=Fi(e?.folderId);p.push(lt("metadata.veltFolderId","==",z))}if(e?.locationId&&p.push(lt("location.id","==",e?.locationId)),c?.length&&p.push(lt("metadata.documentId","in",c)),e?.resolvedBy){if(e?.order==="asc")throw new Error("Order by resolvedBy is not supported in ascending order.");p.push(lt("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(lt("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(lt("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(lt("status.id","in",e?.statusIds))}let u=new Date().getTime();if(e?.createdAfter&&p.push(lt("createdAt",">=",e?.createdAfter)),e?.createdBefore&&p.push(lt("createdAt","<=",e?.createdBefore??u)),e?.updatedAfter&&p.push(lt("lastUpdated",">=",e?.updatedAfter??u)),e?.updatedBefore&&p.push(lt("lastUpdated","<=",e?.updatedBefore??u)),p.push(fi("lastUpdated",e?.order??"desc"),fi("createdAt",e?.order??"desc")),e?.pageToken){let z=yield Aj(e?.pageToken??"","veltencrypttoken","veltencrypttoken");p.push(fce(parseInt(z,10),"lastUpdated"))}let C=e?.pageSize??100;p.push(c0(C+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>C;E=E.slice(0,C);let L=E?.reduce((z,W)=>(z[W?.annotationId]=W,z),{});return L=yield this.commonDbUtilsService.formatResponse({feature:"allComments",data:L,shouldAwait:!0}),L=this.commonDbUtilsService.mergeUsersWithData({feature:"allComments",data:L}),{data:Object.values(L??{}),hasMore:D}}catch(t){throw this.loggingService.catch("Error in CommentService fetchCommentAnnotations:",t),t}})}filterUserDraftComments(e){let t=this.authService.getUser();return e.filter(r=>(r.comments=r?.comments?.filter(a=>a?.from?.userId===t?.userId||!a?.isDraft),!!r?.comments?.length))}removeDraftFlags(e){return e.forEach(t=>delete t.isDraft),e}mergeDraftAnnotations(e){return this.draftCommentAnnotationsByAnnotationId$.pipe(ce(t=>{let r=t||{};return e?.filter(a=>{r?.[a?.annotationId]&&delete r[a?.annotationId]}),r}),ce(t=>{if(t){let r=e.slice();return r.push(...Object.values(t)),r}return e}))}getDataFromDocumentIds({documentIds:e,organizationId:t,query:r}){return this.getDataFromDocuments({documentIds:e,organizationId:t,query:r})}getMultiThreadDataFromDocumentIds(e){return this.getMultiThreadDataFromDocuments({documentIds:e})}getMultiThreadDataFromDocuments(e){if(this.configService?.getApiKey()){let{documentIds:t}=e;if(t?.some(p=>!p)||!this.documentPaths)return se(null);let r=this.docService.getDocumentPaths()?.veltFolderId,a=this.docService.getDocumentPaths()?.allDocuments,s=se([]),c={useCollectionGroup:!0,isCollection:!0,useQuery:!0};if(this.commonDbService.shouldUseFirestore()||(c.documentId=t?.length?t[0]:void 0,c.organizationId=this.documentPaths?.organizationId),r&&a)s=this.commonDbService.dbListener({feature:"allMultiThreads",properties:T(I({},c),{firestoreQuery:[Zn(lt("metadata.apiKey","==",this.configService?.getApiKey()),lt("metadata.organizationId","==",this.documentPaths?.organizationId),lt("metadata.veltFolderId","==",r))]})});else{let p=[];for(let u=0;u<(t?.length??0);u+=j.LISTENER_BATCH_SIZE)p.push(t?.slice(u,u+j.LISTENER_BATCH_SIZE)??[]);s=Sn(p.map(u=>this.commonDbService.dbListener({feature:"allMultiThreads",properties:T(I({},c),{firestoreQuery:[Zn(lt("metadata.apiKey","==",this.configService?.getApiKey()),lt("metadata.organizationId","==",this.documentPaths?.organizationId),lt("metadata.documentId","in",u),...r?[lt("metadata.veltFolderId","==",r)]:[])]})}).pipe(da()))).pipe(ce(u=>Ba(u)))}return s.pipe(he(p=>p?.data?se(p).pipe(ce(u=>({data:u?.data,operation:u?.operation})),ce(({data:u,operation:C})=>{let E=[];return u&&(E=Object.values(u??{}).filter(D=>typeof D=="object")),{data:E,operation:C}}),kn(u=>(this.loggingService.catch("Error in CommentService getMultiThreadDataFromDocumentId: ",u),se({data:[],operation:null}))),ce(({data:u,operation:C})=>{u.forEach(D=>{delete D.isDraft});let E=u.reduce((D,L)=>{let z=L.metadata?.documentId;return z&&(D[z]||(D[z]=[]),D[z].push(L)),D},{});return{data:u,documentMap:E,operation:C}}),he(({data:u,documentMap:C,operation:E})=>{let D=[];return this.commentAnnotationById$.pipe(he(()=>this.domService.getSelectedAnnotationsMap$().pipe(ce(L=>({selectedAnnotationsMap:L})))),ce(({selectedAnnotationsMap:L})=>{let z={};return Object.keys(C??{}).forEach(W=>{let J=this.getCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:this.documentPaths?.organizationId,documentId:W});J&&J?.forEach(ue=>{z[ue?.annotationId]=ue})}),D=u.filter(W=>{let J=!1;if(W?.commentAnnotations){for(let ue in W?.commentAnnotations)if(z?.[ue]&&z?.[ue]?.status?.id!==this.customFilterService.resolvedStatus.id){J=!0;break}}return J}),D.forEach(W=>{Object.keys(W?.commentAnnotations||{}).forEach(J=>{W.commentAnnotationsMap||(W.commentAnnotationsMap={}),W.commentAnnotationsMap[J]=z?.[J]})}),{data:D,operation:E}}))}),he(({data:u,operation:C})=>this.draftMultiThreadCommentAnnotationsByAnnotationId$.pipe(ce(E=>{let D=E||{};return u?.filter(L=>{D?.[L?.annotationId]&&delete D[L?.annotationId]}),D}),ce(E=>{if(E){let D=u.slice();return D.push(...Object.values(E)),{data:D,operation:C}}return{data:u,operation:C}}))),ce(({data:u,operation:C})=>{let E=u.reduce((D,L)=>{let z=L.metadata?.documentId;return z&&(D[z]||(D[z]=[]),D[z].push(L)),D},{});if(C?.type==="removed"){if(C?.ids?.length){let D=this.multiThreadCommentAnnotationById$.value;C?.ids?.forEach(L=>{delete D?.[L]}),this.multiThreadCommentAnnotationById$.next(D)}}else Object.keys(E??{}).forEach(D=>{this.setMultiThreadCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:this.documentPaths?.organizationId,documentId:D,annotations:E[D]})});return u})):se(null)))}else return se(null)}updateUnreadAnnotationsMap(e,t){try{let r=new Date(j.UNREAD_COMMENTS_CHECK_FROM_DATE)?.getTime(),a=e.filter(s=>s?.lastUpdated>r);if(t){let s={},c=!1;a.forEach(p=>{let u=0,C=t?.[p?.annotationId];if(C){let E=C?.comments;E&&p?.comments?.forEach(D=>{!E?.[D?.commentId]?.views?.[this.user?.userSnippylyId]&&this.user?.userSnippylyId!==D?.from?.userSnippylyId&&u++})}u?u!==s?.[p?.annotationId]&&(s[p?.annotationId]=u,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(t=>{if(t?.selectAllContent&&t?.targetElementId){let r=oa(t.targetElementId,["id","data-id"]);if(r){let a=r.textContent;a&&(t.targetTextRange={commonAncestorContainer:this.domService.getXPath(r),text:a,occurrence:1},delete t?.targetElement)}}})}catch(t){this.loggingService.catch("Error in CommentService updateAnnotationsForSelectAllContentMode:",t)}}setCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:e,documentId:t,annotations:r,queryHash:a}){try{if(t){e||(e=j.NO_ORGANIZATION_ID),a||(a=j.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:t}){try{return this.commentAnnotationById$.pipe(ce(()=>this.getCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:e,documentId:t})))}catch(r){return this.loggingService.catch("Error in CommentService getCommentAnnotationsByOrganizationIdAndDocumentId$:",r),se([])}}getCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:e,documentId:t}){try{let r=null;this.commentAnnotationById$.value&&(r={},Object.values(this.commentAnnotationById$.value).forEach(s=>{s?.metadata?.documentId==t&&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===t&&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),[]}}getCommentAnnotationsByDocumentId$({clientDocumentId:e,documentId:t}){try{return e&&!t&&(t=this.docService.generateDocumentId(e)),t?this.docService.getDocumentPaths$().pipe(he(r=>this.getCommentAnnotationsByOrganizationIdAndDocumentId$({organizationId:r?.organizationId,documentId:t}))):se(null)}catch(r){return this.loggingService.catch("Error in CommentService getCommentAnnotationsByDocumentId$:",r),se(null)}}getCommentAnnotationsOnCurrentOrganizationAndDocument$(){return this.docService.getDocumentPaths$().pipe(he(e=>e?.documentId?this.getCommentAnnotationsByOrganizationIdAndDocumentId$({organizationId:e.organizationId,documentId:e.documentId}):se([])))}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 t={};e?.forEach(r=>{r?.annotationId&&(t[r?.annotationId]=r)}),this.originalCommentAnnotationsByDocumentId$.next(I(I({},this.originalCommentAnnotationsByDocumentId$.value),t))}catch(t){this.loggingService.catch("Error in CommentService setOriginalCommentAnnotationsByAnnotationId:",t)}}setMultiThreadCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:e,documentId:t,annotations:r,queryHash:a}){try{if(t){e||(e=j.NO_ORGANIZATION_ID),a||(a=j.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:t}){return this.multiThreadCommentAnnotationById$.pipe(ce(()=>this.getMultiThreadCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:e,documentId:t})))}getMultiThreadCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:e,documentId:t}){try{let r={};Object.values(this.multiThreadCommentAnnotationById$.value??{}).forEach(s=>{s?.metadata?.documentId==t&&s?.metadata?.organizationId==e&&(r[s?.annotationId]=s)});let a=this.draftMultiThreadCommentAnnotationsByAnnotationId$.value;return a&&Object.values(a??{}).forEach(s=>{s?.metadata?.documentId===t&&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(he(e=>e?.documentId?this.getMultiThreadCommentAnnotationsByOrganizationIdAndDocumentId$({organizationId:e.organizationId,documentId:e.documentId}):se([])))}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(he(e=>this.docService.getLocations$().pipe(ce(t=>({location:e,locations:t})))),ce(e=>{let t=[];return t.push(e?.location?.locationId),t.push(...Object.values(e.locations||[]).map(r=>r.locationId)),t||[]}))}filterAnnotationsByLocationIds(e,t,r){try{return e.filter(a=>t.includes(a.locationId)||r?.includes(a?.location?.id)||t?.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((t,r)=>{t?.annotationId&&(t.annotationIndex=r+1)})}catch(t){this.loggingService.catch("Error in CommentService setAnnotationIndex:",t)}}calculateCommentAnnotationPosition(e,t){try{if(e.multiThreadAnnotationId)return;if(e.targetElementId){let r=oa(e.targetElementId,["id","data-id"]);if(r&&this.domService.isElementVisible(r)){let a=r.getAttribute(j.ATTRIBUTES.VELT_COMMENT_TYPE),s=!0;if(a)switch(a){case"popover":s=!0;break;default:s=!1;break}else{let c=document.querySelector(`${j.TAGS.VELT_INLINE_COMMENTS_SECTION}[${j.ATTRIBUTES.TARGET_INLINE_COMMENT_ELEMENT_ID}="${e.targetElementId}"], ${j.TAGS.VELT_INLINE_COMMENTS_SECTION}[${j.ATTRIBUTES.TARGET_COMMENT_ELEMENT_ID}="${e.targetElementId}"], ${j.TAGS.VELT_INLINE_COMMENTS_SECTION}[${j.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()===$P.DYNAMIC_ID&&(!a||!this.domService.isElementVisible(a))&&(r=e.targetElement?.fXpath,r&&(a=this.domService.getElementFromXPath(r)))),(!a||!this.domService.isElementVisible(a))&&t&&(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(!nh({location:p?.location,locationId:p?.locationId},{location:e?.location,locationId:e?.locationId})){let u=this.docService.getAdditionLocationFromElement(a),C=u?this.docService.genarateLocationId(u):void 0;e?.location?.id&&e?.location?.id===u?.id||C&&C===e?.locationId?c=!1:c=!0}}if(c&&(e.ghostComment=null),!c&&a&&Ao(a)&&!a?.closest(".cdk-overlay-container")&&a?.getBoundingClientRect()){let u=this.popoverMode$?.value?0:e.targetElement?.topPercentage,C=this.popoverMode$?.value?100:e.targetElement?.leftPercentage,{height:E,width:D}=Wp(a);e.position={top:E*(u||0)/100,left:D*(C||0)/100};let L=window.getComputedStyle(a).transform;if(L&&L!=="none")try{let z=new DOMMatrixReadOnly(L),W=Math.sqrt(z.a*z.a+z.b*z.b)||1,J=Math.sqrt(z.c*z.c+z.d*z.d)||1;(Math.abs(W-1)>.01||Math.abs(J-1)>.01)&&(e.position.parentScaleX=W,e.position.parentScaleY=J)}catch{}if(this.transformContext$.value){let{containerSelector:z,transforms:W}=this.transformContext$.value,J=document.querySelector(z);J&&J.contains(a)&&(e.position.transformContext=W)}}!c&&t&&!e?.position&&!e?.ghostComment&&(e.ghostComment={},this.setGhostCommentMessage(e),e.ghostComment.targetElement=e.targetElement)}}t&&(e.ghostComment?this.addAnnotationToGhostCommentAnnotationMap(e):this.removeAnnotationFromGhostCommentAnnotationMap(e))}catch(r){this.loggingService.catch("Error in CommentService calculateCommentAnnotationPosition:",r)}}addComment(e,t,r,a,s,c=[],p,u,C,E,D,L,z,W,J,ue,ye,Ae,He,Fe,xe,Se,we,_e){this.loggingService.log("%c[WB] Calling FUNCTION: addComment","color: green;");try{let fe=this.authService.getUser();if(fe)if(fe.isReadOnly||fe.isAnonymous)this.loggingService.catch("Anonymous/Readonly users cannot add comments.");else{let Oe=new Bo;ye&&(Oe=I(I({},Oe),ye)),Oe.comments=[],ye?.comments?.length&&(Oe.comments=ye.comments.map(Zt=>{let Yt=new Nc;return Yt=I(I({},Yt),Zt),Yt.from=fe,Yt.lastUpdated=new Date,Yt.createdAt=this.timestamp,Yt})),Oe.from=fe,Oe.color=Oe?.color||j.DEFAULT_ANNOTATION_COLOR,Oe.lastUpdated=this.timestamp,Oe.createdAt=this.timestamp,Oe.sourceId=J,Oe.assignedTo=ye?.assignedTo||ue,Oe.customList=ye?.customList||[],Se&&(Oe.targetElementId=Se);let{topPositionX:Ne,topPositionY:Ct}=this.domService.getTopLeftPosition();Oe.positionX=Ne,Oe.positionY=Ct;let On=this.domService.getCurrentWindowSizeValue();if(Oe.screenWidth=On.screenWidth,Oe.screenHeight=On.screenHeight,Oe.screenScrollHeight=On.screenScrollHeight,Oe.taggedElementPath="",e&&(Oe.targetElement=this.domService.getTargetElementForCursorPosition(e,!0,!0,!0,Zt=>{if(this.getSvgAsImg()){let Yt=Zt?.closest(`[${j.ATTRIBUTES.VELT_COMMENT_CONTAINER}]`);Yt&&Yt instanceof HTMLElement&&(Zt=Yt)}if(this.getPopoverMode()){let Yt=Zt?.closest(`[${j.ATTRIBUTES.VELT_TARGET_COMMENT_ELEMENT_ID}]`);if(Yt&&Yt instanceof HTMLElement)return Yt}return Zt}),this.getCommentToNearestAllowedElement()&&Oe.targetElement?.xpath)){let Zt=this.domService.getElementFromXPath(Oe.targetElement.xpath);if(Zt&&!this.isElementInsideAllowedElements(Zt)){let Yt=this.getNearestAllowedElement(Zt);if(Yt)Oe.targetElement.xpath=this.domService.getXPath(Yt),Oe.targetElement.fXpath=this.domService.getXPath(Yt,!0),Oe.targetElement.cfXpath=this.domService.getXPath(Yt,!0,!0);else return}}if(t&&(Oe.targetTextRange=t),Oe?.targetElement?.xpath){let Zt=this.domService.getXPath(Oe.targetElement.xpath);if(Zt){let Yt=Zt.iterateNext();Yt&&(Ao(Yt)||(Oe.targetElement=null))}}this.customFilterService.defaultStatus&&!ye?.status&&(Oe.status=this.customFilterService.defaultStatus),Oe.pageInfo=Oi(),Oe.pageInfo&&(Oe.pageInfo.screenWidth=this.domService.getCurrentWindowSizeValue()?.screenWidth);let yt=this.docService.getClientDocumentId(),Rt=this.docService.getLocation()?.location;if(He&&(Oe.context=He&&Oc(He),Oe.contextId=this.generateContextId(Oe.context)),this.commentContextProvider!==null){let Zt=this.commentContextProvider(yt,Rt);Zt&&(Oe.context=Zt&&Oc(Zt),Oe.contextId=this.generateContextId(Oe.context))}if(a){Oe.sourceId=a?.sourceId;let Zt=a?.targetElement,Yt=a?.commentData;if(Zt?.targetText)Oe.targetTextRange={commonAncestorContainer:"/html/body",text:Zt.targetText,occurrence:Zt?.occurrence||1};else if(Zt?.elementId)if(Oe.targetElementId=Zt.elementId,Zt?.selectAllContent)Oe.selectAllContent=!!Zt?.selectAllContent;else{let Xt=oa(Zt.elementId,["id","data-id"]);Xt?Oe.targetElement={xpath:this.domService.getXPath(Xt),fXpath:this.domService.getXPath(Xt,!0),cfXpath:this.domService.getXPath(Xt,!0,!0),topPercentage:50,leftPercentage:90}:Oe.targetElement={xpath:"/html/body",fXpath:"/html/body",cfXpath:"/html/body",topPercentage:50,leftPercentage:90}}a?.status&&(Oe.status=a.status),a?.context&&(Oe.context=a.context?Oc(a.context):a.context,Oe.contextId=this.generateContextId(Oe.context)),Oe.comments||(Oe.comments=[]);let Ai=this.authService.getUser();Yt?.forEach(Xt=>{let Qn=new Nc;Qn.commentText=Xt.commentText,Qn.commentHtml=Xt.commentHtml,Qn.replaceContentHtml=Xt.replaceContentHtml,Qn.replaceContentText=Xt.replaceContentText,Qn.from=Ai,Oe.comments.push(Qn)})}if(s&&(Oe.isPageAnnotation=!0),c?.length&&(Oe.comments=c),p&&(Oe.commentType="chart",Oe.metadata=p),C?.sourceId&&(Oe.sourceId=C.sourceId),Oe?.targetElement?.xpath&&!C){let Zt=this.domService.getElementFromXPath(Oe.targetElement.xpath);Zt&&(C=this.getInlineCommentSectionConfig(Zt))}C?.targetInlineCommentElementId&&(Oe.targetInlineCommentElementId=C?.targetInlineCommentElementId,Oe.targetElementId=C.targetInlineCommentElementId,C?.config?.id&&(Oe.inlineCommentSectionConfig=C?.config));let Bt=!Oe?.comments?.length,In=!!(a?.openComment===!1||Fe);this.getPrivateCommentMode()&&(Oe?.iam||(Oe.iam=new yb),Oe.iam.accessMode=io.PRIVATE),E&&(Oe.context=E.context?Oc(E.context):E.context,Oe.commentType="manual",delete Oe.targetElement,Oe.contextId=this.generateContextId(Oe.context)),D&&(Oe.targetElementId=D.targetElementId,Oe.targetElement=D.targetElement),this.saveCommentToDb(Oe,r,Bt,In,u,L,z,Ae,W,xe,we,_e)}}catch(fe){this.loggingService.catch("Error in CommentService addComment: ",fe)}}setLocationToCommentAnnotation(e){try{let t=this.docService.getLocation();t?(e.locationId=t.locationId,e.location=t.location):(delete e.locationId,delete e.location);try{let r;e.targetElement?.xpath?r=this.domService.getElementFromXPath(e.targetElement.xpath):e.targetElementId?r=oa(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({location:a,source:"internal"});s?.[0]&&(e.locationId=s[0].locationId,e.location=s[0].location)}}catch{}}catch(t){this.loggingService.catch("Error in CommentService setLocationToCommentAnnotation:",t)}}getElementForCommentAnnotation(e){try{let t;return e.targetElement?.xpath?t=this.domService.getElementFromXPath(e.targetElement.xpath):e.targetElementId?t=oa(e.targetElementId,["id","data-id"]):e.targetTextRange?.commonAncestorContainer&&(t=this.domService.getElementFromXPath(e.targetTextRange.commonAncestorContainer)),t}catch(t){return this.loggingService.catch("Error in CommentService getElementForCommentAnnotation: ",t),null}}saveCommentToDb(e,t,r=!1,a=!1,s,c,p,u,C,E,D,L){this.loggingService.log("%c[WB] Calling FUNCTION: saveCommentToDb","color: green;");try{this.authService.getUser()&&this.authService.isFeatureAllowed(Re.COMMENT)&&this.docService.getDocumentPaths$().pipe(Le(z=>!!z),st(1),he(z=>(this.documentPaths=z,this.loggingService.log(this.documentPaths),this.databaseService.getDb().pipe(Le(W=>!!W),st(1),he(W=>Q(this,null,function*(){if(this.documentPaths?.comment){e.annotationId=this.commonDbService.generateDocumentId();let J=this.docService.getClientDocumentId(),ue=this.docService.getLocation()?.location;if(p)e.multiThreadAnnotationId=p;else if(this.getMultiThread()){let we=Ad();e.targetElementId&&(we=Ad(e.targetElementId),e?.location?.id?we=Ad([e?.location?.id,e.targetElementId]):e?.locationId&&(we=Ad([e?.locationId+"",e.targetElementId]))),e.multiThreadAnnotationId=we}let ye={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&&Oc(we),e.contextId=this.generateContextId(e.context),we?.commentType==="manual"&&(e.commentType="manual",delete e.targetElement),e?.annotationId&&this.updateCommentAnnotationContext(e.annotationId,we)},documentId:J,location:ue,annotation:Gn(e),targetAnnotationId:e?.annotationId,targetCommentId:e?.comments?.length?e?.comments[0]?.commentId:void 0};e?.targetElement?.xpath?ye.elementRef={xpath:e.targetElement.xpath}:ye.elementRef=void 0,this.commentAddedEmitter!==null&&"emit"in this.commentAddedEmitter&&this.commentAddedEmitter.emit(ye),this.commentAdded$.next(ye),C&&C(ye);let Ae=yield this.commentActionsService?.getAddCommentAnnotationEventFromCommentAddEventData(ye);Ae&&this.commentActionsService?.triggerAddCommentAnnotationEvent(Ae),this.setLocationToCommentAnnotation(e);let He=this.getElementForCommentAnnotation(e),Fe=this.docService.getBaseMetadata("comment",{element:He,multiThreadAnnotationId:e.multiThreadAnnotationId});if(!Fe?.apiKey)return;if(e?.metadata||(e.metadata={}),e.metadata=I(I({},e.metadata),Fe),E&&(e.metadata=I(I({},e.metadata),E)),s&&typeof s=="object"&&(e.locationId=u||this.docService.genarateLocationId(s),e.location=s,L||this.docService.addLocation({location:s})),r)window.localStorage.setItem(j.LOCAL_STORAGE.SNIPPYLY_QUEUED_COMMENT,JSON.stringify(e));else{let we=window.localStorage.getItem(j.LOCAL_STORAGE.SNIPPYLY_QUEUED_COMMENT);we&&JSON.parse(we).annotationId===e.annotationId&&e.comments!==void 0&&e.comments.length>0&&window.localStorage.removeItem(j.LOCAL_STORAGE.SNIPPYLY_QUEUED_COMMENT)}e.pageInfo&&(e.pageInfo.commentUrl=this.generateCommentUrl(e));let xe=e.comments,Se=JSON.parse(JSON.stringify(e));if(Se.position=null,t){Se.targetElement=null,Se.targetTextRange=null;let we={annotationId:e.multiThreadAnnotationId?e.multiThreadAnnotationId:e.annotationId,type:e.multiThreadAnnotationId?Re.MULTI_THREAD:Re.COMMENT},_e=yield this.areaService.generateAreaAnnotationId();Se.areaAnnotationId=_e;let fe=this.areaService.addArea(void 0,t,we,_e,{locationId:Se.locationId,location:Se.location});fe&&(Se.metadata=I(I({},Se.metadata),fe?.metadata||{}))}!a&&!Se?.targetInlineCommentElementId&&!Se?.isPageAnnotation&&this.domService.toggleAnnotationSelection(Se,c),e.targetTextRange&&sessionStorage.setItem(j.SESSION_STORAGE.SNIPPYLY_AUTO_SELECT_ANNOTATION_ID,e?.multiThreadAnnotationId?e?.multiThreadAnnotationId:e.annotationId),Se?.comments?.length?this.analyticsService.trackEvent(Z.Events.Comments.COMMENT_ADDED,{annotationId:e.annotationId,commentThreadId:Se?.comments[0]?.commentId,commentType:this.getCommentType(Se),commentMode:this.getCommentMode(),source:D??"internal"}):this.analyticsService.trackEvent(Z.Events.Comments.COMMENT_DRAFT_ADDED,{annotationId:e.annotationId,commentType:this.getCommentType(Se),commentMode:this.getCommentMode()}),Se?.comments?.length?Se.comments=[]:Se.isDraft=!0,Se?.multiThreadAnnotationId&&this.saveMultiThreadCommentAnnotation(Se),Se?.context&&(Se.contextId=this.generateContextId(Se.context)),xe?.length&&!Se?.isDraft?this.saveComment(Se,{type:$t.NEWLY_ADDED,updatedComment:xe[0]}):(xe?.length&&(Se.comments=xe),this.draftCommentAnnotationsByAnnotationId$.next(T(I({},this.draftCommentAnnotationsByAnnotationId$.value),{[e.annotationId]:Se})))}})))))).subscribe(()=>{},z=>{this.loggingService.catch("Error in CommentService saveCommentToDb subscription: ",z)})}catch(z){this.loggingService.catch("Error in CommentService saveCommentToDb: ",z)}}saveMultiThreadCommentAnnotation(e){return Q(this,null,function*(){try{if(e?.multiThreadAnnotationId){let t=this.docService.getDocumentPaths();if(this.databaseService.getDbValue()&&t?.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:t?.organizationId,documentId:t?.documentId})?.find(s=>s.annotationId===e.multiThreadAnnotationId);if(a||(a=yield this.commonDbService?.getData({feature:"multiThread",properties:{documentId:t?.documentId??"",organizationId:t?.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 C=this.docService.getBaseMetadata();r.metadata=I(I({},r?.metadata),C)}let{documentId:p,organizationId:u}=r?.metadata||{};yield this.commonDbService.updateData({feature:"multiThread",properties:{id:r.annotationId,documentId:p,organizationId:u},data:JSON.parse(JSON.stringify(r)),callback:()=>{let C=this.draftMultiThreadCommentAnnotationsByAnnotationId$.value;C[e.annotationId]&&(delete C[e.annotationId],this.draftMultiThreadCommentAnnotationsByAnnotationId$.next(C))}})}return r}}return null}catch(t){return this.loggingService.catch("Error in CommentService saveMultiThreadCommentAnnotation: ",t),null}})}setCommentCategory(e){return Q(this,null,function*(){try{if(e?.comments?.length){let t=e.comments[0].commentText?.trim();if(t){let r=yield this.getCommentCategory(t).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:u}=this.getDocumentIdAndOrganizationIdFromCommentAnnotation(c);yield this.commonDbService.updateData({feature:"comment",properties:{id:e.annotationId,documentId:p,organizationId:u,metadata:{apiKey:this.configService.getApiKey(),organizationId:u,veltFolderId:c?.metadata?.veltFolderId,documentId:p}},data:JSON.parse(JSON.stringify(c))})}}}}}}catch(t){this.loggingService.catch("Error in CommentService setCommentCategory: ",t)}})}getCommentCategory(e){try{let t=br(this.functions,Er({url:oi.cloudFunction.chatgptCompletion,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:12e5}),a=[{role:"system",content:`Identify category of this sentence from these categories, ${Object.keys(this.customCategoryMap)?.join(", ")}:`},{role:"user",content:e}];return Zi(t({messages:a,apiKey:this.configService.getApiKey(),sdkVersion:ia(),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(t){return this.loggingService.catch("Error in CommentService getCommentCategory: ",t),se(void 0)}}updateCommentAnnotationContext(e,t,r){return Q(this,null,function*(){try{this.analyticsService.trackEvent(Z.Events.Comments.COMMENT_UPDATE_CONTEXT_TRIGGERED,{annotationId:e,context:t,merge:r?.merge});let a=this.authService.getUser(),s=this.docService.getDocumentPaths();if(a&&s?.comment&&e){let c=this.getAnnotationById(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=t,u=JSON.parse(JSON.stringify(c.context||{}));r?.merge&&(p=I(I({},u),t));let C={context:JSON.parse(JSON.stringify(p||{}))};if(C?.context?.commentType==="manual"&&(C.commentType="manual",C.targetElement=null),c.context=C.context?Oc(C.context):C.context,c.contextId=this.generateContextId(c.context),wi(u,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,metadata:{apiKey:this.configService.getApiKey(),organizationId:D,veltFolderId:c?.metadata?.veltFolderId,documentId:E}},data:JSON.parse(JSON.stringify(c)),callback:()=>{this.analyticsService.trackEvent(Z.Events.Comments.COMMENT_UPDATE_CONTEXT_SUCCESS,{annotationId:e,context:C?.context,merge:r?.merge})}})}}else return this.analyticsService.trackEvent(Z.Events.Comments.COMMENT_UPDATE_CONTEXT_FAILED,{annotationId:e,context:t,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,t,r,a,s){this.loggingService.log("%c[WB] Calling FUNCTION: updateComment","color: green;");try{if(this.authService.getUser()&&this.authService.isFeatureAllowed(Re.COMMENT)){if(t&&this.setLocationToCommentAnnotation(e),e?.targetElement?.xpath){let c=this.domService.getXPath(e.targetElement.xpath);if(c){let p=c.iterateNext();p&&(Ao(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 C=this.docService.getBaseMetadata();c.metadata=I(I({},c?.metadata),C)}let{documentId:p,organizationId:u}=c?.metadata||{};r?this.commonDbService.updateData({feature:"multiThread",properties:{id:c.annotationId,documentId:p,organizationId:u},data:JSON.parse(JSON.stringify(c))}):this.commonDbService.setData({feature:"multiThread",properties:{id:c.annotationId,documentId:p,organizationId:u},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(j.LOCAL_STORAGE.SNIPPYLY_QUEUED_COMMENT);if(p&&JSON.parse(p).annotationId===c.annotationId&&window.localStorage.removeItem(j.LOCAL_STORAGE.SNIPPYLY_QUEUED_COMMENT),c?.multiThreadAnnotationId&&!s&&this.saveMultiThreadCommentAnnotation(c).then(u=>{}),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:u,organizationId:C}=c?.metadata||{},E=a?I({annotationData:a?.commentAnnotation,targetAnnotationData:a?.targetComment,actionType:a?.actionType,notificationSource:"comment"},a?.otherFields||{}):null;this.viewsService.updateCommentAnnotationViews(c),this.commonDbService.setData({feature:"comment",properties:{id:c.annotationId,documentId:u,organizationId:C,metadata:{apiKey:this.configService.getApiKey(),organizationId:C,veltFolderId:c?.metadata?.veltFolderId,documentId:u}},extraData:E,data:JSON.parse(JSON.stringify(c)),callback:D=>{a&&!D?.firestoreAvailable&&this.updateNotificationsDatabase(a.commentAnnotation,a.targetComment,a.actionType,a.otherFields||{})}})}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(t){return this.loggingService.catch("Error in CommentService getDocumentIdAndOrganizationIdFromCommentAnnotation: ",t),{}}}getDocumentIdAndOrganizationIdFromMultiThreadCommentAnnotation(e){try{return{documentId:e?.metadata?.documentId,organizationId:e?.metadata?.organizationId}}catch(t){return this.loggingService.catch("Error in CommentService getDocumentIdAndOrganizationIdFromMultiThreadCommentAnnotation: ",t),{}}}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((t,r)=>Q(this,null,function*(){try{let a=this.domService.getSelectedAnnotationsMap(),s=this.authService.getUser(),c=[];Object.keys(a).forEach(p=>{let u=a[p];["tag","recorder","rewriter","arrow","area","multiThread"].includes(u.type)||s&&u.from&&(s?.isAdmin||u.from.userId===s.userId)&&c.push(u)}),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(Sa,{panelClass:"velt-mat-dialog-container",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(st(1)).subscribe(p=>{try{p?(c.forEach(u=>Q(this,null,function*(){yield this.deleteCommentPinAnnotation(u)})),setTimeout(()=>{document.querySelectorAll(`[${j.SNIPPYLY_HIGHLIGHT}]`).forEach(C=>{this.domService.removeHighlightFromElement(C)}),t()},100)):t()}catch(u){r(u)}},p=>{r(p)})):t(),this.domService.resetSelectedAnnotationsMap(!0,"comment")}catch(a){this.loggingService.catch("Error in CommentService deleteCommentPinAnnotations: ",a),r(a)}}))}deleteCommentPinAnnotation(e,t){return Q(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((t||e.comments?.length)&&this.updateNotificationsDatabase(e,null,$t.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(j.LOCAL_STORAGE.SNIPPYLY_QUEUED_COMMENT);r&&JSON.parse(r).annotationId===e.annotationId&&window.localStorage.removeItem(j.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,metadata:{apiKey:this.configService.getApiKey(),organizationId:c,veltFolderId:e?.metadata?.veltFolderId,documentId:s}}})}else return Promise.resolve();return Promise.resolve()}catch(r){return this.loggingService.catch("Error in CommentService deleteCommentPinAnnotation: ",r),Promise.resolve()}})}removeCommentAnnotationFromMultiThread(e){return Q(this,null,function*(){try{let t=e?.multiThreadAnnotationId;if(t){let r=this.docService.getDocumentPaths(),a=this.getMultiThreadAnnotationById(t);if(!a){let u=e?.metadata?.documentId||r?.documentId,C=e?.metadata?.organizationId||r?.organizationId;a=yield this.commonDbService?.getData({feature:"multiThread",properties:{documentId:u,organizationId:C,id:t}})}let s=this.draftMultiThreadCommentAnnotationsByAnnotationId$.value?.[t];a&&delete a?.commentAnnotations?.[e.annotationId],s&&(delete s?.commentAnnotations?.[e.annotationId],Object.keys(s?.commentAnnotations||{}).length===0&&(delete this.draftMultiThreadCommentAnnotationsByAnnotationId$.value?.[t],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(t){this.loggingService.catch("Error in CommentService removeCommentAnnotationFromMultiThread: ",t)}})}getAnnotationById(e,t){try{let r=this.commentAnnotationById$.value?.[e]||this.draftCommentAnnotationsByAnnotationId$?.value?.[e];if(r){let{documentId:a,organizationId:s}=t||{};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 t=this.commentAnnotationById$.value?.[e];if(t)return t.metadata}catch(t){this.loggingService.catch("Error in CommentService getBaseMetadataFromCommentAnnotationId: ",t)}}getMultiThreadAnnotationById(e,t){try{let r=this.multiThreadCommentAnnotationById$.value?.[e]||this.draftMultiThreadCommentAnnotationsByAnnotationId$?.value?.[e];if(r){let{documentId:a,organizationId:s}=t||{};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 t=this.multiThreadCommentAnnotationById$.value?.[e];if(t)return t.metadata}catch(t){this.loggingService.catch("Error in CommentService getBaseMetadataFromMultiThreadCommentAnnotationId: ",t)}}getElementRefByAnnotationId(e){try{let t=this.getAnnotationById(e);if(t){let r=t?.targetElement?.xpath;if(r)return{xpath:r}}return}catch(t){this.loggingService.catch("Error in CommentService getElementRefByAnnotationId: ",t);return}}scrollToCommentByAnnotationId(e){try{let t=this.getAnnotationById(e),r=document.getElementById(`comment-pin-container-${e}`);r||(r=document.querySelector(`[data-velt-id='${e}']`)),r||(r=document.querySelector(`${j.TAGS.VELT_COMMENT_TEXT}[${j.ATTRIBUTES.ANNOTATION_ID}="${e}"]`)),r&&(r.scrollIntoView({behavior:"smooth",block:"center",inline:"nearest"}),t&&(this.domService.getSelectedAnnotationsMap()[e]||this.domService.toggleAnnotationSelection(t)))}catch(t){this.loggingService.catch("Error in CommentService scrollToCommentByAnnotationId: ",t)}}selectCommentByAnnotationId(e,t){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([vo.ADMIN,vo.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()}setFreeStyleCommentContext(e){try{this.freeStyleCommentContext=e}catch(t){this.loggingService.catch("Error in CommentService setFreeStyleCommentContext: ",t)}}clearFreeStyleCommentContext(){try{this.freeStyleCommentContext=void 0}catch(e){this.loggingService.catch("Error in CommentService resetFreeStyleCommentContext: ",e)}}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(t){this.loggingService.catch("Error in CommentService showCommentIndex: ",t)}}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,t=!1,r=!1){try{this.domService.resetSelectedAnnotationsMap(),e?(document.querySelector(j.TAGS.VELT_COMMENTS_SIDEBAR)||document.querySelector(j.TAGS.SNIPPYLY_COMMENTS_SIDEBAR)?this.sidebarVisible$.next(e):this.loggingService.catch("Error in CommentService setSidebarVisibility: ",`<${j.TAGS.VELT_COMMENTS_SIDEBAR}> tag is not added.`),t&&this.sidebarOpenedByCustomTrigger$.next(!0)):(!this.sidebarOpenedByCustomTrigger$.value||t||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: ",`<${j.TAGS.VELT_COMMENTS_SIDEBAR}> tag is not added.`)}}toggleSidebarVisibility(e=!1,t=!1){try{this.domService.resetSelectedAnnotationsMap(),this.sidebarVisible$.value?(!this.sidebarOpenedByCustomTrigger$.value||e||t)&&(this.sidebarVisible$.next(!this.sidebarVisible$.value),this.sidebarOpenedByCustomTrigger$.next(!1)):(document.querySelector(j.TAGS.VELT_COMMENTS_SIDEBAR)||document.querySelector(j.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: ",`<${j.TAGS.VELT_COMMENTS_SIDEBAR}> tag is not added.`),e&&this.sidebarOpenedByCustomTrigger$.next(!0))}catch{this.loggingService.catch("Error in CommentService toggleSidebarVisibility: ",`<${j.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(t){this.loggingService.catch("Error in CommentService disableFloatingComments: ",t)}}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(t){this.loggingService.catch("Error in CommentService setModeratorMode: ",t)}}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(t){this.loggingService.catch("Error in CommentService setStreamMode: ",t)}}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(t){this.loggingService.catch("Error in CommentService setEnableDialogOnHover: ",t)}}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(t){this.loggingService.catch("Error in CommentService setEnableDialogOnTargetElementClick: ",t)}}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(t){this.loggingService.catch("Error in CommentService setEnablePriority: ",t)}}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(t){this.loggingService.catch("Error in CommentService setEnableStatus: ",t)}}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(t){this.loggingService.catch("Error in CommentService setEnableResolve: ",t)}}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(t){this.loggingService.catch("Error in CommentService setEnableAutoCategorize: ",t)}}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(t){this.loggingService.catch("Error in CommentService setCommentContainerDarkMode: ",t)}}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(t){this.loggingService.catch("Error in CommentService setSuggestionMode: ",t)}}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(t){this.loggingService.catch("Error in CommentService setMobileMode: ",t)}}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(t){this.loggingService.catch("Error in CommentService setTotalMediaLength: ",t)}}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(t){this.loggingService.catch("Error in CommentService setDetectionStrategy: ",t)}}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(t){this.loggingService.catch("Error in CommentService addBubbleCommentAnnotationIds: ",t)}}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(t){this.loggingService.catch("Error in CommentService removeBubbleCommentAnnotationIds: ",t)}}enableSignInButton(e){try{this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{signInButton:e}}),this.enableSignInButton$.next(e)}catch(t){this.loggingService.catch("Error in CommentService enableSignInButton: ",t)}}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(t){this.loggingService.catch("Error in CommentService enableUpgradeButton: ",t)}}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(t){this.loggingService.catch("Error in CommentService enableAttachment: ",t)}}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(t){this.loggingService.catch("Error in CommentService setAllowedRecordings: ",t)}}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 Q(this,null,function*(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{privateCommentMode:!0}}),this.privateCommentMode$.value===!0)return;this.iamService.isUserAdmin$().pipe(st(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(t){this.loggingService.catch("Error in CommentService showScreenSizeInfo: ",t)}}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(t){this.loggingService.catch("Error in CommentService setUnreadIndicatorMode: ",t)}}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(t){this.loggingService.catch("Error in CommentService setComposerMode: ",t)}}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(t){this.loggingService.catch("Error in CommentService setExcludeLocationIdsFromSidebar: ",t)}}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()}enableGroupMatchedComments(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{groupMatchedComments:!0}}),this.groupMatchedComments$.value===!0)return;this.groupMatchedComments$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableGroupMatchedComments: ",e)}}disableGroupMatchedComments(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{groupMatchedComments:!1}}),this.groupMatchedComments$.value===!1)return;this.groupMatchedComments$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableGroupMatchedComments: ",e)}}getGroupMatchedComments(){return this.groupMatchedComments$.value}getGroupMatchedComments$(){return this.groupMatchedComments$.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(t){this.loggingService.catch("Error in CommentService setCommentSidebarFilters: ",t)}}getCommentSidebarFilters(){return this.commentSidebarFilters$.value}getCommentSidebarFilters$(){return this.commentSidebarFilters$.asObservable()}setCommentSidebarSystemFiltersOperator(e){try{this.commentSidebarSystemFiltersOperator$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setCommentSidebarSystemFiltersOperator: ",t)}}getCommentSidebarSystemFiltersOperator(){return this.commentSidebarSystemFiltersOperator$.value}getCommentSidebarSystemFiltersOperator$(){return this.commentSidebarSystemFiltersOperator$.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(t){this.loggingService.catch("Error in CommentService setCustomReactions: ",t)}}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(t){return this.loggingService.catch("Error in CommentService getCommentType: ",t),""}}getCommentAnnotationAvailableOnXPath(e,t,r){try{return this.commentAnnotationById$.pipe(he(()=>this.draftCommentAnnotationsByAnnotationId$),he(a=>(!r&&t&&(r=oa(t,["id","data-id"])),se(T(I({},a),{element:r})))),he(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 u=this.docService.getAdditionalDocumentIdFromElement(s),C=u?this.docService.generateDocumentId(u):p?.documentId,E=this.getCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:p?.organizationId,documentId:C||""});if(E)for(let D of E)(t&&D?.targetElementId===t||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),se(null)}}getCommentAnnotationsByContext({context:e,contextOptions:t,element:r,clientDocumentId:a}){try{return this.commentAnnotationById$.pipe(he(()=>this.draftCommentAnnotationsByAnnotationId$),he(()=>this.docService.getDocumentPaths$()),ce(()=>{let s=null,c=this.docService.getDocumentPaths(),p=Oc(e),u=this.generateContextId(p);if(c?.documentId){let C=a||this.docService.getAdditionalDocumentIdFromElement(r??null),E=C?this.docService.generateDocumentId(C):c?.documentId,D=this.getCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:c?.organizationId,documentId:E||""});if(D){s=[];for(let L of D)t?.partialMatch?HP(L?.context,p)&&s.push(L):u&&L?.contextId===u&&s.push(L)}}return s}))}catch(s){return this.loggingService.catch("Error in CommentService getCommentAnnotationsByContext: ",s),se(null)}}getCommentAnnotationByAnnotationId(e){try{return this.commentAnnotationById$.pipe(ce(()=>this.getAnnotationById(e)),he(t=>t?t?.iam?.accessMode===io.PRIVATE?this.iamService.isUserAdmin$().pipe(ce(r=>{if(r)return t})):se(t):se(t)),he(t=>t?this.filterCommentsUsingSidebarSettings(t).pipe(ce(r=>{if(r)return r})):se(t)))}catch(t){return this.loggingService.catch("Error in CommentService getCommentAnnotationByAnnotationId: ",t),se(void 0)}}getMultiThreadCommentAnnotationByAnnotationId(e){return this.multiThreadCommentAnnotationById$.pipe(ce(()=>this.getMultiThreadAnnotationById(e)))}getCommentBubbleElement(e){try{let t=document.querySelector(`${j.TAGS.VELT_COMMENT_BUBBLE}[${j.ATTRIBUTES.VELT_ANNOTATION_IDS}*="${e?.annotationId}"]`);return t||(t=document.querySelector(`${j.TAGS.SNIPPYLY_COMMENT_BUBBLE}[${j.ATTRIBUTES.VELT_ANNOTATION_IDS}*="${e?.annotationId}"]`)),t}catch(t){return this.loggingService.catch("Error in CommentService getCommentBubbleElement: ",t),null}}getCommentAnnotationsBySectionId(e){try{return this.commentAnnotationById$.pipe(he(()=>this.docService.getDocumentPaths$().pipe(ce(t=>({documentPaths:t,sectionId:e})))),he(t=>{let r=oa(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 u=Object.values(c||{}).find(C=>C.locationId===s||a?.id&&C.location.id===a.id);return T(I({},t),{additionalLocation:u,locationOnElement:!!a})}))}}return se(T(I({},t),{additionalLocation:null,element:r}))}),he(t=>t?.locationOnElement?se(t):this.docService.getLocation$().pipe(ce(r=>T(I({},t),{location:r})))),ce(({documentPaths:t,location:r,additionalLocation:a,locationOnElement:s,element:c})=>{let p=null;if(this.authService.getUser()&&t?.documentId){let C=this.docService.getAdditionalDocumentIdFromElement(c),E=C?this.docService.generateDocumentId(C):t?.documentId,D=this.getCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:t?.organizationId,documentId:E||""});if(D){p=[];let L=Ad(e);s?a?.location?.id?L=Ad([a?.location?.id,e]):a?.locationId&&(L=Ad([a?.locationId+"",e])):r&&(r?.location?.id?L=Ad([r?.location?.id,e]):r?.locationId&&(L=Ad([r?.locationId+"",e])));for(let z of D)z?.multiThreadAnnotationId===L?p.push(z):(z?.targetInlineCommentElementId===e||z?.targetElementId===e)&&(s?a&&nh({location:a?.location,locationId:a?.locationId},{location:z.location,locationId:z.locationId})&&p.push(z):r?nh({location:r?.location,locationId:r?.locationId},{location:z.location,locationId:z.locationId})&&p.push(z):z?.locationId||p.push(z))}}return p}))}catch(t){return this.loggingService.catch("Error in CommentService getCommentAnnotationsBySectionId: ",t),se(null)}}getCommentAnnotationsByMultiThreadAnnotationId(e){try{return this.commentAnnotationById$.pipe(he(()=>this.multiThreadCommentAnnotationById$),he(()=>this.docService.getDocumentPaths$().pipe(ce(t=>({documentPaths:t,multiThreadAnnotationId:e})))),ce(({documentPaths:t,location:r,additionalLocation:a,locationOnElement:s})=>{let c=null;if(t?.documentId){let p=this.getMultiThreadAnnotationById(e),{documentId:u,organizationId:C}=p?.metadata||{documentId:t?.documentId,organizationId:t?.organizationId},E=this.getCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:C,documentId:u||""});if(E){c=[];for(let D of E)D?.multiThreadAnnotationId===e&&p?.commentAnnotations?.[D?.annotationId]&&c.push(D)}}return c}))}catch(t){return this.loggingService.catch("Error in CommentService getCommentAnnotationsBySectionId: ",t),se(null)}}getCommentAnnotationsByAnnotationIds(e){try{return this.commentAnnotationById$.pipe(he(()=>this.draftCommentAnnotationsByAnnotationId$),he(()=>this.docService.getDocumentPaths$().pipe(ce(t=>({documentPaths:t,annotationIds:e})))),ce(({documentPaths:t})=>{let r=null;if(t?.documentId){let a=this.commentAnnotationById$.value?Object.values(this.commentAnnotationById$.value):[],s=this.draftCommentAnnotationsByAnnotationId$.value?Object.values(this.draftCommentAnnotationsByAnnotationId$.value):[];if(a=[...a,...s],a){r=[];for(let c of a)e.includes(c?.annotationId)&&r.push(c)}}return r}))}catch(t){return this.loggingService.catch("Error in CommentService getCommentAnnotationsByAnnotationIds: ",t),se(null)}}getCommentAnnotationsByFolderId({folderId:e,veltFolderId:t}){try{return this.commentAnnotationById$.pipe(he(()=>this.draftCommentAnnotationsByAnnotationId$),he(()=>this.docService.getDocumentPaths$()),ce(()=>{e&&!t&&(t=Fi(e));let r=this.authService.getUser(),a=this.docService.getDocumentPaths(),s=null;if(r&&a?.documentId){this.commentAnnotationById$.value&&(s={},Object.values(this.commentAnnotationById$.value).forEach(p=>{p?.metadata?.folderId==e&&p?.metadata?.veltFolderId==t&&(s[p?.annotationId]=p)}));let c=this.draftCommentAnnotationsByAnnotationId$.value;c&&(s===null&&(s={}),Object.values(c).forEach(p=>{p?.metadata?.folderId==e&&p?.metadata?.veltFolderId==t&&!s[p?.annotationId]&&(s[p?.annotationId]=p)}))}return s?Object.values(s):null}))}catch(r){return this.loggingService.catch("Error in CommentService getCommentAnnotationsByFolderId: ",r),se(null)}}getCommentAnnotationsForCommentComponent(e){try{let{annotationId:t,folderId:r,veltFolderId:a,targetElementId:s,clientDocumentId:c,documentId:p,context:u,contextOptions:C,element:E,type:D,sectionId:L,locationId:z}=e||{};if(c&&!p&&(p=this.docService.generateDocumentId(c)),r&&!a&&(a=Fi(r)),t)return this.getCommentAnnotationByAnnotationId(t).pipe(ce(J=>J?[J]:null));let W=[];if(s&&(D==="pin"||D==="tool"||D==="bubble")){let J=oa(s,["id","data-id"]);if(J){let ue=J,ye=this.domService.getXPath(J);W.push(this.getCommentAnnotationAvailableOnXPath(ye,s,ue))}}return L&&W.push(this.getCommentAnnotationsBySectionId(L)),u&&W.push(this.getCommentAnnotationsByContext({context:u,contextOptions:C,element:E,clientDocumentId:c})),p&&W.push(this.getCommentAnnotationsByDocumentId$({documentId:p})),r&&W.push(this.getCommentAnnotationsByFolderId({folderId:r,veltFolderId:a})),W.length===0?se(null):Sn(W).pipe(ce(J=>{let ue=J.filter(Ae=>Ae!==null&&Array.isArray(Ae));if(ue.length===0)return null;if(ue.length===1){let Ae=ue[0];return z&&Ae?.length?Ae.filter(Fe=>Fe?.location?.id===z):Ae}let ye=ue[0];for(let Ae=1;Ae<ue.length;Ae++){let He=ue[Ae];ye=ye.filter(Fe=>He.some(Se=>Se.annotationId===Fe.annotationId))}return z&&ye?.length&&(ye=ye.filter(Ae=>Ae?.location?.id===z)),ye}),Et(mn))}catch(t){return this.loggingService.catch("Error in CommentService getCommentAnnotationsForCommentComponent: ",t),se(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(t){return this.loggingService.catch("Error in CommentService isElementInsideAllowedElements: ",t),!1}}getNearestAllowedElement(e){try{let t=this.domService.getListedElements({elementIds:this.allowedElementIds$.value,elementClassNames:this.allowedElementClassNames$.value,elementQuerySelectors:this.allowedElementQuerySelectors$.value});if(t?.length){for(let r=0;r<t.length;r++){let a=t[r];if(e.contains(a))return a}return null}return null}catch(t){return this.loggingService.catch("Error in CommentService getNearestAllowedElement: ",t),null}}isElementInsideManualCommentContainer(e){try{return this.domService.isElementInsideParentWithAttribute(e,j.ATTRIBUTES.VELT_MANUAL_COMMENT_CONTAINER,"true")}catch(t){return this.loggingService.catch("Error in CommentService isElementInsideManualCommentContainer: ",t),!1}}saveComment(e,t){return Q(this,null,function*(){try{t?.annotation&&(e=t.annotation),e&&(e=JSON.parse(JSON.stringify(e)));let r=this.originalCommentAnnotationsByDocumentId$.value[e.annotationId];if(r?.comments?.length){let C=JSON.parse(JSON.stringify(e.comments||[]));e.comments=[],r.comments?.forEach(E=>{let D=C.find(L=>L.commentId===E.commentId);D?e.comments.push(D):e.comments.push(E)})}e.comments||(e.comments=[]);let a=!1,s=!1,c;switch(t.type){case $t.NEWLY_ADDED:case $t.ADDED:if(!t.updatedComment)break;e?.comments?.length||(s=!0),e.comments.push(t.updatedComment);let C=t?.assigned||void 0;c={commentAnnotation:e,targetComment:t.updatedComment,actionType:t.type,otherFields:{assigned:C}};break;case $t.PUBLISHED:e.isDraft=!1;break;case $t.APPROVED:e.approved=!0,c={commentAnnotation:e,targetComment:null,actionType:$t.APPROVED};break;case $t.ASSIGNED:e.assignedTo=t.assignedTo,c={commentAnnotation:e,targetComment:null,actionType:$t.ASSIGNED};break;case $t.UPDATED:if(!t.updatedComment)break;let E=e.comments.findIndex(ue=>ue.commentId===t.updatedComment.commentId);if(E>=0){e.comments[E]=t.updatedComment,e.comments[E].status=$t.UPDATED;let ue=t?.assigned||void 0;c={commentAnnotation:e,targetComment:t.updatedComment,actionType:$t.UPDATED,otherFields:{assigned:ue}}}break;case $t.REACTION_ADDED:if(!t.updatedComment)break;let D=e.comments.findIndex(ue=>ue.commentId===t.updatedComment.commentId);D>=0&&(e.comments[D]=t.updatedComment,e.comments[D].status=$t.UPDATED,c={commentAnnotation:e,targetComment:t.updatedComment,actionType:$t.REACTION_ADDED});break;case $t.REACTION_DELETED:if(!t.updatedComment)break;let L=e.comments.findIndex(ue=>ue.commentId===t.updatedComment.commentId);L>=0&&(e.comments[L]=t.updatedComment,e.comments[L].status=$t.UPDATED,c={commentAnnotation:e,targetComment:t.updatedComment,actionType:$t.REACTION_DELETED});break;case $t.STATUS_CHANGED:e.status.type==="terminal"&&(this.domService.resetSelectedAnnotationsMap(!1,"comment"),e.resolvedByUserId=this.authService.getUser()?.userId),c={commentAnnotation:e,targetComment:null,actionType:$t.STATUS_CHANGED,otherFields:{oldStatus:t.oldStatus,newStatus:t.newStatus}};break;case $t.PRIORITY_CHANGED:c={commentAnnotation:e,targetComment:null,actionType:$t.PRIORITY_CHANGED,otherFields:{oldPriority:t.oldPriority,newPriority:t.newPriority}};break;case $t.ACCESS_MODE_CHANGED:c={commentAnnotation:e,targetComment:null,actionType:$t.ACCESS_MODE_CHANGED,otherFields:{oldAccessMode:t.oldAccessMode,newAccessMode:t.newAccessMode}};break;case $t.CUSTOM_LIST_CHANGED:c={commentAnnotation:e,targetComment:null,actionType:$t.CUSTOM_LIST_CHANGED,otherFields:{oldCustomList:t.oldCustomList,newCustomList:t.newCustomList}};break;case $t.SUBSCRIBED:c={commentAnnotation:e,targetComment:null,actionType:$t.SUBSCRIBED};break;case $t.UNSUBSCRIBED:c={commentAnnotation:e,targetComment:null,actionType:$t.UNSUBSCRIBED};break;case $t.DELETED:if(!t.updatedComment)break;let z=e.comments.findIndex(ue=>ue.commentId===t.updatedComment.commentId);if(z>=0){if((z===0&&this.deleteThreadWithFirstComment$.value!==!1||this.deleteReplyConfirmation$.value)&&!t.skipDeleteThreadConfirmation){let Ae={};if(this.deleteReplyConfirmation$.value&&(z!==0||this.deleteThreadWithFirstComment$.value===!1)?Ae={title:"Delete comment?",message:"This selected comment will be deleted.",yesButton:"Delete",noButton:"Cancel",darkMode:this.commentContainerDarkMode$.value,variant:"reply"}:Ae={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(Sa,{panelClass:"velt-mat-dialog-container",data:Ae}).afterClosed().toPromise()))return}let ue=e.comments.splice(z,1),ye=e.metadata;ue?.length&&ue.forEach(Ae=>{Ae?.attachments&&Ae.attachments.forEach(He=>{let Fe={attachmentId:He.attachmentId,organizationId:ye?.organizationId??null,documentId:ye?.documentId??null,folderId:ye?.folderId??null,commentAnnotationId:e.annotationId,apiKey:ye?.apiKey??null};this.deleteAttachment({attachment:He,metadata:Fe})}),Ae?.reactionAnnotationIds&&Ae.reactionAnnotationIds.forEach(He=>{this.deleteReaction(He)})})}e.status=this.customFilterService.defaultStatus,z===0&&this.deleteThreadWithFirstComment$.value!==!1||e.comments?.length===0?a=!0:(this.analyticsService.trackEvent(Z.Events.Comments.COMMENT_THREAD_DELETED,{annotationId:e.annotationId,commentThreadId:t.updatedComment.commentId,commentMode:this.getCommentMode()}),c={commentAnnotation:e,targetComment:t.updatedComment,actionType:$t.DELETED});break;case $t.ACCEPTED:let W={annotationId:e.annotationId,actionUser:this.authService.getUser(),actionType:$t.ACCEPTED,replaceContentHtml:e?.comments?.length?e?.comments[0]?.replaceContentHtml:void 0,replaceContentText:e?.comments?.length?e?.comments[0]?.replaceContentText:void 0,annotation:Gn(e)};this.commentAccepted$.next(W),c={commentAnnotation:e,targetComment:null,actionType:$t.ACCEPTED};break;case $t.REJECTED:let J={annotationId:e.annotationId,actionUser:this.authService.getUser(),actionType:$t.REJECTED,replaceContentHtml:e?.comments?.length?e?.comments[0]?.replaceContentHtml:void 0,replaceContentText:e?.comments?.length?e?.comments[0]?.replaceContentText:void 0,annotation:Gn(e)};this.commentRejected$.next(J),this.domService.resetSelectedAnnotationsMap(),c={commentAnnotation:e,targetComment:null,actionType:$t.REJECTED};break;default:break}e.resolvedByUserId&&e.status.type!=="terminal"&&(e.resolvedByUserId=null),t?.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&&(t.type===$t.ADDED||t.type===$t.NEWLY_ADDED)&&e.comments?.length===1?setTimeout(()=>{this.domService.resetSelectedAnnotationsMap(!1,"comment")},100):this.domService.updateSelectedAnnotationInMap([e]));let p=this.getCustomPinById(e.annotationId),u={type:t.type,annotation:Gn(e),targetAnnotationId:e.annotationId,targetCommentId:t.updatedComment?.commentId,updateContext:(C,E)=>{this.updateCommentAnnotationContext(e.annotationId,C,E)}};p!==void 0&&(u.element=p),delete u?.annotation?.pageInfo,delete u?.annotation?.targetElement,delete u?.annotation?.targetTextRange,u?.type===$t.DELETED&&(e.comments?.length||(u.annotation=null)),a||this.commentUpdated$.next(u)}catch(r){this.loggingService.catch("Error in CommentService saveComment: ",r)}})}attachComment(e,t=[],r,a,s,c,p){try{this.loggingService.log("%c[WB] Calling FUNCTION: attachComment","color: green;");let u;if(e){let C=oa(e,t);C&&(u={targetElement:{xpath:this.domService.getXPath(C),topPercentage:50,leftPercentage:90},targetElementId:e})}(u||r||s)&&this.addComment(void 0,void 0,void 0,void 0,void 0,void 0,void 0,c,void 0,void 0,u,void 0,void 0,void 0,a,void 0,void 0,void 0,r,void 0,s,void 0,void 0,p)}catch(u){this.loggingService.catch("Error in CommentService attachComment: ",u)}}updateNotificationsDatabase(e,t,r,a={}){try{let s=I({annotationData:e,targetAnnotationData:t,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 t=null;if(e?.ghostComment)!t&&e.ghostComment?.targetElement?.fXpath&&(t=this.domService.getElementFromXPath(e.ghostComment?.targetElement?.fXpath),t&&!this.domService.isElementVisible(t)&&(t=null)),!t&&e.ghostComment?.targetElement?.cfXpath&&(t=this.domService.getElementFromXPath(e.ghostComment?.targetElement?.cfXpath),t&&!this.domService.isElementVisible(t)&&(t=null)),!t&&e.ghostComment?.targetElement?.xpath&&(t=this.domService.getElementFromXPath(e.ghostComment?.targetElement?.xpath),t&&!this.domService.isElementVisible(t)&&(t=null));else{let r=!1;!t&&e?.targetElement?.xpath&&(r=this.domService.isXpathWithId(e?.targetElement?.xpath),t=this.domService.getElementFromXPath(e?.targetElement?.xpath),t&&!this.domService.isElementVisible(t)&&(t=null)),r||(!t&&e?.targetElement?.cfXpath&&(t=this.domService.getElementFromXPath(e?.targetElement?.cfXpath),t&&!this.domService.isElementVisible(t)&&(t=null)),!t&&e?.targetElement?.fXpath&&(t=this.domService.getElementFromXPath(e?.targetElement?.fXpath),t&&!this.domService.isElementVisible(t)&&(t=null)))}return t&&!Ao(t)&&(t=null),t}catch(t){return this.loggingService.catch("Error in CommentService getElementFromComment: ",t),null}}getElementFromComments(e){try{let t=[],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&&!Ao(r)&&(r=null),e?.targetElementId&&(t=Array.from(aae(e.targetElementId,["id","data-id"]))),r&&!t.includes(r)&&t.push(r),t}catch(t){return this.loggingService.catch("Error in CommentService getElementFromComment: ",t),[]}}getGhostCommentTargetElement(e){try{let t=e.targetElement?.fXpath||e.targetElement?.xpath,r=null;if(t)for(;!r&&t;)r=this.domService.getElementFromXPath(t),r&&(!this.domService.isElementVisible(r)||!Ao(r))&&(r=null),r||(t=t.substring(0,t.lastIndexOf("/")));return t==="/"&&(t=""),t?{xpath:t,topPercentage:e?.targetElement?.topPercentage||0,leftPercentage:e?.targetElement?.leftPercentage||0}:null}catch(t){return this.loggingService.catch("Error in CommentService getGhostCommentTargetElement: ",t),null}}setGhostCommentMessage(e){try{if(e?.ghostComment){e.ghostComment.message="Original content not found.",e.ghostComment.type=il.ELEMENT_DELETED;let t=e?.pageInfo?.deviceInfo?.deviceType,r=new zn().getDeviceType();t&&t!==r&&(e.ghostComment.type=il.DIFFERENT_DEVICE,e.ghostComment.message=`Original comment was added on ${t}.`,[ir.MOBILE,ir.TABLET].includes(t)&&[ir.MOBILE,ir.TABLET].includes(r)||[ir.DESKTOP,ir.MONITOR].includes(t)&&[ir.DESKTOP,ir.MONITOR].includes(r)?e.ghostComment.isSameGroup=!0:e.ghostComment.isSameGroup=!1)}}catch(t){this.loggingService.catch("Error in CommentService setGhostCommentMessage: ",t)}}addAnnotationToGhostCommentAnnotationMap(e){try{let t=this.ghostCommentAnnotationMap$.value||{},r=t[e?.annotationId]||{};wi(e.ghostComment,r)||(t[e?.annotationId]=e.ghostComment,this.ghostCommentAnnotationMap$.next(t))}catch(t){this.loggingService.catch("Error in CommentService addAnnotationToGhostCommentAnnotationMap: ",t)}}removeAnnotationFromGhostCommentAnnotationMap(e){try{let t=this.ghostCommentAnnotationMap$.value||{};t[e?.annotationId]&&(delete t[e?.annotationId],this.ghostCommentAnnotationMap$.next(t))}catch(t){this.loggingService.catch("Error in CommentService removeAnnotationFromGhostCommentAnnotationMap: ",t)}}getGhostCommentAnnotationMap$(){return this.ghostCommentAnnotationMap$.asObservable()}getGhostCommentAnnotationMap(){return this.ghostCommentAnnotationMap$.value||{}}getUnreadCommentsMap$(){return this.unreadCommentsMap$.asObservable().pipe(Et(mn))}getUnreadCommentsMap(){return this.unreadCommentsMap$.value}getUnreadCommentCountByAnnotationId$(e){return this.getUnreadCommentsMap$().pipe(ce(t=>t?{count:t[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(t=>{if(t){let r=this.docService.getDocumentPaths(),a=[],s=0;return r?.documentId&&(a=this.getCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:r?.organizationId,documentId:r?.documentId}),a&&Object.keys(t).forEach(c=>{a?.find(u=>u.annotationId===c)?.location?.id===e&&(s+=t[c])})),{count:s}}else return null}))}getUnreadCommentAnnotationCountByLocationId$(e){return this.getUnreadCommentsMap$().pipe(ce(t=>{if(t){let r=this.docService.getDocumentPaths(),a=[],s=0;return r?.documentId&&(a=this.getCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:r?.organizationId,documentId:r?.documentId}),Object.keys(t).forEach(c=>{t[c]&&a?.find(u=>u.annotationId===c)?.location?.id===e&&(s+=1)})),{count:s}}else return null}))}setCommentAnnotationsAsRead(e){try{for(let t of e)this.viewsService.setCommentAnnotationAsRead(t)}catch(t){this.loggingService.catch("Error in CommentService setCommentAnnotationsAsRead: ",t)}}setCommentAnnotationsAsResolved(e){try{let t=this.customFilterService.resolvedStatus;if(t){for(let r of e)if(t?.id!==r?.status?.id){let a=JSON.parse(JSON.stringify(r||{}));r.status=this.customFilterService.resolvedStatus;let s={annotation:r,type:$t.STATUS_CHANGED,oldStatus:a.status,newStatus:this.customFilterService.resolvedStatus};this.saveComment(r,s)}}}catch(t){this.loggingService.catch("Error in CommentService setCommentAnnotationsAsResolved: ",t)}}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(t){this.loggingService.catch("Error in CommentService setPinCursorImage: ",t)}}getPinCursorImage$(){return this.commentPinCursorImage$.asObservable()}getPinCursorImage(){return this.commentPinCursorImage$.value}setCommentAnnotationsFromCommentsContainer(e){try{this.commentAnnotationsFromCommentsContainer$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setCommentAnnotationsFromCommentsContainer: ",t)}}getCommentAnnotationsFromCommentsContainer$(){return this.commentAnnotationsFromCommentsContainer$.asObservable()}getCommentAnnotationsFromCommentsContainer(){return this.commentAnnotationsFromCommentsContainer$.value}addManualComment(e){return Q(this,null,function*(){try{return this.loggingService.log("%c[WB] Calling FUNCTION: addManualComment","color: green;"),new Promise((t,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=>{t(c)}),this.addCommentMode$?.value&&!this.persistentCommentMode$?.value&&this.disableAddCommentMode()})}catch(t){return this.loggingService.catch("Error in CommentService addManualComment: ",t),null}})}getCommentUrl(e){try{return e?.pageInfo?.commentUrl?e.pageInfo.commentUrl:(e?.pageInfo||(e.pageInfo=Oi(),e.pageInfo&&(e.pageInfo.screenWidth=this.domService.getCurrentWindowSizeValue()?.screenWidth)),e.pageInfo.commentUrl=this.generateCommentUrl(e),this.updateComment(e),e.pageInfo?.commentUrl)}catch(t){this.loggingService.catch("Error in CommentService getCommentUrl: ",t);return}}uploadFile(e,t){let r=`${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentPaths?.documentId}/${j.FIREBASE_PARTIAL_PATH_COMMENT}/${t.annotationId}`;this.documentPaths?.organizationId&&(r=`${j.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${this.documentPaths.organizationId}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentPaths?.documentId}/${j.FIREBASE_PARTIAL_PATH_COMMENT}/${t.annotationId}`);let a={organizationId:t.metadata?.clientOrganizationId??null,documentId:t.metadata?.clientDocumentId??null,commentAnnotationId:t.annotationId,apiKey:t.metadata?.apiKey??null,folderId:t.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:t}){return this.storageService.deleteAttachment({attachment:e,metadata:t,useAttachmentResolver:this.attachmentResolverService.attachmentDataProviderAvailable()})}deleteReaction(e){try{this.reactionService.deleteReactionPinAnnotation(e)}catch(t){this.loggingService.catch("Error in CommentService deleteReaction: ",t)}}generateCommentUrl(e){let t=new URL(window.location.href);return t.searchParams.delete(j.URL_PARAMS.COMMENT_ID),t.searchParams.append(j.URL_PARAMS.COMMENT_ID,e.annotationId),t.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(t){this.loggingService.catch("Error in CommentService setCustomStatuses: ",t)}}getCustomStatusesShown$(){return this.customStatusesShown$.asObservable()}getCustomStatusesShown(){return this.customStatusesShown$.value}setCustomPriorities(e){try{if(e===void 0)return;this.customFilterService.setCustomPriorityFilters(e)}catch(t){this.loggingService.catch("Error in CommentService setCustomPriorities: ",t)}}setCustomCategories(e){try{if(e===void 0)return;this.customFilterService.setCustomCategories(e)}catch(t){this.loggingService.catch("Error in CommentService setCustomCategories: ",t)}}addCommentOnSelectedText(){try{let e=this.authService.getUser();if(this.textCommentMode$.value&&e&&!(e?.isReadOnly||e?.isAnonymous)&&this.authService.isFeatureAllowed(Re.COMMENT)){let t=this.domService.getRange();if(window.getSelection()?.toString()&&!eM()&&t?.commonAncestorContainer&&this.isElementInsideAllowedElements(t.commonAncestorContainer)&&!Vm(t.commonAncestorContainer)){let r=t?this.domService.getTargetTextRangeFromSelectionRange(t):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 t;if(e){let r=e?.closest(`[${j.ATTRIBUTES.VELT_TARGET_INLINE_COMMENT_ELEMENT_ID}]`);if(r){let a=r.getAttribute(j.ATTRIBUTES.VELT_TARGET_INLINE_COMMENT_ELEMENT_ID);a&&(t={},t.targetInlineCommentElementId=a,r.getAttribute(j.ATTRIBUTES.VELT_INLINE_COMMENT_SECTION_CONFIG)&&(t.config=JSON.parse(r.getAttribute(j.ATTRIBUTES.VELT_INLINE_COMMENT_SECTION_CONFIG)||"{}")))}}return t}catch(t){this.loggingService.catch("Error in CommentService getInlineCommentSectionConfig: ",t)}}createCustomListDataOnAnnotation(e){try{if(e===void 0)return;this.customChipDropdownData$.next(e)}catch(t){this.loggingService.catch("Error in CommentService createCustomListDataOnAnnotation: ",t)}}getCustomChipDropdownData$(){return this.customChipDropdownData$.asObservable()}getCustomChipDropdownData(){return this.customChipDropdownData$.value}setSubscribedUsersDataInCommentAnnotation(e){try{let t={},r=e?.unsubscribedUsers||{},a={};if(e?.subscribedUsers&&Object.keys(e.subscribedUsers||{}).forEach(s=>{let c=e.subscribedUsers?.[s];c?.type==="manual"&&(t[s]=c)}),e?.assignedTo?.userId){let s=bt(e?.assignedTo?.userId);r[s]||t[s]?.type!=="manual"&&(t[s]={user:e?.assignedTo,type:"auto"})}e?.comments?.filter(s=>!s?.isDraft)?.forEach(s=>{if(s?.from?.userId){let c=bt(s?.from?.userId);r[c]||t[c]?.type!=="manual"&&(t[c]={user:s?.from,type:"auto"})}s?.to?.forEach(c=>{if(c?.userId){let p=bt(c.userId);r[p]||t[p]?.type!=="manual"&&(t[p]={user:c,type:"auto"})}}),s?.toOrganizationUserGroup?.forEach(c=>{if(c?.groupId)a[c?.groupId]={type:"auto"};else if(c?.clientGroupId){let p=bt(c.clientGroupId);a[p]={type:"auto"}}})}),e.subscribedUsers=t,e.unsubscribedUsers=r,e.subscribedGroups=a}catch(t){this.loggingService.catch("Error in CommentService setSubscribeUsersDataInCommentAnnotation: ",t)}}getCopyLink$(){return this.copyLink$.asObservable()}setCopyLink(e){try{this.copyLink$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setCopyLink: ",t)}}getCommentAnnotationById(e){return this.commentAnnotationById$.pipe(he(()=>{let{annotationId:t,documentId:r}=e;if(r){let a=En(r).toString();return this.getDataCommentAnnotationsFromDocumentId(a).pipe(ce(s=>s.find(p=>p.annotationId===t)||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===t);return se(c||null)}}}return se(null)}),kn(t=>(this.loggingService.catch("Error in CommentService getCommentAnnotationById: ",t),se(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(t=>t?.data),ce(t=>{let r=[];return t&&(r=Object.values(t??{}).filter(a=>typeof a=="object")),r})):se([])}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,t,r,a,s){try{this.sidebarCustomActionEventData$.next({actions:e,data:t,unreadDataMap:r,systemFilteredData:a,customFilters:s})}catch(c){this.loggingService.catch("Error in CommentService emitOnSidebarCustomAction: ",c)}}getSidebarCustomActionEventData(){return this.sidebarCustomActionEventData$.asObservable()}setCommentSidebarData(e,t){try{this.sidebarData$.next({data:e,options:t})}catch(r){this.loggingService.catch("Error in CommentService setCommentSidebarData: ",r)}}getSidebarCustomData(){return this.sidebarData$.asObservable()}setSidebarCustomActionEventDataAllChanges(e,t,r,a,s){return Q(this,null,function*(){try{this.sidebarCustomActionEventDataAllChanges$.next({actions:e,data:t,unreadDataMap:r,systemFilteredData:a,customFilters:s});let c=yield this.metadataService.getGlobalMetadata(),p={buttonContext:{selections:this.buttonService.buttonToggleMapValue()},unreadCommentAnnotationsMap:r,commentAnnotations:t,systemFilteredAnnotations:a,metadata:c,customFilters:s};this.commentActionsService?.triggerAction(ji.COMMENT_SIDEBAR_DATA_UPDATE,p)}catch(c){this.loggingService.catch("Error in CommentService setSidebarCustomActionEventDataAllChanges: ",c)}})}setSidebarCustomActionEventDataOnInit(e,t,r,a,s){return Q(this,null,function*(){try{this.sidebarCustomActionEventDataOnInit$.next({actions:e,data:t,unreadDataMap:r,systemFilteredData:a,customFilters:s});let p={metadata:yield this.metadataService.getGlobalMetadata(),unreadCommentAnnotationsMap:r,commentAnnotations:t,systemFilteredAnnotations:a,buttonContext:{selections:this.buttonService.buttonToggleMapValue()},customFilters:s};this.commentActionsService?.triggerAction(ji.COMMENT_SIDEBAR_DATA_INIT,p)}catch(c){this.loggingService.catch("Error in CommentService setSidebarCustomActionEventDataOnInit: ",c)}})}getSidebarCustomActionEventDataAllChanges(){return this.sidebarCustomActionEventDataAllChanges$.asObservable()}getSidebarCustomActionEventDataOnInit(){return this.sidebarCustomActionEventDataOnInit$.asObservable()}getSidebarCustomActionEventDataOnInitValue(){return this.sidebarCustomActionEventDataOnInit$.getValue()}setTransformContext(e){try{e?wi(this.transformContext$.value,e)||this.transformContext$.next(e):this.transformContext$.next(null)}catch(t){this.loggingService.catch("Error in CommentService setTransformContext: ",t)}}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)}}enableLinkCallback(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{linkCallback:!0}}),this.linkCallback$.value===!0)return;this.linkCallback$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableLinkCallback: ",e)}}disableLinkCallback(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{linkCallback:!1}}),this.linkCallback$.value===!1)return;this.linkCallback$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableLinkCallback: ",e)}}getResolveStatusAccessAdminOnly$(){return this.resolveStatusAccessAdminOnly$.asObservable()}getLinkCallback$(){return this.linkCallback$.asObservable()}getResolveStatusAccessAdminOnly(){return this.resolveStatusAccessAdminOnly$.value}getLinkCallback(){return this.linkCallback$.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}enableFilterCommentsOnDom(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{filterCommentsOnDom:!0}}),this.filterCommentsOnDom$.value===!0)return;this.filterCommentsOnDom$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableFilterCommentsOnDom: ",e)}}disableFilterCommentsOnDom(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{filterCommentsOnDom:!1}}),this.filterCommentsOnDom$.value===!1)return;this.filterCommentsOnDom$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableFilterCommentsOnDom: ",e)}}getFilterCommentsOnDom$(){return this.filterCommentsOnDom$.asObservable()}getFilterCommentsOnDom(){return this.filterCommentsOnDom$.value}setCommentsFromSidebarMap(e){try{let{comments:t,sidebarVisible:r}=e||{},a=null;t&&(a={},t.forEach(c=>{c?.annotationId&&a&&(a[c.annotationId]=c)}));let s={};t===void 0?s.data=this.commentsFromSidebarMap$.value?.data:s.data=a,r===void 0?s.sidebarVisible=this.commentsFromSidebarMap$.value?.sidebarVisible:s.sidebarVisible=r,wi(this.commentsFromSidebarMap$.value,s)||this.commentsFromSidebarMap$.next(s)}catch(t){this.loggingService.catch("Error in CommentService setCommentsFromSidebarMap: ",t)}}getCommentsFromSidebarMap$(){return this.commentsFromSidebarMap$.asObservable()}getCommentsFromSidebarMap(){return this.commentsFromSidebarMap$.value}setSidebarButtonCountType(e){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{sidebarButtonCountType:e}}),this.sidebarButtonCountType$.value===e)return;this.sidebarButtonCountType$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setSidebarButtonCountType: ",t)}}getSidebarButtonCountType$(){return this.sidebarButtonCountType$.asObservable()}getSidebarButtonCountType(){return this.sidebarButtonCountType$.value}enableFilterGhostCommentsInSidebar(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{filterGhostCommentsInSidebar:!0}}),this.filterGhostCommentsInSidebar$.value===!0)return;this.filterGhostCommentsInSidebar$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableFilterGhostCommentsInSidebar: ",e)}}disableFilterGhostCommentsInSidebar(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{filterGhostCommentsInSidebar:!1}}),this.filterGhostCommentsInSidebar$.value===!1)return;this.filterGhostCommentsInSidebar$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableFilterGhostCommentsInSidebar: ",e)}}getFilterGhostCommentsInSidebar$(){return this.filterGhostCommentsInSidebar$.asObservable()}getFilterGhostCommentsInSidebar(){return this.filterGhostCommentsInSidebar$.value}filterCommentsUsingSidebarSettings(e){try{let t=Array.isArray(e),r;return t?r=e||[]:e?r=[e]:r=[],this.getFilterCommentsOnDom$().pipe(he(a=>a?r.length===0?se(e):this.getCommentsFromSidebarMap$().pipe(ce(s=>{if(!s?.sidebarVisible)return e;let c=r.filter(p=>p?.isDraft||!!s?.data?.[p?.annotationId]);return t?c:c.length>0?c[0]:null})):se(e)))}catch{return se(e)}}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}shouldEnableReadOnly(){return Q(this,null,function*(){try{this.loggingService.log("%c[WB] Calling CommentService FUNCTION: shouldEnableReadOnly","color: green;");let e=this.authService.getUser(),t=this.docService.getDocumentPaths()?.folderId,r=this.docService.getDocumentIds().map(a=>a.clientDocumentId);if(e){let a=yield this.userPermissionService.getUserPermissions();a[e.userId]?t&&a[e.userId]?.folders?.[t]?.accessRole==="viewer"?this.enableReadOnly():r.forEach(s=>{a[e.userId]?.documents?.[s]?.accessRole==="viewer"&&this.enableReadOnly()}):this.getReadOnly()||this.disableReadOnly()}}catch(e){this.loggingService.catch("Error in CommentService shouldEnableReadOnly:",e)}})}sanitizeCommentAnnotation(e){try{return e?.comments?.length&&e.comments.forEach(t=>{t?.commentHtml&&(t.commentHtml=this.domService.sanitizeHtml(t.commentHtml))}),e}catch(t){return this.loggingService.catch("Error in CommentService sanitizeCommentAnnotation: ",t),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:t}){try{this.analyticsService.setFeatureConfig({feature:t||Re.COMMENT,config:e})}catch(r){this.loggingService.catch("Error in CommentService setAnalyticsFeatureConfig: ",r)}}generateContextId(e){try{let t;if(e&&typeof e=="object"){let r=Oc(e),a=JSON.stringify(r);t=bt(a)}return t}catch{return}}setMaxReplyAvatars(e){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{maxReplyAvatars:e}}),this.maxReplyAvatars$.value===e)return;this.maxReplyAvatars$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setMaxReplyAvatars: ",t)}}getMaxReplyAvatars$(){return this.maxReplyAvatars$.asObservable()}getMaxReplyAvatars(){return this.maxReplyAvatars$.value}enableReplyAvatars(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{replyAvatars:!0}}),this.replyAvatars$.value===!0)return;this.replyAvatars$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableReplyAvatars: ",e)}}disableReplyAvatars(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{replyAvatars:!1}}),this.replyAvatars$.value===!1)return;this.replyAvatars$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableReplyAvatars: ",e)}}getReplyAvatars$(){return this.replyAvatars$.asObservable()}getReplyAvatars(){return this.replyAvatars$.value}setCommentplaceholder(e){try{this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{commentplaceholder:e}}),this.commentplaceholder$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setCommentplaceholder: ",t)}}getCommentplaceholder$(){return this.commentplaceholder$.asObservable()}getCommentplaceholder(){return this.commentplaceholder$.value}setReplyplaceholder(e){try{this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{replyplaceholder:e}}),this.replyplaceholder$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setReplyplaceholder: ",t)}}getReplyplaceholder$(){return this.replyplaceholder$.asObservable()}getReplyplaceholder(){return this.replyplaceholder$.value}};o.\u0275fac=function(t){return new(t||o)(ee(et),ee(Vc),ee(pn),ee(Ft),ee(at),ee(Dn),ee(Ve),ee(Be),ee(Di),ee(Bd),ee(xi),ee(sg),ee(Wo),ee(no),ee(vn),ee(y),ee(gn),ee(Zo),ee(rr),ee(Xce),ee(bn),ee(ds),ee(b0),ee(Hd),ee(ag),ee(rg),ee(y0))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var S=(()=>{let _DynamicDataService=class _DynamicDataService{constructor(i,o,n,e,t,r){this.authService=i,this.commentService=o,this.loggingService=n,this.injector=e,this.docService=t,this.configService=r,this.subscriptions=[],this.commonData$=new ve({}),this.evaluateConditionTriggered=new Me,this.conditionRegex=/\{(.*?)\}/g,this.extractedProps={},this.condition="",this.dataComponentConfigSignal=Te({});try{this.subscriptions.push(this.authService.getUser$().subscribe(a=>{this.commonData$.next(T(I({},this.commonData$.value),{user:a}))})),this.subscriptions.push(this.commentService.getUnreadCommentAnnotationCountOnCurrentDocument$().subscribe(a=>{this.commonData$.next(T(I({},this.commonData$.value),{unreadCommentAnnotationCount:a?.count||0}))})),this.subscriptions.push(this.commentService.getUnreadCommentCountOnCurrentDocument$().subscribe(a=>{this.commonData$.next(T(I({},this.commonData$.value),{unreadCommentCount:a?.count||0}))})),this.subscriptions.push(this.docService.getUIState$().subscribe(a=>{this.commonData$.next(I(I({},this.commonData$.value),a))})),this.subscriptions.push(this.getCommonData().subscribe(a=>{this.dataComponentConfigSignal.update(s=>(s=I(I({},s),a),s)),this.executeConditionalClasses()})),this.subscriptions.push(this.evaluateConditionTriggered.subscribe(a=>{this.extractedProps=a.extractedProps,this.evaluateCondition(a.className,a.elementRef,a.condition)}))}catch(a){this.loggingService.catch("Error in DynamicDataService constructor: ",a)}}ngOnDestroy(){try{this.subscriptions.forEach(i=>i.unsubscribe())}catch(i){this.loggingService.catch("Error in DynamicDataService ngOnDestroy: ",i)}}getCommonData(){return this.commonData$.asObservable()}getModifiedPathBasedOnCondition(i,o){try{return Object.keys(o).forEach(n=>{o[n].path=this.modifyPathBasedOnCondition(n,i)}),o}catch(n){this.loggingService.catch("Error in DynamicDataService getModifiedPathBasedOnCondition: ",n)}}getComputedValues(i,o,n,e,t,r){try{Object.keys(n).forEach(a=>{let s;if(Gi(i)?s=Ui(()=>Ca(i(),n[a].path)):s=Ui(()=>Ca(i,n[a].path)),Gi(s()))Ro(()=>{try{let c=s()();n[a].value=c,this.evaluateConditionTriggered.emit({extractedProps:n,className:e,elementRef:t,condition:r})}catch{}},{injector:this.injector,allowSignalWrites:!0});else{let c=s();n[a].value=c,this.evaluateConditionTriggered.emit({extractedProps:n,className:e,elementRef:t,condition:r})}})}catch(a){this.loggingService.catch("Error in DynamicDataService getComputedValues: ",a)}}modifyPathBasedOnCondition(i,o){try{let n=i;if(i.startsWith("userContact."))n=i.replace("userContact","selectorItem.contact");else if(i.startsWith("comment."))n=i.replace("comment","commentObj");else if(i.startsWith("commentAnnotation."))n=i.replace("commentAnnotation","componentConfigSignal.annotation");else if(i.startsWith("commentAnnotations."))n=i.replace("commentAnnotations","componentConfigSignal.annotations");else{let e=i.match(/^([^.\[]+)/),t=e?e[1]:"";if(t&&o&&typeof o=="function"&&o()&&t in o()){let r=i.match(/\[(.*?)\]/);if(r&&r[1]){let a=r[1];if(a.includes(".")){let s=a.split(".")[0];s&&o()&&s in o()?n=i:n=i.replace(`[${a}]`,`[componentConfigSignal.${a}]`)}else n=i}else n=i}else n="componentConfigSignal."+i}return n}catch(n){return this.loggingService.catch("Error in DynamicDataService modifyPathBasedOnCondition: ",n),i}}applyConditionalClasses(i,o){try{this.elementRef=i,this.data=o}catch(n){this.loggingService.catch("Error in DynamicDataService applyConditionalClasses: ",n)}}executeConditionalClasses(){try{let i=this.getHostElementAttributes(this.elementRef),n=[...Object.keys(i).filter(e=>e.startsWith("velt-class-")).map(e=>({name:e,value:i[e]}))];if(i["velt-class"]){let e=i["velt-class"],t=/'([^']+)':\s*([^,]+)(?:,|$)/g,r=[],a=0,s=100,c;for(;(c=t.exec(e))!==null;){if(a++>s){this.loggingService.catch("Too many class definitions detected.");break}if(c.length<3)continue;let[,p,u]=c;!p||!u||p.split(" ").forEach(C=>{C.trim()&&r.push({name:`velt-class-${C.trim()}`,value:u.trim()})})}n=[...n,...r]}this.data&&typeof this.data=="object"&&Object.keys(this.data).forEach(e=>{this.updateDataComponentConfigSignal(e,this.data[e])}),n.forEach(e=>{let t=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,t,this.elementRef,e.value))})}catch(i){this.loggingService.catch("Error in DynamicDataService applyConditionalClasses: ",i)}}updateDataComponentConfigSignal(i,o){try{i==="dataComponentConfigSignal"?this.dataComponentConfigSignal.set(o):this.dataComponentConfigSignal.update(n=>T(I({},n),{[i]:o}))}catch(n){this.loggingService.catch("Error in DataComponent updateDataComponentConfigSignal: ",n)}}extractProps(){try{this.extractedProps={},this.conditionRegex.lastIndex=0;let i;for(;(i=this.conditionRegex.exec(this.condition))!==null;){let o=i[1];this.extractedProps[o]={value:null,path:null,isDynamicPath:this.hasDynamicParts(o)}}}catch(i){this.loggingService.catch("Error in DynamicDataService extractProps: ",i)}}hasDynamicParts(i){try{let o=/\[[^\]'"]*[^\]'"]\]/.test(i),n=/\[[^[\]]*[\.\[][^[\]]*\]/.test(i);return o||n}catch(o){return this.loggingService.catch("Error checking for dynamic path: ",o),!1}}evaluateCondition(i,o,n){try{if(n){let e=this.extractedProps,t=n.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(t),a=this.safeEval(r);return i&&o&&(a?this.setHostElementClasses(o,i):this.removeHostElementClasses(o,i)),a}return!1}catch(e){return this.loggingService.catch("Error in IfComponent evaluateCondition: ",e),!1}}sanitizeCondition(i){try{return i.replace(/[^a-zA-Z0-9\s\+\-\*\/\%\(\)\!\=\<\>\|\&\.\[\]\{\},'"]/g,"")}catch(o){return this.loggingService.catch("Error in IfComponent sanitizeCondition: ",o),""}}safeEval(expression){try{if(this.configService.getSafeEval()){let i=this.tokenize(expression.trim());return this.evaluateTokens(i)}else return eval(expression)}catch(i){return this.loggingService.catch("safeEval error",i),!1}}tokenize(i){try{if(!i||i.trim()==="")return[];let o=[],n=0;for(;n<i.length;){let e=i[n];if(/\s/.test(e)){n++;continue}if(e==='"'||e==="'"){let t=e,r="";for(n++;n<i.length;)if(i[n]==="\\"&&n+1<i.length)r+=i[n+1],n+=2;else if(i[n]===t){n++;break}else r+=i[n],n++;o.push({type:"string",value:r});continue}if(e==="("){o.push({type:"lparen",value:"("}),n++;continue}if(e===")"){o.push({type:"rparen",value:")"}),n++;continue}if(n<i.length-2&&i.substring(n,n+3)==="==="){o.push({type:"operator",value:"===",precedence:4}),n+=3;continue}if(n<i.length-2&&i.substring(n,n+3)==="!=="){o.push({type:"operator",value:"!==",precedence:4}),n+=3;continue}if(n<i.length-1&&i.substring(n,n+2)==="&&"){o.push({type:"operator",value:"&&",precedence:2}),n+=2;continue}if(n<i.length-1&&i.substring(n,n+2)==="||"){o.push({type:"operator",value:"||",precedence:1}),n+=2;continue}if(n<i.length-1&&i.substring(n,n+2)==="<="){o.push({type:"operator",value:"<=",precedence:4}),n+=2;continue}if(n<i.length-1&&i.substring(n,n+2)===">="){o.push({type:"operator",value:">=",precedence:4}),n+=2;continue}if(n<i.length-1&&i.substring(n,n+2)==="=="){o.push({type:"operator",value:"==",precedence:4}),n+=2;continue}if(n<i.length-1&&i.substring(n,n+2)==="!="){o.push({type:"operator",value:"!=",precedence:4}),n+=2;continue}if(e==="!"){o.push({type:"unary",value:"!",precedence:5}),n++;continue}if(e==="<"){o.push({type:"operator",value:"<",precedence:4}),n++;continue}if(e===">"){o.push({type:"operator",value:">",precedence:4}),n++;continue}if(/[a-zA-Z0-9._]/.test(e)){let t="";for(;n<i.length&&/[a-zA-Z0-9._]/.test(i[n]);)t+=i[n],n++;/^-?\d+(\.\d+)?$/.test(t)?o.push({type:"number",value:parseFloat(t)}):t==="true"||t==="false"?o.push({type:"boolean",value:t==="true"}):t==="null"?o.push({type:"null",value:null}):t==="undefined"?o.push({type:"undefined",value:void 0}):o.push({type:"identifier",value:t});continue}n++}return o}catch(o){return this.loggingService.catch("tokenize error",o),[]}}evaluateTokens(i){try{if(!i||i.length===0)return!1;let o=this.infixToPostfix(i);return this.evaluatePostfix(o)}catch(o){return this.loggingService.catch("evaluateTokens error",o),!1}}infixToPostfix(i){try{let o=[],n=[];for(let e of i)if(e.type==="string"||e.type==="number"||e.type==="boolean"||e.type==="null"||e.type==="undefined"||e.type==="identifier")o.push(e);else if(e.type==="unary")n.push(e);else if(e.type==="operator"){for(;n.length>0;){let t=n[n.length-1];if(t.type==="lparen"||t.precedence!==void 0&&t.precedence<e.precedence)break;o.push(n.pop())}n.push(e)}else if(e.type==="lparen")n.push(e);else if(e.type==="rparen"){for(;n.length>0&&n[n.length-1].type!=="lparen";)o.push(n.pop());n.length>0&&n.pop()}for(;n.length>0;){let e=n.pop();e.type!=="lparen"&&e.type!=="rparen"&&o.push(e)}return o}catch(o){return this.loggingService.catch("infixToPostfix error",o),[]}}evaluatePostfix(i){try{let o=[];for(let n of i)if(n.type==="string"||n.type==="number"||n.type==="boolean"||n.type==="null"||n.type==="undefined"||n.type==="identifier")o.push(n.value);else if(n.type==="unary"){if(o.length>=1){let e=o.pop();n.value==="!"&&o.push(!this.isTruthy(e))}}else if(n.type==="operator"&&o.length>=2){let e=o.pop(),t=o.pop();n.value==="&&"?o.push(this.isTruthy(t)&&this.isTruthy(e)):n.value==="||"?o.push(this.isTruthy(t)||this.isTruthy(e)):o.push(this.compare(t,e,n.value))}return o.length===1?this.isTruthy(o[0]):!1}catch(o){return this.loggingService.catch("evaluatePostfix error",o),!1}}parseValue(i){try{let o=i.trim();return o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'")?o.substring(1,o.length-1):/^-?\d+(\.\d+)?$/.test(o)?parseFloat(o):o==="true"?!0:o==="false"?!1:o==="null"?null:o==="undefined"?void 0:o}catch(o){return this.loggingService.catch("parseValue error",o),i}}compare(i,o,n){try{switch(n){case"===":return i===o;case"!==":return i!==o;case"==":return i==o;case"!=":return i!=o;case"<":return i<o;case">":return i>o;case"<=":return i<=o;case">=":return i>=o;default:return!1}}catch(e){return this.loggingService.catch("compare error",e),!1}}isTruthy(i){try{return i==null||i===""||i==="false"?!1:i==="true"?!0:typeof i=="number"?i!==0:!!i}catch(o){return this.loggingService.catch("isTruthy error",o),!1}}getHostElementAttributes(i){try{let o=i,n={};for(let e of o.attributes)n[e.name]=e.value;return n}catch{return{}}}setHostElementClasses(i,o){try{i.classList.add(o)}catch{}}removeHostElementClasses(i,o){try{i.classList.remove(o)}catch{}}};_DynamicDataService.\u0275fac=function(o){return new(o||_DynamicDataService)(ee(Ve),ee(De),ee(y),ee(Ot),ee(at),ee(Ft))},_DynamicDataService.\u0275prov=Pe({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(t){this._loggingService.catch("Error in BaseComponent set veltIf:",t)}}constructor(e,t,r){this._elementRef=e,this._dynamicDataService=t,this._loggingService=r,this.componentConfigSignal=Te({}),this.veltElement=!0,this.conditionSignal=Te(null)}initializeComponentConfigSignal(e){try{this.componentConfigSignal.set(e)}catch(t){this._loggingService.catch("Error in BaseComponent initializeComponentConfigSignal:",t)}}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(t){this._loggingService.catch("Error in BaseComponent setIfCondition:",t)}}};o.\u0275fac=function(t){return new(t||o)(h(R),h(S),h(y))},o.\u0275cmp=O({type:o,selectors:[["app-base"]],hostVars:1,hostBindings:function(t,r){t&2&&x("data-velt-element",r.veltElement)},inputs:{componentConfigSignal:"componentConfigSignal",template:"template",wireframe:"wireframe",veltIf:"veltIf"},standalone:!1,decls:0,vars:0,template:function(t,r){},encapsulation:2});let i=o;return i})();var Je=(()=>{let o=class o extends H{onDarkModeChange(){return this.darkModeSubject$.asObservable()}constructor(e,t,r,a,s,c,p){super(e,c,p),this._elementRef=e,this._themeService=t,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 ve(!1);try{this._themeSubscriptions.push(this._themeService.getDarkMode$().subscribe(u=>{this._globalDarkMode=u,this.setDarkMode()})),this._featureService&&(this._featureService instanceof De?this._themeSubscriptions.push(this._featureService.getCommentContainerDarkMode().subscribe(u=>{this._featureDarkMode=u,this.setDarkMode()})):this._featureService instanceof rr&&this._themeSubscriptions.push(this._featureService.getDarkMode$().subscribe(u=>{u!==null&&(this._featureDarkMode=u),this.setDarkMode()}))),this._componentDarkModeObservable&&this._componentDarkModeObservable instanceof Ut&&this._themeSubscriptions.push(this._componentDarkModeObservable.subscribe(u=>{this._componentDarkMode=u,this.setDarkMode()}))}catch{}}ngOnInit(){super.ngOnInit()}ngOnChanges(e){try{if(e._darkMode){let t=e._darkMode.currentValue;typeof t=="string"&&(t=t==="true"),this._componentDarkMode=t,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(t){return new(t||o)(h(R),h(qe),h(Jt),h("FeatureService",8),h(Ut),h(S),h(y))},o.\u0275cmp=O({type:o,selectors:[["app-themed"]],inputs:{_darkMode:[0,"darkMode","_darkMode"]},standalone:!1,features:[B,Ze],decls:0,vars:0,template:function(t,r){},encapsulation:2,changeDetection:0});let i=o;return i})();var ze=(()=>{let o=class o{constructor(e){this.loggingService=e,this.wireframeMap=new ve(new Map);try{this.loggingService.log("%c[WB] Creating CLASS: WireframeService","color: blue;")}catch(t){this.loggingService.catch("Error in WireframeService constructor: ",t)}}setWireframe(e,t){try{let r=this.wireframeMap.value;r.set(e,t),this.wireframeMap.next(r)}catch(r){this.loggingService.catch("Error in WireframeService setWireframe: ",r)}}setWireframeMap(e){try{let t=this.wireframeMap.value;e.forEach((r,a)=>{t.set(a,r)}),this.wireframeMap.next(t)}catch(t){this.loggingService.catch("Error in WireframeService setWireframeMap: ",t)}}getWireframe(e,t=!0){try{let r=this.wireframeMap.value,a=r.get(e);if(!a&&t){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,t=!0){try{let r=this.wireframeMap.value,a=r.get(e);if(!a&&t){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,t=!0){return this.wireframeMap.asObservable().pipe(ce(r=>this.getWireframe(e,t)))}setChildren(e){try{this.wireframeMap.next(e)}catch(t){this.loggingService.catch("Error in WireframeService setChildren: ",t)}}getWireframeMap(){return this.wireframeMap.value}};o.\u0275fac=function(t){return new(t||o)(ee(y))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var ede=i=>({componentConfigSignal:i}),tRe=(i,o)=>({condition:i,data:o}),nRe=(i,o,n,e,t)=>({template:i,context:o,componentName:"velt-confirm-dialog-wireframe",variant:n,setIfCondition:e,componentElementRef:t});function iRe(i,o){if(i&1&&(f(0),w(1,"app-confirm-dialog-title",5)(2,"app-confirm-dialog-message",5),_(3,"div",6),w(4,"app-confirm-dialog-reject",5)(5,"app-confirm-dialog-approve",5),b(),v()),i&2){let n=l(3);m(),d("componentConfigSignal",n.componentConfigSignal),m(),d("componentConfigSignal",n.componentConfigSignal),m(2),d("componentConfigSignal",n.componentConfigSignal),m(),d("componentConfigSignal",n.componentConfigSignal)}}function oRe(i,o){if(i&1&&(f(0),g(1,iRe,6,4,"ng-container",4),v()),i&2){let n=l().ngIf,e=l();m(),d("veltDynamicTemplate",$(3,nRe,e.template,A(1,ede,e.componentConfigSignal),n.variant,e.setIfCondition.bind(e),e.elementRef))}}function rRe(i,o){if(i&1&&(f(0),g(1,oRe,2,9,"ng-container",3),v()),i&2){let n=l();m(),d("veltIf",k(3,tRe,n.conditionSignal(),A(1,ede,n.componentConfigSignal)))}}var Sa=(()=>{let o=class o extends Je{constructor(e,t,r,a,s,c,p){super(s,a,void 0,void 0,void 0,p,e),this.loggingService=e,this.dialogRef=t,this.wireframeService=r,this.themeService=a,this.elementRef=s,this.dynamicDataService=p,this.subscriptions=[],this.componentConfigSignal=Te({title:"",message:"",yesButton:"",noButton:"",variant:"",closeDialog:this.closeDialog.bind(this)}),this.componentId="velt-confirm-dialog",this.veltElement=!0;try{c&&(this.componentConfigSignal.update(u=>(u=I(I({},u),c),u)),c?.darkMode&&[!0,!1].includes(c?.darkMode)&&super.setComponentDarkMode(c?.darkMode)),this.setZIndex()}catch(u){this.loggingService.catch("Error in ConfirmDialogComponent constructor: ",u)}}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(t=>{if(t){let r=document.createElement(t.tagName);r.innerHTML=t.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(t){this.loggingService.catch("Error in ConfirmDialogComponent closeDialog: ",t)}}};o.\u0275fac=function(t){return new(t||o)(h(y),h(nr),h(ze),h(qe),h(R),h(Pl,8),h(S))},o.\u0275cmp=O({type:o,selectors:[["snippyly-confirm-dialog"]],hostVars:1,hostBindings:function(t,r){t&2&&x("data-velt-element",r.veltElement)},standalone:!1,features:[V([S]),B],decls:3,vars:5,consts:[["floatingConfirmationRef",""],[1,"velt-confirm-dialog",3,"snippylyOverlay","snippylyOverlayZIndex","snippylyOverlayBackdropZIndex"],[4,"ngIf"],[4,"veltIf"],[4,"veltDynamicTemplate"],[3,"componentConfigSignal"],["mat-dialog-actions","",1,"velt-confirm-dialog-actions"]],template:function(t,r){if(t&1&&(_(0,"div",1,0),g(2,rRe,2,6,"ng-container",2),b()),t&2){let a=de(1);d("snippylyOverlay",a)("snippylyOverlayZIndex",1200)("snippylyOverlayBackdropZIndex",1100),x("data-testid",r.componentId),m(2),d("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%] *[_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)}.velt-confirm-dialog-actions[_ngcontent-%COMP%]{justify-content:space-between;gap:var(--velt-spacing-md);min-height:auto} .velt-mat-dialog-container 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 i=o;return i})();var Vc=(()=>{let o=class o{constructor(e,t,r,a,s,c,p,u,C,E,D,L){this.analyticsService=e,this.configService=t,this.docService=r,this.databaseService=a,this.commonDbService=s,this.authService=c,this.domService=p,this.afAuth=u,this.iamService=C,this.dialog=E,this.loggingService=D,this.notificationService=L,this.areaAnnotationById$=new ve({}),this.documentPaths=null,this.areaEnabled$=new ve(!0),this.allowedElementIds$=new ve([]),this.addAreaMode$=new ve(!1),this.loggingService.log("%c[WB] Creating CLASS: AreaService","color: blue;"),this.analyticsService.setAreaService(this),this.authService.setAreaService(this),this.databaseService.getDb().pipe(Le(z=>!!z),st(1)).subscribe(z=>{z&&this.getDocumentPaths()},z=>{this.loggingService.catch("Error in AreaService getDb subscription: ",z)}),this.domService.onWindowPointerMove$().subscribe(z=>{if(this.addAreaMode$.value){this.highlightElement&&this.domService.removeHighlightFromElement(this.highlightElement);let W=this.domService.getBackgroundElement(z.clientX,z.clientY);W&&(this.isElementInsideAllowedElements(W)?KP(z.target)?this.domService.removeClassFromElement(document.body,"show-pin-cursor"):(this.domService.addClassToElement(document.body,"show-pin-cursor"),this.highlightElement=W,this.domService.highlightElement(this.highlightElement,j.CURSOR.AREA_PIN)):this.domService.removeClassFromElement(document.body,"show-pin-cursor"))}},z=>{this.loggingService.catch("Error in AreaService onWindowPointerMove$ subscription: ",z)}),this.domService.onWindowKeyupEsc$().subscribe(z=>{this.addAreaMode$.value&&this.disableAddAreaMode()},z=>{this.loggingService.catch("Error in AreaService onWindowKeyupEsc$ subscription: ",z)}),this.domService.onDocumentClick$().subscribe(z=>{if(z&&this.addAreaMode$.value){if(z.preventDefault(),z.stopPropagation(),!KP(z.target)){let W=this.domService.getBackgroundElement(z.clientX,z.clientY);W&&this.isElementInsideAllowedElements(W)&&this.addArea(z)}this.disableAddAreaMode()}},z=>{this.loggingService.catch("Error in AreaService onDocumentClick$ subscription: ",z)}),this.addAreaMode$.subscribe(z=>{this.highlightElement&&this.domService.removeHighlightFromElement(this.highlightElement),z?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"))},z=>{this.loggingService.catch("Error in AreaService addAreaMode$ subscription: ",z)}),this.domService.onWindowKeyupBackspace$().subscribe(z=>{this.deleteAreaPinAnnotations("keyupBackspace")},z=>{this.loggingService.catch("Error in AreaService onWindowKeyupBackspace$ subscription: ",z)}),this.domService.onWindowKeyupDelete$().subscribe(z=>{this.deleteAreaPinAnnotations("keyupDelete")},z=>{this.loggingService.catch("Error in AreaService onWindowKeyupDelete$ subscription: ",z)})}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,t,r){this.loggingService.log("%c[WB] Calling FUNCTION: getAllAreaAnnotations","color: green;");let a,s;try{if(e&&(s=En(e)),t&&typeof t=="object"){let c=Yo(t);a=En(JSON.stringify(c))}}catch(c){this.loggingService.catch("Error in AreaService getAllAreaAnnotations: ",c)}return ei(this.afAuth).pipe(Le(c=>!!c),he(c=>this.isFeatureAllowed({firebaseUser:c,annotations:[],filteredAnnotations:[]})),he(c=>c.featureAllowed?this.iamService.isUserAllowed$().pipe(ce(p=>(c.featureAllowed=p,c))):se(c)),he(c=>c.featureAllowed?this.authService.isPlanExpired$().pipe(ce(p=>(c.featureAllowed=!p,c))):se(c)),he(c=>c.featureAllowed?se(c).pipe(he(p=>this.docService.getDocumentPaths$().pipe(ce(u=>(this.documentPaths=u,p.documentPaths=u,p)))),he(p=>s?this.getDataFromDocumentIds([s]).pipe(ce(u=>(p.annotations=u||[],I({},p)))):this.docService.getDocumentIds$().pipe(he(u=>{let C=u?.length>0?u.map(E=>E.documentId):[this.documentPaths?.documentId??""];return this.getDataFromDocumentIds(C).pipe(ce(E=>(p.annotations=E||[],I({},p))))}))),he(p=>this.docService.getLocation$().pipe(ce(u=>(p.location=u,p)))),he(p=>this.docService.getLocations$().pipe(ce(u=>(p.customLocations=u,p)))),ce(p=>{if(p.filteredAnnotations=[],s&&!a)return p.filteredAnnotations=p.annotations?.slice(),p;{let u=[],C=[];return a?u.push(a):(u.push(p?.location?.locationId),u.push(...Object.values(p?.customLocations||[]).map(E=>E.locationId)),p?.location?.location?.id&&C.push(p?.location?.location?.id)),p.filteredAnnotations=this.filterAnnotationsByLocationIds(p?.annotations,u,C),p}}),he(p=>r?se(p):p?.annotations?.length?this.domService.onWindowResize$().pipe(ce(()=>p)):se(p)),he(p=>r?se(p):p?.annotations?.length?this.domService.onDomChange$("AreaService getAllAreaAnnotations").pipe(ce(()=>p)):se(p)),ce(p=>(p.filteredAnnotations=p.filteredAnnotations?.map(u=>{let C=Object.assign({},u);return C.areaProperties=this.calculateAreaAnnotationPosition(C),C}),p)),he(p=>p?.filteredAnnotations?se(p?.filteredAnnotations||[]):se([])),he(p=>{if(this.authService.isFeatureAllowed(Re.COMMENT))return se(p);{let u=p?.filter(C=>!C?.targetAnnotations?.filter(E=>E?.type===Re.COMMENT)?.length);return se(u)}})):se([])),Et(mn))}isFeatureAllowed(e){return this.configService.getConfig$().pipe(Le(t=>!!t),ce(t=>T(I({},e),{config:t})),he(t=>this.authService.getUser$().pipe(ce(r=>T(I({},t),{user:r})))),he(t=>ro(t.config,t.user,Re.AREA)?se(T(I({},t),{featureAllowed:!0})):(this.loggingService.warn("Area feature is not allowed."),se(T(I({},t),{featureAllowed:!1})))),Et((t,r)=>t?.featureAllowed===r?.featureAllowed))}getDataFromDocumentIds(e,t){return this.getDataFromDocuments({documentIds:e,filters:t})}getDataFromDocuments(e){if(this.configService.getApiKey()){let{documentIds:t,filters:r}=e;if(t?.some(u=>!u)||!this.documentPaths)return se([]);let a=this.docService.getDocumentPaths()?.veltFolderId,s=this.docService.getDocumentPaths()?.allDocuments,c=se([]),p={useCollectionGroup:!0,isCollection:!0,useQuery:!0};if(this.commonDbService.shouldUseFirestore()||(p.documentId=t?.length?t[0]:void 0,p.organizationId=this.documentPaths?.organizationId),a&&s)c=this.commonDbService.dbListener({feature:"allAreas",properties:T(I({},p),{firestoreQuery:[Zn(lt("metadata.apiKey","==",this.configService?.getApiKey()),lt("metadata.veltFolderId","==",a),lt("metadata.organizationId","==",this.documentPaths?.organizationId))]})});else{let u=[];for(let C=0;C<(t?.length??0);C+=j.LISTENER_BATCH_SIZE)u.push(t?.slice(C,C+j.LISTENER_BATCH_SIZE)??[]);c=Sn(u.map(C=>this.commonDbService.dbListener({feature:"allAreas",properties:T(I({},p),{firestoreQuery:[Zn(lt("metadata.apiKey","==",this.configService?.getApiKey()),lt("metadata.documentId","in",C),lt("metadata.organizationId","==",this.documentPaths?.organizationId),...a?[lt("metadata.veltFolderId","==",a)]:[])]})}).pipe(da()))).pipe(ce(C=>Ba(C)))}return c.pipe(ce(({data:u,operation:C})=>{let E=[];return u&&(E=Object.values(u??{}).filter(D=>typeof D=="object")),{data:E,operation:C}}),ce(({data:u,operation:C})=>{if(!t)return{data:u,documentMap:{},operation:C};let E=u.reduce((D,L)=>{let z=L.metadata?.documentId;return z&&(D[z]||(D[z]=[]),D[z].push(L)),D},{});return{data:u,documentMap:E,operation:C}}),ce(({data:u,documentMap:C,operation:E})=>{if(!r)if(E?.type==="removed"){if(E?.ids?.length){let D=this.areaAnnotationById$.value;E?.ids?.forEach(L=>{delete D?.[L]}),this.areaAnnotationById$.next(D)}}else Object.entries(C??{}).forEach(([D,L])=>{this.setAreaAnnotationsByOrganizationIdAndDocumentId({organizationId:this.documentPaths?.organizationId,documentId:D,annotations:L})});return u}))}else return se([])}setAreaAnnotationsByOrganizationIdAndDocumentId({organizationId:e,documentId:t,annotations:r,queryHash:a}){try{if(t){e||(e=j.NO_ORGANIZATION_ID),a||(a=j.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(t){this.loggingService.catch("Error in AreaService getAnnotationById: ",t);return}}filterAnnotationsByLocationIds(e,t,r){try{return e.filter(a=>t.includes(a.locationId)||r?.includes(a?.location?.id)||t?.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 t=e.targetElements[0],r=e.targetElements[1];if(t?.xpath&&r?.xpath){let a=this.domService.getElementFromXPath(t.xpath);a&&Xi(a)&&(a=null),this.domService.isXpathWithId(t.xpath)||(!a&&t.cfXpath&&(a=this.domService.getElementFromXPath(t.cfXpath),a&&Xi(a)&&(a=null)),!a&&t.fXpath&&(a=this.domService.getElementFromXPath(t.fXpath),a&&Xi(a)&&(a=null)));let c=this.domService.getElementFromXPath(r.xpath);if(c&&Xi(c)&&(c=null),this.domService.isXpathWithId(r.xpath)||(!c&&r.cfXpath&&(c=this.domService.getElementFromXPath(r.cfXpath),c&&Xi(c)&&(c=null)),!c&&r.fXpath&&(c=this.domService.getElementFromXPath(r.fXpath),c&&Xi(c)&&(c=null))),a&&c){let u=Lj(a,c);if(u){let C=a.getBoundingClientRect(),E={};C&&C.width&&C.height&&(E={top:C.height*t.topPercentage/100,left:C.width*t.leftPercentage/100});let D=c.getBoundingClientRect(),L={};D&&D.width&&D.height&&(L={top:D.height*r.topPercentage/100,left:D.width*r.leftPercentage/100});let z=Bj(E.left,E.top,a,u),W=Bj(L.left,L.top,c,u),J,ue,ye,Ae,He={};z.x>W.x?z.y>W.y?(Ae={x:z.x,y:z.y},J={x:W.x,y:W.y},He.handle1=Ae,He.handle2=J):(ue={x:z.x,y:z.y},ye={x:W.x,y:W.y},He.handle1=ue,He.handle2=ye):z.y>W.y?(ye={x:z.x,y:z.y},ue={x:W.x,y:W.y},He.handle1=ye,He.handle2=ue):(J={x:z.x,y:z.y},Ae={x:W.x,y:W.y},He.handle1=J,He.handle2=Ae);let Fe={topLeft:J||{x:ye?.x,y:ue?.y},bottomRight:Ae||{x:ue?.x,y:ye?.y},topRight:ue||{x:Ae?.x,y:J?.y},bottomLeft:ye||{x:J?.x,y:Ae?.y}};return He.coordinates=Fe,He.targetElement=this.domService.getXPath(u),He}}}}return}catch(t){this.loggingService.catch("Error in AreaService calculateAreaAnnotationPosition:",t);return}}addArea(e,t=[],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 lk;a&&(p.annotationId=a),p.from=c,p.color=j.DEFAULT_ANNOTATION_COLOR,p.lastUpdated=this.timestamp,r&&(p.targetAnnotations=[r]),p.props=new Bl;let u=this.domService.getCurrentWindowSizeValue();if(p.props.screenWidth=u.screenWidth,p.props.screenHeight=u.screenHeight,p.props.screenScrollHeight=u.screenScrollHeight,p.props.viewportWidth=window.innerWidth,p.props.viewportHeight=window.innerHeight,e||t?.length>0){let D=e?this.getPointsForAreaPinAnnotation(e):t;p.targetElements=[],D.forEach(L=>{p.targetElements.push(this.getTargetElementForAreaPinAnnotation(e,{clientX:L.x,clientY:L.y}))})}this.setLocationToAreaAnnotation(p),s&&(p.locationId=s.locationId,p.location=s.location),p.pageInfo=Oi(),p.pageInfo&&(p.pageInfo.screenWidth=this.domService.getCurrentWindowSizeValue()?.screenWidth);let C=this.getElementForAreaAnnotation(p),E=this.docService.getBaseMetadata("area",{element:C});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 t=this.docService.getLocation();t?(e.locationId=t.locationId,e.location=t.location):(delete e.locationId,delete e.location)}catch(t){this.loggingService.catch("Error in AreaService setLocationToAreaAnnotation:",t)}}getElementForAreaAnnotation(e){try{let t,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))),t=Lj(r,a),t}catch(t){return this.loggingService.catch("Error in AreaService getElementForAreaAnnotation: ",t),null}}saveAreaToDb(e){this.loggingService.log("%c[WB] Calling FUNCTION: saveAreaToDb","color: green;");try{this.authService.getUser()&&this.authService.isFeatureAllowed(Re.AREA)&&Sn([this.docService.getDocumentPaths$(),this.databaseService.getDb()]).pipe(Le(([t,r])=>!!t&&!!r),st(1),he(([t,r])=>{if(this.documentPaths=t,this.documentPaths?.area){e.annotationId||(e.annotationId=this.commonDbService.generateDocumentId()),e.pageInfo&&(e.pageInfo.areaUrl=this.generateAreaUrl(e));let a=JSON.parse(JSON.stringify(e));if(a.position=null,!a?.metadata?.documentId){a?.metadata||(a.metadata={});let p=this.docService.getBaseMetadata();a.metadata=I(I({},a?.metadata),p)}this.domService.toggleAnnotationSelection(a),this.analyticsService.trackEvent(Z.Events.Area.AREA_ADDED,{annotationId:e.annotationId});let{documentId:s,organizationId:c}=this.getDocumentIdAndOrganizationIdFromAreaAnnotation(e);return this.commonDbService.setData({feature:"area",properties:{id:e.annotationId,documentId:s,organizationId:c},data:JSON.parse(JSON.stringify(a))})}else return se(null)})).subscribe(()=>{},t=>{this.loggingService.catch("Error in AreaService saveAreaToDb subscription: ",t)})}catch(t){this.loggingService.catch("Error in AreaService saveAreaToDb: ",t)}}getDocumentIdAndOrganizationIdFromAreaAnnotation(e){try{return{documentId:e?.metadata?.documentId,organizationId:e?.metadata?.organizationId}}catch(t){return this.loggingService.catch("Error in AreaService getDocumentIdAndOrganizationIdFromAreaAnnotation: ",t),{}}}updateArea(e,t=!1,r){try{r&&this.setLocationToAreaAnnotation(e),t&&this.updateNotificationsDatabase(e,jP.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 t=JSON.parse(JSON.stringify(e));if(t.position=null,!t?.metadata?.documentId){t?.metadata||(t.metadata={});let s=this.docService.getBaseMetadata();t.metadata=I(I({},t?.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(t))})}}catch(t){this.loggingService.catch("Error in AreaService updateAreaToDb: ",t)}}deleteAreaPinAnnotations(e){try{let t=this.domService.getSelectedAnnotationsMap(),r=this.authService.getUser(),a=[];Object.keys(t??{}).forEach(s=>Q(this,null,function*(){let c=t[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(Sa,{panelClass:"velt-mat-dialog-container",data:{title:"Delete area?",message:"This selected area will be deleted.",yesButton:"Delete",noButton:"Cancel",variant:"area"}}).afterClosed().pipe(st(1)).subscribe(s=>{s&&(a.forEach(c=>Q(this,null,function*(){yield this.deleteAreaPinAnnotation(c)})),setTimeout(()=>{document.querySelectorAll(`[${j.SNIPPYLY_HIGHLIGHT}]`).forEach(p=>{this.domService.removeHighlightFromElement(p)})},100))})),this.domService.resetSelectedAnnotationsMap(!0,"area")}catch(t){this.loggingService.catch("Error in AreaService deleteAreaPinAnnotations: ",t)}}getAreaAnnotationsByOrganizationIdAndDocumentId({organizationId:e,documentId:t}){try{let r={};return Object.values(this.areaAnnotationById$.value??{}).forEach(a=>{a?.metadata?.documentId==t&&a?.metadata?.organizationId==e&&(r[a?.annotationId]=a)}),Object.values(r??{})}catch(r){return this.loggingService.catch("Error in AreaService getAreaAnnotationsByOrganizationIdAndDocumentId:",r),[]}}onDeleteTargetAnnotation(e,t){try{if(this.docService.getDocumentId()&&this.areaAnnotationById$.value){let a=Object.values(this.areaAnnotationById$.value||{}),s;t?s=a.find(c=>c?.annotationId===t):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,jP.DELETED),this.analyticsService.trackEvent(Z.Events.Area.AREA_DELETED,{annotationId:e.annotationId});let{documentId:t,organizationId:r}=this.getDocumentIdAndOrganizationIdFromAreaAnnotation(e);return this.commonDbService.deleteData({feature:"area",properties:{id:e.annotationId,documentId:t,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),se(!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,t){try{let r=e,a=r?.touches?.length?r.touches[0]?.clientX:r?.clientX,s=r?.touches?.length?r.touches[0]?.clientY:r?.clientY;t&&(a=t.clientX,s=t.clientY);let c=this.domService.getBackgroundElement(a,s);if(c){let p=this.domService.getXPath(c),u=this.domService.getXPath(c,!0),C=this.domService.getXPath(c,!0,!0),E=c.getBoundingClientRect(),D=a-E.x,L=s-E.y,z=D*100/(E.width||1),W=L*100/(E.height||1);return{xpath:p,fXpath:u,cfXpath:C,leftPercentage:z,topPercentage:W}}else return null}catch(r){return this.loggingService.catch("Error in AreaService getTargetElementForAreaPinAnnotation: ",r),null}}getPointsForAreaPinAnnotation(e){let t=[],r=e,a=r?.touches?.length?r.touches[0]?.clientX:r.clientX,s=r?.touches?.length?r.touches[0]?.clientY:r.clientY;return t.push({x:a,y:s}),t.push({x:a+100,y:s+100}),t}get timestamp(){return this.commonDbService.getServerTimestamp()}isElementInsideAllowedElements(e){try{return this.domService.isElementInsideListedElementIds(e,this.allowedElementIds$.value)}catch(t){return this.loggingService.catch("Error in AreaService isElementInsideAllowedElements: ",t),!1}}updateNotificationsDatabase(e,t){try{let r={annotationData:e,actionType:t,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=Oi(),e.pageInfo&&(e.pageInfo.screenWidth=this.domService.getCurrentWindowSizeValue()?.screenWidth)),e.pageInfo.areaUrl=this.generateAreaUrl(e),this.updateArea(e),e.pageInfo?.areaUrl)}catch(t){this.loggingService.catch("Error in AreaService getAreaUrl: ",t);return}}generateAreaUrl(e){let t=new URL(window.location.href);return t.searchParams.delete(j.URL_PARAMS.TAG_ID),t.searchParams.append(j.URL_PARAMS.TAG_ID,e.annotationId),t.href}generateAreaAnnotationId(){return Q(this,null,function*(){try{if(this.docService.getDocumentPaths()?.area){let t=this.commonDbService.generateDocumentId();return yield Pd(10),t||""}else return""}catch(e){return this.loggingService.catch("Error in AreaService generateAreaAnnotationId: ",e),""}})}};o.\u0275fac=function(t){return new(t||o)(ee(et),ee(Ft),ee(at),ee(Dn),ee(pn),ee(Ve),ee(Be),ee(Di),ee(vn),ee(no),ee(y),ee(gn))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var si=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,n={},e=!0){try{this.hideAnalytics||(n||(n={}),n=T(I({},n),{source:"external"}),this.getService(et).trackAuthenticatedEvent(o,n,e))}catch(t){this.getService(y).catch("Error in _trackEvent: ",t);return}}};var jk=class extends si{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(Vc).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(Vc).disableArea()}catch(o){this.getService(y).catch("Error in _disableAreaComment: ",o)}}};var zd=(()=>{let o=class o{constructor(e,t,r,a,s,c,p,u,C,E,D,L){this.analyticsService=e,this.configService=t,this.docService=r,this.databaseService=a,this.authService=s,this.domService=c,this.afAuth=p,this.iamService=u,this.dialog=C,this.loggingService=E,this.notificationService=D,this.commonDbService=L,this.arrowAnnotations$=new ve({}),this.arrowAnnotationsByDocumentId$=new ve({}),this.documentPaths=null,this.allowedElementIds$=new ve([]),this.addArrowMode$=new ve(!1),this.loggingService.log("%c[WB] Creating CLASS: ArrowService","color: blue;"),this.databaseService.getDb().pipe(Le(z=>!!z),st(1)).subscribe(z=>{z&&this.getDocumentPaths()},z=>{this.loggingService.catch("Error in ArrowService getDb subscription: ",z)}),this.domService.onWindowPointerMove$().subscribe(z=>{if(this.addArrowMode$.value){let W=!0,J=this.domService.getBackgroundElement(z.clientX,z.clientY);J&&(this.isElementInsideAllowedElements(J)?YP(z.target)?this.domService.removeClassFromElement(document.body,"show-pin-cursor"):(this.domService.addClassToElement(document.body,"show-pin-cursor"),this.highlightElement&&this.highlightElement!==J&&this.domService.removeHighlightFromElement(this.highlightElement),this.highlightElement=J,this.domService.highlightElement(this.highlightElement,j.CURSOR.ARROW_PIN),W=!1):this.domService.removeClassFromElement(document.body,"show-pin-cursor")),this.highlightElement&&W&&(this.domService.removeHighlightFromElement(this.highlightElement),this.highlightElement=null)}},z=>{this.loggingService.catch("Error in ArrowService onWindowPointerMove$ subscription: ",z)}),this.domService.onWindowKeyupEsc$().subscribe(z=>{this.addArrowMode$.value&&this.disableAddArrowMode()},z=>{this.loggingService.catch("Error in ArrowService onWindowKeyupEsc$ subscription: ",z)}),this.domService.onDocumentClick$().subscribe(z=>{if(z&&this.addArrowMode$.value){if(!YP(z.target)){let W=this.domService.getBackgroundElement(z.clientX,z.clientY);W&&this.isElementInsideAllowedElements(W)&&(z.preventDefault(),z.stopPropagation(),this.addArrow(z))}this.disableAddArrowMode()}},z=>{this.loggingService.catch("Error in ArrowService onDocumentClick$ subscription: ",z)}),this.addArrowMode$.subscribe(z=>{this.highlightElement&&this.domService.removeHighlightFromElement(this.highlightElement),z?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"))},z=>{this.loggingService.catch("Error in ArrowService addArrowMode$ subscription: ",z)}),this.domService.onWindowKeyupBackspace$().subscribe(z=>{this.deleteArrowPinAnnotations("keyupBackspace")},z=>{this.loggingService.catch("Error in ArrowService onWindowKeyupBackspace$ subscription: ",z)}),this.domService.onWindowKeyupDelete$().subscribe(z=>{this.deleteArrowPinAnnotations("keyupDelete")},z=>{this.loggingService.catch("Error in ArrowService onWindowKeyupDelete$ subscription: ",z)})}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,t,r){this.loggingService.log("%c[WB] Calling FUNCTION: getAllArrowAnnotations","color: green;");let a,s;try{if(e&&(s=En(e)),t&&typeof t=="object"){let c=Yo(t);a=En(JSON.stringify(c))}}catch(c){this.loggingService.catch("Error in ArrowService getAllArrowAnnotations: ",c)}return ei(this.afAuth).pipe(Le(c=>!!c),he(c=>this.isFeatureAllowed({firebaseUser:c,annotations:[],filteredAnnotations:[]})),he(c=>c.featureAllowed?this.iamService.isUserAllowed$().pipe(ce(p=>(c.featureAllowed=p,c))):se(c)),he(c=>c.featureAllowed?this.authService.isPlanExpired$().pipe(ce(p=>(c.featureAllowed=!p,c))):se(c)),he(c=>c.featureAllowed?se(c).pipe(he(p=>this.docService.getDocumentPaths$().pipe(ce(u=>(this.documentPaths=u,p.documentPaths=u,p)))),he(p=>this.getDataFromDocumentId(s).pipe(ce(u=>(p.annotations=u||[],I({},p))))),he(p=>this.docService.getLocation$().pipe(ce(u=>(p.location=u,p)))),he(p=>this.docService.getLocations$().pipe(ce(u=>(p.customLocations=u,p)))),ce(p=>{if(p.filteredAnnotations=[],s&&!a)return p.filteredAnnotations=p.annotations?.slice(),p;{let u=[];return a?u.push(a):(u.push(p?.location?.locationId),u.push(...Object.values(p?.customLocations||[]).map(C=>C.locationId))),p.filteredAnnotations=this.filterAnnotationsByLocationIds(p?.annotations,u),p}}),he(p=>r?se(p):p?.annotations?.length?this.domService.onWindowResize$().pipe(ce(()=>p)):se(p)),he(p=>r?se(p):p?.annotations?.length?this.domService.onDomChange$("ArrowService getAllArrowAnnotations").pipe(ce(()=>p)):se(p)),ce(p=>(p?.filteredAnnotations?.forEach(u=>{this.calculateArrowAnnotationPosition(u)}),p)),he(p=>p?.filteredAnnotations?se(p?.filteredAnnotations||[]):se([]))):se([])),Et(mn))}isFeatureAllowed(e){return this.configService.getConfig$().pipe(Le(t=>!!t),ce(t=>T(I({},e),{config:t})),he(t=>this.authService.getUser$().pipe(ce(r=>T(I({},t),{user:r})))),he(t=>ro(t.config,t.user,Re.ARROW)?se(T(I({},t),{featureAllowed:!0})):(this.loggingService.warn("Arrow feature is not allowed."),se(T(I({},t),{featureAllowed:!1})))),Et((t,r)=>t?.featureAllowed===r?.featureAllowed))}getDataFromDocumentId(e){return this.databaseService.getDb().pipe(Le(t=>!!t),he(t=>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}}),kn(r=>(this.loggingService.catch("Error in ArrowService getDataFromDocumentId: ",r),se({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})):se([])))}setArrowAnnotationsByDocumentId(e,t){try{if(e){let r=T(I({},this.arrowAnnotationsByDocumentId$.value),{[e]:t});this.arrowAnnotationsByDocumentId$.next(r)}}catch(r){this.loggingService.catch("Error in ArrowService setArrowAnnotationsByDocumentId:",r)}}filterAnnotationsByLocationIds(e,t){try{return e.filter(r=>t.includes(r.locationId))}catch(r){return this.loggingService.catch("Error in ArrowService filterAnnotationsByLocations:",r),[]}}calculateArrowAnnotationPosition(e){try{if(e.targetElement){let t=this.domService.getXPath(e.targetElement?.xpath);if(t){let r=t.iterateNext();if(r&&Ao(r)){let a=r.getBoundingClientRect();if(a&&a.width&&a.height){let{height:s,width:c}=Wp(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(t){this.loggingService.catch("Error in ArrowService calculateArrowAnnotationPosition:",t)}}addArrow(e){this.loggingService.log("%c[WB] Calling FUNCTION: addArrow","color: green;");try{let t=this.authService.getUser();if(t)if(t.isReadOnly||t.isAnonymous)this.loggingService.catch("Anonymous/Readonly users cannot add arrows.");else{let r=new ck;r.from=t,r.color=t?.color||j.DEFAULT_ANNOTATION_COLOR,r.lastUpdated=this.timestamp,r.props=new Bl;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=j.VELT_MIN_ARROW_LENGTH,(e?.clientX||0)>j.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&&(Ao(c)||(r.targetElement=null))}}this.setLocationToArrowAnnotation(r),r.pageInfo=Oi(),r.pageInfo&&(r.pageInfo.screenWidth=this.domService.getCurrentWindowSizeValue()?.screenWidth),this.saveArrowToDb(r)}}catch(t){this.loggingService.catch("Error in ArrowService addArrow: ",t)}}setLocationToArrowAnnotation(e){try{let t=this.docService.getLocation();t?(e.locationId=t.locationId,e.location=t.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({location:a,source:"internal"});s?.[0]&&(e.locationId=s[0].locationId,e.location=s[0].location)}}}catch{}}catch(t){this.loggingService.catch("Error in ArrowService setLocationToArrowAnnotation:",t)}}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(Le(t=>!!t),st(1),he(t=>(this.documentPaths=t,this.loggingService.log(this.documentPaths),this.databaseService.getDb().pipe(Le(r=>!!r),st(1),he(r=>{if(this.documentPaths?.arrow){e.annotationId=this.commonDbService.generateDocumentId(),e.pageInfo&&(e.pageInfo.arrowUrl=this.generateArrowUrl(e));let a=JSON.parse(JSON.stringify(e));return a.position=null,this.domService.toggleAnnotationSelection(a),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(a))})}else return se(null)}))))).subscribe(()=>{},t=>{this.loggingService.catch("Error in ArrowService saveArrowToDb subscription: ",t)})}catch(t){this.loggingService.catch("Error in ArrowService saveArrowToDb: ",t)}}updateArrow(e,t=!1,r){try{r&&this.setLocationToArrowAnnotation(e),t&&this.updateNotificationsDatabase(e,UP.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 t=this.domService.getXPath(e.targetElement.xpath);if(t){let r=t.iterateNext();r&&(Ao(r)||(e.targetElement=null))}}this.domService.updateSelectedAnnotationInMap([e]),this.authService.getUser()&&this.authService.isFeatureAllowed(Re.ARROW)&&this.docService.getDocumentPaths$().pipe(Le(t=>!!t),st(1),he(t=>(this.documentPaths=t,this.loggingService.log(this.documentPaths),this.databaseService.getDb().pipe(Le(r=>!!r),st(1),he(r=>{if(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 se(null)}))))).subscribe(()=>{},t=>{this.loggingService.catch("Error in ArrowService updateArrowToDb subscription: ",t)})}catch(t){this.loggingService.catch("Error in ArrowService updateArrowToDb: ",t)}}deleteArrowPinAnnotations(e){try{let t=this.domService.getSelectedAnnotationsMap(),r=this.authService.getUser(),a=[];Object.keys(t).forEach(s=>Q(this,null,function*(){let c=t[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(Sa,{panelClass:"velt-mat-dialog-container",data:{title:"Delete arrow?",message:"This selected arrow will be deleted.",yesButton:"Delete",noButton:"Cancel",variant:"arrow"}}).afterClosed().pipe(st(1)).subscribe(s=>{s&&(a.forEach(c=>Q(this,null,function*(){yield this.deleteArrowPinAnnotation(c)})),setTimeout(()=>{document.querySelectorAll(`[${j.SNIPPYLY_HIGHLIGHT}]`).forEach(p=>{this.domService.removeHighlightFromElement(p)})},100))})),this.domService.resetSelectedAnnotationsMap(!0,"arrow")}catch(t){this.loggingService.catch("Error in ArrowService deleteArrowPinAnnotations: ",t)}}deleteArrowPinAnnotation(e){return this.authService.isFeatureAllowed(Re.ARROW)&&this.documentPaths?.arrow&&e?.annotationId?(this.updateNotificationsDatabase(e,UP.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(t){return this.loggingService.catch("Error in ArrowService isElementInsideAllowedElements: ",t),!1}}updateNotificationsDatabase(e,t){try{let r={annotationData:e,actionType:t,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=Oi(),e.pageInfo&&(e.pageInfo.screenWidth=this.domService.getCurrentWindowSizeValue()?.screenWidth)),e.pageInfo.arrowUrl=this.generateArrowUrl(e),this.updateArrow(e),e.pageInfo?.arrowUrl)}catch(t){this.loggingService.catch("Error in ArrowService getArrowUrl: ",t);return}}generateArrowUrl(e){let t=new URL(window.location.href);return t.searchParams.delete(j.URL_PARAMS.TAG_ID),t.searchParams.append(j.URL_PARAMS.TAG_ID,e.annotationId),t.href}};o.\u0275fac=function(t){return new(t||o)(ee(et),ee(Ft),ee(at),ee(Dn),ee(Ve),ee(Be),ee(Di),ee(vn),ee(no),ee(y),ee(gn),ee(pn))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var Hk=class extends si{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(zd).setAllowedElementIds(o)}catch(n){this.getService(y).catch("Error in allowedElementIds: ",n)}}};var dl=(()=>{let o=class o{constructor(e){this.loggingService=e,this.autocompleteDataMap$=new ve({}),this.onAutocompleteChipClick$=new tt;try{this.loggingService.log("%c[WB] Creating CLASS: AutocompleteService","color: blue;"),this.create({hotkey:"@",type:"contact",data:[]})}catch(t){this.loggingService.catch("Error in AutocompleteService constructor: ",t)}}create(e){try{if(this.loggingService.log("%c[WB] Calling AutocompleteService FUNCTION: create","color: green;"),e?.hotkey){let t=this.autocompleteDataMap$.value;t[e.hotkey]=e,this.autocompleteDataMap$.next(t)}}catch(t){this.loggingService.catch("Error in AutocompleteService create: ",t)}}remove(e){try{this.loggingService.log("%c[WB] Calling AutocompleteService FUNCTION: remove","color: green;");let t=this.autocompleteDataMap$.value;delete t[e],this.autocompleteDataMap$.next(t)}catch(t){this.loggingService.catch("Error in AutocompleteService remove: ",t)}}getAutocompleteDataMap$(){return this.autocompleteDataMap$.asObservable()}getAutocompleteDataMap(){return this.autocompleteDataMap$.value}setOnAutocompleteChipClick(e){this.onAutocompleteChipClick$.next(e)}getOnAutocompleteChipClick$(){return this.onAutocompleteChipClick$.asObservable()}};o.\u0275fac=function(t){return new(t||o)(ee(y))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var Gk=class extends si{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(dl).create(o)}catch(n){this.getService(y).catch("Error in _create: ",n)}}_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(dl).getOnAutocompleteChipClick$()}catch(o){return this.getService(y).catch("Error in _onAutocompleteChipClick: ",o),se(null)}}};var tde=(()=>{let o=class o{constructor(e,t,r,a,s,c,p){this.authService=e,this.iamService=t,this.docService=r,this.configService=a,this.commonDbService=s,this.loggingService=c,this.commentService=p,this.documentPaths=null,this.LISTENER_BATCH_SIZE=30}getAnnotationsCount(e){try{return this.authService.getUser$().pipe(Le(t=>!!t),he(t=>this.commentService.isFeatureAllowed({firebaseUser:t,annotations:[],filteredAnnotations:[]})),he(t=>t.featureAllowed?this.iamService.isUserAllowed$().pipe(ce(r=>(t.featureAllowed=r,t))):se(t)),he(t=>t.featureAllowed?this.processRequest(t,e):se(null)),ce(t=>t??{data:null}),Et(mn))}catch(t){return this.loggingService.catch("Error in CommentService getAnnotationsCount: ",t),se({data:null})}}processRequest(e,t){try{return se(e).pipe(he(()=>this.initializeDocumentPaths(e)),he(()=>this.getDocumentIds$(t)),he(r=>{let a=this.authService.getUser()?.userSnippylyId,s=this.buildRequestContext(t,r);if(!this.validateRequestContext(s,t))return se({data:null,mode:s.mode,serverDocumentIds:s.serverDocumentIds});if(!s.organizationId)return se({data:null,mode:s.mode,serverDocumentIds:s.serverDocumentIds});let c=this.setupTriggers$(s.mode,s.organizationId,s.veltFolderId,s.serverDocumentIds);return this.shouldUseAggregateMode(s.mode)?this.handleAggregateCounts$({triggers$:c,serverDocumentIds:s.serverDocumentIds,request:t,userId:a,organizationId:s.organizationId,clientOrganizationId:s.clientOrganizationId,veltFolderId:s.veltFolderId,folderId:s.folderId,mode:s.mode}).pipe(ce(p=>({data:p,mode:s.mode,serverDocumentIds:s.serverDocumentIds}))):this.handleGroupedCounts$(c,r,t,a,s.organizationId,s.veltFolderId).pipe(ce(p=>({data:p,mode:s.mode,serverDocumentIds:s.serverDocumentIds})))}),he(r=>{if(!r?.data)return se(null);let{data:a,mode:s,serverDocumentIds:c}=r;return t?.filterGhostComments?this.filterGhostComments$(a,s,c):se(a)}),kn(r=>(this.loggingService.catch("Error processing request: ",r),se(null))))}catch(r){return this.loggingService.catch("Error in CommentService getAnnotationsCount: ",r),se(null)}}initializeDocumentPaths(e){try{return this.docService.getDocumentPaths$().pipe(Le(t=>!!t),dn(t=>{this.documentPaths=t,e.documentPaths=t}),ce(()=>{}))}catch(t){return this.loggingService.catch("Error in CommentService initializeDocumentPaths: ",t),se(e)}}buildRequestContext(e,t){try{let r=this.documentPaths?.organizationId,a=this.documentPaths?.clientOrganizationId,s,c,p;if(e?.allDocuments||e?.documentIds||e?.folderId||e?.organizationId||e?.locationIds){if(e.organizationId&&(r=La(e.organizationId),a=e.organizationId),!r)throw new Error("organizationId is required for this request type");e.folderId&&(s=Fi(e.folderId),c=e.folderId),e.allDocuments&&(p=!0)}else s=this.documentPaths?.veltFolderId,c=this.documentPaths?.folderId,p=this.documentPaths?.allDocuments;let u=this.determineMode(e,s,p,t),C=u.isOrgMode?[]:t.length>0?t.map(E=>E.documentId):[this.documentPaths?.documentId??""];return{organizationId:r,clientOrganizationId:a,veltFolderId:s,folderId:c,allDocuments:p,mode:u,serverDocumentIds:C}}catch(r){return this.loggingService.catch("Error in CommentService buildRequestContext: ",r),{organizationId:void 0,clientOrganizationId:void 0,veltFolderId:void 0,folderId:void 0,allDocuments:void 0,mode:{isOrgMode:!1,isFolderMode:!1,isBatchMode:!1},serverDocumentIds:[]}}}validateRequestContext(e,t){try{if(t?.aggregateDocuments&&!e.serverDocumentIds.length)throw this.loggingService.catch("Error in CommentService getAnnotationsCount: documentIds is required when aggregateDocuments is true"),new Error("documentIds is required when aggregateDocuments is true");return!(!e.organizationId||!(e.mode.isOrgMode||e.mode.isFolderMode)&&e.serverDocumentIds.some(r=>!r)||!this.documentPaths)}catch(r){return this.loggingService.catch("Error in CommentService validateRequestContext: ",r),!1}}shouldUseAggregateMode(e){try{return e.isFolderMode||e.isOrgMode||e.isBatchMode}catch(t){return this.loggingService.catch("Error in CommentService shouldUseAggregateMode: ",t),!1}}getDocumentIds$(e){try{return e?.documentIds?.length?se(e.documentIds.map(t=>({clientDocumentId:t,documentId:na(t)}))):this.docService.getDocumentIds$().pipe(ce(t=>t.length>0?t:[{documentId:this.documentPaths?.documentId??"",clientDocumentId:this.documentPaths?.clientDocumentId||""}]))}catch(t){return this.loggingService.catch("Error in CommentService getDocumentIds: ",t),se([])}}determineMode(e,t,r,a){try{let s=!!e?.organizationId&&!e?.documentIds?.length&&!t&&!r,c=!!t&&!!r,p=!!e?.aggregateDocuments&&!r&&!!a?.length;return{isOrgMode:s,isFolderMode:c,isBatchMode:p}}catch(s){return this.loggingService.catch("Error in CommentService determineMode: ",s),{isOrgMode:!1,isFolderMode:!1,isBatchMode:!1}}}setupTriggers$(e,t,r,a){try{if(e.isOrgMode)return[this.commonDbService.dbListener({feature:"organizationMetadata",properties:{useCollectionGroup:!1,isCollection:!1,organizationId:t}}).pipe(ce(c=>c?.data?.commentViewsUpdatedAt??null),Le(c=>!!c),Et(mn))];if(e.isFolderMode)return[this.commonDbService.dbListener({feature:"folder",properties:{useCollectionGroup:!1,isCollection:!1,folderId:r,organizationId:t}}).pipe(ce(c=>c?.data?.commentViewsUpdatedAt??null),Le(c=>!!c),Et(mn))];if(e.isBatchMode){let s=[];for(let c=0;c<a.length;c+=this.LISTENER_BATCH_SIZE)s.push(a.slice(c,c+this.LISTENER_BATCH_SIZE));return s.map(c=>this.commonDbService.dbListener({feature:"allDocuments",properties:{useCollectionGroup:!0,isCollection:!0,useQuery:!0,firestoreQuery:[Zn(lt("metadata.apiKey","==",this.configService?.getApiKey()),lt("metadata.organizationId","==",t),lt("metadata.documentId","in",c))]}}).pipe(ce(u=>Object.values(u?.data||{}).map(E=>E?.commentViewsUpdatedAt??null).sort().join(",")),Et(mn)))}else return a.map(s=>this.commonDbService.dbListener({feature:"documentMetadata",properties:{useCollectionGroup:!1,isCollection:!1,documentId:s,organizationId:t}}).pipe(ce(p=>p?.data?.commentViewsUpdatedAt??null),Le(p=>!!p),Et(mn)))}catch(s){return this.loggingService.catch("Error in CommentService setupTriggers: ",s),[]}}handleGroupedCounts$(e,t,r,a,s,c){try{let p=t.map((u,C)=>e[C].pipe(bo(void 0),he(()=>Zi(this.getCountsForDocument$(u.documentId,u.clientDocumentId,r,a,s,c)))));return Sn(p).pipe(ce(u=>{let C={};return u.forEach(E=>{E&&(C[E.clientDocumentId]={total:E.total,unread:E.unread})}),{data:C}}),kn(u=>(this.loggingService.catch("Error in grouped counts: ",u),se(null))))}catch(p){return this.loggingService.catch("Error in CommentService handleGroupedCounts: ",p),se(null)}}handleAggregateCounts$(e){try{let{triggers$:t,serverDocumentIds:r,request:a,userId:s,organizationId:c,clientOrganizationId:p,veltFolderId:u,folderId:C,mode:E}=e;return Sn(t).pipe(ce(()=>{})).pipe(bo(void 0),he(()=>Zi(this.getAggregateCounts({serverDocumentIds:r,request:a,userId:s,organizationId:c,clientOrganizationId:p,veltFolderId:u,folderId:C,mode:E}))),kn(L=>(this.loggingService.catch("Error in aggregate counts: ",L),se(null))))}catch(t){return this.loggingService.catch("Error in CommentService handleAggregateCounts: ",t),se(null)}}getCountsForDocument$(e,t,r,a,s,c){return Q(this,null,function*(){try{let p=this.configService?.getApiKey(),u={useCollectionGroup:!0,isCollection:!0,useQuery:!0,getCount:!0},C=[lt("metadata.apiKey","==",p),lt("metadata.organizationId","==",s),lt("metadata.documentId","in",[e]),...c?[lt("metadata.veltFolderId","==",c)]:[],...r?.statusIds?.length?[lt("status.id","in",r.statusIds)]:[],...r?.locationIds?.length?[lt("location.id","in",r.locationIds)]:[]],E=[Zn(...C),fi("lastUpdated","desc"),fi("createdAt","desc")],D=yield this.commonDbService.queryData({feature:"allComments",properties:T(I({},u),{firestoreQuery:E})}),L=[...C,lt("viewedByUserIds","array-contains",a)],z=[Zn(...L),fi("lastUpdated","desc"),fi("createdAt","desc")],W=yield this.commonDbService.queryData({feature:"allComments",properties:T(I({},u),{firestoreQuery:z})});return{clientDocumentId:t,total:D,unread:D-W}}catch(p){return this.loggingService.catch("Error in CommentService getCountsForDocument: ",p),null}})}getAggregateCounts(e){return Q(this,null,function*(){try{let t="",{serverDocumentIds:r,request:a,userId:s,organizationId:c,clientOrganizationId:p,veltFolderId:u,folderId:C,mode:E}=e,D=this.configService?.getApiKey(),L={useCollectionGroup:!0,isCollection:!0,useQuery:!0,getCount:!0},z=[lt("metadata.apiKey","==",D),lt("metadata.organizationId","==",c),...a?.statusIds?.length?[lt("status.id","in",a.statusIds)]:[],...a?.locationIds?.length?[lt("location.id","in",a.locationIds)]:[]],W,J;if(E.isFolderMode){t=C??"",z.push(lt("metadata.veltFolderId","==",u));let ue=[Zn(...z),fi("lastUpdated","desc"),fi("createdAt","desc")];W=yield this.commonDbService.queryData({feature:"allComments",properties:T(I({},L),{firestoreQuery:ue})});let ye=[...z,lt("viewedByUserIds","array-contains",s)],Ae=[Zn(...ye),fi("lastUpdated","desc"),fi("createdAt","desc")];J=yield this.commonDbService.queryData({feature:"allComments",properties:T(I({},L),{firestoreQuery:Ae})})}else if(E.isOrgMode){t=p??"";let ue=[Zn(...z),fi("lastUpdated","desc"),fi("createdAt","desc")];W=yield this.commonDbService.queryData({feature:"allComments",properties:T(I({},L),{firestoreQuery:ue})});let ye=[...z,lt("viewedByUserIds","array-contains",s)],Ae=[Zn(...ye),fi("lastUpdated","desc"),fi("createdAt","desc")];J=yield this.commonDbService.queryData({feature:"allComments",properties:T(I({},L),{firestoreQuery:Ae})})}else{t="result";let ue=[];for(let xe=0;xe<r.length;xe+=this.LISTENER_BATCH_SIZE)ue.push(r.slice(xe,xe+this.LISTENER_BATCH_SIZE));let ye=ue.map(xe=>Q(this,null,function*(){let Se=[...z,lt("metadata.documentId","in",xe),...u?[lt("metadata.veltFolderId","==",u)]:[]],we=[Zn(...Se),fi("lastUpdated","desc"),fi("createdAt","desc")];return this.commonDbService.queryData({feature:"allComments",properties:T(I({},L),{firestoreQuery:we})})}));W=(yield Promise.allSettled(ye)).reduce((xe,Se)=>xe+(Se.status==="fulfilled"&&Se.value||0),0);let He=ue.map(xe=>Q(this,null,function*(){let Se=[...z,lt("metadata.documentId","in",xe),...u?[lt("metadata.veltFolderId","==",u)]:[],lt("viewedByUserIds","array-contains",s)],we=[Zn(...Se),fi("lastUpdated","desc"),fi("createdAt","desc")];return this.commonDbService.queryData({feature:"allComments",properties:T(I({},L),{firestoreQuery:we})})}));J=(yield Promise.allSettled(He)).reduce((xe,Se)=>xe+(Se.status==="fulfilled"&&Se.value||0),0)}return{data:{[t]:{total:W,unread:W-J}}}}catch(t){return this.loggingService.catch("Error in CommentService getAggregateCounts: ",t),null}})}filterGhostComments$(e,t,r){try{return e?this.commentService.getGhostCommentAnnotationMap$().pipe(ce(a=>{if(!a)return e;let s=this.buildGhostCommentAnnotationMap(a),c=this.groupGhostCommentsByModeId(s,t,r);return this.adjustCountsForGhostComments(e,c),e})):se(null)}catch(a){return this.loggingService.catch("Error in CommentService filterGhostComments: ",a),se(null)}}buildGhostCommentAnnotationMap(e){let t={};return Object.keys(e).forEach(r=>{let a=this.commentService.getAnnotationById(r);a&&(t[r]=a)}),t}groupGhostCommentsByModeId(e,t,r){try{let a={};return Object.values(e).forEach(s=>{let c=this.getModeIdForAnnotation(s,t,r);c&&(a[c]||(a[c]=[]),a[c].push(s))}),a}catch(a){return this.loggingService.catch("Error in CommentService groupGhostCommentsByModeId: ",a),{}}}getModeIdForAnnotation(e,t,r){try{return t.isOrgMode?e?.metadata?.clientOrganizationId||null:t.isFolderMode?e?.metadata?.folderId||null:t.isBatchMode?r.includes(e?.metadata?.documentId??"")?"result":null:e?.metadata?.clientDocumentId||null}catch(a){return this.loggingService.catch("Error in CommentService getModeIdForAnnotation: ",a),null}}adjustCountsForGhostComments(e,t){try{if(typeof e?.data!="object")return;let a=this.authService.getUser()?.userSnippylyId;Object.keys(e.data||{}).forEach(s=>{let c=t[s];if(!(!c||!e?.data?.[s]?.total)&&(e.data[s].total=Math.max(0,e.data[s].total-c.length),a)){let p=c.filter(u=>u?.viewedByUserIds&&!u?.viewedByUserIds?.includes(a));p.length>0&&(e.data[s].unread=Math.max(0,e.data[s].unread-p.length))}})}catch(r){this.loggingService.catch("Error in CommentService adjustCountsForGhostComments: ",r)}}};o.\u0275fac=function(t){return new(t||o)(ee(Ve),ee(vn),ee(at),ee(Ft),ee(pn),ee(y),ee(De))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var li=(()=>{let o=class o{constructor(e,t,r,a,s,c,p,u,C,E,D,L){this.analyticsService=e,this.authService=t,this.commentService=r,this.commentViewsService=a,this.contactService=s,this.customFilterService=c,this.docService=p,this.iamService=u,this.loggingService=C,this.metadataService=E,this.reactionService=D,this.commonDbService=L,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(z=>{this.isUserAdmin=z})}catch(z){this.loggingService.catch("Error in CommentActionsService constructor: ",z)}}addCommentAnnotation(a,s){return Q(this,arguments,function*({annotation:e,options:t},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=>Q(this,null,function*(){let u=yield this.getAddCommentAnnotationEventFromCommentAddEventData(p);c(u)}),void 0,void 0,e,void 0,void 0,void 0,void 0,void 0,r)})}catch(c){return this.loggingService.catch("Error in CommentActionsService addCommentAnnotation: ",c),null}})}publishCommentAnnotation(a,s){return Q(this,arguments,function*({annotationId:e,options:t},r){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: publishCommentAnnotation","color: green;");let c=this.commentService.getAnnotationById(e,t);if(c){let p=JSON.parse(JSON.stringify(c));p.isDraft=!1,this.commentService.saveComment(p,{type:$t.PUBLISHED}),this.analyticsService.trackEvent(Z.Events.Comments.COMMENT_PUBLISHED,{annotationId:e,commentType:this.commentService.getCommentType(p),commentMode:this.commentService.getCommentMode(),source:r??this.defaultSource});let u=yield this.metadataService.getGlobalMetadata(),C={annotationId:e,commentAnnotation:Gn(p),metadata:u};return this.triggerAction(ji.PUBLISH_COMMENT_ANNOTATION,C),C}else this.triggerAnnotationNotFoundError(e);return null}catch(c){return this.loggingService.catch("Error in CommentActionsService publishCommentAnnotation: ",c),null}})}getAddCommentAnnotationEventFromCommentAddEventData(e){return Q(this,null,function*(){try{let t=yield this.metadataService.getGlobalMetadata();return{commentAnnotation:Gn(e?.annotation),annotationId:e?.annotation?.annotationId,metadata:t,addContext:e?.addContext,elementRef:e?.elementRef}}catch(t){return this.loggingService.catch("Error in CommentActionsService getAddCommentAnnotationEventFromData: ",t),null}})}triggerAddCommentAnnotationEvent(e){try{this.triggerAction(ji.ADD_COMMENT_ANNOTATION,e)}catch(t){this.loggingService.catch("Error in CommentActionsService triggerAddCommentAnnotationEvent: ",t)}}triggerAnnotationNotFoundError(e){try{this.loggingService.catch("Annotation not found:","The annotation with the given id was not found.")}catch(t){this.loggingService.catch("Error in CommentActionsService triggerAnnotationNotFoundError: ",t)}}deleteCommentAnnotation(a,s){return Q(this,arguments,function*({annotationId:e,options:t},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,t);if(p){let u=this.authService.getUser();if(this.isUserAdmin||u?.userId===p?.from?.userId){this.commentService.deleteCommentPinAnnotation(p);let C=yield this.metadataService.getGlobalMetadata(),E={annotationId:p.annotationId,commentAnnotation:Gn(p),metadata:C};return this.triggerAction(ji.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 Q(this,arguments,function*({annotationId:e,priority:t,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 u=this.commentService.getAnnotationById(e,r);if(u){u=JSON.parse(JSON.stringify(u));let C=u.priority?JSON.parse(JSON.stringify(u.priority)):null;C&&t&&C?.id===t?.id?u.priority=void 0:u.priority=t,this.commentService.saveComment(u,{type:$t.PRIORITY_CHANGED,newPriority:t,oldPriority:C});let E=yield this.metadataService.getGlobalMetadata(),D={newPriority:t,oldPriority:C,annotationId:e,commentAnnotation:Gn(u),metadata:E};return this.triggerAction(ji.UPDATE_PRIORITY,D),this.analyticsService.trackEvent(Z.Events.Comments.COMMENT_PRIORITY_CHANGED,{annotationId:e,commentType:this.commentService.getCommentType(u),oldPriority:u.priority,newPriority:t,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 Q(this,arguments,function*({annotationId:e,status:t,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 u=this.commentService.getAnnotationById(e,r);if(u){u=JSON.parse(JSON.stringify(u));let C=u.status?JSON.parse(JSON.stringify(u.status)):null;u.status=t,this.commentService.saveComment(u,{type:$t.STATUS_CHANGED,newStatus:t,oldStatus:C});let E=yield this.metadataService.getGlobalMetadata(),D={newStatus:t,oldStatus:C,annotationId:e,commentAnnotation:Gn(u),metadata:E};return this.triggerAction(ji.UPDATE_STATUS,D),this.analyticsService.trackEvent(Z.Events.Comments.COMMENT_STATUS_CHANGED,{annotationId:e,commentType:this.commentService.getCommentType(u),oldStatus:C,newStatus:t,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 Q(this,arguments,function*({annotationId:e,accessMode:t,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 u=this.commentService.getAnnotationById(e,r);if(u)if(this.isUserAdmin){u=JSON.parse(JSON.stringify(u));let C=u.iam?.accessMode;u.iam.accessMode=t,this.commentService.saveComment(u,{type:$t.ACCESS_MODE_CHANGED,newAccessMode:t,oldAccessMode:C});let E=yield this.metadataService.getGlobalMetadata(),D={newAccessMode:t,oldAccessMode:C,annotationId:e,commentAnnotation:Gn(u),metadata:E};switch(this.triggerAction(ji.UPDATE_ACCESS,D),t){case io.PRIVATE:this.analyticsService.trackEvent(Z.Events.Comments.COMMENT_ACCESS_MODE_CHANGED,{type:io.PRIVATE,source:a??this.defaultSource});break;case io.PUBLIC:this.analyticsService.trackEvent(Z.Events.Comments.COMMENT_ACCESS_MODE_CHANGED,{type:io.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 Q(this,arguments,function*({annotationId:e,options:t}){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,t);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:$t.STATUS_CHANGED,newStatus:c,oldStatus:p}));let u=yield this.metadataService.getGlobalMetadata(),C={annotationId:e,commentAnnotation:Gn(s),metadata:u};return this.triggerAction(ji.RESOLVE_COMMENT,C),C}else this.triggerAnnotationNotFoundError(e);return null}catch(a){return this.loggingService.catch("Error in CommentActionsService resolveCommentAnnotation: ",a),null}})}getLink(a,s){return Q(this,arguments,function*({annotationId:e,options:t},r){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: getLink","color: green;");let c=this.commentService.getAnnotationById(e,t);if(c){let p=this.commentService.getCommentUrl(c)??null,u=yield this.metadataService.getGlobalMetadata();return{link:p,annotationId:e,commentAnnotation:Gn(c),metadata:u}}else this.triggerAnnotationNotFoundError(e);return null}catch(c){return this.loggingService.catch("Error in CommentActionsService getLink: ",c),null}})}copyLink(a,s){return Q(this,arguments,function*({annotationId:e,options:t},r){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: copyLink","color: green;");let c=yield this.getLink({annotationId:e,options:t},r);if(c?.link){As(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(),u={link:c.link,annotationId:e,commentAnnotation:Gn(c.commentAnnotation),metadata:p};return this.triggerAction(ji.COPY_LINK,u),u}return null}catch(c){return this.loggingService.catch("Error in CommentActionsService copyLink: ",c),null}})}addComment(p,u){return Q(this,arguments,function*({annotationId:e,comment:t,assignedTo:r,assigned:a,options:s},c){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: addComment","color: green;");let C=this.authService.getUser();if(!C)return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),null;if(C){let E=this.commentService.getAnnotationById(e,s),D=E?.comments?.length?$t.ADDED:$t.NEWLY_ADDED;if(E){E.status.type==="terminal"&&(E.status=this.customFilterService.defaultStatus);let L=new Nc;L=I(I({},L),t),L.lastUpdated=new Date,L.attachments||(L.attachments=[]),L.attachments=L.attachments.filter(J=>J?.attachmentId),L.createdAt=this.timestamp,L.from=C,r&&(E.assignedTo=r),this.commentService.saveComment(E,{type:D,updatedComment:L,assigned:a});let z=yield this.metadataService.getGlobalMetadata(),W={annotationId:e,commentId:L?.commentId,comment:L,commentAnnotation:Gn(E),metadata:z};return this.triggerAction(ji.ADD_COMMENT,W),this.analyticsService.trackEvent(Z.Events.Comments.COMMENT_ADDED,{annotationId:e,commentThreadId:t?.commentId,commentType:this.commentService.getCommentType(E),commentMode:this.commentService.getCommentMode(),source:c??this.defaultSource}),W}else this.triggerAnnotationNotFoundError(e)}return null}catch(C){return this.loggingService.catch("Error in CommentActionsService addComment: ",C),null}})}approveCommentAnnotation(a,s){return Q(this,arguments,function*({annotationId:e,options:t},r){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: approveCommentAnnotation","color: green;");let c=this.commentService.getAnnotationById(e,t);if(c){c.approved=!0,this.commentService.saveComment(c,{type:$t.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(),u={annotationId:e,commentAnnotation:Gn(c),metadata:p};return this.triggerAction(ji.APPROVE_COMMENT_ANNOTATION,u),u}else this.triggerAnnotationNotFoundError(e);return null}catch(c){return this.loggingService.catch("Error in CommentActionsService approveComment: ",c),null}})}acceptCommentAnnotation(a,s){return Q(this,arguments,function*({annotationId:e,options:t},r){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: acceptCommentAnnotation","color: green;");let c=this.commentService.getAnnotationById(e,t),p=this.authService.getUser();if(c&&p){let u=c.status?JSON.parse(JSON.stringify(c.status)):null;c.status=j.CommentAcceptStatus,this.commentService.saveComment(c,{type:$t.ACCEPTED,oldStatus:u,newStatus:j.CommentAcceptStatus});let C=yield this.metadataService.getGlobalMetadata(),E={annotationId:e,commentAnnotation:Gn(c),metadata:C,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(ji.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 Q(this,arguments,function*({annotationId:e,options:t},r){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: rejectCommentAnnotation","color: green;");let c=this.commentService.getAnnotationById(e,t),p=this.authService.getUser();if(c&&p){let u=c.status?JSON.parse(JSON.stringify(c.status)):null;c.status=j.CommentRejectStatus,this.commentService.saveComment(c,{type:$t.REJECTED,oldStatus:u,newStatus:j.CommentRejectStatus});let C=yield this.metadataService.getGlobalMetadata(),E={annotationId:e,commentAnnotation:Gn(c),metadata:C,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(ji.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 Q(this,arguments,function*({annotationId:e,options:t},r){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: toggleNotificationSubscription","color: green;");let c=this.commentService.getAnnotationById(e,t),p=this.authService.getUser();if(c&&p){let u=bt(p.userId);if(u){c.subscribedUsers||(c.subscribedUsers={}),c.unsubscribedUsers||(c.unsubscribedUsers={});let C,E=!1;if(c?.unsubscribedUsers?.[u])E=!1;else if(c?.subscribedUsers?.[u])E=!0;else{let z=this.contactService.getCurrentOrganizationUserIAM();if(z){let W=z.groups||{};Object.keys(W).forEach(J=>{c?.subscribedGroups?.[J]&&(E=!0)})}}if(r==="subscribe"||!r&&!E)delete c.unsubscribedUsers[u],c.subscribedUsers[u]={user:p,type:"manual"},C=$t.SUBSCRIBED;else if(r==="unsubscribe"||!r&&E)delete c.subscribedUsers[u],c.unsubscribedUsers[u]={user:p,type:"manual"},C=$t.UNSUBSCRIBED;else return null;this.commentService.saveComment(c,{type:C});let D=yield this.metadataService.getGlobalMetadata(),L={annotationId:e,commentAnnotation:Gn(c),metadata:D};return C===$t.SUBSCRIBED?this.triggerAction(ji.SUBSCRIBE_COMMENT_ANNOTATION,L):this.triggerAction(ji.UNSUBSCRIBE_COMMENT_ANNOTATION,L),L}}else this.triggerAnnotationNotFoundError(e);return null}catch(c){return this.loggingService.catch("Error in CommentActionsService toggleNotificationSubscription: ",c),null}})}assignUser(s,c){return Q(this,arguments,function*({annotationId:e,assignedTo:t,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 u=this.commentService.getAnnotationById(e,r);if(u){u.assignedTo=t,this.commentService.saveComment(u,{type:$t.ASSIGNED,assignedTo:t});let C=yield this.metadataService.getGlobalMetadata(),E={annotationId:e,assignedTo:t,commentAnnotation:Gn(u),metadata:C};return this.triggerAction(ji.ASSIGN_USER,E),this.analyticsService.trackEvent(Z.Events.Comments.COMMENT_ASSIGNED,{annotationId:e,commentType:this.commentService.getCommentType(u),commentMode:this.commentService.getCommentMode(),source:a??this.defaultSource,assignedToUserId:t?.userId}),E}else this.triggerAnnotationNotFoundError(e);return null}catch(p){return this.loggingService.catch("Error in CommentActionsService assignUser: ",p),null}})}getComment(r){return Q(this,arguments,function*({annotationId:e,options:t}){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: getComment","color: green;");let a=this.commentService.getAnnotationById(e,t);return a?a.comments||[]:(this.triggerAnnotationNotFoundError(e),[])}catch(a){return this.loggingService.catch("Error in CommentActionsService getComment: ",a),[]}})}updateOrDeleteComment(e,t,r,a,s){return Q(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: updateOrDeleteComment","color: green;"),t?.commentText?.trim()||t?.attachments?.length||t?.recorders?.length){let c=this.authService.getUser();if(this.isUserAdmin||c?.userId===t?.from?.userId){t.lastUpdated=new Date,t.status=$t.UPDATED,t.isEdited||(t.isEdited=!0,t.editedAt=new Date),this.commentService.saveComment(e,{type:$t.UPDATED,updatedComment:t});let p=yield this.metadataService.getGlobalMetadata(),u={annotationId:e?.annotationId,commentId:t?.commentId,comment:t,commentAnnotation:Gn(e),metadata:p};return this.triggerAction(ji.UPDATE_COMMENT,u),this.analyticsService.trackEvent(Z.Events.Comments.COMMENT_EDITED,{annotationId:e?.annotationId,commentThreadId:t?.commentId,commentType:this.commentService.getCommentType(e),commentMode:this.commentService.getCommentMode(),source:s??this.defaultSource}),u}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:t.commentId,skipDeleteThreadConfirmation:r,options:a});return null}catch(c){return this.loggingService.catch("Error in CommentActionsService updateOrDeleteComment: ",c),null}})}updateComment(p,u){return Q(this,arguments,function*({annotationId:e,comment:t,skipDeleteThreadConfirmation:r,merge:a,options:s},c){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: updateComment","color: green;");let C=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(C&&E){let D=t,L=C.comments?.find(z=>z.commentId===t.commentId);if(L){if(this.isUserAdmin||E?.userId===L?.from?.userId)return C?.status.type==="terminal"&&(C.status=this.customFilterService.defaultStatus),a&&(D=I(I({},L),t)),D.from=L.from,D.createdAt=L.createdAt,D.lastUpdated=new Date,yield this.updateOrDeleteComment(C,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(C){return this.loggingService.catch("Error in CommentActionsService updateComment: ",C),null}})}deleteComment(c,p){return Q(this,arguments,function*({annotationId:e,commentId:t,skipDeleteThreadConfirmation:r,options:a},s){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: deleteComment","color: green;");let u=this.commentService.getAnnotationById(e,a),C=this.authService.getUser();if(u){let E=u.comments?.find(D=>D?.commentId===t);if(E)if(this.isUserAdmin||C?.userId===E?.from?.userId){this.commentService.saveComment(u,{type:$t.DELETED,updatedComment:E,skipDeleteThreadConfirmation:r});let D=yield this.metadataService.getGlobalMetadata(),L={annotationId:e,commentId:t,commentAnnotation:Gn(u),comment:E,metadata:D};return this.triggerAction(ji.DELETE_COMMENT,L),L}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(u){return this.loggingService.catch("Error in CommentActionsService deleteComment: ",u),null}})}addAttachment(s,c){return Q(this,arguments,function*({annotationId:e,files:t,options:r},a){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: addAttachment","color: green;");let p=[],u=this.commentService.getAnnotationById(e,r);if(u||a==="internal"){let D=[];t.forEach(L=>{let{valid:z,file:W,maxAllowedSize:J,error:ue}=this.validateFile(L);z&&W?D.push(this.uploadFile(W,u||{}).then(ye=>({valid:z,file:W,maxAllowedSize:J,error:ue,attachment:ye||void 0}))):D.push(Promise.resolve({valid:z,file:W,maxAllowedSize:J,error:ue,attachment:void 0}))}),p=yield Promise.all(D)}else this.triggerAnnotationNotFoundError(e);let C=yield this.metadataService.getGlobalMetadata(),E={annotationId:e,commentAnnotation:u?Gn(u):void 0,attachments:p,metadata:C};return this.triggerAction(ji.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 t=100*1024*1024;(e?.type?.includes("image")||e?.type?.includes("pdf"))&&(t=15*1024*1024);let r=e.size<=t;return{valid:r,file:e,maxAllowedSize:t,maxAllowedSizeInMB:t/1024/1024,error:r?void 0:`File size should be less than ${t/1024/1024} MB`}}catch(t){return this.loggingService.catch("Error in CommentActionsService validateFile: ",t),{valid:!1,maxAllowedSize:0,maxAllowedSizeInMB:0,error:"Error in validating file"}}}deleteAttachment(s){return Q(this,arguments,function*({annotationId:e,commentId:t,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(C=>C?.commentId===t),u=c.metadata;if(p){let C=this.authService.getUser();if(this.isUserAdmin||C?.userId===p?.from?.userId){let E=p.attachments?.find(D=>D?.attachmentId===r);if(E){p.attachments=p.attachments?.filter(W=>W?.attachmentId!==r);let D={attachmentId:E.attachmentId,organizationId:u?.organizationId??null,documentId:u?.documentId??null,folderId:u?.folderId??null,commentAnnotationId:c.annotationId,apiKey:u?.apiKey??null};yield this.commentService.deleteAttachment({attachment:E,metadata:D});let L=yield this.metadataService.getGlobalMetadata(),z={attachment:E,annotationId:e,commentId:t,commentAnnotation:Gn(c),metadata:L};return this.triggerAction(ji.DELETE_ATTACHMENT,z),this.updateComment({annotationId:e,comment:p,options:a}),z}}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 Q(this,arguments,function*({annotationId:e,commentId:t,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===t)?.attachments||[]:(this.triggerAnnotationNotFoundError(e),[])}catch(s){return this.loggingService.catch("Error in CommentActionsService getAttachment: ",s),[]}})}uploadFile(e,t){return Q(this,null,function*(){try{return this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: uploadFile","color: green;"),this.commentService.uploadFile(e,t)}catch(r){return this.loggingService.catch("Error in CommentActionsService uploadFile: ",r),null}})}getRecording(a){return Q(this,arguments,function*({annotationId:e,commentId:t,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===t)?.recorders||[]:(this.triggerAnnotationNotFoundError(e),[])}catch(s){return this.loggingService.catch("Error in CommentActionsService getRecording: ",s),[]}})}deleteRecording(s){return Q(this,arguments,function*({annotationId:e,commentId:t,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(u=>u?.commentId===t);if(p){let u=this.authService.getUser();if(this.isUserAdmin||u?.userId===p?.from?.userId){let C=p.recorders?.find(E=>E?.id===r);if(C){p.recorders=p.recorders?.filter(L=>L?.id!==r);let E=yield this.metadataService.getGlobalMetadata(),D={annotationId:e,commentId:t,recording:C,commentAnnotation:Gn(c),metadata:E};return this.triggerAction(ji.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 Q(this,null,function*(){try{let t=yield this.commentService.fetchCommentAnnotations(e),r;if(t?.hasMore){let s=t?.data[t?.data?.length-1];r=yield Oj(s?.lastUpdated?.toString()??"","veltencrypttoken","veltencrypttoken")}let a=t?.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(Gn(c)),s),{});return I({data:a},t?.hasMore?{nextPageToken:r}:{})}catch(t){return this.loggingService.catch("Error in CommentActionsService fetchCommentAnnotations: ",t),{data:null}}})}toggleReaction(c,p){return Q(this,arguments,function*({annotationId:e,commentId:t,reaction:r,options:a},s){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: toggleReaction","color: green;");let u=this.commentService.getAnnotationById(e,a),C=this.authService.getUser();if(u&&C){let E=u.comments?.find(D=>D?.commentId===t);if(E){let D=yield this.reactionService.addOrUpdateReaction(r.reactionId,E?.reactionAnnotationIds||[],void 0,void 0,u?.annotationId,r.customReaction,s),L=$t.REACTION_ADDED;if(D){D?.reactions?.find(J=>J.from?.userId===C?.userId)||(L=$t.REACTION_DELETED),E.reactionAnnotationIds||(E.reactionAnnotationIds=[]),E.reactionAnnotationIds.includes(D.annotationId)||E.reactionAnnotationIds.push(D.annotationId),D?.reactions?.length||(E.reactionAnnotationIds=E.reactionAnnotationIds.filter(J=>J!==D.annotationId)),this.commentService.saveComment(u,{type:L,updatedComment:E});let z=yield this.metadataService.getGlobalMetadata(),W={annotationId:e,commentId:t,reaction:D,commentAnnotation:Gn(u),metadata:z};return s==="add"?this.triggerAction(ji.ADD_REACTION,W):s==="delete"?this.triggerAction(ji.DELETE_REACTION,W):this.triggerAction(ji.TOGGLE_REACTION,W),W}}}else this.triggerAnnotationNotFoundError(e);return null}catch(u){return this.loggingService.catch("Error in CommentActionsService toggleReaction: ",u),null}})}onComposerClick(t){return Q(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?Gn(e):void 0,metadata:r};this.triggerAction(ji.COMPOSER_CLICKED,a)}catch(r){this.loggingService.catch("Error in CommentActionsService onComposerClick: ",r)}})}autocompleteSearch(e){return Q(this,null,function*(){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: autocompleteSearch","color: green;");let t=yield this.metadataService.getGlobalMetadata();e.metadata=t,this.triggerAction(ji.AUTOCOMPLETE_SEARCH,e)}catch(t){this.loggingService.catch("Error in CommentActionsService autocompleteSearch: ",t)}})}convert(e){try{if(e?.options){let{documentId:t,organizationId:r}=this.docService.getServerId(e?.options);e.options=T(I({},e?.options),{documentId:t,organizationId:r})}return this}catch(t){return this.loggingService.catch("Error in CommentActionsService convert: ",t),this}}triggerAction(e,t){try{this.actionSubjects.has(e)||this.actionSubjects.set(e,new tt),this.actionSubjects.get(e)?.next(t)}catch(r){this.loggingService.catch("Error in CommentActionsService triggerAction: ",r)}}onAction(e){try{return this.actionSubjects.has(e)||this.actionSubjects.set(e,new tt),this.actionSubjects.get(e)?.asObservable()}catch(t){return this.loggingService.catch("Error in CommentActionsService onAction: ",t),se(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."),se({data:null});if(!e?.allDocuments&&!e?.documentIds?.length)return this.loggingService.catch("documentIds is required."),se({data:null})}return this.commentService.getAllCommentAnnotations({excludeDomChanges:!0,skipPositionCalculation:!0,query:e,addFilterCommentsOnDomCheck:!0}).pipe(ce(t=>t?t.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(t=>({data:t})))}catch(t){return this.loggingService.catch("Error in CommentActionsService getCommentAnnotation: ",t),se({data:null})}}getCommentAnnotationsCount$(e){try{return this.commentViewsService.getAnnotationsCount(e).pipe(ce(t=>t||{data:null}))}catch(t){return this.loggingService.catch("Error in CommentActionsService getCommentAnnotation: ",t),se({data:null})}}};o.\u0275fac=function(t){return new(t||o)(ee(et),ee(Ve),ee(De),ee(tde),ee(xi),ee(Zo),ee(at),ee(vn),ee(y),ee(Hd),ee(rr),ee(pn))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var I0=(()=>{let o=class o{constructor(e,t){this.httpClient=e,this.loggingService=t,this.fileContentMap$=new ve({})}getFileContent(e){try{let t=En(e);return this.fileContentMap$.value[t]?se(this.fileContentMap$.value[t]):this.httpClient.get(e,{responseType:"text"}).pipe(ce(r=>(this.fileContentMap$.next(T(I({},this.fileContentMap$.value),{[t]:r})),r)))}catch(t){return this.loggingService.catch("Error in TranscriptionService saveRecorderToDb: ",t),se(null)}}getVttFileTextToArray(e){try{let c=[],p=e.split(`
473
+ `;break}s.innerHTML=c.trim();let p=s.firstElementChild;return p&&a.appendChild(p),a.addEventListener("click",r),a.__cleanup=()=>{a.removeEventListener("click",r)},a}exitPictureInPicture(){return Q(this,null,function*(){try{if("documentPictureInPicture"in window&&(window.documentPictureInPicture.window||this.pipWindow)){this.pipWindow&&!this.pipWindow.closed&&this.pipWindow.close(),this.pipWindow=void 0,this.isPipActive$.next(!1);return}if(document.pictureInPictureElement){yield document.exitPictureInPicture(),this.isPipActive$.next(!1);return}this.isPipActive$.next(!1),this.pipWindow=void 0}catch(e){this.loggingService.catch("Error in PipService exitPictureInPicture:",e),this.isPipActive$.next(!1),this.pipWindow=void 0}})}togglePictureInPicture(e,t){return Q(this,null,function*(){try{this.isPipActive$.value||this.pipWindow||document.pictureInPictureElement?yield this.exitPictureInPicture():yield this.openPictureInPicture(e,t)}catch(r){this.loggingService.catch("Error in PipService togglePictureInPicture:",r),this.isPipActive$.next(!1),this.pipWindow=void 0}})}findVideoElement(){return Q(this,null,function*(){try{let e=['[data-testid*="velt-recorder-control-panel-video-video"]','[data-testid*="velt-recorder-control-panel-screen-screen"]','video[data-testid*="recorder"]'];for(let r of e){let a=document.querySelector(r);if(a&&a.srcObject)return a}let t=Array.from(document.querySelectorAll("video"));for(let r of t)if(r.srcObject)return r;return null}catch(e){return this.loggingService.catch("Error in PipService findVideoElement:",e),null}})}getIsPipActive$(){return this.isPipActive$.asObservable()}getIsPipActive(){return this.isPipActive$.value}getPipStopRecordingTriggered$(){return this.pipStopRecordingTriggered$.asObservable()}resetPipStopRecordingTriggered(){this.pipStopRecordingTriggered$.next(!1)}getPipPauseRecordingTriggered$(){return this.pipPauseRecordingTriggered$.asObservable()}resetPipPauseRecordingTriggered(){this.pipPauseRecordingTriggered$.next(!1)}enablePictureInPicture(){try{if(this.pictureInPicture$.value===!0)return;this.pictureInPicture$.next(!0),this.messageListener||(this.messageListener=e=>{try{if(e.origin!==window.location.origin){this.loggingService.warn("Received message from untrusted origin:",e.origin);return}if(e.source!==this.pipWindow&&e.source!==window.parent){this.loggingService.warn("Received message from untrusted source window");return}e.data?.type==="pip-stop-recording"?this.pipStopRecordingTriggered$.next(!0):e.data?.type==="pip-pause-recording"||e.data?.type==="pip-resume-recording"?this.pipPauseRecordingTriggered$.next(!0):e.data?.type==="pip-clear-recording"&&this.pipClearRecordingTriggered$.next(!0)}catch(t){this.loggingService.catch("Error in PipService enablePictureInPicture message listener:",t)}},window.addEventListener("message",this.messageListener))}catch(e){this.loggingService.catch("Error in PipService enablePictureInPicture: ",e)}}disablePictureInPicture(){try{if(this.pictureInPicture$.value===!1)return;this.pictureInPicture$.next(!1),this.messageListener&&(window.removeEventListener("message",this.messageListener),this.messageListener=void 0),this.pipStopRecordingTriggered$.next(!1),this.pipPauseRecordingTriggered$.next(!1),this.pipClearRecordingTriggered$.next(!1),this.isPipActive$.next(!1),this.pipWindow&&!this.pipWindow.closed&&this.pipWindow.close(),this.pipWindow=void 0}catch(e){this.loggingService.catch("Error in PipService disablePictureInPicture: ",e)}}getPictureInPicture$(){return this.pictureInPicture$.asObservable()}isPictureInPictureEnabled(){try{let e=new zn;return this.pictureInPicture$.value&&e.getBrowserName()==="Chrome"}catch(e){return this.loggingService.catch("Error in PipService isPictureInPictureEnabled: ",e),!1}}};o.\u0275fac=function(t){return new(t||o)(ee(y))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var bn=(()=>{let o=class o{constructor(e,t,r,a,s,c,p,u){this.analyticsService=e,this.loggingService=t,this.matDialog=r,this.storageService=a,this.docService=s,this.databaseService=c,this.domService=p,this.pipService=u,this.recorderStatusSubject$=new ve(null),this.recorderDurationSubject$=new ve(null),this.darkMode$=new ve(null),this.shadowDom$=new ve(null),this.recordingDurations=[],this.chunks=[],this.recordingCountdownEnabled$=new ve(!0),this.recorderInitData$=new tt,this.recordedRawData$=new tt,this.recordedData$=new tt,this.onInitRecording$=new ve(null),this.onRecordingAttributeRemovedFromBodySubject$=new tt,this.videoEditor$=new ve(!1),this.settingsEmbedded$=new ve(!1),this.autoOpenVideoEditor$=new ve(!1),this.playVideoInFullScreen$=new ve(void 0),this.recordedDataStream=[],this.documentPaths=null,this.uploadPromises=[],this.chunkUrls$=new ve({}),this.recordingQualityConstraints=new ve({safari:{audio:{sampleRate:48e3,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0},video:{width:{min:640,ideal:1280,max:1280},height:{min:360,ideal:720,max:720},frameRate:{min:15,ideal:20,max:30},aspectRatio:{ideal:1.777777778}}},other:{audio:{sampleRate:48e3,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0},video:{width:{min:640,ideal:1280,max:1280},height:{min:360,ideal:720,max:720},frameRate:{min:15,ideal:20,max:30},aspectRatio:{ideal:1.777777778}}}}),this.recordingEncodingOptions=new ve({safari:{videoBitsPerSecond:25e5,audioBitsPerSecond:128e3},other:{videoBitsPerSecond:1e6,audioBitsPerSecond:128e3}}),this.recordingMicEnabled$=new ve(null),this.onboardingTooltip$=new ve(!1),this.retakeOnVideoEditor$=new ve(!1),this.maxRecordingLength=null,this.screenStreamSubject$=new ve(null),this.onInitRecording$.subscribe(C=>{C?this.setRecordingAttributeAtBody():this.removeRecordingAttributeFromBody()}),this.pipService.getPipPauseRecordingTriggered$().subscribe(C=>{C&&(this.recorderStatusSubject$.value==="started"||this.recorderStatusSubject$.value==="resumed"?this.pauseRecording():this.recorderStatusSubject$.value==="paused"&&this.resumeRecording(),this.pipService.resetPipPauseRecordingTriggered())}),this.databaseService.getDb().pipe(Le(C=>!!C),st(1)).subscribe(C=>{C&&this.getDocumentPaths()},C=>{this.loggingService.catch("Error in RecorderAnnotationService getDb subscription: ",C)})}getDocumentPaths(){this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentPaths","color: green;");try{this.docService.getDocumentPaths$().pipe(dn(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(j.ATTRIBUTES.VELT_ONGOING_RECORDING,e.type),e?.isCommentRecording&&document.body.setAttribute(j.ATTRIBUTES.VELT_COMMENT_RECORDING,"true"))}catch(e){this.loggingService.catch("Error in RecorderService setRecordingAttributeAtBody: ",e)}}removeRecordingAttributeFromBody(){try{document.body.removeAttribute(j.ATTRIBUTES.VELT_ONGOING_RECORDING),document.body.removeAttribute(j.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,t,r,a,s,c,p,u,C){return Q(this,null,function*(){try{let E={};switch(e){case"audio":E.audio={enabled:!0};break;case"video":E.video={enabled:!0},E.audio={enabled:!0};break;case"screen":E.screen={enabled:!0,stream:C},E.video={enabled:!1},E.audio={enabled:!1};break;default:break}C&&e==="screen"&&(E.screen={enabled:!0,stream:C}),this.matDialog.open(Bk,{panelClass:"velt-mat-dialog-container",data:{type:e,mediaConfig:E,darkMode:[!0,!1].includes(a)?a:this.darkMode$.value,shadowDom:s,recordingCountdown:u}}).afterClosed().subscribe(D=>{if(D){let L={};switch(e){case"audio":L.audio={enabled:!0,deviceId:D.audio?.deviceId},L.audio=D.audio;break;case"video":L.video={enabled:!0,deviceId:D.video?.deviceId},L.audio={enabled:!0,deviceId:D.audio?.deviceId},L.video=D.video,L.audio=D.audio;break;case"screen":L.screen={enabled:!0},L.audio=D.audio,L.video=D.video,L.screen=D.screen;break;default:break}this.onInitRecording$.next({type:e,panelId:t,mediaConfig:L,isCommentRecording:r,darkMode:[!0,!1].includes(a)?a:!!this.darkMode$.value,shadowDom:s,commentAnnotationId:c,clientDocumentId:p})}},D=>{this.loggingService.catch("Error in RecorderService initRecording afterClosed: ",D)})}catch(E){this.loggingService.catch("Error in RecorderService initRecording: ",E)}})}startRecording(e,t){return Q(this,null,function*(){try{this.loggingService.log("[startRecording] Starting with config:",e,"mediaConfig:",t);let r=new MediaStream,a=yield this.getBrowserSpecificOptions();return yield this.collectMediaTracks(r,e,t),yield this.initializeMediaRecorder(r,a,e),this.setupRecorderData(e,r),r}catch(r){return this.loggingService.catch("Error in RecorderService startRecording: ",r),Promise.reject(r)}})}getBrowserSpecificOptions(){return Q(this,null,function*(){try{let e={videoBitsPerSecond:this.recordingEncodingOptions.value[this.isSafari()?"safari":"other"]?.videoBitsPerSecond,audioBitsPerSecond:this.recordingEncodingOptions.value[this.isSafari()?"safari":"other"]?.audioBitsPerSecond},t=this.getSupportedMimeTypes();if(t.length>0){let a=t.find(s=>s.includes("mp4")&&s.includes("h264"))||t.find(s=>s.includes("mp4"))||t[0];e.mimeType=a}return new zn().getBrowserName()==="Firefox"&&(t.includes("video/webm")&&(e.mimeType="video/webm"),e.videoBitsPerSecond=Math.min(e.videoBitsPerSecond||1e6,2e6),e.audioBitsPerSecond=Math.min(e.audioBitsPerSecond||128e3,256e3)),e}catch(e){return this.loggingService.catch("Error in RecorderService getBrowserSpecificOptions: ",e),{}}})}collectMediaTracks(e,t,r){return Q(this,null,function*(){try{if(t.type.screen&&r?.screen?.stream){let a=this.getCommonVideoQualityConstraints(!0);r.screen.stream.getTracks().forEach(s=>{e.addTrack(s),s.onended=()=>this.stopRecording(),s.applyConstraints(I({},a))})}if(t?.type.audio||t?.type.video)if(this.isFirefox()&&t.type.screen&&(r?.audio?.stream||r?.video?.stream)){let s=new Set;t.type.audio&&r?.audio?.stream&&r.audio.stream.getAudioTracks().forEach(c=>{s.has(c)||(e.addTrack(c),s.add(c))}),t.type.video&&r?.video?.stream&&r.video.stream.getVideoTracks().forEach(c=>{s.has(c)||(e.addTrack(c),s.add(c))})}else{let s=this.buildMediaConstraints(t,r),c=yield navigator.mediaDevices.getUserMedia(s);if(c)if(this.isSafari()){if(t?.type.audio&&(yield this.adjustSafariAudioTrack(e,c)),t?.type.video){let p=c.getVideoTracks();if(p.length>0){let u=p[0];u.enabled=!0;let C=u.clone();e.addTrack(C),r&&r.video&&(r.video.track=u)}}}else c.getTracks().forEach(p=>e.addTrack(p))}}catch(a){this.loggingService.catch("Error in RecorderService collectMediaTracks: ",a);return}})}buildMediaConstraints(e,t){try{let r=this.getCommonVideoQualityConstraints(!!e.type.video);return{audio:this.getCommonAudioConstraints(!!e.type.audio,t),video:e.type.video?T(I({deviceId:t?.video?.deviceId?{ideal:t.video.deviceId}:void 0},r),{facingMode:"user"}):!1}}catch(r){return this.loggingService.catch("Error in RecorderService buildMediaConstraints: ",r),{}}}getCommonAudioConstraints(e,t){try{if(!e)return!1;let r=this.recordingQualityConstraints.value[this.isSafari()?"safari":"other"]?.audio||{};return I({deviceId:t?.audio?.deviceId?{ideal:t.audio.deviceId}:void 0},r)}catch(r){return this.loggingService.catch("Error in RecorderService getCommonAudioConstraints: ",r),{}}}getCommonVideoQualityConstraints(e){try{return e?this.recordingQualityConstraints.value[this.isSafari()?"safari":"other"]?.video||{}:{}}catch(t){return this.loggingService.catch("Error in RecorderService getCommonVideoQualityConstraints: ",t),{}}}adjustSafariAudioTrack(e,t){return Q(this,null,function*(){try{let r=t.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,t,r){return Q(this,null,function*(){try{if(e.getTracks().length===0)throw new Error("MediaStream has no tracks");this.mediaRecorder=new MediaRecorder(e,t),this.chunks=[],this.chunkUrls$.next({}),this.uploadPromises=[];let a=0;if(this.isSafari()){let u=e.getVideoTracks();u.length>0&&u.forEach(C=>{C.contentHint="detail",C.enabled=!0})}let c=new zn().getBrowserName()==="Firefox";c&&e.getTracks().forEach(u=>{u.enabled=!0}),this.mediaRecorder.addEventListener("dataavailable",u=>{if(u.data?.size>0){let C=a++;this.chunks.push(u.data);let E=`recording_${new Date().getTime()}_${Math.random().toString(36).substring(2,9)}`,D=u.data,L=this.uploadChunk(D,E,C);this.uploadPromises||(this.uploadPromises=[]),this.uploadPromises.push({promise:L,index:C}),L.then(z=>{this.chunkUrls$.next(T(I({},this.chunkUrls$.value),{[C]:z}))}).catch(z=>{})}}),this.mediaRecorder.addEventListener("stop",()=>{c&&this.chunks.length===0&&this.attemptFirefoxCanvasRecording(e),this.onStopRecording()}),this.mediaRecorder.addEventListener("error",u=>{this.loggingService.catch("MediaRecorder error event:",u)});let p=4e3;c&&r.type.screen&&(p=void 0),p?this.mediaRecorder.start(p):this.mediaRecorder.start(),c&&setTimeout(()=>{if(this.chunks.length===0&&this.mediaRecorder.state==="recording")try{this.mediaRecorder.requestData&&this.mediaRecorder.requestData()}catch{}},2e3)}catch(a){throw this.loggingService.catch("Error in RecorderService initializeMediaRecorder: ",a),a}})}uploadChunk(e,t,r){return Q(this,null,function*(){try{let s=this.mediaRecorder.mimeType||"video/mp4",c=s.includes("webm")?"webm":"mp4",p=`chunk_${r}_${new Date().getTime()}.${c}`,u=new File([e],p,{type:s});return yield this.uploadChunkToStorage(u,t,r)}catch(a){throw a}})}uploadChunkToStorage(e,t,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=`${j.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${j.FIREBASE_PARTIAL_PATH_RECORDER}/${t}`;return a&&(c=`${j.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${a}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${j.FIREBASE_PARTIAL_PATH_RECORDER}/${t}`),this.storageService.uploadChunk(c,e,r)}catch(a){throw this.loggingService.catch("Error in RecorderService uploadChunkToStorage: ",a),a}}setupRecorderData(e,t){try{return this.recorderInitData=new _k,this.recorderStatusSubject$.next("started"),this.isSafari()&&e.type.video&&t.getVideoTracks().forEach(r=>{r.enabled=!0}),this.recorderInitData.stream=t,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.recorderActionsService?.onRecordingStarted(this.getRecorderDataFromInitData()),this.pipService.getIsPipActive()&&window.postMessage({type:"recording-status-update",status:"started"},"*"),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(t){return this.loggingService.catch("Error in RecorderService determineRecorderType: ",t),"audio"}}timeout(e){return new Promise(t=>setTimeout(t,e))}pauseRecording(){try{if(this.recorderStatusSubject$.next("paused"),this.mediaRecorder.pause(),this.firefoxFallbackRecorder?.state==="recording")try{this.firefoxFallbackRecorder.pause()}catch(e){this.loggingService.catch("Error pausing Firefox fallback recorder: ",e)}this.recordingDurations?.length&&(this.recordingDurations[this.recordingDurations.length-1].end=new Date().getTime()),this.stopTimer(),this.recorderActionsService?.onRecordingPaused(this.getRecorderDataFromInitData()),this.pipService.getIsPipActive()&&window.postMessage({type:"recording-status-update",status:"paused",recordingType:this.recorderInitData?.type||"video"},window.location.origin)}catch(e){this.loggingService.catch("Error in RecorderService pauseRecording: ",e)}}resumeRecording(){try{if(this.recorderStatusSubject$.next("resumed"),this.mediaRecorder.resume(),this.firefoxFallbackRecorder?.state==="paused")try{this.firefoxFallbackRecorder.resume()}catch(e){this.loggingService.catch("Error resuming Firefox fallback recorder: ",e)}this.recordingDurations.push({start:new Date().getTime()}),this.startTimer(),this.recorderActionsService?.onRecordingResumed(this.getRecorderDataFromInitData()),this.pipService.getIsPipActive()&&window.postMessage({type:"recording-status-update",status:"started",recordingType:this.recorderInitData?.type||"video"},"*")}catch(e){this.loggingService.catch("Error in RecorderService resumeRecording: ",e)}}stopRecording(){try{if(this.mediaRecorder?.state!=="inactive"?(this.mediaRecorder.stop(),this.removeRecordingAttributeFromBody()):this.clearRecording(),this.firefoxFallbackRecorder?.state==="recording")try{this.firefoxFallbackRecorder.stop()}catch(e){this.loggingService.catch("Error stopping Firefox fallback recorder: ",e)}this.recorderActionsService?.onRecordingStopped(this.getRecorderDataFromInitData())}catch(e){this.loggingService.catch("Error in RecorderService stopRecording: ",e)}}onStopRecording(){return Q(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(r=>{r.stop()}),yield this.timeout(100);let t=new Sb;if(this.chunks.length>0){let r=this.recorderInitData?.type==="audio"?"audio/mp4":"video/mp4";this.loggingService.log("[onStopRecording] Creating blob with type:",r),t.blob=new Blob(this.chunks,{type:r}),this.loggingService.log("[onStopRecording] Blob created, size:",t.blob.size);try{let a=yield this.getVideoDuration(t.blob);if(a&&isFinite(a)&&a>0){let s={};s.duration=a*1e3,s.display=this.convertMillisecondsToTime(a*1e3),this.recorderDurationSubject$.next(s),t.recordedTime=s}else{let s=this.recorderDurationSubject$.value;t.recordedTime=s}}catch(a){let s=this.recorderDurationSubject$.value;t.recordedTime=s,this.recorderInitData&&this.loggingService.catch("Error in RecorderService onStopRecording getVideoDuration: ",a)}if(t.blob.size===0)throw new Error("Recorded blob has zero size");if(t.url=URL.createObjectURL(t.blob),t.type=this.recorderInitData?.type,t.recordedTime=this.recorderDurationSubject$.value,t?.type!=="audio")try{yield this.timeout(200);let a=yield iae(t.blob,3);a&&(t.thumbnail=yield oae(a))}catch(a){this.recorderInitData&&this.loggingService.catch("Error in RecorderService onStopRecording getVideoCover: ",a)}this.recordedRawData$.next(t)}else throw new Error("No data chunks recorded")}catch(e){this.loggingService.catch("Error in RecorderService onStopRecording: ",e),this.recordedRawData$.error(e)}})}clearRecording(e){return Q(this,null,function*(){try{if(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.firefoxFallbackRecorder){try{this.firefoxFallbackRecorder.state==="recording"&&this.firefoxFallbackRecorder.stop()}catch(t){this.loggingService.catch("Error stopping Firefox fallback recorder during cleanup: ",t)}this.firefoxFallbackRecorder=void 0}this.recorderInitData?.stream?.getTracks()?.forEach(t=>{t.stop()}),e?.triggerEvent==="cancelled"&&this.recorderActionsService?.onRecordingCancelled(this.getRecorderDataFromInitData()),this.recorderInitData=null,this.recorderInitData$.next(null),this.chunks=[],this.chunkUrls$.next({}),this.stopTimer()}catch(t){this.loggingService.catch("Error in RecorderService clearRecording: ",t)}})}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(r=>{r.end?e+=r?.end-r.start:e+=new Date().getTime()-r.start});let t={};t.duration=e,t.display=this.convertMillisecondsToTime(e),this.recorderDurationSubject$.next(t),this.pipService.getIsPipActive()&&window.postMessage({type:"recording-timer-update",display:t.display},"*")}else this.recorderDurationSubject$.next(null)}catch(e){this.loggingService.catch("Error in RecorderService calculateRecordedTime: ",e)}}checkMaxLength(){try{if(!this.maxRecordingLength||!this.recordingDurations?.length)return!1;let e=0;this.recordingDurations.forEach(r=>{r.end?e+=r?.end-r.start:e+=new Date().getTime()-r.start});let t=e>=this.maxRecordingLength*1e3+500;return t&&this.loggingService.log("%c[WB] Max recording length reached. Duration: "+e+"ms, Target: "+this.maxRecordingLength+"s","color: orange;"),t}catch(e){return this.loggingService.catch("Error in RecorderService checkMaxLength: ",e),!1}}convertMillisecondsToTime(e){try{let t=Math.floor(e/1e3),r=Math.floor(t/60),a=Math.floor(r/60);return t=t%60,r=r%60,`${a.toString().padStart(2,"0")}:${r.toString().padStart(2,"0")}:${t.toString().padStart(2,"0")}`}catch(t){return this.loggingService.catch("Error in RecorderService convertMillisecondsToTime: ",t),""}}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}}isFirefox(){try{return new zn().getBrowserName()==="Firefox"}catch(e){return this.loggingService.catch("Error in RecorderService isFirefox: ",e),!1}}getSupportedMimeTypes(){try{return["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;codecs=vp9","video/webm;codecs=vp8","video/webm","audio/webm;codecs=opus","audio/webm"].filter(r=>MediaRecorder.isTypeSupported(r))}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 Q(this,null,function*(){try{if(this.uploadPromises.length===0)return{};let e=this.uploadPromises.map(t=>t.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(t){this.loggingService.catch("Error in RecorderAnnotationService setRecorderActionsService: ",t)}}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}setRecordingQualityConstraints(e){try{let t=this.recordingQualityConstraints.value;t={other:{audio:I(I({},t.other?.audio),e.other?.audio),video:I(I({},t.other?.video),e.other?.video)},safari:{audio:I(I({},t.safari?.audio),e.safari?.audio),video:I(I({},t.safari?.video),e.safari?.video)}},this.recordingQualityConstraints.next(t)}catch(t){this.loggingService.catch("Error in RecorderService setRecordingQualityConstraints: ",t)}}setRecordingEncodingOptions(e){try{let t=this.recordingEncodingOptions.value;t={other:I(I({},t.other),e.other),safari:I(I({},t.safari),e.safari)},this.recordingEncodingOptions.next(t)}catch(t){this.loggingService.catch("Error in RecorderService setRecordingEncodingOptions: ",t)}}getVideoDuration(e){return Q(this,null,function*(){return new Promise((t,r)=>{try{let a=URL.createObjectURL(e),s=document.createElement("video"),c=navigator.userAgent.includes("Firefox");c&&(s.preload="auto"),s.onloadedmetadata=()=>{let p=s.duration;c&&p>0&&p<10&&e.size>1e6?setTimeout(()=>{let u=s.duration;URL.revokeObjectURL(a),t(u)},1e3):(URL.revokeObjectURL(a),t(p))},s.onerror=p=>{URL.revokeObjectURL(a),r(p)},s.src=a,s.load()}catch(a){this.loggingService.catch("Error in RecorderService getVideoDuration: ",a),r(a)}})})}enableRecordingMic(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableRecordingMic","color: green;"),this.recordingMicEnabled$.value===!0)return;this.recordingMicEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in RecorderService enableRecordingMic: ",e)}}disableRecordingMic(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableRecordingMic","color: green;"),this.recordingMicEnabled$.value===!1)return;this.recordingMicEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in RecorderService disableRecordingMic: ",e)}}getRecordingMicEnabled$(){return this.recordingMicEnabled$.asObservable()}getRecordingMicEnabled(){return this.recordingMicEnabled$.value}setOnboardingTooltip(e){try{if(this.onboardingTooltip$.value===e)return;this.onboardingTooltip$.next(e)}catch(t){this.loggingService.catch("Error in RecorderService setOnboardingTooltip: ",t)}}enableOnboardingTooltip(){try{if(this.onboardingTooltip$.value===!0)return;this.onboardingTooltip$.next(!0)}catch(e){this.loggingService.catch("Error in RecorderService enableOnboardingTooltip: ",e)}}disableOnboardingTooltip(){try{if(this.onboardingTooltip$.value===!1)return;this.onboardingTooltip$.next(!1)}catch(e){this.loggingService.catch("Error in RecorderService disableOnboardingTooltip: ",e)}}getOnboardingTooltip$(){return this.onboardingTooltip$.asObservable()}getOnboardingTooltip(){return this.onboardingTooltip$.value}enableRetakeOnVideoEditor(){try{if(this.retakeOnVideoEditor$.value===!0)return;this.retakeOnVideoEditor$.next(!0)}catch(e){this.loggingService.catch("Error in RecorderService enableRetakeOnVideoEditor: ",e)}}disableRetakeOnVideoEditor(){try{if(this.retakeOnVideoEditor$.value===!1)return;this.retakeOnVideoEditor$.next(!1)}catch(e){this.loggingService.catch("Error in RecorderService disableRetakeOnVideoEditor: ",e)}}getRetakeOnVideoEditor$(){return this.retakeOnVideoEditor$.asObservable()}getRetakeOnVideoEditor(){return this.retakeOnVideoEditor$.value}getRecorderStream(){return this.recorderInitData?.stream}getScreenStream$(){return this.screenStreamSubject$.asObservable()}requestScreenPermission(){return Q(this,null,function*(){try{if(!navigator.mediaDevices||!navigator.mediaDevices.getDisplayMedia)throw new Error("Screen sharing is not supported in this browser");let e=yield navigator.mediaDevices.getDisplayMedia({video:!0});if(!e.getVideoTracks()[0])throw new Error("No video track available in screen share stream");return e.getTracks().forEach(r=>{r.onended=()=>{this.screenStreamSubject$.next(null),this.clearRecording()}}),this.screenStreamSubject$.next(e),e}catch(e){return e.name==="NotAllowedError"||e.name==="PermissionDeniedError"?this.loggingService.catch("Screen sharing permission denied by user"):e.name==="NotFoundError"?this.loggingService.catch("No screen sharing device found"):e.name==="NotReadableError"||e.name==="OverconstrainedError"?this.loggingService.catch("Could not access screen sharing device"):this.loggingService.catch("Error in RecorderService requestScreenPermission: ",e),null}})}setMaxRecordingLength(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setMaxRecordingLength","color: green;"),this.maxRecordingLength=e}catch(t){this.loggingService.catch("Error in RecorderService setMaxRecordingLength: ",t)}}getMaxRecordingLength(){return this.maxRecordingLength}attemptFirefoxCanvasRecording(e){return Q(this,null,function*(){try{let t=document.createElement("video");t.srcObject=e,t.muted=!0,t.autoplay=!0;let r=document.createElement("canvas"),a=r.getContext("2d");yield new Promise(u=>{t.onloadedmetadata=u}),r.width=t.videoWidth||1280,r.height=t.videoHeight||720;let s=r.captureStream(30);this.firefoxFallbackRecorder=new MediaRecorder(s,{mimeType:"video/webm;codecs=vp8",videoBitsPerSecond:this.recordingEncodingOptions.value.other?.videoBitsPerSecond||1e6});let c=[];this.firefoxFallbackRecorder.addEventListener("dataavailable",u=>{u.data.size>0&&c.push(u.data)}),this.firefoxFallbackRecorder.addEventListener("stop",()=>{if(c.length>0){let u=new Blob(c,{type:"video/webm"});this.chunks=c;let C=new Sb;C.blob=u,C.url=URL.createObjectURL(u),C.type=this.recorderInitData?.type,C.recordedTime=this.recorderDurationSubject$.value,this.recordedRawData$.next(C)}this.firefoxFallbackRecorder=void 0});let p=()=>{t.readyState>=2&&a&&a.drawImage(t,0,0,r.width,r.height),t.srcObject&&this.firefoxFallbackRecorder?.state==="recording"&&requestAnimationFrame(p)};this.firefoxFallbackRecorder.start(1e3),p()}catch(t){this.loggingService.catch("Error in RecorderService attemptFirefoxCanvasRecording: ",t)}})}getRecorderDataFromInitData(){return{type:this.recorderInitData?.type}}askDevicePermission(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: askDevicePermission","color: green;"),navigator.mediaDevices.getUserMedia({audio:e.audio??!1,video:e.video??!1}).then(t=>{t.getTracks().forEach(r=>{r.stop()})}).catch(t=>{this.loggingService.catch("Error in RecorderService askDevicePermission: ",t)})}catch(t){this.loggingService.catch("Error in RecorderService askDevicePermission: ",t)}}openPictureInPicture(){return Q(this,null,function*(){try{this.loggingService.log("%c[WB] Calling FUNCTION: openPictureInPicture","color: green;");let e=this.getRecorderStream();if(!e)return;yield this.pipService.openPictureInPicture(e,()=>this.stopRecording())}catch(e){this.loggingService.catch("Error in RecorderService openPictureInPicture: ",e)}})}};o.\u0275fac=function(t){return new(t||o)(ee(et),ee(y),ee(no),ee(sg),ee(at),ee(Dn),ee(Be),ee($a))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var y0=(()=>{let o=class o{constructor(e,t,r,a,s){this.authService=e,this.docService=t,this.loggingService=r,this.commonDbService=a,this.usersService=s,this.currentUserPermissions$=new ve(null);try{this.docService.setUserPermissionService(this)}catch(c){this.loggingService.catch("Error in UserPermissionService constructor:",c)}}organizationDetails(e){return Q(this,null,function*(){try{let t=yield this.commonDbService?.getData({feature:"organizationMetadata",properties:{organizationId:e}});return t&&t?.errorCode?{errorCode:wr.PERMISSION_DENIED,error:!0}:t&&!t?.metadata?{errorCode:wr.DOES_NOT_EXIST,error:!0}:{error:!1}}catch(t){return this.loggingService.catch("Error in UserPermissionService organizationDetails:",t),{errorCode:wr.SOMETHING_WENT_WRONG,error:!0}}})}documentDetails(r){return Q(this,arguments,function*({documentId:e,organizationId:t}){try{let a=yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:e,organizationId:t}});return a&&a?.errorCode?{errorCode:wr.PERMISSION_DENIED,error:!0}:a&&!a?.metadata?{errorCode:wr.DOES_NOT_EXIST,error:!0}:{error:!1}}catch(a){return this.loggingService.catch("Error in UserPermissionService documentDetails:",a),{errorCode:wr.SOMETHING_WENT_WRONG,error:!0}}})}folderDetails(r){return Q(this,arguments,function*({folderId:e,organizationId:t}){try{let a=yield this.commonDbService?.getData({feature:"folderMetadata",properties:{folderId:e,organizationId:t}});return a&&a?.errorCode?{errorCode:wr.PERMISSION_DENIED,error:!0}:a&&!a?.metadata?{errorCode:wr.DOES_NOT_EXIST,error:!0}:{error:!1}}catch(a){return this.loggingService.catch("Error in UserPermissionService folderDetails:",a),{errorCode:wr.SOMETHING_WENT_WRONG,error:!0}}})}getUserPermissions(e){return Q(this,null,function*(){try{let t=this.extractResourceIds(e);if(!t.clientOrganizationId||!t.organizationId)return{};let r=yield this.validateResources(t),[a,s]=yield this.fetchUserPermissionsFromDB(t),c=this.buildPermissionsResponse(t,r,a,s);return!e&&Object.keys(c).length>0&&this.setCurrentUserPermissions(c),c}catch(t){return this.loggingService.catch("Error in UserPermissionService getUserPermissions:",t),{}}})}extractResourceIds(e){let t=this.docService.getDocumentPaths(),r=this.docService.getDocumentIds();return{folderIds:e?.folderIds?.length?e.folderIds:t?.folderId?[t.folderId]:[],documentIds:e?.documentIds?.length?e.documentIds:r.map(a=>a.clientDocumentId),clientOrganizationId:e?.organizationId??t?.clientOrganizationId,organizationId:e?.organizationId??t?.clientOrganizationId?La(e?.organizationId??t?.clientOrganizationId??""):void 0}}validateResources(e){return Q(this,null,function*(){let{folderIds:t,documentIds:r,organizationId:a,clientOrganizationId:s}=e,c=[],p=[];a&&(c.push(this.organizationDetails(a)),p.push({id:s??"",type:"organization"})),t.forEach(C=>{c.push(this.folderDetails({folderId:Fi(C),organizationId:a??""})),p.push({id:C,type:"folder"})}),r.forEach(C=>{c.push(this.documentDetails({documentId:na(C),organizationId:a??""})),p.push({id:C,type:"document"})});let u=yield Promise.allSettled(c);return this.processValidationResults(u,p)})}processValidationResults(e,t){let r=[],a=[],s,c=e.map((p,u)=>({result:p,metadata:t[u]})).filter(({result:p})=>p.status==="rejected"||p.status==="fulfilled"&&p.value.error);for(let{result:p,metadata:u}of c){let C=p.status==="fulfilled"?p.value.errorCode??wr.SOMETHING_WENT_WRONG:wr.SOMETHING_WENT_WRONG,E={id:u.id,errorCode:C};switch(u.type){case"organization":if(s=E,C===wr.DOES_NOT_EXIST)throw new Error(`Organization with id '${u.id}' does not exist`);break;case"folder":r.push(E);break;case"document":a.push(E);break}}return{failedFolderIds:r,failedDocumentIds:a,failedOrganizationId:s}}fetchUserPermissionsFromDB(e){return Q(this,null,function*(){let{folderIds:t,documentIds:r,organizationId:a}=e,s=[this.authService.getUser()?.userId??""],c=[...t.map(C=>Fi(C)),...r.map(C=>na(C)),a??""],[p,u]=yield Promise.allSettled([this.usersService.getUsersFromDBWithBatching({userIds:s,organizationId:a}),this.usersService.getTemporaryUsersFromDBWithBatching({userIds:s,organizationId:a,resourceIds:c})]);return[p.status==="fulfilled"?p.value:[],u.status==="fulfilled"?u.value:[]]})}buildPermissionsResponse(e,t,r,a){let{folderIds:s,documentIds:c,clientOrganizationId:p,organizationId:u}=e,{failedFolderIds:C,failedDocumentIds:E,failedOrganizationId:D}=t,L={};return this.processRegularUserPermissions(L,r,s,c,p??"",u??"",C,E,D),this.processTemporaryUserPermissions(L,a),L}processRegularUserPermissions(e,t,r,a,s,c,p,u,C){for(let E of t)for(let D of E)D?.user?.userId&&(e[D.user.userId]=T(I({},r.length&&{folders:this.buildFolderPermissions(r,D,p)}),{documents:this.buildDocumentPermissions(a,D,u),organization:{[s]:this.buildOrganizationPermission(c,D,C)}}))}getErrorMessage(e,t){try{switch(this.loggingService.log(`Error in UserPermissionService getErrorMessage: ${e} ${t}`),e){case wr.DOES_NOT_EXIST:return`${t} does not exist`;case wr.PERMISSION_DENIED:return`User does not have access to ${t}`;case wr.SOMETHING_WENT_WRONG:return"Something went wrong";default:return"Something went wrong"}}catch(r){return this.loggingService.catch("Error in UserPermissionService getErrorMessage:",r),"Something went wrong"}}buildFolderPermissions(e,t,r){return e.reduce((a,s)=>{let c=r.find(p=>p.id===s);return c?a[s]={error:this.getErrorMessage(c.errorCode,"folder"),errorCode:c.errorCode}:a[s]={accessRole:t.viewerFolderIds?.includes(Fi(s))?ks.VIEWER:ks.EDITOR},a},{})}buildDocumentPermissions(e,t,r){return e.reduce((a,s)=>{let c=r.find(p=>p.id===s);return c?a[s]={error:this.getErrorMessage(c.errorCode,"document"),errorCode:c.errorCode}:a[s]={accessRole:t.viewerDocumentIds?.includes(na(s))?ks.VIEWER:ks.EDITOR},a},{})}buildOrganizationPermission(e,t,r){return r?{error:this.getErrorMessage(r.errorCode,"organization"),errorCode:r.errorCode}:{accessRole:t.viewerOrganizationIds?.includes(e)?ks.VIEWER:ks.EDITOR}}processTemporaryUserPermissions(e,t){for(let r of t)if(r?.userId)switch(this.ensureUserPermissionStructure(e,r.userId),r.type){case"folder":this.addTemporaryFolderPermission(e,r);break;case"document":this.addTemporaryDocumentPermission(e,r);break;case"organization":this.addTemporaryOrganizationPermission(e,r);break}}ensureUserPermissionStructure(e,t){e[t]||(e[t]={})}addTemporaryFolderPermission(e,t){let{userId:r,resourceId:a,role:s,expiresAt:c}=t;e[r].folders||(e[r].folders={}),e[r].folders[a]||(e[r].folders[a]={accessRole:s??ks.EDITOR,expiresAt:c})}addTemporaryDocumentPermission(e,t){let{userId:r,resourceId:a,role:s,expiresAt:c}=t;e[r].documents||(e[r].documents={}),e[r].documents[a]={accessRole:s??ks.EDITOR,expiresAt:c}}addTemporaryOrganizationPermission(e,t){let{userId:r,resourceId:a,role:s,expiresAt:c}=t;e[r].organization||(e[r].organization={}),e[r].organization[a]={accessRole:s??ks.EDITOR,expiresAt:c}}hasEditAccess({organizationId:e,folderId:t,documentId:r}){try{let a=!0,s=this.getCurrentUserPermissionsWithServerIds(),c=this.authService.getUser()?.userId??"";return s&&(e&&typeof e=="string"&&s?.[c]?.organization?.[e]&&(s?.[c]?.organization?.[e]?.accessRole===ks.VIEWER||s?.[c]?.organization?.[e]?.errorCode===wr.PERMISSION_DENIED)&&(a=!1),t&&typeof t=="string"&&s?.[c]?.folders?.[t]&&(s?.[c]?.folders?.[t]?.accessRole===ks.VIEWER||s?.[c]?.folders?.[t]?.errorCode===wr.PERMISSION_DENIED)&&(a=!1),r&&typeof r=="string"&&s?.[c]?.documents?.[r]&&(s?.[c]?.documents?.[r]?.accessRole===ks.VIEWER||s?.[c]?.documents?.[r]?.errorCode===wr.PERMISSION_DENIED)&&(a=!1)),a}catch{return!0}}getCurrentUserPermissions$(){return this.currentUserPermissions$.asObservable().pipe(Et(mn))}refactorPermissionsWithServerIds(e){try{let t=JSON.parse(JSON.stringify(e??{})),r=this.authService.getUser()?.userId??"";if(t?.[r]){let a=this.docService.getDocumentPaths()?.clientOrganizationId??"";if(t?.[r]?.organization?.[a]){let s=La(a);t[r].organization&&(t[r].organization[s]=t[r].organization[a],delete t[r].organization[a])}t?.[r]?.folders&&(t[r].folders=Object.fromEntries(Object.entries(t?.[r]?.folders??{}).map(([s,c])=>[Fi(s),c]))),t?.[r]?.documents&&(t[r].documents=Object.fromEntries(Object.entries(t?.[r]?.documents??{}).map(([s,c])=>[na(s),c])))}return t}catch(t){return this.loggingService.catch("Error in UsersService refactorPermissionsWithServerIds:",t),e}}getCurrentUserPermissionsWithServerIds$(){return this.currentUserPermissions$.asObservable().pipe(ce(e=>this.refactorPermissionsWithServerIds(e)),Et(mn))}getCurrentUserPermissionsWithServerIds(){return this.refactorPermissionsWithServerIds(this.currentUserPermissions$.value)}setCurrentUserPermissions(e){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setCurrentUserPermissions","color: green;"),this.currentUserPermissions$.next(e)}catch(t){this.loggingService.catch("Error in UsersService setCurrentUserPermissions:",t)}}};o.\u0275fac=function(t){return new(t||o)(ee(Ve),ee(at),ee(y),ee(pn),ee(Vn))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var ds=(()=>{let o=class o{constructor(e,t,r,a,s,c,p,u,C,E){this.afAuth=e,this.authService=t,this.configService=r,this.databaseService=a,this.docService=s,this.commonDbService=c,this.iamService=p,this.loggingService=u,this.notificationService=C,this.userPermissionService=E,this.documentPaths=null,this.views$=new ve({}),this.commentViews$=new ve({}),this.documentViews$=new ve({}),this.locationViews$=new ve({}),this.commentViewsByOrganizationIdAndDocumentId$=new ve({}),this.documentViewsByOrganizationIdAndDocumentId$=new ve({}),this.locationViewsByOrganizationIdAndLocationId$=new ve({}),this.documentViewsEnabled$=new ve(!1),this.documentViewsSetByDocumentId={},this.loggingService.log("%c[WB] Creating CLASS: ViewsService","color: blue;");try{this.authService.setViewsService(this),this.databaseService.getDb().pipe(Le(D=>!!D),st(1)).subscribe(D=>{D&&(this.subscribeViewsData().subscribe(),this.getNotificationFeatureViews$().subscribe(L=>{this.notificationService.setNotificationViews(L)}),this.authService.getUser$().pipe(Le(L=>!!L),he(L=>this.documentViewsEnabled$.pipe(Le(z=>z),ce(()=>L))),he(L=>this.docService.getDocumentPaths$().pipe(bo(null),Bi(),ce(([z,W])=>(z?.documentId!==W?.documentId&&this.views$.next({}),W)),ce(z=>(this.documentPaths=z,this.setDocumentAsRead({documentId:this.documentPaths?.documentId??"",clientDocumentId:this.documentPaths?.clientDocumentId??""}),{_user:L,_documentPaths:z})),he(z=>this.docService.getDocumentIds$().pipe(he(W=>(W?.length&&(W.find(J=>J.documentId===this.documentPaths?.documentId)||W.push({documentId:this.documentPaths?.documentId??"",clientDocumentId:this.documentPaths?.clientDocumentId??""}),W.forEach(J=>{this.setDocumentAsRead({documentId:J.documentId,clientDocumentId:J.clientDocumentId})})),se(z))))))),he(L=>this.docService.getDocumentMetadata$().pipe(Le(z=>!!z),ce(z=>T(I({},L),{_documentMetadata:z}))))).subscribe(),this.authService.getUser$().pipe(Le(L=>!!L),he(L=>this.documentViewsEnabled$.pipe(Le(z=>z),ce(()=>L))),he(L=>this.docService.getLocation$().pipe(Le(z=>!!z))),he(L=>this.docService.getDocumentIds$().pipe(he(z=>(z.find(W=>W.documentId===this.documentPaths?.documentId)||z.push({documentId:this.documentPaths?.documentId??"",clientDocumentId:this.documentPaths?.clientDocumentId??""}),z.forEach(W=>{this.setLocationAsRead({documentId:W.documentId,clientDocumentId:W.clientDocumentId})}),se(L)))))).subscribe())},D=>{this.loggingService.catch("Error in ViewsService getDb subscription: ",D)})}catch(D){this.loggingService.catch("Error in ViewsService constructor: ",D)}}setCommentService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setCommentService","color: green;"),this.commentService=e}catch(t){this.loggingService.catch("Error in ViewsService setCommentService: ",t)}}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,t){this.loggingService.log("%c[WB] Calling FUNCTION: subscribeViewsData","color: green;");let r,a;try{if(e&&(a=En(e)),t&&typeof t=="object"){let s=Yo(t);r=En(JSON.stringify(s))}}catch(s){this.loggingService.catch("Error in ViewsService subscribeViewsData: ",s)}return ei(this.afAuth).pipe(Le(s=>!!s),he(s=>this.isFeatureAllowed({firebaseUser:s})),he(s=>s.featureAllowed?this.iamService.isUserAllowed$().pipe(ce(c=>(s.featureAllowed=c,s))):se(s)),he(s=>s.featureAllowed?se(s).pipe(he(c=>this.docService.getDocumentPaths$().pipe(ce(p=>(this.documentPaths=p,c.documentPaths=p,c)))),he(c=>a?this.getDataFromDocumentIds([a]):this.docService.getDocumentIds$().pipe(he(p=>{let u=p?.length>0?p.map(C=>C.documentId):[this.documentPaths?.documentId??""];return this.getDataFromDocumentIds(u)})))):se([])))}isFeatureAllowed(e){return this.configService.getConfig$().pipe(Le(t=>!!t),ce(t=>T(I({},e),{config:t})),he(t=>this.authService.getUser$().pipe(ce(r=>T(I({},t),{user:r})))),he(t=>t.user?se(T(I({},t),{featureAllowed:!0})):se(T(I({},t),{featureAllowed:!1}))),Et((t,r)=>t?.featureAllowed===r?.featureAllowed))}getDataFromDocumentIds(e,t){return this.getDataFromDocuments({documentIds:e,filters:t})}getCommentViewsById(e){try{return this.commentViews$.value?.[e]?this.commentViews$.value?.[e]:void 0}catch(t){this.loggingService.catch("Error in ViewsService getCommentViewsById: ",t);return}}getDocumentViewsById(e){try{return this.documentViews$.value?.[e]}catch(t){this.loggingService.catch("Error in ViewsService getDocumentViewsById: ",t);return}}getLocationViewsById(e){try{return this.locationViews$.value?.[e]}catch(t){this.loggingService.catch("Error in ViewsService getLocationViewsById: ",t);return}}getDataFromDocuments(e){if(this.configService?.getApiKey()){let{documentIds:t,filters:r}=e;return t?.some(a=>!a)||!this.documentPaths?se([]):this.documentViewsEnabled$.pipe(he(a=>a?Sn([this.getCommentViewsDataFromDocuments(),this.getDocumentViewsDataFromDocuments(t),this.getLocationViewsDataFromDocuments(t)]):Sn([this.getCommentViewsDataFromDocuments()])))}else return se(null)}getCommentViews(e){try{let t={};Object.entries(e??{}).forEach(([r,a])=>{let s=a.metadata?.documentId,c=a.views;!s||!c||(t[s]||(t[s]={}),t[s][a.annotationId]=c)}),Object.entries(t??{}).forEach(([r,a])=>{this.setCommentViewsByOrganizationIdAndDocumentId({organizationId:this.documentPaths?.organizationId,documentId:r,commentViews:a})})}catch(t){this.loggingService.catch("Error in ViewsService getCommentViews: ",t)}}getCommentViewsDataFromDocuments(){try{return this.commentService?this.commentService?.getAllCommentAnnotations({detectGhostComments:!0,addFilterCommentsOnDomCheck:!0,analytics:{enabled:!0,properties:{source:"internal",sourceId:"commentsContainer"}}}).pipe(Le(e=>!!e),dn(e=>{this.getCommentViews(e)})):se([])}catch(e){return this.loggingService.catch("Error in ViewsService getCommentViewsDataFromDocuments: ",e),se([])}}getDocumentViewsDataFromDocuments(e){let t=this.docService.getDocumentPaths()?.veltFolderId,r=this.docService.getDocumentPaths()?.allDocuments,a=se([]),s={useCollectionGroup:!0,isCollection:!0,useQuery:!0};if(this.commonDbService.shouldUseFirestore()||(s.documentId=e?.length?e[0]:void 0,s.organizationId=this.documentPaths?.organizationId),t&&r)a=this.commonDbService.dbListener({feature:"allDocumentViews",properties:T(I({},s),{firestoreQuery:[Zn(lt("metadata.apiKey","==",this.configService?.getApiKey()),lt("metadata.veltFolderId","==",t),lt("metadata.organizationId","==",this.documentPaths?.organizationId))]})});else{let c=[];for(let p=0;p<(e?.length??0);p+=j.LISTENER_BATCH_SIZE)c.push(e?.slice(p,p+j.LISTENER_BATCH_SIZE)??[]);a=Sn(c.map(p=>this.commonDbService.dbListener({feature:"allDocumentViews",properties:T(I({},s),{firestoreQuery:[Zn(lt("metadata.apiKey","==",this.configService?.getApiKey()),lt("metadata.documentId","in",p),lt("metadata.organizationId","==",this.documentPaths?.organizationId),...t?[lt("metadata.veltFolderId","==",t)]:[])]})}).pipe(da()))).pipe(ce(p=>Ba(p)))}return a.pipe(ce(c=>({data:c?.data,operation:c?.operation})),ce(({data:c,operation:p})=>{let u={};return e?(Object.entries(c??{}).forEach(([C,E])=>{let D=E.metadata?.documentId;D&&(u[D]||(u[D]={}),u[D][C]=E)}),{data:c,documentMap:u,operation:p}):{data:c,documentMap:u,operation:p}}),ce(({data:c,documentMap:p,operation:u})=>{if(u?.type==="removed"){if(u?.ids?.length){let C=this.documentViews$.value;u?.ids?.forEach(E=>{delete C?.[E]}),this.documentViews$.next(C)}}else Object.entries(p??{}).forEach(([C,E])=>{this.setDocumentViewsByOrganizationIdAndDocumentId({organizationId:this.documentPaths?.organizationId,documentId:C,documentViews:E})})}))}getLocationViewsDataFromDocuments(e){let t=this.docService.getDocumentPaths()?.veltFolderId,r=this.docService.getDocumentPaths()?.allDocuments,a=se([]),s={useCollectionGroup:!0,isCollection:!0,useQuery:!0};if(this.commonDbService.shouldUseFirestore()||(s.documentId=e?.length?e[0]:void 0,s.organizationId=this.documentPaths?.organizationId),t&&r)a=this.commonDbService.dbListener({feature:"allLocationViews",properties:T(I({},s),{firestoreQuery:[Zn(lt("metadata.apiKey","==",this.configService?.getApiKey()),lt("metadata.veltFolderId","==",t),lt("metadata.organizationId","==",this.documentPaths?.organizationId))]})});else{let c=[];for(let p=0;p<(e?.length??0);p+=j.LISTENER_BATCH_SIZE)c.push(e?.slice(p,p+j.LISTENER_BATCH_SIZE)??[]);a=Sn(c.map(p=>this.commonDbService.dbListener({feature:"allLocationViews",properties:T(I({},s),{firestoreQuery:[Zn(lt("metadata.apiKey","==",this.configService?.getApiKey()),lt("metadata.documentId","in",p),lt("metadata.organizationId","==",this.documentPaths?.organizationId),...t?[lt("metadata.veltFolderId","==",t)]:[])]})}).pipe(da()))).pipe(ce(p=>Ba(p)))}return a.pipe(ce(c=>({data:c?.data,operation:c?.operation})),ce(({data:c,operation:p})=>{let u={};return e?(Object.entries(c??{}).forEach(([C,E])=>{let D=E.metadata?.documentId;D&&(u[D]||(u[D]={}),u[D][C]=E)}),{data:c,documentMap:u,operation:p}):{data:c,documentMap:u,operation:p}}),ce(({data:c,documentMap:p,operation:u})=>{if(u?.type==="removed"){if(u?.ids?.length){let C=this.locationViews$.value;u?.ids?.forEach(E=>{delete C?.[E]}),this.locationViews$.next(C)}}else Object.entries(p??{}).forEach(([C,E])=>{this.setLocationViewsByOrganizationIdAndDocumentId({organizationId:this.documentPaths?.organizationId,documentId:C,locationViews:E})})}))}setViewsData(e){try{this.views$.next(I(I({},this.views$.getValue()),e||{}))}catch(t){this.loggingService.catch("Error in ViewsService setViewsData:",t)}}setCommentViewsByOrganizationIdAndDocumentId({organizationId:e,documentId:t,commentViews:r,queryHash:a}){try{if(r||(r={}),t){e||(e=j.NO_ORGANIZATION_ID),a||(a=j.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]),{[t]:T(I({},this.commentViewsByOrganizationIdAndDocumentId$.value[e]?.[t]),{[a]:r})})}))}}catch(s){this.loggingService.catch("Error in CommentService setCommentAnnotationsByOrganizationIdAndDocumentId:",s)}}setDocumentViewsByOrganizationIdAndDocumentId({organizationId:e,documentId:t,documentViews:r,queryHash:a}){try{if(r||(r={}),t){e||(e=j.NO_ORGANIZATION_ID),a||(a=j.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]),{[t]:T(I({},this.documentViewsByOrganizationIdAndDocumentId$.value[e]?.[t]),{[a]:r})})}))}}catch(s){this.loggingService.catch("Error in CommentService setCommentAnnotationsByOrganizationIdAndDocumentId:",s)}}setLocationViewsByOrganizationIdAndDocumentId({organizationId:e,documentId:t,locationViews:r,queryHash:a}){try{if(r||(r={}),t){e||(e=j.NO_ORGANIZATION_ID),a||(a=j.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]),{[t]:T(I({},this.locationViewsByOrganizationIdAndLocationId$.value[e]?.[t]),{[a]:r})})}))}}catch(s){this.loggingService.catch("Error in CommentService setCommentAnnotationsByOrganizationIdAndDocumentId:",s)}}getCommentFeatureViews$(){return this.commentViews$.pipe(Et((e,t)=>JSON.stringify(e||{})===JSON.stringify(t||{})))}setCommentAnnotationAsRead(e){return Q(this,null,function*(){try{if(this.authService.getUser()&&e?.annotationId){this.updateCommentAnnotationViews(e);let r=e?.metadata?.organizationId??this.documentPaths?.organizationId??"",a=e?.metadata?.documentId??this.documentPaths?.documentId??"";yield this.commonDbService.setData({feature:"comment",properties:{id:e.annotationId,documentId:a,organizationId:r,metadata:{apiKey:this.configService.getApiKey(),organizationId:r,veltFolderId:e?.metadata?.veltFolderId,documentId:a}},data:JSON.parse(JSON.stringify(e))})}}catch(t){this.loggingService.catch("Error in ViewsService setCommentAnnotationAsRead:",t)}})}updateCommentAnnotationViews(e){try{let t=this.authService.getUser(),r={views:{},comments:{}};if(t){let a={},s=e?.views?.comments||{},c=new Date().getTime()+this.commonDbService.getOffset();e.comments?.forEach(u=>{s[u.commentId]||(s[u.commentId]={views:{}}),s[u.commentId].views||(s[u.commentId].views={}),s[u.commentId].views[t.userSnippylyId]||(s[u.commentId].views[t.userSnippylyId]={timestamp:c})});let p=new Set(e.comments?.map(u=>u.commentId+""));if(Object.keys(s??{}).forEach(u=>{p.has(u)||delete s[u]}),e.comments?.length){let u=s[e.comments[0].commentId]?.views||{},C=Object.keys(u??{}).filter(E=>e.comments?.every(D=>s[D.commentId]?.views?.[E]));C.forEach(E=>{a[E]={timestamp:u[E].timestamp}}),e.viewedByUserIds=C}r.views=a,r.comments=s,e.views=r}return r}catch(t){return this.loggingService.catch("Error in ViewsService updateCommentAnnotationViews:",t),{views:{},comments:{}}}}getNotificationFeatureViews$(){return this.views$.pipe(Et((e,t)=>JSON.stringify(e?.notification||{})===JSON.stringify(t?.notification||{})))}setNotificationsAsRead(e){try{let t=this.authService.getUser();if(t){let r=new Date().getTime()+this.commonDbService.getOffset();e.forEach(a=>{this.commonDbService.updateData({feature:"notificationViewsTimestamp",properties:{id:a,user:t.userSnippylyId,documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??""},data:{timestamp:r}})})}}catch(t){this.loggingService.catch("Error in ViewsService setNotificationAsRead:",t)}}getDocumentViews$(){return this.views$.pipe(Et((e,t)=>JSON.stringify(e?.documentViews||{})===JSON.stringify(t?.documentViews||{})))}getUniqueViewsByUser(e){try{return this.enableDocumentViews(),this.docService.getDocumentPaths$().pipe(he(t=>(this.documentPaths=t,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||{}:{}})))),Et(mn))}catch(t){return this.loggingService.catch("Error in ViewsService getUniqueViewsByUser:",t),se({})}}getUniqueViewsByDate(e){try{return this.enableDocumentViews(),this.docService.getDocumentPaths$().pipe(he(t=>(this.documentPaths=t,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(t){return this.loggingService.catch("Error in ViewsService getUniqueViewsByDate:",t),se({})}}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 Q(this,arguments,function*({documentId:e,clientDocumentId:t}){try{let a=this.authService.getUser();if(a&&e&&this.userPermissionService?.hasEditAccess({documentId:e??"",folderId:this.documentPaths?.allDocuments&&this.documentPaths?.veltFolderId?this.documentPaths?.veltFolderId:void 0})){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 u=new Date().toISOString().split("T")[0];p?.users[a.userSnippylyId]||(p.users[a.userSnippylyId]={}),p.users[a.userSnippylyId][u]={timestamp:this.timestamp},p?.day[u]||(p.day[u]={}),p.day[u][a.userSnippylyId]={timestamp:this.timestamp},p.metadata=this.docService.getBaseMetadata("documentViews",{clientDocumentId:t}),this.commonDbService.updateData({feature:"documentViews",properties:{id:e,date:u,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:t})}),this.docService.getDocumentMetadata$(e).pipe(Le(u=>u!==null),st(1)).subscribe(()=>{let u={day:{[c]:{[a.userSnippylyId]:{timestamp:s}}},users:{[a.userSnippylyId]:{[c]:{timestamp:s}}},metadata:this.docService.getBaseMetadata("documentViews",{clientDocumentId:t})};this.commonDbService.updateData({feature:"documentViews",properties:{id:e,date:c,user:a.userSnippylyId,documentId:e,organizationId:this.documentPaths?.organizationId??"",skipRtdb:!0},data:u})});this.checkAndTriggerNotification(a)}}catch(a){this.loggingService.catch("Error in ViewsService setDocumentAsRead:",a)}})}checkAndTriggerNotification(e){try{this.getUniqueViewsByUser().pipe(st(1)).subscribe(t=>{if(Object.keys(t??{}).length===2){let r=this.docService.getDocumentMetadata();if(r?.creator?.email&&r?.creator?.email!==e.email){let a=[r.creator.email];this.updateNotificationsDatabase(xj.FIRST_VIEWED,{documentViews:{emails:a}})}}})}catch(t){this.loggingService.catch("Error in checkAndTriggerNotification:",t)}}setLocationAsRead(r){return Q(this,arguments,function*({documentId:e,clientDocumentId:t}){try{let a=this.authService.getUser(),s=this.docService.getLocation(),c=s?.locationId,p=s?.location;if(a&&c&&p){let u=new Date().getTime()+this.commonDbService.getOffset(),C=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:t}),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:C,documentId:e,organizationId:this.documentPaths?.organizationId??"",skipFirestore:!0},data:{timestamp:u}}),this.commonDbService.updateData({feature:"locationDayViews",properties:{id:c,date:C,user:a.userSnippylyId,documentId:e,organizationId:this.documentPaths?.organizationId??"",skipFirestore:!0},data:{timestamp:u}}),this.commonDbService.updateData({feature:"locationMetadataViews",properties:{id:c,documentId:e,organizationId:this.documentPaths?.organizationId??"",skipFirestore:!0},data:this.docService.getBaseMetadata("locationViews",{clientDocumentId:t})});let D={day:{[C]:{[a.userSnippylyId]:{timestamp:u}}},users:{[a.userSnippylyId]:{[C]:{timestamp:u}}},metadata:this.docService.getBaseMetadata("locationViews",{clientDocumentId:t}),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,t={}){try{let r=I({actionType:e,notificationSource:"documentViews"},t);this.notificationService.updateNotificationDatabase(r)}catch(r){this.loggingService.catch("Error in CommentService updateNotificationsDatabase: ",r)}}get timestamp(){return this.commonDbService.getServerTimestamp()}};o.\u0275fac=function(t){return new(t||o)(ee(Di),ee(Ve),ee(Ft),ee(Dn),ee(at),ee(pn),ee(vn),ee(y),ee(gn),ee(y0))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var Hd=(()=>{let o=class o{constructor(e,t,r){this.docService=e,this.loggingService=t,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 Q(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 t=this.docService.getOrganizationMetadata(this.docService.getOrganizationConfig()?.organizationId),r=this.docService.getDocumentMetadataOfAvailableDocuments(),a=this.docService.getLocation();t&&(t=JSON.parse(JSON.stringify(t)),delete t?.organizationId,t.organizationId=t?.clientOrganizationId,delete t?.clientOrganizationId,delete t?.pageInfo),r&&(r=JSON.parse(JSON.stringify(r)),r.forEach(C=>{delete C?.locations,delete C?.location,delete C?.locationId,delete C?.pageInfo,delete C?.documentId,C.documentId=C?.clientDocumentId,delete C?.clientDocumentId,delete C?.veltFolderId,C?.clientOrganizationId&&(C.organizationId=C?.clientOrganizationId,delete C?.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(C=>{C?.location&&s.push(C?.location)});let p=this.docService.getDocumentPaths()?.folderId;return{organization:t,documents:r,locations:s,folderId:p}}catch(e){return this.loggingService.catch("Error in MetadataService getGlobalMetadata: ",e),{}}})}};o.\u0275fac=function(t){return new(t||o)(ee(at),ee(y),ee(Ve))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var b0=(()=>{let o=class o{constructor(e,t,r){this.coreActionsService=e,this.loggingService=t,this.metadataService=r,this.buttonClickSubject$=new tt,this.buttonToggleMap$=new ve({}),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 Q(this,arguments,function*({id:e,type:t,groupId:r,contextData:a}){try{this.buttonToggle(e,void 0,t,r);let c=this.extractButtonData(a),p=this.createButtonContext(e,t,r),u=yield this.metadataService.getGlobalMetadata(),C=T(I({buttonContext:p},c),{metadata:u});this.buttonClickSubject$.next(C),this.coreActionsService.triggerAction($i.VELT_BUTTON_CLICK,C)}catch(c){this.loggingService.catch("Error in ButtonService buttonClick: ",c)}})}buttonActive({id:e,type:t,groupId:r,contextData:a}){try{let s=this.buttonToggleMap$.value?.[r||"ungrouped"]?.[e]||!0;this.buttonToggle(e,s,t,r)}catch(s){this.loggingService.catch("Error in ButtonService buttonClick: ",s)}}buttonToggle(e,t,r,a){try{let s=this.buttonToggleMap$.value,c=this.createNewToggleMap(s,e,t,r,a);this.buttonToggleMap$.next(c)}catch(s){this.loggingService.catch("Error in ButtonService buttonToggle: ",s)}}extractButtonData(e){try{let t={};return Object.entries(this.contextDataMapping).forEach(([r,a])=>{let s=this.getNestedValue(e,a.source);s!==void 0&&(t[a.target]=s)}),t}catch(t){return this.loggingService.catch("Error in ButtonService extractContextData: ",t),{}}}getNestedValue(e,t){try{let r=e;for(let a of t){if(r?.[a]===void 0)return;Gi(r[a])?r=r[a]():r=r[a]}return r}catch(r){this.loggingService.catch("Error in ButtonService getNestedValue: ",r);return}}createButtonContext(e,t,r){try{let a={type:t,selections:this.buttonToggleMap$.value,clickedButtonId:e};return(t==="single-select"||t==="multi-select")&&r?T(I({},a),{groupId:r}):a}catch(a){return this.loggingService.catch("Error in ButtonService createButtonMetadata: ",a),{}}}createNewToggleMap(e,t,r,a,s){try{let c=I({},e);return a==="button-toggle"?T(I({},c),{ungrouped:T(I({},c.ungrouped),{[t]:r??!c.ungrouped?.[t]})}):a==="single-select"&&s?T(I({},c),{[s]:{[t]:r??!0}}):a==="multi-select"&&s?T(I({},c),{[s]:T(I({},c[s]),{[t]:r??!c[s]?.[t]})}):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 Q(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(u=>{Object.keys(p[u]).forEach(C=>{C===s&&delete p?.[u]?.[C]})}),this.buttonToggleMap$.next(p)}else this.buttonToggleMap$.next({});let t={selections:this.buttonToggleMap$.value},r=yield this.metadataService.getGlobalMetadata(),a={buttonContext:t,metadata:r};this.coreActionsService.triggerAction($i.VELT_BUTTON_CLICK,a)}catch(t){this.loggingService.catch("Error in ButtonService resetVeltButtonState: ",t)}})}buttonToggleMapValue(){return this.buttonToggleMap$.value}};o.\u0275fac=function(t){return new(t||o)(ee(Vd),ee(y),ee(Hd))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var De=(()=>{let o=class o{constructor(e,t,r,a,s,c,p,u,C,E,D,L,z,W,J,ue,ye,Ae,He,Fe,xe,Se,we,_e,fe,Oe,Ne){this.analyticsService=e,this.areaService=t,this.commonDbService=r,this.configService=a,this.docService=s,this.databaseService=c,this.authService=p,this.domService=u,this.afAuth=C,this.avatarService=E,this.contactService=D,this.storageService=L,this.functions=z,this.dialog=W,this.iamService=J,this.loggingService=ue,this.notificationService=ye,this.customFilterService=Ae,this.reactionService=He,this.hotkeyService=Fe,this.recorderService=xe,this.viewsService=Se,this.buttonService=we,this.metadataService=_e,this.commonDbUtilsService=fe,this.attachmentResolverService=Oe,this.userPermissionService=Ne,this.customPinsById=new Map,this.commentAdded$=new tt,this.commentUpdated$=new tt,this.commentAccepted$=new tt,this.commentRejected$=new tt,this.commentAnnotationDeleted$=new tt,this.multiThreadCommentAnnotationDeleted$=new tt,this.commentAnnotationById$=new ve(null),this.multiThreadCommentAnnotationById$=new ve(null),this.ghostCommentAnnotationMap$=new ve({}),this.unreadCommentsMap$=new ve(null),this.documentPaths=null,this.user=null,this.customCategoryMap=j.CommentCategoryMap,this.allowedElementIds$=new ve([]),this.allowedElementClassNames$=new ve([]),this.allowedElementQuerySelectors$=new ve([]),this.addCommentMode$=new ve(!1),this.persistentCommentMode$=new ve(!1),this.seenByUsers$=new ve(!0),this.deleteReplyConfirmation$=new ve(!1),this.persistentModeBanner$=new ve(!0),this.commentAddedEmitter=null,this.commentContextProvider=null,this.textCommentMode$=new ve(!0),this.sidebarVisible$=new ve(!1),this.sidebarOpenedByCustomTrigger$=new ve(!1),this.floatingCommentsEnabled$=new ve(!0),this.moderatorMode$=new ve(!1),this.streamMode$=new ve(!1),this.enableSignInButton$=new ve(!1),this.enableUpgradeButton$=new ve(!1),this.onSignInClick$=new tt,this.onUpgradeClick$=new tt,this.enableAttachment$=new ve(!0),this.enableReactions$=new ve(!0),this.allowedRecordings$=new ve(["audio","video","screen"]),this.openSidebar$=new tt,this.showScreenSizeInfo$=new ve(!1),this.showCommentIndex$=new ve(!1),this.popoverMode$=new ve(!1),this.popoverTriangleComponent$=new ve(!0),this.draftMode$=new ve(!0),this.enableDialogOnHover$=new ve(!0),this.enableDialogOnTargetElementClick$=new ve(!1),this.enablePriority$=new ve(!1),this.enableStatus$=new ve(!0),this.enableResolve$=new ve(!0),this.enableGhostComments$=new ve(!1),this.enableGhostCommentsMessage$=new ve(!0),this.inboxMode$=new ve(!1),this.enableAutoCategorize$=new ve(!1),this.commentContainerDarkMode$=new ve(!1),this.suggestionMode$=new ve(!1),this.mobileMode$=new ve(!0),this.inlineCommentMode$=new ve(!1),this.minimap$=new ve(!1),this.commentsOnDom$=new ve(!0),this.commentToolEnabled$=new ve(!0),this.totalMediaLength$=new ve(0),this.sidebarUrlNavigationEnabled$=new ve(!1),this.detectionStrategy$=new ve($P.DEFAULT),this.sidebarButtonOnCommentDialogVisible$=new ve(!1),this.sidebarButtonOnCommentDialogClick$=new tt,this.commentNavigationButtonClick$=new tt,this.deviceIndicatorOnCommentPins$=new ve(!1),this.sidebarCommentClick$=new tt,this.privateCommentMode$=new ve(!1),this.scrollToComment$=new ve(!0),this.userMentions$=new ve(!0),this.deleteOnBackspace$=new ve(!0),this.hotkeyEnabled$=new ve(!1),this.recordingSummaryEnabled$=new ve(!0),this.unreadIndicatorMode$=new ve(Ju.MINIMAL),this.composerMode$=new ve(eh.DEFAULT),this.enterKeyToSubmit$=new ve(!1),this.resolvedCommentsOnDom$=new ve(!1),this.bubbleOnPinEnabled$=new ve(!1),this.bubbleOnPinHoverEnabled$=new ve(!0),this.excludeLocationIdsFromSidebar$=new ve([]),this.multiThread$=new ve(!1),this.groupMatchedComments$=new ve(!1),this.shortUserName$=new ve(!0),this.collapsedComments$=new ve(!1),this.fullExpanded$=new ve(!1),this.queryParamsComments$=new ve(!1),this.resolveStatusAccessAdminOnly$=new ve(!1),this.linkCallback$=new ve(!1),this.svgAsImg$=new ve(!1),this.commentToNearestAllowedElement$=new ve(!1),this.filterCommentsOnDom$=new ve(!1),this.maxReplyAvatars$=new ve(3),this.replyAvatars$=new ve(!1),this.commentplaceholder$=new ve(void 0),this.replyplaceholder$=new ve(void 0),this.pinShadowDOM$=new ve(!0),this.dialogShadowDOM$=new ve(!0),this.textCommentToolShadowDOM$=new ve(!0),this.pinDarkMode$=new ve(null),this.textCommentToolDarkMode$=new ve(null),this.textCommentToolbarDarkMode$=new ve(null),this.textCommentToolbarShadowDOM$=new ve(!0),this.sidebarShadowDOM$=new ve(!0),this.changeDetectionInCommentMode$=new ve(!1),this.commentSelectionChange$=new tt,this.commentsFromSidebarMap$=new ve(null),this.sidebarButtonCountType$=new ve("default"),this.filterGhostCommentsInSidebar$=new ve(!1),this.commentSidebarFilters$=new ve({}),this.commentSidebarSystemFiltersOperator$=new ve(Dc.AND),this.bubbleCommentAnnotationIds$=new ve([]),this.updateCommentDialogPositionTriggerSubject$=new ve(void 0),this.areaCommentEnabled$=new ve(!0),this.commentPinCursorImage$=new ve(""),this.commentAnnotationsFromCommentsContainer$=new ve([]),this.customChipDropdownData$=new ve(null),this.originalCommentAnnotationsByDocumentId$=new ve({}),this.draftCommentAnnotationsByAnnotationId$=new ve(null),this.draftMultiThreadCommentAnnotationsByAnnotationId$=new ve({}),this.copyLink$=new ve(""),this.addCommentDragMode=!1,this.dragSubscriptions=[],this.hotkeySubscriptions=[],this.sidebarData$=new ve(null),this.sidebarCustomActionEventData$=new ve(null),this.sidebarCustomActionEventDataAllChanges$=new ve(null),this.sidebarCustomActionEventDataOnInit$=new ve(null),this.customActions$=new ve(!1),this.focusedThreadMode$=new ve(!1),this.customStatusesShown$=new ve(!1),this.readOnly$=new ve(!1),this.customAutocompleteSearch$=new ve(!1),this.deleteThreadWithFirstComment$=new ve(!0),this.transformContext$=new ve(null),this.expandMentionGroups$=new ve(!1),this.showMentionGroupsFirst$=new ve(!1),this.showMentionGroupsOnly$=new ve(!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.viewsService.setCommentService(this),this.docService.getDocumentPaths$().pipe(Bi()).subscribe(([Ct,On])=>{Ct?.documentId!==On?.documentId&&this.unreadCommentsMap$.next(null),On&&this.shouldEnableReadOnly()},Ct=>{this.loggingService.catch("Error in CommentService getDocumentPaths$ subscription: ",Ct)}),this.authService.getUser$().subscribe(Ct=>{Ct||this.resetCacheData()},Ct=>{this.loggingService.catch("Error in CommentService getUser$ subscription: ",Ct)}),this.databaseService.getDb().pipe(Le(Ct=>!!Ct),st(1)).subscribe(Ct=>{Ct&&this.getDocumentPaths()},Ct=>{this.loggingService.catch("Error in CommentService getDb subscription: ",Ct)}),this.domService.onWindowPointerMove$().subscribe(Ct=>{if(this.addCommentMode$.value){let On=!0;if(this.addCommentDragMode)this.domService.removeClassFromElement(document.body,"show-pin-cursor");else{let yt=this.domService.getBackgroundElement(Ct.clientX,Ct.clientY,!0,!0);if(yt)if(this.isElementInsideAllowedElements(yt))if(Vm(Ct.target))this.domService.removeClassFromElement(document.body,"show-pin-cursor");else{this.domService.addClassToElement(document.body,"show-pin-cursor"),this.hightlightElement&&this.hightlightElement!==yt&&this.domService.removeHighlightFromElement(this.hightlightElement),this.hightlightElement=yt;let Rt=this.domService.getSelectedAnnotationsMap("comment")||{},Bt=this.commentPinCursorImage$.value||j.CURSOR.COMMENT_PIN;this.domService.highlightElement(this.hightlightElement,Bt,!!Object.keys(Rt)?.length),On=!1}else this.domService.removeClassFromElement(document.body,"show-pin-cursor")}this.hightlightElement&&On&&(this.domService.removeHighlightFromElement(this.hightlightElement),this.hightlightElement=null)}},Ct=>{this.loggingService.catch("Error in CommentService onWindowPointerMove$ subscription: ",Ct)}),this.domService.onWindowKeyupEsc$().subscribe(Ct=>{if(this.addCommentMode$.value){let On=this.domService.getSelectedAnnotationsMap("comment")||{};Object.keys(On)?.length?this.domService.resetSelectedAnnotationsMap():this.disableAddCommentMode()}},Ct=>{this.loggingService.catch("Error in CommentService onWindowKeyupEsc$ subscription: ",Ct)}),this.domService.onDocumentClick$().subscribe(Ct=>{if(Ct?.target&&!Xi(Ct?.target)){let On=this.domService.getSelectedAnnotationsMap("comment")||{};if(On=I(I({},On),this.domService.getSelectedAnnotationsMap("multiThread")||{}),Object.keys(On)?.length&&(this.domService.resetSelectedAnnotationsMap(),this.persistentCommentMode$?.value)){this.addCommentMode$.value&&this.detectToAddAreaComment(),Ct.preventDefault(),Ct.stopPropagation();return}}if(Ct&&this.addCommentMode$.value&&!Vm(Ct.target)){let On=!1;if(this.addCommentDragMode)Ct.preventDefault(),Ct.stopPropagation(),this.addCommentDragMode=!1;else if(!this.domService.getDraftCommentAnnotationDialogs()?.length){let yt=this.domService.getBackgroundElement(Ct.clientX,Ct.clientY);if((this.persistentCommentMode$?.value&&this.domService.getBackgroundVeltElement(Ct.clientX,Ct.clientY)||Ct?.target&&Xi(Ct?.target))&&(yt=null),yt&&(this.isElementInsideAllowedElements(yt)||this.getCommentToNearestAllowedElement()&&this.getNearestAllowedElement(yt))&&(On=this.isElementInsideManualCommentContainer(yt),!On)){Ct.preventDefault(),Ct.stopPropagation();let Rt=this.freeStyleCommentContext&&typeof this.freeStyleCommentContext=="object"?JSON.parse(JSON.stringify(this.freeStyleCommentContext)):void 0;this.addComment(Ct,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,void 0,void 0,void 0,void 0,Rt)}}this.persistentCommentMode$?.value?this.detectToAddAreaComment():On||this.disableAddCommentMode()}},Ct=>{this.loggingService.catch("Error in CommentService onDocumentClick$ subscription: ",Ct)}),this.addCommentMode$.subscribe(Ct=>{this.hightlightElement&&this.domService.removeHighlightFromElement(this.hightlightElement),Ct?(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(On=>On.unsubscribe()),this.clearFreeStyleCommentContext())},Ct=>{this.loggingService.catch("Error in CommentService addCommentMode$ subscription: ",Ct)}),this.domService.onWindowKeyupBackspace$().subscribe(Ct=>{this.getDeleteOnBackspace()&&this.deleteCommentPinAnnotations("keyupBackspace")},Ct=>{this.loggingService.catch("Error in CommentService onWindowKeyupBackspace$ subscription: ",Ct)}),this.domService.onWindowKeyupDelete$().subscribe(Ct=>{this.deleteCommentPinAnnotations("keyupDelete")},Ct=>{this.loggingService.catch("Error in CommentService onWindowKeyupDelete$ subscription: ",Ct)}),this.domService.getDeleteCommmentAnnotations$().subscribe(Ct=>{Ct?.length&&(Ct?.filter(yt=>!["tag","recorder","rewriter","arrow","area","multiThread"].includes(yt.type))).forEach(yt=>Q(this,null,function*(){yield this.deleteCommentPinAnnotation(yt)}))},Ct=>{this.loggingService.catch("Error in CommentService onWindowKeyupDelete$ subscription: ",Ct)}),this.getPopoverMode$().subscribe(Ct=>{Ct?document?.body?.setAttribute(j.ATTRIBUTES.VELT_POPOVER_MODE,"true"):document?.body?.removeAttribute(j.ATTRIBUTES.VELT_POPOVER_MODE)},Ct=>{this.loggingService.catch("Error in CommentService getPopoverMode subscription: ",Ct)}),this.customFilterService.customCategoryMap$.subscribe(Ct=>{this.customCategoryMap=Ct},Ct=>{this.loggingService.catch("Error in CommentService customCategoryMap$ subscription: ",Ct)}),this.hotkeyEnabled$.subscribe(Ct=>{Ct?this.subscribeHotkeyEvents():this.unsubscribeHotkeyEvents()},Ct=>{this.loggingService.catch("Error in CommentService hotkeyEnabled$ subscription: ",Ct)}),this.domService.getSelectedAnnotationsMap$().pipe(Bi()).subscribe(([Ct,On])=>{try{let yt=Object.values(Ct||{}).filter(Bt=>!["tag","recorder","rewriter","arrow","area"].includes(Bt.type)),Rt=Object.values(On||{}).filter(Bt=>!["tag","recorder","rewriter","arrow","area"].includes(Bt.type));yt?.forEach(Bt=>{Rt?.find(In=>In.annotationId===Bt.annotationId)||this.commentSelectionChange$.next({annotation:Gn(Bt),selected:!1})}),Rt?.forEach(Bt=>{yt?.find(In=>In.annotationId===Bt.annotationId)||this.commentSelectionChange$.next({annotation:Gn(Bt),selected:!0})})}catch(yt){this.loggingService.catch("Error in CommentService getSelectedAnnotationsMap$: ",yt)}},Ct=>{this.loggingService.catch("Error in CommentService getSelectedAnnotationsMap$ subscription: ",Ct)})}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,this.commentsFromSidebarMap$.next(null)}catch(e){this.loggingService.catch("Error in CommentService clearCache: ",e)}}setCommentActionsService(e){try{this.commentActionsService=e}catch(t){this.loggingService.catch("Error in CommentService setCommentActionsService: ",t)}}detectToAddAreaComment(){try{let e=this.areaService.getAreaEnabled(),t=this.getAreaCommentEnabled();if(e&&t){let r,a,s,c=null,p=null;this.dragSubscriptions.forEach(u=>u.unsubscribe()),this.dragSubscriptions.push(this.domService.onWindowMouseDown$().pipe(Le(u=>!Xi(u?.target)),st(1)).subscribe(u=>{c=null,p=null,this.dragSubscriptions.push(this.domService.getClickAndDragPointsObservable().subscribe(C=>{if(c===null){let E=C?.startPoint?.event?.target,D=Xi(E),L=Vm(E),z=this.isElementInsideAllowedElements(E);c=!D&&!L&&z}if(c){this.addCommentDragMode=!0,r=C.startPoint,a=C.curPoint;let E=C?.curPoint?.event?.target,D=Xi(E),L=Vm(E),z=this.isElementInsideAllowedElements(E);p=!D&&!L&&z,p?s=this.domService.drawRectangle(r,a):s?.remove()}})),this.domService.onWindowPointerUp$().pipe(Hs(1),st(1)).subscribe(C=>{if(a={x:C.clientX,y:C.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}],D=this.freeStyleCommentContext&&typeof this.freeStyleCommentContext=="object"?JSON.parse(JSON.stringify(this.freeStyleCommentContext)):void 0;this.addComment(C,void 0,E,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,void 0,void 0,D)}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(j.TAGS.VELT_AREAS)||document.querySelector(j.TAGS.SNIPPYLY_AREAS))){let t=document.createElement(j.TAGS.VELT_AREAS);document.body.appendChild(t)}}catch(e){this.loggingService.catch("Error in CommentService addAreaContainerTag: ",e)}}addIframeContainerStaticAttribute(){try{document.querySelectorAll(`[${j.ATTRIBUTES.VELT_IFRAME_CONTAINER}]`).forEach(t=>{window.getComputedStyle(t).position==="static"&&t.setAttribute(j.ATTRIBUTES.VELT_IFRAME_CONTAINER_STATIC,"true")})}catch(e){this.loggingService.catch("Error in CommentService addIframeContainerStaticAttribute: ",e)}}removeIframeContainerStaticAttribute(){try{document.querySelectorAll(`[${j.ATTRIBUTES.VELT_IFRAME_CONTAINER_STATIC}]`).forEach(t=>{t.removeAttribute(j.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(t){this.loggingService.catch("Error in CommentService setCommentAddedEmitter: ",t)}}setContextProvider(e){try{this.commentContextProvider=e}catch(t){this.loggingService.catch("Error in CommentService setContextProvider: ",t)}}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(t){this.loggingService.catch("Error in CommentService setAllowedElementIds: ",t)}}getAllowedElementIds(){return this.allowedElementIds$.asObservable()}setAllowedElementClassNames(e){try{this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{allowedElementClassNames:e}}),this.allowedElementClassNames$.next(e||[])}catch(t){this.loggingService.catch("Error in CommentService setAllowedElementClassNames: ",t)}}getAllowedElementClassNames(){return this.allowedElementClassNames$.asObservable()}setAllowedElementQuerySelectors(e){try{this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{allowedElementQuerySelectors:e}}),this.allowedElementQuerySelectors$.next(e||[])}catch(t){this.loggingService.catch("Error in CommentService setAllowedElementQuerySelectors: ",t)}}getAllowedElementQuerySelectors(){return this.allowedElementQuerySelectors$.asObservable()}getAnnotationsCount(e){try{return ei(this.afAuth).pipe(Le(t=>!!t),he(t=>this.isFeatureAllowed({firebaseUser:t,annotations:[],filteredAnnotations:[]})),he(t=>t.featureAllowed?this.iamService.isUserAllowed$().pipe(ce(r=>(t.featureAllowed=r,t))):se(t)),he(t=>t.featureAllowed?se(t).pipe(he(r=>this.docService.getDocumentPaths$().pipe(ce(a=>(this.documentPaths=a,r.documentPaths=a,r)))),he(()=>e?.documentIds?.length?se(e?.documentIds.map(r=>({clientDocumentId:r,documentId:`${En(r)}`}))):this.docService.getDocumentIds$().pipe(ce(r=>r?.length>0?r:[{documentId:this.documentPaths?.documentId??"",clientDocumentId:this.documentPaths?.clientDocumentId||""}]))),he(r=>{let a=this.authService.getUser()?.userSnippylyId,s=this.documentPaths?.organizationId,c=r?.length>0?r.map(L=>L.documentId):[this.documentPaths?.documentId??""];if(c.some(L=>!L)||!this.documentPaths)return se();let p=this.docService.getDocumentPaths()?.veltFolderId,u=this.docService.getDocumentPaths()?.allDocuments,C=se(),E=se(),D={useCollectionGroup:!0,isCollection:!0,useQuery:!0};if(p&&u)C=this.commonDbService.dbListener({feature:"allComments",properties:T(I({},D),{firestoreQuery:[Zn(lt("metadata.apiKey","==",this.configService?.getApiKey()),lt("metadata.organizationId","==",s),lt("metadata.veltFolderId","==",p),...e?.statusIds?[lt("status.id","in",e.statusIds)]:[]),fi("lastUpdated","desc"),fi("createdAt","desc")]})}).pipe(ce(L=>L?.data)),E=this.commonDbService.dbListener({feature:"allCommentViews",properties:T(I({},D),{firestoreQuery:[Zn(lt("metadata.apiKey","==",this.configService?.getApiKey()),lt("metadata.organizationId","==",s),lt("metadata.veltFolderId","==",p))]})}).pipe(ce(L=>L?.data));else{let L=[];for(let z=0;z<(c?.length??0);z+=j.LISTENER_BATCH_SIZE)L.push(c?.slice(z,z+j.LISTENER_BATCH_SIZE)??[]);C=Sn(L.map(z=>this.commonDbService.dbListener({feature:"allComments",properties:T(I({},D),{firestoreQuery:[Zn(lt("metadata.apiKey","==",this.configService?.getApiKey()),lt("metadata.organizationId","==",s),lt("metadata.documentId","in",z),...e?.statusIds?[lt("status.id","in",e.statusIds)]:[],...p?[lt("metadata.veltFolderId","==",p)]:[]),fi("lastUpdated","desc"),fi("createdAt","desc")]})}).pipe(da()))).pipe(ce(z=>Ba(z)?.data)),E=Sn(L.map(z=>this.commonDbService.dbListener({feature:"allCommentViews",properties:T(I({},D),{firestoreQuery:[Zn(lt("metadata.apiKey","==",this.configService?.getApiKey()),lt("metadata.organizationId","==",s),lt("metadata.documentId","in",z),...p?[lt("metadata.veltFolderId","==",p)]:[])]})}).pipe(da()))).pipe(ce(z=>Ba(z)?.data))}return e?.filterGhostComments&&(C=C.pipe(he(L=>L?this.getGhostCommentAnnotationMap$().pipe(ce(z=>{if(z){let W={};return Object.values(L).forEach(J=>{J?.annotationId&&!z?.[J?.annotationId]&&(W[J?.annotationId]=J)}),W}return L})):se(L)))),Sn([C,E]).pipe(he(([L,z])=>!L||!z?se(null):se([L,z]).pipe(ce(([W,J])=>{let ue=Object.values(W||{});e?.locationIds?.length&&(ue=ue.filter(xe=>e.locationIds?.includes(xe.location?.id??"")));let ye={};ue.forEach(xe=>{ye[xe.annotationId]=xe});let Ae={};Object.entries(J||{}).forEach(([xe,Se])=>{ye[xe]&&(Se?.views?.[a]||(Ae[xe]=Se))});let He=ue.reduce((xe,Se)=>{let we=Se?.metadata?.clientDocumentId;return we&&(xe[we]||(xe[we]=[]),xe[we].push(Se)),xe},{}),Fe=Object.values(Ae).reduce((xe,Se)=>{let we=Se?.metadata?.clientDocumentId;return we&&(xe[we]||(xe[we]=[]),xe[we].push(Se)),xe},{});return r.reduce((xe,{clientDocumentId:Se})=>{xe?.data||(xe.data={});let we=He[Se]?.length??0,_e=Fe[Se]?.length??0;return xe.data[Se]={total:we,unread:_e},xe},{data:{}})}),kn(W=>(this.loggingService.catch("Error in CommentService getAnnotationsCount: ",W),se(null))))))})):se(null)),ce(t=>t||{data:null}),Et(mn))}catch(t){return this.loggingService.catch("Error in CommentService getAnnotationsCount: ",t),se({data:null})}}getAllCommentAnnotations({customClientDocumentId:e,params:t,excludeDomChanges:r,detectGhostComments:a,skipPositionCalculation:s,query:c,fromCommentSidebar:p,analytics:u,addFilterCommentsOnDomCheck:C}){this.loggingService.log("%c[WB] Calling FUNCTION: getAllCommentAnnotations","color: green;");let E,D,L;u?.enabled&&this.analyticsService.trackEvent(u?.eventName||Z.Events.Comments.GET_ALL_COMMENT_ANNOTATIONS_TRIGGERED_INTERNAL,u?.properties);try{if(e&&(L=`${En(e)}`),t&&typeof t=="object"){let z=Yo(t);D=z?.id,E=En(JSON.stringify(z))}}catch(z){this.loggingService.catch("Error in CommentService getAllCommentAnnotations: ",z)}return ei(this.afAuth).pipe(Le(z=>!!z),he(z=>this.isFeatureAllowed({firebaseUser:z,annotations:[],filteredAnnotations:[]})),he(z=>z.featureAllowed?this.iamService.isUserAllowed$().pipe(ce(W=>(z.featureAllowed=W,z))):se(z)),he(z=>z.featureAllowed?se(z).pipe(he(W=>this.docService.getDocumentPaths$().pipe(ce(J=>(this.documentPaths=J,W.documentPaths=J,W)))),he(W=>c?.documentIds?.length||L?this.getDataFromDocumentIds({documentIds:L?[L]:c?.documentIds?.map(J=>`${En(J)}`),organizationId:this.documentPaths?.organizationId,query:c}).pipe(ce(J=>({res:W,data:J}))):this.docService.getDocumentIds$().pipe(he(J=>{let ue=J?.length>0?J.map(ye=>ye.documentId):[this.documentPaths?.documentId??""];return this.getDataFromDocumentIds({documentIds:ue.length>0?ue:[L??""],organizationId:this.documentPaths?.organizationId,query:c}).pipe(ce(ye=>({res:W,data:ye})))}))),he(W=>W?.data?(W.res.annotations=W.data||[],se(W.res).pipe(he(J=>this.docService.getLocation$().pipe(ce(ue=>(J.location=ue,J)))),he(J=>this.docService.getLocations$().pipe(ce(ue=>(J.customLocations=ue,J)))),he(J=>this.docService.getExcludedLocationIds$().pipe(ce(ue=>(J.excludedLocationIds=ue,J)))),ce(J=>{if(J.filteredAnnotations=[],c)return J.filteredAnnotations=J.annotations?.slice(),J;if(L&&!E||p)return J.filteredAnnotations=J.annotations?.slice(),J?.excludedLocationIds?.length&&(J.filteredAnnotations=J.filteredAnnotations?.filter(ue=>ue?.location?.id?!J.excludedLocationIds.includes(ue.location.id):!0)),J;{let ue=[],ye=[];return E?(ue.push(E),D&&ye.push(D)):(ue.push(J?.location?.locationId),ue.push(...Object.values(J?.customLocations||[]).map(Ae=>Ae.locationId)),J?.location?.location?.id&&ye.push(J?.location?.location?.id),ye.push(...Object.values(J?.customLocations||{}).map(Ae=>Ae.location?.id).filter(Ae=>!!Ae))),J.filteredAnnotations=this.filterAnnotationsByLocationIds(J?.annotations,ue,ye),J?.excludedLocationIds?.length&&(J.filteredAnnotations=J.filteredAnnotations?.filter(Ae=>Ae?.location?.id?!J.excludedLocationIds.includes(Ae.location.id):!0)),J}}),he(J=>this.iamService.isUserAdmin$().pipe(ce(ue=>(ue||(J.filteredAnnotations=J.filteredAnnotations?.filter(ye=>ye?.iam?.accessMode!==io.PRIVATE)),J)))),he(J=>this.draftCommentAnnotationsByAnnotationId$.pipe(ce(ue=>(J.filteredAnnotations=J.filteredAnnotations?.filter(ye=>!ye.isDraft),ue&&J.filteredAnnotations.push(...Object.values(ue)),J)))),he(J=>r?se(J):J?.annotations?.length&&(!this.getPopoverMode()||this.getPopoverTriangleComponent())?this.domService.onWindowResize$().pipe(ce(()=>J)):se(J)),he(J=>r?se(J):this.addCommentMode$.pipe(he(ue=>ue&&!this.getChangeDetectionInCommentMode()?se(J):J?.annotations?.length&&(!this.getPopoverMode()||this.getPopoverTriangleComponent())?this.domService.onDomChange$("CommentService getAllCommentAnnotations").pipe(ce(()=>J)):se(J)))),ce(J=>{if(!s){(!this.getPopoverMode()||this.getPopoverTriangleComponent())&&(J.filteredAnnotations=J.filteredAnnotations?.map(ye=>{let Ae=Object.assign({},ye);return this.calculateCommentAnnotationPosition(Ae,a),Ae}));let ue={};J.filteredAnnotations?.forEach(ye=>{if(ye?.targetTextRange?.commonAncestorContainer){let Ae=this.domService.getElementFromXPath(ye?.targetTextRange?.commonAncestorContainer);ue[ye.annotationId]=!!Ae}}),J.textAnnotationsElementMap=ue}return J}),he(J=>J?.annotations?.length?this.viewsService.getCommentFeatureViews$().pipe(ce(ue=>(this.updateUnreadAnnotationsMap(J?.annotations,ue),J))):se(J)))):se(null))):se(null)),ce(z=>{try{return typeof z=="object"&&z?JSON.parse(JSON.stringify(z)):z}catch{return z}}),Et((z,W)=>mn(z?.filteredAnnotations,W?.filteredAnnotations)&&mn(z?.textAnnotationsElementMap,W?.textAnnotationsElementMap)),he(z=>z?z?.filteredAnnotations?se(z?.filteredAnnotations||[]):se([]):se(null)),he(z=>C?this.filterCommentsUsingSidebarSettings(z):se(z)))}getAllMultiThreadCommentAnnotations(e,t,r,a,s){this.loggingService.log("%c[WB] Calling FUNCTION: getAllMultiThreadCommentAnnotations","color: green;");let c,p;try{if(e&&(p=En(e)),t&&typeof t=="object"){let u=Yo(t);c=En(JSON.stringify(u))}}catch(u){this.loggingService.catch("Error in CommentService getAllMultiThreadCommentAnnotations: ",u)}return ei(this.afAuth).pipe(Le(u=>!!u),he(u=>this.isFeatureAllowed({firebaseUser:u,annotations:[],filteredAnnotations:[]})),he(u=>u.featureAllowed?this.iamService.isUserAllowed$().pipe(ce(C=>(u.featureAllowed=C,u))):se(u)),he(u=>u.featureAllowed?se(u).pipe(he(C=>this.docService.getDocumentPaths$().pipe(ce(E=>(this.documentPaths=E,C.documentPaths=E,C)))),he(C=>p?this.getMultiThreadDataFromDocumentIds([p]).pipe(ce(E=>({res:C,data:E}))):this.docService.getDocumentIds$().pipe(he(E=>{let D=E?.length>0?E.map(L=>L.documentId):[this.documentPaths?.documentId??""];return this.getMultiThreadDataFromDocumentIds(D.length>0?D:[`${p}`]).pipe(ce(L=>({res:C,data:L})))}))),he(({res:C,data:E})=>E?(C.annotations=E||[],se(C).pipe(he(D=>this.docService.getLocation$().pipe(ce(L=>(D.location=L,D)))),he(D=>this.docService.getLocations$().pipe(ce(L=>(D.customLocations=L,D)))),he(D=>this.docService.getExcludedLocationIds$().pipe(ce(L=>(D.excludedLocationIds=L,D)))),ce(D=>{if(D.filteredAnnotations=[],p&&!c)return D.filteredAnnotations=D.annotations?.slice(),D?.excludedLocationIds?.length&&(D.filteredAnnotations=D.filteredAnnotations?.filter(L=>L?.location?.id?!D.excludedLocationIds.includes(L.location.id):!0)),D;{let L=[],z=[];return c?L.push(c):(L.push(D?.location?.locationId),L.push(...Object.values(D?.customLocations||[]).map(W=>W.locationId)),D?.location?.location?.id&&z.push(D?.location?.location?.id),z.push(...Object.values(D?.customLocations||{}).map(W=>W.location?.id).filter(W=>!!W))),D.filteredAnnotations=this.filterAnnotationsByLocationIds(D?.annotations,L,z),D?.excludedLocationIds?.length&&(D.filteredAnnotations=D.filteredAnnotations?.filter(W=>W?.location?.id?!D.excludedLocationIds.includes(W.location.id):!0)),D}}),he(D=>this.draftMultiThreadCommentAnnotationsByAnnotationId$.pipe(ce(L=>(D.filteredAnnotations=D.filteredAnnotations?.filter(z=>!z.isDraft),L&&D.filteredAnnotations.push(...Object.values(L)),D)))),he(D=>r?se(D):D?.annotations?.length&&(!this.getPopoverMode()||this.getPopoverTriangleComponent())?this.domService.onWindowResize$().pipe(ce(()=>D)):se(D)),he(D=>r?se(D):this.addCommentMode$.pipe(he(L=>L&&!this.getChangeDetectionInCommentMode()?se(D):D?.annotations?.length&&(!this.getPopoverMode()||this.getPopoverTriangleComponent())?this.domService.onDomChange$("CommentService getAllMultiThreadCommentAnnotations").pipe(ce(()=>D)):se(D)))),ce(D=>(s||(!this.getPopoverMode()||this.getPopoverTriangleComponent())&&(D.filteredAnnotations=D.filteredAnnotations?.map(L=>{let z=Object.assign({},L);return this.calculateCommentAnnotationPosition(z,a),z})),D)),he(D=>D?.filteredAnnotations?se(D?.filteredAnnotations||[]):se([])))):se(null))):se(null)),Et(mn))}isFeatureAllowed(e){return this.configService.getConfig$().pipe(Le(t=>!!t),ce(t=>T(I({},e),{config:t})),he(t=>this.authService.getUser$().pipe(ce(r=>(this.user=r,T(I({},t),{user:r}))))),he(t=>ro(t.config,t.user,Re.COMMENT)?se(T(I({},t),{featureAllowed:!0})):(this.loggingService.warn("Comment feature is not allowed."),se(T(I({},t),{featureAllowed:!1})))),Et((t,r)=>t?.featureAllowed===r?.featureAllowed))}getDataFromDocuments(e){let{documentIds:t,organizationId:r,query:a}=e;if(!this.configService?.getApiKey())return se(null);if(t?.some(D=>!D)||!this.documentPaths)return se(null);let s,c,p,u=[];if(a)a?.folderId&&(s=Fi(a?.folderId)),c=a?.allDocuments,a?.locationId&&(u=[...u,a?.locationId]),a?.locationIds?.length&&(u=[...u,...a?.locationIds]),p=a?.statusIds;else{s=this.docService.getDocumentPaths()?.veltFolderId,c=this.docService.getDocumentPaths()?.allDocuments;let D=this.docService.getDocumentPaths()?.locationId;D&&(u=[...u,D])}let C=se([]),E={useCollectionGroup:!0,isCollection:!0,useQuery:!0};if(this.commonDbService.shouldUseFirestore()||(E.documentId=t?.length?t[0]:void 0,E.organizationId=this.documentPaths?.organizationId),c)C=this.commonDbService.dbListener({feature:"allComments",properties:T(I({},E),{firestoreQuery:[Zn(lt("metadata.apiKey","==",this.configService?.getApiKey()),lt("metadata.organizationId","==",r??this.documentPaths?.organizationId),...s?[lt("metadata.veltFolderId","==",s)]:[],...p?[lt("status.id","in",p)]:[],...u?.length?[lt("location.id","in",u)]:[]),fi("lastUpdated","desc"),fi("createdAt","desc")]})});else{let D=[];for(let L=0;L<(t?.length??0);L+=j.LISTENER_BATCH_SIZE)D.push(t?.slice(L,L+j.LISTENER_BATCH_SIZE)??[]);C=Sn(D.map(L=>this.commonDbService.dbListener({feature:"allComments",properties:T(I({},E),{firestoreQuery:[Zn(lt("metadata.apiKey","==",this.configService?.getApiKey()),lt("metadata.organizationId","==",r??this.documentPaths?.organizationId),lt("metadata.documentId","in",L),...p?[lt("status.id","in",p)]:[],...s?[lt("metadata.veltFolderId","==",s)]:[],...u?.length?[lt("location.id","in",u)]:[]),fi("lastUpdated","desc"),fi("createdAt","desc")]})}).pipe(da()))).pipe(ce(L=>Ba(JSON.parse(JSON.stringify(L)))))}return C.pipe(he(D=>D?.data?se(D).pipe(he(L=>this.commonDbUtilsService.mergeLocationMetadataWithData$({data:L,feature:"allComments"}).pipe(ce(z=>({data:Object.values(z?.data||{}).filter(W=>typeof W=="object"),operation:z?.operation})))),ce(({data:L,operation:z})=>{let W=L.reduce((J,ue)=>{let ye=ue.metadata?.documentId;return ye&&(J[ye]||(J[ye]=[]),J[ye].push(ue)),J},{});return{data:L,documentMap:W,operation:z}}),ce(({data:L,documentMap:z,operation:W})=>p?{data:L,documentMap:z,operation:W}:(L?.length&&(L?.forEach(J=>{this.sanitizeCommentAnnotation(J)}),this.setAnnotationIndex(L),this.updateAnnotationsForSelectAllContentMode(L),L.forEach(J=>{this.customFilterService.convertLegacyAnnotationStatus(J),this.customFilterService.convertLegacyPriority(J),this.customFilterService.convertLegacyCategory(J)})),{data:L,documentMap:z,operation:W})),kn(L=>(this.loggingService.catch("Error in CommentService getDataFromDocuments: ",L),se([]))),dn(({documentMap:L})=>{p||Object.entries(L??{}).forEach(([z,W])=>{this.setOriginalCommentAnnotationsByAnnotationId(JSON.parse(JSON.stringify(W)))})}),ce(({data:L,documentMap:z,operation:W})=>({data:this.filterUserDraftComments(L),documentMap:z,operation:W})),ce(({data:L,documentMap:z,operation:W})=>({data:this.removeDraftFlags(L),documentMap:z,operation:W})),he(({data:L,documentMap:z,operation:W})=>p?se({data:L,documentMap:z,operation:W}):this.mergeDraftAnnotations(L).pipe(ce(J=>({data:J,documentMap:z,operation:W})))),ce(({data:L,documentMap:z,operation:W})=>{if(!p)if(W?.type==="removed"){if(W?.ids?.length){let J=this.commentAnnotationById$.value??{};W?.ids?.forEach(ue=>{delete J?.[ue]}),this.commentAnnotationById$.next(J)}}else Object.entries(z??{}).length?Object.entries(z??{}).forEach(([ue,ye])=>{this.setCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:this.documentPaths?.organizationId,documentId:ue,annotations:ye})}):this.commentAnnotationById$.value||this.commentAnnotationById$.next({});return L})):se(null)))}fetchCommentAnnotations(e){return Q(this,null,function*(){try{let t=this.authService.getUser();if(!t)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??t?.clientOrganizationId,s=La(a??""),c=[];e?.allDocuments||(c=e?.documentIds?.map(z=>na(z??""))??this.docService.getDocumentIds()?.map(z=>z.documentId));let p=[];if(p.push(lt("metadata.organizationId","==",s)),p.push(lt("metadata.apiKey","==",r)),e?.folderId){let z=Fi(e?.folderId);p.push(lt("metadata.veltFolderId","==",z))}if(e?.locationId&&p.push(lt("location.id","==",e?.locationId)),c?.length&&p.push(lt("metadata.documentId","in",c)),e?.resolvedBy){if(e?.order==="asc")throw new Error("Order by resolvedBy is not supported in ascending order.");p.push(lt("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(lt("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(lt("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(lt("status.id","in",e?.statusIds))}let u=new Date().getTime();if(e?.createdAfter&&p.push(lt("createdAt",">=",e?.createdAfter)),e?.createdBefore&&p.push(lt("createdAt","<=",e?.createdBefore??u)),e?.updatedAfter&&p.push(lt("lastUpdated",">=",e?.updatedAfter??u)),e?.updatedBefore&&p.push(lt("lastUpdated","<=",e?.updatedBefore??u)),p.push(fi("lastUpdated",e?.order??"desc"),fi("createdAt",e?.order??"desc")),e?.pageToken){let z=yield Aj(e?.pageToken??"","veltencrypttoken","veltencrypttoken");p.push(fce(parseInt(z,10),"lastUpdated"))}let C=e?.pageSize??100;p.push(c0(C+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>C;E=E.slice(0,C);let L=E?.reduce((z,W)=>(z[W?.annotationId]=W,z),{});return L=yield this.commonDbUtilsService.formatResponse({feature:"allComments",data:L,shouldAwait:!0}),L=this.commonDbUtilsService.mergeUsersWithData({feature:"allComments",data:L}),{data:Object.values(L??{}),hasMore:D}}catch(t){throw this.loggingService.catch("Error in CommentService fetchCommentAnnotations:",t),t}})}filterUserDraftComments(e){let t=this.authService.getUser();return e.filter(r=>(r.comments=r?.comments?.filter(a=>a?.from?.userId===t?.userId||!a?.isDraft),!!r?.comments?.length))}removeDraftFlags(e){return e.forEach(t=>delete t.isDraft),e}mergeDraftAnnotations(e){return this.draftCommentAnnotationsByAnnotationId$.pipe(ce(t=>{let r=t||{};return e?.filter(a=>{r?.[a?.annotationId]&&delete r[a?.annotationId]}),r}),ce(t=>{if(t){let r=e.slice();return r.push(...Object.values(t)),r}return e}))}getDataFromDocumentIds({documentIds:e,organizationId:t,query:r}){return this.getDataFromDocuments({documentIds:e,organizationId:t,query:r})}getMultiThreadDataFromDocumentIds(e){return this.getMultiThreadDataFromDocuments({documentIds:e})}getMultiThreadDataFromDocuments(e){if(this.configService?.getApiKey()){let{documentIds:t}=e;if(t?.some(p=>!p)||!this.documentPaths)return se(null);let r=this.docService.getDocumentPaths()?.veltFolderId,a=this.docService.getDocumentPaths()?.allDocuments,s=se([]),c={useCollectionGroup:!0,isCollection:!0,useQuery:!0};if(this.commonDbService.shouldUseFirestore()||(c.documentId=t?.length?t[0]:void 0,c.organizationId=this.documentPaths?.organizationId),r&&a)s=this.commonDbService.dbListener({feature:"allMultiThreads",properties:T(I({},c),{firestoreQuery:[Zn(lt("metadata.apiKey","==",this.configService?.getApiKey()),lt("metadata.organizationId","==",this.documentPaths?.organizationId),lt("metadata.veltFolderId","==",r))]})});else{let p=[];for(let u=0;u<(t?.length??0);u+=j.LISTENER_BATCH_SIZE)p.push(t?.slice(u,u+j.LISTENER_BATCH_SIZE)??[]);s=Sn(p.map(u=>this.commonDbService.dbListener({feature:"allMultiThreads",properties:T(I({},c),{firestoreQuery:[Zn(lt("metadata.apiKey","==",this.configService?.getApiKey()),lt("metadata.organizationId","==",this.documentPaths?.organizationId),lt("metadata.documentId","in",u),...r?[lt("metadata.veltFolderId","==",r)]:[])]})}).pipe(da()))).pipe(ce(u=>Ba(u)))}return s.pipe(he(p=>p?.data?se(p).pipe(ce(u=>({data:u?.data,operation:u?.operation})),ce(({data:u,operation:C})=>{let E=[];return u&&(E=Object.values(u??{}).filter(D=>typeof D=="object")),{data:E,operation:C}}),kn(u=>(this.loggingService.catch("Error in CommentService getMultiThreadDataFromDocumentId: ",u),se({data:[],operation:null}))),ce(({data:u,operation:C})=>{u.forEach(D=>{delete D.isDraft});let E=u.reduce((D,L)=>{let z=L.metadata?.documentId;return z&&(D[z]||(D[z]=[]),D[z].push(L)),D},{});return{data:u,documentMap:E,operation:C}}),he(({data:u,documentMap:C,operation:E})=>{let D=[];return this.commentAnnotationById$.pipe(he(()=>this.domService.getSelectedAnnotationsMap$().pipe(ce(L=>({selectedAnnotationsMap:L})))),ce(({selectedAnnotationsMap:L})=>{let z={};return Object.keys(C??{}).forEach(W=>{let J=this.getCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:this.documentPaths?.organizationId,documentId:W});J&&J?.forEach(ue=>{z[ue?.annotationId]=ue})}),D=u.filter(W=>{let J=!1;if(W?.commentAnnotations){for(let ue in W?.commentAnnotations)if(z?.[ue]&&z?.[ue]?.status?.id!==this.customFilterService.resolvedStatus.id){J=!0;break}}return J}),D.forEach(W=>{Object.keys(W?.commentAnnotations||{}).forEach(J=>{W.commentAnnotationsMap||(W.commentAnnotationsMap={}),W.commentAnnotationsMap[J]=z?.[J]})}),{data:D,operation:E}}))}),he(({data:u,operation:C})=>this.draftMultiThreadCommentAnnotationsByAnnotationId$.pipe(ce(E=>{let D=E||{};return u?.filter(L=>{D?.[L?.annotationId]&&delete D[L?.annotationId]}),D}),ce(E=>{if(E){let D=u.slice();return D.push(...Object.values(E)),{data:D,operation:C}}return{data:u,operation:C}}))),ce(({data:u,operation:C})=>{let E=u.reduce((D,L)=>{let z=L.metadata?.documentId;return z&&(D[z]||(D[z]=[]),D[z].push(L)),D},{});if(C?.type==="removed"){if(C?.ids?.length){let D=this.multiThreadCommentAnnotationById$.value;C?.ids?.forEach(L=>{delete D?.[L]}),this.multiThreadCommentAnnotationById$.next(D)}}else Object.keys(E??{}).forEach(D=>{this.setMultiThreadCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:this.documentPaths?.organizationId,documentId:D,annotations:E[D]})});return u})):se(null)))}else return se(null)}updateUnreadAnnotationsMap(e,t){try{let r=new Date(j.UNREAD_COMMENTS_CHECK_FROM_DATE)?.getTime(),a=e.filter(s=>s?.lastUpdated>r);if(t){let s={},c=!1;a.forEach(p=>{let u=0,C=t?.[p?.annotationId];if(C){let E=C?.comments;E&&p?.comments?.forEach(D=>{!E?.[D?.commentId]?.views?.[this.user?.userSnippylyId]&&this.user?.userSnippylyId!==D?.from?.userSnippylyId&&u++})}u?u!==s?.[p?.annotationId]&&(s[p?.annotationId]=u,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(t=>{if(t?.selectAllContent&&t?.targetElementId){let r=oa(t.targetElementId,["id","data-id"]);if(r){let a=r.textContent;a&&(t.targetTextRange={commonAncestorContainer:this.domService.getXPath(r),text:a,occurrence:1},delete t?.targetElement)}}})}catch(t){this.loggingService.catch("Error in CommentService updateAnnotationsForSelectAllContentMode:",t)}}setCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:e,documentId:t,annotations:r,queryHash:a}){try{if(t){e||(e=j.NO_ORGANIZATION_ID),a||(a=j.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:t}){try{return this.commentAnnotationById$.pipe(ce(()=>this.getCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:e,documentId:t})))}catch(r){return this.loggingService.catch("Error in CommentService getCommentAnnotationsByOrganizationIdAndDocumentId$:",r),se([])}}getCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:e,documentId:t}){try{let r=null;this.commentAnnotationById$.value&&(r={},Object.values(this.commentAnnotationById$.value).forEach(s=>{s?.metadata?.documentId==t&&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===t&&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),[]}}getCommentAnnotationsByDocumentId$({clientDocumentId:e,documentId:t}){try{return e&&!t&&(t=this.docService.generateDocumentId(e)),t?this.docService.getDocumentPaths$().pipe(he(r=>this.getCommentAnnotationsByOrganizationIdAndDocumentId$({organizationId:r?.organizationId,documentId:t}))):se(null)}catch(r){return this.loggingService.catch("Error in CommentService getCommentAnnotationsByDocumentId$:",r),se(null)}}getCommentAnnotationsOnCurrentOrganizationAndDocument$(){return this.docService.getDocumentPaths$().pipe(he(e=>e?.documentId?this.getCommentAnnotationsByOrganizationIdAndDocumentId$({organizationId:e.organizationId,documentId:e.documentId}):se([])))}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 t={};e?.forEach(r=>{r?.annotationId&&(t[r?.annotationId]=r)}),this.originalCommentAnnotationsByDocumentId$.next(I(I({},this.originalCommentAnnotationsByDocumentId$.value),t))}catch(t){this.loggingService.catch("Error in CommentService setOriginalCommentAnnotationsByAnnotationId:",t)}}setMultiThreadCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:e,documentId:t,annotations:r,queryHash:a}){try{if(t){e||(e=j.NO_ORGANIZATION_ID),a||(a=j.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:t}){return this.multiThreadCommentAnnotationById$.pipe(ce(()=>this.getMultiThreadCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:e,documentId:t})))}getMultiThreadCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:e,documentId:t}){try{let r={};Object.values(this.multiThreadCommentAnnotationById$.value??{}).forEach(s=>{s?.metadata?.documentId==t&&s?.metadata?.organizationId==e&&(r[s?.annotationId]=s)});let a=this.draftMultiThreadCommentAnnotationsByAnnotationId$.value;return a&&Object.values(a??{}).forEach(s=>{s?.metadata?.documentId===t&&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(he(e=>e?.documentId?this.getMultiThreadCommentAnnotationsByOrganizationIdAndDocumentId$({organizationId:e.organizationId,documentId:e.documentId}):se([])))}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(he(e=>this.docService.getLocations$().pipe(ce(t=>({location:e,locations:t})))),ce(e=>{let t=[];return t.push(e?.location?.locationId),t.push(...Object.values(e.locations||[]).map(r=>r.locationId)),t||[]}))}filterAnnotationsByLocationIds(e,t,r){try{return e.filter(a=>t.includes(a.locationId)||r?.includes(a?.location?.id)||t?.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((t,r)=>{t?.annotationId&&(t.annotationIndex=r+1)})}catch(t){this.loggingService.catch("Error in CommentService setAnnotationIndex:",t)}}calculateCommentAnnotationPosition(e,t){try{if(e.multiThreadAnnotationId)return;if(e.targetElementId){let r=oa(e.targetElementId,["id","data-id"]);if(r&&this.domService.isElementVisible(r)){let a=r.getAttribute(j.ATTRIBUTES.VELT_COMMENT_TYPE),s=!0;if(a)switch(a){case"popover":s=!0;break;default:s=!1;break}else{let c=document.querySelector(`${j.TAGS.VELT_INLINE_COMMENTS_SECTION}[${j.ATTRIBUTES.TARGET_INLINE_COMMENT_ELEMENT_ID}="${e.targetElementId}"], ${j.TAGS.VELT_INLINE_COMMENTS_SECTION}[${j.ATTRIBUTES.TARGET_COMMENT_ELEMENT_ID}="${e.targetElementId}"], ${j.TAGS.VELT_INLINE_COMMENTS_SECTION}[${j.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()===$P.DYNAMIC_ID&&(!a||!this.domService.isElementVisible(a))&&(r=e.targetElement?.fXpath,r&&(a=this.domService.getElementFromXPath(r)))),(!a||!this.domService.isElementVisible(a))&&t&&(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(!nh({location:p?.location,locationId:p?.locationId},{location:e?.location,locationId:e?.locationId})){let u=this.docService.getAdditionLocationFromElement(a),C=u?this.docService.genarateLocationId(u):void 0;e?.location?.id&&e?.location?.id===u?.id||C&&C===e?.locationId?c=!1:c=!0}}if(c&&(e.ghostComment=null),!c&&a&&Ao(a)&&!a?.closest(".cdk-overlay-container")&&a?.getBoundingClientRect()){let u=this.popoverMode$?.value?0:e.targetElement?.topPercentage,C=this.popoverMode$?.value?100:e.targetElement?.leftPercentage,{height:E,width:D}=Wp(a);e.position={top:E*(u||0)/100,left:D*(C||0)/100};let L=window.getComputedStyle(a).transform;if(L&&L!=="none")try{let z=new DOMMatrixReadOnly(L),W=Math.sqrt(z.a*z.a+z.b*z.b)||1,J=Math.sqrt(z.c*z.c+z.d*z.d)||1;(Math.abs(W-1)>.01||Math.abs(J-1)>.01)&&(e.position.parentScaleX=W,e.position.parentScaleY=J)}catch{}if(this.transformContext$.value){let{containerSelector:z,transforms:W}=this.transformContext$.value,J=document.querySelector(z);J&&J.contains(a)&&(e.position.transformContext=W)}}!c&&t&&!e?.position&&!e?.ghostComment&&(e.ghostComment={},this.setGhostCommentMessage(e),e.ghostComment.targetElement=e.targetElement)}}t&&(e.ghostComment?this.addAnnotationToGhostCommentAnnotationMap(e):this.removeAnnotationFromGhostCommentAnnotationMap(e))}catch(r){this.loggingService.catch("Error in CommentService calculateCommentAnnotationPosition:",r)}}addComment(e,t,r,a,s,c=[],p,u,C,E,D,L,z,W,J,ue,ye,Ae,He,Fe,xe,Se,we,_e){this.loggingService.log("%c[WB] Calling FUNCTION: addComment","color: green;");try{let fe=this.authService.getUser();if(fe)if(fe.isReadOnly||fe.isAnonymous)this.loggingService.catch("Anonymous/Readonly users cannot add comments.");else{let Oe=new Bo;ye&&(Oe=I(I({},Oe),ye)),Oe.comments=[],ye?.comments?.length&&(Oe.comments=ye.comments.map(Zt=>{let Yt=new Nc;return Yt=I(I({},Yt),Zt),Yt.from=fe,Yt.lastUpdated=new Date,Yt.createdAt=this.timestamp,Yt})),Oe.from=fe,Oe.color=Oe?.color||j.DEFAULT_ANNOTATION_COLOR,Oe.lastUpdated=this.timestamp,Oe.createdAt=this.timestamp,Oe.sourceId=J,Oe.assignedTo=ye?.assignedTo||ue,Oe.customList=ye?.customList||[],Se&&(Oe.targetElementId=Se);let{topPositionX:Ne,topPositionY:Ct}=this.domService.getTopLeftPosition();Oe.positionX=Ne,Oe.positionY=Ct;let On=this.domService.getCurrentWindowSizeValue();if(Oe.screenWidth=On.screenWidth,Oe.screenHeight=On.screenHeight,Oe.screenScrollHeight=On.screenScrollHeight,Oe.taggedElementPath="",e&&(Oe.targetElement=this.domService.getTargetElementForCursorPosition(e,!0,!0,!0,Zt=>{if(this.getSvgAsImg()){let Yt=Zt?.closest(`[${j.ATTRIBUTES.VELT_COMMENT_CONTAINER}]`);Yt&&Yt instanceof HTMLElement&&(Zt=Yt)}if(this.getPopoverMode()){let Yt=Zt?.closest(`[${j.ATTRIBUTES.VELT_TARGET_COMMENT_ELEMENT_ID}]`);if(Yt&&Yt instanceof HTMLElement)return Yt}return Zt}),this.getCommentToNearestAllowedElement()&&Oe.targetElement?.xpath)){let Zt=this.domService.getElementFromXPath(Oe.targetElement.xpath);if(Zt&&!this.isElementInsideAllowedElements(Zt)){let Yt=this.getNearestAllowedElement(Zt);if(Yt)Oe.targetElement.xpath=this.domService.getXPath(Yt),Oe.targetElement.fXpath=this.domService.getXPath(Yt,!0),Oe.targetElement.cfXpath=this.domService.getXPath(Yt,!0,!0);else return}}if(t&&(Oe.targetTextRange=t),Oe?.targetElement?.xpath){let Zt=this.domService.getXPath(Oe.targetElement.xpath);if(Zt){let Yt=Zt.iterateNext();Yt&&(Ao(Yt)||(Oe.targetElement=null))}}this.customFilterService.defaultStatus&&!ye?.status&&(Oe.status=this.customFilterService.defaultStatus),Oe.pageInfo=Oi(),Oe.pageInfo&&(Oe.pageInfo.screenWidth=this.domService.getCurrentWindowSizeValue()?.screenWidth);let yt=this.docService.getClientDocumentId(),Rt=this.docService.getLocation()?.location;if(He&&(Oe.context=He&&Oc(He),Oe.contextId=this.generateContextId(Oe.context)),this.commentContextProvider!==null){let Zt=this.commentContextProvider(yt,Rt);Zt&&(Oe.context=Zt&&Oc(Zt),Oe.contextId=this.generateContextId(Oe.context))}if(a){Oe.sourceId=a?.sourceId;let Zt=a?.targetElement,Yt=a?.commentData;if(Zt?.targetText)Oe.targetTextRange={commonAncestorContainer:"/html/body",text:Zt.targetText,occurrence:Zt?.occurrence||1};else if(Zt?.elementId)if(Oe.targetElementId=Zt.elementId,Zt?.selectAllContent)Oe.selectAllContent=!!Zt?.selectAllContent;else{let Xt=oa(Zt.elementId,["id","data-id"]);Xt?Oe.targetElement={xpath:this.domService.getXPath(Xt),fXpath:this.domService.getXPath(Xt,!0),cfXpath:this.domService.getXPath(Xt,!0,!0),topPercentage:50,leftPercentage:90}:Oe.targetElement={xpath:"/html/body",fXpath:"/html/body",cfXpath:"/html/body",topPercentage:50,leftPercentage:90}}a?.status&&(Oe.status=a.status),a?.context&&(Oe.context=a.context?Oc(a.context):a.context,Oe.contextId=this.generateContextId(Oe.context)),Oe.comments||(Oe.comments=[]);let Ai=this.authService.getUser();Yt?.forEach(Xt=>{let Qn=new Nc;Qn.commentText=Xt.commentText,Qn.commentHtml=Xt.commentHtml,Qn.replaceContentHtml=Xt.replaceContentHtml,Qn.replaceContentText=Xt.replaceContentText,Qn.from=Ai,Oe.comments.push(Qn)})}if(s&&(Oe.isPageAnnotation=!0),c?.length&&(Oe.comments=c),p&&(Oe.commentType="chart",Oe.metadata=p),C?.sourceId&&(Oe.sourceId=C.sourceId),Oe?.targetElement?.xpath&&!C){let Zt=this.domService.getElementFromXPath(Oe.targetElement.xpath);Zt&&(C=this.getInlineCommentSectionConfig(Zt))}C?.targetInlineCommentElementId&&(Oe.targetInlineCommentElementId=C?.targetInlineCommentElementId,Oe.targetElementId=C.targetInlineCommentElementId,C?.config?.id&&(Oe.inlineCommentSectionConfig=C?.config));let Bt=!Oe?.comments?.length,In=!!(a?.openComment===!1||Fe);this.getPrivateCommentMode()&&(Oe?.iam||(Oe.iam=new yb),Oe.iam.accessMode=io.PRIVATE),E&&(Oe.context=E.context?Oc(E.context):E.context,Oe.commentType="manual",delete Oe.targetElement,Oe.contextId=this.generateContextId(Oe.context)),D&&(Oe.targetElementId=D.targetElementId,Oe.targetElement=D.targetElement),this.saveCommentToDb(Oe,r,Bt,In,u,L,z,Ae,W,xe,we,_e)}}catch(fe){this.loggingService.catch("Error in CommentService addComment: ",fe)}}setLocationToCommentAnnotation(e){try{let t=this.docService.getLocation();t?(e.locationId=t.locationId,e.location=t.location):(delete e.locationId,delete e.location);try{let r;e.targetElement?.xpath?r=this.domService.getElementFromXPath(e.targetElement.xpath):e.targetElementId?r=oa(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({location:a,source:"internal"});s?.[0]&&(e.locationId=s[0].locationId,e.location=s[0].location)}}catch{}}catch(t){this.loggingService.catch("Error in CommentService setLocationToCommentAnnotation:",t)}}getElementForCommentAnnotation(e){try{let t;return e.targetElement?.xpath?t=this.domService.getElementFromXPath(e.targetElement.xpath):e.targetElementId?t=oa(e.targetElementId,["id","data-id"]):e.targetTextRange?.commonAncestorContainer&&(t=this.domService.getElementFromXPath(e.targetTextRange.commonAncestorContainer)),t}catch(t){return this.loggingService.catch("Error in CommentService getElementForCommentAnnotation: ",t),null}}saveCommentToDb(e,t,r=!1,a=!1,s,c,p,u,C,E,D,L){this.loggingService.log("%c[WB] Calling FUNCTION: saveCommentToDb","color: green;");try{this.authService.getUser()&&this.authService.isFeatureAllowed(Re.COMMENT)&&this.docService.getDocumentPaths$().pipe(Le(z=>!!z),st(1),he(z=>(this.documentPaths=z,this.loggingService.log(this.documentPaths),this.databaseService.getDb().pipe(Le(W=>!!W),st(1),he(W=>Q(this,null,function*(){if(this.documentPaths?.comment){e.annotationId=this.commonDbService.generateDocumentId();let J=this.docService.getClientDocumentId(),ue=this.docService.getLocation()?.location;if(p)e.multiThreadAnnotationId=p;else if(this.getMultiThread()){let we=Ad();e.targetElementId&&(we=Ad(e.targetElementId),e?.location?.id?we=Ad([e?.location?.id,e.targetElementId]):e?.locationId&&(we=Ad([e?.locationId+"",e.targetElementId]))),e.multiThreadAnnotationId=we}let ye={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&&Oc(we),e.contextId=this.generateContextId(e.context),we?.commentType==="manual"&&(e.commentType="manual",delete e.targetElement),e?.annotationId&&this.updateCommentAnnotationContext(e.annotationId,we)},documentId:J,location:ue,annotation:Gn(e),targetAnnotationId:e?.annotationId,targetCommentId:e?.comments?.length?e?.comments[0]?.commentId:void 0};e?.targetElement?.xpath?ye.elementRef={xpath:e.targetElement.xpath}:ye.elementRef=void 0,this.commentAddedEmitter!==null&&"emit"in this.commentAddedEmitter&&this.commentAddedEmitter.emit(ye),this.commentAdded$.next(ye),C&&C(ye);let Ae=yield this.commentActionsService?.getAddCommentAnnotationEventFromCommentAddEventData(ye);Ae&&this.commentActionsService?.triggerAddCommentAnnotationEvent(Ae),this.setLocationToCommentAnnotation(e);let He=this.getElementForCommentAnnotation(e),Fe=this.docService.getBaseMetadata("comment",{element:He,multiThreadAnnotationId:e.multiThreadAnnotationId});if(!Fe?.apiKey)return;if(e?.metadata||(e.metadata={}),e.metadata=I(I({},e.metadata),Fe),E&&(e.metadata=I(I({},e.metadata),E)),s&&typeof s=="object"&&(e.locationId=u||this.docService.genarateLocationId(s),e.location=s,L||this.docService.addLocation({location:s})),r)window.localStorage.setItem(j.LOCAL_STORAGE.SNIPPYLY_QUEUED_COMMENT,JSON.stringify(e));else{let we=window.localStorage.getItem(j.LOCAL_STORAGE.SNIPPYLY_QUEUED_COMMENT);we&&JSON.parse(we).annotationId===e.annotationId&&e.comments!==void 0&&e.comments.length>0&&window.localStorage.removeItem(j.LOCAL_STORAGE.SNIPPYLY_QUEUED_COMMENT)}e.pageInfo&&(e.pageInfo.commentUrl=this.generateCommentUrl(e));let xe=e.comments,Se=JSON.parse(JSON.stringify(e));if(Se.position=null,t){Se.targetElement=null,Se.targetTextRange=null;let we={annotationId:e.multiThreadAnnotationId?e.multiThreadAnnotationId:e.annotationId,type:e.multiThreadAnnotationId?Re.MULTI_THREAD:Re.COMMENT},_e=yield this.areaService.generateAreaAnnotationId();Se.areaAnnotationId=_e;let fe=this.areaService.addArea(void 0,t,we,_e,{locationId:Se.locationId,location:Se.location});fe&&(Se.metadata=I(I({},Se.metadata),fe?.metadata||{}))}!a&&!Se?.targetInlineCommentElementId&&!Se?.isPageAnnotation&&this.domService.toggleAnnotationSelection(Se,c),e.targetTextRange&&sessionStorage.setItem(j.SESSION_STORAGE.SNIPPYLY_AUTO_SELECT_ANNOTATION_ID,e?.multiThreadAnnotationId?e?.multiThreadAnnotationId:e.annotationId),Se?.comments?.length?this.analyticsService.trackEvent(Z.Events.Comments.COMMENT_ADDED,{annotationId:e.annotationId,commentThreadId:Se?.comments[0]?.commentId,commentType:this.getCommentType(Se),commentMode:this.getCommentMode(),source:D??"internal"}):this.analyticsService.trackEvent(Z.Events.Comments.COMMENT_DRAFT_ADDED,{annotationId:e.annotationId,commentType:this.getCommentType(Se),commentMode:this.getCommentMode()}),Se?.comments?.length?Se.comments=[]:Se.isDraft=!0,Se?.multiThreadAnnotationId&&this.saveMultiThreadCommentAnnotation(Se),Se?.context&&(Se.contextId=this.generateContextId(Se.context)),xe?.length&&!Se?.isDraft?this.saveComment(Se,{type:$t.NEWLY_ADDED,updatedComment:xe[0]}):(xe?.length&&(Se.comments=xe),this.draftCommentAnnotationsByAnnotationId$.next(T(I({},this.draftCommentAnnotationsByAnnotationId$.value),{[e.annotationId]:Se})))}})))))).subscribe(()=>{},z=>{this.loggingService.catch("Error in CommentService saveCommentToDb subscription: ",z)})}catch(z){this.loggingService.catch("Error in CommentService saveCommentToDb: ",z)}}saveMultiThreadCommentAnnotation(e){return Q(this,null,function*(){try{if(e?.multiThreadAnnotationId){let t=this.docService.getDocumentPaths();if(this.databaseService.getDbValue()&&t?.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:t?.organizationId,documentId:t?.documentId})?.find(s=>s.annotationId===e.multiThreadAnnotationId);if(a||(a=yield this.commonDbService?.getData({feature:"multiThread",properties:{documentId:t?.documentId??"",organizationId:t?.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 C=this.docService.getBaseMetadata();r.metadata=I(I({},r?.metadata),C)}let{documentId:p,organizationId:u}=r?.metadata||{};yield this.commonDbService.updateData({feature:"multiThread",properties:{id:r.annotationId,documentId:p,organizationId:u},data:JSON.parse(JSON.stringify(r)),callback:()=>{let C=this.draftMultiThreadCommentAnnotationsByAnnotationId$.value;C[e.annotationId]&&(delete C[e.annotationId],this.draftMultiThreadCommentAnnotationsByAnnotationId$.next(C))}})}return r}}return null}catch(t){return this.loggingService.catch("Error in CommentService saveMultiThreadCommentAnnotation: ",t),null}})}setCommentCategory(e){return Q(this,null,function*(){try{if(e?.comments?.length){let t=e.comments[0].commentText?.trim();if(t){let r=yield this.getCommentCategory(t).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:u}=this.getDocumentIdAndOrganizationIdFromCommentAnnotation(c);yield this.commonDbService.updateData({feature:"comment",properties:{id:e.annotationId,documentId:p,organizationId:u,metadata:{apiKey:this.configService.getApiKey(),organizationId:u,veltFolderId:c?.metadata?.veltFolderId,documentId:p}},data:JSON.parse(JSON.stringify(c))})}}}}}}catch(t){this.loggingService.catch("Error in CommentService setCommentCategory: ",t)}})}getCommentCategory(e){try{let t=br(this.functions,Er({url:oi.cloudFunction.chatgptCompletion,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:12e5}),a=[{role:"system",content:`Identify category of this sentence from these categories, ${Object.keys(this.customCategoryMap)?.join(", ")}:`},{role:"user",content:e}];return Zi(t({messages:a,apiKey:this.configService.getApiKey(),sdkVersion:ia(),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(t){return this.loggingService.catch("Error in CommentService getCommentCategory: ",t),se(void 0)}}updateCommentAnnotationContext(e,t,r){return Q(this,null,function*(){try{this.analyticsService.trackEvent(Z.Events.Comments.COMMENT_UPDATE_CONTEXT_TRIGGERED,{annotationId:e,context:t,merge:r?.merge});let a=this.authService.getUser(),s=this.docService.getDocumentPaths();if(a&&s?.comment&&e){let c=this.getAnnotationById(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=t,u=JSON.parse(JSON.stringify(c.context||{}));r?.merge&&(p=I(I({},u),t));let C={context:JSON.parse(JSON.stringify(p||{}))};if(C?.context?.commentType==="manual"&&(C.commentType="manual",C.targetElement=null),c.context=C.context?Oc(C.context):C.context,c.contextId=this.generateContextId(c.context),wi(u,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,metadata:{apiKey:this.configService.getApiKey(),organizationId:D,veltFolderId:c?.metadata?.veltFolderId,documentId:E}},data:JSON.parse(JSON.stringify(c)),callback:()=>{this.analyticsService.trackEvent(Z.Events.Comments.COMMENT_UPDATE_CONTEXT_SUCCESS,{annotationId:e,context:C?.context,merge:r?.merge})}})}}else return this.analyticsService.trackEvent(Z.Events.Comments.COMMENT_UPDATE_CONTEXT_FAILED,{annotationId:e,context:t,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,t,r,a,s){this.loggingService.log("%c[WB] Calling FUNCTION: updateComment","color: green;");try{if(this.authService.getUser()&&this.authService.isFeatureAllowed(Re.COMMENT)){if(t&&this.setLocationToCommentAnnotation(e),e?.targetElement?.xpath){let c=this.domService.getXPath(e.targetElement.xpath);if(c){let p=c.iterateNext();p&&(Ao(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 C=this.docService.getBaseMetadata();c.metadata=I(I({},c?.metadata),C)}let{documentId:p,organizationId:u}=c?.metadata||{};r?this.commonDbService.updateData({feature:"multiThread",properties:{id:c.annotationId,documentId:p,organizationId:u},data:JSON.parse(JSON.stringify(c))}):this.commonDbService.setData({feature:"multiThread",properties:{id:c.annotationId,documentId:p,organizationId:u},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(j.LOCAL_STORAGE.SNIPPYLY_QUEUED_COMMENT);if(p&&JSON.parse(p).annotationId===c.annotationId&&window.localStorage.removeItem(j.LOCAL_STORAGE.SNIPPYLY_QUEUED_COMMENT),c?.multiThreadAnnotationId&&!s&&this.saveMultiThreadCommentAnnotation(c).then(u=>{}),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:u,organizationId:C}=c?.metadata||{},E=a?I({annotationData:a?.commentAnnotation,targetAnnotationData:a?.targetComment,actionType:a?.actionType,notificationSource:"comment"},a?.otherFields||{}):null;this.viewsService.updateCommentAnnotationViews(c),this.commonDbService.setData({feature:"comment",properties:{id:c.annotationId,documentId:u,organizationId:C,metadata:{apiKey:this.configService.getApiKey(),organizationId:C,veltFolderId:c?.metadata?.veltFolderId,documentId:u}},extraData:E,data:JSON.parse(JSON.stringify(c)),callback:D=>{a&&!D?.firestoreAvailable&&this.updateNotificationsDatabase(a.commentAnnotation,a.targetComment,a.actionType,a.otherFields||{})}})}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(t){return this.loggingService.catch("Error in CommentService getDocumentIdAndOrganizationIdFromCommentAnnotation: ",t),{}}}getDocumentIdAndOrganizationIdFromMultiThreadCommentAnnotation(e){try{return{documentId:e?.metadata?.documentId,organizationId:e?.metadata?.organizationId}}catch(t){return this.loggingService.catch("Error in CommentService getDocumentIdAndOrganizationIdFromMultiThreadCommentAnnotation: ",t),{}}}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((t,r)=>Q(this,null,function*(){try{let a=this.domService.getSelectedAnnotationsMap(),s=this.authService.getUser(),c=[];Object.keys(a).forEach(p=>{let u=a[p];["tag","recorder","rewriter","arrow","area","multiThread"].includes(u.type)||s&&u.from&&(s?.isAdmin||u.from.userId===s.userId)&&c.push(u)}),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(Sa,{panelClass:"velt-mat-dialog-container",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(st(1)).subscribe(p=>{try{p?(c.forEach(u=>Q(this,null,function*(){yield this.deleteCommentPinAnnotation(u)})),setTimeout(()=>{document.querySelectorAll(`[${j.SNIPPYLY_HIGHLIGHT}]`).forEach(C=>{this.domService.removeHighlightFromElement(C)}),t()},100)):t()}catch(u){r(u)}},p=>{r(p)})):t(),this.domService.resetSelectedAnnotationsMap(!0,"comment")}catch(a){this.loggingService.catch("Error in CommentService deleteCommentPinAnnotations: ",a),r(a)}}))}deleteCommentPinAnnotation(e,t){return Q(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((t||e.comments?.length)&&this.updateNotificationsDatabase(e,null,$t.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(j.LOCAL_STORAGE.SNIPPYLY_QUEUED_COMMENT);r&&JSON.parse(r).annotationId===e.annotationId&&window.localStorage.removeItem(j.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,metadata:{apiKey:this.configService.getApiKey(),organizationId:c,veltFolderId:e?.metadata?.veltFolderId,documentId:s}}})}else return Promise.resolve();return Promise.resolve()}catch(r){return this.loggingService.catch("Error in CommentService deleteCommentPinAnnotation: ",r),Promise.resolve()}})}removeCommentAnnotationFromMultiThread(e){return Q(this,null,function*(){try{let t=e?.multiThreadAnnotationId;if(t){let r=this.docService.getDocumentPaths(),a=this.getMultiThreadAnnotationById(t);if(!a){let u=e?.metadata?.documentId||r?.documentId,C=e?.metadata?.organizationId||r?.organizationId;a=yield this.commonDbService?.getData({feature:"multiThread",properties:{documentId:u,organizationId:C,id:t}})}let s=this.draftMultiThreadCommentAnnotationsByAnnotationId$.value?.[t];a&&delete a?.commentAnnotations?.[e.annotationId],s&&(delete s?.commentAnnotations?.[e.annotationId],Object.keys(s?.commentAnnotations||{}).length===0&&(delete this.draftMultiThreadCommentAnnotationsByAnnotationId$.value?.[t],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(t){this.loggingService.catch("Error in CommentService removeCommentAnnotationFromMultiThread: ",t)}})}getAnnotationById(e,t){try{let r=this.commentAnnotationById$.value?.[e]||this.draftCommentAnnotationsByAnnotationId$?.value?.[e];if(r){let{documentId:a,organizationId:s}=t||{};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 t=this.commentAnnotationById$.value?.[e];if(t)return t.metadata}catch(t){this.loggingService.catch("Error in CommentService getBaseMetadataFromCommentAnnotationId: ",t)}}getMultiThreadAnnotationById(e,t){try{let r=this.multiThreadCommentAnnotationById$.value?.[e]||this.draftMultiThreadCommentAnnotationsByAnnotationId$?.value?.[e];if(r){let{documentId:a,organizationId:s}=t||{};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 t=this.multiThreadCommentAnnotationById$.value?.[e];if(t)return t.metadata}catch(t){this.loggingService.catch("Error in CommentService getBaseMetadataFromMultiThreadCommentAnnotationId: ",t)}}getElementRefByAnnotationId(e){try{let t=this.getAnnotationById(e);if(t){let r=t?.targetElement?.xpath;if(r)return{xpath:r}}return}catch(t){this.loggingService.catch("Error in CommentService getElementRefByAnnotationId: ",t);return}}scrollToCommentByAnnotationId(e){try{let t=this.getAnnotationById(e),r=document.getElementById(`comment-pin-container-${e}`);r||(r=document.querySelector(`[data-velt-id='${e}']`)),r||(r=document.querySelector(`${j.TAGS.VELT_COMMENT_TEXT}[${j.ATTRIBUTES.ANNOTATION_ID}="${e}"]`)),r&&(r.scrollIntoView({behavior:"smooth",block:"center",inline:"nearest"}),t&&(this.domService.getSelectedAnnotationsMap()[e]||this.domService.toggleAnnotationSelection(t)))}catch(t){this.loggingService.catch("Error in CommentService scrollToCommentByAnnotationId: ",t)}}selectCommentByAnnotationId(e,t){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([vo.ADMIN,vo.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()}setFreeStyleCommentContext(e){try{this.freeStyleCommentContext=e}catch(t){this.loggingService.catch("Error in CommentService setFreeStyleCommentContext: ",t)}}clearFreeStyleCommentContext(){try{this.freeStyleCommentContext=void 0}catch(e){this.loggingService.catch("Error in CommentService resetFreeStyleCommentContext: ",e)}}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(t){this.loggingService.catch("Error in CommentService showCommentIndex: ",t)}}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,t=!1,r=!1){try{this.domService.resetSelectedAnnotationsMap(),e?(document.querySelector(j.TAGS.VELT_COMMENTS_SIDEBAR)||document.querySelector(j.TAGS.SNIPPYLY_COMMENTS_SIDEBAR)?this.sidebarVisible$.next(e):this.loggingService.catch("Error in CommentService setSidebarVisibility: ",`<${j.TAGS.VELT_COMMENTS_SIDEBAR}> tag is not added.`),t&&this.sidebarOpenedByCustomTrigger$.next(!0)):(!this.sidebarOpenedByCustomTrigger$.value||t||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: ",`<${j.TAGS.VELT_COMMENTS_SIDEBAR}> tag is not added.`)}}toggleSidebarVisibility(e=!1,t=!1){try{this.domService.resetSelectedAnnotationsMap(),this.sidebarVisible$.value?(!this.sidebarOpenedByCustomTrigger$.value||e||t)&&(this.sidebarVisible$.next(!this.sidebarVisible$.value),this.sidebarOpenedByCustomTrigger$.next(!1)):(document.querySelector(j.TAGS.VELT_COMMENTS_SIDEBAR)||document.querySelector(j.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: ",`<${j.TAGS.VELT_COMMENTS_SIDEBAR}> tag is not added.`),e&&this.sidebarOpenedByCustomTrigger$.next(!0))}catch{this.loggingService.catch("Error in CommentService toggleSidebarVisibility: ",`<${j.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(t){this.loggingService.catch("Error in CommentService disableFloatingComments: ",t)}}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(t){this.loggingService.catch("Error in CommentService setModeratorMode: ",t)}}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(t){this.loggingService.catch("Error in CommentService setStreamMode: ",t)}}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(t){this.loggingService.catch("Error in CommentService setEnableDialogOnHover: ",t)}}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(t){this.loggingService.catch("Error in CommentService setEnableDialogOnTargetElementClick: ",t)}}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(t){this.loggingService.catch("Error in CommentService setEnablePriority: ",t)}}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(t){this.loggingService.catch("Error in CommentService setEnableStatus: ",t)}}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(t){this.loggingService.catch("Error in CommentService setEnableResolve: ",t)}}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(t){this.loggingService.catch("Error in CommentService setEnableAutoCategorize: ",t)}}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(t){this.loggingService.catch("Error in CommentService setCommentContainerDarkMode: ",t)}}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(t){this.loggingService.catch("Error in CommentService setSuggestionMode: ",t)}}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(t){this.loggingService.catch("Error in CommentService setMobileMode: ",t)}}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(t){this.loggingService.catch("Error in CommentService setTotalMediaLength: ",t)}}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(t){this.loggingService.catch("Error in CommentService setDetectionStrategy: ",t)}}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(t){this.loggingService.catch("Error in CommentService addBubbleCommentAnnotationIds: ",t)}}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(t){this.loggingService.catch("Error in CommentService removeBubbleCommentAnnotationIds: ",t)}}enableSignInButton(e){try{this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{signInButton:e}}),this.enableSignInButton$.next(e)}catch(t){this.loggingService.catch("Error in CommentService enableSignInButton: ",t)}}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(t){this.loggingService.catch("Error in CommentService enableUpgradeButton: ",t)}}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(t){this.loggingService.catch("Error in CommentService enableAttachment: ",t)}}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(t){this.loggingService.catch("Error in CommentService setAllowedRecordings: ",t)}}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 Q(this,null,function*(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{privateCommentMode:!0}}),this.privateCommentMode$.value===!0)return;this.iamService.isUserAdmin$().pipe(st(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(t){this.loggingService.catch("Error in CommentService showScreenSizeInfo: ",t)}}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(t){this.loggingService.catch("Error in CommentService setUnreadIndicatorMode: ",t)}}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(t){this.loggingService.catch("Error in CommentService setComposerMode: ",t)}}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(t){this.loggingService.catch("Error in CommentService setExcludeLocationIdsFromSidebar: ",t)}}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()}enableGroupMatchedComments(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{groupMatchedComments:!0}}),this.groupMatchedComments$.value===!0)return;this.groupMatchedComments$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableGroupMatchedComments: ",e)}}disableGroupMatchedComments(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{groupMatchedComments:!1}}),this.groupMatchedComments$.value===!1)return;this.groupMatchedComments$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableGroupMatchedComments: ",e)}}getGroupMatchedComments(){return this.groupMatchedComments$.value}getGroupMatchedComments$(){return this.groupMatchedComments$.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(t){this.loggingService.catch("Error in CommentService setCommentSidebarFilters: ",t)}}getCommentSidebarFilters(){return this.commentSidebarFilters$.value}getCommentSidebarFilters$(){return this.commentSidebarFilters$.asObservable()}setCommentSidebarSystemFiltersOperator(e){try{this.commentSidebarSystemFiltersOperator$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setCommentSidebarSystemFiltersOperator: ",t)}}getCommentSidebarSystemFiltersOperator(){return this.commentSidebarSystemFiltersOperator$.value}getCommentSidebarSystemFiltersOperator$(){return this.commentSidebarSystemFiltersOperator$.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(t){this.loggingService.catch("Error in CommentService setCustomReactions: ",t)}}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(t){return this.loggingService.catch("Error in CommentService getCommentType: ",t),""}}getCommentAnnotationAvailableOnXPath(e,t,r){try{return this.commentAnnotationById$.pipe(he(()=>this.draftCommentAnnotationsByAnnotationId$),he(a=>(!r&&t&&(r=oa(t,["id","data-id"])),se(T(I({},a),{element:r})))),he(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 u=this.docService.getAdditionalDocumentIdFromElement(s),C=u?this.docService.generateDocumentId(u):p?.documentId,E=this.getCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:p?.organizationId,documentId:C||""});if(E)for(let D of E)(t&&D?.targetElementId===t||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),se(null)}}getCommentAnnotationsByContext({context:e,contextOptions:t,element:r,clientDocumentId:a}){try{return this.commentAnnotationById$.pipe(he(()=>this.draftCommentAnnotationsByAnnotationId$),he(()=>this.docService.getDocumentPaths$()),ce(()=>{let s=null,c=this.docService.getDocumentPaths(),p=Oc(e),u=this.generateContextId(p);if(c?.documentId){let C=a||this.docService.getAdditionalDocumentIdFromElement(r??null),E=C?this.docService.generateDocumentId(C):c?.documentId,D=this.getCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:c?.organizationId,documentId:E||""});if(D){s=[];for(let L of D)t?.partialMatch?HP(L?.context,p)&&s.push(L):u&&L?.contextId===u&&s.push(L)}}return s}))}catch(s){return this.loggingService.catch("Error in CommentService getCommentAnnotationsByContext: ",s),se(null)}}getCommentAnnotationByAnnotationId(e){try{return this.commentAnnotationById$.pipe(ce(()=>this.getAnnotationById(e)),he(t=>t?t?.iam?.accessMode===io.PRIVATE?this.iamService.isUserAdmin$().pipe(ce(r=>{if(r)return t})):se(t):se(t)),he(t=>t?this.filterCommentsUsingSidebarSettings(t).pipe(ce(r=>{if(r)return r})):se(t)))}catch(t){return this.loggingService.catch("Error in CommentService getCommentAnnotationByAnnotationId: ",t),se(void 0)}}getMultiThreadCommentAnnotationByAnnotationId(e){return this.multiThreadCommentAnnotationById$.pipe(ce(()=>this.getMultiThreadAnnotationById(e)))}getCommentBubbleElement(e){try{let t=document.querySelector(`${j.TAGS.VELT_COMMENT_BUBBLE}[${j.ATTRIBUTES.VELT_ANNOTATION_IDS}*="${e?.annotationId}"]`);return t||(t=document.querySelector(`${j.TAGS.SNIPPYLY_COMMENT_BUBBLE}[${j.ATTRIBUTES.VELT_ANNOTATION_IDS}*="${e?.annotationId}"]`)),t}catch(t){return this.loggingService.catch("Error in CommentService getCommentBubbleElement: ",t),null}}getCommentAnnotationsBySectionId(e){try{return this.commentAnnotationById$.pipe(he(()=>this.docService.getDocumentPaths$().pipe(ce(t=>({documentPaths:t,sectionId:e})))),he(t=>{let r=oa(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 u=Object.values(c||{}).find(C=>C.locationId===s||a?.id&&C.location.id===a.id);return T(I({},t),{additionalLocation:u,locationOnElement:!!a})}))}}return se(T(I({},t),{additionalLocation:null,element:r}))}),he(t=>t?.locationOnElement?se(t):this.docService.getLocation$().pipe(ce(r=>T(I({},t),{location:r})))),ce(({documentPaths:t,location:r,additionalLocation:a,locationOnElement:s,element:c})=>{let p=null;if(this.authService.getUser()&&t?.documentId){let C=this.docService.getAdditionalDocumentIdFromElement(c),E=C?this.docService.generateDocumentId(C):t?.documentId,D=this.getCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:t?.organizationId,documentId:E||""});if(D){p=[];let L=Ad(e);s?a?.location?.id?L=Ad([a?.location?.id,e]):a?.locationId&&(L=Ad([a?.locationId+"",e])):r&&(r?.location?.id?L=Ad([r?.location?.id,e]):r?.locationId&&(L=Ad([r?.locationId+"",e])));for(let z of D)z?.multiThreadAnnotationId===L?p.push(z):(z?.targetInlineCommentElementId===e||z?.targetElementId===e)&&(s?a&&nh({location:a?.location,locationId:a?.locationId},{location:z.location,locationId:z.locationId})&&p.push(z):r?nh({location:r?.location,locationId:r?.locationId},{location:z.location,locationId:z.locationId})&&p.push(z):z?.locationId||p.push(z))}}return p}))}catch(t){return this.loggingService.catch("Error in CommentService getCommentAnnotationsBySectionId: ",t),se(null)}}getCommentAnnotationsByMultiThreadAnnotationId(e){try{return this.commentAnnotationById$.pipe(he(()=>this.multiThreadCommentAnnotationById$),he(()=>this.docService.getDocumentPaths$().pipe(ce(t=>({documentPaths:t,multiThreadAnnotationId:e})))),ce(({documentPaths:t,location:r,additionalLocation:a,locationOnElement:s})=>{let c=null;if(t?.documentId){let p=this.getMultiThreadAnnotationById(e),{documentId:u,organizationId:C}=p?.metadata||{documentId:t?.documentId,organizationId:t?.organizationId},E=this.getCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:C,documentId:u||""});if(E){c=[];for(let D of E)D?.multiThreadAnnotationId===e&&p?.commentAnnotations?.[D?.annotationId]&&c.push(D)}}return c}))}catch(t){return this.loggingService.catch("Error in CommentService getCommentAnnotationsBySectionId: ",t),se(null)}}getCommentAnnotationsByAnnotationIds(e){try{return this.commentAnnotationById$.pipe(he(()=>this.draftCommentAnnotationsByAnnotationId$),he(()=>this.docService.getDocumentPaths$().pipe(ce(t=>({documentPaths:t,annotationIds:e})))),ce(({documentPaths:t})=>{let r=null;if(t?.documentId){let a=this.commentAnnotationById$.value?Object.values(this.commentAnnotationById$.value):[],s=this.draftCommentAnnotationsByAnnotationId$.value?Object.values(this.draftCommentAnnotationsByAnnotationId$.value):[];if(a=[...a,...s],a){r=[];for(let c of a)e.includes(c?.annotationId)&&r.push(c)}}return r}))}catch(t){return this.loggingService.catch("Error in CommentService getCommentAnnotationsByAnnotationIds: ",t),se(null)}}getCommentAnnotationsByFolderId({folderId:e,veltFolderId:t}){try{return this.commentAnnotationById$.pipe(he(()=>this.draftCommentAnnotationsByAnnotationId$),he(()=>this.docService.getDocumentPaths$()),ce(()=>{e&&!t&&(t=Fi(e));let r=this.authService.getUser(),a=this.docService.getDocumentPaths(),s=null;if(r&&a?.documentId){this.commentAnnotationById$.value&&(s={},Object.values(this.commentAnnotationById$.value).forEach(p=>{p?.metadata?.folderId==e&&p?.metadata?.veltFolderId==t&&(s[p?.annotationId]=p)}));let c=this.draftCommentAnnotationsByAnnotationId$.value;c&&(s===null&&(s={}),Object.values(c).forEach(p=>{p?.metadata?.folderId==e&&p?.metadata?.veltFolderId==t&&!s[p?.annotationId]&&(s[p?.annotationId]=p)}))}return s?Object.values(s):null}))}catch(r){return this.loggingService.catch("Error in CommentService getCommentAnnotationsByFolderId: ",r),se(null)}}getCommentAnnotationsForCommentComponent(e){try{let{annotationId:t,folderId:r,veltFolderId:a,targetElementId:s,clientDocumentId:c,documentId:p,context:u,contextOptions:C,element:E,type:D,sectionId:L,locationId:z}=e||{};if(c&&!p&&(p=this.docService.generateDocumentId(c)),r&&!a&&(a=Fi(r)),t)return this.getCommentAnnotationByAnnotationId(t).pipe(ce(J=>J?[J]:null));let W=[];if(s&&(D==="pin"||D==="tool"||D==="bubble")){let J=oa(s,["id","data-id"]);if(J){let ue=J,ye=this.domService.getXPath(J);W.push(this.getCommentAnnotationAvailableOnXPath(ye,s,ue))}}return L&&W.push(this.getCommentAnnotationsBySectionId(L)),u&&W.push(this.getCommentAnnotationsByContext({context:u,contextOptions:C,element:E,clientDocumentId:c})),p&&W.push(this.getCommentAnnotationsByDocumentId$({documentId:p})),r&&W.push(this.getCommentAnnotationsByFolderId({folderId:r,veltFolderId:a})),W.length===0?se(null):Sn(W).pipe(ce(J=>{let ue=J.filter(Ae=>Ae!==null&&Array.isArray(Ae));if(ue.length===0)return null;if(ue.length===1){let Ae=ue[0];return z&&Ae?.length?Ae.filter(Fe=>Fe?.location?.id===z):Ae}let ye=ue[0];for(let Ae=1;Ae<ue.length;Ae++){let He=ue[Ae];ye=ye.filter(Fe=>He.some(Se=>Se.annotationId===Fe.annotationId))}return z&&ye?.length&&(ye=ye.filter(Ae=>Ae?.location?.id===z)),ye}),Et(mn))}catch(t){return this.loggingService.catch("Error in CommentService getCommentAnnotationsForCommentComponent: ",t),se(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(t){return this.loggingService.catch("Error in CommentService isElementInsideAllowedElements: ",t),!1}}getNearestAllowedElement(e){try{let t=this.domService.getListedElements({elementIds:this.allowedElementIds$.value,elementClassNames:this.allowedElementClassNames$.value,elementQuerySelectors:this.allowedElementQuerySelectors$.value});if(t?.length){for(let r=0;r<t.length;r++){let a=t[r];if(e.contains(a))return a}return null}return null}catch(t){return this.loggingService.catch("Error in CommentService getNearestAllowedElement: ",t),null}}isElementInsideManualCommentContainer(e){try{return this.domService.isElementInsideParentWithAttribute(e,j.ATTRIBUTES.VELT_MANUAL_COMMENT_CONTAINER,"true")}catch(t){return this.loggingService.catch("Error in CommentService isElementInsideManualCommentContainer: ",t),!1}}saveComment(e,t){return Q(this,null,function*(){try{t?.annotation&&(e=t.annotation),e&&(e=JSON.parse(JSON.stringify(e)));let r=this.originalCommentAnnotationsByDocumentId$.value[e.annotationId];if(r?.comments?.length){let C=JSON.parse(JSON.stringify(e.comments||[]));e.comments=[],r.comments?.forEach(E=>{let D=C.find(L=>L.commentId===E.commentId);D?e.comments.push(D):e.comments.push(E)})}e.comments||(e.comments=[]);let a=!1,s=!1,c;switch(t.type){case $t.NEWLY_ADDED:case $t.ADDED:if(!t.updatedComment)break;e?.comments?.length||(s=!0),e.comments.push(t.updatedComment);let C=t?.assigned||void 0;c={commentAnnotation:e,targetComment:t.updatedComment,actionType:t.type,otherFields:{assigned:C}};break;case $t.PUBLISHED:e.isDraft=!1;break;case $t.APPROVED:e.approved=!0,c={commentAnnotation:e,targetComment:null,actionType:$t.APPROVED};break;case $t.ASSIGNED:e.assignedTo=t.assignedTo,c={commentAnnotation:e,targetComment:null,actionType:$t.ASSIGNED};break;case $t.UPDATED:if(!t.updatedComment)break;let E=e.comments.findIndex(ue=>ue.commentId===t.updatedComment.commentId);if(E>=0){e.comments[E]=t.updatedComment,e.comments[E].status=$t.UPDATED;let ue=t?.assigned||void 0;c={commentAnnotation:e,targetComment:t.updatedComment,actionType:$t.UPDATED,otherFields:{assigned:ue}}}break;case $t.REACTION_ADDED:if(!t.updatedComment)break;let D=e.comments.findIndex(ue=>ue.commentId===t.updatedComment.commentId);D>=0&&(e.comments[D]=t.updatedComment,e.comments[D].status=$t.UPDATED,c={commentAnnotation:e,targetComment:t.updatedComment,actionType:$t.REACTION_ADDED});break;case $t.REACTION_DELETED:if(!t.updatedComment)break;let L=e.comments.findIndex(ue=>ue.commentId===t.updatedComment.commentId);L>=0&&(e.comments[L]=t.updatedComment,e.comments[L].status=$t.UPDATED,c={commentAnnotation:e,targetComment:t.updatedComment,actionType:$t.REACTION_DELETED});break;case $t.STATUS_CHANGED:e.status.type==="terminal"&&(this.domService.resetSelectedAnnotationsMap(!1,"comment"),e.resolvedByUserId=this.authService.getUser()?.userId),c={commentAnnotation:e,targetComment:null,actionType:$t.STATUS_CHANGED,otherFields:{oldStatus:t.oldStatus,newStatus:t.newStatus}};break;case $t.PRIORITY_CHANGED:c={commentAnnotation:e,targetComment:null,actionType:$t.PRIORITY_CHANGED,otherFields:{oldPriority:t.oldPriority,newPriority:t.newPriority}};break;case $t.ACCESS_MODE_CHANGED:c={commentAnnotation:e,targetComment:null,actionType:$t.ACCESS_MODE_CHANGED,otherFields:{oldAccessMode:t.oldAccessMode,newAccessMode:t.newAccessMode}};break;case $t.CUSTOM_LIST_CHANGED:c={commentAnnotation:e,targetComment:null,actionType:$t.CUSTOM_LIST_CHANGED,otherFields:{oldCustomList:t.oldCustomList,newCustomList:t.newCustomList}};break;case $t.SUBSCRIBED:c={commentAnnotation:e,targetComment:null,actionType:$t.SUBSCRIBED};break;case $t.UNSUBSCRIBED:c={commentAnnotation:e,targetComment:null,actionType:$t.UNSUBSCRIBED};break;case $t.DELETED:if(!t.updatedComment)break;let z=e.comments.findIndex(ue=>ue.commentId===t.updatedComment.commentId);if(z>=0){if((z===0&&this.deleteThreadWithFirstComment$.value!==!1||this.deleteReplyConfirmation$.value)&&!t.skipDeleteThreadConfirmation){let Ae={};if(this.deleteReplyConfirmation$.value&&(z!==0||this.deleteThreadWithFirstComment$.value===!1)?Ae={title:"Delete comment?",message:"This selected comment will be deleted.",yesButton:"Delete",noButton:"Cancel",darkMode:this.commentContainerDarkMode$.value,variant:"reply"}:Ae={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(Sa,{panelClass:"velt-mat-dialog-container",data:Ae}).afterClosed().toPromise()))return}let ue=e.comments.splice(z,1),ye=e.metadata;ue?.length&&ue.forEach(Ae=>{Ae?.attachments&&Ae.attachments.forEach(He=>{let Fe={attachmentId:He.attachmentId,organizationId:ye?.organizationId??null,documentId:ye?.documentId??null,folderId:ye?.folderId??null,commentAnnotationId:e.annotationId,apiKey:ye?.apiKey??null};this.deleteAttachment({attachment:He,metadata:Fe})}),Ae?.reactionAnnotationIds&&Ae.reactionAnnotationIds.forEach(He=>{this.deleteReaction(He)})})}e.status=this.customFilterService.defaultStatus,z===0&&this.deleteThreadWithFirstComment$.value!==!1||e.comments?.length===0?a=!0:(this.analyticsService.trackEvent(Z.Events.Comments.COMMENT_THREAD_DELETED,{annotationId:e.annotationId,commentThreadId:t.updatedComment.commentId,commentMode:this.getCommentMode()}),c={commentAnnotation:e,targetComment:t.updatedComment,actionType:$t.DELETED});break;case $t.ACCEPTED:let W={annotationId:e.annotationId,actionUser:this.authService.getUser(),actionType:$t.ACCEPTED,replaceContentHtml:e?.comments?.length?e?.comments[0]?.replaceContentHtml:void 0,replaceContentText:e?.comments?.length?e?.comments[0]?.replaceContentText:void 0,annotation:Gn(e)};this.commentAccepted$.next(W),c={commentAnnotation:e,targetComment:null,actionType:$t.ACCEPTED};break;case $t.REJECTED:let J={annotationId:e.annotationId,actionUser:this.authService.getUser(),actionType:$t.REJECTED,replaceContentHtml:e?.comments?.length?e?.comments[0]?.replaceContentHtml:void 0,replaceContentText:e?.comments?.length?e?.comments[0]?.replaceContentText:void 0,annotation:Gn(e)};this.commentRejected$.next(J),this.domService.resetSelectedAnnotationsMap(),c={commentAnnotation:e,targetComment:null,actionType:$t.REJECTED};break;default:break}e.resolvedByUserId&&e.status.type!=="terminal"&&(e.resolvedByUserId=null),t?.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&&(t.type===$t.ADDED||t.type===$t.NEWLY_ADDED)&&e.comments?.length===1?setTimeout(()=>{this.domService.resetSelectedAnnotationsMap(!1,"comment")},100):this.domService.updateSelectedAnnotationInMap([e]));let p=this.getCustomPinById(e.annotationId),u={type:t.type,annotation:Gn(e),targetAnnotationId:e.annotationId,targetCommentId:t.updatedComment?.commentId,updateContext:(C,E)=>{this.updateCommentAnnotationContext(e.annotationId,C,E)}};p!==void 0&&(u.element=p),delete u?.annotation?.pageInfo,delete u?.annotation?.targetElement,delete u?.annotation?.targetTextRange,u?.type===$t.DELETED&&(e.comments?.length||(u.annotation=null)),a||this.commentUpdated$.next(u)}catch(r){this.loggingService.catch("Error in CommentService saveComment: ",r)}})}attachComment(e,t=[],r,a,s,c,p){try{this.loggingService.log("%c[WB] Calling FUNCTION: attachComment","color: green;");let u;if(e){let C=oa(e,t);C&&(u={targetElement:{xpath:this.domService.getXPath(C),topPercentage:50,leftPercentage:90},targetElementId:e})}(u||r||s)&&this.addComment(void 0,void 0,void 0,void 0,void 0,void 0,void 0,c,void 0,void 0,u,void 0,void 0,void 0,a,void 0,void 0,void 0,r,void 0,s,void 0,void 0,p)}catch(u){this.loggingService.catch("Error in CommentService attachComment: ",u)}}updateNotificationsDatabase(e,t,r,a={}){try{let s=I({annotationData:e,targetAnnotationData:t,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 t=null;if(e?.ghostComment)!t&&e.ghostComment?.targetElement?.fXpath&&(t=this.domService.getElementFromXPath(e.ghostComment?.targetElement?.fXpath),t&&!this.domService.isElementVisible(t)&&(t=null)),!t&&e.ghostComment?.targetElement?.cfXpath&&(t=this.domService.getElementFromXPath(e.ghostComment?.targetElement?.cfXpath),t&&!this.domService.isElementVisible(t)&&(t=null)),!t&&e.ghostComment?.targetElement?.xpath&&(t=this.domService.getElementFromXPath(e.ghostComment?.targetElement?.xpath),t&&!this.domService.isElementVisible(t)&&(t=null));else{let r=!1;!t&&e?.targetElement?.xpath&&(r=this.domService.isXpathWithId(e?.targetElement?.xpath),t=this.domService.getElementFromXPath(e?.targetElement?.xpath),t&&!this.domService.isElementVisible(t)&&(t=null)),r||(!t&&e?.targetElement?.cfXpath&&(t=this.domService.getElementFromXPath(e?.targetElement?.cfXpath),t&&!this.domService.isElementVisible(t)&&(t=null)),!t&&e?.targetElement?.fXpath&&(t=this.domService.getElementFromXPath(e?.targetElement?.fXpath),t&&!this.domService.isElementVisible(t)&&(t=null)))}return t&&!Ao(t)&&(t=null),t}catch(t){return this.loggingService.catch("Error in CommentService getElementFromComment: ",t),null}}getElementFromComments(e){try{let t=[],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&&!Ao(r)&&(r=null),e?.targetElementId&&(t=Array.from(aae(e.targetElementId,["id","data-id"]))),r&&!t.includes(r)&&t.push(r),t}catch(t){return this.loggingService.catch("Error in CommentService getElementFromComment: ",t),[]}}getGhostCommentTargetElement(e){try{let t=e.targetElement?.fXpath||e.targetElement?.xpath,r=null;if(t)for(;!r&&t;)r=this.domService.getElementFromXPath(t),r&&(!this.domService.isElementVisible(r)||!Ao(r))&&(r=null),r||(t=t.substring(0,t.lastIndexOf("/")));return t==="/"&&(t=""),t?{xpath:t,topPercentage:e?.targetElement?.topPercentage||0,leftPercentage:e?.targetElement?.leftPercentage||0}:null}catch(t){return this.loggingService.catch("Error in CommentService getGhostCommentTargetElement: ",t),null}}setGhostCommentMessage(e){try{if(e?.ghostComment){e.ghostComment.message="Original content not found.",e.ghostComment.type=il.ELEMENT_DELETED;let t=e?.pageInfo?.deviceInfo?.deviceType,r=new zn().getDeviceType();t&&t!==r&&(e.ghostComment.type=il.DIFFERENT_DEVICE,e.ghostComment.message=`Original comment was added on ${t}.`,[ir.MOBILE,ir.TABLET].includes(t)&&[ir.MOBILE,ir.TABLET].includes(r)||[ir.DESKTOP,ir.MONITOR].includes(t)&&[ir.DESKTOP,ir.MONITOR].includes(r)?e.ghostComment.isSameGroup=!0:e.ghostComment.isSameGroup=!1)}}catch(t){this.loggingService.catch("Error in CommentService setGhostCommentMessage: ",t)}}addAnnotationToGhostCommentAnnotationMap(e){try{let t=this.ghostCommentAnnotationMap$.value||{},r=t[e?.annotationId]||{};wi(e.ghostComment,r)||(t[e?.annotationId]=e.ghostComment,this.ghostCommentAnnotationMap$.next(t))}catch(t){this.loggingService.catch("Error in CommentService addAnnotationToGhostCommentAnnotationMap: ",t)}}removeAnnotationFromGhostCommentAnnotationMap(e){try{let t=this.ghostCommentAnnotationMap$.value||{};t[e?.annotationId]&&(delete t[e?.annotationId],this.ghostCommentAnnotationMap$.next(t))}catch(t){this.loggingService.catch("Error in CommentService removeAnnotationFromGhostCommentAnnotationMap: ",t)}}getGhostCommentAnnotationMap$(){return this.ghostCommentAnnotationMap$.asObservable()}getGhostCommentAnnotationMap(){return this.ghostCommentAnnotationMap$.value||{}}getUnreadCommentsMap$(){return this.unreadCommentsMap$.asObservable().pipe(Et(mn))}getUnreadCommentsMap(){return this.unreadCommentsMap$.value}getUnreadCommentCountByAnnotationId$(e){return this.getUnreadCommentsMap$().pipe(ce(t=>t?{count:t[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(t=>{if(t){let r=this.docService.getDocumentPaths(),a=[],s=0;return r?.documentId&&(a=this.getCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:r?.organizationId,documentId:r?.documentId}),a&&Object.keys(t).forEach(c=>{a?.find(u=>u.annotationId===c)?.location?.id===e&&(s+=t[c])})),{count:s}}else return null}))}getUnreadCommentAnnotationCountByLocationId$(e){return this.getUnreadCommentsMap$().pipe(ce(t=>{if(t){let r=this.docService.getDocumentPaths(),a=[],s=0;return r?.documentId&&(a=this.getCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:r?.organizationId,documentId:r?.documentId}),Object.keys(t).forEach(c=>{t[c]&&a?.find(u=>u.annotationId===c)?.location?.id===e&&(s+=1)})),{count:s}}else return null}))}setCommentAnnotationsAsRead(e){try{for(let t of e)this.viewsService.setCommentAnnotationAsRead(t)}catch(t){this.loggingService.catch("Error in CommentService setCommentAnnotationsAsRead: ",t)}}setCommentAnnotationsAsResolved(e){try{let t=this.customFilterService.resolvedStatus;if(t){for(let r of e)if(t?.id!==r?.status?.id){let a=JSON.parse(JSON.stringify(r||{}));r.status=this.customFilterService.resolvedStatus;let s={annotation:r,type:$t.STATUS_CHANGED,oldStatus:a.status,newStatus:this.customFilterService.resolvedStatus};this.saveComment(r,s)}}}catch(t){this.loggingService.catch("Error in CommentService setCommentAnnotationsAsResolved: ",t)}}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(t){this.loggingService.catch("Error in CommentService setPinCursorImage: ",t)}}getPinCursorImage$(){return this.commentPinCursorImage$.asObservable()}getPinCursorImage(){return this.commentPinCursorImage$.value}setCommentAnnotationsFromCommentsContainer(e){try{this.commentAnnotationsFromCommentsContainer$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setCommentAnnotationsFromCommentsContainer: ",t)}}getCommentAnnotationsFromCommentsContainer$(){return this.commentAnnotationsFromCommentsContainer$.asObservable()}getCommentAnnotationsFromCommentsContainer(){return this.commentAnnotationsFromCommentsContainer$.value}addManualComment(e){return Q(this,null,function*(){try{return this.loggingService.log("%c[WB] Calling FUNCTION: addManualComment","color: green;"),new Promise((t,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=>{t(c)}),this.addCommentMode$?.value&&!this.persistentCommentMode$?.value&&this.disableAddCommentMode()})}catch(t){return this.loggingService.catch("Error in CommentService addManualComment: ",t),null}})}getCommentUrl(e){try{return e?.pageInfo?.commentUrl?e.pageInfo.commentUrl:(e?.pageInfo||(e.pageInfo=Oi(),e.pageInfo&&(e.pageInfo.screenWidth=this.domService.getCurrentWindowSizeValue()?.screenWidth)),e.pageInfo.commentUrl=this.generateCommentUrl(e),this.updateComment(e),e.pageInfo?.commentUrl)}catch(t){this.loggingService.catch("Error in CommentService getCommentUrl: ",t);return}}uploadFile(e,t){let r=`${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentPaths?.documentId}/${j.FIREBASE_PARTIAL_PATH_COMMENT}/${t.annotationId}`;this.documentPaths?.organizationId&&(r=`${j.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${this.documentPaths.organizationId}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentPaths?.documentId}/${j.FIREBASE_PARTIAL_PATH_COMMENT}/${t.annotationId}`);let a={organizationId:t.metadata?.clientOrganizationId??null,documentId:t.metadata?.clientDocumentId??null,commentAnnotationId:t.annotationId,apiKey:t.metadata?.apiKey??null,folderId:t.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:t}){return this.storageService.deleteAttachment({attachment:e,metadata:t,useAttachmentResolver:this.attachmentResolverService.attachmentDataProviderAvailable()})}deleteReaction(e){try{this.reactionService.deleteReactionPinAnnotation(e)}catch(t){this.loggingService.catch("Error in CommentService deleteReaction: ",t)}}generateCommentUrl(e){let t=new URL(window.location.href);return t.searchParams.delete(j.URL_PARAMS.COMMENT_ID),t.searchParams.append(j.URL_PARAMS.COMMENT_ID,e.annotationId),t.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(t){this.loggingService.catch("Error in CommentService setCustomStatuses: ",t)}}getCustomStatusesShown$(){return this.customStatusesShown$.asObservable()}getCustomStatusesShown(){return this.customStatusesShown$.value}setCustomPriorities(e){try{if(e===void 0)return;this.customFilterService.setCustomPriorityFilters(e)}catch(t){this.loggingService.catch("Error in CommentService setCustomPriorities: ",t)}}setCustomCategories(e){try{if(e===void 0)return;this.customFilterService.setCustomCategories(e)}catch(t){this.loggingService.catch("Error in CommentService setCustomCategories: ",t)}}addCommentOnSelectedText(){try{let e=this.authService.getUser();if(this.textCommentMode$.value&&e&&!(e?.isReadOnly||e?.isAnonymous)&&this.authService.isFeatureAllowed(Re.COMMENT)){let t=this.domService.getRange();if(window.getSelection()?.toString()&&!eM()&&t?.commonAncestorContainer&&this.isElementInsideAllowedElements(t.commonAncestorContainer)&&!Vm(t.commonAncestorContainer)){let r=t?this.domService.getTargetTextRangeFromSelectionRange(t):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 t;if(e){let r=e?.closest(`[${j.ATTRIBUTES.VELT_TARGET_INLINE_COMMENT_ELEMENT_ID}]`);if(r){let a=r.getAttribute(j.ATTRIBUTES.VELT_TARGET_INLINE_COMMENT_ELEMENT_ID);a&&(t={},t.targetInlineCommentElementId=a,r.getAttribute(j.ATTRIBUTES.VELT_INLINE_COMMENT_SECTION_CONFIG)&&(t.config=JSON.parse(r.getAttribute(j.ATTRIBUTES.VELT_INLINE_COMMENT_SECTION_CONFIG)||"{}")))}}return t}catch(t){this.loggingService.catch("Error in CommentService getInlineCommentSectionConfig: ",t)}}createCustomListDataOnAnnotation(e){try{if(e===void 0)return;this.customChipDropdownData$.next(e)}catch(t){this.loggingService.catch("Error in CommentService createCustomListDataOnAnnotation: ",t)}}getCustomChipDropdownData$(){return this.customChipDropdownData$.asObservable()}getCustomChipDropdownData(){return this.customChipDropdownData$.value}setSubscribedUsersDataInCommentAnnotation(e){try{let t={},r=e?.unsubscribedUsers||{},a={};if(e?.subscribedUsers&&Object.keys(e.subscribedUsers||{}).forEach(s=>{let c=e.subscribedUsers?.[s];c?.type==="manual"&&(t[s]=c)}),e?.assignedTo?.userId){let s=bt(e?.assignedTo?.userId);r[s]||t[s]?.type!=="manual"&&(t[s]={user:e?.assignedTo,type:"auto"})}e?.comments?.filter(s=>!s?.isDraft)?.forEach(s=>{if(s?.from?.userId){let c=bt(s?.from?.userId);r[c]||t[c]?.type!=="manual"&&(t[c]={user:s?.from,type:"auto"})}s?.to?.forEach(c=>{if(c?.userId){let p=bt(c.userId);r[p]||t[p]?.type!=="manual"&&(t[p]={user:c,type:"auto"})}}),s?.toOrganizationUserGroup?.forEach(c=>{if(c?.groupId)a[c?.groupId]={type:"auto"};else if(c?.clientGroupId){let p=bt(c.clientGroupId);a[p]={type:"auto"}}})}),e.subscribedUsers=t,e.unsubscribedUsers=r,e.subscribedGroups=a}catch(t){this.loggingService.catch("Error in CommentService setSubscribeUsersDataInCommentAnnotation: ",t)}}getCopyLink$(){return this.copyLink$.asObservable()}setCopyLink(e){try{this.copyLink$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setCopyLink: ",t)}}getCommentAnnotationById(e){return this.commentAnnotationById$.pipe(he(()=>{let{annotationId:t,documentId:r}=e;if(r){let a=En(r).toString();return this.getDataCommentAnnotationsFromDocumentId(a).pipe(ce(s=>s.find(p=>p.annotationId===t)||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===t);return se(c||null)}}}return se(null)}),kn(t=>(this.loggingService.catch("Error in CommentService getCommentAnnotationById: ",t),se(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(t=>t?.data),ce(t=>{let r=[];return t&&(r=Object.values(t??{}).filter(a=>typeof a=="object")),r})):se([])}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,t,r,a,s){try{this.sidebarCustomActionEventData$.next({actions:e,data:t,unreadDataMap:r,systemFilteredData:a,customFilters:s})}catch(c){this.loggingService.catch("Error in CommentService emitOnSidebarCustomAction: ",c)}}getSidebarCustomActionEventData(){return this.sidebarCustomActionEventData$.asObservable()}setCommentSidebarData(e,t){try{this.sidebarData$.next({data:e,options:t})}catch(r){this.loggingService.catch("Error in CommentService setCommentSidebarData: ",r)}}getSidebarCustomData(){return this.sidebarData$.asObservable()}setSidebarCustomActionEventDataAllChanges(e,t,r,a,s){return Q(this,null,function*(){try{this.sidebarCustomActionEventDataAllChanges$.next({actions:e,data:t,unreadDataMap:r,systemFilteredData:a,customFilters:s});let c=yield this.metadataService.getGlobalMetadata(),p={buttonContext:{selections:this.buttonService.buttonToggleMapValue()},unreadCommentAnnotationsMap:r,commentAnnotations:t,systemFilteredAnnotations:a,metadata:c,customFilters:s};this.commentActionsService?.triggerAction(ji.COMMENT_SIDEBAR_DATA_UPDATE,p)}catch(c){this.loggingService.catch("Error in CommentService setSidebarCustomActionEventDataAllChanges: ",c)}})}setSidebarCustomActionEventDataOnInit(e,t,r,a,s){return Q(this,null,function*(){try{this.sidebarCustomActionEventDataOnInit$.next({actions:e,data:t,unreadDataMap:r,systemFilteredData:a,customFilters:s});let p={metadata:yield this.metadataService.getGlobalMetadata(),unreadCommentAnnotationsMap:r,commentAnnotations:t,systemFilteredAnnotations:a,buttonContext:{selections:this.buttonService.buttonToggleMapValue()},customFilters:s};this.commentActionsService?.triggerAction(ji.COMMENT_SIDEBAR_DATA_INIT,p)}catch(c){this.loggingService.catch("Error in CommentService setSidebarCustomActionEventDataOnInit: ",c)}})}getSidebarCustomActionEventDataAllChanges(){return this.sidebarCustomActionEventDataAllChanges$.asObservable()}getSidebarCustomActionEventDataOnInit(){return this.sidebarCustomActionEventDataOnInit$.asObservable()}getSidebarCustomActionEventDataOnInitValue(){return this.sidebarCustomActionEventDataOnInit$.getValue()}setTransformContext(e){try{e?wi(this.transformContext$.value,e)||this.transformContext$.next(e):this.transformContext$.next(null)}catch(t){this.loggingService.catch("Error in CommentService setTransformContext: ",t)}}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)}}enableLinkCallback(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{linkCallback:!0}}),this.linkCallback$.value===!0)return;this.linkCallback$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableLinkCallback: ",e)}}disableLinkCallback(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{linkCallback:!1}}),this.linkCallback$.value===!1)return;this.linkCallback$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableLinkCallback: ",e)}}getResolveStatusAccessAdminOnly$(){return this.resolveStatusAccessAdminOnly$.asObservable()}getLinkCallback$(){return this.linkCallback$.asObservable()}getResolveStatusAccessAdminOnly(){return this.resolveStatusAccessAdminOnly$.value}getLinkCallback(){return this.linkCallback$.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}enableFilterCommentsOnDom(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{filterCommentsOnDom:!0}}),this.filterCommentsOnDom$.value===!0)return;this.filterCommentsOnDom$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableFilterCommentsOnDom: ",e)}}disableFilterCommentsOnDom(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{filterCommentsOnDom:!1}}),this.filterCommentsOnDom$.value===!1)return;this.filterCommentsOnDom$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableFilterCommentsOnDom: ",e)}}getFilterCommentsOnDom$(){return this.filterCommentsOnDom$.asObservable()}getFilterCommentsOnDom(){return this.filterCommentsOnDom$.value}setCommentsFromSidebarMap(e){try{let{comments:t,sidebarVisible:r}=e||{},a=null;t&&(a={},t.forEach(c=>{c?.annotationId&&a&&(a[c.annotationId]=c)}));let s={};t===void 0?s.data=this.commentsFromSidebarMap$.value?.data:s.data=a,r===void 0?s.sidebarVisible=this.commentsFromSidebarMap$.value?.sidebarVisible:s.sidebarVisible=r,wi(this.commentsFromSidebarMap$.value,s)||this.commentsFromSidebarMap$.next(s)}catch(t){this.loggingService.catch("Error in CommentService setCommentsFromSidebarMap: ",t)}}getCommentsFromSidebarMap$(){return this.commentsFromSidebarMap$.asObservable()}getCommentsFromSidebarMap(){return this.commentsFromSidebarMap$.value}setSidebarButtonCountType(e){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{sidebarButtonCountType:e}}),this.sidebarButtonCountType$.value===e)return;this.sidebarButtonCountType$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setSidebarButtonCountType: ",t)}}getSidebarButtonCountType$(){return this.sidebarButtonCountType$.asObservable()}getSidebarButtonCountType(){return this.sidebarButtonCountType$.value}enableFilterGhostCommentsInSidebar(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{filterGhostCommentsInSidebar:!0}}),this.filterGhostCommentsInSidebar$.value===!0)return;this.filterGhostCommentsInSidebar$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableFilterGhostCommentsInSidebar: ",e)}}disableFilterGhostCommentsInSidebar(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{filterGhostCommentsInSidebar:!1}}),this.filterGhostCommentsInSidebar$.value===!1)return;this.filterGhostCommentsInSidebar$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableFilterGhostCommentsInSidebar: ",e)}}getFilterGhostCommentsInSidebar$(){return this.filterGhostCommentsInSidebar$.asObservable()}getFilterGhostCommentsInSidebar(){return this.filterGhostCommentsInSidebar$.value}filterCommentsUsingSidebarSettings(e){try{let t=Array.isArray(e),r;return t?r=e||[]:e?r=[e]:r=[],this.getFilterCommentsOnDom$().pipe(he(a=>a?r.length===0?se(e):this.getCommentsFromSidebarMap$().pipe(ce(s=>{if(!s?.sidebarVisible)return e;let c=r.filter(p=>p?.isDraft||!!s?.data?.[p?.annotationId]);return t?c:c.length>0?c[0]:null})):se(e)))}catch{return se(e)}}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}shouldEnableReadOnly(){return Q(this,null,function*(){try{this.loggingService.log("%c[WB] Calling CommentService FUNCTION: shouldEnableReadOnly","color: green;");let e=this.authService.getUser(),t=this.docService.getDocumentPaths()?.folderId,r=this.docService.getDocumentIds().map(a=>a.clientDocumentId);if(e){let a=yield this.userPermissionService.getUserPermissions();a[e.userId]?t&&a[e.userId]?.folders?.[t]?.accessRole==="viewer"?this.enableReadOnly():r.forEach(s=>{a[e.userId]?.documents?.[s]?.accessRole==="viewer"&&this.enableReadOnly()}):this.getReadOnly()||this.disableReadOnly()}}catch(e){this.loggingService.catch("Error in CommentService shouldEnableReadOnly:",e)}})}sanitizeCommentAnnotation(e){try{return e?.comments?.length&&e.comments.forEach(t=>{t?.commentHtml&&(t.commentHtml=this.domService.sanitizeHtml(t.commentHtml))}),e}catch(t){return this.loggingService.catch("Error in CommentService sanitizeCommentAnnotation: ",t),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:t}){try{this.analyticsService.setFeatureConfig({feature:t||Re.COMMENT,config:e})}catch(r){this.loggingService.catch("Error in CommentService setAnalyticsFeatureConfig: ",r)}}generateContextId(e){try{let t;if(e&&typeof e=="object"){let r=Oc(e),a=JSON.stringify(r);t=bt(a)}return t}catch{return}}setMaxReplyAvatars(e){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{maxReplyAvatars:e}}),this.maxReplyAvatars$.value===e)return;this.maxReplyAvatars$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setMaxReplyAvatars: ",t)}}getMaxReplyAvatars$(){return this.maxReplyAvatars$.asObservable()}getMaxReplyAvatars(){return this.maxReplyAvatars$.value}enableReplyAvatars(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{replyAvatars:!0}}),this.replyAvatars$.value===!0)return;this.replyAvatars$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableReplyAvatars: ",e)}}disableReplyAvatars(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{replyAvatars:!1}}),this.replyAvatars$.value===!1)return;this.replyAvatars$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableReplyAvatars: ",e)}}getReplyAvatars$(){return this.replyAvatars$.asObservable()}getReplyAvatars(){return this.replyAvatars$.value}setCommentplaceholder(e){try{this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{commentplaceholder:e}}),this.commentplaceholder$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setCommentplaceholder: ",t)}}getCommentplaceholder$(){return this.commentplaceholder$.asObservable()}getCommentplaceholder(){return this.commentplaceholder$.value}setReplyplaceholder(e){try{this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{replyplaceholder:e}}),this.replyplaceholder$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setReplyplaceholder: ",t)}}getReplyplaceholder$(){return this.replyplaceholder$.asObservable()}getReplyplaceholder(){return this.replyplaceholder$.value}};o.\u0275fac=function(t){return new(t||o)(ee(et),ee(Vc),ee(pn),ee(Ft),ee(at),ee(Dn),ee(Ve),ee(Be),ee(Di),ee(Bd),ee(xi),ee(sg),ee(Wo),ee(no),ee(vn),ee(y),ee(gn),ee(Zo),ee(rr),ee(Xce),ee(bn),ee(ds),ee(b0),ee(Hd),ee(ag),ee(rg),ee(y0))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var S=(()=>{let _DynamicDataService=class _DynamicDataService{constructor(i,o,n,e,t,r){this.authService=i,this.commentService=o,this.loggingService=n,this.injector=e,this.docService=t,this.configService=r,this.subscriptions=[],this.commonData$=new ve({}),this.evaluateConditionTriggered=new Me,this.conditionRegex=/\{(.*?)\}/g,this.extractedProps={},this.condition="",this.dataComponentConfigSignal=Te({});try{this.subscriptions.push(this.authService.getUser$().subscribe(a=>{this.commonData$.next(T(I({},this.commonData$.value),{user:a}))})),this.subscriptions.push(this.commentService.getUnreadCommentAnnotationCountOnCurrentDocument$().subscribe(a=>{this.commonData$.next(T(I({},this.commonData$.value),{unreadCommentAnnotationCount:a?.count||0}))})),this.subscriptions.push(this.commentService.getUnreadCommentCountOnCurrentDocument$().subscribe(a=>{this.commonData$.next(T(I({},this.commonData$.value),{unreadCommentCount:a?.count||0}))})),this.subscriptions.push(this.docService.getUIState$().subscribe(a=>{this.commonData$.next(I(I({},this.commonData$.value),a))})),this.subscriptions.push(this.getCommonData().subscribe(a=>{this.dataComponentConfigSignal.update(s=>(s=I(I({},s),a),s)),this.executeConditionalClasses()})),this.subscriptions.push(this.evaluateConditionTriggered.subscribe(a=>{this.extractedProps=a.extractedProps,this.evaluateCondition(a.className,a.elementRef,a.condition)}))}catch(a){this.loggingService.catch("Error in DynamicDataService constructor: ",a)}}ngOnDestroy(){try{this.subscriptions.forEach(i=>i.unsubscribe())}catch(i){this.loggingService.catch("Error in DynamicDataService ngOnDestroy: ",i)}}getCommonData(){return this.commonData$.asObservable()}getModifiedPathBasedOnCondition(i,o){try{return Object.keys(o).forEach(n=>{o[n].path=this.modifyPathBasedOnCondition(n,i)}),o}catch(n){this.loggingService.catch("Error in DynamicDataService getModifiedPathBasedOnCondition: ",n)}}getComputedValues(i,o,n,e,t,r){try{Object.keys(n).forEach(a=>{let s;if(Gi(i)?s=Ui(()=>Ca(i(),n[a].path)):s=Ui(()=>Ca(i,n[a].path)),Gi(s()))Ro(()=>{try{let c=s()();n[a].value=c,this.evaluateConditionTriggered.emit({extractedProps:n,className:e,elementRef:t,condition:r})}catch{}},{injector:this.injector,allowSignalWrites:!0});else{let c=s();n[a].value=c,this.evaluateConditionTriggered.emit({extractedProps:n,className:e,elementRef:t,condition:r})}})}catch(a){this.loggingService.catch("Error in DynamicDataService getComputedValues: ",a)}}modifyPathBasedOnCondition(i,o){try{let n=i;if(i.startsWith("userContact."))n=i.replace("userContact","selectorItem.contact");else if(i.startsWith("comment."))n=i.replace("comment","commentObj");else if(i.startsWith("commentAnnotation."))n=i.replace("commentAnnotation","componentConfigSignal.annotation");else if(i.startsWith("commentAnnotations."))n=i.replace("commentAnnotations","componentConfigSignal.annotations");else{let e=i.match(/^([^.\[]+)/),t=e?e[1]:"";if(t&&o&&typeof o=="function"&&o()&&t in o()){let r=i.match(/\[(.*?)\]/);if(r&&r[1]){let a=r[1];if(a.includes(".")){let s=a.split(".")[0];s&&o()&&s in o()?n=i:n=i.replace(`[${a}]`,`[componentConfigSignal.${a}]`)}else n=i}else n=i}else n="componentConfigSignal."+i}return n}catch(n){return this.loggingService.catch("Error in DynamicDataService modifyPathBasedOnCondition: ",n),i}}applyConditionalClasses(i,o){try{this.elementRef=i,this.data=o}catch(n){this.loggingService.catch("Error in DynamicDataService applyConditionalClasses: ",n)}}executeConditionalClasses(){try{let i=this.getHostElementAttributes(this.elementRef),n=[...Object.keys(i).filter(e=>e.startsWith("velt-class-")).map(e=>({name:e,value:i[e]}))];if(i["velt-class"]){let e=i["velt-class"],t=/'([^']+)':\s*([^,]+)(?:,|$)/g,r=[],a=0,s=100,c;for(;(c=t.exec(e))!==null;){if(a++>s){this.loggingService.catch("Too many class definitions detected.");break}if(c.length<3)continue;let[,p,u]=c;!p||!u||p.split(" ").forEach(C=>{C.trim()&&r.push({name:`velt-class-${C.trim()}`,value:u.trim()})})}n=[...n,...r]}this.data&&typeof this.data=="object"&&Object.keys(this.data).forEach(e=>{this.updateDataComponentConfigSignal(e,this.data[e])}),n.forEach(e=>{let t=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,t,this.elementRef,e.value))})}catch(i){this.loggingService.catch("Error in DynamicDataService applyConditionalClasses: ",i)}}updateDataComponentConfigSignal(i,o){try{i==="dataComponentConfigSignal"?this.dataComponentConfigSignal.set(o):this.dataComponentConfigSignal.update(n=>T(I({},n),{[i]:o}))}catch(n){this.loggingService.catch("Error in DataComponent updateDataComponentConfigSignal: ",n)}}extractProps(){try{this.extractedProps={},this.conditionRegex.lastIndex=0;let i;for(;(i=this.conditionRegex.exec(this.condition))!==null;){let o=i[1];this.extractedProps[o]={value:null,path:null,isDynamicPath:this.hasDynamicParts(o)}}}catch(i){this.loggingService.catch("Error in DynamicDataService extractProps: ",i)}}hasDynamicParts(i){try{let o=/\[[^\]'"]*[^\]'"]\]/.test(i),n=/\[[^[\]]*[\.\[][^[\]]*\]/.test(i);return o||n}catch(o){return this.loggingService.catch("Error checking for dynamic path: ",o),!1}}evaluateCondition(i,o,n){try{if(n){let e=this.extractedProps,t=n.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(t),a=this.safeEval(r);return i&&o&&(a?this.setHostElementClasses(o,i):this.removeHostElementClasses(o,i)),a}return!1}catch(e){return this.loggingService.catch("Error in IfComponent evaluateCondition: ",e),!1}}sanitizeCondition(i){try{return i.replace(/[^a-zA-Z0-9\s\+\-\*\/\%\(\)\!\=\<\>\|\&\.\[\]\{\},'"]/g,"")}catch(o){return this.loggingService.catch("Error in IfComponent sanitizeCondition: ",o),""}}safeEval(expression){try{if(this.configService.getSafeEval()){let i=this.tokenize(expression.trim());return this.evaluateTokens(i)}else return eval(expression)}catch(i){return this.loggingService.catch("safeEval error",i),!1}}tokenize(i){try{if(!i||i.trim()==="")return[];let o=[],n=0;for(;n<i.length;){let e=i[n];if(/\s/.test(e)){n++;continue}if(e==='"'||e==="'"){let t=e,r="";for(n++;n<i.length;)if(i[n]==="\\"&&n+1<i.length)r+=i[n+1],n+=2;else if(i[n]===t){n++;break}else r+=i[n],n++;o.push({type:"string",value:r});continue}if(e==="("){o.push({type:"lparen",value:"("}),n++;continue}if(e===")"){o.push({type:"rparen",value:")"}),n++;continue}if(n<i.length-2&&i.substring(n,n+3)==="==="){o.push({type:"operator",value:"===",precedence:4}),n+=3;continue}if(n<i.length-2&&i.substring(n,n+3)==="!=="){o.push({type:"operator",value:"!==",precedence:4}),n+=3;continue}if(n<i.length-1&&i.substring(n,n+2)==="&&"){o.push({type:"operator",value:"&&",precedence:2}),n+=2;continue}if(n<i.length-1&&i.substring(n,n+2)==="||"){o.push({type:"operator",value:"||",precedence:1}),n+=2;continue}if(n<i.length-1&&i.substring(n,n+2)==="<="){o.push({type:"operator",value:"<=",precedence:4}),n+=2;continue}if(n<i.length-1&&i.substring(n,n+2)===">="){o.push({type:"operator",value:">=",precedence:4}),n+=2;continue}if(n<i.length-1&&i.substring(n,n+2)==="=="){o.push({type:"operator",value:"==",precedence:4}),n+=2;continue}if(n<i.length-1&&i.substring(n,n+2)==="!="){o.push({type:"operator",value:"!=",precedence:4}),n+=2;continue}if(e==="!"){o.push({type:"unary",value:"!",precedence:5}),n++;continue}if(e==="<"){o.push({type:"operator",value:"<",precedence:4}),n++;continue}if(e===">"){o.push({type:"operator",value:">",precedence:4}),n++;continue}if(/[a-zA-Z0-9._]/.test(e)){let t="";for(;n<i.length&&/[a-zA-Z0-9._]/.test(i[n]);)t+=i[n],n++;/^-?\d+(\.\d+)?$/.test(t)?o.push({type:"number",value:parseFloat(t)}):t==="true"||t==="false"?o.push({type:"boolean",value:t==="true"}):t==="null"?o.push({type:"null",value:null}):t==="undefined"?o.push({type:"undefined",value:void 0}):o.push({type:"identifier",value:t});continue}n++}return o}catch(o){return this.loggingService.catch("tokenize error",o),[]}}evaluateTokens(i){try{if(!i||i.length===0)return!1;let o=this.infixToPostfix(i);return this.evaluatePostfix(o)}catch(o){return this.loggingService.catch("evaluateTokens error",o),!1}}infixToPostfix(i){try{let o=[],n=[];for(let e of i)if(e.type==="string"||e.type==="number"||e.type==="boolean"||e.type==="null"||e.type==="undefined"||e.type==="identifier")o.push(e);else if(e.type==="unary")n.push(e);else if(e.type==="operator"){for(;n.length>0;){let t=n[n.length-1];if(t.type==="lparen"||t.precedence!==void 0&&t.precedence<e.precedence)break;o.push(n.pop())}n.push(e)}else if(e.type==="lparen")n.push(e);else if(e.type==="rparen"){for(;n.length>0&&n[n.length-1].type!=="lparen";)o.push(n.pop());n.length>0&&n.pop()}for(;n.length>0;){let e=n.pop();e.type!=="lparen"&&e.type!=="rparen"&&o.push(e)}return o}catch(o){return this.loggingService.catch("infixToPostfix error",o),[]}}evaluatePostfix(i){try{let o=[];for(let n of i)if(n.type==="string"||n.type==="number"||n.type==="boolean"||n.type==="null"||n.type==="undefined"||n.type==="identifier")o.push(n.value);else if(n.type==="unary"){if(o.length>=1){let e=o.pop();n.value==="!"&&o.push(!this.isTruthy(e))}}else if(n.type==="operator"&&o.length>=2){let e=o.pop(),t=o.pop();n.value==="&&"?o.push(this.isTruthy(t)&&this.isTruthy(e)):n.value==="||"?o.push(this.isTruthy(t)||this.isTruthy(e)):o.push(this.compare(t,e,n.value))}return o.length===1?this.isTruthy(o[0]):!1}catch(o){return this.loggingService.catch("evaluatePostfix error",o),!1}}parseValue(i){try{let o=i.trim();return o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'")?o.substring(1,o.length-1):/^-?\d+(\.\d+)?$/.test(o)?parseFloat(o):o==="true"?!0:o==="false"?!1:o==="null"?null:o==="undefined"?void 0:o}catch(o){return this.loggingService.catch("parseValue error",o),i}}compare(i,o,n){try{switch(n){case"===":return i===o;case"!==":return i!==o;case"==":return i==o;case"!=":return i!=o;case"<":return i<o;case">":return i>o;case"<=":return i<=o;case">=":return i>=o;default:return!1}}catch(e){return this.loggingService.catch("compare error",e),!1}}isTruthy(i){try{return i==null||i===""||i==="false"?!1:i==="true"?!0:typeof i=="number"?i!==0:!!i}catch(o){return this.loggingService.catch("isTruthy error",o),!1}}getHostElementAttributes(i){try{let o=i,n={};for(let e of o.attributes)n[e.name]=e.value;return n}catch{return{}}}setHostElementClasses(i,o){try{i.classList.add(o)}catch{}}removeHostElementClasses(i,o){try{i.classList.remove(o)}catch{}}};_DynamicDataService.\u0275fac=function(o){return new(o||_DynamicDataService)(ee(Ve),ee(De),ee(y),ee(Ot),ee(at),ee(Ft))},_DynamicDataService.\u0275prov=Pe({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(t){this._loggingService.catch("Error in BaseComponent set veltIf:",t)}}constructor(e,t,r){this._elementRef=e,this._dynamicDataService=t,this._loggingService=r,this.componentConfigSignal=Te({}),this.veltElement=!0,this.conditionSignal=Te(null)}initializeComponentConfigSignal(e){try{this.componentConfigSignal.set(e)}catch(t){this._loggingService.catch("Error in BaseComponent initializeComponentConfigSignal:",t)}}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(t){this._loggingService.catch("Error in BaseComponent setIfCondition:",t)}}};o.\u0275fac=function(t){return new(t||o)(h(R),h(S),h(y))},o.\u0275cmp=O({type:o,selectors:[["app-base"]],hostVars:1,hostBindings:function(t,r){t&2&&x("data-velt-element",r.veltElement)},inputs:{componentConfigSignal:"componentConfigSignal",template:"template",wireframe:"wireframe",veltIf:"veltIf"},standalone:!1,decls:0,vars:0,template:function(t,r){},encapsulation:2});let i=o;return i})();var Je=(()=>{let o=class o extends H{onDarkModeChange(){return this.darkModeSubject$.asObservable()}constructor(e,t,r,a,s,c,p){super(e,c,p),this._elementRef=e,this._themeService=t,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 ve(!1);try{this._themeSubscriptions.push(this._themeService.getDarkMode$().subscribe(u=>{this._globalDarkMode=u,this.setDarkMode()})),this._featureService&&(this._featureService instanceof De?this._themeSubscriptions.push(this._featureService.getCommentContainerDarkMode().subscribe(u=>{this._featureDarkMode=u,this.setDarkMode()})):this._featureService instanceof rr&&this._themeSubscriptions.push(this._featureService.getDarkMode$().subscribe(u=>{u!==null&&(this._featureDarkMode=u),this.setDarkMode()}))),this._componentDarkModeObservable&&this._componentDarkModeObservable instanceof Ut&&this._themeSubscriptions.push(this._componentDarkModeObservable.subscribe(u=>{this._componentDarkMode=u,this.setDarkMode()}))}catch{}}ngOnInit(){super.ngOnInit()}ngOnChanges(e){try{if(e._darkMode){let t=e._darkMode.currentValue;typeof t=="string"&&(t=t==="true"),this._componentDarkMode=t,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(t){return new(t||o)(h(R),h(qe),h(Jt),h("FeatureService",8),h(Ut),h(S),h(y))},o.\u0275cmp=O({type:o,selectors:[["app-themed"]],inputs:{_darkMode:[0,"darkMode","_darkMode"]},standalone:!1,features:[B,Ze],decls:0,vars:0,template:function(t,r){},encapsulation:2,changeDetection:0});let i=o;return i})();var ze=(()=>{let o=class o{constructor(e){this.loggingService=e,this.wireframeMap=new ve(new Map);try{this.loggingService.log("%c[WB] Creating CLASS: WireframeService","color: blue;")}catch(t){this.loggingService.catch("Error in WireframeService constructor: ",t)}}setWireframe(e,t){try{let r=this.wireframeMap.value;r.set(e,t),this.wireframeMap.next(r)}catch(r){this.loggingService.catch("Error in WireframeService setWireframe: ",r)}}setWireframeMap(e){try{let t=this.wireframeMap.value;e.forEach((r,a)=>{t.set(a,r)}),this.wireframeMap.next(t)}catch(t){this.loggingService.catch("Error in WireframeService setWireframeMap: ",t)}}getWireframe(e,t=!0){try{let r=this.wireframeMap.value,a=r.get(e);if(!a&&t){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,t=!0){try{let r=this.wireframeMap.value,a=r.get(e);if(!a&&t){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,t=!0){return this.wireframeMap.asObservable().pipe(ce(r=>this.getWireframe(e,t)))}setChildren(e){try{this.wireframeMap.next(e)}catch(t){this.loggingService.catch("Error in WireframeService setChildren: ",t)}}getWireframeMap(){return this.wireframeMap.value}};o.\u0275fac=function(t){return new(t||o)(ee(y))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var ede=i=>({componentConfigSignal:i}),tRe=(i,o)=>({condition:i,data:o}),nRe=(i,o,n,e,t)=>({template:i,context:o,componentName:"velt-confirm-dialog-wireframe",variant:n,setIfCondition:e,componentElementRef:t});function iRe(i,o){if(i&1&&(f(0),w(1,"app-confirm-dialog-title",5)(2,"app-confirm-dialog-message",5),_(3,"div",6),w(4,"app-confirm-dialog-reject",5)(5,"app-confirm-dialog-approve",5),b(),v()),i&2){let n=l(3);m(),d("componentConfigSignal",n.componentConfigSignal),m(),d("componentConfigSignal",n.componentConfigSignal),m(2),d("componentConfigSignal",n.componentConfigSignal),m(),d("componentConfigSignal",n.componentConfigSignal)}}function oRe(i,o){if(i&1&&(f(0),g(1,iRe,6,4,"ng-container",4),v()),i&2){let n=l().ngIf,e=l();m(),d("veltDynamicTemplate",$(3,nRe,e.template,A(1,ede,e.componentConfigSignal),n.variant,e.setIfCondition.bind(e),e.elementRef))}}function rRe(i,o){if(i&1&&(f(0),g(1,oRe,2,9,"ng-container",3),v()),i&2){let n=l();m(),d("veltIf",k(3,tRe,n.conditionSignal(),A(1,ede,n.componentConfigSignal)))}}var Sa=(()=>{let o=class o extends Je{constructor(e,t,r,a,s,c,p){super(s,a,void 0,void 0,void 0,p,e),this.loggingService=e,this.dialogRef=t,this.wireframeService=r,this.themeService=a,this.elementRef=s,this.dynamicDataService=p,this.subscriptions=[],this.componentConfigSignal=Te({title:"",message:"",yesButton:"",noButton:"",variant:"",closeDialog:this.closeDialog.bind(this)}),this.componentId="velt-confirm-dialog",this.veltElement=!0;try{c&&(this.componentConfigSignal.update(u=>(u=I(I({},u),c),u)),c?.darkMode&&[!0,!1].includes(c?.darkMode)&&super.setComponentDarkMode(c?.darkMode)),this.setZIndex()}catch(u){this.loggingService.catch("Error in ConfirmDialogComponent constructor: ",u)}}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(t=>{if(t){let r=document.createElement(t.tagName);r.innerHTML=t.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(t){this.loggingService.catch("Error in ConfirmDialogComponent closeDialog: ",t)}}};o.\u0275fac=function(t){return new(t||o)(h(y),h(nr),h(ze),h(qe),h(R),h(Pl,8),h(S))},o.\u0275cmp=O({type:o,selectors:[["snippyly-confirm-dialog"]],hostVars:1,hostBindings:function(t,r){t&2&&x("data-velt-element",r.veltElement)},standalone:!1,features:[V([S]),B],decls:3,vars:5,consts:[["floatingConfirmationRef",""],[1,"velt-confirm-dialog",3,"snippylyOverlay","snippylyOverlayZIndex","snippylyOverlayBackdropZIndex"],[4,"ngIf"],[4,"veltIf"],[4,"veltDynamicTemplate"],[3,"componentConfigSignal"],["mat-dialog-actions","",1,"velt-confirm-dialog-actions"]],template:function(t,r){if(t&1&&(_(0,"div",1,0),g(2,rRe,2,6,"ng-container",2),b()),t&2){let a=de(1);d("snippylyOverlay",a)("snippylyOverlayZIndex",1200)("snippylyOverlayBackdropZIndex",1100),x("data-testid",r.componentId),m(2),d("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%] *[_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)}.velt-confirm-dialog-actions[_ngcontent-%COMP%]{justify-content:space-between;gap:var(--velt-spacing-md);min-height:auto} .velt-mat-dialog-container 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 i=o;return i})();var Vc=(()=>{let o=class o{constructor(e,t,r,a,s,c,p,u,C,E,D,L){this.analyticsService=e,this.configService=t,this.docService=r,this.databaseService=a,this.commonDbService=s,this.authService=c,this.domService=p,this.afAuth=u,this.iamService=C,this.dialog=E,this.loggingService=D,this.notificationService=L,this.areaAnnotationById$=new ve({}),this.documentPaths=null,this.areaEnabled$=new ve(!0),this.allowedElementIds$=new ve([]),this.addAreaMode$=new ve(!1),this.loggingService.log("%c[WB] Creating CLASS: AreaService","color: blue;"),this.analyticsService.setAreaService(this),this.authService.setAreaService(this),this.databaseService.getDb().pipe(Le(z=>!!z),st(1)).subscribe(z=>{z&&this.getDocumentPaths()},z=>{this.loggingService.catch("Error in AreaService getDb subscription: ",z)}),this.domService.onWindowPointerMove$().subscribe(z=>{if(this.addAreaMode$.value){this.highlightElement&&this.domService.removeHighlightFromElement(this.highlightElement);let W=this.domService.getBackgroundElement(z.clientX,z.clientY);W&&(this.isElementInsideAllowedElements(W)?KP(z.target)?this.domService.removeClassFromElement(document.body,"show-pin-cursor"):(this.domService.addClassToElement(document.body,"show-pin-cursor"),this.highlightElement=W,this.domService.highlightElement(this.highlightElement,j.CURSOR.AREA_PIN)):this.domService.removeClassFromElement(document.body,"show-pin-cursor"))}},z=>{this.loggingService.catch("Error in AreaService onWindowPointerMove$ subscription: ",z)}),this.domService.onWindowKeyupEsc$().subscribe(z=>{this.addAreaMode$.value&&this.disableAddAreaMode()},z=>{this.loggingService.catch("Error in AreaService onWindowKeyupEsc$ subscription: ",z)}),this.domService.onDocumentClick$().subscribe(z=>{if(z&&this.addAreaMode$.value){if(z.preventDefault(),z.stopPropagation(),!KP(z.target)){let W=this.domService.getBackgroundElement(z.clientX,z.clientY);W&&this.isElementInsideAllowedElements(W)&&this.addArea(z)}this.disableAddAreaMode()}},z=>{this.loggingService.catch("Error in AreaService onDocumentClick$ subscription: ",z)}),this.addAreaMode$.subscribe(z=>{this.highlightElement&&this.domService.removeHighlightFromElement(this.highlightElement),z?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"))},z=>{this.loggingService.catch("Error in AreaService addAreaMode$ subscription: ",z)}),this.domService.onWindowKeyupBackspace$().subscribe(z=>{this.deleteAreaPinAnnotations("keyupBackspace")},z=>{this.loggingService.catch("Error in AreaService onWindowKeyupBackspace$ subscription: ",z)}),this.domService.onWindowKeyupDelete$().subscribe(z=>{this.deleteAreaPinAnnotations("keyupDelete")},z=>{this.loggingService.catch("Error in AreaService onWindowKeyupDelete$ subscription: ",z)})}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,t,r){this.loggingService.log("%c[WB] Calling FUNCTION: getAllAreaAnnotations","color: green;");let a,s;try{if(e&&(s=En(e)),t&&typeof t=="object"){let c=Yo(t);a=En(JSON.stringify(c))}}catch(c){this.loggingService.catch("Error in AreaService getAllAreaAnnotations: ",c)}return ei(this.afAuth).pipe(Le(c=>!!c),he(c=>this.isFeatureAllowed({firebaseUser:c,annotations:[],filteredAnnotations:[]})),he(c=>c.featureAllowed?this.iamService.isUserAllowed$().pipe(ce(p=>(c.featureAllowed=p,c))):se(c)),he(c=>c.featureAllowed?this.authService.isPlanExpired$().pipe(ce(p=>(c.featureAllowed=!p,c))):se(c)),he(c=>c.featureAllowed?se(c).pipe(he(p=>this.docService.getDocumentPaths$().pipe(ce(u=>(this.documentPaths=u,p.documentPaths=u,p)))),he(p=>s?this.getDataFromDocumentIds([s]).pipe(ce(u=>(p.annotations=u||[],I({},p)))):this.docService.getDocumentIds$().pipe(he(u=>{let C=u?.length>0?u.map(E=>E.documentId):[this.documentPaths?.documentId??""];return this.getDataFromDocumentIds(C).pipe(ce(E=>(p.annotations=E||[],I({},p))))}))),he(p=>this.docService.getLocation$().pipe(ce(u=>(p.location=u,p)))),he(p=>this.docService.getLocations$().pipe(ce(u=>(p.customLocations=u,p)))),ce(p=>{if(p.filteredAnnotations=[],s&&!a)return p.filteredAnnotations=p.annotations?.slice(),p;{let u=[],C=[];return a?u.push(a):(u.push(p?.location?.locationId),u.push(...Object.values(p?.customLocations||[]).map(E=>E.locationId)),p?.location?.location?.id&&C.push(p?.location?.location?.id)),p.filteredAnnotations=this.filterAnnotationsByLocationIds(p?.annotations,u,C),p}}),he(p=>r?se(p):p?.annotations?.length?this.domService.onWindowResize$().pipe(ce(()=>p)):se(p)),he(p=>r?se(p):p?.annotations?.length?this.domService.onDomChange$("AreaService getAllAreaAnnotations").pipe(ce(()=>p)):se(p)),ce(p=>(p.filteredAnnotations=p.filteredAnnotations?.map(u=>{let C=Object.assign({},u);return C.areaProperties=this.calculateAreaAnnotationPosition(C),C}),p)),he(p=>p?.filteredAnnotations?se(p?.filteredAnnotations||[]):se([])),he(p=>{if(this.authService.isFeatureAllowed(Re.COMMENT))return se(p);{let u=p?.filter(C=>!C?.targetAnnotations?.filter(E=>E?.type===Re.COMMENT)?.length);return se(u)}})):se([])),Et(mn))}isFeatureAllowed(e){return this.configService.getConfig$().pipe(Le(t=>!!t),ce(t=>T(I({},e),{config:t})),he(t=>this.authService.getUser$().pipe(ce(r=>T(I({},t),{user:r})))),he(t=>ro(t.config,t.user,Re.AREA)?se(T(I({},t),{featureAllowed:!0})):(this.loggingService.warn("Area feature is not allowed."),se(T(I({},t),{featureAllowed:!1})))),Et((t,r)=>t?.featureAllowed===r?.featureAllowed))}getDataFromDocumentIds(e,t){return this.getDataFromDocuments({documentIds:e,filters:t})}getDataFromDocuments(e){if(this.configService.getApiKey()){let{documentIds:t,filters:r}=e;if(t?.some(u=>!u)||!this.documentPaths)return se([]);let a=this.docService.getDocumentPaths()?.veltFolderId,s=this.docService.getDocumentPaths()?.allDocuments,c=se([]),p={useCollectionGroup:!0,isCollection:!0,useQuery:!0};if(this.commonDbService.shouldUseFirestore()||(p.documentId=t?.length?t[0]:void 0,p.organizationId=this.documentPaths?.organizationId),a&&s)c=this.commonDbService.dbListener({feature:"allAreas",properties:T(I({},p),{firestoreQuery:[Zn(lt("metadata.apiKey","==",this.configService?.getApiKey()),lt("metadata.veltFolderId","==",a),lt("metadata.organizationId","==",this.documentPaths?.organizationId))]})});else{let u=[];for(let C=0;C<(t?.length??0);C+=j.LISTENER_BATCH_SIZE)u.push(t?.slice(C,C+j.LISTENER_BATCH_SIZE)??[]);c=Sn(u.map(C=>this.commonDbService.dbListener({feature:"allAreas",properties:T(I({},p),{firestoreQuery:[Zn(lt("metadata.apiKey","==",this.configService?.getApiKey()),lt("metadata.documentId","in",C),lt("metadata.organizationId","==",this.documentPaths?.organizationId),...a?[lt("metadata.veltFolderId","==",a)]:[])]})}).pipe(da()))).pipe(ce(C=>Ba(C)))}return c.pipe(ce(({data:u,operation:C})=>{let E=[];return u&&(E=Object.values(u??{}).filter(D=>typeof D=="object")),{data:E,operation:C}}),ce(({data:u,operation:C})=>{if(!t)return{data:u,documentMap:{},operation:C};let E=u.reduce((D,L)=>{let z=L.metadata?.documentId;return z&&(D[z]||(D[z]=[]),D[z].push(L)),D},{});return{data:u,documentMap:E,operation:C}}),ce(({data:u,documentMap:C,operation:E})=>{if(!r)if(E?.type==="removed"){if(E?.ids?.length){let D=this.areaAnnotationById$.value;E?.ids?.forEach(L=>{delete D?.[L]}),this.areaAnnotationById$.next(D)}}else Object.entries(C??{}).forEach(([D,L])=>{this.setAreaAnnotationsByOrganizationIdAndDocumentId({organizationId:this.documentPaths?.organizationId,documentId:D,annotations:L})});return u}))}else return se([])}setAreaAnnotationsByOrganizationIdAndDocumentId({organizationId:e,documentId:t,annotations:r,queryHash:a}){try{if(t){e||(e=j.NO_ORGANIZATION_ID),a||(a=j.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(t){this.loggingService.catch("Error in AreaService getAnnotationById: ",t);return}}filterAnnotationsByLocationIds(e,t,r){try{return e.filter(a=>t.includes(a.locationId)||r?.includes(a?.location?.id)||t?.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 t=e.targetElements[0],r=e.targetElements[1];if(t?.xpath&&r?.xpath){let a=this.domService.getElementFromXPath(t.xpath);a&&Xi(a)&&(a=null),this.domService.isXpathWithId(t.xpath)||(!a&&t.cfXpath&&(a=this.domService.getElementFromXPath(t.cfXpath),a&&Xi(a)&&(a=null)),!a&&t.fXpath&&(a=this.domService.getElementFromXPath(t.fXpath),a&&Xi(a)&&(a=null)));let c=this.domService.getElementFromXPath(r.xpath);if(c&&Xi(c)&&(c=null),this.domService.isXpathWithId(r.xpath)||(!c&&r.cfXpath&&(c=this.domService.getElementFromXPath(r.cfXpath),c&&Xi(c)&&(c=null)),!c&&r.fXpath&&(c=this.domService.getElementFromXPath(r.fXpath),c&&Xi(c)&&(c=null))),a&&c){let u=Lj(a,c);if(u){let C=a.getBoundingClientRect(),E={};C&&C.width&&C.height&&(E={top:C.height*t.topPercentage/100,left:C.width*t.leftPercentage/100});let D=c.getBoundingClientRect(),L={};D&&D.width&&D.height&&(L={top:D.height*r.topPercentage/100,left:D.width*r.leftPercentage/100});let z=Bj(E.left,E.top,a,u),W=Bj(L.left,L.top,c,u),J,ue,ye,Ae,He={};z.x>W.x?z.y>W.y?(Ae={x:z.x,y:z.y},J={x:W.x,y:W.y},He.handle1=Ae,He.handle2=J):(ue={x:z.x,y:z.y},ye={x:W.x,y:W.y},He.handle1=ue,He.handle2=ye):z.y>W.y?(ye={x:z.x,y:z.y},ue={x:W.x,y:W.y},He.handle1=ye,He.handle2=ue):(J={x:z.x,y:z.y},Ae={x:W.x,y:W.y},He.handle1=J,He.handle2=Ae);let Fe={topLeft:J||{x:ye?.x,y:ue?.y},bottomRight:Ae||{x:ue?.x,y:ye?.y},topRight:ue||{x:Ae?.x,y:J?.y},bottomLeft:ye||{x:J?.x,y:Ae?.y}};return He.coordinates=Fe,He.targetElement=this.domService.getXPath(u),He}}}}return}catch(t){this.loggingService.catch("Error in AreaService calculateAreaAnnotationPosition:",t);return}}addArea(e,t=[],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 lk;a&&(p.annotationId=a),p.from=c,p.color=j.DEFAULT_ANNOTATION_COLOR,p.lastUpdated=this.timestamp,r&&(p.targetAnnotations=[r]),p.props=new Bl;let u=this.domService.getCurrentWindowSizeValue();if(p.props.screenWidth=u.screenWidth,p.props.screenHeight=u.screenHeight,p.props.screenScrollHeight=u.screenScrollHeight,p.props.viewportWidth=window.innerWidth,p.props.viewportHeight=window.innerHeight,e||t?.length>0){let D=e?this.getPointsForAreaPinAnnotation(e):t;p.targetElements=[],D.forEach(L=>{p.targetElements.push(this.getTargetElementForAreaPinAnnotation(e,{clientX:L.x,clientY:L.y}))})}this.setLocationToAreaAnnotation(p),s&&(p.locationId=s.locationId,p.location=s.location),p.pageInfo=Oi(),p.pageInfo&&(p.pageInfo.screenWidth=this.domService.getCurrentWindowSizeValue()?.screenWidth);let C=this.getElementForAreaAnnotation(p),E=this.docService.getBaseMetadata("area",{element:C});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 t=this.docService.getLocation();t?(e.locationId=t.locationId,e.location=t.location):(delete e.locationId,delete e.location)}catch(t){this.loggingService.catch("Error in AreaService setLocationToAreaAnnotation:",t)}}getElementForAreaAnnotation(e){try{let t,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))),t=Lj(r,a),t}catch(t){return this.loggingService.catch("Error in AreaService getElementForAreaAnnotation: ",t),null}}saveAreaToDb(e){this.loggingService.log("%c[WB] Calling FUNCTION: saveAreaToDb","color: green;");try{this.authService.getUser()&&this.authService.isFeatureAllowed(Re.AREA)&&Sn([this.docService.getDocumentPaths$(),this.databaseService.getDb()]).pipe(Le(([t,r])=>!!t&&!!r),st(1),he(([t,r])=>{if(this.documentPaths=t,this.documentPaths?.area){e.annotationId||(e.annotationId=this.commonDbService.generateDocumentId()),e.pageInfo&&(e.pageInfo.areaUrl=this.generateAreaUrl(e));let a=JSON.parse(JSON.stringify(e));if(a.position=null,!a?.metadata?.documentId){a?.metadata||(a.metadata={});let p=this.docService.getBaseMetadata();a.metadata=I(I({},a?.metadata),p)}this.domService.toggleAnnotationSelection(a),this.analyticsService.trackEvent(Z.Events.Area.AREA_ADDED,{annotationId:e.annotationId});let{documentId:s,organizationId:c}=this.getDocumentIdAndOrganizationIdFromAreaAnnotation(e);return this.commonDbService.setData({feature:"area",properties:{id:e.annotationId,documentId:s,organizationId:c},data:JSON.parse(JSON.stringify(a))})}else return se(null)})).subscribe(()=>{},t=>{this.loggingService.catch("Error in AreaService saveAreaToDb subscription: ",t)})}catch(t){this.loggingService.catch("Error in AreaService saveAreaToDb: ",t)}}getDocumentIdAndOrganizationIdFromAreaAnnotation(e){try{return{documentId:e?.metadata?.documentId,organizationId:e?.metadata?.organizationId}}catch(t){return this.loggingService.catch("Error in AreaService getDocumentIdAndOrganizationIdFromAreaAnnotation: ",t),{}}}updateArea(e,t=!1,r){try{r&&this.setLocationToAreaAnnotation(e),t&&this.updateNotificationsDatabase(e,jP.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 t=JSON.parse(JSON.stringify(e));if(t.position=null,!t?.metadata?.documentId){t?.metadata||(t.metadata={});let s=this.docService.getBaseMetadata();t.metadata=I(I({},t?.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(t))})}}catch(t){this.loggingService.catch("Error in AreaService updateAreaToDb: ",t)}}deleteAreaPinAnnotations(e){try{let t=this.domService.getSelectedAnnotationsMap(),r=this.authService.getUser(),a=[];Object.keys(t??{}).forEach(s=>Q(this,null,function*(){let c=t[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(Sa,{panelClass:"velt-mat-dialog-container",data:{title:"Delete area?",message:"This selected area will be deleted.",yesButton:"Delete",noButton:"Cancel",variant:"area"}}).afterClosed().pipe(st(1)).subscribe(s=>{s&&(a.forEach(c=>Q(this,null,function*(){yield this.deleteAreaPinAnnotation(c)})),setTimeout(()=>{document.querySelectorAll(`[${j.SNIPPYLY_HIGHLIGHT}]`).forEach(p=>{this.domService.removeHighlightFromElement(p)})},100))})),this.domService.resetSelectedAnnotationsMap(!0,"area")}catch(t){this.loggingService.catch("Error in AreaService deleteAreaPinAnnotations: ",t)}}getAreaAnnotationsByOrganizationIdAndDocumentId({organizationId:e,documentId:t}){try{let r={};return Object.values(this.areaAnnotationById$.value??{}).forEach(a=>{a?.metadata?.documentId==t&&a?.metadata?.organizationId==e&&(r[a?.annotationId]=a)}),Object.values(r??{})}catch(r){return this.loggingService.catch("Error in AreaService getAreaAnnotationsByOrganizationIdAndDocumentId:",r),[]}}onDeleteTargetAnnotation(e,t){try{if(this.docService.getDocumentId()&&this.areaAnnotationById$.value){let a=Object.values(this.areaAnnotationById$.value||{}),s;t?s=a.find(c=>c?.annotationId===t):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,jP.DELETED),this.analyticsService.trackEvent(Z.Events.Area.AREA_DELETED,{annotationId:e.annotationId});let{documentId:t,organizationId:r}=this.getDocumentIdAndOrganizationIdFromAreaAnnotation(e);return this.commonDbService.deleteData({feature:"area",properties:{id:e.annotationId,documentId:t,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),se(!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,t){try{let r=e,a=r?.touches?.length?r.touches[0]?.clientX:r?.clientX,s=r?.touches?.length?r.touches[0]?.clientY:r?.clientY;t&&(a=t.clientX,s=t.clientY);let c=this.domService.getBackgroundElement(a,s);if(c){let p=this.domService.getXPath(c),u=this.domService.getXPath(c,!0),C=this.domService.getXPath(c,!0,!0),E=c.getBoundingClientRect(),D=a-E.x,L=s-E.y,z=D*100/(E.width||1),W=L*100/(E.height||1);return{xpath:p,fXpath:u,cfXpath:C,leftPercentage:z,topPercentage:W}}else return null}catch(r){return this.loggingService.catch("Error in AreaService getTargetElementForAreaPinAnnotation: ",r),null}}getPointsForAreaPinAnnotation(e){let t=[],r=e,a=r?.touches?.length?r.touches[0]?.clientX:r.clientX,s=r?.touches?.length?r.touches[0]?.clientY:r.clientY;return t.push({x:a,y:s}),t.push({x:a+100,y:s+100}),t}get timestamp(){return this.commonDbService.getServerTimestamp()}isElementInsideAllowedElements(e){try{return this.domService.isElementInsideListedElementIds(e,this.allowedElementIds$.value)}catch(t){return this.loggingService.catch("Error in AreaService isElementInsideAllowedElements: ",t),!1}}updateNotificationsDatabase(e,t){try{let r={annotationData:e,actionType:t,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=Oi(),e.pageInfo&&(e.pageInfo.screenWidth=this.domService.getCurrentWindowSizeValue()?.screenWidth)),e.pageInfo.areaUrl=this.generateAreaUrl(e),this.updateArea(e),e.pageInfo?.areaUrl)}catch(t){this.loggingService.catch("Error in AreaService getAreaUrl: ",t);return}}generateAreaUrl(e){let t=new URL(window.location.href);return t.searchParams.delete(j.URL_PARAMS.TAG_ID),t.searchParams.append(j.URL_PARAMS.TAG_ID,e.annotationId),t.href}generateAreaAnnotationId(){return Q(this,null,function*(){try{if(this.docService.getDocumentPaths()?.area){let t=this.commonDbService.generateDocumentId();return yield Pd(10),t||""}else return""}catch(e){return this.loggingService.catch("Error in AreaService generateAreaAnnotationId: ",e),""}})}};o.\u0275fac=function(t){return new(t||o)(ee(et),ee(Ft),ee(at),ee(Dn),ee(pn),ee(Ve),ee(Be),ee(Di),ee(vn),ee(no),ee(y),ee(gn))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var si=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,n={},e=!0){try{this.hideAnalytics||(n||(n={}),n=T(I({},n),{source:"external"}),this.getService(et).trackAuthenticatedEvent(o,n,e))}catch(t){this.getService(y).catch("Error in _trackEvent: ",t);return}}};var jk=class extends si{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(Vc).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(Vc).disableArea()}catch(o){this.getService(y).catch("Error in _disableAreaComment: ",o)}}};var zd=(()=>{let o=class o{constructor(e,t,r,a,s,c,p,u,C,E,D,L){this.analyticsService=e,this.configService=t,this.docService=r,this.databaseService=a,this.authService=s,this.domService=c,this.afAuth=p,this.iamService=u,this.dialog=C,this.loggingService=E,this.notificationService=D,this.commonDbService=L,this.arrowAnnotations$=new ve({}),this.arrowAnnotationsByDocumentId$=new ve({}),this.documentPaths=null,this.allowedElementIds$=new ve([]),this.addArrowMode$=new ve(!1),this.loggingService.log("%c[WB] Creating CLASS: ArrowService","color: blue;"),this.databaseService.getDb().pipe(Le(z=>!!z),st(1)).subscribe(z=>{z&&this.getDocumentPaths()},z=>{this.loggingService.catch("Error in ArrowService getDb subscription: ",z)}),this.domService.onWindowPointerMove$().subscribe(z=>{if(this.addArrowMode$.value){let W=!0,J=this.domService.getBackgroundElement(z.clientX,z.clientY);J&&(this.isElementInsideAllowedElements(J)?YP(z.target)?this.domService.removeClassFromElement(document.body,"show-pin-cursor"):(this.domService.addClassToElement(document.body,"show-pin-cursor"),this.highlightElement&&this.highlightElement!==J&&this.domService.removeHighlightFromElement(this.highlightElement),this.highlightElement=J,this.domService.highlightElement(this.highlightElement,j.CURSOR.ARROW_PIN),W=!1):this.domService.removeClassFromElement(document.body,"show-pin-cursor")),this.highlightElement&&W&&(this.domService.removeHighlightFromElement(this.highlightElement),this.highlightElement=null)}},z=>{this.loggingService.catch("Error in ArrowService onWindowPointerMove$ subscription: ",z)}),this.domService.onWindowKeyupEsc$().subscribe(z=>{this.addArrowMode$.value&&this.disableAddArrowMode()},z=>{this.loggingService.catch("Error in ArrowService onWindowKeyupEsc$ subscription: ",z)}),this.domService.onDocumentClick$().subscribe(z=>{if(z&&this.addArrowMode$.value){if(!YP(z.target)){let W=this.domService.getBackgroundElement(z.clientX,z.clientY);W&&this.isElementInsideAllowedElements(W)&&(z.preventDefault(),z.stopPropagation(),this.addArrow(z))}this.disableAddArrowMode()}},z=>{this.loggingService.catch("Error in ArrowService onDocumentClick$ subscription: ",z)}),this.addArrowMode$.subscribe(z=>{this.highlightElement&&this.domService.removeHighlightFromElement(this.highlightElement),z?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"))},z=>{this.loggingService.catch("Error in ArrowService addArrowMode$ subscription: ",z)}),this.domService.onWindowKeyupBackspace$().subscribe(z=>{this.deleteArrowPinAnnotations("keyupBackspace")},z=>{this.loggingService.catch("Error in ArrowService onWindowKeyupBackspace$ subscription: ",z)}),this.domService.onWindowKeyupDelete$().subscribe(z=>{this.deleteArrowPinAnnotations("keyupDelete")},z=>{this.loggingService.catch("Error in ArrowService onWindowKeyupDelete$ subscription: ",z)})}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,t,r){this.loggingService.log("%c[WB] Calling FUNCTION: getAllArrowAnnotations","color: green;");let a,s;try{if(e&&(s=En(e)),t&&typeof t=="object"){let c=Yo(t);a=En(JSON.stringify(c))}}catch(c){this.loggingService.catch("Error in ArrowService getAllArrowAnnotations: ",c)}return ei(this.afAuth).pipe(Le(c=>!!c),he(c=>this.isFeatureAllowed({firebaseUser:c,annotations:[],filteredAnnotations:[]})),he(c=>c.featureAllowed?this.iamService.isUserAllowed$().pipe(ce(p=>(c.featureAllowed=p,c))):se(c)),he(c=>c.featureAllowed?this.authService.isPlanExpired$().pipe(ce(p=>(c.featureAllowed=!p,c))):se(c)),he(c=>c.featureAllowed?se(c).pipe(he(p=>this.docService.getDocumentPaths$().pipe(ce(u=>(this.documentPaths=u,p.documentPaths=u,p)))),he(p=>this.getDataFromDocumentId(s).pipe(ce(u=>(p.annotations=u||[],I({},p))))),he(p=>this.docService.getLocation$().pipe(ce(u=>(p.location=u,p)))),he(p=>this.docService.getLocations$().pipe(ce(u=>(p.customLocations=u,p)))),ce(p=>{if(p.filteredAnnotations=[],s&&!a)return p.filteredAnnotations=p.annotations?.slice(),p;{let u=[];return a?u.push(a):(u.push(p?.location?.locationId),u.push(...Object.values(p?.customLocations||[]).map(C=>C.locationId))),p.filteredAnnotations=this.filterAnnotationsByLocationIds(p?.annotations,u),p}}),he(p=>r?se(p):p?.annotations?.length?this.domService.onWindowResize$().pipe(ce(()=>p)):se(p)),he(p=>r?se(p):p?.annotations?.length?this.domService.onDomChange$("ArrowService getAllArrowAnnotations").pipe(ce(()=>p)):se(p)),ce(p=>(p?.filteredAnnotations?.forEach(u=>{this.calculateArrowAnnotationPosition(u)}),p)),he(p=>p?.filteredAnnotations?se(p?.filteredAnnotations||[]):se([]))):se([])),Et(mn))}isFeatureAllowed(e){return this.configService.getConfig$().pipe(Le(t=>!!t),ce(t=>T(I({},e),{config:t})),he(t=>this.authService.getUser$().pipe(ce(r=>T(I({},t),{user:r})))),he(t=>ro(t.config,t.user,Re.ARROW)?se(T(I({},t),{featureAllowed:!0})):(this.loggingService.warn("Arrow feature is not allowed."),se(T(I({},t),{featureAllowed:!1})))),Et((t,r)=>t?.featureAllowed===r?.featureAllowed))}getDataFromDocumentId(e){return this.databaseService.getDb().pipe(Le(t=>!!t),he(t=>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}}),kn(r=>(this.loggingService.catch("Error in ArrowService getDataFromDocumentId: ",r),se({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})):se([])))}setArrowAnnotationsByDocumentId(e,t){try{if(e){let r=T(I({},this.arrowAnnotationsByDocumentId$.value),{[e]:t});this.arrowAnnotationsByDocumentId$.next(r)}}catch(r){this.loggingService.catch("Error in ArrowService setArrowAnnotationsByDocumentId:",r)}}filterAnnotationsByLocationIds(e,t){try{return e.filter(r=>t.includes(r.locationId))}catch(r){return this.loggingService.catch("Error in ArrowService filterAnnotationsByLocations:",r),[]}}calculateArrowAnnotationPosition(e){try{if(e.targetElement){let t=this.domService.getXPath(e.targetElement?.xpath);if(t){let r=t.iterateNext();if(r&&Ao(r)){let a=r.getBoundingClientRect();if(a&&a.width&&a.height){let{height:s,width:c}=Wp(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(t){this.loggingService.catch("Error in ArrowService calculateArrowAnnotationPosition:",t)}}addArrow(e){this.loggingService.log("%c[WB] Calling FUNCTION: addArrow","color: green;");try{let t=this.authService.getUser();if(t)if(t.isReadOnly||t.isAnonymous)this.loggingService.catch("Anonymous/Readonly users cannot add arrows.");else{let r=new ck;r.from=t,r.color=t?.color||j.DEFAULT_ANNOTATION_COLOR,r.lastUpdated=this.timestamp,r.props=new Bl;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=j.VELT_MIN_ARROW_LENGTH,(e?.clientX||0)>j.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&&(Ao(c)||(r.targetElement=null))}}this.setLocationToArrowAnnotation(r),r.pageInfo=Oi(),r.pageInfo&&(r.pageInfo.screenWidth=this.domService.getCurrentWindowSizeValue()?.screenWidth),this.saveArrowToDb(r)}}catch(t){this.loggingService.catch("Error in ArrowService addArrow: ",t)}}setLocationToArrowAnnotation(e){try{let t=this.docService.getLocation();t?(e.locationId=t.locationId,e.location=t.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({location:a,source:"internal"});s?.[0]&&(e.locationId=s[0].locationId,e.location=s[0].location)}}}catch{}}catch(t){this.loggingService.catch("Error in ArrowService setLocationToArrowAnnotation:",t)}}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(Le(t=>!!t),st(1),he(t=>(this.documentPaths=t,this.loggingService.log(this.documentPaths),this.databaseService.getDb().pipe(Le(r=>!!r),st(1),he(r=>{if(this.documentPaths?.arrow){e.annotationId=this.commonDbService.generateDocumentId(),e.pageInfo&&(e.pageInfo.arrowUrl=this.generateArrowUrl(e));let a=JSON.parse(JSON.stringify(e));return a.position=null,this.domService.toggleAnnotationSelection(a),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(a))})}else return se(null)}))))).subscribe(()=>{},t=>{this.loggingService.catch("Error in ArrowService saveArrowToDb subscription: ",t)})}catch(t){this.loggingService.catch("Error in ArrowService saveArrowToDb: ",t)}}updateArrow(e,t=!1,r){try{r&&this.setLocationToArrowAnnotation(e),t&&this.updateNotificationsDatabase(e,UP.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 t=this.domService.getXPath(e.targetElement.xpath);if(t){let r=t.iterateNext();r&&(Ao(r)||(e.targetElement=null))}}this.domService.updateSelectedAnnotationInMap([e]),this.authService.getUser()&&this.authService.isFeatureAllowed(Re.ARROW)&&this.docService.getDocumentPaths$().pipe(Le(t=>!!t),st(1),he(t=>(this.documentPaths=t,this.loggingService.log(this.documentPaths),this.databaseService.getDb().pipe(Le(r=>!!r),st(1),he(r=>{if(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 se(null)}))))).subscribe(()=>{},t=>{this.loggingService.catch("Error in ArrowService updateArrowToDb subscription: ",t)})}catch(t){this.loggingService.catch("Error in ArrowService updateArrowToDb: ",t)}}deleteArrowPinAnnotations(e){try{let t=this.domService.getSelectedAnnotationsMap(),r=this.authService.getUser(),a=[];Object.keys(t).forEach(s=>Q(this,null,function*(){let c=t[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(Sa,{panelClass:"velt-mat-dialog-container",data:{title:"Delete arrow?",message:"This selected arrow will be deleted.",yesButton:"Delete",noButton:"Cancel",variant:"arrow"}}).afterClosed().pipe(st(1)).subscribe(s=>{s&&(a.forEach(c=>Q(this,null,function*(){yield this.deleteArrowPinAnnotation(c)})),setTimeout(()=>{document.querySelectorAll(`[${j.SNIPPYLY_HIGHLIGHT}]`).forEach(p=>{this.domService.removeHighlightFromElement(p)})},100))})),this.domService.resetSelectedAnnotationsMap(!0,"arrow")}catch(t){this.loggingService.catch("Error in ArrowService deleteArrowPinAnnotations: ",t)}}deleteArrowPinAnnotation(e){return this.authService.isFeatureAllowed(Re.ARROW)&&this.documentPaths?.arrow&&e?.annotationId?(this.updateNotificationsDatabase(e,UP.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(t){return this.loggingService.catch("Error in ArrowService isElementInsideAllowedElements: ",t),!1}}updateNotificationsDatabase(e,t){try{let r={annotationData:e,actionType:t,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=Oi(),e.pageInfo&&(e.pageInfo.screenWidth=this.domService.getCurrentWindowSizeValue()?.screenWidth)),e.pageInfo.arrowUrl=this.generateArrowUrl(e),this.updateArrow(e),e.pageInfo?.arrowUrl)}catch(t){this.loggingService.catch("Error in ArrowService getArrowUrl: ",t);return}}generateArrowUrl(e){let t=new URL(window.location.href);return t.searchParams.delete(j.URL_PARAMS.TAG_ID),t.searchParams.append(j.URL_PARAMS.TAG_ID,e.annotationId),t.href}};o.\u0275fac=function(t){return new(t||o)(ee(et),ee(Ft),ee(at),ee(Dn),ee(Ve),ee(Be),ee(Di),ee(vn),ee(no),ee(y),ee(gn),ee(pn))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var Hk=class extends si{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(zd).setAllowedElementIds(o)}catch(n){this.getService(y).catch("Error in allowedElementIds: ",n)}}};var dl=(()=>{let o=class o{constructor(e){this.loggingService=e,this.autocompleteDataMap$=new ve({}),this.onAutocompleteChipClick$=new tt;try{this.loggingService.log("%c[WB] Creating CLASS: AutocompleteService","color: blue;"),this.create({hotkey:"@",type:"contact",data:[]})}catch(t){this.loggingService.catch("Error in AutocompleteService constructor: ",t)}}create(e){try{if(this.loggingService.log("%c[WB] Calling AutocompleteService FUNCTION: create","color: green;"),e?.hotkey){let t=this.autocompleteDataMap$.value;t[e.hotkey]=e,this.autocompleteDataMap$.next(t)}}catch(t){this.loggingService.catch("Error in AutocompleteService create: ",t)}}remove(e){try{this.loggingService.log("%c[WB] Calling AutocompleteService FUNCTION: remove","color: green;");let t=this.autocompleteDataMap$.value;delete t[e],this.autocompleteDataMap$.next(t)}catch(t){this.loggingService.catch("Error in AutocompleteService remove: ",t)}}getAutocompleteDataMap$(){return this.autocompleteDataMap$.asObservable()}getAutocompleteDataMap(){return this.autocompleteDataMap$.value}setOnAutocompleteChipClick(e){this.onAutocompleteChipClick$.next(e)}getOnAutocompleteChipClick$(){return this.onAutocompleteChipClick$.asObservable()}};o.\u0275fac=function(t){return new(t||o)(ee(y))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var Gk=class extends si{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(dl).create(o)}catch(n){this.getService(y).catch("Error in _create: ",n)}}_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(dl).getOnAutocompleteChipClick$()}catch(o){return this.getService(y).catch("Error in _onAutocompleteChipClick: ",o),se(null)}}};var tde=(()=>{let o=class o{constructor(e,t,r,a,s,c,p){this.authService=e,this.iamService=t,this.docService=r,this.configService=a,this.commonDbService=s,this.loggingService=c,this.commentService=p,this.documentPaths=null,this.LISTENER_BATCH_SIZE=30}getAnnotationsCount(e){try{return this.authService.getUser$().pipe(Le(t=>!!t),he(t=>this.commentService.isFeatureAllowed({firebaseUser:t,annotations:[],filteredAnnotations:[]})),he(t=>t.featureAllowed?this.iamService.isUserAllowed$().pipe(ce(r=>(t.featureAllowed=r,t))):se(t)),he(t=>t.featureAllowed?this.processRequest(t,e):se(null)),ce(t=>t??{data:null}),Et(mn))}catch(t){return this.loggingService.catch("Error in CommentService getAnnotationsCount: ",t),se({data:null})}}processRequest(e,t){try{return se(e).pipe(he(()=>this.initializeDocumentPaths(e)),he(()=>this.getDocumentIds$(t)),he(r=>{let a=this.authService.getUser()?.userSnippylyId,s=this.buildRequestContext(t,r);if(!this.validateRequestContext(s,t))return se({data:null,mode:s.mode,serverDocumentIds:s.serverDocumentIds});if(!s.organizationId)return se({data:null,mode:s.mode,serverDocumentIds:s.serverDocumentIds});let c=this.setupTriggers$(s.mode,s.organizationId,s.veltFolderId,s.serverDocumentIds);return this.shouldUseAggregateMode(s.mode)?this.handleAggregateCounts$({triggers$:c,serverDocumentIds:s.serverDocumentIds,request:t,userId:a,organizationId:s.organizationId,clientOrganizationId:s.clientOrganizationId,veltFolderId:s.veltFolderId,folderId:s.folderId,mode:s.mode}).pipe(ce(p=>({data:p,mode:s.mode,serverDocumentIds:s.serverDocumentIds}))):this.handleGroupedCounts$(c,r,t,a,s.organizationId,s.veltFolderId).pipe(ce(p=>({data:p,mode:s.mode,serverDocumentIds:s.serverDocumentIds})))}),he(r=>{if(!r?.data)return se(null);let{data:a,mode:s,serverDocumentIds:c}=r;return t?.filterGhostComments?this.filterGhostComments$(a,s,c):se(a)}),kn(r=>(this.loggingService.catch("Error processing request: ",r),se(null))))}catch(r){return this.loggingService.catch("Error in CommentService getAnnotationsCount: ",r),se(null)}}initializeDocumentPaths(e){try{return this.docService.getDocumentPaths$().pipe(Le(t=>!!t),dn(t=>{this.documentPaths=t,e.documentPaths=t}),ce(()=>{}))}catch(t){return this.loggingService.catch("Error in CommentService initializeDocumentPaths: ",t),se(e)}}buildRequestContext(e,t){try{let r=this.documentPaths?.organizationId,a=this.documentPaths?.clientOrganizationId,s,c,p;if(e?.allDocuments||e?.documentIds||e?.folderId||e?.organizationId||e?.locationIds){if(e.organizationId&&(r=La(e.organizationId),a=e.organizationId),!r)throw new Error("organizationId is required for this request type");e.folderId&&(s=Fi(e.folderId),c=e.folderId),e.allDocuments&&(p=!0)}else s=this.documentPaths?.veltFolderId,c=this.documentPaths?.folderId,p=this.documentPaths?.allDocuments;let u=this.determineMode(e,s,p,t),C=u.isOrgMode?[]:t.length>0?t.map(E=>E.documentId):[this.documentPaths?.documentId??""];return{organizationId:r,clientOrganizationId:a,veltFolderId:s,folderId:c,allDocuments:p,mode:u,serverDocumentIds:C}}catch(r){return this.loggingService.catch("Error in CommentService buildRequestContext: ",r),{organizationId:void 0,clientOrganizationId:void 0,veltFolderId:void 0,folderId:void 0,allDocuments:void 0,mode:{isOrgMode:!1,isFolderMode:!1,isBatchMode:!1},serverDocumentIds:[]}}}validateRequestContext(e,t){try{if(t?.aggregateDocuments&&!e.serverDocumentIds.length)throw this.loggingService.catch("Error in CommentService getAnnotationsCount: documentIds is required when aggregateDocuments is true"),new Error("documentIds is required when aggregateDocuments is true");return!(!e.organizationId||!(e.mode.isOrgMode||e.mode.isFolderMode)&&e.serverDocumentIds.some(r=>!r)||!this.documentPaths)}catch(r){return this.loggingService.catch("Error in CommentService validateRequestContext: ",r),!1}}shouldUseAggregateMode(e){try{return e.isFolderMode||e.isOrgMode||e.isBatchMode}catch(t){return this.loggingService.catch("Error in CommentService shouldUseAggregateMode: ",t),!1}}getDocumentIds$(e){try{return e?.documentIds?.length?se(e.documentIds.map(t=>({clientDocumentId:t,documentId:na(t)}))):this.docService.getDocumentIds$().pipe(ce(t=>t.length>0?t:[{documentId:this.documentPaths?.documentId??"",clientDocumentId:this.documentPaths?.clientDocumentId||""}]))}catch(t){return this.loggingService.catch("Error in CommentService getDocumentIds: ",t),se([])}}determineMode(e,t,r,a){try{let s=!!e?.organizationId&&!e?.documentIds?.length&&!t&&!r,c=!!t&&!!r,p=!!e?.aggregateDocuments&&!r&&!!a?.length;return{isOrgMode:s,isFolderMode:c,isBatchMode:p}}catch(s){return this.loggingService.catch("Error in CommentService determineMode: ",s),{isOrgMode:!1,isFolderMode:!1,isBatchMode:!1}}}setupTriggers$(e,t,r,a){try{if(e.isOrgMode)return[this.commonDbService.dbListener({feature:"organizationMetadata",properties:{useCollectionGroup:!1,isCollection:!1,organizationId:t}}).pipe(ce(c=>c?.data?.commentViewsUpdatedAt??null),Le(c=>!!c),Et(mn))];if(e.isFolderMode)return[this.commonDbService.dbListener({feature:"folder",properties:{useCollectionGroup:!1,isCollection:!1,folderId:r,organizationId:t}}).pipe(ce(c=>c?.data?.commentViewsUpdatedAt??null),Le(c=>!!c),Et(mn))];if(e.isBatchMode){let s=[];for(let c=0;c<a.length;c+=this.LISTENER_BATCH_SIZE)s.push(a.slice(c,c+this.LISTENER_BATCH_SIZE));return s.map(c=>this.commonDbService.dbListener({feature:"allDocuments",properties:{useCollectionGroup:!0,isCollection:!0,useQuery:!0,firestoreQuery:[Zn(lt("metadata.apiKey","==",this.configService?.getApiKey()),lt("metadata.organizationId","==",t),lt("metadata.documentId","in",c))]}}).pipe(ce(u=>Object.values(u?.data||{}).map(E=>E?.commentViewsUpdatedAt??null).sort().join(",")),Et(mn)))}else return a.map(s=>this.commonDbService.dbListener({feature:"documentMetadata",properties:{useCollectionGroup:!1,isCollection:!1,documentId:s,organizationId:t}}).pipe(ce(p=>p?.data?.commentViewsUpdatedAt??null),Le(p=>!!p),Et(mn)))}catch(s){return this.loggingService.catch("Error in CommentService setupTriggers: ",s),[]}}handleGroupedCounts$(e,t,r,a,s,c){try{let p=t.map((u,C)=>e[C].pipe(bo(void 0),he(()=>Zi(this.getCountsForDocument$(u.documentId,u.clientDocumentId,r,a,s,c)))));return Sn(p).pipe(ce(u=>{let C={};return u.forEach(E=>{E&&(C[E.clientDocumentId]={total:E.total,unread:E.unread})}),{data:C}}),kn(u=>(this.loggingService.catch("Error in grouped counts: ",u),se(null))))}catch(p){return this.loggingService.catch("Error in CommentService handleGroupedCounts: ",p),se(null)}}handleAggregateCounts$(e){try{let{triggers$:t,serverDocumentIds:r,request:a,userId:s,organizationId:c,clientOrganizationId:p,veltFolderId:u,folderId:C,mode:E}=e;return Sn(t).pipe(ce(()=>{})).pipe(bo(void 0),he(()=>Zi(this.getAggregateCounts({serverDocumentIds:r,request:a,userId:s,organizationId:c,clientOrganizationId:p,veltFolderId:u,folderId:C,mode:E}))),kn(L=>(this.loggingService.catch("Error in aggregate counts: ",L),se(null))))}catch(t){return this.loggingService.catch("Error in CommentService handleAggregateCounts: ",t),se(null)}}getCountsForDocument$(e,t,r,a,s,c){return Q(this,null,function*(){try{let p=this.configService?.getApiKey(),u={useCollectionGroup:!0,isCollection:!0,useQuery:!0,getCount:!0},C=[lt("metadata.apiKey","==",p),lt("metadata.organizationId","==",s),lt("metadata.documentId","in",[e]),...c?[lt("metadata.veltFolderId","==",c)]:[],...r?.statusIds?.length?[lt("status.id","in",r.statusIds)]:[],...r?.locationIds?.length?[lt("location.id","in",r.locationIds)]:[]],E=[Zn(...C),fi("lastUpdated","desc"),fi("createdAt","desc")],D=yield this.commonDbService.queryData({feature:"allComments",properties:T(I({},u),{firestoreQuery:E})}),L=[...C,lt("viewedByUserIds","array-contains",a)],z=[Zn(...L),fi("lastUpdated","desc"),fi("createdAt","desc")],W=yield this.commonDbService.queryData({feature:"allComments",properties:T(I({},u),{firestoreQuery:z})});return{clientDocumentId:t,total:D,unread:D-W}}catch(p){return this.loggingService.catch("Error in CommentService getCountsForDocument: ",p),null}})}getAggregateCounts(e){return Q(this,null,function*(){try{let t="",{serverDocumentIds:r,request:a,userId:s,organizationId:c,clientOrganizationId:p,veltFolderId:u,folderId:C,mode:E}=e,D=this.configService?.getApiKey(),L={useCollectionGroup:!0,isCollection:!0,useQuery:!0,getCount:!0},z=[lt("metadata.apiKey","==",D),lt("metadata.organizationId","==",c),...a?.statusIds?.length?[lt("status.id","in",a.statusIds)]:[],...a?.locationIds?.length?[lt("location.id","in",a.locationIds)]:[]],W,J;if(E.isFolderMode){t=C??"",z.push(lt("metadata.veltFolderId","==",u));let ue=[Zn(...z),fi("lastUpdated","desc"),fi("createdAt","desc")];W=yield this.commonDbService.queryData({feature:"allComments",properties:T(I({},L),{firestoreQuery:ue})});let ye=[...z,lt("viewedByUserIds","array-contains",s)],Ae=[Zn(...ye),fi("lastUpdated","desc"),fi("createdAt","desc")];J=yield this.commonDbService.queryData({feature:"allComments",properties:T(I({},L),{firestoreQuery:Ae})})}else if(E.isOrgMode){t=p??"";let ue=[Zn(...z),fi("lastUpdated","desc"),fi("createdAt","desc")];W=yield this.commonDbService.queryData({feature:"allComments",properties:T(I({},L),{firestoreQuery:ue})});let ye=[...z,lt("viewedByUserIds","array-contains",s)],Ae=[Zn(...ye),fi("lastUpdated","desc"),fi("createdAt","desc")];J=yield this.commonDbService.queryData({feature:"allComments",properties:T(I({},L),{firestoreQuery:Ae})})}else{t="result";let ue=[];for(let xe=0;xe<r.length;xe+=this.LISTENER_BATCH_SIZE)ue.push(r.slice(xe,xe+this.LISTENER_BATCH_SIZE));let ye=ue.map(xe=>Q(this,null,function*(){let Se=[...z,lt("metadata.documentId","in",xe),...u?[lt("metadata.veltFolderId","==",u)]:[]],we=[Zn(...Se),fi("lastUpdated","desc"),fi("createdAt","desc")];return this.commonDbService.queryData({feature:"allComments",properties:T(I({},L),{firestoreQuery:we})})}));W=(yield Promise.allSettled(ye)).reduce((xe,Se)=>xe+(Se.status==="fulfilled"&&Se.value||0),0);let He=ue.map(xe=>Q(this,null,function*(){let Se=[...z,lt("metadata.documentId","in",xe),...u?[lt("metadata.veltFolderId","==",u)]:[],lt("viewedByUserIds","array-contains",s)],we=[Zn(...Se),fi("lastUpdated","desc"),fi("createdAt","desc")];return this.commonDbService.queryData({feature:"allComments",properties:T(I({},L),{firestoreQuery:we})})}));J=(yield Promise.allSettled(He)).reduce((xe,Se)=>xe+(Se.status==="fulfilled"&&Se.value||0),0)}return{data:{[t]:{total:W,unread:W-J}}}}catch(t){return this.loggingService.catch("Error in CommentService getAggregateCounts: ",t),null}})}filterGhostComments$(e,t,r){try{return e?this.commentService.getGhostCommentAnnotationMap$().pipe(ce(a=>{if(!a)return e;let s=this.buildGhostCommentAnnotationMap(a),c=this.groupGhostCommentsByModeId(s,t,r);return this.adjustCountsForGhostComments(e,c),e})):se(null)}catch(a){return this.loggingService.catch("Error in CommentService filterGhostComments: ",a),se(null)}}buildGhostCommentAnnotationMap(e){let t={};return Object.keys(e).forEach(r=>{let a=this.commentService.getAnnotationById(r);a&&(t[r]=a)}),t}groupGhostCommentsByModeId(e,t,r){try{let a={};return Object.values(e).forEach(s=>{let c=this.getModeIdForAnnotation(s,t,r);c&&(a[c]||(a[c]=[]),a[c].push(s))}),a}catch(a){return this.loggingService.catch("Error in CommentService groupGhostCommentsByModeId: ",a),{}}}getModeIdForAnnotation(e,t,r){try{return t.isOrgMode?e?.metadata?.clientOrganizationId||null:t.isFolderMode?e?.metadata?.folderId||null:t.isBatchMode?r.includes(e?.metadata?.documentId??"")?"result":null:e?.metadata?.clientDocumentId||null}catch(a){return this.loggingService.catch("Error in CommentService getModeIdForAnnotation: ",a),null}}adjustCountsForGhostComments(e,t){try{if(typeof e?.data!="object")return;let a=this.authService.getUser()?.userSnippylyId;Object.keys(e.data||{}).forEach(s=>{let c=t[s];if(!(!c||!e?.data?.[s]?.total)&&(e.data[s].total=Math.max(0,e.data[s].total-c.length),a)){let p=c.filter(u=>u?.viewedByUserIds&&!u?.viewedByUserIds?.includes(a));p.length>0&&(e.data[s].unread=Math.max(0,e.data[s].unread-p.length))}})}catch(r){this.loggingService.catch("Error in CommentService adjustCountsForGhostComments: ",r)}}};o.\u0275fac=function(t){return new(t||o)(ee(Ve),ee(vn),ee(at),ee(Ft),ee(pn),ee(y),ee(De))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var li=(()=>{let o=class o{constructor(e,t,r,a,s,c,p,u,C,E,D,L){this.analyticsService=e,this.authService=t,this.commentService=r,this.commentViewsService=a,this.contactService=s,this.customFilterService=c,this.docService=p,this.iamService=u,this.loggingService=C,this.metadataService=E,this.reactionService=D,this.commonDbService=L,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(z=>{this.isUserAdmin=z})}catch(z){this.loggingService.catch("Error in CommentActionsService constructor: ",z)}}addCommentAnnotation(a,s){return Q(this,arguments,function*({annotation:e,options:t},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=>Q(this,null,function*(){let u=yield this.getAddCommentAnnotationEventFromCommentAddEventData(p);c(u)}),void 0,void 0,e,void 0,void 0,void 0,void 0,void 0,r)})}catch(c){return this.loggingService.catch("Error in CommentActionsService addCommentAnnotation: ",c),null}})}publishCommentAnnotation(a,s){return Q(this,arguments,function*({annotationId:e,options:t},r){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: publishCommentAnnotation","color: green;");let c=this.commentService.getAnnotationById(e,t);if(c){let p=JSON.parse(JSON.stringify(c));p.isDraft=!1,this.commentService.saveComment(p,{type:$t.PUBLISHED}),this.analyticsService.trackEvent(Z.Events.Comments.COMMENT_PUBLISHED,{annotationId:e,commentType:this.commentService.getCommentType(p),commentMode:this.commentService.getCommentMode(),source:r??this.defaultSource});let u=yield this.metadataService.getGlobalMetadata(),C={annotationId:e,commentAnnotation:Gn(p),metadata:u};return this.triggerAction(ji.PUBLISH_COMMENT_ANNOTATION,C),C}else this.triggerAnnotationNotFoundError(e);return null}catch(c){return this.loggingService.catch("Error in CommentActionsService publishCommentAnnotation: ",c),null}})}getAddCommentAnnotationEventFromCommentAddEventData(e){return Q(this,null,function*(){try{let t=yield this.metadataService.getGlobalMetadata();return{commentAnnotation:Gn(e?.annotation),annotationId:e?.annotation?.annotationId,metadata:t,addContext:e?.addContext,elementRef:e?.elementRef}}catch(t){return this.loggingService.catch("Error in CommentActionsService getAddCommentAnnotationEventFromData: ",t),null}})}triggerAddCommentAnnotationEvent(e){try{this.triggerAction(ji.ADD_COMMENT_ANNOTATION,e)}catch(t){this.loggingService.catch("Error in CommentActionsService triggerAddCommentAnnotationEvent: ",t)}}triggerAnnotationNotFoundError(e){try{this.loggingService.catch("Annotation not found:","The annotation with the given id was not found.")}catch(t){this.loggingService.catch("Error in CommentActionsService triggerAnnotationNotFoundError: ",t)}}deleteCommentAnnotation(a,s){return Q(this,arguments,function*({annotationId:e,options:t},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,t);if(p){let u=this.authService.getUser();if(this.isUserAdmin||u?.userId===p?.from?.userId){this.commentService.deleteCommentPinAnnotation(p);let C=yield this.metadataService.getGlobalMetadata(),E={annotationId:p.annotationId,commentAnnotation:Gn(p),metadata:C};return this.triggerAction(ji.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 Q(this,arguments,function*({annotationId:e,priority:t,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 u=this.commentService.getAnnotationById(e,r);if(u){u=JSON.parse(JSON.stringify(u));let C=u.priority?JSON.parse(JSON.stringify(u.priority)):null;C&&t&&C?.id===t?.id?u.priority=void 0:u.priority=t,this.commentService.saveComment(u,{type:$t.PRIORITY_CHANGED,newPriority:t,oldPriority:C});let E=yield this.metadataService.getGlobalMetadata(),D={newPriority:t,oldPriority:C,annotationId:e,commentAnnotation:Gn(u),metadata:E};return this.triggerAction(ji.UPDATE_PRIORITY,D),this.analyticsService.trackEvent(Z.Events.Comments.COMMENT_PRIORITY_CHANGED,{annotationId:e,commentType:this.commentService.getCommentType(u),oldPriority:u.priority,newPriority:t,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 Q(this,arguments,function*({annotationId:e,status:t,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 u=this.commentService.getAnnotationById(e,r);if(u){u=JSON.parse(JSON.stringify(u));let C=u.status?JSON.parse(JSON.stringify(u.status)):null;u.status=t,this.commentService.saveComment(u,{type:$t.STATUS_CHANGED,newStatus:t,oldStatus:C});let E=yield this.metadataService.getGlobalMetadata(),D={newStatus:t,oldStatus:C,annotationId:e,commentAnnotation:Gn(u),metadata:E};return this.triggerAction(ji.UPDATE_STATUS,D),this.analyticsService.trackEvent(Z.Events.Comments.COMMENT_STATUS_CHANGED,{annotationId:e,commentType:this.commentService.getCommentType(u),oldStatus:C,newStatus:t,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 Q(this,arguments,function*({annotationId:e,accessMode:t,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 u=this.commentService.getAnnotationById(e,r);if(u)if(this.isUserAdmin){u=JSON.parse(JSON.stringify(u));let C=u.iam?.accessMode;u.iam.accessMode=t,this.commentService.saveComment(u,{type:$t.ACCESS_MODE_CHANGED,newAccessMode:t,oldAccessMode:C});let E=yield this.metadataService.getGlobalMetadata(),D={newAccessMode:t,oldAccessMode:C,annotationId:e,commentAnnotation:Gn(u),metadata:E};switch(this.triggerAction(ji.UPDATE_ACCESS,D),t){case io.PRIVATE:this.analyticsService.trackEvent(Z.Events.Comments.COMMENT_ACCESS_MODE_CHANGED,{type:io.PRIVATE,source:a??this.defaultSource});break;case io.PUBLIC:this.analyticsService.trackEvent(Z.Events.Comments.COMMENT_ACCESS_MODE_CHANGED,{type:io.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 Q(this,arguments,function*({annotationId:e,options:t}){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,t);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:$t.STATUS_CHANGED,newStatus:c,oldStatus:p}));let u=yield this.metadataService.getGlobalMetadata(),C={annotationId:e,commentAnnotation:Gn(s),metadata:u};return this.triggerAction(ji.RESOLVE_COMMENT,C),C}else this.triggerAnnotationNotFoundError(e);return null}catch(a){return this.loggingService.catch("Error in CommentActionsService resolveCommentAnnotation: ",a),null}})}getLink(a,s){return Q(this,arguments,function*({annotationId:e,options:t},r){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: getLink","color: green;");let c=this.commentService.getAnnotationById(e,t);if(c){let p=this.commentService.getCommentUrl(c)??null,u=yield this.metadataService.getGlobalMetadata();return{link:p,annotationId:e,commentAnnotation:Gn(c),metadata:u}}else this.triggerAnnotationNotFoundError(e);return null}catch(c){return this.loggingService.catch("Error in CommentActionsService getLink: ",c),null}})}copyLink(a,s){return Q(this,arguments,function*({annotationId:e,options:t},r){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: copyLink","color: green;");let c=yield this.getLink({annotationId:e,options:t},r);if(c?.link){As(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(),u={link:c.link,annotationId:e,commentAnnotation:Gn(c.commentAnnotation),metadata:p};return this.triggerAction(ji.COPY_LINK,u),u}return null}catch(c){return this.loggingService.catch("Error in CommentActionsService copyLink: ",c),null}})}addComment(p,u){return Q(this,arguments,function*({annotationId:e,comment:t,assignedTo:r,assigned:a,options:s},c){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: addComment","color: green;");let C=this.authService.getUser();if(!C)return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),null;if(C){let E=this.commentService.getAnnotationById(e,s),D=E?.comments?.length?$t.ADDED:$t.NEWLY_ADDED;if(E){E.status.type==="terminal"&&(E.status=this.customFilterService.defaultStatus);let L=new Nc;L=I(I({},L),t),L.lastUpdated=new Date,L.attachments||(L.attachments=[]),L.attachments=L.attachments.filter(J=>J?.attachmentId),L.createdAt=this.timestamp,L.from=C,r&&(E.assignedTo=r),this.commentService.saveComment(E,{type:D,updatedComment:L,assigned:a});let z=yield this.metadataService.getGlobalMetadata(),W={annotationId:e,commentId:L?.commentId,comment:L,commentAnnotation:Gn(E),metadata:z};return this.triggerAction(ji.ADD_COMMENT,W),this.analyticsService.trackEvent(Z.Events.Comments.COMMENT_ADDED,{annotationId:e,commentThreadId:t?.commentId,commentType:this.commentService.getCommentType(E),commentMode:this.commentService.getCommentMode(),source:c??this.defaultSource}),W}else this.triggerAnnotationNotFoundError(e)}return null}catch(C){return this.loggingService.catch("Error in CommentActionsService addComment: ",C),null}})}approveCommentAnnotation(a,s){return Q(this,arguments,function*({annotationId:e,options:t},r){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: approveCommentAnnotation","color: green;");let c=this.commentService.getAnnotationById(e,t);if(c){c.approved=!0,this.commentService.saveComment(c,{type:$t.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(),u={annotationId:e,commentAnnotation:Gn(c),metadata:p};return this.triggerAction(ji.APPROVE_COMMENT_ANNOTATION,u),u}else this.triggerAnnotationNotFoundError(e);return null}catch(c){return this.loggingService.catch("Error in CommentActionsService approveComment: ",c),null}})}acceptCommentAnnotation(a,s){return Q(this,arguments,function*({annotationId:e,options:t},r){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: acceptCommentAnnotation","color: green;");let c=this.commentService.getAnnotationById(e,t),p=this.authService.getUser();if(c&&p){let u=c.status?JSON.parse(JSON.stringify(c.status)):null;c.status=j.CommentAcceptStatus,this.commentService.saveComment(c,{type:$t.ACCEPTED,oldStatus:u,newStatus:j.CommentAcceptStatus});let C=yield this.metadataService.getGlobalMetadata(),E={annotationId:e,commentAnnotation:Gn(c),metadata:C,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(ji.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 Q(this,arguments,function*({annotationId:e,options:t},r){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: rejectCommentAnnotation","color: green;");let c=this.commentService.getAnnotationById(e,t),p=this.authService.getUser();if(c&&p){let u=c.status?JSON.parse(JSON.stringify(c.status)):null;c.status=j.CommentRejectStatus,this.commentService.saveComment(c,{type:$t.REJECTED,oldStatus:u,newStatus:j.CommentRejectStatus});let C=yield this.metadataService.getGlobalMetadata(),E={annotationId:e,commentAnnotation:Gn(c),metadata:C,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(ji.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 Q(this,arguments,function*({annotationId:e,options:t},r){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: toggleNotificationSubscription","color: green;");let c=this.commentService.getAnnotationById(e,t),p=this.authService.getUser();if(c&&p){let u=bt(p.userId);if(u){c.subscribedUsers||(c.subscribedUsers={}),c.unsubscribedUsers||(c.unsubscribedUsers={});let C,E=!1;if(c?.unsubscribedUsers?.[u])E=!1;else if(c?.subscribedUsers?.[u])E=!0;else{let z=this.contactService.getCurrentOrganizationUserIAM();if(z){let W=z.groups||{};Object.keys(W).forEach(J=>{c?.subscribedGroups?.[J]&&(E=!0)})}}if(r==="subscribe"||!r&&!E)delete c.unsubscribedUsers[u],c.subscribedUsers[u]={user:p,type:"manual"},C=$t.SUBSCRIBED;else if(r==="unsubscribe"||!r&&E)delete c.subscribedUsers[u],c.unsubscribedUsers[u]={user:p,type:"manual"},C=$t.UNSUBSCRIBED;else return null;this.commentService.saveComment(c,{type:C});let D=yield this.metadataService.getGlobalMetadata(),L={annotationId:e,commentAnnotation:Gn(c),metadata:D};return C===$t.SUBSCRIBED?this.triggerAction(ji.SUBSCRIBE_COMMENT_ANNOTATION,L):this.triggerAction(ji.UNSUBSCRIBE_COMMENT_ANNOTATION,L),L}}else this.triggerAnnotationNotFoundError(e);return null}catch(c){return this.loggingService.catch("Error in CommentActionsService toggleNotificationSubscription: ",c),null}})}assignUser(s,c){return Q(this,arguments,function*({annotationId:e,assignedTo:t,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 u=this.commentService.getAnnotationById(e,r);if(u){u.assignedTo=t,this.commentService.saveComment(u,{type:$t.ASSIGNED,assignedTo:t});let C=yield this.metadataService.getGlobalMetadata(),E={annotationId:e,assignedTo:t,commentAnnotation:Gn(u),metadata:C};return this.triggerAction(ji.ASSIGN_USER,E),this.analyticsService.trackEvent(Z.Events.Comments.COMMENT_ASSIGNED,{annotationId:e,commentType:this.commentService.getCommentType(u),commentMode:this.commentService.getCommentMode(),source:a??this.defaultSource,assignedToUserId:t?.userId}),E}else this.triggerAnnotationNotFoundError(e);return null}catch(p){return this.loggingService.catch("Error in CommentActionsService assignUser: ",p),null}})}getComment(r){return Q(this,arguments,function*({annotationId:e,options:t}){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: getComment","color: green;");let a=this.commentService.getAnnotationById(e,t);return a?a.comments||[]:(this.triggerAnnotationNotFoundError(e),[])}catch(a){return this.loggingService.catch("Error in CommentActionsService getComment: ",a),[]}})}updateOrDeleteComment(e,t,r,a,s){return Q(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: updateOrDeleteComment","color: green;"),t?.commentText?.trim()||t?.attachments?.length||t?.recorders?.length){let c=this.authService.getUser();if(this.isUserAdmin||c?.userId===t?.from?.userId){t.lastUpdated=new Date,t.status=$t.UPDATED,t.isEdited||(t.isEdited=!0,t.editedAt=new Date),this.commentService.saveComment(e,{type:$t.UPDATED,updatedComment:t});let p=yield this.metadataService.getGlobalMetadata(),u={annotationId:e?.annotationId,commentId:t?.commentId,comment:t,commentAnnotation:Gn(e),metadata:p};return this.triggerAction(ji.UPDATE_COMMENT,u),this.analyticsService.trackEvent(Z.Events.Comments.COMMENT_EDITED,{annotationId:e?.annotationId,commentThreadId:t?.commentId,commentType:this.commentService.getCommentType(e),commentMode:this.commentService.getCommentMode(),source:s??this.defaultSource}),u}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:t.commentId,skipDeleteThreadConfirmation:r,options:a});return null}catch(c){return this.loggingService.catch("Error in CommentActionsService updateOrDeleteComment: ",c),null}})}updateComment(p,u){return Q(this,arguments,function*({annotationId:e,comment:t,skipDeleteThreadConfirmation:r,merge:a,options:s},c){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: updateComment","color: green;");let C=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(C&&E){let D=t,L=C.comments?.find(z=>z.commentId===t.commentId);if(L){if(this.isUserAdmin||E?.userId===L?.from?.userId)return C?.status.type==="terminal"&&(C.status=this.customFilterService.defaultStatus),a&&(D=I(I({},L),t)),D.from=L.from,D.createdAt=L.createdAt,D.lastUpdated=new Date,yield this.updateOrDeleteComment(C,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(C){return this.loggingService.catch("Error in CommentActionsService updateComment: ",C),null}})}deleteComment(c,p){return Q(this,arguments,function*({annotationId:e,commentId:t,skipDeleteThreadConfirmation:r,options:a},s){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: deleteComment","color: green;");let u=this.commentService.getAnnotationById(e,a),C=this.authService.getUser();if(u){let E=u.comments?.find(D=>D?.commentId===t);if(E)if(this.isUserAdmin||C?.userId===E?.from?.userId){this.commentService.saveComment(u,{type:$t.DELETED,updatedComment:E,skipDeleteThreadConfirmation:r});let D=yield this.metadataService.getGlobalMetadata(),L={annotationId:e,commentId:t,commentAnnotation:Gn(u),comment:E,metadata:D};return this.triggerAction(ji.DELETE_COMMENT,L),L}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(u){return this.loggingService.catch("Error in CommentActionsService deleteComment: ",u),null}})}addAttachment(s,c){return Q(this,arguments,function*({annotationId:e,files:t,options:r},a){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: addAttachment","color: green;");let p=[],u=this.commentService.getAnnotationById(e,r);if(u||a==="internal"){let D=[];t.forEach(L=>{let{valid:z,file:W,maxAllowedSize:J,error:ue}=this.validateFile(L);z&&W?D.push(this.uploadFile(W,u||{}).then(ye=>({valid:z,file:W,maxAllowedSize:J,error:ue,attachment:ye||void 0}))):D.push(Promise.resolve({valid:z,file:W,maxAllowedSize:J,error:ue,attachment:void 0}))}),p=yield Promise.all(D)}else this.triggerAnnotationNotFoundError(e);let C=yield this.metadataService.getGlobalMetadata(),E={annotationId:e,commentAnnotation:u?Gn(u):void 0,attachments:p,metadata:C};return this.triggerAction(ji.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 t=100*1024*1024;(e?.type?.includes("image")||e?.type?.includes("pdf"))&&(t=15*1024*1024);let r=e.size<=t;return{valid:r,file:e,maxAllowedSize:t,maxAllowedSizeInMB:t/1024/1024,error:r?void 0:`File size should be less than ${t/1024/1024} MB`}}catch(t){return this.loggingService.catch("Error in CommentActionsService validateFile: ",t),{valid:!1,maxAllowedSize:0,maxAllowedSizeInMB:0,error:"Error in validating file"}}}deleteAttachment(s){return Q(this,arguments,function*({annotationId:e,commentId:t,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(C=>C?.commentId===t),u=c.metadata;if(p){let C=this.authService.getUser();if(this.isUserAdmin||C?.userId===p?.from?.userId){let E=p.attachments?.find(D=>D?.attachmentId===r);if(E){p.attachments=p.attachments?.filter(W=>W?.attachmentId!==r);let D={attachmentId:E.attachmentId,organizationId:u?.organizationId??null,documentId:u?.documentId??null,folderId:u?.folderId??null,commentAnnotationId:c.annotationId,apiKey:u?.apiKey??null};yield this.commentService.deleteAttachment({attachment:E,metadata:D});let L=yield this.metadataService.getGlobalMetadata(),z={attachment:E,annotationId:e,commentId:t,commentAnnotation:Gn(c),metadata:L};return this.triggerAction(ji.DELETE_ATTACHMENT,z),this.updateComment({annotationId:e,comment:p,options:a}),z}}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 Q(this,arguments,function*({annotationId:e,commentId:t,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===t)?.attachments||[]:(this.triggerAnnotationNotFoundError(e),[])}catch(s){return this.loggingService.catch("Error in CommentActionsService getAttachment: ",s),[]}})}uploadFile(e,t){return Q(this,null,function*(){try{return this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: uploadFile","color: green;"),this.commentService.uploadFile(e,t)}catch(r){return this.loggingService.catch("Error in CommentActionsService uploadFile: ",r),null}})}getRecording(a){return Q(this,arguments,function*({annotationId:e,commentId:t,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===t)?.recorders||[]:(this.triggerAnnotationNotFoundError(e),[])}catch(s){return this.loggingService.catch("Error in CommentActionsService getRecording: ",s),[]}})}deleteRecording(s){return Q(this,arguments,function*({annotationId:e,commentId:t,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(u=>u?.commentId===t);if(p){let u=this.authService.getUser();if(this.isUserAdmin||u?.userId===p?.from?.userId){let C=p.recorders?.find(E=>E?.id===r);if(C){p.recorders=p.recorders?.filter(L=>L?.id!==r);let E=yield this.metadataService.getGlobalMetadata(),D={annotationId:e,commentId:t,recording:C,commentAnnotation:Gn(c),metadata:E};return this.triggerAction(ji.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 Q(this,null,function*(){try{let t=yield this.commentService.fetchCommentAnnotations(e),r;if(t?.hasMore){let s=t?.data[t?.data?.length-1];r=yield Oj(s?.lastUpdated?.toString()??"","veltencrypttoken","veltencrypttoken")}let a=t?.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(Gn(c)),s),{});return I({data:a},t?.hasMore?{nextPageToken:r}:{})}catch(t){return this.loggingService.catch("Error in CommentActionsService fetchCommentAnnotations: ",t),{data:null}}})}toggleReaction(c,p){return Q(this,arguments,function*({annotationId:e,commentId:t,reaction:r,options:a},s){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: toggleReaction","color: green;");let u=this.commentService.getAnnotationById(e,a),C=this.authService.getUser();if(u&&C){let E=u.comments?.find(D=>D?.commentId===t);if(E){let D=yield this.reactionService.addOrUpdateReaction(r.reactionId,E?.reactionAnnotationIds||[],void 0,void 0,u?.annotationId,r.customReaction,s),L=$t.REACTION_ADDED;if(D){D?.reactions?.find(J=>J.from?.userId===C?.userId)||(L=$t.REACTION_DELETED),E.reactionAnnotationIds||(E.reactionAnnotationIds=[]),E.reactionAnnotationIds.includes(D.annotationId)||E.reactionAnnotationIds.push(D.annotationId),D?.reactions?.length||(E.reactionAnnotationIds=E.reactionAnnotationIds.filter(J=>J!==D.annotationId)),this.commentService.saveComment(u,{type:L,updatedComment:E});let z=yield this.metadataService.getGlobalMetadata(),W={annotationId:e,commentId:t,reaction:D,commentAnnotation:Gn(u),metadata:z};return s==="add"?this.triggerAction(ji.ADD_REACTION,W):s==="delete"?this.triggerAction(ji.DELETE_REACTION,W):this.triggerAction(ji.TOGGLE_REACTION,W),W}}}else this.triggerAnnotationNotFoundError(e);return null}catch(u){return this.loggingService.catch("Error in CommentActionsService toggleReaction: ",u),null}})}onComposerClick(t){return Q(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?Gn(e):void 0,metadata:r};this.triggerAction(ji.COMPOSER_CLICKED,a)}catch(r){this.loggingService.catch("Error in CommentActionsService onComposerClick: ",r)}})}autocompleteSearch(e){return Q(this,null,function*(){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: autocompleteSearch","color: green;");let t=yield this.metadataService.getGlobalMetadata();e.metadata=t,this.triggerAction(ji.AUTOCOMPLETE_SEARCH,e)}catch(t){this.loggingService.catch("Error in CommentActionsService autocompleteSearch: ",t)}})}convert(e){try{if(e?.options){let{documentId:t,organizationId:r}=this.docService.getServerId(e?.options);e.options=T(I({},e?.options),{documentId:t,organizationId:r})}return this}catch(t){return this.loggingService.catch("Error in CommentActionsService convert: ",t),this}}triggerAction(e,t){try{this.actionSubjects.has(e)||this.actionSubjects.set(e,new tt),this.actionSubjects.get(e)?.next(t)}catch(r){this.loggingService.catch("Error in CommentActionsService triggerAction: ",r)}}onAction(e){try{return this.actionSubjects.has(e)||this.actionSubjects.set(e,new tt),this.actionSubjects.get(e)?.asObservable()}catch(t){return this.loggingService.catch("Error in CommentActionsService onAction: ",t),se(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."),se({data:null});if(!e?.allDocuments&&!e?.documentIds?.length)return this.loggingService.catch("documentIds is required."),se({data:null})}return this.commentService.getAllCommentAnnotations({excludeDomChanges:!0,skipPositionCalculation:!0,query:e,addFilterCommentsOnDomCheck:!0}).pipe(ce(t=>t?t.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(t=>({data:t})))}catch(t){return this.loggingService.catch("Error in CommentActionsService getCommentAnnotation: ",t),se({data:null})}}getCommentAnnotationsCount$(e){try{return this.commentViewsService.getAnnotationsCount(e).pipe(ce(t=>t||{data:null}))}catch(t){return this.loggingService.catch("Error in CommentActionsService getCommentAnnotation: ",t),se({data:null})}}};o.\u0275fac=function(t){return new(t||o)(ee(et),ee(Ve),ee(De),ee(tde),ee(xi),ee(Zo),ee(at),ee(vn),ee(y),ee(Hd),ee(rr),ee(pn))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var I0=(()=>{let o=class o{constructor(e,t){this.httpClient=e,this.loggingService=t,this.fileContentMap$=new ve({})}getFileContent(e){try{let t=En(e);return this.fileContentMap$.value[t]?se(this.fileContentMap$.value[t]):this.httpClient.get(e,{responseType:"text"}).pipe(ce(r=>(this.fileContentMap$.next(T(I({},this.fileContentMap$.value),{[t]:r})),r)))}catch(t){return this.loggingService.catch("Error in TranscriptionService saveRecorderToDb: ",t),se(null)}}getVttFileTextToArray(e){try{let c=[],p=e.split(`
474
474
  `);for(var t=0;t<p.length;t++)if(p[t].indexOf("-->")!==-1){var r=p[t].split(" --> ")[0],a=p[t].split(" --> ")[1],s=p[t+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 t=e.split(":"),r=0;t.length===3&&(r=parseInt(t[0]),t.shift());let a=parseInt(t[0]),s=parseInt(t[1].split(".")[0]),c=parseInt(t[1].split(".")[1]);return((r*60*60+a*60+s)*1e3+c)/1e3}catch(t){return this.loggingService.catch("Error in TranscriptionService getTimeInSecondsFromVttTime: ",t),0}}};o.\u0275fac=function(t){return new(t||o)(ee(KA),ee(y))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var Yi=(()=>{let o=class o{constructor(e,t,r,a,s,c,p,u,C,E,D,L,z,W,J,ue,ye,Ae,He){this.analyticsService=e,this.configService=t,this.docService=r,this.databaseService=a,this.commonDbService=s,this.authService=c,this.domService=p,this.afAuth=u,this.iamService=C,this.functions=E,this.avatarService=D,this.contactService=L,this.storageService=z,this.dialog=W,this.loggingService=J,this.notificationService=ue,this.transcriptionService=ye,this.recorderService=Ae,this.recorderUtilsService=He,this.recorderAnnotationById$=new ve({}),this.documentPaths=null,this.allowedElementIds$=new ve([]),this.addRecorderMode$=new ve(!1),this.recorderContainerDarkMode$=new ve(!1),this.recordingTranscriptionEnabled$=new ve(!0),this.draftRecordings$=new ve([]),this.recorderNotesFound$=new ve(!1),this.recordedData=null,this.videoEditorAutoOpen$=new ve({}),this.getAllRecorderAnnotations().subscribe(Fe=>{}),this.loggingService.log("%c[WB] Creating CLASS: RecorderAnnotationService","color: blue;"),this.analyticsService.setRecorderAnnotationService(this),this.authService.setRecorderAnnotationService(this),this.databaseService.getDb().pipe(Le(Fe=>!!Fe),st(1)).subscribe(Fe=>{Fe&&this.getDocumentPaths()},Fe=>{this.loggingService.catch("Error in RecorderAnnotationService getDb subscription: ",Fe)}),this.domService.onWindowPointerMove$().subscribe(Fe=>{if(this.addRecorderMode$.value){this.highlightElement&&this.domService.removeHighlightFromElement(this.highlightElement);let xe=this.domService.getBackgroundElement(Fe.clientX,Fe.clientY);xe&&(this.isElementInsideAllowedElements(xe)?ZP(Fe.target)?this.domService.removeClassFromElement(document.body,"show-pin-cursor"):(this.domService.addClassToElement(document.body,"show-pin-cursor"),this.highlightElement=xe):this.domService.removeClassFromElement(document.body,"show-pin-cursor"))}},Fe=>{this.loggingService.catch("Error in RecorderAnnotationService onWindowPointerMove$ subscription: ",Fe)}),this.domService.onWindowKeyupEsc$().subscribe(Fe=>{this.addRecorderMode$.value&&this.disableAddRecorderMode()},Fe=>{this.loggingService.catch("Error in RecorderAnnotationService onWindowKeyupEsc$ subscription: ",Fe)}),this.domService.onDocumentClick$().subscribe(Fe=>{if(Fe&&this.addRecorderMode$.value){if(Fe.preventDefault(),Fe.stopPropagation(),!ZP(Fe.target)){let xe=this.domService.getBackgroundElement(Fe.clientX,Fe.clientY);xe&&this.isElementInsideAllowedElements(xe)}this.disableAddRecorderMode()}},Fe=>{this.loggingService.catch("Error in RecorderAnnotationService onDocumentClick$ subscription: ",Fe)}),this.addRecorderMode$.subscribe(Fe=>{this.highlightElement&&this.domService.removeHighlightFromElement(this.highlightElement),Fe?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"))},Fe=>{this.loggingService.catch("Error in RecorderAnnotationService addRecorderMode$ subscription: ",Fe)}),this.domService.onWindowKeyupBackspace$().subscribe(Fe=>{this.deleteRecorderPinAnnotations()},Fe=>{this.loggingService.catch("Error in RecorderAnnotationService onWindowKeyupBackspace$ subscription: ",Fe)}),this.domService.onWindowKeyupDelete$().subscribe(Fe=>{this.deleteRecorderPinAnnotations()},Fe=>{this.loggingService.catch("Error in RecorderAnnotationService onWindowKeyupDelete$ subscription: ",Fe)}),this.recorderService.onRecordedData().subscribe(Fe=>{this.recordedData=Fe},Fe=>{this.loggingService.catch("Error in RecorderAnnotationService onRecordedData subscription: ",Fe)}),this.domService.getDeleteCommmentAnnotations$().subscribe(Fe=>{Fe?.length&&Fe.forEach(xe=>Q(this,null,function*(){}))},Fe=>{this.loggingService.catch("Error in RecorderAnnotationService onWindowKeyupDelete$ subscription: ",Fe)})}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(dn(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)),he(t=>Q(this,null,function*(){return t?yield this.createRecorderData(t,!0):void 0})))}catch(t){return this.loggingService.catch("Error in RecorderAnnotationService getRecorderDataByRecorderId: ",t),se(void 0)}}getRecorderDataByRecorderIds(e){return Q(this,null,function*(){try{let t={};return yield Promise.all(e.recorderIds.map(r=>Q(this,null,function*(){let a=this.getAnnotationById(r);if(!a)return;let s=yield this.createRecorderData(a,!0);s&&(t[r]=s)}))),{data:Object.keys(t).length>0?t:null}}catch(t){return this.loggingService.catch("Error in RecorderAnnotationService getRecorderDataByRecorderIds: ",t),{data:null}}})}fetchRecorderDataByRecorderIds(e){return Q(this,null,function*(){try{let t=this.recorderAnnotationById$.value,r=[],a=Object.values(t);return e?.recorderIds?.length&&(a=a.filter(s=>e.recorderIds.includes(s.annotationId))),a.length===0?[]:(yield Promise.all(a.map(s=>Q(this,null,function*(){if(!s)return;let c=yield this.createRecorderData(s,!0);c&&r.push(c)}))),r)}catch(t){return this.loggingService.catch("Error in RecorderAnnotationService fetchRecorderDataByRecorderIds: ",t),[]}})}deleteRecorderDataByRecorderIds(e){return Q(this,null,function*(){try{let t=this.recorderAnnotationById$.value,r=[],a=Object.values(t),s=[];return e?.recorderIds?.length&&(s=a.filter(c=>e.recorderIds.includes(c.annotationId))),s.length===0?[]:(yield Promise.all(s.map(c=>Q(this,null,function*(){if(!c)return;let p=yield this.createRecorderData(c,!0);yield this.deleteRecorderPinAnnotation(c),p&&r.push(p)}))),r)}catch(t){return this.loggingService.catch("Error in RecorderAnnotationService deleteRecorderDataByRecorderIds: ",t),[]}})}getRecordings(e){try{return this.recorderAnnotationById$.pipe(he(t=>Q(this,null,function*(){let r=[],a=Object.values(t);return e?.recorderIds?.length&&(a=a.filter(s=>e.recorderIds.includes(s.annotationId))),a.length===0?[]:(yield Promise.all(a.map(s=>Q(this,null,function*(){if(!s)return;let c=yield this.createRecorderData(s,!0);c&&r.push(c)}))),r)})),kn(t=>(this.loggingService.catch("Error in RecorderAnnotationService getRecordings: ",t),se([]))))}catch(t){return this.loggingService.catch("Error in RecorderAnnotationService getRecordings: ",t),se([])}}setRecorderActionsService(e){try{this.recorderActionsService=e}catch(t){this.loggingService.catch("Error in RecorderAnnotationService setRecorderActionsService: ",t)}}getVttFileTextToArray(e){try{return this.transcriptionService.getVttFileTextToArray(e)}catch(t){this.loggingService.catch("Error in RecorderAnnotationService getVttFileTextToArray: ",t)}}getAllRecorderAnnotations(e,t,r){this.loggingService.log("%c[WB] Calling FUNCTION: getAllRecorderAnnotations","color: green;");let a,s;try{if(e&&(s=En(e)),t&&typeof t=="object"){let c=Yo(t);a=En(JSON.stringify(c))}}catch(c){this.loggingService.catch("Error in RecorderAnnotationService getAllRecorderAnnotations: ",c)}return ei(this.afAuth).pipe(Le(c=>!!c),he(c=>this.isFeatureAllowed({firebaseUser:c,annotations:[],filteredAnnotations:[]})),he(c=>c.featureAllowed?this.iamService.isUserAllowed$().pipe(ce(p=>(c.featureAllowed=p,c))):se(c)),he(c=>c.featureAllowed?this.authService.isPlanExpired$().pipe(ce(p=>(c.featureAllowed=!p,c))):se(c)),he(c=>c.featureAllowed?se(c).pipe(he(p=>this.docService.getDocumentPaths$().pipe(ce(u=>(this.documentPaths=u,p.documentPaths=u,p)))),he(p=>s?this.getDataFromDocumentIds([s]).pipe(ce(u=>(p.annotations=u||[],I({},p)))):this.docService.getDocumentIds$().pipe(he(u=>{let C=u?.length>0?u.map(E=>E.documentId):[this.documentPaths?.documentId??""];return this.getDataFromDocumentIds(C).pipe(ce(E=>(p.annotations=E||[],I({},p))))}))),he(p=>this.docService.getLocation$().pipe(ce(u=>(p.location=u,p)))),he(p=>this.docService.getLocations$().pipe(ce(u=>(p.customLocations=u,p)))),ce(p=>{if(p.filteredAnnotations=[],s&&!a)return p.filteredAnnotations=p.annotations?.slice(),p;{let u=[];return a?u.push(a):(u.push(p?.location?.locationId),u.push(...Object.values(p?.customLocations||[]).map(C=>C.locationId))),p.filteredAnnotations=this.filterAnnotationsByLocationIds(p?.annotations,u),p}}),he(p=>r?se(p):p?.annotations?.length?this.domService.onWindowResize$().pipe(ce(()=>p)):se(p)),he(p=>r?se(p):p?.annotations?.length?this.domService.onDomChange$("RecorderAnnotationService getAllRecorderAnnotations").pipe(ce(()=>p)):se(p)),ce(p=>{let u=[];return p?.filteredAnnotations?.forEach(C=>{this.calculateRecorderAnnotationPosition(C),C?.targetElement||u.push(C)}),this.draftRecordings$.next(u),p}),he(p=>p?.filteredAnnotations?se(p?.filteredAnnotations||[]):se([]))):se([])),Et(mn))}isFeatureAllowed(e){return this.configService.getConfig$().pipe(Le(t=>!!t),ce(t=>T(I({},e),{config:t})),he(t=>this.authService.getUser$().pipe(ce(r=>T(I({},t),{user:r})))),he(t=>ro(t.config,t.user,Re.RECORDER)?se(T(I({},t),{featureAllowed:!0})):(this.loggingService.warn("Recorder feature is not allowed."),se(T(I({},t),{featureAllowed:!1})))),Et((t,r)=>t?.featureAllowed===r?.featureAllowed))}getDataFromDocumentIds(e,t){return this.getDataFromDocuments({documentIds:e,filters:t})}getDataFromDocuments(e){if(this.configService?.getApiKey()){let{documentIds:t,filters:r}=e;if(t?.some(u=>!u)||!this.documentPaths)return se([]);let a=this.docService.getDocumentPaths()?.veltFolderId,s=this.docService.getDocumentPaths()?.allDocuments,c=se([]),p={useCollectionGroup:!0,isCollection:!0,useQuery:!0};if(this.commonDbService.shouldUseFirestore()||(p.documentId=t?.length?t[0]:void 0,p.organizationId=this.documentPaths?.organizationId),a&&s)c=this.commonDbService.dbListener({feature:"allRecorders",properties:T(I({},p),{firestoreQuery:[Zn(lt("metadata.apiKey","==",this.configService?.getApiKey()),lt("metadata.veltFolderId","==",a),lt("metadata.organizationId","==",this.documentPaths?.organizationId))]})});else{let u=[];for(let C=0;C<(t?.length??0);C+=j.LISTENER_BATCH_SIZE)u.push(t?.slice(C,C+j.LISTENER_BATCH_SIZE)??[]);c=Sn(u.map(C=>this.commonDbService.dbListener({feature:"allRecorders",properties:T(I({},p),{firestoreQuery:[Zn(lt("metadata.apiKey","==",this.configService?.getApiKey()),lt("metadata.documentId","in",C),lt("metadata.organizationId","==",this.documentPaths?.organizationId),...a?[lt("metadata.veltFolderId","==",a)]:[])]})}).pipe(da()))).pipe(ce(C=>Ba(C)))}return c.pipe(ce(u=>({data:u?.data,operation:u?.operation})),ce(({data:u,operation:C})=>{let E=[];return u&&(E=Object.values(u).filter(D=>typeof D=="object")),{data:E,operation:C}}),ce(({data:u,operation:C})=>{if(!t)return{data:u,documentMap:{},operation:C};let E=u.reduce((D,L)=>{let z=L.metadata?.documentId;return z&&(D[z]||(D[z]=[]),D[z].push(L)),D},{});return{data:u,documentMap:E,operation:C}}),ce(({data:u,documentMap:C,operation:E})=>{if(!r)if(E?.type==="removed"){if(E?.ids?.length){let D=this.recorderAnnotationById$.value;E?.ids?.forEach(L=>{delete D?.[L]}),this.recorderAnnotationById$.next(D)}}else Object.entries(C).forEach(([D,L])=>{this.setRecorderAnnotationsByOrganizationIdAndDocumentId({organizationId:this.documentPaths?.organizationId,documentId:D,annotations:L})});return u}),kn(u=>(this.loggingService.catch("Error in RecorderAnnotationService getDataFromDocumentId: ",u),se([]))))}else return se([])}setRecorderAnnotationsByOrganizationIdAndDocumentId({organizationId:e,documentId:t,annotations:r,queryHash:a}){try{if(t){e||(e=j.NO_ORGANIZATION_ID),a||(a=j.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,t){try{return e.filter(r=>t.includes(r.locationId))}catch(r){return this.loggingService.catch("Error in RecorderAnnotationService filterAnnotationsByLocations:",r),[]}}calculateRecorderAnnotationPosition(e){try{if(e.targetElement){let t=this.domService.getXPath(e.targetElement?.xpath);if(t){let r=t.iterateNext();if(r&&Ao(r)){let a=r.getBoundingClientRect();if(a&&a.width&&a.height){let{height:s,width:c}=Wp(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(t){this.loggingService.catch("Error in RecorderAnnotationService calculateRecorderAnnotationPosition:",t)}}getAnnotationById(e,t){try{let r=this.recorderAnnotationById$.value?.[e];if(r){let{documentId:a,organizationId:s}=t||{};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 t=this.recorderAnnotationById$.value?.[e];if(t)return t.metadata}catch(t){this.loggingService.catch("Error in RecorderAnnotationService getBaseMetadataFromRecorderAnnotationId: ",t)}}getRecorderAnnotationById(e,t){return this.recorderAnnotationById$.pipe(he(()=>{let r=this.getAnnotationById(e,t);return r?se(r):se(null)}),kn(r=>(this.loggingService.catch("Error in RecorderAnnotationService getCommentAnnotationById: ",r),se(null))))}getRecorderAnnotationsByOrganizationIdAndDocumentId({organizationId:e,documentId:t}){try{let r={};return Object.values(this.recorderAnnotationById$.value).forEach(a=>{a?.metadata?.documentId==t&&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 t=this.docService.getLocation();t?(e.locationId=t.locationId,e.location=t.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({location:a,source:"internal"});s?.[0]&&(e.locationId=s[0].locationId,e.location=s[0].location)}}}catch{}}catch(t){this.loggingService.catch("Error in RecorderAnnotationService setLocationToRecorderAnnotation:",t)}}addRecorder(e,t,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."),se(null);{t.from=a,t.color=j.DEFAULT_ANNOTATION_COLOR,t.lastUpdated=this.timestamp;let{topPositionX:s,topPositionY:c}=this.domService.getTopLeftPosition();t.positionX=s,t.positionY=c;let p=this.domService.getCurrentWindowSizeValue();if(t.screenWidth=p.screenWidth,t.screenHeight=p.screenHeight,t.screenScrollHeight=p.screenScrollHeight,t.recorderedElementPath="",e&&(t.targetElement=this.domService.getTargetElementForCursorPosition(e)),t?.targetElement?.xpath){let u=this.domService.getXPath(t.targetElement.xpath);if(u){let C=u.iterateNext();C&&(Ao(C)||(t.targetElement=null))}}return this.setLocationToRecorderAnnotation(t),t.pageInfo=Oi(),t.pageInfo&&(t.pageInfo.screenWidth=this.domService.getCurrentWindowSizeValue()?.screenWidth),this.saveRecorderToDb(t,r)}}else return se(null)}catch(a){return this.loggingService.catch("Error in RecorderAnnotationService addRecorder: ",a),se(null)}}saveRecorderToDb(e,t){this.loggingService.log("%c[WB] Calling FUNCTION: saveRecorderToDb","color: green;");try{return this.authService.getUser()&&this.authService.isFeatureAllowed(Re.RECORDER)?this.docService.getDocumentPaths$().pipe(Le(r=>!!r),st(1),he(r=>(this.documentPaths=r,this.loggingService.log(this.documentPaths),this.databaseService.getDb().pipe(Le(a=>!!a),st(1),he(a=>Q(this,null,function*(){if(this.documentPaths?.recorder){e.annotationId=this.commonDbService.generateDocumentId(),e.pageInfo&&(e.pageInfo.recorderUrl=this.generateRecorderUrl(e));let s=JSON.parse(JSON.stringify(e));if(s.position=null,!s?.metadata?.documentId){s?.metadata||(s.metadata={});let u=this.docService.getBaseMetadata("recorder",{commentAnnotationId:e.commentAnnotationId});s.metadata=I(I({},s?.metadata),u)}let{documentId:c,organizationId:p}=s?.metadata||{};return yield new Promise((u,C)=>Q(this,null,function*(){yield this.commonDbService.setData({feature:"recorder",properties:{id:e.annotationId,documentId:c,organizationId:p},data:JSON.parse(JSON.stringify(s)),callback:()=>{u(!0)},errorCallback:E=>{C(E)}})})),this.analyticsService.trackEvent(Z.Events.Recording.RECORDING_ADDED,{annotationId:e.annotationId,recorderType:e.recordingType,recorderMode:e.mode,recorderTime:e?.recordedTime?.duration,recorderSize:e?.attachments?.length?e?.attachments[0]?.size:e?.attachment?.size,sourceFeature:t||"recording"}),this.setVideoEditorAutoOpen({[e.annotationId]:!0}),this.processRecording(e,"recording","merge"),this.updateNotificationsDatabase(e,xv.ADDED),e}else return null})))))):se(null)}catch(r){return this.loggingService.catch("Error in RecorderAnnotationService saveRecorderToDb: ",r),se(null)}}processRecording(e,t,r){return Q(this,null,function*(){try{let a=br(this.functions,Er({url:oi?.cloudFunction?.processRecording,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:36e5}),s=this.docService.getDocumentPaths();e?.metadata?.documentId&&(s=new Ud({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:ia(),sdkType:this.configService.getSdkType(),useFirestore:this.commonDbService.shouldUseFirestore(),storageBucket:this.authService.getFirebaseConfig()?.firebaseOptions?.storageBucket,documentPath:s?.recorder,annotationId:e?.annotationId,sourceFeature:t||"recording",annotationData:e,skipMerge:!0,transcriptionEnabled:this.getRecordingTranscriptionEnabled(),type:r,returnType:"transcription"};if(c?.useFirestore){let z=yield this.recorderUtilsService.encryptRecorderAnnotation(e);c.annotationData=z}let p=this.documentPaths?.organizationId,u=this.documentPaths?.documentId;e?.metadata?.documentId&&(u=e.metadata.documentId,p=e.metadata.organizationId);let C=`${this.configService.getApiKey()}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${u}/${j.FIREBASE_PARTIAL_PATH_RECORDER}`;p&&(C=`${this.configService.getApiKey()}/${j.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${p}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${u}/${j.FIREBASE_PARTIAL_PATH_RECORDER}`),c.bucketPath=C;let E;try{E=yield a(c)}catch(z){z?.details?.type==="recording"&&this.recorderActionsService?.onError({type:"recordingFailed",message:"Recording failed",recorderId:z.details.recorderId}),z?.details?.type==="transcription"&&this.recorderActionsService?.onError({type:"transcriptionFailed",message:"Transcription failed",recorderId:z.details.recorderId}),this.loggingService.catch("Error in RecorderAnnotationService processRecording: ",z)}let D=this.getAnnotationById(e?.annotationId);if(!D)return;let L=yield this.createRecorderData(D,!1);if(L){if(E?.data?.transcriptedText&&(L.transcription.contentSummary=E.data.transcriptedText),E?.data?.vttUrl)try{let z=yield this.transcriptionService.getFileContent(E.data.vttUrl).toPromise();z&&(L.transcription.transcriptSegments=this.getVttFileTextToArray(z),L.transcription.vttFileUrl=E.data.vttUrl),L?.assets?.length&&L.assets.forEach(W=>{W.transcription=L.transcription}),L?.assetsAllVersions?.length&&(L.assetsAllVersions[0].transcription=L.transcription),this.recorderActionsService?.onTranscriptionDone(L)}catch(z){this.loggingService.catch("Error fetching VTT content: ",z)}D?.attachments?.length&&this.recordedData&&(this.recordedData.videoUrl=D.attachments[0].url),t==="recording"&&this.recorderActionsService?.onRecordingDone(L)}this.recordedData&&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(t){return this.loggingService.catch("Error in RecorderAnnotationService getDocumentIdAndOrganizationIdFromRecorderAnnotation: ",t),{}}}createRecorderData(e,t=!1){return Q(this,null,function*(){try{if(!e)return null;let r=Rv(e.metadata||{}),a=_a(e.from),s={recorderId:e.annotationId||"",from:a,assets:[],metadata:r,assetsAllVersions:[],transcription:{transcriptSegments:[],vttFileUrl:"",contentSummary:""}},c=e;e.latestVersion&&e.recordingEditVersions?.[e.latestVersion]&&(c=e.recordingEditVersions[e.latestVersion]);let p=C=>Q(this,null,function*(){let E={transcriptSegments:[],vttFileUrl:"",contentSummary:C?.transcription?.transcriptedText||""};if(t&&C?.transcription?.vttUrl)try{let D=yield this.transcriptionService.getFileContent(C.transcription.vttUrl).toPromise();D&&(E.transcriptSegments=this.getVttFileTextToArray(D),E.vttFileUrl=C.transcription.vttUrl)}catch(D){this.loggingService.catch("Error fetching VTT content: ",D)}return E}),u=yield p(c);if(s.transcription=u,c?.attachments?.length)for(let C of c.attachments)C?.url&&s.assets.push({version:e.latestVersion||1,url:C.url,mimeType:C.mimeType,fileName:C.name,fileSizeInBytes:C.size,fileFormat:C.type,transcription:I({},u),thumbnailUrl:e.attachments?.[0]?.thumbnail});if(e.recordingEditVersions){let C=Object.entries(e.recordingEditVersions).map(z=>Q(this,[z],function*([D,L]){let W=parseInt(D),J=yield p(L),ue=L?.attachments?.[0]||L?.attachment;return{version:W,url:ue?.url,mimeType:ue?.mimeType,fileName:ue?.name,fileSizeInBytes:ue?.size,fileFormat:ue?.type,transcription:J,thumbnailUrl:L?.attachments?.[0]?.thumbnail}})),E=yield Promise.all(C);s.assetsAllVersions=E.filter(D=>D.url)}else s.assetsAllVersions=[...s.assets];return s}catch(r){return this.loggingService.catch("Error in RecorderAnnotationService createRecorderData: ",r),null}})}updateRecorder(e,t=!1,r){try{r&&this.setLocationToRecorderAnnotation(e),t&&this.updateNotificationsDatabase(e,xv.UPDATED),this.updateRecorderToDb(e)}catch(a){this.loggingService.catch("Error in RecorderAnnotationService updateRecorder: ",a)}}resolveRecorder(e){try{this.domService.resetSelectedAnnotationsMap(!1),this.updateNotificationsDatabase(e,xv.RESOLVED),this.updateRecorderToDb(e),this.domService.updateSelectedAnnotationInMap([e])}catch(t){this.loggingService.catch("Error in RecorderAnnotationService resolveRecorder: ",t)}}updateRecorderToDb(e){this.loggingService.log("%c[WB] Calling FUNCTION: updateRecorderToDb","color: green;");try{if(e?.targetElement?.xpath){let t=this.domService.getXPath(e.targetElement.xpath);if(t){let r=t.iterateNext();r&&(Ao(r)||(e.targetElement=null))}}if(e.annotationId){let t=this.recorderAnnotationById$.value;this.recorderAnnotationById$.next(T(I({},t),{[e.annotationId]:I({},e)}))}if(this.domService.updateSelectedAnnotationInMap([e]),this.authService.getUser()&&this.authService.isFeatureAllowed(Re.RECORDER)){let t=JSON.parse(JSON.stringify(e));if(t.position=null,!t?.metadata?.documentId){t?.metadata||(t.metadata={});let s=this.docService.getBaseMetadata();t.metadata=I(I({},t?.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(t))})}}catch(t){this.loggingService.catch("Error in RecorderAnnotationService updateRecorderToDb: ",t)}}deleteRecorderPinAnnotations(){try{let e=this.domService.getSelectedAnnotationsMap(),t=this.authService.getUser(),r=[];Object.keys(e).forEach(a=>Q(this,null,function*(){let s=e[a];s.type==="recorder"&&t&&s.from&&(t?.isAdmin||s.from.userId===t.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(Sa,{panelClass:"velt-mat-dialog-container",data:{title:"Delete recording?",message:"This selected recording will be deleted.",yesButton:"Delete",noButton:"Cancel",darkMode:this.recorderContainerDarkMode$.value,variant:"recorder"}}).afterClosed().pipe(st(1)).subscribe(a=>{a&&(r.forEach(s=>Q(this,null,function*(){yield this.deleteRecorderPinAnnotation(s)})),setTimeout(()=>{document.querySelectorAll(`[${j.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,t){if(this.authService.isFeatureAllowed(Re.RECORDER)&&this.documentPaths?.recorder&&e?.annotationId){this.updateNotificationsDatabase(e,xv.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,recorderTime:e?.recordedTime?.duration,recorderSize:e?.attachments?.length?e?.attachments[0]?.size:e.attachment?.size,sourceFeature:t||"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=>Q(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(t){this.loggingService.catch("Error in RecorderAnnotationService setRecorderContainerDarkMode: ",t)}}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(t){return this.loggingService.catch("Error in RecorderAnnotationService isElementInsideAllowedElements: ",t),!1}}attachRecorder(e){let t=document.getElementById(e);if(t){let r=this.domService.getXPath(t),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 t=new tg;t.from=e,t.color=j.DEFAULT_ANNOTATION_COLOR,t.lastUpdated=this.timestamp;let{topPositionX:r,topPositionY:a}=this.domService.getTopLeftPosition();t.positionX=r,t.positionY=a;let s=this.domService.getCurrentWindowSizeValue();t.screenWidth=s.screenWidth,t.screenHeight=s.screenHeight,t.screenScrollHeight=s.screenScrollHeight,t.recorderedElementPath="";let c=this.docService.getLocation();return c&&(t.locationId=c.locationId,t.location=c.location),t}return null}updateNotificationsDatabase(e,t,r={}){try{let a=I({annotationData:e,actionType:t,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=Oi(),e.pageInfo&&(e.pageInfo.screenWidth=this.domService.getCurrentWindowSizeValue()?.screenWidth)),e.pageInfo.recorderUrl=this.generateRecorderUrl(e),this.updateRecorder(e),e.pageInfo?.recorderUrl):""}catch(t){this.loggingService.catch("Error in RecorderAnnotationService getRecorderUrl: ",t);return}}uploadFile(e,t){let r=this.documentPaths?.organizationId,a=this.documentPaths?.documentId;t?.metadata?.documentId&&(a=t.metadata.documentId,r=t.metadata.organizationId);let s=`${j.FIREBASE_PARTIAL_PATH_DOCS}/${a}/${j.FIREBASE_PARTIAL_PATH_RECORDER}`;return r&&(s=`${j.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${r}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${a}/${j.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 t=new URL(window.location.href);return t.searchParams.delete(j.URL_PARAMS.RECORDER_ID),t.searchParams.append(j.URL_PARAMS.RECORDER_ID,e.annotationId),t.href}setRecorderNotesFound(e){try{this.recorderNotesFound$.next(e)}catch(t){this.loggingService.catch("Error in RecorderAnnotationService setRecorderNotesFound: ",t)}}getRecorderNotesFound$(){try{return this.recorderNotesFound$.asObservable()}catch(e){return this.loggingService.catch("Error in RecorderAnnotationService getRecorderNotesFound: ",e),se(!1)}}getRecorderNotesFound(){try{return this.recorderNotesFound$.value}catch(e){return this.loggingService.catch("Error in RecorderAnnotationService getRecorderNotesFound: ",e),!1}}editVideoRecording(e,t,r,a,s,c){return Q(this,null,function*(){try{let p=br(this.functions,Er({url:oi?.cloudFunction?.videoBackend,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:36e5}),u=this.docService.getDocumentPaths();r?.metadata?.documentId&&(u=new Ud({apiKey:this.configService.getApiKey(),clientDocumentId:r.metadata.clientDocumentId,clientOrganizationId:r.metadata.clientOrganizationId,documentId:r.metadata.documentId,organizationId:r.metadata.organizationId}));let C={databaseUrl:this.authService.getFirebaseConfig()?.firebaseOptions?.databaseURL,entirePath:u?.recorder+(r?.annotationId||""),fromUser:this.authService.getUser(),clientOrganizationId:u?.clientOrganizationId,clientDocumentId:u?.clientDocumentId,apiKey:this.configService.getApiKey(),sdkVersion:ia(),sdkType:this.configService.getSdkType(),useFirestore:this.commonDbService.shouldUseFirestore(),storageBucket:this.authService.getFirebaseConfig()?.firebaseOptions?.storageBucket,documentPath:u?.recorder,annotationId:r?.annotationId,annotationData:r,videoUrl:e,segments:t,zoomOptions:a,transcriptionEnabled:this.getRecordingTranscriptionEnabled(),type:s,backendUpload:!0};if(c){let W=yield c.arrayBuffer(),J=new Uint8Array(W),ue="";for(let Ae=0;Ae<J.length;Ae++)ue+=String.fromCharCode(J[Ae]);let ye=btoa(ue);C.videoBlobData=ye,C.videoBlobType=c.type,C.videoBlobSize=c.size}if(C?.useFirestore&&r){let W=yield this.recorderUtilsService.encryptRecorderAnnotation(r);C.annotationData=W}let E=this.documentPaths?.organizationId,D=this.documentPaths?.documentId;r?.metadata?.documentId&&(D=r.metadata.documentId,E=r.metadata.organizationId);let L=`${this.configService.getApiKey()}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${D}/${j.FIREBASE_PARTIAL_PATH_RECORDER}`;E&&(L=`${this.configService.getApiKey()}/${j.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${E}/${j.FIREBASE_PARTIAL_PATH_DOCS}/${D}/${j.FIREBASE_PARTIAL_PATH_RECORDER}`),C.bucketPath=L;let z=yield p(C);if(s==="standalone"){let W=z?.data;if(W&&W?.videoData){let J=atob(W.videoData),ue=new ArrayBuffer(J.length),ye=new Uint8Array(ue);for(let Fe=0;Fe<J.length;Fe++)ye[Fe]=J.charCodeAt(Fe);let Ae=new Blob([ye],{type:W.mimeType||"video/mp4"}),He=document.createElement("a");He.href=URL.createObjectURL(Ae),He.download="edited-video.mp4",document.body.appendChild(He),He.click(),document.body.removeChild(He)}}return z}catch(p){throw this.loggingService.catch("Error in RecorderAnnotationService editVideoRecording: ",p),p}})}setVideoEditorAutoOpen(e){try{this.videoEditorAutoOpen$.next(I(I({},this.videoEditorAutoOpen$.value),e))}catch(t){this.loggingService.catch("Error in RecorderAnnotationService setVideoEditorAutoOpen: ",t)}}getVideoEditorAutoOpen$(){try{return this.videoEditorAutoOpen$.asObservable()}catch(e){return this.loggingService.catch("Error in RecorderAnnotationService getVideoEditorAutoOpen: ",e),se({})}}getVideoEditorAutoOpen(){try{return this.videoEditorAutoOpen$.value}catch(e){return this.loggingService.catch("Error in RecorderAnnotationService getVideoEditorAutoOpen: ",e),{}}}downloadLatestVideo(e){return Q(this,null,function*(){try{this.loggingService.log("%c[WB] Calling FUNCTION: downloadLatestVideo","color: green;");let t=this.getAnnotationById(e);if(!t)return this.loggingService.catch("Recording not found with ID: "+e),!1;let r,a,s=t.latestVersion;if(s&&t.recordingEditVersions?.[s]?(r=t.recordingEditVersions[s].attachments?.[0]?.url,a=t.recordingEditVersions[s].attachments?.[0]?.name):(r=t.attachments?.[0]?.url||t.attachment?.url,a=t.attachments?.[0]?.name||t.attachment?.name),!r)return this.loggingService.catch("No video URL found for recording: "+e),!1;let c=yield fetch(r);if(!c.ok)return this.loggingService.catch("Failed to fetch video: "+c.statusText),!1;let p=yield c.blob(),u=document.createElement("a");return u.href=URL.createObjectURL(p),u.download=a||`recording-${e}.mp4`,document.body.appendChild(u),u.click(),document.body.removeChild(u),URL.revokeObjectURL(u.href),this.loggingService.log("Successfully downloaded video: "+a),!0}catch(t){return this.loggingService.catch("Error in RecorderAnnotationService downloadLatestVideo: ",t),!1}})}};o.\u0275fac=function(t){return new(t||o)(ee(et),ee(Ft),ee(at),ee(Dn),ee(pn),ee(Ve),ee(Be),ee(Di),ee(vn),ee(Wo),ee(Bd),ee(xi),ee(sg),ee(no),ee(y),ee(gn),ee(I0),ee(bn),ee(v0))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var Wk=class extends si{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.setSystemFiltersOperator=this._setSystemFiltersOperator,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.enableGroupMultipleMatch=this._enableGroupMatchedComments,this.disableGroupMultipleMatch=this._disableGroupMatchedComments,this.enableGroupMatchedComments=this._enableGroupMatchedComments,this.disableGroupMatchedComments=this._disableGroupMatchedComments,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.enableLinkCallback=this._enableLinkCallback,this.disableLinkCallback=this._disableLinkCallback,this.enableSeenByUsers=this._enableSeenByUsers,this.disableSeenByUsers=this._disableSeenByUsers,this.enableShortUserName=this._enableShortUserName,this.disableShortUserName=this._disableShortUserName,this.addCommentAnnotation=this._addCommentAnnotation,this.publishCommentAnnotation=this._publishCommentAnnotation,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.enableFilterCommentsOnDom=this._enableFilterCommentsOnDom,this.disableFilterCommentsOnDom=this._disableFilterCommentsOnDom,this.enableReplyAvatars=this._enableReplyAvatars,this.disableReplyAvatars=this._disableReplyAvatars,this.setMaxReplyAvatars=this._setMaxReplyAvatars,this.setSidebarButtonCountType=this._setSidebarButtonCountType,this.enableFilterGhostCommentsInSidebar=this._enableFilterGhostCommentsInSidebar,this.disableFilterGhostCommentsInSidebar=this._disableFilterGhostCommentsInSidebar,this.on=this._on}_getAllCommentAnnotations(o,n){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:n}}),this.getService(De).getAllCommentAnnotations({customClientDocumentId:o,params:n,excludeDomChanges:!0,skipPositionCalculation:!0,addFilterCommentsOnDomCheck:!0}).pipe(ce(e=>e?.length?e?.map(t=>Gn(t)):e))}catch(e){return this.getService(y).catch("Error in _getLiveCommentsOnCurrentDocument: ",e),se(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(De).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(De).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(De).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(De).setAllowedElementIds(o)}catch(n){this.getService(y).catch("Error in allowedElementIds: ",n)}}_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(De).setAllowedElementClassNames(o)}catch(n){this.getService(y).catch("Error in allowedElementClassNames: ",n)}}_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(De).setAllowedElementQuerySelectors(o)}catch(n){this.getService(y).catch("Error in allowedElementQuerySelectors: ",n)}}_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(De).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(De).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(De).attachComment(o,["id","data-id"])}catch(n){this.getService(y).catch("Error in _attachComment: ",n)}}_openCommentSidebar(){this.getService(y).log("%c[WB] Calling FUNCTION: openCommentSidebar","color: green;");try{this.trackEvent(Z.Events.Comments.OPEN_COMMENT_SIDEBAR_TRIGGERED),this.getService(De).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(De).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(De).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(De).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(De).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(De).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(De).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(De).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(De).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(De).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(De).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(De).addCommentModeChange()}catch(o){return this.getService(y).catch("Error in _onCommentModeChange: ",o),se(!1)}}_enableAttachment(){this.getService(y).log("%c[WB] Calling FUNCTION: enableAttachment","color: green;");try{this.trackEvent(Z.Events.Comments.ENABLE_ATTACHMENTS_TRIGGERED),this.getService(De).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(De).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(De).isUserGlobalContact$()}catch(o){return this.getService(y).catch("Error in _isUserGlobalContact: ",o),se(!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(De).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(De).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(De).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(De).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(De).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(De).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(De).showCommentIndex(o)}catch(n){this.getService(y).catch("Error in _showCommentIndex: ",n)}}_enableCommentIndex(){this.getService(y).log("%c[WB] Calling FUNCTION: enableCommentIndex","color: green;");try{this.trackEvent(Z.Events.Comments.ENABLE_COMMENT_INDEX_TRIGGERED),this.getService(De).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(De).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(De).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(De).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(De).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(De).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(De).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(De).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(De).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(De).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(De).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(De).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(De).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(De).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(De).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(De).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(De).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(De).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(De).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(De).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(De).setCustomStatuses(o)}catch(n){this.getService(y).catch("Error in _setCustomStatus: ",n)}}_enableInboxMode(){this.getService(y).log("%c[WB] Calling FUNCTION: enableInboxMode","color: green;");try{this.trackEvent(Z.Events.Comments.ENABLE_INBOX_MODE_TRIGGERED),this.getService(De).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(De).setCustomPriorities(o)}catch(n){this.getService(y).catch("Error in _setCustomPriority: ",n)}}_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(De).setCustomCategories(o)}catch(n){this.getService(y).catch("Error in _setCustomCategory: ",n)}}_disableInboxMode(){this.getService(y).log("%c[WB] Calling FUNCTION: disableInboxMode","color: green;");try{this.trackEvent(Z.Events.Comments.DISABLE_INBOX_MODE_TRIGGERED),this.getService(De).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(De).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(De).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(De).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(De).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:mce,location}}),this.getService(De).setContextProvider(o)}catch(n){this.getService(y).catch("Error in _setContextProvider: ",n)}}_enableSuggestionMode(){this.getService(y).log("%c[WB] Calling FUNCTION: enableSuggestionMode","color: green;");try{this.trackEvent(Z.Events.Comments.ENABLE_SUGGESTION_MODE_TRIGGERED),this.getService(De).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(De).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(De).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(De).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(De).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(De).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(De).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(De).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(De).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(De).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(De).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(De).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(De).setTotalMediaLength(o)}catch(n){this.getService(y).catch("Error in _setTotalMediaLength: ",n)}}_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(De).onCommentAdd$()}catch(o){return this.getService(y).catch("Error in _onCommentAdd: ",o),se()}}_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(De).onCommentUpdate$()}catch(o){return this.getService(y).catch("Error in _onCommentUpdate: ",o),se()}}_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(De).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(De).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(De).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(De).setDetectionStrategy(o)}catch(n){this.getService(y).catch("Error in _setDStrategy: ",n)}}_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(De).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(De).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(De).getSidebarButtonOnCommentDialogClick$()}catch(o){return this.getService(y).catch("Error in _onSidebarButtonOnCommentDialogClick: ",o),se(null)}}_enableReactions(){this.getService(y).log("%c[WB] Calling FUNCTION: enableReactions","color: green;");try{this.trackEvent(Z.Events.Comments.ENABLE_REACTIONS_TRIGGERED),this.getService(De).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(De).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(n=>n.trim())),this.getService(De).setAllowedRecordings(o)}catch(n){this.getService(y).catch("Error in _setRecordings: ",n)}}_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(De).addCommentOnElement(o)}catch(n){this.getService(y).catch("Error in _addCommentOnElement: ",n)}}_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(De).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(De).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(De).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(De).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(De).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(De).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(De).setCommentSidebarFilters(o)}catch(n){this.getService(y).catch("Error in _setCommentSidebarFilters: ",n)}}_setSystemFiltersOperator(o){this.getService(y).log("%c[WB] Calling FUNCTION: setSystemFiltersOperator","color: green;");try{this.trackEvent(Z.Events.Comments.SET_SYSTEM_FILTERS_OPERATOR_TRIGGERED,{payload:{operator:o}}),this.getService(De).setCommentSidebarSystemFiltersOperator(o)}catch(n){this.getService(y).catch("Error in _setSystemFiltersOperator: ",n)}}_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(De).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(De).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(De).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(De).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(De).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(De).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(De).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(De).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(De).getElementRefByAnnotationId(o)}catch(n){this.getService(y).catch("Error in _getElementRefByAnnotationId: ",n);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(De).scrollToCommentByAnnotationId(o)}catch(n){this.getService(y).catch("Error in _scrollToCommentByAnnotationId: ",n)}}_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(De).selectCommentByAnnotationId(o)}catch(n){this.getService(y).catch("Error in _selectCommentByAnnotationId: ",n)}}_enableRecordingSummary(){this.getService(y).log("%c[WB] Calling FUNCTION: enableRecordingSummary","color: green;");try{this.trackEvent(Z.Events.Comments.ENABLE_RECORDING_SUMMARY_TRIGGERED),this.getService(De).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(De).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(Yi).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(Yi).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(De).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(De).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(De).setUnreadIndicatorMode(o)}catch(n){this.getService(y).catch("Error in _setUnreadIndicatorMode: ",n)}}_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(De).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(De).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(De).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(De).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(De).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(De).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(De).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(De).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(De).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(De).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(De).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(De).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(De).setCustomReactions(o)}catch(n){this.getService(y).catch("Error in _setCustomReactions: ",n)}}_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(De).onCommentSelectionChange$()}catch(o){return this.getService(y).catch("Error in _onCommentSelectionChange: ",o),se(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(De).getUnreadCommentCountByAnnotationId$(o)}catch(n){return this.getService(y).catch("Error in _getUnreadCommentCountByAnnotationId: ",n),se(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(De).getUnreadCommentAnnotationCountOnCurrentDocument$()}catch(o){return this.getService(y).catch("Error in _getUnreadCommentAnnotationCountOnCurrentDocument: ",o),se(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(De).getUnreadCommentCountOnCurrentDocument$()}catch(o){return this.getService(y).catch("Error in _getUnreadCommentCountOnCurrentDocument: ",o),se(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(De).getUnreadCommentAnnotationCountByLocationId$(o)}catch(n){return this.getService(y).catch("Error in _getUnreadCommentAnnotationCountByLocationId: ",n),se(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(De).getUnreadCommentCountByLocationId$(o)}catch(n){return this.getService(y).catch("Error in _getUnreadCommentCountByLocationId: ",n),se(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(De).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(De).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(De).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(De).setPinCursorImage(o)}catch(n){this.getService(y).catch("Error in _setPinCursorImage: ",n)}}_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(De).addManualComment(o)}catch(n){return this.getService(y).catch("Error in _addManualComment: ",n),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(De).createCustomListDataOnAnnotation(o)}catch(n){this.getService(y).catch("Error in _createCustomListDataOnAnnotation: ",n)}}_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(dl).create(o)}catch(n){this.getService(y).catch("Error in _createCustomListDataOnComment: ",n)}}_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(De).setExcludeLocationIdsFromSidebar(o)}catch(n){this.getService(y).catch("Error in _excludeLocationIdsFromSidebar: ",n)}}_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(De).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(De).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(De).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(De).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(De).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(De).disableMultiThread()}catch(o){this.getService(y).catch("Error in _disableMultiThread: ",o)}}_enableGroupMatchedComments(){this.getService(y).log("%c[WB] Calling FUNCTION: enableGroupMatchedComments","color: green;");try{this.trackEvent(Z.Events.Comments.ENABLE_GROUP_MATCHED_COMMENTS_TRIGGERED),this.getService(De).enableGroupMatchedComments()}catch(o){this.getService(y).catch("Error in _enableGroupMatchedComments: ",o)}}_disableGroupMatchedComments(){this.getService(y).log("%c[WB] Calling FUNCTION: disableGroupMatchedComments","color: green;");try{this.trackEvent(Z.Events.Comments.DISABLE_GROUP_MATCHED_COMMENTS_TRIGGERED),this.getService(De).disableGroupMatchedComments()}catch(o){this.getService(y).catch("Error in _disableGroupMatchedComments: ",o)}}_updateContext(o,n,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:n,config:e}}),this.getService(De).updateCommentAnnotationContext(o,n,e)}catch(t){return this.getService(y).catch("Error in _updateContext: ",t),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(Be).getSelectedComments$()}catch(o){return this.getService(y).catch("Error in _getSelectedComments: ",o),se([])}}_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(De).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(De).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(De).getCopyLink$()}catch(o){return this.getService(y).catch("Error in _onCopyLink: ",o),se("")}}_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(De).getCommentAnnotationById(o)}catch(n){return this.getService(y).catch("Error in _getCommentAnnotationById: ",n),se(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(De).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(De).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(De).getSidebarCustomActionEventData()}catch(o){return this.getService(y).catch("Error in _onCommentSidebarActionButtonClick: ",o),se(null)}}_setCommentSidebarData(o,n){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:n}}),this.getService(De).setCommentSidebarData(o,n)}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(De).getSidebarCustomActionEventDataOnInit()}catch(o){return this.getService(y).catch("Error in _onCommentSidebarInit: ",o),se(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(De).getSidebarCustomActionEventDataAllChanges()}catch(o){return this.getService(y).catch("Error in _onCommentSidebarData: ",o),se(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(De).setSidebarCustomActionEventData(o,[],{},[],{})}catch(n){this.getService(y).catch("Error in _setCommentSidebarDefaultCustomActions: ",n)}}_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(De).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(De).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(De).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(De).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(De).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(De).disableResolveStatusAccessAdminOnly()}catch(o){this.getService(y).catch("Error in _disableResolveStatusAccessAdminOnly: ",o)}}_enableLinkCallback(){this.getService(y).log("%c[WB] Calling FUNCTION: enableLinkCallback","color: green;");try{this.trackEvent(Z.Events.Comments.ENABLE_LINK_CALLBACK_TRIGGERED),this.getService(De).enableLinkCallback()}catch(o){this.getService(y).catch("Error in _enableLinkCallback: ",o)}}_disableLinkCallback(){this.getService(y).log("%c[WB] Calling FUNCTION: disableLinkCallback","color: green;");try{this.trackEvent(Z.Events.Comments.DISABLE_LINK_CALLBACK_TRIGGERED),this.getService(De).disableLinkCallback()}catch(o){this.getService(y).catch("Error in _disableLinkCallback: ",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(De).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(De).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(De).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(De).disableShortUserName()}catch(o){this.getService(y).catch("Error in _disableShortUserName: ",o)}}_addCommentAnnotation(o){return Q(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(li).convert(o).addCommentAnnotation(o,"external")}catch(n){return this.getService(y).catch("Error in _addCommentAnnotation: ",n),null}})}_publishCommentAnnotation(o){return Q(this,null,function*(){this.getService(y).log("%c[WB] Calling FUNCTION: publishCommentAnnotation","color: green;");try{return this.trackEvent(Z.Events.Comments.PUBLISH_COMMENT_ANNOTATION_TRIGGERED,{payload:{publishCommentAnnotationRequest:o}}),this.getService(li).convert(o).publishCommentAnnotation(o,"external")}catch(n){return this.getService(y).catch("Error in _publishCommentAnnotation: ",n),null}})}_approveCommentAnnotation(o){return Q(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(li).convert(o).approveCommentAnnotation(o,"external")}catch(n){return this.getService(y).catch("Error in _approveCommentAnnotation: ",n),null}})}_acceptCommentAnnotation(o){return Q(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(li).convert(o).acceptCommentAnnotation(o,"external")}catch(n){return this.getService(y).catch("Error in _acceptCommentAnnotation: ",n),null}})}_rejectCommentAnnotation(o){return Q(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(li).convert(o).rejectCommentAnnotation(o,"external")}catch(n){return this.getService(y).catch("Error in _rejectCommentAnnotation: ",n),null}})}_subscribeCommentAnnotation(o){return Q(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(li).convert(o).toggleNotificationSubscription(o,"subscribe")}catch(n){return this.getService(y).catch("Error in _subscribeCommentAnnotation: ",n),null}})}_unsubscribeCommentAnnotation(o){return Q(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(li).convert(o).toggleNotificationSubscription(o,"unsubscribe")}catch(n){return this.getService(y).catch("Error in _unsubscribeCommentAnnotation: ",n),null}})}_deleteCommentAnnotation(o){return Q(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(li).convert(o).deleteCommentAnnotation(o,"external")}catch(n){return this.getService(y).catch("Error in _deleteCommentAnnotation: ",n),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(li).getCommentAnnotations(o).pipe(ce(n=>(n.data&&Object.keys(n.data).forEach(e=>{if(n.data?.[e]?.length){let t=n.data[e];n.data[e]=t?.map(r=>Gn(r))}}),n)))}catch(n){return this.getService(y).catch("Error in _getCommentAnnotations: ",n),se({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(li).getCommentAnnotationsCount$(o)}catch(n){return this.getService(y).catch("Error in _getCommentAnnotationsCount: ",n),se({data:null})}}_assignUser(o){return Q(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(li).convert(o).assignUser(o,"external")}catch(n){return this.getService(y).catch("Error in _assignUser: ",n),null}})}_updatePriority(o){return Q(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(li).convert(o).updatePriority(o,"external")}catch(n){return this.getService(y).catch("Error in _updatePriority: ",n),null}})}_updateStatus(o){return Q(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(li).convert(o).updateStatus(o,"external")}catch(n){return this.getService(y).catch("Error in _updateStatus: ",n),null}})}_updateAccess(o){return Q(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(li).convert(o).updateAccess(o,"external")}catch(n){return this.getService(y).catch("Error in _updateAccess: ",n),null}})}_resolveCommentAnnotation(o){return Q(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(li).convert(o).resolveCommentAnnotation(o)}catch(n){return this.getService(y).catch("Error in _resolveCommentAnnotation: ",n),null}})}_getLink(o){return Q(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(li).convert(o).getLink(o,"external")}catch(n){return this.getService(y).catch("Error in _getLink: ",n),null}})}_copyLink(o){return Q(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(li).convert(o).copyLink(o,"external")}catch(n){return this.getService(y).catch("Error in _copyLink: ",n),null}})}_addComment(o){return Q(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(li).convert(o).addComment(o,"external")}catch(n){return this.getService(y).catch("Error in _addComment: ",n),null}})}_updateComment(o){return Q(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(li).convert(o).updateComment(o,"external")}catch(n){return this.getService(y).catch("Error in _updateComment: ",n),null}})}_deleteComment(o){return Q(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(li).convert(o).deleteComment(o,"external")}catch(n){return this.getService(y).catch("Error in _deleteComment: ",n),null}})}_getComment(o){return Q(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(li).convert(o).getComment(o)}catch(n){return this.getService(y).catch("Error in _getComment: ",n),[]}})}_addAttachment(o){return Q(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(li).convert(o).addAttachment(o)}catch(n){return this.getService(y).catch("Error in _addAttachment: ",n),Promise.resolve([])}})}_deleteAttachment(o){return Q(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(li).convert(o).deleteAttachment(o)}catch(n){return this.getService(y).catch("Error in _deleteAttachment: ",n),null}})}_getAttachment(o){return Q(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(li).convert(o).getAttachment(o)}catch(n){return this.getService(y).catch("Error in _getAttachment: ",n),[]}})}_getRecording(o){return Q(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(li).convert(o).getRecording(o)}catch(n){return this.getService(y).catch("Error in _getRecording: ",n),[]}})}_deleteRecording(o){return Q(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(li).convert(o).deleteRecording(o)}catch(n){return this.getService(y).catch("Error in _deleteRecording: ",n),null}})}_fetchCommentAnnotations(o){return Q(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(li).fetchCommentAnnotations(o)}catch(n){return this.getService(y).catch("Error in _fetchCommentAnnotations: ",n),{data:null}}})}_addReaction(o){return Q(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(li).convert(o).toggleReaction(o,"add")}catch(n){return this.getService(y).catch("Error in _addReaction: ",n),null}})}_deleteReaction(o){return Q(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(li).convert(o).toggleReaction(o,"delete")}catch(n){return this.getService(y).catch("Error in _deleteReaction: ",n),null}})}_toggleReaction(o){return Q(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(li).convert(o).toggleReaction(o)}catch(n){return this.getService(y).catch("Error in _toggleReaction: ",n),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(li).onAction(o)}catch(n){return this.getService(y).catch("Error in _on: ",n),se(null)}}_enableReadOnly(){return Q(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(De).enableReadOnly()}catch(o){this.getService(y).catch("Error in _toggleReaction: ",o);return}})}_disableReadOnly(){return Q(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(De).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(De).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(De).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(De).setTransformContext(o)}catch(n){this.getService(y).catch("Error in _setTransformContext: ",n);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(De).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(De).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(De).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(De).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(De).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(De).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(De).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(De).disableDraftMode()}catch(o){this.getService(y).catch("Error in _disableDraftMode: ",o);return}}_enableFilterCommentsOnDom(){this.getService(y).log("%c[WB] Calling FUNCTION: enableFilterCommentsOnDom","color: green;");try{this.trackEvent(Z.Events.Comments.ENABLE_FILTER_COMMENTS_ON_DOM_TRIGGERED),this.getService(De).enableFilterCommentsOnDom()}catch(o){this.getService(y).catch("Error in _enableFilterCommentsOnDom: ",o);return}}_disableFilterCommentsOnDom(){this.getService(y).log("%c[WB] Calling FUNCTION: disableFilterCommentsOnDom","color: green;");try{this.trackEvent(Z.Events.Comments.DISABLE_FILTER_COMMENTS_ON_DOM_TRIGGERED),this.getService(De).disableFilterCommentsOnDom()}catch(o){this.getService(y).catch("Error in _disableFilterCommentsOnDom: ",o);return}}_enableReplyAvatars(){this.getService(y).log("%c[WB] Calling FUNCTION: enableReplyAvatars","color: green;");try{this.trackEvent(Z.Events.Comments.ENABLE_REPLY_AVATARS_TRIGGERED),this.getService(De).enableReplyAvatars()}catch(o){this.getService(y).catch("Error in _enableReplyAvatars: ",o);return}}_disableReplyAvatars(){this.getService(y).log("%c[WB] Calling FUNCTION: disableReplyAvatars","color: green;");try{this.trackEvent(Z.Events.Comments.DISABLE_REPLY_AVATARS_TRIGGERED),this.getService(De).disableReplyAvatars()}catch(o){this.getService(y).catch("Error in _disableReplyAvatars: ",o);return}}_setMaxReplyAvatars(o){this.getService(y).log("%c[WB] Calling FUNCTION: setMaxReplyAvatars","color: green;");try{this.trackEvent(Z.Events.Comments.SET_MAX_REPLY_AVATARS_TRIGGERED,{payload:{maxReplyAvatars:o}}),this.getService(De).setMaxReplyAvatars(o)}catch(n){this.getService(y).catch("Error in _setMaxReplyAvatars: ",n);return}}_setSidebarButtonCountType(o){this.getService(y).log("%c[WB] Calling FUNCTION: setSidebarButtonCountType","color: green;");try{this.trackEvent(Z.Events.Comments.SET_SIDEBAR_BUTTON_COUNT_TYPE_TRIGGERED,{payload:{type:o}}),this.getService(De).setSidebarButtonCountType(o)}catch(n){this.getService(y).catch("Error in _setSidebarButtonCountType: ",n);return}}_enableFilterGhostCommentsInSidebar(){this.getService(y).log("%c[WB] Calling FUNCTION: enableFilterGhostCommentsInSidebar","color: green;");try{this.trackEvent(Z.Events.Comments.ENABLE_FILTER_GHOST_COMMENTS_IN_SIDEBAR_TRIGGERED),this.getService(De).enableFilterGhostCommentsInSidebar()}catch(o){this.getService(y).catch("Error in _enableFilterGhostCommentsInSidebar: ",o);return}}_disableFilterGhostCommentsInSidebar(){this.getService(y).log("%c[WB] Calling FUNCTION: disableFilterGhostCommentsInSidebar","color: green;");try{this.trackEvent(Z.Events.Comments.DISABLE_FILTER_GHOST_COMMENTS_IN_SIDEBAR_TRIGGERED),this.getService(De).disableFilterGhostCommentsInSidebar()}catch(o){this.getService(y).catch("Error in _disableFilterGhostCommentsInSidebar: ",o);return}}};var qk=class extends si{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(xi).isUserGlobalContact$()}catch(o){return this.getService(y).catch("Error in _isUserGlobalContact: ",o),se(!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(xi).onContactSelected$()}catch(o){return this.getService(y).catch("Error in _onContactSelected: ",o),se(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(xi).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(xi).setAtHereLabel(o)}catch(n){this.getService(y).catch("Error in setAtHereLabel: ",n)}}_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(xi).setAtHereDescription(o)}catch(n){this.getService(y).catch("Error in setAtHereDescription: ",n)}}_disableAtHere(){this.getService(y).log("%c[WB] Calling FUNCTION: disableAtHere","color: green;");try{this.trackEvent(Z.Events.Contact.DISABLE_AT_HERE_TRIGGERED),this.getService(xi).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(xi).updateContactListScopeForOrganizationUsers(o)}catch(n){this.getService(y).catch("Error in _updateContactListScopeForOrganizationUsers: ",n)}}_updateContactList(o,n){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:n}}),typeof o=="object"&&o instanceof Array&&(!n||n&&typeof n=="object")&&(o=JSON.parse(JSON.stringify(o)),this.getService(xi).convert(n).updateContactList(o,n))}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(xi).getContactList$()}catch(o){return this.getService(y).catch("Error in _getContactList: ",o),se(null)}}};var Uc=(()=>{let o=class o{static generateKey(){return Q(this,null,function*(){try{return yield window.crypto.subtle.generateKey({name:"AES-GCM",length:this.KEY_LENGTH},!1,["encrypt","decrypt"])}catch(e){return ot.catch("Failed to generate key: ",e),null}})}static deriveKeyFromPassword(e,t){return Q(this,null,function*(){try{if(!t){let c=yield window.crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));t=new Uint8Array(c).slice(0,this.SALT_LENGTH)}let r=new TextEncoder().encode(e),a=yield window.crypto.subtle.importKey("raw",r,"PBKDF2",!1,["deriveBits","deriveKey"]);return{key:yield window.crypto.subtle.deriveKey({name:"PBKDF2",salt:t,iterations:this.PBKDF2_ITERATIONS,hash:"SHA-256"},a,{name:"AES-GCM",length:this.KEY_LENGTH},!1,["encrypt","decrypt"]),salt:t}}catch(r){return ot.catch("Failed to derive key from password: ",r),null}})}static resolveKey(e){return Q(this,null,function*(){try{if(e.customKey){if(e.customKey instanceof CryptoKey)return{key:e.customKey};if(typeof e.customKey=="string"){let r=yield this.deriveKeyFromPassword(e.customKey,e.customSalt);if(!r)return ot.catch("Failed to derive key from password"),null;let{key:a,salt:s}=r;return{key:a,salt:s}}}let t=yield this.generateKey();return t?{key:t}:(ot.catch("Failed to generate key"),null)}catch(t){return ot.catch("Failed to resolve key: ",t),null}})}static encrypt(r){return Q(this,arguments,function*(e,t={}){try{if(t.customEncryptCallback)try{return yield t.customEncryptCallback(e)}catch(E){return ot.catch("Custom encryption callback failed: ",E),""}let a=yield this.resolveKey(t);if(!a)return ot.catch("Failed to resolve key"),"";let{key:s,salt:c}=a,p;if(t.customIV){if(t.customIV.length!==this.IV_LENGTH)return ot.catch(`Custom IV must be exactly ${this.IV_LENGTH} bytes`),"";p=t.customIV}else p=window.crypto.getRandomValues(new Uint8Array(this.IV_LENGTH));let u=new TextEncoder().encode(e),C={name:"AES-GCM",iv:p,tagLength:128};t.additionalData&&(C.additionalData=t.additionalData);try{let E=yield window.crypto.subtle.encrypt(C,s,u),D=new Uint8Array(p.length+E.byteLength);return D.set(p,0),D.set(new Uint8Array(E),p.length),btoa(String.fromCharCode(...D))}catch(E){return ot.catch("Encryption failed: ",E),""}}catch(a){return ot.catch("Failed to encrypt: ",a),null}})}static decrypt(r){return Q(this,arguments,function*(e,t={}){try{if(t.customDecryptCallback)try{return yield t.customDecryptCallback(e)}catch(E){return ot.catch("Custom decryption callback failed: ",E),""}let a=yield this.resolveKey(t);if(!a)return ot.catch("Failed to resolve key"),"";let{key:s}=a,c=new Uint8Array(atob(e).split("").map(E=>E.charCodeAt(0)));if(c.length<this.IV_LENGTH)return ot.catch("Invalid encrypted data: Too short"),"";let p;if(t.customIV){if(t.customIV.length!==this.IV_LENGTH)return ot.catch(`Custom IV must be exactly ${this.IV_LENGTH} bytes`),"";p=t.customIV}else p=c.slice(0,this.IV_LENGTH);let u=c.slice(this.IV_LENGTH),C={name:"AES-GCM",iv:p,tagLength:128};t.additionalData&&(C.additionalData=t.additionalData);try{let E=yield window.crypto.subtle.decrypt(C,s,u);return new TextDecoder().decode(E)}catch(E){return ot.catch("Decryption failed: ",E),""}}catch(a){return ot.catch("Failed to decrypt: ",a),""}})}static encryptData(r){return Q(this,arguments,function*(e,t={}){try{let a=JSON.stringify(e);return(yield this.encrypt(a,t))??""}catch(a){return ot.catch("Failed to encrypt data: ",a),""}})}static decryptData(r){return Q(this,arguments,function*(e,t={}){try{let a=yield this.decrypt(e,t);return JSON.parse(a)}catch(a){return ot.catch("Failed to decrypt data: ",a),null}})}};o.IV_LENGTH=12,o.SALT_LENGTH=16,o.PBKDF2_ITERATIONS=1e5,o.KEY_LENGTH=256;let i=o;return i})();var ml=(()=>{let o=class o{constructor(e,t,r,a,s,c,p){this.authService=e,this.commonDbService=t,this.commonDbUtilsService=r,this.configService=a,this.docService=s,this.domService=c,this.loggingService=p;try{this.loggingService.log("%c[WB] Creating CLASS: CrdtService","color: blue;")}catch(u){this.loggingService.catch("Error in CrdtService constructor: ",u)}}updateData(r){return Q(this,arguments,function*({id:e,state:t}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: updateData","color: green;");let a=this.docService.getDocumentPaths(),s=this.authService.getUser(),c=this.domService.getTabId();if(s?.userId&&a){let p=bt(e),u=s.userId,C=bt(s.userId),E=null,D=this.configService.getEncryptionProvider();if(D?.encrypt&&typeof D.encrypt=="function")E=yield D.encrypt({data:t});else{let L={};L.customKey=p,E=yield Uc.encryptData(t,L)}return this.commonDbService.updateData({feature:"crdtData",properties:{documentId:a?.documentId??"",organizationId:a?.organizationId??"",id:p,skipFirestore:!0},data:{id:e,veltId:p,encryptedState:E,lastUpdate:new Date().toISOString(),lastUpdatedBy:u,lastUpdatedByVeltUserId:C,sessionId:c}})}return Promise.resolve(null)}catch(a){return this.loggingService.catch("Error in CrdtService updateData: ",a),Promise.resolve(null)}})}onDataChange({id:e,callback:t}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: onDataChange","color: green;");let r=this.docService.getDocumentPaths();if(r){let a=bt(e),s=this.commonDbService.dbListener({feature:"crdtData",properties:{documentId:r?.documentId??"",organizationId:r?.organizationId??"",id:a,skipFirestore:!0}}).subscribe(c=>Q(this,null,function*(){try{if(c?.data){if(c.data.encryptedState){let p=null,u=this.configService.getEncryptionProvider();if(u?.decrypt&&typeof u.decrypt=="function")p=yield u.decrypt({data:c.data.encryptedState});else{let C={};C.customKey=a,p=yield Uc.decryptData(c.data.encryptedState,C)}c.data.state=p,delete c.data?.encryptedState}t(c.data)}else{if(c?.encryptedState){let p=null,u=this.configService.getEncryptionProvider();if(u?.decrypt&&typeof u.decrypt=="function")p=yield u.decrypt({data:c.encryptedState});else{let C={};C.customKey=a,p=yield Uc.decryptData(c.encryptedState,C)}c.state=p,delete c?.encryptedState}t(c)}}catch(p){this.loggingService.catch("Error in CrdtService onDataChange subscription: ",p)}}));return()=>s.unsubscribe()}return()=>{}}catch(r){return this.loggingService.catch("Error in CrdtService onDataChange: ",r),()=>{}}}getData(t){return Q(this,arguments,function*({id:e}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: getData","color: green;");let r=this.docService.getDocumentPaths();if(r){let a=bt(e),s=yield this.commonDbService.getData({feature:"crdtData",properties:{documentId:r?.documentId??"",organizationId:r?.organizationId??"",id:a,skipFirestore:!0}});if(s?.encryptedState){let c=null,p=this.configService.getEncryptionProvider();if(p?.decrypt&&typeof p.decrypt=="function")c=yield p.decrypt({data:s.encryptedState});else{let u={};u.customKey=a,c=yield Uc.decryptData(s.encryptedState,u)}s.state=c,delete s?.encryptedState}return s}return Promise.resolve(null)}catch(r){return this.loggingService.catch("Error in CrdtService getData: ",r),Promise.resolve(null)}})}onStateChange({id:e,callback:t}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: onStateChange","color: green;");let r=this.docService.getDocumentPaths();if(r){let a=bt(e),s=this.commonDbService.dbListener({feature:"crdtSyncState",properties:{documentId:r?.documentId??"",organizationId:r?.organizationId??"",id:a,skipFirestore:!0}}).subscribe(c=>Q(this,null,function*(){try{if(c?.data){if(c.data.encryptedState){let p=null,u=this.configService.getEncryptionProvider();if(u?.decrypt&&typeof u.decrypt=="function")p=yield u.decrypt({data:c.data.encryptedState});else{let C={};C.customKey=a,p=yield Uc.decryptData(c.data.encryptedState,C)}c.data.state=p,delete c.data?.encryptedState}t(c.data)}else{if(c?.encryptedState){let p=null,u=this.configService.getEncryptionProvider();if(u?.decrypt&&typeof u.decrypt=="function")p=yield u.decrypt({data:c.encryptedState});else{let C={};C.customKey=a,p=yield Uc.decryptData(c.encryptedState,C)}c.state=p,delete c?.encryptedState}t(c)}}catch(p){this.loggingService.catch("Error in CrdtService onStateChange subscription: ",p)}}));return()=>s.unsubscribe()}return()=>{}}catch(r){return this.loggingService.catch("Error in CrdtService onStateChange: ",r),()=>{}}}updateState(r){return Q(this,arguments,function*({id:e,state:t}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: updateState","color: green;");let a=this.docService.getDocumentPaths(),s=this.authService.getUser(),c=this.domService.getTabId();if(s?.userId&&a){let p=bt(e),u=s.userId,C=bt(u),E=null,D=this.configService.getEncryptionProvider();if(D?.encrypt&&typeof D.encrypt=="function")E=yield D.encrypt({data:t});else{let L={};L.customKey=p,E=yield Uc.encryptData(t,L)}return this.commonDbService.setData({feature:"crdtSyncState",properties:{documentId:a?.documentId??"",organizationId:a?.organizationId??"",id:p,skipFirestore:!0},data:{id:e,veltId:p,encryptedState:E,lastUpdate:new Date().toISOString(),lastUpdatedBy:u,lastUpdatedByVeltUserId:C,sessionId:c}})}return Promise.resolve(null)}catch(a){return this.loggingService.catch("Error in CrdtService updateState: ",a),Promise.resolve(null)}})}registerSyncUser(t){return Q(this,arguments,function*({id:e}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: registerSyncUser","color: green;");let r=this.authService.getUser(),a=this.docService.getDocumentPaths(),s=this.configService.getApiKey(),c=bt(e),p=this.domService.getTabId();if(r?.userId&&a&&s){let u=r.userId,C=bt(u),E={documentId:a?.documentId??"",organizationId:a?.organizationId??"",id:c,userId:C,apiKey:s,skipFirestore:!0},D={userId:u,veltUserId:C,status:"online",lastSeen:Date.now(),sessionId:p};yield this.commonDbService.setData({feature:"crdtSyncPresence",properties:E,data:D});let L=this.commonDbUtilsService.getDocumentPath({feature:"crdtSyncPresence",properties:E,defaultDocumentPaths:a,apiKey:s});L&&(yield this.commonDbService.setupOnDisconnect(L,{status:"offline",lastSeen:new Date().getTime(),sessionId:p}))}}catch(r){this.loggingService.catch("Error in CrdtService registerSyncUser: ",r)}})}onRegisteredUserChange({id:e,callback:t}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: onRegisteredUserChange","color: green;");let r=this.docService.getDocumentPaths();if(r){let a=bt(e),s=this.commonDbService.dbListener({feature:"allCrdtSyncPresence",properties:{documentId:r?.documentId??"",organizationId:r?.organizationId??"",id:a,skipFirestore:!0}}).subscribe(c=>{try{c?.data?t(c.data):t(c)}catch(p){this.loggingService.catch("Error in CrdtService onRegisteredUserChange subscription: ",p)}});return()=>s.unsubscribe()}return()=>{}}catch(r){return this.loggingService.catch("Error in CrdtService onRegisteredUserChange: ",r),()=>{}}}setPresence(t){return Q(this,arguments,function*({id:e}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: setPresence","color: green;");let r=this.authService.getUser(),a=this.docService.getDocumentPaths(),s=this.configService.getApiKey(),c=bt(e),p=this.domService.getTabId();if(r?.userId&&a&&s){let u=r.userId,C=bt(u),E={documentId:a?.documentId??"",organizationId:a?.organizationId??"",id:c,userId:C,apiKey:s,skipFirestore:!0},D={userId:u,veltUserId:C,status:"online",lastSeen:Date.now(),sessionId:p};yield this.commonDbService.setData({feature:"crdtPresence",properties:E,data:D});let L=this.commonDbUtilsService.getDocumentPath({feature:"crdtPresence",properties:E,defaultDocumentPaths:a,apiKey:s});L&&(yield this.commonDbService.setupOnDisconnect(L,{status:"offline",lastSeen:new Date().getTime(),sessionId:p}))}}catch(r){this.loggingService.catch("Error in CrdtService setPresence: ",r)}})}onPresenceChange({id:e,callback:t}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: onPresenceChange","color: green;");let r=this.docService.getDocumentPaths();if(r){let a=bt(e),s=this.commonDbService.dbListener({feature:"allCrdtPresence",properties:{documentId:r?.documentId??"",organizationId:r?.organizationId??"",id:a,skipFirestore:!0}}).subscribe(c=>{try{c?.data?t(c.data):t(c)}catch(p){this.loggingService.catch("Error in CrdtService onPresenceChange subscription: ",p)}});return()=>s.unsubscribe()}return()=>{}}catch(r){return this.loggingService.catch("Error in CrdtService onPresenceChange: ",r),()=>{}}}saveVersion(s){return Q(this,arguments,function*({id:e,versionId:t,versionName:r,state:a}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: saveVersion","color: green;");let c=this.docService.getDocumentPaths();if(c){let p=bt(e),u="",C=this.configService.getEncryptionProvider();if(C?.encrypt&&typeof C.encrypt=="function")u=yield C.encrypt({data:a});else{let D={};D.customKey=p,u=yield Uc.encryptData(a,D)}let E={versionId:t,versionName:r,encryptedState:u,timestamp:new Date().getTime()};return this.commonDbService.setData({feature:"crdtVersion",properties:{documentId:c?.documentId??"",organizationId:c?.organizationId??"",id:p,versionId:t,skipFirestore:!0},data:I({id:e},E)})}return Promise.resolve(null)}catch(c){return this.loggingService.catch("Error in CrdtService saveVersion: ",c),Promise.resolve(null)}})}getVersion(r){return Q(this,arguments,function*({id:e,versionId:t}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: getVersion","color: green;");let a=this.docService.getDocumentPaths();if(a){let s=bt(e),c=yield this.commonDbService.getData({feature:"crdtVersion",properties:{documentId:a?.documentId??"",organizationId:a?.organizationId??"",id:s,versionId:t,skipFirestore:!0}});if(c?.encryptedState){let p=null,u=this.configService.getEncryptionProvider();if(u?.decrypt&&typeof u.decrypt=="function")p=yield u.decrypt({data:c.encryptedState});else{let C={};C.customKey=s,p=yield Uc.decryptData(c.encryptedState,C)}c.state=p,delete c.encryptedState}return c}return Promise.resolve(null)}catch(a){return this.loggingService.catch("Error in CrdtService getVersion: ",a),Promise.resolve(null)}})}getVersions(t){return Q(this,arguments,function*({id:e}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: getVersions","color: green;");let r=this.docService.getDocumentPaths();if(r){let a=bt(e),s=yield this.commonDbService.getData({feature:"crdtVersions",properties:{documentId:r?.documentId??"",organizationId:r?.organizationId??"",id:a,skipFirestore:!0}}),c=null;if(s){c=[];for(let p of Object.values(s))if(p?.encryptedState){let u=null,C=this.configService.getEncryptionProvider();if(C?.decrypt&&typeof C.decrypt=="function")u=yield C.decrypt({data:p.encryptedState});else{let D={};D.customKey=a,u=yield Uc.decryptData(p.encryptedState,D)}let E=T(I({},p),{state:u});delete E?.encryptedState,c.push(E)}else c.push(p)}return c}return Promise.resolve(null)}catch(r){return this.loggingService.catch("Error in CrdtService getVersions: ",r),Promise.resolve(null)}})}};o.\u0275fac=function(t){return new(t||o)(ee(Ve),ee(pn),ee(ag),ee(Ft),ee(at),ee(Be),ee(y))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var Yk=class extends si{constructor(o){super(o),this.getService(y).log("%c[WB] Creating CLASS: CrdtElement","color: blue;"),this.updateData=this._updateData,this.onDataChange=this._onDataChange,this.getData=this._getData,this.onStateChange=this._onStateChange,this.updateState=this._updateState,this.registerSyncUser=this._registerSyncUser,this.onRegisteredUserChange=this._onRegisteredUserChange,this.setPresence=this._setPresence,this.onPresenceChange=this._onPresenceChange,this.saveVersion=this._saveVersion,this.getVersion=this._getVersion,this.getVersions=this._getVersions}_updateData(o){this.getService(y).log("%c[WB] Calling FUNCTION: updateData","color: green;");try{return this.getService(ml).updateData(o)}catch(n){return this.getService(y).catch("Error in updateData: ",n),Promise.resolve(null)}}_onDataChange(o){this.getService(y).log("%c[WB] Calling FUNCTION: onDataChange","color: green;");try{return this.getService(ml).onDataChange(o)}catch(n){return this.getService(y).catch("Error in onDataChange: ",n),()=>{}}}_getData(o){this.getService(y).log("%c[WB] Calling FUNCTION: getData","color: green;");try{return this.getService(ml).getData(o)}catch(n){return this.getService(y).catch("Error in getData: ",n),Promise.resolve(null)}}_onStateChange(o){this.getService(y).log("%c[WB] Calling FUNCTION: onStateChange","color: green;");try{return this.getService(ml).onStateChange(o)}catch(n){return this.getService(y).catch("Error in onStateChange: ",n),()=>{}}}_updateState(o){this.getService(y).log("%c[WB] Calling FUNCTION: updateState","color: green;");try{return this.getService(ml).updateState(o)}catch(n){return this.getService(y).catch("Error in updateState: ",n),Promise.resolve(null)}}_registerSyncUser(o){this.getService(y).log("%c[WB] Calling FUNCTION: registerSyncUser","color: green;");try{return this.getService(ml).registerSyncUser(o)}catch(n){return this.getService(y).catch("Error in registerSyncUser: ",n),Promise.resolve()}}_onRegisteredUserChange(o){this.getService(y).log("%c[WB] Calling FUNCTION: onRegisteredUserChange","color: green;");try{return this.getService(ml).onRegisteredUserChange(o)}catch(n){return this.getService(y).catch("Error in onRegisteredUserChange: ",n),()=>{}}}_setPresence(o){this.getService(y).log("%c[WB] Calling FUNCTION: setPresence","color: green;");try{return this.getService(ml).setPresence(o)}catch(n){return this.getService(y).catch("Error in setPresence: ",n),Promise.resolve()}}_onPresenceChange(o){this.getService(y).log("%c[WB] Calling FUNCTION: onPresenceChange","color: green;");try{return this.getService(ml).onPresenceChange(o)}catch(n){return this.getService(y).catch("Error in onPresenceChange: ",n),()=>{}}}_saveVersion(o){this.getService(y).log("%c[WB] Calling FUNCTION: saveVersion","color: green;");try{return this.getService(ml).saveVersion(o)}catch(n){return this.getService(y).catch("Error in saveVersion: ",n),Promise.resolve(null)}}_getVersion(o){this.getService(y).log("%c[WB] Calling FUNCTION: getVersion","color: green;");try{return this.getService(ml).getVersion(o)}catch(n){return this.getService(y).catch("Error in getVersion: ",n),Promise.resolve(null)}}_getVersions(o){this.getService(y).log("%c[WB] Calling FUNCTION: getVersions","color: green;");try{return this.getService(ml).getVersions(o)}catch(n){return this.getService(y).catch("Error in getVersions: ",n),Promise.resolve(null)}}};var ms=function(i){return i.CLICK="click",i.HOVER="hover",i.SCROLL="scroll",i.NAVIGATE="navigate",i}(ms||{}),qm=class{constructor(){this.type=ms.HOVER,this.data=null,this.pageInfo=Oi(),this.timestamp=Date.now()}},Kk=class{constructor(o,n){this.targetXpath=o,this.xpath=n}};var Zk=class{constructor(){this.sessionId=null,this.isLeader=!1,this.lastProcessedActionTimestamp=null}};var _h=class{constructor(o){this.snippylyId=o,this.joinTimestamp=Date.now()}};var Xk=class{constructor(o,n,e){this.followers=[],this.actionStack=[],this.id=xn(),this.leaderId=o,this.leaderName=n,this.followers.push(new _h(e))}};var nde=(()=>{let o=class o{constructor(e,t,r,a,s){this.databaseService=e,this.docService=t,this.loggingService=r,this.authService=a,this.commonDbService=s,this.currentUser$=new ve(null),this.currentSession$=new ve(null);try{this.databaseService.getDb().pipe(Le(c=>!!c),st(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(t){this.loggingService.catch("Error in FlockSessionService startCurrentFlockUserSubscription: ",t)}}stopCurrentFlockUserSubscription(){try{this.currentUserSub?.unsubscribe()}catch(e){this.loggingService.catch("Error in FlockSessionService stopCurrentFlockUserSubscription: ",e)}}provisionFlockSession(e,t,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(st(1)).subscribe(s=>{s?.data&&s?.data?.sessionId?this.subscribeToCurrentSession(s?.data?.sessionId,r):this.createFlockSession(e,t,r)})}catch(a){this.loggingService.catch("Error in FlockSessionService provisionFlockSession: ",a)}return null}swapLeader(e,t,r){try{if(this.updateRemoteFlockUser(e,{isLeader:!1}),this.updateRemoteFlockUser(t,{isLeader:!0}),this.currentSession){this.currentSession.leaderId=t,this.currentSession.leaderName=r,this.currentSession.followers.push(new _h(e));let a=this.currentSession.followers.findIndex(s=>s.snippylyId===t);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,t,r){try{let a=new Xk(e,t,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 t=this.currentSession.followers.findIndex(r=>r.snippylyId===e);if(t>-1){if(this.currentSession.followers.splice(t,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(t){this.loggingService.catch("Error in FlockSessionService removeFollowerFromSession: ",t)}}updateRemoteFlockUser(e,t={}){try{if(!e)return;let r=this.docService.getDocumentPaths();for(let a in t)t.hasOwnProperty(a)&&t[a]===void 0&&delete t[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(t))})}catch(r){this.loggingService.catch("Error in FlockSessionService updateRemoteFlockUser: ",r)}}subscribeToCurrentSession(e,t=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,t!==void 0&&this.currentSession?.followers.findIndex(s=>s.snippylyId===t)===-1&&(this.currentSession.followers.push(new _h(t)),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 t=this.docService.getDocumentPaths();t&&this.db&&(this.currentUserSub&&this.currentUserSub.unsubscribe(),this.currentUserSub=this.commonDbService.dbListener({feature:"flockUser",properties:{documentId:t?.documentId,organizationId:t?.organizationId,id:e,skipFirestore:!0}}).pipe(kn(r=>(this.loggingService.catch("Error in FlockSessionService subscribeToCurrentFlockUser: ",r),se(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(t){this.loggingService.catch("Error in FlockSessionService subscribeToCurrentFlockUser: ",t)}}updateSession(e,t={}){try{if(!e)return;let r=this.docService.getDocumentPaths();for(let a in t)t.hasOwnProperty(a)&&t[a]===void 0&&delete t[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(t))})}catch(r){this.loggingService.catch("Error in FlockSessionService updateSession: ",r)}}deleteSession(e){try{let t=this.docService.getDocumentPaths();t&&this.db&&(this.commonDbService.deleteData({feature:"flockSession",properties:{documentId:t?.documentId??"",organizationId:t?.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(t){this.loggingService.catch("Error in FlockSessionService deleteSession: ",t)}}addActionToStack(e,t){try{t=t&&JSON.parse(JSON.stringify(t));let r=this.docService.getDocumentPaths();if(r&&this.db&&e){let a=qi(this.db,`${r.flock}/sessions/${e}/actionStack`);Bu(a,s=>s?(s.unshift(t),s.slice(0,5)):[t]),t.type===ms.NAVIGATE&&this.updateSession(e,{pageInfo:t.pageInfo})}}catch(r){this.loggingService.catch("Error in FlockSessionService addActionToStack: ",r)}}};o.\u0275fac=function(t){return new(t||o)(ee(Dn),ee(at),ee(y),ee(Ve),ee(pn))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();function lRe(i,o){if(i&1&&(_(0,"span",6),te(1),P(2,"translate"),b()),i&2){let n=l(2).ngIf;m(),vr("",M(2,2,"You are following")," ",n.leaderName,"")}}function cRe(i,o){i&1&&(_(0,"span",6),te(1),P(2,"translate"),b()),i&2&&(m(),Ge(M(2,1,"You are leading.")))}function dRe(i,o){if(i&1){let n=Y();_(0,"div",2),G("click",function(){N(n);let t=l().ngIf,r=l();return F(t.type==="following"?r.closeOverlay():void 0)}),_(1,"div",3),g(2,lRe,3,4,"span",4)(3,cRe,3,3,"span",4),_(4,"button",5),G("click",function(){N(n);let t=l(2);return F(t.closeOverlay())}),te(5),P(6,"translate"),P(7,"translate"),b()()()}if(i&2){let n=l().ngIf;ge("no-pointer",n.type==="leading"),m(2),d("ngIf",n.type==="following"),m(),d("ngIf",n.type==="leading"),m(2),vr("",M(6,6,"Stop")," ",M(7,8,n.type),"")}}function mRe(i,o){if(i&1&&(f(0),g(1,dRe,8,10,"div",1),v()),i&2){let n=o.ngIf;m(),d("ngIf",n.leaderName!==""||n.type==="leading")}}var kb=(()=>{let o=class o extends Je{closeOverlay(){this.closeOverlayEvent.emit()}constructor(e,t,r){super(t,r),this.loggingService=e,this.elementRef=t,this.themeService=r,this.closeOverlayEvent=new Me,this.componentConfigSignal=Te({leaderName:"",type:"following"})}ngOnInit(){}setLeaderName(e){try{this.componentConfigSignal.update(t=>(t=T(I({},t),{leaderName:e}),t))}catch(t){this.loggingService.catch("Error in FollowOverlayComponent setLeaderName: ",t)}}getLeaderName(){return this.componentConfigSignal().leaderName}setType(e){try{this.componentConfigSignal.update(t=>(t=T(I({},t),{type:e}),t))}catch(t){this.loggingService.catch("Error in FollowOverlayComponent setType: ",t)}}ngOnDestroy(){try{super.ngOnDestroy()}catch{}}};o.\u0275fac=function(t){return new(t||o)(h(y),h(R),h(qe))},o.\u0275cmp=O({type:o,selectors:[["snippyly-follow-overlay"]],outputs:{closeOverlayEvent:"closeOverlayEvent"},standalone:!1,features:[B],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(t,r){t&1&&g(0,mRe,2,1,"ng-container",0),t&2&&d("ngIf",r.componentConfigSignal())},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}
475
475
  `],encapsulation:3,changeDetection:0});let i=o;return i})();var ide=(()=>{let o=class o{constructor(e,t,r,a){this.componentFactoryResolver=e,this.applicationRef=t,this.injector=r,this.loggingService=a,this.darkMode=!1}createFollowOverlay(e,t){try{let a=this.componentFactoryResolver.resolveComponentFactory(kb).create(this.injector);a.instance.setLeaderName(e),a.instance.closeOverlayEvent.pipe(st(1)).subscribe(()=>{this.removeOverlay(),t()}),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(j.ATTRIBUTES.VELT_IGNORE,""),document.body.appendChild(s)}catch(r){this.loggingService.catch("Error in FlockOverlayService createFollowOverlay: ",r)}}createLeaderOverlay(e){let r=this.componentFactoryResolver.resolveComponentFactory(kb).create(this.injector);r.instance.setType("leading"),r.instance.closeOverlayEvent.pipe(st(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(j.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(t){this.loggingService.catch("Error in FlockOverlayService setDarkMode: ",t)}}};o.\u0275fac=function(t){return new(t||o)(ee(wo),ee(Ci),ee(Ot),ee(y))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var jc=(()=>{let o=class o{constructor(e,t,r,a,s){this.authService=e,this.domService=t,this.loggingService=r,this.flockSessionService=a,this.flockOverlayService=s,this.flockLeader$=new ve({userId:"",name:""}),this.flockMode$=new ve(!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:u}=c,C=p;if(this.provisionFollowUser(),C&&this.currentFlockUser&&this.currentFlockUser.snippylyId)if(this.currentFlockUser.sessionId){if(this.currentFlockUser.snippylyId&&this.currentFlockUser.isLeader){this.flockSessionService.swapLeader(this.currentFlockUser.snippylyId,C,u);return}this.removeCurrentUserFromSession()}else this.flockSessionService.provisionFlockSession(C,u,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=Oi();if(c.pageInfo){if(p&&p.url!==c.pageInfo.url){let u=new qm;u.type=ms.NAVIGATE,this.flockSessionService.addActionToStack(c.id,u)}}else{this.flockSessionService.updateSession(c.id,{pageInfo:p});let u=new qm;u.type=ms.NAVIGATE,this.flockSessionService.addActionToStack(c.id,u)}}}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()}),Sn([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 Zk,this.currentFlockUser.snippylyId=e.userSnippylyId)}}catch(e){this.loggingService.catch("Error in FlockService provisionFollowUser: ",e)}}startFollowingUser(e,t){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,t);return}this.removeCurrentUserFromSession()}this.flockSessionService.provisionFlockSession(e,t,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,t=window.history.replaceState;window.history.pushState=(...r)=>{e.apply(window.history,r),this.onUrlChange()},window.history.replaceState=(...r)=>{t.apply(window.history,r),this.onUrlChange()},this.domSubscriptions.push({unsubscribe:()=>{window.history.pushState=e,window.history.replaceState=t}}),this.domSubscriptions.push(pi(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 qm;e.type=ms.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 ms.CLICK:this.clickUserElement(e.data);break;case ms.HOVER:this.scrollToHoveredElement(e.data);break;case ms.SCROLL:this.scrollToFollowedUser(e.data);break;case ms.NAVIGATE:this.checkMatchingUrl(e.pageInfo);break}this.currentFlockUser&&this.currentFlockUser.snippylyId&&this.flockSessionService.updateRemoteFlockUser(this.currentFlockUser.snippylyId,{lastProcessedActionTimestamp:e.timestamp})}catch(t){this.loggingService.catch("Error in FlockService processAction: ",t)}}subscribeToLeaderDOMEvents(){try{this.domSubscriptions.length>0&&(this.domSubscriptions.forEach(e=>e.unsubscribe()),this.domSubscriptions=[]),this.domSubscriptions.push(pi(window,"mouseover").pipe(lr(500)).subscribe(e=>{let t=e?.target;if(t){let r=window.getComputedStyle(t);if(r.position==="fixed"||r.position==="sticky"||t.hasAttribute(j.ATTRIBUTES.VELT_IGNORE))return;t=Nj(t,{x:e.clientX,y:e.clientY}),this.updateHoveredElement(t)}})),this.domSubscriptions.push(this.domService.onWindowClick$().subscribe(e=>{let t=e?.target;if(t){if(t.hasAttribute(j.ATTRIBUTES.VELT_IGNORE))return;this.updateClickedElement(t)}})),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 t=this.domService.getXPath(e),r=Ov(e),a=this.domService.getXPath(r),s={id:Math.random().toString(36).substring(2),xpath:t,parentXpath:a},c=new qm;c.type=ms.CLICK,c.data=s,this.flockSessionService.addActionToStack(this.currentFlockUser.sessionId,c)}}catch(t){this.loggingService.catch("Error in FlockService updateClickedElement: ",t)}}updateHoveredElement(e){try{if(this.currentFlockUser&&this.currentFlockUser.sessionId){let t=this.domService.getXPath(e),r=Ov(e),a=this.domService.getXPath(r),s={id:Math.random().toString(36).substring(2),xpath:t,parentXpath:a},c=new qm;c.type=ms.HOVER,c.data=s,this.flockSessionService.addActionToStack(this.currentFlockUser.sessionId,c)}}catch(t){this.loggingService.catch("Error in FlockService updateHoveredElement: ",t)}}subscribeToScrollables(){try{let e=pae();e.push(document),e?.forEach(t=>{this.domSubscriptions.push(pi(t,"scroll").pipe(lr(100)).subscribe(r=>{this.currentFlockUser&&this.currentFlockUser.sessionId&&this.currentFlockUser.isLeader&&this.updateScrollPositionOfElement(t)}))})}catch(e){this.loggingService.catch("Error in FlockService getScrollableElements: ",e)}}updateScrollPositionOfElement(e){try{if(this.currentFlockUser&&this.currentFlockUser.sessionId){let t=new Kk("","");if(e===document){let s=hae();if(s){let c=Nj(s);c&&(t.targetXpath=this.domService.getXPath(c))}t.xpath=""}else{let s=uae(e);t.targetXpath=this.domService.getXPath(s),t.xpath=this.domService.getXPath(e)}let r=!1,a=!1;if(this.localScrollData.forEach((s,c)=>{s.xpath===s.xpath&&(t.targetXpath!==s.targetXpath&&(r=!0),this.localScrollData[c]=Object.assign(s,t),a=!0)}),a||this.localScrollData.push(t),r||!a){let s=new qm;s.type=ms.SCROLL,s.data=t,this.flockSessionService.addActionToStack(this.currentFlockUser.sessionId,s)}}}catch(t){this.loggingService.catch("Error in FlockService calculateScrollPositionOfAnElement: ",t)}}enableFlockMode(e){try{if(this.flockMode$.next(!0),e){let{useHistoryAPI:t,onNavigate:r,disableDefaultNavigation:a,darkMode:s}=e;t!==void 0&&(this.useHistoryAPI=t),r!==void 0&&typeof r=="function"&&(this.onNavigate=r),a!==void 0&&(this.disableDefaultNavigation=a),this.flockOverlayService.setDarkMode(s)}}catch(t){this.loggingService.catch("Error in FlockService enableFlockMode: ",t)}}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(t){this.loggingService.catch("Error in FlockService setDisableFlockNavigation: ",t)}}getFlockMode$(){return this.flockMode$.asObservable()}getFlockMode(){return this.flockMode$.value}setNavigateEmitter(e){try{this.onNavigateEmitter=e}catch(t){this.loggingService.catch("Error in FlockService setNavigateEmitter: ",t)}}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(t){this.loggingService.catch("Error in FlockService setTabFocused: ",t)}}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(t){this.loggingService.catch("Error in FlockService setWindowFocused: ",t)}}setFlockLeader(e,t){try{this.flockLeader$.next({userId:e,name:t})}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=Oi()?.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(t){this.loggingService.catch("Error in FlockService checkMatchingUrl: ",t)}}scrollToFollowedUser(e){try{if(e.xpath===""){let t=this.domService.getElementFromXPath(e.targetXpath);t&&tM(t)}else{let t=this.domService.getElementFromXPath(e.xpath),r=this.domService.getElementFromXPath(e.targetXpath);t&&r&&(tM(t),Fj(t,r))}}catch(t){this.loggingService.catch("Error in FlockService scrollToFollowedUser: ",t)}}clickUserElement(e){try{let t=this.domService.getElementFromXPath(e.xpath);t&&this.lastClickedElement?.id!==e.id&&(t?.click(),this.lastClickedElement=e)}catch(t){this.loggingService.catch("Error in FlockService clickUserElement: ",t)}}scrollToHoveredElement(e){try{let t=this.domService.getElementFromXPath(e.xpath);if(t&&e.parentXpath)if(e.parentXpath==="/html")tM(t);else{let r=this.domService.getElementFromXPath(e.parentXpath);r&&Fj(r,t,!0)}}catch(t){this.loggingService.catch("Error in FlockService clickUserElement: ",t)}}};o.\u0275fac=function(t){return new(t||o)(ee(Ve),ee(Be),ee(y),ee(nde),ee(ide))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var Qk=(()=>{let o=class o{constructor(e,t){this.analyticsService=e,this.loggingService=t,this.actionSubjects=new Map,this.subscriptions=[]}onAccessRequested(e){try{this.triggerAction($p.ACCESS_REQUESTED,e),this.analyticsService.trackEvent(Z.Events.LiveStateSync.SEM_ACCESS_REQUESTED,{viewerUserId:e?.viewer?.userId,editorUserId:e?.editor?.userId,timestamp:e?.timestamp,status:e?.status})}catch(t){this.loggingService.catch("Error in LiveStateActionsService onAccessRequested: ",t)}}onAccessRequestCanceled(e){try{this.triggerAction($p.ACCESS_REQUEST_CANCELED,e),this.analyticsService.trackEvent(Z.Events.LiveStateSync.SEM_ACCESS_REQUEST_CANCELED,{viewerUserId:e?.viewer?.userId,editorUserId:e?.editor?.userId,timestamp:e?.timestamp,status:e?.status})}catch(t){this.loggingService.catch("Error in LiveStateActionsService onAccessRequestCanceled: ",t)}}onAccessAccepted(e){try{this.triggerAction($p.ACCESS_ACCEPTED,e),this.analyticsService.trackEvent(Z.Events.LiveStateSync.SEM_ACCESS_ACCEPTED,{viewerUserId:e?.viewer?.userId,editorUserId:e?.editor?.userId,timestamp:e?.timestamp,status:e?.status})}catch(t){this.loggingService.catch("Error in LiveStateActionsService onAccessAccepted: ",t)}}onAccessRejected(e){try{this.triggerAction($p.ACCESS_REJECTED,e),this.analyticsService.trackEvent(Z.Events.LiveStateSync.SEM_ACCESS_REJECTED,{viewerUserId:e?.viewer?.userId,editorUserId:e?.editor?.userId,timestamp:e?.timestamp,status:e?.status})}catch(t){this.loggingService.catch("Error in LiveStateActionsService onAccessRejected: ",t)}}onEditorAssigned(e){try{this.triggerAction($p.EDITOR_ASSIGNED,e),this.analyticsService.trackEvent(Z.Events.LiveStateSync.SEM_EDITOR_ASSIGNED,{editorUserId:e?.editor?.userId,timestamp:e?.timestamp,role:e?.role})}catch(t){this.loggingService.catch("Error in LiveStateActionsService onEditorAssigned: ",t)}}onEditorOnDifferentTabDetected(e){try{this.triggerAction($p.EDITOR_ON_DIFFERENT_TAB_DETECTED,e),this.analyticsService.trackEvent(Z.Events.LiveStateSync.SEM_EDITOR_ON_DIFFERENT_TAB_DETECTED,{editorUserId:e?.editor?.userId,timestamp:e?.timestamp,role:e?.role})}catch(t){this.loggingService.catch("Error in LiveStateActionsService onEditorOnDifferentTabDetected: ",t)}}onViewerAssigned(e){try{this.triggerAction($p.VIEWER_ASSIGNED,e),this.analyticsService.trackEvent(Z.Events.LiveStateSync.SEM_VIEWER_ASSIGNED,{viewerUserId:e?.viewer?.userId,timestamp:e?.timestamp,role:e?.role})}catch(t){this.loggingService.catch("Error in LiveStateActionsService onViewerAssigned: ",t)}}triggerAction(e,t){try{this.actionSubjects.has(e)||this.actionSubjects.set(e,new tt),this.actionSubjects.get(e)?.next(t)}catch(r){this.loggingService.catch("Error in LiveStateActionsService triggerAction: ",r)}}onAction(e){try{return this.actionSubjects.has(e)||this.actionSubjects.set(e,new tt),this.actionSubjects.get(e)?.asObservable()}catch(t){return this.loggingService.catch("Error in LiveStateActionsService onAction: ",t),se(null)}}};o.\u0275fac=function(t){return new(t||o)(ee(et),ee(y))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var Li=(()=>{let o=class o{constructor(e,t,r,a,s,c,p,u,C,E,D,L,z){this.afAuth=e,this.analyticsService=t,this.authService=r,this.configService=a,this.databaseService=s,this.docService=c,this.domService=p,this.iamService=u,this.loggingService=C,this.commonDbService=E,this.liveStateActionsService=D,this.liveStateUtilsService=L,this.usersService=z,this.db=ts(),this.liveStateDataMap$=new ve({}),this.liveStateDataMapDraft={},this.singleEditorMode$=new ve(!1),this.singleEditorModeConfig$=new ve(null),this.singleEditorLiveStateData$=new ve(null),this.singleEditorLiveStateData={},this.editorAccessTimeout$=new ve(j.LIVE_STATE_REQUEST_EDITOR_ACCESS_WAIT_TIME),this.editorAccessTransferOnTimeOut$=new ve(!0),this.defaultSingleEditorUIEnabled$=new ve(!0),this.editorAccessTimer$=new ve(new p0),this.autoSyncState$=new ve(!1),this.serverConnectionState$=new ve(ol.PENDING_INIT),this.userPresence$=new ve(null),this.user=null,this.keydownSubscription=null,this.isEditor$=new ve(null),this.preventEventsOnElementMap={},this.PREVENT_EVENTS=["click","mouseup","mousedown"],this.autoSyncStateHistory=null,this.singleEditorModeContainerIds$=new ve([]),this.inputChangeSubscriptionMap={},this.childListMutationSubscription=null,this.tabId=this.domService.getTabId();try{this.loggingService.log("%c[WB] Creating CLASS: LiveStateService","color: blue;"),this.analyticsService.setLiveStateService(this),this.databaseService.getDb().pipe(Le(W=>!!W),st(1)).subscribe(W=>{W&&(this.db=W,this.getUser(),this.getDocumentPaths(),this.subscribeLiveStateData().subscribe(),this.singleEditorMode$.subscribe(J=>{J&&this.detectKeydownOnInput()}),this.autoSyncState$.subscribe(J=>{J?(this.detectLiveSyncInputs(),this.observeElementAddedOnDom()):(this.unsubscribeInputChanges(),this.childListMutationSubscription?.unsubscribe(),this.childListMutationSubscription=null)}),this.updateOnDatabaseDisconnect().subscribe(()=>{},J=>{this.loggingService.catch("Error in LiveStateService constructor updateOnDatabaseDisconnect: ",J)}),this.updateServerStateOnDatabaseDisconnect().subscribe(()=>{},J=>{this.loggingService.catch("Error in LiveStateService constructor updateServerStateOnDatabaseDisconnect: ",J)}))},W=>{this.loggingService.catch("Error in LiveStateService getDb subscription: ",W)}),this.liveStateDataMap$.pipe(Le(W=>!!W?.default?.autoSyncState),ce(W=>W.default?.autoSyncState),Et((W,J)=>JSON.stringify(W||{})===JSON.stringify(J||{}))).subscribe(W=>{W&&(this.getAutoSyncState()&&(!this.autoSyncStateHistory&&W?.history&&this.updateLiveStateSyncInputDataLocally(W.history),W?.current&&this.updateLiveStateSyncInputDataLocally({[W.current.liveStateDataId]:W.current})),!this.autoSyncStateHistory&&W?.history&&(this.autoSyncStateHistory=W.history))}),this.docService.addPreDocumentIdChangeFunction("live-state-service",W=>(this.updateUserPresence(null),this.isUserEditor()?.isEditor&&(!this.getSingleEditorModeConfig()?.singleTabEditor||this.isUserEditor()?.isEditorOnCurrentTab)?this.removeEditorAccess({metadata:{from:"addPreDocumentIdChangeFunction-liveStateService",reason:"Document id changed"}}):Promise.resolve())),this.singleEditorLiveStateData$.pipe(Bi()).subscribe(([W,J])=>{try{let ue=J?.requestEditorAccess?.status,ye=W?.requestEditorAccess?.status,Ae=this.authService.getUser();if(ue==="pending"){if(Ae?.userId===J?.editor?.userId){let He={viewer:_a(J?.requestEditorAccess?.user)??void 0,editor:_a(J?.editor)??void 0,timestamp:new Date().getTime(),status:"requested"};this.liveStateActionsService?.onAccessRequested(He)}return}if(ue==="cancelled"){if(Ae?.userId===J?.editor?.userId){let He={viewer:_a(J?.requestEditorAccess?.user)??void 0,editor:_a(J?.editor)??void 0,timestamp:new Date().getTime(),status:"canceled"};this.liveStateActionsService?.onAccessRequestCanceled(He)}return}if(ye==="pending"&&!ue){if(W?.requestEditorAccess?.user?.userId===J?.editor?.userId){if(W?.requestEditorAccess?.user?.userId===Ae?.userId){let He={viewer:_a(W?.editor)??void 0,editor:_a(J?.editor)??void 0,timestamp:new Date().getTime(),status:"accepted"};this.liveStateActionsService?.onAccessAccepted(He)}return}if(W?.requestEditorAccess?.user?.userId!==J?.editor?.userId){if(W?.requestEditorAccess?.user?.userId===Ae?.userId){let He={viewer:_a(W?.requestEditorAccess?.user)??void 0,editor:_a(J?.editor)??void 0,timestamp:new Date().getTime(),status:"rejected"};this.liveStateActionsService?.onAccessRejected(He)}return}}}catch(ue){this.loggingService.catch("Error in LiveStateService singleEditorLiveStateData$ subscription: ",ue)}}),this.isUserEditor$().pipe(Et(mn)).subscribe(W=>{try{if(W){this.analyticsService.trackEvent(Z.Events.LiveStateSync.SEM_USER_EDITOR_STATS,{isEditor:W?.isEditor,isEditorOnCurrentTab:W?.isEditorOnCurrentTab});let J=this.singleEditorLiveStateData$.value;if(W?.isEditor)if(W?.isEditorOnCurrentTab){let ue={editor:_a(J?.editor)??void 0,timestamp:new Date().getTime(),role:"editor"};this.liveStateActionsService?.onEditorAssigned(ue)}else{let ue={editor:_a(J?.editor)??void 0,timestamp:new Date().getTime(),role:"editorOnDifferentTab"};this.liveStateActionsService?.onEditorOnDifferentTabDetected(ue)}else{let ue={viewer:_a(this.authService.getUser())??void 0,timestamp:new Date().getTime(),role:"viewer"};this.liveStateActionsService?.onViewerAssigned(ue)}}}catch(J){this.loggingService.catch("Error in LiveStateService isUserEditor$ subscription: ",J)}})}catch(W){this.loggingService.catch("Error in LiveStateService constructor: ",W)}}setPresenceService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setPresenceService","color: green;"),this.presenceService=e}catch(t){this.loggingService.catch("Error in LiveStateService setPresenceService: ",t)}}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(t=>{let r=Array.from(t.addedNodes||[]).filter(a=>a instanceof HTMLElement);r?.forEach(a=>{Vj(a,!0)?.forEach(p=>{typeof p?.getAttribute=="function"&&p?.getAttribute(j.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(Le(e=>e?.target instanceof HTMLInputElement||e?.target instanceof HTMLTextAreaElement||e?.target instanceof HTMLSelectElement),Le(e=>!!this.isElementInsideSingleEditorModeContainerElements(e?.target)),st(1)).subscribe(e=>{this.unsubscribeKeydownSubscription(),this.getSingleEditorModeConfig()?.customMode||this.setUserAsEditor({skipEditorCheck:!0})},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;"),ei(this.afAuth).pipe(Le(e=>!!e),he(e=>this.isFeatureAllowed({firebaseUser:e,liveStateData:{}})),he(e=>e.featureAllowed?this.iamService.isUserAllowed$().pipe(ce(t=>(e.featureAllowed=t,e))):se(e)),he(e=>e.featureAllowed?this.authService.isPlanExpired$().pipe(ce(t=>(e.featureAllowed=!t,e))):se(e)),he(e=>e.featureAllowed?se(e).pipe(he(t=>this.docService.getDocumentPaths$().pipe(Le(r=>!!r),ce(r=>(this.documentPaths=r,t.documentPaths=r,t)))),dn(t=>{this.serverConnectionState$?.value===ol.PENDING_INIT&&t?.documentPaths?.liveState&&this.serverConnectionState$.next(ol.PENDING_DATA)}),he(t=>this.domService.onNetworkStatusChange$().pipe(Le(r=>r),ce(()=>t))),he(t=>this.getDataFromDocumentId().pipe(ce(r=>(t.liveStateData=r,I({},t))))),he(t=>this.getSingleEditorMode$().pipe(ce(()=>t))),he(t=>this.presenceService?this.presenceService.getPresenceUser().pipe(ce(()=>t)):se(t)),ce(t=>{if([ol.ONLINE,ol.OFFLINE].includes(this.serverConnectionState$?.value)||this.serverConnectionState$.next(ol.ONLINE),t.liveStateData)this.liveStateDataMap$.next(t.liveStateData);else{let r=this.liveStateDataMap$.value;r&&Object.keys(r).length>0&&this.liveStateDataMap$.next({})}return t}),he(t=>this.getSingleEditorMode()?this.getUserPresence$().pipe(ce(r=>{if(!t?.liveStateData?.default?.singleEditorMode){let a=this.singleEditorLiveStateData$.value&&typeof this.singleEditorLiveStateData$.value=="object"?JSON.parse(JSON.stringify(this.singleEditorLiveStateData$.value)):this.singleEditorLiveStateData$.value;this.analyticsService.trackEvent(Z.Events.LiveStateSync.SEM_SINGLE_EDITOR_LIVE_STATE_EMPTY_DATA_STATS,{previousSingleEditorModeData:a,currentSingleEditorModeData:t?.liveStateData?.default?.singleEditorMode,currentSingleEditorModeDataParentStats:{liveStateDataAvailable:!!t?.liveStateData,defaultAvailable:!!t?.liveStateData?.default,singleEditorModeAvailable:!!t?.liveStateData?.default?.singleEditorMode}})}this.updateSingleEditorLiveSyncData(t?.liveStateData?.default?.singleEditorMode||{},r)})):se(t))):se({})))}updateSingleEditorLiveSyncData(e,t){return Q(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: updateSingleEditorLiveSyncData","color: green;"),wi(e,{})){let a=yield this.fetchSingleEditorLiveStateDataFromDatabase();if(!wi(a,e)&&(this.analyticsService.trackEvent(Z.Events.LiveStateSync.SEM_SINGLE_EDITOR_LIVE_STATE_DATA_MISMATCH,{serverData:a,localData:e}),a&&typeof a=="object")){let s=yield this.liveStateUtilsService.resolveAndMergeSingleEditorLiveStateDataWithUser(JSON.parse(JSON.stringify(a)));e=JSON.parse(JSON.stringify(s))}}if(wi(e,{})&&!this.keydownSubscription&&this.detectKeydownOnInput(),t&&(this.compareServerAndExternalData(e,t),e&&typeof e=="object"&&(e=JSON.parse(JSON.stringify(e))),!e?.editor)){let a=this.authService.getUser();if(t?.sameUserPresentOnTab)e.editor=a,e.tabId=`sameUserPresentOnTab_${this.tabId}`;else if(t?.differentUserPresentOnTab){let s=t?.userIds?.[0],c;s&&(yield this.usersService.resolveUsers({userIds:[s],forceResolve:!0}),c=this.usersService.getUserById(s)),c?(e.editor=c,e.tabId=`differentUserPresentOnTab_${this.tabId}`):(e.editor={userId:`anonymous_${a?.userId}`,name:"Anonymous"},e.tabId=`differentUserPresentOnTab_${this.tabId}`)}}let r;if((!this.domService.getNetworkStatus()||this.presenceService?.getPresenceUserValue()?.onlineStatus===j.PRESENCE_STATUS_OFFLINE)&&(r=null),e&&!e?.editor&&this.isEditor$?.value!==r&&!t?.sameUserPresentOnTab&&!t?.differentUserPresentOnTab&&this.isEditor$.next(r),wi(this.singleEditorLiveStateData,e))return;{this.singleEditorLiveStateData=e,this.singleEditorLiveStateData$.next(e);let a;if(this.singleEditorLiveStateData&&typeof this.singleEditorLiveStateData=="object"&&(a=this.liveStateUtilsService.formatLiveStateSingleEditorModeData(JSON.parse(JSON.stringify(this.singleEditorLiveStateData)))),this.analyticsService.trackEvent(Z.Events.LiveStateSync.SEM_SINGLE_EDITOR_LIVE_STATE_DATA_STATS,{singleEditorLiveStateData:a}),this.singleEditorLiveStateData?.editor){let s=this.authService.getUser();this.singleEditorLiveStateData?.editor?.userId!==s?.userId?this.makeReader():this.makeEditor()}else this.isEditor$?.value!==r&&this.isEditor$.next(r),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||j.LIVE_STATE_REQUEST_EDITOR_ACCESS_WAIT_TIME)}}catch{}})}compareServerAndExternalData(e,t){try{if(t){let r=this.authService.getUser(),a={isEditor:e?.editor?.userId===r?.userId,isEditorOnCurrentTab:e?.editor?.userId===r?.userId&&e?.tabId===this.tabId},s={isEditor:t?.sameUserPresentOnTab&&!t?.differentUserPresentOnTab,isEditorOnCurrentTab:!1};wi(a,s)||this.analyticsService.trackEvent(Z.Events.LiveStateSync.SEM_SINGLE_EDITOR_DATA_MISMATCH_WITH_EXTERNAL,{serverUserEditorAccess:a,externalUserEditorAccess:s,serverData:e,externalData:t})}}catch(r){this.loggingService.catch("Error in LiveStateService compareServerAndExternalData: ",r)}}isFeatureAllowed(e){return this.configService.getConfig$().pipe(Le(t=>!!t),ce(t=>T(I({},e),{config:t})),he(t=>this.authService.getUser$().pipe(ce(r=>T(I({},t),{user:r})))),he(t=>ro(t.config,t.user,Re.LIVE_STATE_SYNC)?se(T(I({},t),{featureAllowed:!0})):(this.loggingService.warn("Live state sync feature is not allowed."),se(T(I({},t),{featureAllowed:!1})))),Et((t,r)=>t?.featureAllowed===r?.featureAllowed))}getDataFromDocumentId(e){return this.databaseService.getDb().pipe(Le(t=>!!t),he(t=>(this.db=t,this.configService?.getApiKey()&&this.documentPaths?.liveState?this.commonDbService.dbListener({feature:"allLiveStates",properties:{documentId:e??this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,skipFirestore:!0}}).pipe(Le(r=>!!r?.data),ce(r=>r?.data&&typeof r?.data=="object"?JSON.parse(JSON.stringify(r?.data)):r?.data),kn(r=>(this.loggingService.catch("Error in LiveStateService getDataFromDocumentId: ",r),se({})))):se({}))),Et(mn))}getLiveStateData$(e,t){try{return this.loggingService.log("%c[WB] Calling FUNCTION: getLiveStateData$","color: green;"),ei(this.afAuth).pipe(Le(r=>!!r),he(r=>this.isFeatureAllowed({firebaseUser:r,liveStateData:{}})),he(r=>r.featureAllowed?this.iamService.isUserAllowed$().pipe(ce(a=>(r.featureAllowed=a,r))):se(r)),he(r=>r.featureAllowed?this.authService.isPlanExpired$().pipe(ce(a=>(r.featureAllowed=!a,r))):se(r)),he(r=>r.featureAllowed?se(r).pipe(he(a=>this.docService.getDocumentPaths$().pipe(ce(s=>(this.documentPaths=s,a.documentPaths=s,a)))),he(a=>{let s=t?.listenToNewChangesOnly?1:0;return this.getLiveStateDataFromDatabase$(e).pipe(Hs(s))}),ce(a=>{if(a)if(e){let s=bt(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],u=p?.data;if(p?.isDataStringified&&typeof u=="string")try{u=JSON.parse(u)}catch{}s[p.liveStateDataId]=u}}),s}return a})):se(void 0).pipe(Le(Boolean))),Et((r,a)=>JSON.stringify(r||{})===JSON.stringify(a||{})),Le(r=>r!==void 0),ce(r=>r))}catch(r){return this.loggingService.catch("Error in LiveStateService getLiveStateData$: ",r),se(null)}}getLiveStateDataFromDatabase$(e){try{return this.databaseService.getDb().pipe(Le(t=>!!t),he(t=>{this.db=t;let r=e?bt(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}),kn(a=>(this.loggingService.catch("Error in LiveStateService getLiveStateDataFromDatabase$: ",a),se(null)))):se(void 0)}))}catch(t){return this.loggingService.catch("Error in LiveStateService getLiveStateDataFromDatabase$: ",t),se(void 0)}}setLiveStateData(e,t,r){return Q(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=bt(e+""),c=!1;try{if(r?.merge&&typeof t=="object"){let u=yield this.commonDbService.getData({feature:"liveStateCustom",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",id:s,skipFirestore:!0}});if(u?.isDataStringified){let C=JSON.parse(u?.data);typeof t=="object"&&(t=I(I({},C),t))}}}catch{}try{typeof t=="object"&&(t=JSON.stringify(t),c=!0)}catch{}let p={id:s,lastUpdated:this.timestamp,liveStateDataId:e,data:t,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]=t)}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(t=>{if(this.isElementInsideSingleEditorModeContainerElements(t)&&!this.isSingleEditorModeDisabledForElement(t)&&!Xi(t)){let r=t?.hasAttribute("disabled");t?.hasAttribute("contenteditable")&&(r=t?.getAttribute("contenteditable")==="false"),r||(t.setAttribute("disabled","true"),t.setAttribute(j.ATTRIBUTES.VELT_SYNC_ACCESS_AUTO,"true"),t?.hasAttribute("contenteditable")&&t.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(t=>{t?.hasAttribute(j.ATTRIBUTES.VELT_SYNC_ACCESS_AUTO)&&(t.removeAttribute("disabled"),t.removeAttribute(j.ATTRIBUTES.VELT_SYNC_ACCESS_AUTO),t?.getAttribute("contenteditable")&&t.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(`[${j.ATTRIBUTES.VELT_SYNC_ACCESS}]`)?.forEach(t=>{let r=this.domService.getXPath(t);r&&!this.preventEventsOnElementMap[r]&&(this.preventEventsOnElementMap[r]={element:t,events:{}},this.PREVENT_EVENTS.forEach(a=>{let s=pi(t,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 t=this.preventEventsOnElementMap[e];Object.keys(t.events||{}).forEach(r=>{t?.events[r]?.unsubscribe()})}),this.preventEventsOnElementMap={}}catch(e){this.loggingService.catch("Error in LiveStateService enableElementClicks: ",e)}}setUserAsEditor(e){return Q(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: setUserAsEditor","color: green;"),this.user&&this.documentPaths?.liveStateSingleEditorMode){if(this.analyticsService.trackEvent(Z.Events.LiveStateSync.SET_USER_AS_EDITOR_TRIGGERED,{editorUserId:this.user?.userSnippylyId,tabId:this.tabId}),!e?.skipEditorCheck){let r=yield this.fetchSingleEditorLiveStateDataFromDatabase();if(r?.editor){let a=this.authService.getUser(),s=null;a?.userId===r?.editor?.userId?r?.tabId===this.tabId?s={code:"same_user_editor_current_tab",message:"Same user is already editor in current tab.",source:"setUserAsEditor"}:s={code:"same_user_editor_different_tab",message:"Same user is already editor in different tab.",source:"setUserAsEditor"}:s={code:"another_user_editor",message:"Another user is already editor.",source:"setUserAsEditor"};let c;return r&&typeof r=="object"&&(c=this.liveStateUtilsService.formatLiveStateSingleEditorModeData(JSON.parse(JSON.stringify(r)))),this.analyticsService.trackEvent(Z.Events.LiveStateSync.SET_USER_AS_EDITOR_ERROR,{error:s,singleEditorLiveStateData:c}),{error:s}}}let t={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,rtdbTransaction:!0},data:JSON.parse(JSON.stringify(t))})}}catch(t){this.loggingService.catch("Error in LiveStateService setUserAsEditor: ",t)}})}fetchSingleEditorLiveStateDataFromDatabase(){return Q(this,null,function*(){try{return this.loggingService.log("%c[WB] Calling FUNCTION: fetchSingleEditorLiveStateDataFromDatabase","color: green;"),yield this.commonDbService.getData({feature:"liveStateSingleEditorMode",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",skipFirestore:!0}})}catch(e){return this.loggingService.catch("Error in LiveStateService fetchSingleEditorLiveStateDataFromDatabase: ",e),null}})}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(t){this.loggingService.catch("Error in LiveStateService setRequestAccessTimer: ",t)}}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 Ut(e=>{let t=null;try{if(this.user&&this.documentPaths?.liveStateSingleEditorMode){let r=this.getEditorAccessTimeout(),a=qi(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,rtdbTransaction:!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({skipEditorCheck:!0})},(r+3)*1e3),this.setEditorAccessTimerInterval(r+3)),t=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()=>{t&&t?.unsubscribe()}})}catch(e){return this.loggingService.catch("Error in LiveStateService requestEditorAccess: ",e),se(null)}}makeEditor(){try{this.loggingService.log("%c[WB] Calling FUNCTION: makeEditor","color: green;");let e=this.singleEditorLiveStateData?.tabId===this.tabId;this.analyticsService.trackEvent(Z.Events.LiveStateSync.SEM_MAKE_EDITOR_TRIGGERED,{editorUserId:this.singleEditorLiveStateData?.editor?.userId,tabId:this.tabId,editorTabId:this.singleEditorLiveStateData?.tabId,isEditor:!0,isEditorOnCurrentTab:e}),this.isEditor$.next({isEditor:!0,isEditorOnCurrentTab:e}),this.getSingleEditorModeConfig()?.customMode||(!this.getSingleEditorModeConfig()?.singleTabEditor||e?(this.enableInputElements(),this.enableElementEvents()):(this.disableInputElements(),this.disableElementEvents())),this.fetchSingleEditorLiveStateDataFromDatabase().then(t=>{this.analyticsService.trackEvent(Z.Events.LiveStateSync.SEM_SINGLE_EDITOR_LIVE_STATE_DATA_ON_MAKE_EDITOR,{editorUserId:this.singleEditorLiveStateData?.editor?.userId,tabId:this.tabId,editorTabId:this.singleEditorLiveStateData?.tabId,isEditor:!0,isEditorOnCurrentTab:e,singleEditorLiveStateDataOnServer:t})}).catch(t=>{})}catch(e){this.loggingService.catch("Error in LiveStateService makeEditor: ",e)}}makeReader(){try{this.loggingService.log("%c[WB] Calling FUNCTION: makeReader","color: green;"),this.analyticsService.trackEvent(Z.Events.LiveStateSync.SEM_MAKE_READER_TRIGGERED,{editorUserId:this.singleEditorLiveStateData?.editor?.userId,tabId:this.tabId,editorTabId:this.singleEditorLiveStateData?.tabId,isEditor:!1,isEditorOnCurrentTab:!1}),this.isEditor$.next({isEditor:!1,isEditorOnCurrentTab:!1}),this.getSingleEditorModeConfig()?.customMode||(this.disableInputElements(),this.disableElementEvents()),this.fetchSingleEditorLiveStateDataFromDatabase().then(e=>{this.analyticsService.trackEvent(Z.Events.LiveStateSync.SEM_SINGLE_EDITOR_LIVE_STATE_DATA_ON_MAKE_READER,{editorUserId:this.singleEditorLiveStateData?.editor?.userId,tabId:this.tabId,editorTabId:this.singleEditorLiveStateData?.tabId,isEditor:!1,isEditorOnCurrentTab:!1,singleEditorLiveStateDataOnServer:e})}).catch(e=>{})}catch(e){this.loggingService.catch("Error in makeReader: ",e)}}acceptEditorAccessRequest(){return Q(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,t=this.singleEditorLiveStateData?.requestEditorAccess?.tabId;if(e&&t){let r={editor:e,requestEditorAccess:null,tabId:t,editorAt:this.timestamp};this.commonDbService.updateData({feature:"liveStateSingleEditorMode",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",skipFirestore:!0,rtdbTransaction:!0},data:JSON.parse(JSON.stringify(r))}),this.analyticsService.trackEvent(Z.Events.LiveStateSync.ACCEPT_EDITOR_ACCESS_REQUEST_TRIGGERED,{editorUserId:e?.userSnippylyId,tabId:t})}}}catch(e){this.loggingService.catch("Error in acceptEditorAccessRequest: ",e)}})}rejectEditorAccessRequest(){return Q(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,rtdbTransaction:!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 Q(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,rtdbTransaction:!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,rtdbTransaction:!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 Q(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,editor:this.user,editorAt:this.timestamp};this.commonDbService.updateData({feature:"liveStateSingleEditorMode",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",skipFirestore:!0,rtdbTransaction:!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().pipe(Et(mn))}catch(e){return this.loggingService.catch("Error in LiveStateService isUserEditor$: ",e),se(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),Et())}catch(e){return this.loggingService.catch("Error in LiveStateService getEditor$: ",e),se(null)}}isEditorAccessRequested$(){try{return this.loggingService.log("%c[WB] Calling FUNCTION: isEditorAccessRequested$","color: green;"),this.isUserEditor$().pipe(he(e=>e?.isEditor?this.singleEditorLiveStateData$.pipe(ce(t=>t?.requestEditorAccess?{requestStatus:"requested",requestedBy:t?.requestEditorAccess?.user}:null)):se(null)),Et((e,t)=>JSON.stringify(e||{})===JSON.stringify(t||{})))}catch(e){return this.loggingService.catch("Error in LiveStateService isEditorAccessRequested$: ",e),se(null)}}removeEditorAccess(e){return Q(this,null,function*(){try{this.loggingService.log("%c[WB] Calling FUNCTION: removeEditorAccess","color: green;"),this.analyticsService.trackEvent(Z.Events.LiveStateSync.REMOVE_EDITOR_ACCESS,{removeEditorAccessMetadata:e?.metadata}),(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(t){this.loggingService.catch("Error in LiveStateService removeEditorAccess: ",t)}})}getSingleEditorLiveStateData$(){return this.singleEditorLiveStateData$.asObservable().pipe(Et(mn))}enableSingleEditorMode(e){try{if(this.singleEditorMode$.value===!0)return;this.singleEditorMode$.next(!0),e?this.singleEditorModeConfig$.next(e):this.singleEditorModeConfig$.next(new fk)}catch(t){this.loggingService.catch("Error in LiveStateService enableSingleEditorMode: ",t)}}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(t){this.loggingService.catch("Error in LiveStateService setEditorAccessTimeout: ",t)}}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(t){this.loggingService.catch("Error in LiveStateService setEditorAccessTimerCountdown interval: ",t),this.clearEditorAccessTimerInterval()}},1e3))}catch(t){this.loggingService.catch("Error in LiveStateService setEditorAccessTimerCountdown: ",t),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()}updateUserPresence(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: updateUserPresence","color: green;"),this.userPresence$.next(e)}catch(t){this.loggingService.catch("Error in LiveStateService updateUserPresence: ",t)}}getUserPresence$(){return this.userPresence$.asObservable().pipe(Et(mn))}getUserPresence(){return this.userPresence$.value}detectLiveSyncInputs(){try{document.querySelectorAll(`[${j.ATTRIBUTES.VELT_SYNC_STATE}]`)?.forEach(t=>{this.subscribeInputChanges(t)})}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 t=e.tagName,r=this.domService.getXPath(e),a=bt(r);if(this.inputChangeSubscriptionMap[a])this.loggingService.warn("subscription already exists",a,e);else{this.inputChangeSubscriptionMap[a]={id:a,element:e};let s;switch(t?.toLowerCase()){case"input":s=pi(e,"input").pipe(lr(300)).subscribe(p=>{let u={value:p?.target?.value,tagName:p?.target?.tagName,type:p?.target?.type};this.setLiveStateSyncInputData(p?.target,u)});break;case"textarea":s=pi(e,"input").pipe(lr(300)).subscribe(p=>{let u={value:p?.target?.value,tagName:p?.target?.tagName};this.setLiveStateSyncInputData(p?.target,u)});break;default:e.getAttribute("contenteditable")&&(s=pi(e,"input").pipe(lr(300)).subscribe(p=>{let u={innerText:p?.target?.innerText,innerHTML:this.domService.sanitizeHtml(p?.target?.innerHTML),tagName:p?.target?.tagName,isContentEditable:!0};this.setLiveStateSyncInputData(p?.target,u)}));break}s&&(this.inputChangeSubscriptionMap[a]?.subscriptions||(this.inputChangeSubscriptionMap[a]={subscriptions:[]}),this.inputChangeSubscriptionMap[a].subscriptions?.push(s))}}}catch(t){this.loggingService.catch("Error in LiveStateService subscribeInputChanges: ",t)}}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,t){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: setLiveStateSyncInputData","color: green;"),this.user&&this.documentPaths?.liveState){let r=this.domService.getXPath(e),a=bt(r),s={id:a,lastUpdated:this.timestamp,liveStateDataId:r,data:t,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(t=>{let r=e[t],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&&!yae()&&!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(t){this.loggingService.catch("Error in LiveStateService updateLiveStateSyncInputDataLocally: ",t)}}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 t=this.singleEditorModeContainerIds$.value,r=document.querySelectorAll(`[${j.ATTRIBUTES.VELT_SINGLE_EDITOR_MODE_CONTAINER}]`);if(!t?.length&&!r?.length)return!0;if(t?.length)for(let a=0;a<t.length;a++){let s=document.getElementById(t[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(t){return this.loggingService.catch("Error in LiveStateService isElementInsideSingleEditorModeContainerElements: ",t),!1}}isSingleEditorModeDisabledForElement(e){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: isSingleEditorModeDisabledForElement","color: green;"),e){if(e.getAttribute(j.ATTRIBUTES.VELT_SYNC_ACCESS_DISABLED))return!0;{let r=e?.parentElement;if(r)return this.isSingleEditorModeDisabledForElement(r)}}return!1}catch(t){return this.loggingService.catch("Error in LiveStateService isSingleEditorModeDisabledForElement: ",t),!1}}updateOnDatabaseDisconnect(){return this.loggingService.log("%c[WB] Calling FUNCTION: updateOnDatabaseDisconnect","color: green;"),this.isUserEditor$().pipe(dn(e=>{try{if(this.documentPaths?.liveStateSingleEditorMode){let t=qi(this.db,`${this.documentPaths?.liveStateSingleEditorMode}`);e?.isEditor&&(!this.getSingleEditorModeConfig()?.singleTabEditor||e?.isEditorOnCurrentTab)?bd(t).remove():bd(t).cancel()}}catch(t){this.loggingService.catch("Error in LiveStateService updateOnDatabaseDisconnect tap: ",t)}}))}updateServerStateOnDatabaseDisconnect(){return this.loggingService.log("%c[WB] Calling FUNCTION: updateServerStateOnDatabaseDisconnect","color: green;"),ei(this.afAuth).pipe(Le(e=>!!e),he(e=>this.docService.getDocumentPaths$().pipe(ce(t=>e))),dn(e=>Q(this,null,function*(){try{if(this.docService.getDocumentPaths()?.liveState&&e){let r=qi(this.db,".info/connected"),a=!0;Np(r,s=>{let c=s.val();if(a&&c===!1){a=!1;return}a=!1,c===!1?this.serverConnectionState$.next(ol.OFFLINE):this.serverConnectionState$.value===ol.OFFLINE&&this.serverConnectionState$.next(ol.ONLINE)})}}catch(t){this.loggingService.catch("Error in updateServerStateOnDatabaseDisconnect:",t)}})))}getSemStats(){try{let e=!!this.authService?.getUser(),t=!!this.docService?.getDocumentPaths(),r=this.singleEditorMode$.value,a=!!this.singleEditorModeConfig$.value,s=this.isUserEditor(),c;this.singleEditorLiveStateData$.value&&typeof this.singleEditorLiveStateData$.value=="object"&&(c=this.liveStateUtilsService?.formatLiveStateSingleEditorModeData(JSON.parse(JSON.stringify(this.singleEditorLiveStateData$.value))));let p=this.getUserPresence();return{userAvailable:e,documentPathsAvailable:t,singleEditorModeEnabled:r,singleEditorModeConfig:a,isEditor:s,singleEditorLiveStateData:c,userPresence:p}}catch(e){this.loggingService.catch("Error in LiveStateService getSemStats: ",e)}}get timestamp(){return this.commonDbService.getServerTimestamp()}};o.\u0275fac=function(t){return new(t||o)(ee(Di),ee(et),ee(Ve),ee(Ft),ee(Dn),ee(at),ee(Be),ee(vn),ee(y),ee(pn),ee(Qk),ee(kk),ee(Vn))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var jl=(()=>{let o=class o{constructor(e,t,r,a,s,c,p,u,C,E,D,L,z){this.analyticsService=e,this.docService=t,this.domService=r,this.authService=a,this.afAuth=s,this.iamService=c,this.databaseService=p,this.configService=u,this.avatarService=C,this.loggingService=E,this.flockService=D,this.liveStateService=L,this.commonDbService=z,this.db=ts(),this.presenceUser$=new ve(new Ck),this.documentPaths=null,this.inactivityTime=5*60*1e3,this.offlineInactivityTime=10*60*1e3,this.presenceUsers$=new ve([]),this.presenceUsersSubscription=null,this.includeSelf$=new ve(!0),this.userIdleStateDetectionSubscription=null,this.userOfflineStateDetectionSubscription=null;try{this.loggingService.log("%c[WB] Creating CLASS: PresenceService","color: blue;"),this.liveStateService.setPresenceService(this),this.databaseService.getDb().pipe(Le(W=>!!W),st(1)).subscribe(W=>{W&&(this.db=W,this.getUser(),this.getDocumentPaths(),this.getLocation(),this.updateOnUserDbConnectionStateChange().subscribe(()=>{},J=>{this.loggingService.catch("Error in PresenceService constructor updateOnUserDbConnectionStateChange: ",J)}),this.updateOnDatabaseDisconnect().subscribe(()=>{},J=>{this.loggingService.catch("Error in PresenceService constructor updateOnDatabaseDisconnect: ",J)}),this.updateOnDocumentFocusChange(),this.updateOnAllowedFeatureListChange())},W=>{this.loggingService.catch("Error in PresenceService constructor: ",W)}),this.authService.addPreSignOutFuction("presence-signout",this.signOutUser.bind(this)),this.presenceUsers$.pipe(Bi()).subscribe(([W,J])=>{try{J?.length>=0&&this.analyticsService.updateDefaultProperties({presenceUsersCount:J?.length}),sessionStorage.getItem(j.SESSION_STORAGE.VELT_PRESENCE_MULTIPLE_USERS_DETECTED)||J?.length>1&&W.length!==J.length&&(this.analyticsService.trackEvent(Z.Events.Presence.PRESENCE_MULTIPLE_USERS_DETECTED,{totalUsers:J.length,presenceSnippylyUserIds:J.map(ye=>ye.userSnippylyId),presenceClientUserIds:J.map(ye=>ye.userId)}),sessionStorage.setItem(j.SESSION_STORAGE.VELT_PRESENCE_MULTIPLE_USERS_DETECTED,"true"));let ue=this.authService.getUser();ue&&!W?.some(ye=>ye.userId===ue.userId)&&J?.some(ye=>ye.userId===ue.userId)&&this.presenceActionsService?.onMultipleUsersOnline({users:J})}catch(ue){this.loggingService.catch("Error in presenceUsers$ pairwise subscription: ",ue)}}),this.authService.getUser$().pipe(Le(W=>!!W),st(1)).subscribe(W=>{W?(this.detectUserIdleState(),this.detectUserOfflineState()):(this.unsubscribeUserIdleStateDetectionSubscription(),this.unsubscribeUserOfflineStateDetectionSubscription())}),this.presenceUser$.subscribe(W=>{try{W?.onlineStatus&&this.presenceActionsService?.onUserStateChange({user:JSON.parse(JSON.stringify(W)),state:W?.onlineStatus})}catch(J){this.loggingService.catch("Error in presenceUser$ subscription: ",J)}},W=>{this.loggingService.catch("Error in presenceUser$ subscribe: ",W)}),this.domService.onNetworkStatusChange$().subscribe(W=>{try{!W&&this.presenceUser$?.value?.onlineStatus&&this.presenceActionsService?.onUserStateChange({user:T(I({},JSON.parse(JSON.stringify(this.presenceUser$.value))),{onlineStatus:j.PRESENCE_STATUS_OFFLINE}),state:j.PRESENCE_STATUS_OFFLINE})}catch(J){this.loggingService.catch("Error in domService.onNetworkStatusChange$ subscription: ",J)}},W=>{this.loggingService.catch("Error in domService.onNetworkStatusChange$ subscribe: ",W)})}catch(W){this.loggingService.catch("Error in PresenceService constructor: ",W)}}setPresenceActionsService(e){try{this.presenceActionsService=e}catch(t){this.loggingService.catch("Error in setPresenceActionsService: ",t)}}detectUserIdleState(){try{this.unsubscribeUserIdleStateDetectionSubscription();let e=!1;this.userIdleStateDetectionSubscription=this.domService.onWindowPointerMove$().pipe(Kh(2e3),dn(()=>{this.presenceUser$.value&&e&&(this.setCurrentPresenceUserStatus(j.PRESENCE_STATUS_ONLINE),e=!1)}),lr(this.inactivityTime),dn(()=>{this.setCurrentPresenceUserStatus(j.PRESENCE_STATUS_AWAY,{isUserIdle:!0}),e=!0})).subscribe()}catch(e){this.loggingService.catch("Error in detectUserIdleState: ",e)}}detectUserOfflineState(){try{this.unsubscribeUserOfflineStateDetectionSubscription();let e=!1;this.userOfflineStateDetectionSubscription=this.domService.onWindowPointerMove$().pipe(Kh(2e3),lr(this.offlineInactivityTime),dn(()=>{this.setCurrentPresenceUserStatus(j.PRESENCE_STATUS_OFFLINE,{isUserIdle:!0}),e=!0})).subscribe()}catch(e){this.loggingService.catch("Error in detectUserOfflineState: ",e)}}unsubscribeUserIdleStateDetectionSubscription(){try{this.userIdleStateDetectionSubscription&&(this.userIdleStateDetectionSubscription.unsubscribe(),this.userIdleStateDetectionSubscription=null)}catch(e){this.loggingService.catch("Error in unsubscribeUserIdleStateDetectionSubscription: ",e)}}unsubscribeUserOfflineStateDetectionSubscription(){try{this.userOfflineStateDetectionSubscription&&(this.userOfflineStateDetectionSubscription.unsubscribe(),this.userOfflineStateDetectionSubscription=null)}catch(e){this.loggingService.catch("Error in unsubscribeUserOfflineStateDetectionSubscription: ",e)}}getUser(){this.loggingService.log("%c[WB] Calling FUNCTION: getUser","color: green;"),this.authService.getUser$().pipe(Le(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(dn(e=>{this.documentPaths=e}),Bi(),dn(([e,t])=>{e&&this.updateUserStatusOnDocumentChange(j.PRESENCE_STATUS_OFFLINE,e),t&&this.updateUserStatusOnDocumentChange(j.PRESENCE_STATUS_ONLINE,t)})).subscribe(()=>{},e=>{this.loggingService.catch("Error in getDocumentPaths: ",e)})}getLocation(){this.docService.getLocation$().pipe(dn(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()}getPresenceUserValue(){return this.presenceUser$.value}getOnlineUsersOnCurrentDocument(e){return this.loggingService.log("%c[WB] Calling FUNCTION: getOnlineUsersOnCurrentDocument","color: green;"),ei(this.afAuth).pipe(Le(t=>!!t),he(t=>this.isFeatureAllowed({firebaseUser:t,users:[],filteredUsers:[]})),he(t=>t.featureAllowed?this.iamService.isUserAllowed$().pipe(ce(r=>(t.featureAllowed=r,t))):se(t)),he(t=>t.featureAllowed?this.authService.isPlanExpired$().pipe(ce(r=>(t.featureAllowed=!r,t))):se(t)),he(t=>t.featureAllowed?se(t).pipe(he(r=>this.docService.getDocumentPaths$().pipe(ce(a=>(this.documentPaths=a,r.documentPaths=a,r)))),he(r=>this.getDataFromDocumentId(e).pipe(ce(a=>(r.users=a||[],I({},r))))),ce(r=>(e?e?.statuses?.length?r.filteredUsers=r?.users?.filter(a=>e?.statuses?.includes(a?.onlineStatus)):r.filteredUsers=r?.users?.slice():r.filteredUsers=this.filterOnlineUsers(r.users,r.firebaseUser),r)),he(r=>this.getIncludeSelf$().pipe(ce(a=>(a||(r.filteredUsers=r?.filteredUsers?.filter(s=>s?.userSnippylyId!==r.user?.userSnippylyId)),r)))),he(r=>r?.filteredUsers?se(r?.filteredUsers||[]):se([]))):se([])),Et(mn))}isFeatureAllowed(e){return this.configService.getConfig$().pipe(Le(t=>!!t),ce(t=>T(I({},e),{config:t})),he(t=>this.authService.getUser$().pipe(ce(r=>T(I({},t),{user:r})))),he(t=>ro(t.config,t.user,Re.PRESENCE)?se(T(I({},t),{featureAllowed:!0})):(this.loggingService.warn("Presence feature is not allowed."),se(T(I({},t),{featureAllowed:!1})))),Et((t,r)=>t?.featureAllowed===r?.featureAllowed))}getDataFromDocumentId(e){return this.databaseService.getDb().pipe(Le(t=>!!t),he(t=>{if(this.db=t,this.loggingService.log(this.db),this.configService?.getApiKey()&&this.documentPaths?.presence){let r=new Date(Date.now()-864e5).getTime();return this.commonDbService.dbListener({feature:"allPresence",properties:{documentId:e?.documentId??this.documentPaths?.documentId,organizationId:e?.organizationId??this.documentPaths?.organizationId,skipFirestore:!0,useQuery:!0,rtdbQuery:[Lu("timestamp"),Vu(r)]}}).pipe(kn(a=>(this.loggingService.catch("Error in PresenceService getDataFromDocumentId: ",a),se(null))),ce(a=>a?.data),ce(a=>{let s=[];return a&&(s=Object.values(a).filter(c=>typeof c=="object")),s}))}else return se([])}))}filterOnlineUsers(e,t){this.loggingService.log("%c[WB] Calling FUNCTION: filterOnlineUsers","color: green;");try{let a=e.slice().filter(s=>{let c=zp(s.timestamp);return s.userSnippylyId&&(s.onlineStatus===j.PRESENCE_STATUS_ONLINE||s.onlineStatus===j.PRESENCE_STATUS_AWAY)&&c<this.offlineInactivityTime});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 t=this.presenceUsers$.value.find(r=>r.userId===e);if(t)return t}return null}catch(t){return this.loggingService.catch("Error in getNameFromSnippylyId:",t),null}}getAnonymousAvatarImage(){return this.loggingService.log("%c[WB] Calling FUNCTION: getAnonymousAvatarImage","color: green;"),this.avatarService.generateUserImage()}updateCurrentPresenceUser(e){return Q(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 oo,e?.onlineStatus===j.PRESENCE_STATUS_ONLINE&&(e.isTabAway=!1,e.isUserIdle=!1);let t=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({},t),{timestamp:this.timestamp})))})}this.presenceUser$.next(e)}}catch(t){this.loggingService.catch("Error in updateCurrentPresenceUser:",t)}})}setCurrentPresenceUserStatus(e,t){return Q(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: setCurrentPresenceUserStatus","color: green;");try{this.loggingService.log(e);let r=this.presenceUser$.value;if(r.onlineStatus!==e){this.presenceUsersSubscription&&this.presenceUsersSubscription?.unsubscribe();let a=r.onlineStatus,s=e;this.presenceUsersSubscription=this.getPresenceUsers$().pipe(Le(c=>!!c?.length),st(1)).subscribe(c=>{c?.length>1&&this.analyticsService.trackEvent(Z.Events.Presence.PRESENCE_USER_STATUS_CHANGED,{oldStatus:a,newStatus:s,totalUsers:c?.length,presenceSnippylyUserIds:c?.map(p=>p.userSnippylyId),presenceClientUserIds:c?.map(p=>p.userId)})})}r.onlineStatus=e,t&&(r.isTabAway=t?.isTabAway,r.isUserIdle=t?.isUserIdle),e===j.PRESENCE_STATUS_ONLINE&&(r.isTabAway=!1,r.isUserIdle=!1),e===j.PRESENCE_STATUS_OFFLINE&&this.flockService.isInSession()&&this.flockService.removeCurrentUserFromSession(),e===j.PRESENCE_STATUS_OFFLINE&&this.liveStateService.isUserEditor()?.isEditor&&(!this.liveStateService.getSingleEditorModeConfig()?.singleTabEditor||this.liveStateService.isUserEditor()?.isEditorOnCurrentTab)&&this.liveStateService.removeEditorAccess({metadata:{from:"setCurrentPresenceUserStatus-presenceService",reason:"User went offline"}}),this.updateCurrentPresenceUser(r)}catch(r){this.loggingService.catch("Error in setCurrentPresenceUserStatus:",r)}})}updateUserStatusOnDocumentChange(e,t){return Q(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: updateUserStatusOnDocumentChange","color: green;");try{let r=this.presenceUser$.value;if(r.onlineStatus=e,t?.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:t?.documentId,organizationId:t?.organizationId,userId:r.userSnippylyId,skipFirestore:!0},data:JSON.parse(JSON.stringify(a))})}}catch(r){this.loggingService.catch("Error in updateUserStatusOnDocumentChange:",r)}})}updateUserOnLocationChange(e){return Q(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: updateUserOnLocationChange","color: green;");try{let t=this.presenceUser$.value;if(t.location=e?e.location:null,t.locationId=e?e?.locationId:null,this.documentPaths?.presence&&t&&t.userId&&!t.isAnonymous&&this.authService.isFeatureAllowed(Re.PRESENCE)){let r=JSON.parse(JSON.stringify(t));this.commonDbService.updateData({feature:"presence",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,userId:t.userSnippylyId,skipFirestore:!0},data:JSON.parse(JSON.stringify(r))})}}catch(t){this.loggingService.catch("Error in updateUserOnLocationChange:",t)}})}updateOnUserDbConnectionStateChange(){this.loggingService.log("%c[WB] Calling FUNCTION: updateOnUserDbConnectionStateChange","color: green;");let e=qi(this.db,".info/connected"),t=U6(e).pipe(ce(r=>r?j.PRESENCE_STATUS_ONLINE:j.PRESENCE_STATUS_OFFLINE));return ei(this.afAuth).pipe(Hs(1),he(r=>r?t:se(j.PRESENCE_STATUS_OFFLINE)),dn(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(j.PRESENCE_STATUS_AWAY,{isTabAway:!0}),this.flockService.getFlockMode()&&this.flockService.setTabFocused(!1)):(this.setCurrentPresenceUserStatus(j.PRESENCE_STATUS_ONLINE),this.flockService.getFlockMode()&&this.flockService.setTabFocused(!0)))}),window&&(window.addEventListener("focus",()=>{this.authService.getUser()&&(this.setCurrentPresenceUserStatus(j.PRESENCE_STATUS_ONLINE),this.flockService.getFlockMode()&&this.flockService.setWindowFocused(!0))}),window.addEventListener("blur",()=>{this.authService.getUser()&&(document.visibilityState!=="hidden"&&this.setCurrentPresenceUserStatus(j.PRESENCE_STATUS_AWAY,{isTabAway:!0}),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 t=this.presenceUser$.value,r=!1;if(e.featureAllowList.includes(Re.PRESENCE)?t?.onlineStatus!==j.PRESENCE_STATUS_ONLINE&&(t.onlineStatus=j.PRESENCE_STATUS_ONLINE,r=!0):t?.onlineStatus!==j.PRESENCE_STATUS_OFFLINE&&(t.onlineStatus=j.PRESENCE_STATUS_OFFLINE,r=!0),r&&this.authService.getUser()&&this.documentPaths?.presence&&t&&t.userId&&!t.isAnonymous){let a=JSON.parse(JSON.stringify(t));this.commonDbService.updateData({feature:"presence",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,userId:t.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;"),ei(this.afAuth).pipe(Le(e=>!!e),he(e=>this.docService.getDocumentPaths$().pipe(ce(t=>e))),dn(e=>Q(this,null,function*(){try{if(this.documentPaths?.presence&&e){let t=yield Mm(e,!0).catch(a=>null);if(!t)return;let{user:r}=t.claims;if(!r?.isAnonymous&&this.documentPaths?.presence){this.flockService.isInSession()&&this.flockService.removeCurrentUserFromSession();let a=`${this.documentPaths.presence}/${e.uid}`;this.commonDbService.setupOnDisconnect(a,{onlineStatus:j.PRESENCE_STATUS_OFFLINE,timestamp:this.timestamp}).catch(s=>{this.loggingService.catch("Error in updateOnDatabaseDisconnect:",s)})}}}catch(t){this.loggingService.catch("Error in updateOnDatabaseDisconnect:",t)}})))}setPresenceUser(e){this.loggingService.log("%c[WB] Calling FUNCTION: setPresenceUser","color: green;");try{let t=this.presenceUser$.value;t.userId=e?.userId,t.name=e?.name,t.email=e?.email,t.photoUrl=e?.photoUrl,t.userSnippylyId=e?.userSnippylyId,t.color=e?.color,t.textColor=e?.textColor,t.initial=e?.initial,t.timestamp=this.timestamp,t.type=e?.type,t.isReadOnly=e?.isReadOnly,t.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&&(t.name=`${a} ${c?c+".":""}`)}this.updateCurrentPresenceUser(t)}catch(t){this.loggingService.catch("Error in setPresenceUser:",t)}}signOutUser(e){return new Promise((t,r)=>{try{this.documentPaths?.presence&&e?this.commonDbService.getData({feature:"presence",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,userId:e.uid,skipFirestore:!0}}).then(a=>{a&&(this.flockService.isInSession()&&this.flockService.removeCurrentUserFromSession(),this.liveStateService.isUserEditor()?.isEditor&&(!this.liveStateService.getSingleEditorModeConfig()?.singleTabEditor||this.liveStateService.isUserEditor()?.isEditorOnCurrentTab)&&this.liveStateService.removeEditorAccess({metadata:{from:"signOutUser-presenceService",reason:"User signed out"}}),this.commonDbService.updateData({feature:"presence",errorCallback:s=>{r(s)},callback:()=>{t(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:j.PRESENCE_STATUS_OFFLINE})))})),t(null)}).catch(a=>{this.loggingService.catch("Error in signOutUser subscription: ",a),r(a)}):t(null)}catch(a){this.loggingService.catch("Error in signOutUser:",a),r(a)}})}setInactivityTime(e){try{this.inactivityTime=e,this.analyticsService.trackEvent(Z.Events.Presence.PRESENCE_SET_CUSTOM_INACTIVITY_TIMER,{inactivityTime:this.inactivityTime}),this.detectUserIdleState()}catch(t){this.loggingService.catch("Error in setInactivityTime: ",t)}}getInactivityTime(){return this.inactivityTime}setOfflineInactivityTime(e){try{e>=this.inactivityTime?(this.offlineInactivityTime=e,this.analyticsService.trackEvent(Z.Events.Presence.PRESENCE_SET_CUSTOM_OFFLINE_INACTIVITY_TIMER,{offlineInactivityTime:this.offlineInactivityTime}),this.detectUserOfflineState()):this.loggingService.catch("Error in setOfflineInactivityTime: ","offline-inactivity-time value is less than inactivity-time.")}catch(t){this.loggingService.catch("Error in setOfflineInactivityTime: ",t)}}getOfflineInactivityTime(){return this.offlineInactivityTime}getPresenceUsers$(){return this.presenceUsers$.asObservable()}getPresenceUsers(){return this.presenceUsers$.value}get timestamp(){return this.commonDbService.getServerTimestamp()}};o.\u0275fac=function(t){return new(t||o)(ee(et),ee(at),ee(Be),ee(Ve),ee(Di),ee(vn),ee(Dn),ee(Ft),ee(Bd),ee(y),ee(jc),ee(Li),ee(pn))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var E0=(()=>{let o=class o{constructor(e,t,r,a,s,c,p,u,C,E,D){this.analyticsService=e,this.configService=t,this.presenceService=r,this.docService=a,this.afAuth=s,this.iamService=c,this.domService=p,this.databaseService=u,this.authService=C,this.loggingService=E,this.commonDbService=D,this.cursorUser$=new ve(new m0),this.documentPaths=null,this.inactivityTime=2*60*1e3,this.allowedElementIds$=new ve([]),this.cursorTagAvailable$=new ve(!1),this.cursorTagAvailable=!1,this.cursorUsers$=new ve([]),this.loggingService.log("%c[WB] Creating CLASS: CursorService","color: blue;");try{this.checkCursorTagAvailable(),this.databaseService.getDb().pipe(Le(L=>!!L),he(L=>this.cursorTagAvailable$.pipe(Le(z=>!!z),st(1),ce(()=>L))),st(1)).subscribe(L=>{L&&this.cursorTagAvailable&&(this.getPresenceUser(),this.getDocumentPaths(),this.getLocation(),this.updateOnDatabaseDisconnect().subscribe(()=>{},z=>{this.loggingService.catch("Error in CursorService constructor updateOnDatabaseDisconnect: ",z)}),this.addMouseMoveListener(),this.addScreenSizeChangeListener(),this.updateOnAllowedFeatureListChange())},L=>{this.loggingService.catch("Error in CursorService constructor getDb: ",L)}),this.cursorUsers$.pipe(Bi()).subscribe(([L,z])=>{sessionStorage.getItem(j.SESSION_STORAGE.VELT_CURSOR_MULTIPLE_USERS_DETECTED)||z?.length>1&&L.length!==z.length&&(this.analyticsService.trackEvent(Z.Events.Cursor.CURSOR_MULTIPLE_USERS_DETECTED,{totalUsers:z.length,cursorSnippylyUserIds:z.map(W=>W.userSnippylyId),cursorClientUserIds:z.map(W=>W.userId)}),sessionStorage.setItem(j.SESSION_STORAGE.VELT_CURSOR_MULTIPLE_USERS_DETECTED,"true"))}),this.authService.addPreSignOutFuction("cursor-signout",this.signOutUser.bind(this))}catch(L){this.loggingService.catch("Error in CursorService constructor: ",L)}}checkCursorTagAvailable(){this.loggingService.log("%c[WB] Calling FUNCTION: checkCursorTagAvailable","color: green;");try{this.cursorTagAvailable=!!document.querySelector(j.TAGS.VELT_CURSOR)||!!document.querySelector(j.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(Le(e=>!!e),he(e=>this.domService.getCurrentWindowSize$("CursorService addScreenSizeChangeListener").pipe(Le(t=>!!t)))).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(Kh(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(dn(e=>{this.documentPaths=e}),Bi(),dn(([e,t])=>{e&&this.updateUserStatusOnDocumentChange(j.PRESENCE_STATUS_OFFLINE,e),t&&this.updateUserStatusOnDocumentChange(j.PRESENCE_STATUS_ONLINE,t)})).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(dn(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(Le(e=>!!e),kn(e=>se(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;"),ei(this.afAuth).pipe(Le(e=>!!e),he(e=>this.isFeatureAllowed({firebaseUser:e,users:[],filteredUsers:[]})),he(e=>e.featureAllowed?this.iamService.isUserAllowed$().pipe(ce(t=>(e.featureAllowed=t,e))):se(e)),he(e=>e.featureAllowed?this.authService.isPlanExpired$().pipe(ce(t=>(e.featureAllowed=!t,e))):se(e)),he(e=>!e.featureAllowed||e?.user?.isAnonymous?se([]):se(e).pipe(he(t=>this.docService.getDocumentPaths$().pipe(ce(r=>(this.documentPaths=r,t.documentPaths=r,t)))),he(t=>this.getDataFromDocumentId().pipe(ce(r=>(t.users=r||[],I({},t))))),ce(t=>(t.filteredUsers=this.filterOnlineUsers(t.users,t.firebaseUser),t)),he(t=>t?.filteredUsers?.length?this.domService.getCurrentWindowSize$("CursorService getLiveCursorsOnCurrentDocument").pipe(ce(()=>t)):se(t)),ce(t=>(t?.filteredUsers?.forEach(r=>{this.calculateCursorUserPosition(r)}),t)),he(t=>t?.filteredUsers?se(t?.filteredUsers||[]):se([])))))}isFeatureAllowed(e){return this.configService.getConfig$().pipe(Le(t=>!!t),ce(t=>T(I({},e),{config:t})),he(t=>this.authService.getUser$().pipe(ce(r=>T(I({},t),{user:r})))),he(t=>ro(t.config,t.user,Re.CURSOR)?se(T(I({},t),{featureAllowed:!0})):(this.loggingService.warn("Cursor feature is not allowed."),se(T(I({},t),{featureAllowed:!1})))),Et((t,r)=>t?.featureAllowed===r?.featureAllowed))}getDataFromDocumentId(e){return this.databaseService.getDb().pipe(Le(t=>!!t),he(t=>{if(this.configService?.getApiKey()&&this.documentPaths?.cursor){let r=new Date(Date.now()-864e5).getTime();return this.commonDbService.dbListener({feature:"allCursors",properties:{documentId:e??this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,skipFirestore:!0,useQuery:!0,rtdbQuery:[Lu("timestamp"),Vu(r)]}}).pipe(kn(a=>(this.loggingService.catch("Error in CursorService getDataFromDocumentId: ",a),se(null))),ce(a=>a?.data),ce(a=>{let s=[];return a&&(s=Object.values(a).filter(c=>typeof c=="object")),s}))}else return se([])}))}calculateCursorUserPosition(e){try{if(e?.targetElement){let t=this.domService.getXPath(e.targetElement?.xpath);if(t){let r=t.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(t){this.loggingService.catch("Error in calculateCursorUserPosition:",t)}}filterOnlineUsers(e,t){try{let a=e.slice().filter(c=>{let p=zp(c.timestamp);return c.userSnippylyId&&c.onlineStatus===j.PRESENCE_STATUS_ONLINE&&p<this.inactivityTime});this.cursorUsers$.next(a),a=a.filter(c=>c?.userSnippylyId!==t?.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 t=this.cursorUser$.value;t.userId=e?.userId,t.name=e?.name,t.email=e?.email,t.photoUrl=e?.photoUrl,t.comment="",this.authService.isFeatureAllowed(Re.PRESENCE)&&(t.onlineStatus=e?.onlineStatus),t.userSnippylyId=e?.userSnippylyId,t.color=e?.color,t.textColor=e?.textColor,t.initial=e?.initial,t.timestamp=this.timestamp,t.type=e?.type,t.isReadOnly=e?.isReadOnly,t.isAnonymous=e?.isAnonymous;let r=this.domService.getCurrentWindowSizeValue();t.screenWidth=r?.screenWidth,t.screenHeight=r?.screenHeight,t.screenScrollHeight=r?.screenScrollHeight,this.updateCurrentCursorUser(t)}catch(t){this.loggingService.catch("Error in setCursorUser:",t)}}setCurrentCursorUserPosition(e,t,r){try{let a=this.cursorUser$.value;a?.onlineStatus===j.PRESENCE_STATUS_ONLINE&&(a.positionX=e,a.positionY=t,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 t=this.cursorUser$.value;t?.onlineStatus===j.PRESENCE_STATUS_ONLINE&&(t.screenWidth=e.screenWidth,t.screenHeight=e.screenHeight,t.screenScrollHeight=e.screenScrollHeight,this.updateCurrentCursorUser(t))}}catch(t){this.loggingService.catch("Error in setCurrentCursorUserScreenSize:",t)}}updateCurrentCursorUser(e){return Q(this,null,function*(){try{if(this.documentPaths&&e&&e.userId&&this.authService.isFeatureAllowed(Re.CURSOR)){if(!e.isAnonymous){e.pageInfo=new oo;let t=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({},t),{timestamp:this.timestamp})))})}this.cursorUser$.next(e)}}catch(t){this.loggingService.catch("Error in updateCurrentCursorUser:",t)}})}updateUserStatusOnDocumentChange(e,t){return Q(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: updateUserStatusOnDocumentChange","color: green;");try{let r=this.cursorUser$.value;if(r.onlineStatus=e,t&&r&&r.userId&&!r.isAnonymous&&this.authService.isFeatureAllowed(Re.CURSOR)){let a=JSON.parse(JSON.stringify(r));this.commonDbService.updateData({feature:"cursor",properties:{documentId:t?.documentId??"",organizationId:t?.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 Q(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: updateUserOnLocationChange","color: green;");try{let t=this.cursorUser$.value;if(t.location=e?e.location:null,t.locationId=e?e?.locationId:null,this.documentPaths&&t&&t.userId&&!t.isAnonymous&&this.authService.isFeatureAllowed(Re.CURSOR)){let r=JSON.parse(JSON.stringify(t));this.commonDbService.updateData({feature:"cursor",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",id:t.userSnippylyId,skipFirestore:!0},data:JSON.parse(JSON.stringify(T(I({},r),{timestamp:this.timestamp})))})}}catch(t){this.loggingService.catch("Error in updateUserOnLocationChange:",t)}})}updateOnAllowedFeatureListChange(){try{this.configService.getConfig$().subscribe(e=>{if(e&&e.featureAllowList?.length){let t=this.cursorUser$.value,r=!1;if(e.featureAllowList.includes(Re.CURSOR)?t?.onlineStatus!==j.PRESENCE_STATUS_ONLINE&&(t.onlineStatus=j.PRESENCE_STATUS_ONLINE,r=!0):t?.onlineStatus!==j.PRESENCE_STATUS_OFFLINE&&(t.onlineStatus=j.PRESENCE_STATUS_OFFLINE,r=!0),r&&this.documentPaths&&t&&t.userId&&!t.isAnonymous){let a=JSON.parse(JSON.stringify(t));this.commonDbService.updateData({feature:"cursor",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",id:t.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;"),ei(this.afAuth).pipe(Le(e=>!!e),he(e=>this.docService.getDocumentPaths$().pipe(ce(t=>e))),dn(e=>Q(this,null,function*(){try{if(this.documentPaths&&e){let t=yield Mm(e,!0).catch(a=>null);if(!t)return;let{user:r}=t.claims;if(!r?.isAnonymous&&this.documentPaths?.cursor){let a=`${this.documentPaths.cursor}/${e.uid}`;this.commonDbService.setupOnDisconnect(a,{onlineStatus:j.PRESENCE_STATUS_OFFLINE,comment:"",timestamp:this.timestamp}).catch(s=>{this.loggingService.catch("Error in updateOnDatabaseDisconnect:",s)})}}}catch(t){this.loggingService.catch("Error in updateOnDatabaseDisconnect:",t)}})))}signOutUser(e){return new Promise((t,r)=>{try{this.documentPaths&&e?this.commonDbService.getData({feature:"cursor",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,id:e.uid,skipFirestore:!0}}).then(a=>{a&&this.commonDbService.updateData({feature:"cursor",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",id:e.uid,skipFirestore:!0},callback:()=>{t(null)},data:JSON.parse(JSON.stringify(T(I({},a?.data??{}),{timestamp:this.timestamp,onlineStatus:j.PRESENCE_STATUS_OFFLINE})))}),t(null)}).catch(a=>{this.loggingService.catch("Error in signOutUser subscription: ",a),r(a)}):t(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(t){return this.loggingService.catch("Error in CursorService isElementInsideAllowedElements: ",t),!1}}get timestamp(){return this.commonDbService.getServerTimestamp()}};o.\u0275fac=function(t){return new(t||o)(ee(et),ee(Ft),ee(jl),ee(at),ee(Di),ee(vn),ee(Be),ee(Dn),ee(Ve),ee(y),ee(pn))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var Jk=class extends si{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(E0).getLiveCursorsOnCurrentDocument()}catch(o){return this.getService(y).catch("Error in _getOnlineUsersOnCurrentDocument: ",o),se(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(E0).setInactivityTime(o)}catch(n){this.getService(y).catch("Error in setInactivityTime: ",n)}}_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(E0).setAllowedElementIds(o)}catch(n){this.getService(y).catch("Error in allowedElementIds: ",n)}}};var e9=class extends si{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(at).getDocumentMetadata$()}catch(o){return this.getService(y).catch("Error in getDocumentMetadata: ",o),se(null)}}};var fr=(()=>{let o=class o{constructor(e,t,r,a,s,c,p,u,C,E,D,L,z){this.afAuth=e,this.analyticsService=t,this.authService=r,this.databaseService=a,this.docService=s,this.configService=c,this.domService=p,this.huddleUtilsService=u,this.functions=C,this.loggingService=E,this.notificationService=D,this.commonDbService=L,this.usersService=z,this.documentPaths=null,this.localStream$=new ve(null),this.peerConnectionMap={},this.localStream=new MediaStream,this.screenSharingStream=new MediaStream,this.screenSharingStream$=new ve(null),this.remoteStreamMap={},this.remoteStreamMap$=new ve(null),this.localStreamState$=new ve({}),this.peerConnectionStateMap={},this.peerConnectionStateMap$=new ve({}),this.hudleToolComponentId$=new ve(null),this.attendees$=new ve([]),this.invitees$=new ve([]),this.huddleJoined$=new ve(!1),this.userHuddleStartTime$=new ve(null),this.messages$=new ve([]),this.messagesPanelVisible$=new ve(!1),this.huddleOnCursorMode$=new ve(!1),this.flockModeOnAvatarClickEnabled$=new ve(!1),this.chatEnabled$=new ve(!0),this.serverFallback$=new ve(!0),this.huddleOnCursorModeByAttendeeId$=new ve({}),this.huddleCursorAvailableByAttendeeId$=new ve({}),this.remoteStreamsByUserId$=new ve({}),this.messagesSubscription=null,this.huddleJoined=!1,this.onAnswerConnectionIdHistory={},this.onOfferUidHistory={},this.senders={},this.db=ts(),this.dbRefsRemoveOnDropCall=[],this.servers={iceServers:[{urls:["stun:stun1.l.google.com:19302","stun:stun2.l.google.com:19302"]}]},this.databaseService.getDb().pipe(Le(W=>!!W),st(1)).subscribe(W=>{try{W&&(this.db=W,this.isHuddleTagInstalled()&&this.getServerFallback()&&this.getTwilioIceServers(),this.getUser(),this.getDocumentPaths())}catch(J){this.loggingService.catch("Error in HuddleService getDb:",J)}},W=>{this.loggingService.catch("Error in HuddleService getDb subscription: ",W)}),this.docService.addPreDocumentIdChangeFunction("huddle-service",W=>Q(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(W=>{W&&(this.localStream=W)}),this.screenSharingStream$.subscribe(W=>{W&&(this.screenSharingStream=W)}),this.configService.getConfig$().subscribe(W=>{try{!W?.featureAllowList?.find(ue=>ue===Re.CURSOR)&&this.huddleOnCursorMode$.next(!1)}catch(J){this.loggingService.catch("Error in HuddleService configService.getConfig$:",J)}},W=>{this.loggingService.catch("Error in HuddleService configService.getConfig$ subscription: ",W)}),this.attendees$.subscribe(W=>{try{if(W?.length){if(this.huddleOnCursorMode$?.value){let J=this.huddleOnCursorModeByAttendeeId$.getValue()||{};W.forEach(ue=>{J[ue.userSnippylyId]=!0}),this.huddleOnCursorModeByAttendeeId$.next(J)}this.huddleJoined$?.value&&(W?.find(J=>J?.huddleOnCursorMode)?this.addCursorTag():this.removeCursorTag())}}catch(J){this.loggingService.catch("Error in HuddleService attendees$:",J)}},W=>{this.loggingService.catch("Error in HuddleService attendees$ subscription: ",W)}),Sn([this.huddleJoined$,this.huddleOnCursorMode$]).subscribe(([W,J])=>{try{if(W){if(J){let ue=this.attendees$.getValue()||[],ye=this.huddleOnCursorModeByAttendeeId$.getValue()||{};ue.forEach(Ae=>{ye[Ae.userSnippylyId]=!0}),document?.body?.setAttribute(j.ATTRIBUTES.VELT_HUDDLE_ON_CURSOR_MODE,"true")}else this.huddleOnCursorModeByAttendeeId$.next({}),document?.body?.removeAttribute(j.ATTRIBUTES.VELT_HUDDLE_ON_CURSOR_MODE);this.updateHuddleOnCursorMode()}else this.removeCursorTag(),document?.body?.removeAttribute(j.ATTRIBUTES.VELT_HUDDLE_ON_CURSOR_MODE)}catch(ue){this.loggingService.catch("Error in HuddleService huddleJoined$:",ue)}},W=>{this.loggingService.catch("Error in HuddleService huddleJoined$ subscription: ",W)}),this.huddleOnCursorModeByAttendeeId$.subscribe(W=>{try{this.huddleJoined&&(Object.keys(W).length?this.addCursorTag():this.removeCursorTag())}catch(J){this.loggingService.catch("Error in HuddleService huddleOnCursorModeByAttendeeId$:",J)}},W=>{this.loggingService.catch("Error in HuddleService huddleOnCursorModeByAttendeeId$ subscription: ",W)}),this.authService.addPreSignOutFuction("huddle-signout",this.signOutUser.bind(this))}isHuddleTagInstalled(){try{return!!document?.querySelector(`${j.TAGS.VELT_HUDDLE}`)||!!document?.querySelector(`${j.TAGS.SNIPPYLY_HUDDLE}`)}catch(e){return this.loggingService.catch("Error in HuddleService isHuddleTagInstalled:",e),!1}}getTwilioIceServers(){return Q(this,null,function*(){try{let t=(yield br(this.functions,Er({url:oi.cloudFunction.getIceServers,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:12e5})())?.data;t&&t?.iceServers&&(this.servers.iceServers=t.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 ei(this.afAuth).pipe(Le(e=>!!e),ce(e=>({firebaseUser:e})),he(e=>this.configService.getConfig$().pipe(Le(t=>!!t),ce(t=>T(I({},e),{config:t})))),he(e=>this.authService.getUser$().pipe(ce(t=>T(I({},e),{user:t})))),he(e=>ro(e.config,e.user,Re.HUDDLE)?se(T(I({},e),{allowed:!0})):(this.loggingService.warn("Huddle feature is not allowed."),se(T(I({},e),{allowed:!1})))),Et((e,t)=>e?.allowed===t?.allowed),he(e=>this.docService.getDocumentPaths$().pipe(ce(t=>(this.documentPaths=t,e)))),he(e=>e?.allowed?e?.user?.isAnonymous?se(null):this.documentPaths?.huddle?this.commonDbService.dbListener({feature:"allHuddleAttendees",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,skipFirestore:!0}}).pipe(ce(t=>t?.data),ce(t=>t?(this.attendees$.next(Object.values(t)),Object.values(t)):(this.attendees$.next([]),null))):se(null):se([])))}getInvitees(){try{return ei(this.afAuth).pipe(Le(e=>!!e),ce(e=>({firebaseUser:e})),he(e=>this.configService.getConfig$().pipe(Le(t=>!!t),ce(t=>T(I({},e),{config:t})))),he(e=>this.authService.getUser$().pipe(ce(t=>T(I({},e),{user:t})))),he(e=>ro(e.config,e.user,Re.HUDDLE)?se(T(I({},e),{allowed:!0})):(this.loggingService.warn("Huddle feature is not allowed."),se(T(I({},e),{allowed:!1})))),Et((e,t)=>e?.allowed===t?.allowed),he(e=>this.docService.getDocumentPaths$().pipe(ce(t=>(this.documentPaths=t,e)))),he(e=>e?.allowed?e?.user?.isAnonymous?se(null):this.documentPaths?.huddle?this.commonDbService.dbListener({feature:"allHuddleInvitees",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,skipFirestore:!0}}).pipe(ce(t=>t?.data),ce(t=>t?(this.invitees$.next(Object.values(t)),Object.values(t)):(this.invitees$.next([]),null))):se(null):se([])))}catch(e){return this.loggingService.catch("Error in HuddleService getInvitees:",e),se([])}}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(Le(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(dn(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 Q(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=qi(this.db,this.documentPaths?.huddle),this.iceCandidates=qi(this.db,`${this.documentPaths?.huddle}/iceCandidates`),this.connections=qi(this.db,`${this.documentPaths?.huddle}/connections`),this.attendees=qi(this.db,`${this.documentPaths?.huddle}/attendees`),this.messages=qi(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(t){this.loggingService.catch("Error in HuddleService joinHuddle:",t)}})}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;"),Np(this.connections,e=>{try{if(e.exists()){let t=e.val();Object.values(t).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=>Q(this,null,function*(){t[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(t=>Q(this,null,function*(){Object.values(this.remoteStreamMap[t]).forEach(r=>{r.getTracks().forEach(a=>{a.stop()})}),yield this.removeIceCandidates(t)})),this.remoteStreamMap={},this.remoteStreamMap$.next(this.remoteStreamMap)}catch(t){this.loggingService.catch("Error in HuddleService setHuddleLister onValue:",t)}}),NV(this.iceCandidates).subscribe(e=>{try{e.event==="child_added"&&this.onIceCandidateSnapshot(e.snapshot)}catch(t){this.loggingService.catch("Error in HuddleService iceCandidates stateChanges:",t)}}),NV(this.attendees).subscribe(e=>{try{if(e.event==="child_removed"){let t=e?.snapshot?.val();if(t){delete this.onOfferUidHistory[t?.userSnippylyId];let r=this.getCombinedId(this.user.userSnippylyId,t?.userSnippylyId);delete this.onAnswerConnectionIdHistory[r],this.closeConnection(r)}}}catch(t){this.loggingService.catch("Error in HuddleService iceCandidates stateChanges:",t)}}),this.messagesSubscription&&this.messagesSubscription.unsubscribe(),this.messagesSubscription=new Ut(e=>{let t=Np(this.messages,r=>e.next(r),r=>e.error(r));return()=>t()}).pipe(he(e=>this.usersService.getUserById$().pipe(ce(()=>e))),he(e=>{if(e.exists()){let t=e.val();return Zi(this.huddleUtilsService.resolveUsersFromHuddleMessages(Object.values(t||{})))}return se([])}),kn(e=>(this.loggingService.catch("Error in HuddleService messages onValue:",e),se([])))).subscribe(e=>{this.messages$.next(e)})}onHuddleSnapshot(e,t){try{this.loggingService.log("%c[WB] Calling FUNCTION: onHuddleSnapshot","color: green;"),t.offerData&&!t.answerData&&t.offerData.from!==this.user.userSnippylyId&&t.offerData.to===this.user.userSnippylyId&&!(e in this.peerConnectionMap)&&!this.onOfferUidHistory[t.offerData.from]?(this.loggingService.log("offer received"),this.loggingService.log(t),this.onOfferUidHistory[t.offerData.from]=!0,this.onOffer(e,t.offerData)):t.answerData&&t.answerData.from!==this.user.userSnippylyId&&t.answerData.to===this.user.userSnippylyId&&this.peerConnectionMap[e]&&this.peerConnectionMap[e]?.connectionState!=="connected"&&!this.onAnswerConnectionIdHistory[e]&&(this.loggingService.log("answer received"),this.loggingService.log(t),this.onAnswerConnectionIdHistory[e]=!0,this.onAnswer(e,t.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 t=e.val(),r=t.connectionId;t?.from!==this.user.userSnippylyId&&r in this.peerConnectionMap&&this.onIceCandidateChange(r,t)}catch(t){this.loggingService.catch("Error in HuddleService onIceCandidateSnapshot:",t)}}onOffer(e,t){return Q(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: onOffer","color: green;"),this.createPeerConnection(e,t.from)){this.addLocalStreamToPeerConnection(e,!0);let a=t.offer;yield this.setRemoteDescription(e,a),yield this.sendAnswer(e,t.from)}}catch(r){this.loggingService.catch("Error in HuddleService onOffer:",r)}})}sendAnswer(e,t){return Q(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:t},c=qi(this.db,`${this.documentPaths?.huddle}/connections/${e}`);this.dbRefsRemoveOnDropCall.push({type:"connection",dbRef:c}),yield H6(c,{answerData:s}),bd(c).remove()}else this.loggingService.catch("Error in sendAnswer: documentPaths not found")}catch(r){this.loggingService.catch("Error in HuddleService onHuddleSnapshot:",r)}})}onAnswer(e,t){return Q(this,null,function*(){try{this.loggingService.log("%c[WB] Calling FUNCTION: onAnswer","color: green;");let r=t.answer;yield this.setRemoteDescription(e,r)}catch(r){this.loggingService.catch("Error in HuddleService onAnswer:",r)}})}onIceCandidateChange(e,t){return Q(this,null,function*(){try{this.loggingService.log("%c[WB] Calling FUNCTION: onIceCandidateChange","color: green;");let r=t.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,t){return Q(this,null,function*(){try{this.loggingService.log("%c[WB] Calling FUNCTION: setRemoteDescription","color: green;"),yield this.peerConnectionMap[e].setRemoteDescription(new RTCSessionDescription(t))}catch(r){this.loggingService.catch("Error in HuddleService setRemoteDescription:",r)}})}addAttendee(){return Q(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 t=qi(this.db,`${this.documentPaths?.huddle}/attendees/${this.user.userSnippylyId}`);yield nv(t,JSON.parse(JSON.stringify(e))),this.dbRefsRemoveOnDropCall.push({type:"attendee",dbRef:t}),bd(t).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;"),Pne(this.attendees).pipe(st(1)).subscribe(e=>{e&&e.length>1?(e.forEach(t=>{t.userSnippylyId!==this.user.userSnippylyId&&!this.onOfferUidHistory[t.userSnippylyId]&&(this.loggingService.log("calling"),this.loggingService.log(t),this.initOffer(t.userSnippylyId))}),this.addLocalStreamToAllPeerConnections()):this.deleteMessages()})}catch(e){this.loggingService.catch("Error in HuddleService callExistingAttendees:",e)}}addLocalStreamToAllPeerConnections(){return Q(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(t=>{this.loggingService.log(t),this.senders[e].replaceTrack(t)})})}catch(e){this.loggingService.catch("Error in HuddleService addLocalStreamToAllPeerConnections:",e)}})}initOffer(e){return Q(this,null,function*(){try{this.loggingService.log("%c[WB] Calling FUNCTION: initOffer","color: green;");let t=this.createPeerConnection(null,e);t&&(this.addLocalStreamToPeerConnection(t,!1),yield this.sendOffer(t,e))}catch(t){this.loggingService.catch("Error in HuddleService initOffer:",t)}})}createPeerConnection(e,t){try{return this.loggingService.log("%c[WB] Calling FUNCTION: createPeerConnection","color: green;"),e||(e=this.getCombinedId(this.user?.userSnippylyId,t)),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=Nne(this.iceCandidates,a);this.dbRefsRemoveOnDropCall.push({type:"iceCandidate",dbRef:s}),bd(s).remove()}},this.peerConnectionMap[e].ontrack=r=>{this.loggingService.log("pc ontrack"),this.onTrack(e,r)},this.peerConnectionMap[e].onconnectionstatechange=r=>Q(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=>Q(this,null,function*(){this.logStatuses("onicegatheringstatechange",e,r)}),this.peerConnectionMap[e].onsignalingstatechange=r=>Q(this,null,function*(){this.logStatuses("onsignalingstatechange",e,r)}),this.peerConnectionMap[e].oniceconnectionstatechange=r=>Q(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,t,r){let a={};["connectionState","iceConnectionState","iceGatheringState","signalingState"].forEach(c=>{a[c]=this.peerConnectionMap[t][c]}),this.loggingService.log("Huddle: logStatues: ",t,e,a,r,this.peerConnectionMap[t])}checkForRemovingAttendee(){return Q(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 t=this.peerConnectionMap[e];t.getTransceivers()?.forEach(a=>{a.stop()}),t.getReceivers()?.forEach(a=>{a.track?.stop()}),t.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(t){this.loggingService.catch("Error in HuddleService closeConnection:",t)}}removeConnection(e){return Q(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(t){this.loggingService.catch("Error in HuddleService removeConnection:",t)}})}addLocalStreamToPeerConnection(e,t){try{this.loggingService.log("%c[WB] Calling FUNCTION: addLocalStreamToPeerConnection","color: green;"),t?(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 t=this.peerConnectionMap[e].getTransceivers();this.loggingService.log(t),t.map(r=>{this.loggingService.log(r.currentDirection),r.currentDirection!=="sendrecv"&&(r.direction="sendrecv"),this.senders[e]=r.sender})}catch(t){this.loggingService.catch("Error in HuddleService updateTransceiverDirection:",t)}}generateKey(){this.loggingService.log("%c[WB] Calling FUNCTION: generateKey","color: green;");let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t="";for(let r=0;r<20;r++)t+=e.charAt(Math.floor(Math.random()*e.length));return t}getCombinedId(e,t){try{return e.localeCompare(t)===-1?`${e}__${t}`:`${t}__${e}`}catch(r){return this.loggingService.catch("Error in HuddleService getCombinedId:",r),""}}sendOffer(e,t){return Q(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: sendOffer","color: green;"),this.documentPaths?.huddle&&e){this.onOfferUidHistory[t]=!0;let r=yield this.peerConnectionMap[e].createOffer();yield this.setLocalDescription(e,r);let a={sdp:r.sdp,type:r.type};t||(t="all");let s={offer:a,from:this.user.userSnippylyId,connectionId:e,to:t},c=qi(this.db,`${this.documentPaths?.huddle}/connections/${e}`);yield nv(c,{offerData:s}),this.dbRefsRemoveOnDropCall.push({type:"connection",dbRef:c}),bd(c).remove()}}catch(r){this.loggingService.catch("Error in HuddleService sendOffer:",r)}})}setLocalDescription(e,t){return Q(this,null,function*(){try{this.loggingService.log("%c[WB] Calling FUNCTION: setLocalDescription","color: green;"),yield this.peerConnectionMap[e].setLocalDescription(t)}catch(r){this.loggingService.catch("Error in HuddleService setLocalDescription:",r)}})}onTrack(e,t){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: onTrack","color: green;"),this.remoteStreamMap[e]||(this.remoteStreamMap[e]={}),this.loggingService.log(t.receiver.track),t?.streams?.length){this.remoteStreamMap[e][t.streams[0].id]=t.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===t.streams[0].id&&(this.remoteStreamMap[e].webcam=t.streams[0]),a?.streamMetadata?.screen===t.streams[0].id&&(this.remoteStreamMap[e].screen=t.streams[0])),this.remoteStreamMap$.next(this.remoteStreamMap)}}catch(r){this.loggingService.catch("Error in HuddleService onTrack:",r)}}toggleScreenSharing(e){return Q(this,null,function*(){try{if(e)this.screenSharingStream=yield navigator.mediaDevices?.getDisplayMedia({video:!0}),Object.keys(this.peerConnectionMap).forEach(t=>{this.peerConnectionMap[t].getSenders().find(s=>s?.track?.kind==this.screenSharingStream?.getVideoTracks()[0].kind)?.replaceTrack(this.screenSharingStream?.getVideoTracks()[0])});else{let t=this.localStream;Object.keys(this.peerConnectionMap).forEach(r=>{this.peerConnectionMap[r].getSenders().find(c=>c?.track?.kind==t.getVideoTracks()[0].kind)?.replaceTrack(t.getVideoTracks()[0])}),this.screenSharingStream?.getTracks().forEach(r=>r.stop())}}catch(t){this.loggingService.catch("Error in HuddleService toggleScreenSharing:",t)}})}setLocalStream(e){return Q(this,null,function*(){try{if(this.localStream=new MediaStream([this.silence(),this.black()]),e?.audio||e?.video){let t=e,r=Ac();e?.audio&&(e?.audio instanceof Object?t.audio=T(I({},e?.audio),{deviceId:r?.selectedAudioDevice?.deviceId}):t.audio={deviceId:r?.selectedAudioDevice?.deviceId}),e?.video&&(e?.video instanceof Object?t.video=T(I({},e?.video),{deviceId:r?.selectedVideoDevice?.deviceId}):t.video={deviceId:r?.selectedVideoDevice?.deviceId});let a=yield navigator.mediaDevices.getUserMedia(t);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(t){this.loggingService.catch("Error in HuddleService setLocalStream:",t)}})}setScreenSharingStream(){return Q(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 Q(this,null,function*(){try{this.localStream$?.value&&(this.localStream$.value.getTracks().forEach(t=>{t.stop()}),this.localStream$.next(null))}catch(e){this.loggingService.catch("Error in HuddleService removeLocalStream:",e)}})}toggleLocalStreamAudio(e){return Q(this,null,function*(){try{let t=this.localStream$.value;if(t){let r=t.getAudioTracks()[0];if(r.enabled&&!e)r.stop(),t.getAudioTracks()?.forEach(a=>{t.removeTrack(a)}),t.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&&(t.getAudioTracks()?.forEach(c=>{t.removeTrack(c)}),s.getAudioTracks()?.forEach(c=>{t.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==t?.getAudioTracks()[0].kind)?.replaceTrack(t?.getAudioTracks()[0])}),this.updateUserHuddleState()}}catch(t){this.loggingService.catch("Error in HuddleService toggleLocalStreamAudio:",t)}})}toggleLocalStreamVideo(e){return Q(this,null,function*(){try{let t=this.localStream$.value;if(t){let r=t.getVideoTracks()[0];if(r.enabled&&!e)r.stop(),t.getVideoTracks()?.forEach(a=>{t.removeTrack(a)}),t.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&&(t.getVideoTracks()?.forEach(c=>{t.removeTrack(c)}),s.getVideoTracks()?.forEach(c=>{t.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==t?.getVideoTracks()[0].kind)?.replaceTrack(t?.getVideoTracks()[0])}),this.updateUserHuddleState()}}catch(t){this.loggingService.catch("Error in HuddleService toggleLocalStreamVideo:",t)}})}toggleLocalScreenSharing(){return Q(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 Q(this,null,function*(){let e=this.screenSharingStream;if(e){let t=e.getVideoTracks()[0];t.enabled&&(t.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 Q(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 Q(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 t=this.peerConnectionMap[e];t.getTransceivers()?.forEach(r=>{r.stop()}),t.getSenders()?.forEach(r=>{r.track?.stop()}),t.getReceivers()?.forEach(r=>{r.track?.stop()}),t.close()}),this.peerConnectionMap={},this.dbRefsRemoveOnDropCall.forEach(e=>Q(this,null,function*(){yield $6(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,t,r){try{let a=JSON.parse(sessionStorage.getItem(j.SESSION_STORAGE.SNIPPYLY_HUDDLE_DATA)||"{}");r?sessionStorage.setItem(j.SESSION_STORAGE.SNIPPYLY_HUDDLE_DATA,JSON.stringify(r)):(a[e]=t,sessionStorage.setItem(j.SESSION_STORAGE.SNIPPYLY_HUDDLE_DATA,JSON.stringify(a)))}catch(a){this.loggingService.catch("Error in HuddleService updateHuddleSessionData:",a)}}getHuddleSessionData(){try{return sessionStorage.getItem(j.SESSION_STORAGE.SNIPPYLY_HUDDLE_DATA)?JSON.parse(sessionStorage.getItem(j.SESSION_STORAGE.SNIPPYLY_HUDDLE_DATA)):null}catch(e){return this.loggingService.catch("Error in HuddleService getHuddleSessionData:",e),null}}removeHuddleSessionData(){try{sessionStorage.removeItem(j.SESSION_STORAGE.SNIPPYLY_HUDDLE_DATA)}catch(e){this.loggingService.catch("Error in HuddleService removeHuddleSessionData:",e)}}removeAttendee(){return Q(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 Q(this,null,function*(){try{if(this.attendees&&this.user&&this.documentPaths?.huddle){let e=this.getAudioState(),t=this.getVideoState(),r=this.getScreenSharingState();this.localStreamState$.next({audioState:e,videoState:t,screenSharingState:r});let a={audioState:e,videoState:t,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 Q(this,null,function*(){try{if(this.attendees&&this.user&&this.documentPaths?.huddle){let e=qi(this.db,`${this.documentPaths?.huddle}/attendees/${this.user.userSnippylyId}/huddleOnCursorMode`);yield nv(e,!!this.huddleOnCursorMode$.value)}}catch(e){this.loggingService.catch("Error in HuddleService updateHuddleOnCursorMode:",e)}})}getAudioState(){try{let e=this.localStream$.value;if(e){let t=e?.getAudioTracks();return!!(t?.length?t[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 t=e?.getVideoTracks();return!!(t?.length?t[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 t=e?.getVideoTracks();return!!(t?.length?t[0]:null)?.enabled}return!1}catch(e){return this.loggingService.catch("Error in HuddleService getVideoState:",e),!1}}removeIceCandidates(e){return Q(this,null,function*(){try{if(this.documentPaths?.huddle&&e){let t=yield this.commonDbService?.getData({feature:"allHuddleIceCandidates",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",skipFirestore:!0}});Object.keys(t).length>0&&Object.keys(t).forEach(r=>Q(this,null,function*(){t[r].connectionId===e&&this.commonDbService.deleteData({feature:"huddleIceCandidate",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,id:r,skipFirestore:!0}})}))}}catch(t){this.loggingService.catch("Error in HuddleService dropCall:",t)}})}get timestamp(){return this.commonDbService.getServerTimestamp()}silence(){try{let e=new AudioContext,t=e.createOscillator(),r=t.connect(e.createMediaStreamDestination());return t.start(),Object.assign(r.stream.getAudioTracks()[0],{enabled:!1})}catch(e){this.loggingService.catch("Error in HuddleService silence:",e)}}black({width:e=640,height:t=480}={}){try{let r=Object.assign(document.createElement("canvas"),{width:e,height:t});r.getContext("2d")?.fillRect(0,0,e,t);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),se([])}}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),se([])}}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 t={};t.notificationSource="huddleInvite",t.huddleInvitees=e,t.huddleType=this.getInitialHuddleType(),this.updateNotificationsDatabase(t)}catch(t){this.loggingService.catch("Error in HuddleService inviteUsers:",t)}}updateInvitees(e){try{if(this.documentPaths?.huddle){let t={};e.forEach(r=>{if(r?.email){let a=bt(r.email);t[a]=r}}),this.commonDbService.setData({feature:"allHuddleInvitees",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,skipFirestore:!0},data:t})}}catch(t){this.loggingService.catch("Error in HuddleService updateInvitees:",t)}}updateNotificationsDatabase(e={}){try{let t=I({notificationSource:"huddle"},e);this.notificationService.updateNotificationDatabase(t)}catch(t){this.loggingService.catch("Error in HuddleService updateNotificationsDatabase: ",t)}}getHuddleJoined$(){try{return this.huddleJoined$.asObservable()}catch(e){return this.loggingService.catch("Error in HuddleService getHuddleJoined$:",e),se(!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),se({})}}updateHuddleCursorAvailableByAttendeeId(e,t){try{let r=this.huddleCursorAvailableByAttendeeId$.value;r[e]=t,this.huddleCursorAvailableByAttendeeId$.next(r)}catch(r){this.loggingService.catch("Error in HuddleService updateCursorUserAvailableByUserId:",r)}}setRemoteStreamsByUserId(e){try{this.remoteStreamsByUserId$.next(e)}catch(t){this.loggingService.catch("Error in HuddleService setRemoteStreamsByUserId:",t)}}getRemoteStreamsByUserId$(){try{return this.remoteStreamsByUserId$.asObservable()}catch(e){return this.loggingService.catch("Error in HuddleService getRemoteStreamsByUserId$:",e),se({})}}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),se(!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),se(!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),se(!1)}}getChatEnabled(){try{return this.chatEnabled$.value}catch(e){return this.loggingService.catch("Error in HuddleService getChatEnabled:",e),!1}}enableServerFallback(){try{if(this.serverFallback$.value===!0)return;this.serverFallback$.next(!0)}catch(e){this.loggingService.catch("Error in HuddleService enableServerFallback:",e)}}disableServerFallback(){try{if(this.serverFallback$.value===!1)return;this.serverFallback$.next(!1)}catch(e){this.loggingService.catch("Error in HuddleService disableServerFallback:",e)}}getServerFallback$(){try{return this.serverFallback$.asObservable()}catch(e){return this.loggingService.catch("Error in HuddleService getServerFallback$:",e),se(!1)}}getServerFallback(){try{return this.serverFallback$.value}catch(e){return this.loggingService.catch("Error in HuddleService getServerFallback:",e),!1}}getHuddleOnCursorModeByAttendeeId$(){try{return this.huddleOnCursorModeByAttendeeId$.asObservable()}catch(e){return this.loggingService.catch("Error in HuddleService getHuddleOnCursorModeByAttendeeId$:",e),se({})}}toggleHuddleOnCursorModeByAttendeeId(e){try{let t=this.huddleOnCursorModeByAttendeeId$.value;t[e]?delete t[e]:t[e]=!0,this.huddleOnCursorModeByAttendeeId$.next(t)}catch(t){this.loggingService.catch("Error in HuddleService toggleHuddleOnCursorModeByAttendeeId:",t)}}addCursorTag(){try{if(!document.querySelector(`${j.TAGS.SNIPPYLY_CURSOR}`)){let e=document.createElement(j.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(`${j.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 t=new hk;t.message=e,t.from=this.user,t.timestamp=this.timestamp,this.commonDbService.setData({feature:"huddleMessage",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,id:t.id,skipFirestore:!0},data:t})}}catch(t){this.loggingService.catch("Error in HuddleService sendMessage:",t)}}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),se([])}}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),se(!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 Q(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(t){this.loggingService.catch("Error in HuddleService signOutUser:",t)}})}};o.\u0275fac=function(t){return new(t||o)(ee(Di),ee(et),ee(Ve),ee(Dn),ee(at),ee(Ft),ee(Be),ee(Mk),ee(Wo),ee(y),ee(gn),ee(pn),ee(Vn))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var t9=class extends si{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(fr).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(fr).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(fr).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(fr).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(fr).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(fr).disableFlockModeOnAvatarClick()}catch(o){this.getService(y).catch("Error in disableFlockModeOnAvatarClick: ",o)}}};var n9=class extends si{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,this.updateUserPresence=this._updateUserPresence,this.on=this._on}_getLiveStateData(o,n){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(Li).getLiveStateData$(o,n)}catch(e){return this.getService(y).catch("Error in _getLiveStateData: ",e),se(null)}}_setLiveStateData(o,n,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(Li).setLiveStateData(o,n,e)}catch(t){return this.getService(y).catch("Error in _setLiveStateData: ",t),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(Li).enableSingleEditorMode(o)}catch(n){this.getService(y).catch("Error in _enableSingleEditorMode: ",n)}}_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(Li).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(Li).isUserEditor$()}catch(o){return this.getService(y).catch("Error in _isUserEditor$: ",o),se(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(Li).getEditor$()}catch(o){return this.getService(y).catch("Error in _getEditor: ",o),se(null)}}_setUserAsEditor(){this.getService(y).log("%c[WB] Calling FUNCTION: setUserAsEditor","color: green;");try{return this.trackEvent(Z.Events.LiveStateSync.SET_USER_AS_EDITOR_TRIGGERED),this.getService(Li).setUserAsEditor()}catch(o){return this.getService(y).catch("Error in _setUserAsEditor: ",o),Promise.resolve()}}_resetUserAccess(){this.getService(y).log("%c[WB] Calling FUNCTION: resetUserAccess","color: green;");try{this.trackEvent(Z.Events.LiveStateSync.RESET_USER_ACCESS_TRIGGERED),this.getService(Li).removeEditorAccess({metadata:{from:"resetUserAccess-liveStateSyncElement",reason:"Client called"}})}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(Li).setSingleEditorModeContainerIds(o)}catch(n){this.getService(y).catch("Error in _singleEditorModeContainerIds: ",n)}}_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(Li).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(Li).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(Li).requestEditorAccess()}catch(o){return this.getService(y).catch("Error in _requestEditorAccess: ",o),se(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(Li).isEditorAccessRequested$()}catch(o){return this.getService(y).catch("Error in _isEditorAccessRequested: ",o),se(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(Li).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(Li).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(Li).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(Li).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(Li).setEditorAccessTimeout(o)}catch(n){this.getService(y).catch("Error in _setEditorAccessTimeout: ",n)}}_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(Li).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(Li).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(Li).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(Li).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(Li).getEditorAccessTimer$()}catch(o){return this.getService(y).catch("Error in _getEditorAccessTimer: ",o),se(new p0)}}_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(Li).onServerConnectionStateChange$()}catch(o){return this.getService(y).catch("Error in _onServerConnectionStateChange: ",o),se(ol.PENDING_INIT)}}_updateUserPresence(o){this.getService(y).log("%c[WB] Calling FUNCTION: updateUserPresence","color: green;");try{this.trackEvent(Z.Events.LiveStateSync.UPDATE_USER_PRESENCE_TRIGGERED,{payload:{userPresence:o}}),this.getService(Li).updateUserPresence(o)}catch(n){this.getService(y).catch("Error in _updateUserPresence: ",n)}}_on(o){this.getService(y).log("%c[WB] Calling FUNCTION: on","color: green;");try{return this.trackEvent(Z.Events.LiveStateSync.ON_ACTION_TRIGGERED,{payload:{action:o}}),this.getService(Qk).onAction(o)}catch(n){return this.getService(y).catch("Error in _on: ",n),se(null)}}};var i9=(()=>{let o=class o{constructor(e){this.loggingService=e,this.actionSubjects=new Map,this.defaultSource="internal",this.isUserAdmin=!1,this.subscriptions=[],this.loggingService.log("%c[WB] Creating CLASS: CommentActionsService","color: blue;")}triggerSettingsUpdatedEvent(e){try{this.triggerAction(Zre.SETTINGS_UPDATED,e)}catch(t){this.loggingService.catch("Error in NotificationsActionsService triggerAddCommentAnnotationEvent: ",t)}}triggerAction(e,t){try{this.actionSubjects.has(e)||this.actionSubjects.set(e,new tt),this.actionSubjects.get(e)?.next(t)}catch(r){this.loggingService.catch("Error in NotificationsActionsService triggerAction: ",r)}}onAction(e){try{return this.actionSubjects.has(e)||this.actionSubjects.set(e,new tt),this.actionSubjects.get(e)?.asObservable()}catch(t){return this.loggingService.catch("Error in NotificationsActionsService onAction: ",t),se(null)}}};o.\u0275fac=function(t){return new(t||o)(ee(y))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var o9=class extends si{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,this.setSettings=this._setSettings,this.getSettings=this._getSettings,this.muteAllNotifications=this._muteAllNotifications,this.enableSettings=this._enableSettings,this.enableSelfNotifications=this._enableSelfNotifications,this.disableSelfNotifications=this._disableSelfNotifications,this.disableSettings=this._disableSettings,this.setSettingsInitialConfig=this._setSettingsInitialConfig,this.openNotificationsPanel=this._openNotificationsPanel,this.closeNotificationsPanel=this._closeNotificationsPanel,this.on=this._on}_openHistoryPanel(){this.getService(y).log("%c[WB] Calling FUNCTION: _openHistoryPanel","color: green;");try{this.trackEvent(Z.Events.Notifications.OPEN_HISTORY_PANEL_TRIGGERED),this.getService(gn).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(gn).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(gn).toggleHistoryPanelVisibility(!0)}catch(o){this.getService(y).catch("Error in toggleHistoryPanel: ",o)}}_getNotificationsData(o){this.getService(y).log("%c[WB] Calling FUNCTION: _getNotificationsData","color: green;");try{return this.trackEvent(Z.Events.Notifications.GET_NOTIFICATIONS_DATA_TRIGGERED),this.getService(gn).getNotifications$(o)}catch(n){return this.getService(y).catch("Error in getNotificationsData: ",n),se([])}}_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(gn).setMaxDays(o)}catch(n){this.getService(y).catch("Error in setMaxDays: ",n)}}_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(gn).setTabConfig(o)}catch(n){this.getService(y).catch("Error in setTabConfig: ",n)}}_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(gn).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(gn).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(gn).setAllNotificationsAsRead(o)}catch(n){this.getService(y).catch("Error in setAllNotificationsAsRead: ",n)}}_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(gn).getUnreadNotificationsCount$()}catch(o){return this.getService(y).catch("Error in getUnreadNotificationsCount: ",o),se({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(gn).markNotificationAsReadById(o)}catch(n){this.getService(y).catch("Error in markNotificationAsReadById: ",n)}}_setSettings(o){this.getService(y).log("%c[WB] Calling FUNCTION: _setSettings","color: green;");try{this.trackEvent(Z.Events.Notifications.SET_SETTINGS_TRIGGERED,{payload:{config:o}}),this.getService(gn).setSettingsConfigWithDB(o)}catch(n){this.getService(y).catch("Error in setSettings: ",n)}}_getSettings(){this.getService(y).log("%c[WB] Calling FUNCTION: _getSettings","color: green;");try{return this.trackEvent(Z.Events.Notifications.GET_SETTINGS_TRIGGERED),this.getService(gn).getSettingsConfig$()}catch(o){return this.getService(y).catch("Error in getSettings: ",o),se(null)}}_muteAllNotifications(){this.getService(y).log("%c[WB] Calling FUNCTION: _muteAllNotifications","color: green;");try{this.trackEvent(Z.Events.Notifications.MUTE_ALL_NOTIFICATIONS_TRIGGERED),this.getService(gn).setMuteAllNotifications()}catch(o){this.getService(y).catch("Error in muteAllNotifications: ",o)}}_enableSettings(){this.getService(y).log("%c[WB] Calling FUNCTION: _enableSettings","color: green;");try{this.trackEvent(Z.Events.Notifications.ENABLE_SETTINGS_TRIGGERED),this.getService(gn).enableSettings()}catch(o){this.getService(y).catch("Error in enableSettings: ",o)}}_enableSelfNotifications(){this.getService(y).log("%c[WB] Calling FUNCTION: _enableSelfNotifications","color: green;");try{this.trackEvent(Z.Events.Notifications.ENABLE_SELF_NOTIFICATIONS_TRIGGERED),this.getService(gn).enableSelfNotifications()}catch(o){this.getService(y).catch("Error in enableSelfNotifications: ",o)}}_disableSelfNotifications(){this.getService(y).log("%c[WB] Calling FUNCTION: _disableSelfNotifications","color: green;");try{this.trackEvent(Z.Events.Notifications.DISABLE_SELF_NOTIFICATIONS_TRIGGERED),this.getService(gn).disableSelfNotifications()}catch(o){this.getService(y).catch("Error in disableSelfNotifications: ",o)}}_disableSettings(){this.getService(y).log("%c[WB] Calling FUNCTION: _disableSettings","color: green;");try{this.trackEvent(Z.Events.Notifications.DISABLE_SETTINGS_TRIGGERED),this.getService(gn).disableSettings()}catch(o){this.getService(y).catch("Error in disableSettings: ",o)}}_setSettingsInitialConfig(o){this.getService(y).log("%c[WB] Calling FUNCTION: _setSettingsInitialConfig","color: green;");try{this.trackEvent(Z.Events.Notifications.SET_SETTINGS_INITIAL_CONFIG_TRIGGERED,{payload:{settings:o}}),this.getService(gn).setSettingsInitialConfig(o)}catch(n){this.getService(y).catch("Error in setSettingsInitialConfig: ",n)}}_on(o){this.getService(y).log("%c[WB] Calling FUNCTION: on","color: green;");try{return this.trackEvent(Z.Events.Notifications.ON_ACTION_TRIGGERED,{payload:{action:o}}),this.getService(i9).onAction(o)}catch(n){return this.getService(y).catch("Error in _on: ",n),se(null)}}_openNotificationsPanel(){this.getService(y).log("%c[WB] Calling FUNCTION: _openNotificationsPanel","color: green;");try{this.trackEvent(Z.Events.Notifications.OPEN_NOTIFICATIONS_PANEL_TRIGGERED),this.getService(gn).openNotificationsPanel()}catch(o){this.getService(y).catch("Error in openNotificationsPanel: ",o)}}_closeNotificationsPanel(){this.getService(y).log("%c[WB] Calling FUNCTION: _closeNotificationsPanel","color: green;");try{this.trackEvent(Z.Events.Notifications.CLOSE_NOTIFICATIONS_PANEL_TRIGGERED),this.getService(gn).closeNotificationsPanel()}catch(o){this.getService(y).catch("Error in closeNotificationsPanel: ",o)}}};var kz=(()=>{let o=class o{constructor(e,t,r){this.analyticsService=e,this.loggingService=t,this.presenceService=r,this.actionSubjects=new Map,this.subscriptions=[];try{this.presenceService.setPresenceActionsService(this)}catch(a){this.loggingService.catch("Error in PresenceActionsService constructor: ",a)}}onMultipleUsersOnline(e){try{this.loggingService.log("%c[WB] Calling PresenceActionsService FUNCTION: onMultipleUsersOnline","color: green;"),this.triggerAction(Ij.MULTIPLE_USERS_ONLINE,e),this.analyticsService.trackEvent(Z.Events.Presence.MULTIPLE_USERS_ONLINE,{totalUsers:e?.users?.length,presenceSnippylyUserIds:e?.users?.map(t=>t.userSnippylyId),presenceClientUserIds:e?.users?.map(t=>t.userId)})}catch(t){this.loggingService.catch("Error in PresenceActionsService onMultipleUsersOnline: ",t)}}onUserStateChange(e){try{this.loggingService.log("%c[WB] Calling PresenceActionsService FUNCTION: onUserStateChange","color: green;"),this.triggerAction(Ij.USER_STATE_CHANGE,e),this.analyticsService.trackEvent(Z.Events.Presence.ON_USER_STATE_CHANGE,{userSnippylyId:e?.user?.userSnippylyId,userId:e?.user?.userId,state:e?.state})}catch(t){this.loggingService.catch("Error in PresenceActionsService onUserStateChange: ",t)}}getData(e){try{return this.loggingService.log("%c[WB] Calling PresenceActionsService FUNCTION: getData","color: green;"),this.presenceService.getOnlineUsersOnCurrentDocument(e).pipe(ce(t=>({data:t})))}catch(t){return this.loggingService.catch("Error in PresenceActionsService getData: ",t),se({data:null})}}triggerAction(e,t){try{this.actionSubjects.has(e)||this.actionSubjects.set(e,new tt),this.actionSubjects.get(e)?.next(t)}catch(r){this.loggingService.catch("Error in PresenceActionsService triggerAction: ",r)}}onAction(e){try{return this.actionSubjects.has(e)||this.actionSubjects.set(e,new tt),this.actionSubjects.get(e)?.asObservable()}catch(t){return this.loggingService.catch("Error in PresenceActionsService onAction: ",t),se(null)}}};o.\u0275fac=function(t){return new(t||o)(ee(et),ee(y),ee(jl))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var r9=class extends si{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,this.getData=this._getData,this.on=this._on}_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(jl).getOnlineUsersOnCurrentDocument()}catch(o){return this.getService(y).catch("Error in _getOnlineUsersOnCurrentDocument: ",o),se(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(jl).setInactivityTime(o)}catch(n){this.getService(y).catch("Error in setInactivityTime: ",n)}}_disableFlockMode(){try{this.trackEvent(Z.Events.Presence.DISABLE_FLOCK_MODE_TRIGGERED),this.getService(jc).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(jc).enableFlockMode(o)}catch(n){this.getService(y).catch("Error in _enableFlockMode: ",n)}}_stopFollowingUser(){try{this.trackEvent(Z.Events.Presence.STOP_FOLLOWING_USER_TRIGGERED),this.getService(jc).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 n=this.getService(jl).getPresenceUserFromExternalId(o);return n&&n.userSnippylyId&&n.name!==void 0?(this.getService(jc).startFollowingUser(n.userSnippylyId,n.name),{success:!0,msg:"Joined flock session."}):{success:!1,msg:"User could not be found."}}catch(n){return this.getService(y).catch("Error in _startFollowingUser: ",n),{success:!1,msg:"Unknown error.",raw:n}}}_enableSelf(){try{this.trackEvent(Z.Events.Presence.ENABLE_SELF_TRIGGERED),this.getService(jl).enableIncludeSelf()}catch(o){this.getService(y).catch("Error in _enableSelf: ",o)}}_disableSelf(){try{this.trackEvent(Z.Events.Presence.DISABLE_SELF_TRIGGERED),this.getService(jl).disableIncludeSelf()}catch(o){this.getService(y).catch("Error in _disableSelf: ",o)}}_getData(o){this.getService(y).log("%c[WB] Calling FUNCTION: getData","color: green;");try{return this.trackEvent(Z.Events.Presence.GET_PRESENCE_DATA_TRIGGERED,{payload:{query:o}}),o&&typeof o=="object"&&(o=I({},o),o?.documentId&&(o.documentId=na(o.documentId)),o?.organizationId&&(o.organizationId=La(o.organizationId))),this.getService(kz).getData(o)}catch(n){return this.getService(y).catch("Error in _getData: ",n),se({data:null})}}_on(o){this.getService(y).log("%c[WB] Calling FUNCTION: on","color: green;");try{return this.trackEvent(Z.Events.Presence.ON_ACTION_TRIGGERED,{payload:{action:o}}),this.getService(kz).onAction(o)}catch(n){return this.getService(y).catch("Error in _on: ",n),se(null)}}};var a9=class extends si{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(rr).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(rr).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(rr).setCustomReactions(o)}catch(n){this.getService(y).catch("Error in _setCustomReactions: ",n)}}};var dg=(()=>{let o=class o{constructor(e,t,r){this.loggingService=e,this.recorderAnnotationService=t,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(Nl.TRANSCRIPTION_DONE,e)}catch(t){this.loggingService.catch("Error in RecorderActionsService onTranscriptionDone: ",t)}}onRecordingDone(e){try{this.triggerAction(Nl.RECORDING_DONE,e)}catch(t){this.loggingService.catch("Error in RecorderActionsService onRecordingDone: ",t)}}onRecordingEditDone(e){try{this.triggerAction(Nl.RECORDING_EDIT_DONE,e)}catch(t){this.loggingService.catch("Error in RecorderActionsService onRecordingEditDone: ",t)}}onRecordingStarted(e){try{this.triggerAction(Nl.RECORDING_STARTED,e)}catch(t){this.loggingService.catch("Error in RecorderActionsService onRecordingStarted: ",t)}}onRecordingPaused(e){try{this.triggerAction(Nl.RECORDING_PAUSED,e)}catch(t){this.loggingService.catch("Error in RecorderActionsService onRecordingPaused: ",t)}}onRecordingCancelled(e){try{this.triggerAction(Nl.RECORDING_CANCELLED,e)}catch(t){this.loggingService.catch("Error in RecorderActionsService onRecordingCancelled: ",t)}}onRecordingStopped(e){try{this.triggerAction(Nl.RECORDING_STOPPED,e)}catch(t){this.loggingService.catch("Error in RecorderActionsService onRecordingStopped: ",t)}}onRecordingResumed(e){try{this.triggerAction(Nl.RECORDING_RESUMED,e)}catch(t){this.loggingService.catch("Error in RecorderActionsService onRecordingResumed: ",t)}}onDeleteRecording(e){try{this.triggerAction(Nl.DELETE_RECORDING,e)}catch(t){this.loggingService.catch("Error in RecorderActionsService onDeleteRecording: ",t)}}onError(e){try{this.triggerAction(Nl.ERROR,e)}catch(t){this.loggingService.catch("Error in RecorderActionsService onError: ",t)}}onRecordingSaveInitiated(e){try{this.triggerAction(Nl.RECORDING_SAVE_INITIATED,e)}catch(t){this.loggingService.catch("Error in RecorderActionsService onRecordingSaveInitiated: ",t)}}triggerAction(e,t){try{this.actionSubjects.has(e)||this.actionSubjects.set(e,new tt),this.actionSubjects.get(e)?.next(t)}catch(r){this.loggingService.catch("Error in RecorderActionsService triggerAction: ",r)}}onAction(e){try{return this.actionSubjects.has(e)||this.actionSubjects.set(e,new tt),this.actionSubjects.get(e)?.asObservable()}catch(t){return this.loggingService.catch("Error in RecorderActionsService onAction: ",t),se(null)}}};o.\u0275fac=function(t){return new(t||o)(ee(y),ee(Yi),ee(bn))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var s9=class extends si{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.deleteRecordings=this._deleteRecordings,this.setRecordingQualityConstraints=this._setRecordingQualityConstraints,this.setRecordingEncodingOptions=this._setRecordingEncodingOptions,this.downloadLatestVideo=this._downloadLatestVideo,this.enableRecordingMic=this._enableRecordingMic,this.disableRecordingMic=this._disableRecordingMic,this.enableOnboardingTooltip=this._enableOnboardingTooltip,this.disableOnboardingTooltip=this._disableOnboardingTooltip,this.enableRetakeOnVideoEditor=this._enableRetakeOnVideoEditor,this.disableRetakeOnVideoEditor=this._disableRetakeOnVideoEditor,this.askDevicePermission=this._askDevicePermission,this.setMaxLength=this._setMaxLength,this.openPictureInPicture=this._openPictureInPicture,this.exitPictureInPicture=this._exitPictureInPicture,this.requestScreenPermission=this._requestScreenPermission,this.enablePictureInPicture=this._enablePictureInPicture,this.disablePictureInPicture=this._disablePictureInPicture,this.on=this._on}_initRecording(o,n){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:n}}),this.getService(bn).initRecording(o,n)}catch(e){return this.getService(y).catch("Error in _initRecording: ",e),se(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(bn).onRecordedData()}catch(o){return this.getService(y).catch("Error in _onRecordedData: ",o),se(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(Yi).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(Yi).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(bn).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(bn).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(Yi).getRecorderDataByRecorderId(o)}catch(n){return this.getService(y).catch("Error in _getRecordingDataByRecorderId: ",n),se(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(Yi).getRecordings(o)}catch(n){return this.getService(y).catch("Error in _getRecordings: ",n),se([])}}_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(Yi).getRecorderDataByRecorderIds(o)}catch(n){return this.getService(y).catch("Error in _getRecordingData: ",n),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(Yi).fetchRecorderDataByRecorderIds(o)}catch(n){return this.getService(y).catch("Error in _fetchRecordings: ",n),Promise.resolve([])}}_deleteRecordings(o){this.getService(y).log("%c[WB] Calling FUNCTION: deleteRecording","color: green;");try{return this.trackEvent(Z.Events.Recording.DELETE_RECORDING_TRIGGERED,{payload:{query:o}}),this.getService(Yi).deleteRecorderDataByRecorderIds(o)}catch(n){return this.getService(y).catch("Error in _deleteRecording: ",n),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(Yi).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(Yi).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(dg).onAction(o)}catch(n){return this.getService(y).catch("Error in _on: ",n),se(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(bn).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(bn).disableVideoEditor()}catch(o){this.getService(y).catch("Error in _disableVideoEditor: ",o)}}_setRecordingQualityConstraints(o){this.getService(y).log("%c[WB] Calling FUNCTION: setRecordingQualityConstraints","color: green;");try{this.trackEvent(Z.Events.Recording.SET_RECORDING_QUALITY_CONSTRAINTS_TRIGGERED,{payload:{constraints:o}}),this.getService(bn).setRecordingQualityConstraints(o)}catch(n){this.getService(y).catch("Error in _setRecordingQualityConstraints: ",n)}}_setRecordingEncodingOptions(o){this.getService(y).log("%c[WB] Calling FUNCTION: setRecordingEncodingOptions","color: green;");try{this.trackEvent(Z.Events.Recording.SET_RECORDING_ENCODING_OPTIONS_TRIGGERED,{payload:{options:o}}),this.getService(bn).setRecordingEncodingOptions(o)}catch(n){this.getService(y).catch("Error in _setRecordingEncodingOptions: ",n)}}_downloadLatestVideo(o){this.getService(y).log("%c[WB] Calling FUNCTION: downloadLatestVideo","color: green;");try{return this.trackEvent(Z.Events.Recording.DOWNLOAD_LATEST_VIDEO_TRIGGERED,{payload:{recorderId:o}}),this.getService(Yi).downloadLatestVideo(o)}catch(n){return this.getService(y).catch("Error in _downloadLatestVideo: ",n),Promise.resolve(!1)}}_enableRecordingMic(){this.getService(y).log("%c[WB] Calling FUNCTION: enableRecordingMic","color: green;");try{this.trackEvent(Z.Events.Recording.ENABLE_RECORDING_MIC_TRIGGERED),this.getService(bn).enableRecordingMic()}catch(o){this.getService(y).catch("Error in _enableRecordingMic: ",o)}}_disableRecordingMic(){this.getService(y).log("%c[WB] Calling FUNCTION: disableRecordingMic","color: green;");try{this.trackEvent(Z.Events.Recording.DISABLE_RECORDING_MIC_TRIGGERED),this.getService(bn).disableRecordingMic()}catch(o){this.getService(y).catch("Error in _disableRecordingMic: ",o)}}_enableOnboardingTooltip(){this.getService(y).log("%c[WB] Calling FUNCTION: enableOnboardingTooltip","color: green;");try{this.trackEvent(Z.Events.Recording.ENABLE_ONBOARDING_TOOLTIP_TRIGGERED),this.getService(bn).enableOnboardingTooltip()}catch(o){this.getService(y).catch("Error in _enableOnboardingTooltip: ",o);return}}_disableOnboardingTooltip(){this.getService(y).log("%c[WB] Calling FUNCTION: disableOnboardingTooltip","color: green;");try{this.trackEvent(Z.Events.Recording.DISABLE_ONBOARDING_TOOLTIP_TRIGGERED),this.getService(bn).disableOnboardingTooltip()}catch(o){this.getService(y).catch("Error in _disableOnboardingTooltip: ",o);return}}_enableRetakeOnVideoEditor(){this.getService(y).log("%c[WB] Calling FUNCTION: enableRetakeOnVideoEditor","color: green;");try{this.trackEvent(Z.Events.Recording.ENABLE_RETAKE_ON_VIDEO_EDITOR_TRIGGERED),this.getService(bn).enableRetakeOnVideoEditor()}catch(o){this.getService(y).catch("Error in _enableRetakeOnVideoEditor: ",o)}}_disableRetakeOnVideoEditor(){this.getService(y).log("%c[WB] Calling FUNCTION: disableRetakeOnVideoEditor","color: green;");try{this.trackEvent(Z.Events.Recording.DISABLE_RETAKE_ON_VIDEO_EDITOR_TRIGGERED),this.getService(bn).disableRetakeOnVideoEditor()}catch(o){this.getService(y).catch("Error in _disableRetakeOnVideoEditor: ",o)}}_askDevicePermission(o){this.getService(y).log("%c[WB] Calling FUNCTION: askDevicePermission","color: green;");try{this.trackEvent(Z.Events.Recording.ASK_DEVICE_PERMISSION_TRIGGERED),this.getService(bn).askDevicePermission(o)}catch(n){this.getService(y).catch("Error in _askDevicePermission: ",n)}}_setMaxLength(o){this.getService(y).log("%c[WB] Calling FUNCTION: setMaxLength","color: green;");try{this.trackEvent(Z.Events.Recording.SET_MAX_LENGTH_TRIGGERED,{payload:{seconds:o}}),this.getService(bn).setMaxRecordingLength(o)}catch(n){this.getService(y).catch("Error in _setMaxLength: ",n)}}_openPictureInPicture(){return Q(this,null,function*(){this.getService(y).log("%c[WB] Calling FUNCTION: openPictureInPicture","color: green;");try{this.trackEvent(Z.Events.Recording.OPEN_PICTURE_IN_PICTURE_TRIGGERED),yield this.getService(bn).openPictureInPicture()}catch(o){this.getService(y).catch("Error in _openPictureInPicture: ",o)}})}_exitPictureInPicture(){return Q(this,null,function*(){this.getService(y).log("%c[WB] Calling FUNCTION: exitPictureInPicture","color: green;");try{this.trackEvent(Z.Events.Recording.EXIT_PICTURE_IN_PICTURE_TRIGGERED),yield this.getService($a).exitPictureInPicture()}catch(o){this.getService(y).catch("Error in _exitPictureInPicture: ",o)}})}_requestScreenPermission(){return Q(this,null,function*(){this.getService(y).log("%c[WB] Calling FUNCTION: requestScreenPermission","color: green;");try{return this.trackEvent(Z.Events.Recording.REQUEST_SCREEN_PERMISSION_TRIGGERED),this.getService(bn).requestScreenPermission()}catch(o){return this.getService(y).catch("Error in _requestScreenPermission: ",o),null}})}_enablePictureInPicture(){this.getService(y).log("%c[WB] Calling FUNCTION: enablePictureInPicture","color: green;");try{this.trackEvent(Z.Events.Recording.ENABLE_PICTURE_IN_PICTURE_TRIGGERED),this.getService($a).enablePictureInPicture()}catch(o){this.getService(y).catch("Error in _enablePictureInPicture: ",o)}}_disablePictureInPicture(){this.getService(y).log("%c[WB] Calling FUNCTION: disablePictureInPicture","color: green;");try{this.trackEvent(Z.Events.Recording.DISABLE_PICTURE_IN_PICTURE_TRIGGERED),this.getService($a).disablePictureInPicture()}catch(o){this.getService(y).catch("Error in _disablePictureInPicture: ",o)}}};var $c=(()=>{let o=class o{constructor(e,t,r,a,s,c){this.analyticsService=e,this.authService=t,this.configService=r,this.domService=a,this.loggingService=s,this.functions=c,this.rewriterAnnotations$=new ve([]),this.rewriterOptions$=new ve({}),this.rewriterEnabled$=new ve(!1),this.lastOpenAIPromptCalledAt=0,this.getRewriterEnabled$().subscribe(p=>{try{if(p){let u=document.querySelectorAll(j.TAGS.SNIPPYLY_REWRITER);if(!document.querySelectorAll(j.TAGS.VELT_REWRITER)?.length&&!u?.length){let E=document.createElement(j.TAGS.VELT_REWRITER);document.body.appendChild(E),this.authService.getUser$().pipe(Le(D=>!!D),st(1)).subscribe(D=>{this.analyticsService.trackEvent(Z.Events.Rewriter.REWRITER_ENABLED,{isMobileDevice:this.domService.isMobileDevice()})})}}else{let u=document.querySelectorAll(j.TAGS.SNIPPYLY_REWRITER);u?.length&&u.forEach(E=>{E.remove()});let C=document.querySelectorAll(j.TAGS.VELT_REWRITER);C?.length&&C.forEach(E=>{E.remove()})}}catch(u){this.loggingService.catch("Error in rewriterEnabled$: ",u)}},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),se([])}}addRewriter(e,t,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 Sk;s.from=a,s.color=j.DEFAULT_ANNOTATION_COLOR,t&&(s.targetTextRange=t),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 t=this.rewriterAnnotations$.getValue();t.push(e),this.rewriterAnnotations$.next(t),this.domService.toggleAnnotationSelection(e)}catch(t){this.loggingService.catch("Error in RewriterService saveRewriterToDb: ",t)}}removeRewriter(e){try{let t=this.rewriterAnnotations$.getValue(),r=t.findIndex(a=>a.annotationId===e.annotationId);r>-1&&(t.splice(r,1),this.rewriterAnnotations$.next(t))}catch(t){this.loggingService.catch("Error in RewriterService removeRewriter: ",t)}}getRewriterOptions(e,t,r){try{if(this.lastOpenAIPromptCalledAt&&Date.now()-this.lastOpenAIPromptCalledAt<1e3)return this.lastOpenAIPromptCalledAt=Date.now(),se([]);this.lastOpenAIPromptCalledAt=Date.now();let a=br(this.functions,Er({url:oi.cloudFunction.chatgptCompletion,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:20*60*1e3}),s=t?.[0]?.role==="system"?t?.[0]?.content:null;return this.analyticsService.trackEvent(Z.Events.Rewriter.REWRITE_PROMPT_SUBMITTED,{isMobileDevice:this.domService.isMobileDevice(),prompt:s,type:e}),Zi(a({messages:t,type:e,apiKey:this.configService.getApiKey(),sdkVersion:ia(),sdkType:this.configService.getSdkType()})).pipe(ce(c=>c?.data?c.data:[]))}catch(a){return this.loggingService.catch("Error in RewriterService getRewriterOptions: ",a),se([])}}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),se(!1)}}resetRewriter(){try{this.domService.resetSelectedAnnotationsMap(!1,"rewriter"),this.rewriterAnnotations$.next([])}catch(e){this.loggingService.catch("Error in RewriterService resetRewriter: ",e)}}getChatGPTInput(e,t,r=[]){try{let a="";return e&&(a=`
476
476
  ${a}