@veltdev/sdk-staging 4.5.0-beta.32 → 4.5.0-beta.33
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/velt.js +2 -2
package/velt.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var SNIPPYLY_VERSION = '4.5.0-beta.
|
|
1
|
+
var SNIPPYLY_VERSION = '4.5.0-beta.33';
|
|
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 yve=Object.create;var ZD=Object.defineProperty,Sve=Object.defineProperties,bve=Object.getOwnPropertyDescriptor,Ive=Object.getOwnPropertyDescriptors,Eve=Object.getOwnPropertyNames,KD=Object.getOwnPropertySymbols,jz=Object.getPrototypeOf,U9=Object.prototype.hasOwnProperty,$z=Object.prototype.propertyIsEnumerable,xve=Reflect.get;var Uz=(n,o,t)=>o in n?ZD(n,o,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[o]=t,I=(n,o)=>{for(var t in o||={})U9.call(o,t)&&Uz(n,t,o[t]);if(KD)for(var t of KD(o))$z.call(o,t)&&Uz(n,t,o[t]);return n},T=(n,o)=>Sve(n,Ive(o));var j9=(n,o)=>{var t={};for(var e in n)U9.call(n,e)&&o.indexOf(e)<0&&(t[e]=n[e]);if(n!=null&&KD)for(var e of KD(n))o.indexOf(e)<0&&$z.call(n,e)&&(t[e]=n[e]);return t};var Tve=(n,o)=>()=>(o||n((o={exports:{}}).exports,o),o.exports),XD=(n,o)=>{for(var t in o)ZD(n,t,{get:o[t],enumerable:!0})},Dve=(n,o,t,e)=>{if(o&&typeof o=="object"||typeof o=="function")for(let i of Eve(o))!U9.call(n,i)&&i!==t&&ZD(n,i,{get:()=>o[i],enumerable:!(e=bve(o,i))||e.enumerable});return n};var Hz=(n,o,t)=>(t=n!=null?yve(jz(n)):{},Dve(o||!n||!n.__esModule?ZD(t,"default",{value:n,enumerable:!0}):t,n));var Vd=(n,o,t)=>xve(jz(n),t,o);var te=(n,o,t)=>new Promise((e,i)=>{var r=c=>{try{s(t.next(c))}catch(p){i(p)}},a=c=>{try{s(t.throw(c))}catch(p){i(p)}},s=c=>c.done?e(c.value):Promise.resolve(c.value).then(r,a);s((t=t.apply(n,o)).next())});var rz=Tve((iJi,oz)=>{"use strict";var _t={};_t.generateIdentifier=function(){return Math.random().toString(36).substring(2,12)};_t.localCName=_t.generateIdentifier();_t.splitLines=function(n){return n.trim().split(`
|
|
@@ -192,7 +192,7 @@ This typically indicates that your device does not have a healthy Internet conne
|
|
|
192
192
|
<img src="${o||this.thumbnailWithPlayIconUrl||this.thumbnailUrl}" />
|
|
193
193
|
</a>
|
|
194
194
|
`}};var Up=class{constructor(){this.type="recorder",this.recordingType="audio",this.mode="floating",this.attachment=null,this.attachments=[],this.pageInfo=new Qi}};var FM=class{constructor(){this.type="rewriter",this.rewriterType="copywriter",this.pageInfo=new Qi}};var GS=class{constructor(){this.screenWidth=0,this.screenHeight=0,this.screenScrollHeight=0}};var jp=class{constructor(){this.pageInfo=new Qi}},WS=function(n){return n.Start="start",n.End="end",n}(WS||{}),Wv=function(n){return n.Avatar="avatar",n.Label="label",n}(Wv||{});var LM=class{constructor(){this.sources=[],this.playerState=new qS}},qS=class{constructor(){this.volume=1}};var YS=class{constructor(){this.to=[],this.resolved=!1,this.type="tag",this.pageInfo=new Qi}};var $p=class{constructor(){this.visibility="private"}};var BM=class{constructor(){this.reactions=[],this.type="reaction",this.pageInfo=new Qi,this.isReactionResolverUsed=!1}};var VM=class{};var jt=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.analyticsService=i,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);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(),mt.logsEnabled=r},r=>{this.loggingService.catch("Error in ConfigService logsEnabled$: ",r)})}catch(r){this.loggingService.catch("Error in ConfigService constructor: ",r)}}initConfig(e){try{e.featureAllowList?.length||(e.featureAllowList=Object.values(Re)),this.baseFeatureAllowList=e.featureAllowList?.slice(),this.config$.next(e)}catch(i){this.loggingService.catch("Error in ConfigService initConfig: ",i)}}setApiKey(e){this.apiKey$.next(e)}getApiKey(){return this.apiKey$.value}getApiKey$(){return this.apiKey$.asObservable()}getConfig(){return this.config$.value}getConfig$(){return this.config$.asObservable()}disableFeatures(e){try{let i=this.config$.value;i&&(e?.length?i.featureAllowList=this.baseFeatureAllowList.filter(r=>!e.includes(r)):i.featureAllowList=this.baseFeatureAllowList.slice()),this.config$.next(i)}catch(i){this.loggingService.catch("Error in ConfigService disableFeatures: ",i)}}setSF(e){try{this.sf$.next(e),this.analyticsService.setSF(e)}catch(i){this.loggingService.catch("Error in ConfigService setSF: ",i)}}getSF(){try{return this.sf$.value}catch(e){return this.loggingService.catch("Error in ConfigService getSF: ",e),!1}}getSF$(){try{return this.sf$.asObservable()}catch(e){return this.loggingService.catch("Error in ConfigService getSF$: ",e),re(!1)}}setSdkType(e){try{this.sdkType$.next(e)}catch(i){this.loggingService.catch("Error in ConfigService setSdkType: ",i)}}getSdkType(){try{return this.sdkType$.value}catch(e){return this.loggingService.catch("Error in ConfigService getSdkType: ",e),"core"}}getSdkType$(){try{return this.sdkType$.asObservable()}catch(e){return this.loggingService.catch("Error in ConfigService getSdkType$: ",e),re("core")}}enableLogs(){try{if(this.logsEnabled$.value===!0)return;this.logsEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in ConfigService enableLogs: ",e)}}disableLogs(e){try{e&&this.disableLogsConfig$.next({warnings:e.warnings??!0,suppressAll:e.suppressAll??!1}),e?.warnings!==!1&&this.logsEnabled$.next(!1)}catch(i){this.loggingService.catch("Error in ConfigService disableLogs: ",i)}}getDisableLogsConfig(){return this.disableLogsConfig$.value}getDisableLogsConfig$(){return this.disableLogsConfig$.asObservable()}getApiProxyDomain(){try{return this.config$.value?.apiProxyDomain}catch(e){this.loggingService.catch("Error in ConfigService getApiProxyDomain: ",e);return}}};o.\u0275fac=function(i){return new(i||o)(Q(y),Q(Ke))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var hse=(()=>{let o=class o{constructor(e){this.loggingService=e,this.initLocalStorageData()}initLocalStorageData(){this.loggingService.log("%c[WB] Calling FUNCTION: initLocalStorageData","color: green;"),this.getLocalStorageData(),this.getSessionStorageData()}getLocalStorageData(){this.loggingService.log("%c[WB] Calling FUNCTION: getLocalStorageData","color: green;");try{let e=localStorage?.getItem(U.LOCALSTORAGE_DATA_ID);if(e)return JSON.parse(e);{let i=new Qu;return this.setLocalStorageData(i),i}}catch(e){return this.loggingService.catch("Error in getLocalStorageData:",e),new Qu}}setLocalStorageData(e){this.loggingService.log("%c[WB] Calling FUNCTION: setLocalStorageData","color: green;");try{if(e){let i=JSON.stringify(e);localStorage?.setItem(U.LOCALSTORAGE_DATA_ID,i)}}catch(i){this.loggingService.catch("Error in setLocalStorageData:",i)}}deleteLocalStorageData(){this.loggingService.log("%c[WB] Calling FUNCTION: deleteLocalStorageData","color: green;"),localStorage?.removeItem(U.LOCALSTORAGE_DATA_ID)}getSessionStorageData(){this.loggingService.log("%c[WB] Calling FUNCTION: getSessionStorageData","color: green;");try{let e=sessionStorage?.getItem(U.LOCALSTORAGE_DATA_ID);if(e)return JSON.parse(e);{let i=new Qu;return this.setSessionStorageData(i),i}}catch(e){return this.loggingService.catch("Error in getSessionStorageData:",e),new Qu}}setSessionStorageData(e){this.loggingService.log("%c[WB] Calling FUNCTION: setSessionStorageData","color: green;");try{if(e){let i=JSON.stringify(e);sessionStorage?.setItem(U.LOCALSTORAGE_DATA_ID,i)}}catch(i){this.loggingService.catch("Error in setSessionStorageData:",i)}}deleteSessionStorageData(){this.loggingService.log("%c[WB] Calling FUNCTION: deleteSessionStorageData","color: green;");try{sessionStorage?.removeItem(U.LOCALSTORAGE_DATA_ID)}catch(e){this.loggingService.catch("Error in deleteSessionStorageData:",e)}}};o.\u0275fac=function(i){return new(i||o)(Q(y))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var bm=(()=>{let o=class o{constructor(e,i){this.localStorageService=e,this.loggingService=i,this.avatarList=[{userId:"1",name:"Bear",photoUrl:"https://snippyly.com/assets/avatars/avatar-bear.svg",type:"anonymous"},{userId:"2",name:"Beaver",photoUrl:"https://snippyly.com/assets/avatars/avatar-beaver.svg",type:"anonymous"},{userId:"3",name:"Bunny",photoUrl:"https://snippyly.com/assets/avatars/avatar-bunny.svg",type:"anonymous"},{userId:"4",name:"Cat",photoUrl:"https://snippyly.com/assets/avatars/avatar-cat.svg",type:"anonymous"},{userId:"5",name:"Cow",photoUrl:"https://snippyly.com/assets/avatars/avatar-cow.svg",type:"anonymous"},{userId:"6",name:"Dinosaur",photoUrl:"https://snippyly.com/assets/avatars/avatar-dinosaur.svg",type:"anonymous"},{userId:"7",name:"Elephant",photoUrl:"https://snippyly.com/assets/avatars/avatar-elephant.svg",type:"anonymous"},{userId:"8",name:"Monkey",photoUrl:"https://snippyly.com/assets/avatars/avatar-monkey.svg",type:"anonymous"},{userId:"9",name:"Hedgehog",photoUrl:"https://snippyly.com/assets/avatars/avatar-hedgehog.svg",type:"anonymous"},{userId:"10",name:"Hippo",photoUrl:"https://snippyly.com/assets/avatars/avatar-hippo.svg",type:"anonymous"},{userId:"11",name:"Horse",photoUrl:"https://snippyly.com/assets/avatars/avatar-horse.svg",type:"anonymous"},{userId:"12",name:"Kitten",photoUrl:"https://snippyly.com/assets/avatars/avatar-kitten.svg",type:"anonymous"},{userId:"13",name:"Octopus",photoUrl:"https://snippyly.com/assets/avatars/avatar-octopus.svg",type:"anonymous"},{userId:"14",name:"Oink",photoUrl:"https://snippyly.com/assets/avatars/avatar-oink.svg",type:"anonymous"},{userId:"15",name:"Panda",photoUrl:"https://snippyly.com/assets/avatars/avatar-panda.svg",type:"anonymous"},{userId:"16",name:"Penguin",photoUrl:"https://snippyly.com/assets/avatars/avatar-penguin.svg",type:"anonymous"},{userId:"17",name:"Rabbit",photoUrl:"https://snippyly.com/assets/avatars/avatar-rabbit.svg",type:"anonymous"},{userId:"18",name:"Tiger",photoUrl:"https://snippyly.com/assets/avatars/avatar-tiger.svg",type:"anonymous"}],this.loggingService.log("%c[WB] Creating SERVICE AvatarService","color: blue;")}getSessionAvatar(){this.loggingService.log("%c[WB] Calling FUNCTION: getSessionAvatar","color: green;");try{let e=new Do,i=this.localStorageService.getSessionStorageData();if(i.snippylyAvatar)e=i.snippylyAvatar;else{let r=this.generateUserAvatar();i.snippylyAvatar=r,this.localStorageService.setSessionStorageData(i)}return e}catch(e){return this.loggingService.catch("Error in getSessionAvatar:",e),new Do}}generateUserAvatar(){this.loggingService.log("%c[WB] Calling FUNCTION: generateUserAvatar","color: green;");try{let e=Math.floor(Math.random()*this.avatarList.length),i=this.avatarList[e];return i.color=this.generateUserColor(),i}catch(e){return this.loggingService.catch("Error in generateUserAvatar:",e),this.avatarList[0]}}generateUserColor(e){this.loggingService.log("%c[WB] Calling FUNCTION: generateUserColor","color: green;");try{if(e)return U.AVATAR_COLOR_LIST[e%U.AVATAR_COLOR_LIST.length];let i=Math.floor(Math.random()*U.AVATAR_COLOR_LIST.length);return U.AVATAR_COLOR_LIST[i]}catch(i){return this.loggingService.catch("Error in generateUserColor:",i),""}}generateUserImage(){this.loggingService.log("%c[WB] Calling FUNCTION: generateUserImage","color: green;");try{return this.getSessionAvatar().photoUrl}catch(e){return this.loggingService.catch("Error in generateUserImage:",e),""}}};o.\u0275fac=function(i){return new(i||o)(Q(hse),Q(y))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Hp=(()=>{let o=class o{constructor(e){this.loggingService=e,this.actionSubjects=new Map,this.subscriptions=[]}triggerAction(e,i){try{this.actionSubjects.has(e)||this.actionSubjects.set(e,new Xe),this.actionSubjects.get(e)?.next(i)}catch(r){this.loggingService.catch("Error in CoreActionsService triggerAction: ",r)}}onAction(e){try{return this.actionSubjects.has(e)||this.actionSubjects.set(e,new Xe),this.actionSubjects.get(e)?.asObservable()}catch(i){return this.loggingService.catch("Error in CoreActionsService onAction: ",i),re(null)}}};o.\u0275fac=function(i){return new(i||o)(Q(y))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var{entries:xse,setPrototypeOf:fse,isFrozen:i9e,getPrototypeOf:o9e,getOwnPropertyDescriptor:r9e}=Object,{freeze:Za,seal:Il,create:Tse}=Object,{apply:O$,construct:A$}=typeof Reflect<"u"&&Reflect;Za||(Za=function(o){return o});Il||(Il=function(o){return o});O$||(O$=function(o,t,e){return o.apply(t,e)});A$||(A$=function(o,t){return new o(...t)});var UM=Xa(Array.prototype.forEach),a9e=Xa(Array.prototype.lastIndexOf),vse=Xa(Array.prototype.pop),ZS=Xa(Array.prototype.push),s9e=Xa(Array.prototype.splice),$M=Xa(String.prototype.toLowerCase),E$=Xa(String.prototype.toString),Cse=Xa(String.prototype.match),XS=Xa(String.prototype.replace),l9e=Xa(String.prototype.indexOf),c9e=Xa(String.prototype.trim),yc=Xa(Object.prototype.hasOwnProperty),Ka=Xa(RegExp.prototype.test),QS=m9e(TypeError);function Xa(n){return function(o){o instanceof RegExp&&(o.lastIndex=0);for(var t=arguments.length,e=new Array(t>1?t-1:0),i=1;i<t;i++)e[i-1]=arguments[i];return O$(n,o,e)}}function m9e(n){return function(){for(var o=arguments.length,t=new Array(o),e=0;e<o;e++)t[e]=arguments[e];return A$(n,t)}}function ni(n,o){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:$M;fse&&fse(n,null);let e=o.length;for(;e--;){let i=o[e];if(typeof i=="string"){let r=t(i);r!==i&&(i9e(o)||(o[e]=r),i=r)}n[i]=!0}return n}function d9e(n){for(let o=0;o<n.length;o++)yc(n,o)||(n[o]=null);return n}function Ju(n){let o=Tse(null);for(let[t,e]of xse(n))yc(n,t)&&(Array.isArray(e)?o[t]=d9e(e):e&&typeof e=="object"&&e.constructor===Object?o[t]=Ju(e):o[t]=e);return o}function JS(n,o){for(;n!==null;){let e=r9e(n,o);if(e){if(e.get)return Xa(e.get);if(typeof e.value=="function")return Xa(e.value)}n=o9e(n)}function t(){return null}return t}var _se=Za(["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"]),x$=Za(["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"]),T$=Za(["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"]),p9e=Za(["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"]),D$=Za(["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"]),g9e=Za(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),yse=Za(["#text"]),Sse=Za(["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"]),w$=Za(["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"]),bse=Za(["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"]),jM=Za(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),u9e=Il(/\{\{[\w\W]*|[\w\W]*\}\}/gm),h9e=Il(/<%[\w\W]*|[\w\W]*%>/gm),f9e=Il(/\$\{[\w\W]*/gm),v9e=Il(/^data-[\-\w.\u00B7-\uFFFF]+$/),C9e=Il(/^aria-[\-\w]+$/),Dse=Il(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),_9e=Il(/^(?:\w+script|data):/i),y9e=Il(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),wse=Il(/^html$/i),S9e=Il(/^[a-z][.\w]*(-[.\w]+)+$/i),Ise=Object.freeze({__proto__:null,ARIA_ATTR:C9e,ATTR_WHITESPACE:y9e,CUSTOM_ELEMENT:S9e,DATA_ATTR:v9e,DOCTYPE_NAME:wse,ERB_EXPR:h9e,IS_ALLOWED_URI:Dse,IS_SCRIPT_OR_DATA:_9e,MUSTACHE_EXPR:u9e,TMPLIT_EXPR:f9e}),eb={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,progressingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},b9e=function(){return typeof window>"u"?null:window},I9e=function(o,t){if(typeof o!="object"||typeof o.createPolicy!="function")return null;let e=null,i="data-tt-policy-suffix";t&&t.hasAttribute(i)&&(e=t.getAttribute(i));let r="dompurify"+(e?"#"+e:"");try{return o.createPolicy(r,{createHTML(a){return a},createScriptURL(a){return a}})}catch{return console.warn("TrustedTypes policy "+r+" could not be created."),null}},Ese=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function Ose(){let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:b9e(),o=Yt=>Ose(Yt);if(o.version="3.2.5",o.removed=[],!n||!n.document||n.document.nodeType!==eb.document||!n.Element)return o.isSupported=!1,o;let{document:t}=n,e=t,i=e.currentScript,{DocumentFragment:r,HTMLTemplateElement:a,Node:s,Element:c,NodeFilter:p,NamedNodeMap:u=n.NamedNodeMap||n.MozNamedAttrMap,HTMLFormElement:C,DOMParser:E,trustedTypes:A}=n,B=c.prototype,G=JS(B,"cloneNode"),K=JS(B,"remove"),pe=JS(B,"nextSibling"),Ce=JS(B,"childNodes"),Ie=JS(B,"parentNode");if(typeof a=="function"){let Yt=t.createElement("template");Yt.content&&Yt.content.ownerDocument&&(t=Yt.content.ownerDocument)}let $e,Ye="",{implementation:ke,createNodeIterator:Se,createDocumentFragment:De,getElementsByTagName:Pe}=t,{importNode:_e}=e,he=Ese();o.isSupported=typeof xse=="function"&&typeof Ie=="function"&&ke&&ke.createHTMLDocument!==void 0;let{MUSTACHE_EXPR:Le,ERB_EXPR:Ee,TMPLIT_EXPR:xn,DATA_ATTR:Ht,ARIA_ATTR:ut,IS_SCRIPT_OR_DATA:wt,ATTR_WHITESPACE:At,CUSTOM_ELEMENT:sn}=Ise,{IS_ALLOWED_URI:to}=Ise,oi=null,Ri=ni({},[..._se,...x$,...T$,...D$,...yse]),pn=null,Ci=ni({},[...Sse,...w$,...bse,...jM]),Ni=Object.seal(Tse(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),Vm=null,uo=null,Xs=!0,jr=!0,Qs=!1,Ml=!0,Tc=!1,pg=!0,Pl=!1,gg=!1,ph=!1,Um=!1,gh=!1,ug=!1,i_=!0,uh=!1,kD="user-content-",o_=!0,jm=!1,Dc={},wc=null,Dr=ni({},["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"]),$r=null,hg=ni({},["audio","video","img","source","image","track"]),hh=null,r_=ni({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),fh="http://www.w3.org/1998/Math/MathML",Oc="http://www.w3.org/2000/svg",Js="http://www.w3.org/1999/xhtml",$m=Js,fg=!1,a_=null,P9=ni({},[fh,Oc,Js],E$),Fd=ni({},["mi","mo","mn","ms","mtext"]),vg=ni({},["annotation-xml"]),RD=ni({},["title","style","font","a","script"]),kl=null,s_=["application/xhtml+xml","text/html"],l_="text/html",ho=null,Hm=null,vh=t.createElement("form"),c_=function(Be){return Be instanceof RegExp||Be instanceof Function},zm=function(){let Be=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(Hm&&Hm===Be)){if((!Be||typeof Be!="object")&&(Be={}),Be=Ju(Be),kl=s_.indexOf(Be.PARSER_MEDIA_TYPE)===-1?l_:Be.PARSER_MEDIA_TYPE,ho=kl==="application/xhtml+xml"?E$:$M,oi=yc(Be,"ALLOWED_TAGS")?ni({},Be.ALLOWED_TAGS,ho):Ri,pn=yc(Be,"ALLOWED_ATTR")?ni({},Be.ALLOWED_ATTR,ho):Ci,a_=yc(Be,"ALLOWED_NAMESPACES")?ni({},Be.ALLOWED_NAMESPACES,E$):P9,hh=yc(Be,"ADD_URI_SAFE_ATTR")?ni(Ju(r_),Be.ADD_URI_SAFE_ATTR,ho):r_,$r=yc(Be,"ADD_DATA_URI_TAGS")?ni(Ju(hg),Be.ADD_DATA_URI_TAGS,ho):hg,wc=yc(Be,"FORBID_CONTENTS")?ni({},Be.FORBID_CONTENTS,ho):Dr,Vm=yc(Be,"FORBID_TAGS")?ni({},Be.FORBID_TAGS,ho):{},uo=yc(Be,"FORBID_ATTR")?ni({},Be.FORBID_ATTR,ho):{},Dc=yc(Be,"USE_PROFILES")?Be.USE_PROFILES:!1,Xs=Be.ALLOW_ARIA_ATTR!==!1,jr=Be.ALLOW_DATA_ATTR!==!1,Qs=Be.ALLOW_UNKNOWN_PROTOCOLS||!1,Ml=Be.ALLOW_SELF_CLOSE_IN_ATTR!==!1,Tc=Be.SAFE_FOR_TEMPLATES||!1,pg=Be.SAFE_FOR_XML!==!1,Pl=Be.WHOLE_DOCUMENT||!1,Um=Be.RETURN_DOM||!1,gh=Be.RETURN_DOM_FRAGMENT||!1,ug=Be.RETURN_TRUSTED_TYPE||!1,ph=Be.FORCE_BODY||!1,i_=Be.SANITIZE_DOM!==!1,uh=Be.SANITIZE_NAMED_PROPS||!1,o_=Be.KEEP_CONTENT!==!1,jm=Be.IN_PLACE||!1,to=Be.ALLOWED_URI_REGEXP||Dse,$m=Be.NAMESPACE||Js,Fd=Be.MATHML_TEXT_INTEGRATION_POINTS||Fd,vg=Be.HTML_INTEGRATION_POINTS||vg,Ni=Be.CUSTOM_ELEMENT_HANDLING||{},Be.CUSTOM_ELEMENT_HANDLING&&c_(Be.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(Ni.tagNameCheck=Be.CUSTOM_ELEMENT_HANDLING.tagNameCheck),Be.CUSTOM_ELEMENT_HANDLING&&c_(Be.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(Ni.attributeNameCheck=Be.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),Be.CUSTOM_ELEMENT_HANDLING&&typeof Be.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(Ni.allowCustomizedBuiltInElements=Be.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),Tc&&(jr=!1),gh&&(Um=!0),Dc&&(oi=ni({},yse),pn=[],Dc.html===!0&&(ni(oi,_se),ni(pn,Sse)),Dc.svg===!0&&(ni(oi,x$),ni(pn,w$),ni(pn,jM)),Dc.svgFilters===!0&&(ni(oi,T$),ni(pn,w$),ni(pn,jM)),Dc.mathMl===!0&&(ni(oi,D$),ni(pn,bse),ni(pn,jM))),Be.ADD_TAGS&&(oi===Ri&&(oi=Ju(oi)),ni(oi,Be.ADD_TAGS,ho)),Be.ADD_ATTR&&(pn===Ci&&(pn=Ju(pn)),ni(pn,Be.ADD_ATTR,ho)),Be.ADD_URI_SAFE_ATTR&&ni(hh,Be.ADD_URI_SAFE_ATTR,ho),Be.FORBID_CONTENTS&&(wc===Dr&&(wc=Ju(wc)),ni(wc,Be.FORBID_CONTENTS,ho)),o_&&(oi["#text"]=!0),Pl&&ni(oi,["html","head","body"]),oi.table&&(ni(oi,["tbody"]),delete Vm.tbody),Be.TRUSTED_TYPES_POLICY){if(typeof Be.TRUSTED_TYPES_POLICY.createHTML!="function")throw QS('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof Be.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw QS('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');$e=Be.TRUSTED_TYPES_POLICY,Ye=$e.createHTML("")}else $e===void 0&&($e=I9e(A,i)),$e!==null&&typeof Ye=="string"&&(Ye=$e.createHTML(""));Za&&Za(Be),Hm=Be}},m_=ni({},[...x$,...T$,...p9e]),Hr=ni({},[...D$,...g9e]),ND=function(Be){let St=Ie(Be);(!St||!St.tagName)&&(St={namespaceURI:$m,tagName:"template"});let Gt=$M(Be.tagName),no=$M(St.tagName);return a_[Be.namespaceURI]?Be.namespaceURI===Oc?St.namespaceURI===Js?Gt==="svg":St.namespaceURI===fh?Gt==="svg"&&(no==="annotation-xml"||Fd[no]):!!m_[Gt]:Be.namespaceURI===fh?St.namespaceURI===Js?Gt==="math":St.namespaceURI===Oc?Gt==="math"&&vg[no]:!!Hr[Gt]:Be.namespaceURI===Js?St.namespaceURI===Oc&&!vg[no]||St.namespaceURI===fh&&!Fd[no]?!1:!Hr[Gt]&&(RD[Gt]||!m_[Gt]):!!(kl==="application/xhtml+xml"&&a_[Be.namespaceURI]):!1},va=function(Be){ZS(o.removed,{element:Be});try{Ie(Be).removeChild(Be)}catch{K(Be)}},Ac=function(Be,St){try{ZS(o.removed,{attribute:St.getAttributeNode(Be),from:St})}catch{ZS(o.removed,{attribute:null,from:St})}if(St.removeAttribute(Be),Be==="is")if(Um||gh)try{va(St)}catch{}else try{St.setAttribute(Be,"")}catch{}},FD=function(Be){let St=null,Gt=null;if(ph)Be="<remove></remove>"+Be;else{let Or=Cse(Be,/^[\r\n\t ]+/);Gt=Or&&Or[0]}kl==="application/xhtml+xml"&&$m===Js&&(Be='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+Be+"</body></html>");let no=$e?$e.createHTML(Be):Be;if($m===Js)try{St=new E().parseFromString(no,kl)}catch{}if(!St||!St.documentElement){St=ke.createDocument($m,"template",null);try{St.documentElement.innerHTML=fg?Ye:no}catch{}}let wr=St.body||St.documentElement;return Be&&Gt&&wr.insertBefore(t.createTextNode(Gt),wr.childNodes[0]||null),$m===Js?Pe.call(St,Pl?"html":"body")[0]:Pl?St.documentElement:wr},LD=function(Be){return Se.call(Be.ownerDocument||Be,Be,p.SHOW_ELEMENT|p.SHOW_COMMENT|p.SHOW_TEXT|p.SHOW_PROCESSING_INSTRUCTION|p.SHOW_CDATA_SECTION,null)},Mc=function(Be){return Be instanceof C&&(typeof Be.nodeName!="string"||typeof Be.textContent!="string"||typeof Be.removeChild!="function"||!(Be.attributes instanceof u)||typeof Be.removeAttribute!="function"||typeof Be.setAttribute!="function"||typeof Be.namespaceURI!="string"||typeof Be.insertBefore!="function"||typeof Be.hasChildNodes!="function")},BD=function(Be){return typeof s=="function"&&Be instanceof s};function Rl(Yt,Be,St){UM(Yt,Gt=>{Gt.call(o,Be,St,Hm)})}let Cg=function(Be){let St=null;if(Rl(he.beforeSanitizeElements,Be,null),Mc(Be))return va(Be),!0;let Gt=ho(Be.nodeName);if(Rl(he.uponSanitizeElement,Be,{tagName:Gt,allowedTags:oi}),Be.hasChildNodes()&&!BD(Be.firstElementChild)&&Ka(/<[/\w!]/g,Be.innerHTML)&&Ka(/<[/\w!]/g,Be.textContent)||Be.nodeType===eb.progressingInstruction||pg&&Be.nodeType===eb.comment&&Ka(/<[/\w]/g,Be.data))return va(Be),!0;if(!oi[Gt]||Vm[Gt]){if(!Vm[Gt]&&Ch(Gt)&&(Ni.tagNameCheck instanceof RegExp&&Ka(Ni.tagNameCheck,Gt)||Ni.tagNameCheck instanceof Function&&Ni.tagNameCheck(Gt)))return!1;if(o_&&!wc[Gt]){let no=Ie(Be)||Be.parentNode,wr=Ce(Be)||Be.childNodes;if(wr&&no){let Or=wr.length;for(let Ar=Or-1;Ar>=0;--Ar){let Ts=G(wr[Ar],!0);Ts.__removalCount=(Be.__removalCount||0)+1,no.insertBefore(Ts,pe(Be))}}}return va(Be),!0}return Be instanceof c&&!ND(Be)||(Gt==="noscript"||Gt==="noembed"||Gt==="noframes")&&Ka(/<\/no(script|embed|frames)/i,Be.innerHTML)?(va(Be),!0):(Tc&&Be.nodeType===eb.text&&(St=Be.textContent,UM([Le,Ee,xn],no=>{St=XS(St,no," ")}),Be.textContent!==St&&(ZS(o.removed,{element:Be.cloneNode()}),Be.textContent=St)),Rl(he.afterSanitizeElements,Be,null),!1)},d_=function(Be,St,Gt){if(i_&&(St==="id"||St==="name")&&(Gt in t||Gt in vh))return!1;if(!(jr&&!uo[St]&&Ka(Ht,St))){if(!(Xs&&Ka(ut,St))){if(!pn[St]||uo[St]){if(!(Ch(Be)&&(Ni.tagNameCheck instanceof RegExp&&Ka(Ni.tagNameCheck,Be)||Ni.tagNameCheck instanceof Function&&Ni.tagNameCheck(Be))&&(Ni.attributeNameCheck instanceof RegExp&&Ka(Ni.attributeNameCheck,St)||Ni.attributeNameCheck instanceof Function&&Ni.attributeNameCheck(St))||St==="is"&&Ni.allowCustomizedBuiltInElements&&(Ni.tagNameCheck instanceof RegExp&&Ka(Ni.tagNameCheck,Gt)||Ni.tagNameCheck instanceof Function&&Ni.tagNameCheck(Gt))))return!1}else if(!hh[St]){if(!Ka(to,XS(Gt,At,""))){if(!((St==="src"||St==="xlink:href"||St==="href")&&Be!=="script"&&l9e(Gt,"data:")===0&&$r[Be])){if(!(Qs&&!Ka(wt,XS(Gt,At,"")))){if(Gt)return!1}}}}}}return!0},Ch=function(Be){return Be!=="annotation-xml"&&Cse(Be,sn)},_g=function(Be){Rl(he.beforeSanitizeAttributes,Be,null);let{attributes:St}=Be;if(!St||Mc(Be))return;let Gt={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:pn,forceKeepAttr:void 0},no=St.length;for(;no--;){let wr=St[no],{name:Or,namespaceURI:Ar,value:Ts}=wr,Gm=ho(Or),ir=Or==="value"?Ts:c9e(Ts);if(Gt.attrName=Gm,Gt.attrValue=ir,Gt.keepAttr=!0,Gt.forceKeepAttr=void 0,Rl(he.uponSanitizeAttribute,Be,Gt),ir=Gt.attrValue,uh&&(Gm==="id"||Gm==="name")&&(Ac(Or,Be),ir=kD+ir),pg&&Ka(/((--!?|])>)|<\/(style|title)/i,ir)){Ac(Or,Be);continue}if(Gt.forceKeepAttr||(Ac(Or,Be),!Gt.keepAttr))continue;if(!Ml&&Ka(/\/>/i,ir)){Ac(Or,Be);continue}Tc&&UM([Le,Ee,xn],_h=>{ir=XS(ir,_h," ")});let kc=ho(Be.nodeName);if(d_(kc,Gm,ir)){if($e&&typeof A=="object"&&typeof A.getAttributeType=="function"&&!Ar)switch(A.getAttributeType(kc,Gm)){case"TrustedHTML":{ir=$e.createHTML(ir);break}case"TrustedScriptURL":{ir=$e.createScriptURL(ir);break}}try{Ar?Be.setAttributeNS(Ar,Or,ir):Be.setAttribute(Or,ir),Mc(Be)?va(Be):vse(o.removed)}catch{}}}Rl(he.afterSanitizeAttributes,Be,null)},Pc=function Yt(Be){let St=null,Gt=LD(Be);for(Rl(he.beforeSanitizeShadowDOM,Be,null);St=Gt.nextNode();)Rl(he.uponSanitizeShadowNode,St,null),Cg(St),_g(St),St.content instanceof r&&Yt(St.content);Rl(he.afterSanitizeShadowDOM,Be,null)};return o.sanitize=function(Yt){let Be=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},St=null,Gt=null,no=null,wr=null;if(fg=!Yt,fg&&(Yt="<!-->"),typeof Yt!="string"&&!BD(Yt))if(typeof Yt.toString=="function"){if(Yt=Yt.toString(),typeof Yt!="string")throw QS("dirty is not a string, aborting")}else throw QS("toString is not a function");if(!o.isSupported)return Yt;if(gg||zm(Be),o.removed=[],typeof Yt=="string"&&(jm=!1),jm){if(Yt.nodeName){let Ts=ho(Yt.nodeName);if(!oi[Ts]||Vm[Ts])throw QS("root node is forbidden and cannot be sanitized in-place")}}else if(Yt instanceof s)St=FD("<!---->"),Gt=St.ownerDocument.importNode(Yt,!0),Gt.nodeType===eb.element&&Gt.nodeName==="BODY"||Gt.nodeName==="HTML"?St=Gt:St.appendChild(Gt);else{if(!Um&&!Tc&&!Pl&&Yt.indexOf("<")===-1)return $e&&ug?$e.createHTML(Yt):Yt;if(St=FD(Yt),!St)return Um?null:ug?Ye:""}St&&ph&&va(St.firstChild);let Or=LD(jm?Yt:St);for(;no=Or.nextNode();)Cg(no),_g(no),no.content instanceof r&&Pc(no.content);if(jm)return Yt;if(Um){if(gh)for(wr=De.call(St.ownerDocument);St.firstChild;)wr.appendChild(St.firstChild);else wr=St;return(pn.shadowroot||pn.shadowrootmode)&&(wr=_e.call(e,wr,!0)),wr}let Ar=Pl?St.outerHTML:St.innerHTML;return Pl&&oi["!doctype"]&&St.ownerDocument&&St.ownerDocument.doctype&&St.ownerDocument.doctype.name&&Ka(wse,St.ownerDocument.doctype.name)&&(Ar="<!DOCTYPE "+St.ownerDocument.doctype.name+`>
|
|
195
|
-
`+Ar),Tc&&UM([Le,Ee,xn],Ts=>{Ar=XS(Ar,Ts," ")}),$e&&ug?$e.createHTML(Ar):Ar},o.setConfig=function(){let Yt=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};zm(Yt),gg=!0},o.clearConfig=function(){Hm=null,gg=!1},o.isValidAttribute=function(Yt,Be,St){Hm||zm({});let Gt=ho(Yt),no=ho(Be);return d_(Gt,no,St)},o.addHook=function(Yt,Be){typeof Be=="function"&&ZS(he[Yt],Be)},o.removeHook=function(Yt,Be){if(Be!==void 0){let St=a9e(he[Yt],Be);return St===-1?void 0:s9e(he[Yt],St,1)[0]}return vse(he[Yt])},o.removeHooks=function(Yt){he[Yt]=[]},o.removeAllHooks=function(){he=Ese()},o}var M$=Ose();var Ase={ADD_TAGS:["velt-skeleton-loader"],ADD_ATTR:["border-radius"]},Fe=(()=>{let o=class o{constructor(e,i,r){this.rendererFactory2=e,this.loggingService=i,this.sanitizer=r,this.isVideoEditorHandlingDelete=!1,this.pageScrollHeight=0,this.enableRectSelectionSubject$=new ve(!1),this.enableRectSelection$=this.enableRectSelectionSubject$.asObservable(),this.scrollableElementsIds$=new ve([]),this.mousedown=!1,this.windowMouseDown$=new Xe,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 Xe,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 ei),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=a=>{try{let s=[];return a.forEach(c=>{if(!Hi(c))if(c instanceof HTMLElement){if(c.className.includes("cdk-overlay-container")||c.className.includes("cdk-overlay-connected-position-bounding-box"))return;if(c.className.includes("cdk-overlay")){let p=!1;c.childNodes.forEach(u=>{Hi(u)&&(p=!0)}),p||s.push(c)}else s.push(c)}else s.push(c)}),s}catch(s){return this.loggingService.catch("Error in DomService filterSnippylyNodes: ",s),[]}},this.loggingService.log("%c[WB] Creating CLASS: DomService","color: blue;");try{this.renderer=this.rendererFactory2.createRenderer(null,null);let a=this.calculateScreenSize();this.currentScreenSize$=new ve(a),this.currentMousePosition$=new ve(this.currentMousePosition),this.detectNetworkStatusChange(),this.getScrollableElementsIds$().pipe(Ai(),gn(([s,c])=>{try{let p=c.filter(C=>!s.includes(C)),u=s.filter(C=>!c.includes(C));u.length&&u.map(E=>document.getElementById(E)).filter(E=>E).forEach(E=>{this.unlistenElementScroll&&this.unlistenElementScroll[E.id]&&this.unlistenElementScroll[E.id]()}),p.length&&p.map(E=>document.getElementById(E)).filter(E=>E).forEach(E=>{this.unlistenElementScroll[E.id]=this.renderer.listen(E,"scroll",A=>{let B=this.calculateScreenSize();this.currentScreenSize$.next(B)})})}catch(p){this.loggingService.catch("Error in DomService getScrollableElementsIds subscription: ",p)}})).subscribe(()=>{},s=>{this.loggingService.catch("Error in DomService getScrollableElementsIds subscription: ",s)}),this.getSelectedAnnotationsMap$().subscribe(s=>{Object.keys(s||{})?.length?uoe("snippylyUserScalableNo","viewport","width=device-width, user-scalable=no"):hoe("snippylyUserScalableNo")},s=>{this.loggingService.catch("Error in DomService getSelectedAnnotationsMap$ subscription: ",s)})}catch(a){this.loggingService.catch("Error in DomService constructor: ",a)}}setDocService(e){try{this.docService=e,this.subscribeToDomEvents()}catch(i){this.loggingService.catch("Error in DomService setDocService: ",i)}}subscribeToDomEvents(){try{this.docService?.getDocumentPaths$().pipe(ce(e=>{e?(this.onWindowResize(),this.onWindowScroll(),this.onPointerDown(),this.onWindowClick(),this.onWindowKeyupBackspace(),this.onWindowKeyupDelete(),this.onWindowKeyupEsc(),this.onWindowPopState(),this.onWindowKeydownShift(),this.onWindowKeyupShift(),this.addPointerMoveListener(),this.addPointerUpListener(),this.addSelectionChangeListener(),this.onDocumentClick(),this.onDocumentFocus()):(this.unsubscribeFromWindowResize(),this.unsubscribeFromWindowScroll(),this.unsubscribeFromPointerDown(),this.unsubscribeFromWindowClick(),this.unsubscribeFromWindowKeyupBackspace(),this.unsubscribeFromWindowKeyupDelete(),this.unsubscribeFromWindowKeyupEsc(),this.unsubscribeFromWindowPopState(),this.unsubscribeFromWindowKeydownShift(),this.unsubscribeFromWindowKeyupShift(),this.unsubscribeFromPointerMoveListener(),this.unsubscribeFromPointerUpListener(),this.unsubscribeFromSelectionChangeListener(),this.unsubscribeFromDocumentClick(),this.unsubscribeFromDocumentFocus(),this.unsetMutationObserver())})).subscribe()}catch(e){this.loggingService.catch("Error in DomService subscribeToDomEvents: ",e)}}setScrollableElementsIds(e){try{e&&e.length&&this.scrollableElementsIds$.next(Array.from(new Set(e)))}catch(i){this.loggingService.catch("Error in DomService setScrollableElementsIds: ",i)}}getScrollableElementsIds$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getScrollableElementsIds$","color: green;"),this.scrollableElementsIds$.asObservable()}removeScrollableElementsIds(){this.scrollableElementsIds$.next([])}setMutationObserver(e){try{this.mutationObserver||(this.loggingService.log("%c[WB] Calling DomService FUNCTION: setMutationObserver","color: green;"),this.loggingService.log("%c[WB] setMutationObserver from: "+e,"color: green;"),this.mutationObserver=new MutationObserver(i=>{try{if(i?.find(a=>a?.attributeName===U.VELT_IGNORE_CHANGE_DETECTION))return;let r=i.filter(a=>a.type==="childList").filter(a=>{let s=a.target;return a.removedNodes.forEach(c=>{let p=c;if(typeof p.getAttribute=="function"){let u=p.getAttribute(U.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))}}}),Hi(s)?!1:!!(this.filterSnippylyNodes(a.addedNodes).length||this.filterSnippylyNodes(a.removedNodes).length)});this.childListMutation$.next(r),r.push(...i.filter(a=>a.type==="attributes").filter(a=>!Hi(a.target)).filter(a=>this.filterSnippylyNodes([a.target]).length).filter(a=>{if(a){let s=a.target;return s?.classList?.contains("snippyly-sidebar-panel")?!1:s?!s.getAttribute(U.VELT_IGNORE_CHANGE_DETECTION):!0}return!0})),r=r.filter(a=>{let s=!0;return Object.keys(U.INGNORE_MUTATION_OBSERVER_CHANGE_TAGS).forEach(c=>{a.target?.closest(c)&&(s=!1)}),s}),r=r.filter(a=>a.target&&xo(a.target)),r.length&&this.mutation$.next(r)}catch(r){this.loggingService.catch("Error in DomService change detection: ",r)}}),this.mutationObserver.observe(document.body,{childList:!0,subtree:!0,attributes:!0}))}catch(i){this.loggingService.catch("Error in DomService change detection: ",i)}}unsetMutationObserver(){try{this.mutationObserver&&(this.mutationObserver.disconnect(),this.mutationObserver=null)}catch(e){this.loggingService.catch("Error in DomService unsetMutationObserver: ",e)}}detectNetworkStatusChange(){this.loggingService.log("%c[WB] Calling FUNCTION: detectNetworkStatusChange","color: green;");try{oo(ri(window,"offline").pipe(ce(()=>!1)),ri(window,"online").pipe(ce(()=>!0)),new Lt(e=>{e.next(navigator.onLine),e.complete()})).subscribe(e=>{this.networkStatus$.next(e)})}catch(e){this.loggingService.catch("Error in DomService detectNetworkStatusChange: ",e)}}onWindowResize(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowResize","color: green;");try{this.unsubscribeFromWindowResize(),this.unlistenWindowResize=this.renderer.listen("window","resize",e=>{this.windowResize$.next(e);let i=this.calculateScreenSize();this.deviceInfo$.next(new ei),this.currentScreenSize$.next(i)})}catch(e){this.loggingService.catch("Error in DomService onWindowResize: ",e)}}unsubscribeFromWindowResize(){try{this.unlistenWindowResize&&typeof this.unlistenWindowResize=="function"&&(this.unlistenWindowResize(),this.unlistenWindowResize=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromWindowResize: ",e)}}onWindowScroll(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowScroll","color: green;");try{this.unsubscribeFromWindowScroll(),this.unlistenWindowScroll=this.renderer.listen("window","scroll",e=>{this.windowScroll$.next(e);let i=this.calculateScreenSize();this.currentScreenSize$.next(i)})}catch(e){this.loggingService.catch("Error in DomService onWindowScroll: ",e)}}unsubscribeFromWindowScroll(){try{this.unlistenWindowScroll&&typeof this.unlistenWindowScroll=="function"&&(this.unlistenWindowScroll(),this.unlistenWindowScroll=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromWindowScroll: ",e)}}onPointerDown(){this.loggingService.log("%c[WB] Calling FUNCTION: onPointerDown","color: green;");try{this.unsubscribeFromPointerDown(),this.unlistenPointerDown=this.renderer.listen("window","pointerdown",e=>{this.mousedown=!0,this.windowMouseDown$.next(e),this.setPointerPosition(e)})}catch(e){this.loggingService.catch("Error in DomService onPointerDown: ",e)}}unsubscribeFromPointerDown(){try{this.unlistenPointerDown&&typeof this.unlistenPointerDown=="function"&&(this.unlistenPointerDown(),this.unlistenPointerDown=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromPointerDown: ",e)}}onWindowClick(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowKeyupBackspace","color: green;");try{this.unsubscribeFromWindowClick(),this.unlistenWindowClick=this.renderer.listen("window","click",e=>{this.windowClick$.next(e)})}catch(e){this.loggingService.catch("Error in DomService onWindowClick: ",e)}}unsubscribeFromWindowClick(){try{this.unlistenWindowClick&&typeof this.unlistenWindowClick=="function"&&(this.unlistenWindowClick(),this.unlistenWindowClick=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromWindowClick: ",e)}}onWindowKeyupBackspace(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowKeyupBackspace","color: green;");try{this.unsubscribeFromWindowKeyupBackspace(),this.unlistenWindowKeyupBackspace=this.renderer.listen("window","keyup.backspace",e=>{this.isVideoEditorHandlingDelete||this.windowKeyupBackspace$.next(e)})}catch(e){this.loggingService.catch("Error in DomService onWindowKeyupBackspace: ",e)}}unsubscribeFromWindowKeyupBackspace(){try{this.unlistenWindowKeyupBackspace&&typeof this.unlistenWindowKeyupBackspace=="function"&&(this.unlistenWindowKeyupBackspace(),this.unlistenWindowKeyupBackspace=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromWindowKeyupBackspace: ",e)}}onWindowKeyupDelete(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowKeyupDelete","color: green;");try{this.unsubscribeFromWindowKeyupDelete(),this.unlistenWindowKeyupDelete=this.renderer.listen("window","keyup.delete",e=>{this.isVideoEditorHandlingDelete||this.windowKeyupDelete$.next(e)})}catch(e){this.loggingService.catch("Error in DomService onWindowKeyupDelete: ",e)}}unsubscribeFromWindowKeyupDelete(){try{this.unlistenWindowKeyupDelete&&typeof this.unlistenWindowKeyupDelete=="function"&&(this.unlistenWindowKeyupDelete(),this.unlistenWindowKeyupDelete=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromWindowKeyupDelete: ",e)}}onWindowKeyupEsc(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowKeyupEsc","color: green;");try{this.unsubscribeFromWindowKeyupEsc(),this.unlistenWindowKeyupEsc=this.renderer.listen("window","keyup.esc",e=>{this.windowKeyupEsc$.next(e)})}catch(e){this.loggingService.catch("Error in DomService onWindowKeyupEsc: ",e)}}unsubscribeFromWindowKeyupEsc(){try{this.unlistenWindowKeyupEsc&&typeof this.unlistenWindowKeyupEsc=="function"&&(this.unlistenWindowKeyupEsc(),this.unlistenWindowKeyupEsc=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromWindowKeyupEsc: ",e)}}onWindowPopState(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowPopState","color: green;");try{this.unsubscribeFromWindowPopState(),this.unlistenWindowPopState=this.renderer.listen("window","popstate",e=>{this.windowPopState$.next(e)})}catch(e){this.loggingService.catch("Error in DomService onWindowPopState: ",e)}}unsubscribeFromWindowPopState(){try{this.unlistenWindowPopState&&typeof this.unlistenWindowPopState=="function"&&(this.unlistenWindowPopState(),this.unlistenWindowPopState=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromWindowPopState: ",e)}}onDocumentClick(){this.loggingService.log("%c[WB] Calling FUNCTION: onDocumentClick","color: green;");try{this.unsubscribeFromDocumentClick(),this.documentClickListener=e=>{e?.target?.tagName?.toLowerCase()!==U.TAGS.SUPERFLOW_TOOLBAR&&(this.documentClick$.next(e),this.documentClickSubject$.next(e))},document.addEventListener("click",this.documentClickListener,!0)}catch(e){this.loggingService.catch("Error in DomService onDocumentClick: ",e)}}unsubscribeFromDocumentClick(){try{this.documentClickListener&&typeof this.documentClickListener=="function"&&(document.removeEventListener("click",this.documentClickListener,!0),this.documentClickListener=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromDocumentClick: ",e)}}onDocumentFocus(){this.loggingService.log("%c[WB] Calling FUNCTION: onDocumentFocus","color: green;");try{this.unsubscribeFromDocumentFocus(),this.documentFocusListener=e=>{this.documentFocus$.next(e)},document.addEventListener("focus",this.documentFocusListener,!0)}catch(e){this.loggingService.catch("Error in DomService onDocumentFocus: ",e)}}unsubscribeFromDocumentFocus(){try{this.documentFocusListener&&typeof this.documentFocusListener=="function"&&(document.removeEventListener("focus",this.documentFocusListener,!0),this.documentFocusListener=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromDocumentFocus: ",e)}}onWindowKeydownShift(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowKeydownShift","color: green;");try{this.unsubscribeFromWindowKeydownShift(),this.unlistenWindowKeydownShift=this.renderer.listen("window","keydown.shift",e=>{this.windowKeydownShift$.next(e),this.windowKeyupShift$.next(null)})}catch(e){this.loggingService.catch("Error in DomService onWindowKeydownShift: ",e)}}unsubscribeFromWindowKeydownShift(){try{this.unlistenWindowKeydownShift&&typeof this.unlistenWindowKeydownShift=="function"&&(this.unlistenWindowKeydownShift(),this.unlistenWindowKeydownShift=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromWindowKeydownShift: ",e)}}onWindowKeyupShift(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowKeyupShift","color: green;");try{this.unsubscribeFromWindowKeyupShift(),this.unlistenWindowKeyupShift=this.renderer.listen("window","keyup.shift",e=>{this.windowKeyupShift$.next(e),this.windowKeydownShift$.next(null)})}catch(e){this.loggingService.catch("Error in DomService onWindowKeyupShift: ",e)}}unsubscribeFromWindowKeyupShift(){try{this.unlistenWindowKeyupShift&&typeof this.unlistenWindowKeyupShift=="function"&&(this.unlistenWindowKeyupShift(),this.unlistenWindowKeyupShift=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromWindowKeyupShift: ",e)}}onWindowKeydown$(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowKeydown$","color: green;");try{return ri(window,"keydown")}catch(e){return this.loggingService.catch("Error in DomService onWindowKeydown$: ",e),Dg}}addPointerMoveListener(){this.loggingService.log("%c[WB] Calling FUNCTION: addPointerMoveListener","color: green;");try{this.unsubscribeFromPointerMoveListener(),this.unlistenPointerMoveListener=this.renderer.listen("document","pointermove",e=>{this.windowPointerMove$.next(e),this.mouseMoveEvent=e})}catch(e){this.loggingService.catch("Error in DomService addPointerMoveListener: ",e)}}unsubscribeFromPointerMoveListener(){try{this.unlistenPointerMoveListener&&typeof this.unlistenPointerMoveListener=="function"&&(this.unlistenPointerMoveListener(),this.unlistenPointerMoveListener=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromPointerMoveListener: ",e)}}addPointerUpListener(){this.loggingService.log("%c[WB] Calling FUNCTION: addPointerUpListener","color: green;");try{this.unsubscribeFromPointerUpListener(),this.unlistenPointerUpListener=this.renderer.listen("document","pointerup",e=>{this.windowPointerUp$.next(e)})}catch(e){this.loggingService.catch("Error in DomService addPointerUpListener: ",e)}}unsubscribeFromPointerUpListener(){try{this.unlistenPointerUpListener&&typeof this.unlistenPointerUpListener=="function"&&(this.unlistenPointerUpListener(),this.unlistenPointerUpListener=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromPointerUpListener: ",e)}}addSelectionChangeListener(){this.loggingService.log("%c[WB] Calling FUNCTION: addPointerUpListener","color: green;");try{this.unsubscribeFromSelectionChangeListener(),this.unlistenSelectionChangeListener=this.renderer.listen("document","selectionchange",e=>{this.documentSelectionChange$.next(e)})}catch(e){this.loggingService.catch("Error in DomService addPointerUpListener: ",e)}}unsubscribeFromSelectionChangeListener(){try{this.unlistenSelectionChangeListener&&typeof this.unlistenSelectionChangeListener=="function"&&(this.unlistenSelectionChangeListener(),this.unlistenSelectionChangeListener=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromSelectionChangeListener: ",e)}}updateCurrentMousePosition(e){try{if(this.currentMousePosition.pageX=e.pageX,this.currentMousePosition.pageY=e.pageY,this.currentMousePosition.clientX=e.clientX,this.currentMousePosition.clientY=e.clientY,e.target){let i=this.getXPath(e.target),r=e.target;if(i?.includes("name()='svg'")){let C=this.getXPath(i);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:i,topPercentage:u,leftPercentage:p}}else this.currentMousePosition.element=null;this.currentMousePosition$.next(this.currentMousePosition)}catch(i){this.loggingService.catch("Error in DomService updateCurrentMousePosition: ",i)}}getTargetElementForCursorPosition(e,i=!0,r=!1,a=!0,s){try{let c=e,p=c?.touches?.length?c.touches[0]?.clientX:c.clientX,u=c?.touches?.length?c.touches[0]?.clientY:c.clientY,C=this.getBackgroundElement(p,u,i,r);if(C&&s&&typeof s=="function"&&(C=s(C)),C){let E=this.getXPath(C),A=this.getXPath(C,!0),B=C.getBoundingClientRect(),G=p-B.x,K=u-B.y,pe=G*100/(B.width||1),Ce=K*100/(B.height||1),Ie={xpath:E,fXpath:A,leftPercentage:pe,topPercentage:Ce};if(a){let $e=this.getXPath(C,!0,!0);Ie.cfXpath=$e}return Ie}else return null}catch(c){return this.loggingService.catch("Error in DomService getTargetElementForCommentPinAnnotation: ",c),null}}getBackgroundElement(e,i,r=!0,a=!1){try{let s=document.elementsFromPoint(e,i),c=[];s.forEach(u=>{Hi(u)?c=[]:xo(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,i){try{let r=document.elementsFromPoint(e,i),a=[];return r.forEach(s=>{Hi(s)&&xo(s)&&a.push(s)}),a[0]}catch(r){return this.loggingService.catch("Error in DomService getBackgroundSnippylyElement: ",r),null}}setPointerPosition(e){this.loggingService.log("%c[WB] Calling FUNCTION: setPointerPosition","color: green;");try{this.previousMousePosition.pageX=e.pageX,this.previousMousePosition.pageY=e.pageY,this.currentMousePosition.pageX=e.pageX,this.currentMousePosition.pageY=e.pageY}catch(i){this.loggingService.catch("Error in DomService setPointerPosition: ",i)}}getCurrentWindowSize$(e){return this.loggingService.log("%c[WB] Calling FUNCTION: getCurrentWindowSize","color: green;"),this.currentScreenSize$.asObservable()}getCurrentMousePosition$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getCurrentMousePosition","color: green;"),this.currentMousePosition$.asObservable()}getCurrentWindowSizeValue(){return this.loggingService.log("%c[WB] Calling FUNCTION: getCurrentWindowSizeValue","color: green;"),this.currentScreenSize$.value}getTopLeftPosition(){this.loggingService.log("%c[WB] Calling FUNCTION: getTopLeftPosition","color: green;");try{let e=document?.body?.getBoundingClientRect()||document?.documentElement?.getBoundingClientRect(),i=this.currentMousePosition?.pageX||e.x+200,r=Math.min(i,e.width/2),a=Math.abs(e.y),s=e.y-20;return a>50&&(s=Math.abs(e.y)+180),this.loggingService.log(e),this.loggingService.log(r),this.loggingService.log(s),{topPositionX:r,topPositionY:s}}catch(e){return this.loggingService.catch("Error in DomService getTopLeftPosition: ",e),{topPositionX:0,topPositionY:0}}}toggleSelection(){this.enableRectSelectionSubject$.next(!this.enableRectSelectionSubject$.value)}enableSelection(){this.enableRectSelectionSubject$.next(!0)}disableSelection(){this.enableRectSelectionSubject$.next(!1)}setPinHighlighterClass(e){this.pinHighlighterClass$.next(e)}setTextHighlighterClass(e){this.textHighlighterClass$.next(e)}getTextHighlighterClass(){return this.textHighlighterClass$.asObservable()}enableCommentPinHighlighter(){this.commentPinHighlighter$.next(!0)}disableCommentPinHighlighter(){this.commentPinHighlighter$.next(!1)}getCommentPinHighlighter$(){return this.commentPinHighlighter$.asObservable()}getCommentPinHighlighter(){return this.commentPinHighlighter$?.value}highlightElement(e,i,r){if(e){if(!r&&this.getCommentPinHighlighter()&&(this.pinHighlighterClass$.value?this.addClassToElement(e,this.pinHighlighterClass$.value):this.addClassToElement(e,U.SNIPPYLY_HIGHLIGHT)),i&&!e.hasAttribute(U.ATTRIBUTES.DEFAULT_CURSOR)){let a=e.style.getPropertyValue("cursor"),s=e.style.getPropertyPriority("cursor"),c=a?{defaultCursorValue:a,defaultCursorPriority:s}:"";e.setAttribute(U.ATTRIBUTES.DEFAULT_CURSOR,c?JSON.stringify(c):""),e.style.setProperty("cursor",i,"important")}e.setAttribute(U.SNIPPYLY_HIGHLIGHT,"true"),e.setAttribute(U.VELT_IGNORE_CHANGE_DETECTION,"true")}}removeHighlightFromElement(e){if(e&&(this.pinHighlighterClass$.value&&this.removeClassFromElement(e,this.pinHighlighterClass$.value),this.removeClassFromElement(e,U.SNIPPYLY_HIGHLIGHT),e.removeAttribute(U.SNIPPYLY_HIGHLIGHT),e.removeAttribute(U.VELT_IGNORE_CHANGE_DETECTION),e.hasAttribute(U.ATTRIBUTES.DEFAULT_CURSOR))){try{if(e.style.removeProperty("cursor"),e.getAttribute(U.ATTRIBUTES.DEFAULT_CURSOR)){let i=JSON.parse(e.getAttribute(U.ATTRIBUTES.DEFAULT_CURSOR));e.style.setProperty("cursor",i.defaultCursorValue,i.defaultCursorPriority)}}catch{}e.removeAttribute(U.ATTRIBUTES.DEFAULT_CURSOR)}}highlightUserElement(e,i,r,a=!1){try{e&&(this.addClassToElement(e,U.VELT_LIVE_SELECTION_ON_ELEMENT),a&&this.addClassToElement(e,U.VELT_LIVE_SELECTION_ON_ELEMENT_DEFAULT),e.setAttribute(U.SNIPPYLY_HIGHLIGHT,"true"),e.setAttribute(U.VELT_IGNORE_CHANGE_DETECTION,"true"),i&&!e.style.getPropertyValue(U.VELT_SELECTION_COLOR)&&e.style.setProperty(U.VELT_SELECTION_COLOR,i),r&&e.setAttribute(U.SNIPPYLY_HIGHLIGHT_USER_NAME,r))}catch(s){this.loggingService.catch("Error in DomService highlightUserElement: ",s)}}removeHighlightUserFromElement(e){try{e&&(this.removeClassFromElement(e,U.VELT_LIVE_SELECTION_ON_ELEMENT),this.removeClassFromElement(e,U.VELT_LIVE_SELECTION_ON_ELEMENT_DEFAULT),e.removeAttribute(U.SNIPPYLY_HIGHLIGHT),e.removeAttribute(U.VELT_IGNORE_CHANGE_DETECTION),e.removeAttribute(U.VELT_SELECTION_COLOR),e.removeAttribute(U.SNIPPYLY_HIGHLIGHT_USER_NAME),e.style.removeProperty(U.VELT_SELECTION_COLOR))}catch(i){this.loggingService.catch("Error in DomService removeHighlightUserFromElement: ",i)}}previewHighlightElement(e){e&&e.setAttribute(U.SNIPPYLY_HIGHLIGHT_PREVIEW,"true")}removePreviewHighlightFromElement(e){e&&e.removeAttribute(U.SNIPPYLY_HIGHLIGHT_PREVIEW)}getXPath(e,i=!1,r=!1,a){try{let s=this.calculateXPath(e,i,r,a);if(s&&typeof s=="string"&&s.includes("/svg")){let c=s.split("/"),p=!1;c.forEach((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,i,r,a){try{if(e){if(typeof e=="string")return document.evaluate(e,a||document,this.namespaceResolver,XPathResult.ANY_TYPE,null);if(!e||e.nodeType!=1)return"";if(e.id&&document.querySelectorAll(`[id='${e.id}']`)?.length===1&&!i)return"//*[@id='"+e.id+"']";if(r&&e.className&&e.className.split){let c=e.className?.split(" ")?.filter(p=>!p?.includes("snippyly")&&!p?.includes("velt")&&!["show-pin-cursor"].includes(p))[0];if(c){let p=this.calculateXPath(e.parentNode,i,r,a)+"/"+e.tagName.toLowerCase(),u=Array.from(e.parentNode?.children||[]).filter(C=>C.nodeType===1&&C.tagName===e.tagName?C.className?.split(" ")?.filter(A=>A?.includes("snippyly")||A?.includes("velt")||["show-pin-cursor"].includes(A))[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,i,r)+"/"+e.tagName.toLowerCase()+(s.length>1?"["+([].indexOf.call(s,e)+1)+"]":"")}}catch(s){this.loggingService.catch("Error in DomService calculateXPath:",s)}}getElementFromXPath(e,i=document){try{if(this.xpathCache.has(e)){let a=this.xpathCache.get(e);if(a!==void 0&&document.contains(a))return a;this.xpathCache.delete(e)}let r=this.getXPath(e,!1,!1,i);if(r){let a=r?.iterateNext();if(a!==null&&typeof a.setAttribute=="function"){let s=wn();a.setAttribute(U.ATTRIBUTES.VELT_ELEMENT_CACHE_ID,s),this.xpathCacheId.set(s,e)}return this.xpathCache.set(e,a),a}return null}catch(r){return this.loggingService.catch("Error in DomService getElementFromXPath:",r),null}}calculateScreenSize(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowResize","color: green;");try{let e=[document?.body?.clientHeight||0,document?.documentElement?.clientHeight||0,window?.innerHeight||0],i=[document?.body?.clientWidth||0,document?.documentElement?.clientWidth||0,window?.innerWidth||0];this.calculatePageScrollHeight(),this.loggingService.log(this.pageScrollHeight),this.loggingService.log(this.nodeMap),this.highestNode=this.nodeMap[this.pageScrollHeight];let r=new GS;return r.screenWidth=Math.max(...i),r.screenHeight=Math.max(...e),r.screenScrollHeight=this.pageScrollHeight,r}catch(e){return this.loggingService.catch("Error in DomService calculateScreenSize:",e),new GS}}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(i){return this.loggingService.catch("Error in DomService removeSnippylyContent: ",i),e}}mergeAdjacentTextNodes(e){try{let i=e.firstChild;for(;i;){if(i.nodeType===Node.TEXT_NODE){let r=i.nextSibling;for(;r&&r.nodeType===Node.TEXT_NODE;)i.textContent+=r.textContent,r.remove(),r=i.nextSibling}i=i.nextSibling}}catch(i){this.loggingService.catch("Error in DomService mergeAdjacentTextNodes: ",i)}}findLongestNode(e){try{for(let i=e.length-1;i>=0;i--){if(e[i]?.scrollHeight&&e[i]?.clientHeight){let r=Math.max(e[i]?.scrollHeight,e[i]?.clientHeight);this.pageScrollHeight=Math.max(r,this.pageScrollHeight),this.nodeMap[r]=e[i]}e[i]?.childNodes?.length&&this.findLongestNode(e[i]?.childNodes)}}catch(i){this.loggingService.catch("Error in DomService findLongestNode: ",i)}}resetSelectedAnnotationsMap(e=!0,i){try{let r=Array.from(document.querySelectorAll(`[${U.ATTRIBUTES.VELT_ANNOTATION_DRAFT}]`)),a=this.getDraftCommentAnnotationDialogs()||[];r.push(...a),r=Array.from(new Set(r));let s=r.map(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(U.ATTRIBUTES.VELT_ANNOTATION_EDIT_COMMENT)||C.classList.contains("velt-annotation-draft-checked")||this.addClassToElement(C,"velt-annotation-draft-checked")},100),C.getAttribute(U.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 A=p[E];A?.to?.length||s.includes(E)||C.push(A)}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]),i)switch(i){case"comment":["comment","videoPin"].includes(p[C]?.type)||(u[C]=p[C]);break;default:p[C]?.type!==i&&(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,i){try{if(i)this.recordingInProgress$.next(T(I({},this.recordingInProgress$.value),{[e]:i}));else{let r=this.recordingInProgress$.value;delete r[e],this.recordingInProgress$.next(r)}}catch(r){this.loggingService.catch("Error in DomService setRecordingInProgress: ",r)}}resetRecordingInProgress(){try{this.recordingInProgress$.next({})}catch(e){this.loggingService.catch("Error in DomService resetRecordingInProgress: ",e)}}getRecordingInProgress(){try{return this.recordingInProgress$.value}catch(e){return this.loggingService.catch("Error in DomService getRecordingInProgress: ",e),{}}}getDraftCommentAnnotationDialogs(){try{let e=[];return Array.from(document.querySelectorAll(`${U.TAGS.SNIPPYLY_COMMENT_DIALOG}`)).forEach(r=>{if(r?.shadowRoot){let a=r.shadowRoot.querySelector(`[${U.ATTRIBUTES.VELT_ANNOTATION_DRAFT}]`);a&&e.push(a)}else{let a=r.querySelector(`${U.TAGS.VELT_SHADOW_DOM_INTERNAL}`);if(a?.shadowRoot){let s=a.shadowRoot?.querySelector(`[${U.ATTRIBUTES.VELT_ANNOTATION_DRAFT}]`);s&&e.push(s)}else{let s=r.querySelector(`[${U.ATTRIBUTES.VELT_ANNOTATION_DRAFT}]`);s&&e.push(s)}}}),e}catch(e){return this.loggingService.catch("Error in DomService getDraftCommentAnnotationDialogs: ",e),[]}}getSelectedAnnotationsMap(e){try{let i=this.selectedAnnotationsMap$.value;if(e){let r={};return Object.keys(i).forEach(a=>{switch(e){case"comment":["comment","videoPin"].includes(i[a].type)&&(r[a]=i[a]);break;default:i[a].type===e&&(r[a]=i[a]);break}}),r}else return i}catch(i){return this.loggingService.catch("Error in DomService getSelectedAnnotationsMap: ",i),{}}}getSelectedAnnotationsMap$(e){return this.selectedAnnotationsMap$.asObservable().pipe(ce(i=>{if(e){let r={};return Object.keys(i).forEach(a=>{i[a].type===e&&(r[a]=i[a])}),r}else return i}))}getSelectedComments$(){return this.selectedAnnotationsMap$.asObservable().pipe(ce(e=>Object.values(e)))}getSelectedAnnotationsLocationMap(){try{return this.selectedAnnotationsLocationMap$.value}catch(e){return this.loggingService.catch("Error in DomService getSelectedAnnotationsLocationMap: ",e),{}}}getSelectedAnnotationsLocationMap$(){return this.selectedAnnotationsLocationMap$.asObservable()}toggleAnnotationSelection(e,i,r,a=!1){try{r==="sidebarShowReplies"?this.setDialogOpenedInSidebar(!0):this.setDialogOpenedInSidebar(!1);let s=JSON.parse(JSON.stringify(this.selectedAnnotationsMap$.value||{})),c=JSON.parse(JSON.stringify(this.selectedAnnotationsLocationMap$.value||{}));if(s[e.annotationId]&&!a)delete s[e.annotationId];else{(!this.windowKeydownShift$.value||a)&&(s={}),s[e.annotationId]=e,c[e.annotationId]=i;let p=e?.multiThreadAnnotationId;p&&(s[p]={annotationId:p,type:"multiThread"},c[p]=i)}this.selectedAnnotationsMap$.next(s),Object.keys(c).forEach(p=>{s[p]||delete c[p]}),this.selectedAnnotationsLocationMap$.next(c)}catch(s){this.loggingService.catch("Error in DomService toggleAnnotationSelection: ",s)}}setSelectedAnnotationLocation(e,i){try{let r=JSON.parse(JSON.stringify(this.getSelectedAnnotationsLocationMap()||{}));r?.[e]!==i&&(r[e]=i,this.selectedAnnotationsLocationMap$.next(r))}catch(r){this.loggingService.catch("Error in DomService setSelectedAnnotationLocation: ",r)}}updateSelectedAnnotationInMap(e){try{let i=this.selectedAnnotationsMap$.value;e.forEach(r=>{i[r.annotationId]&&(i[r.annotationId]=r)}),this.selectedAnnotationsMap$.next(i)}catch(i){this.loggingService.catch("Error in DomService updateSelectedAnnotationInMap: ",i)}}getDeleteCommmentAnnotations$(){try{return this.deleteAnnotations$.asObservable()}catch(e){return this.loggingService.catch("Error in DomService getDeleteCommmentAnnotations$: ",e),re([])}}getHighestNode(){return this.loggingService.log("%c[WB] Calling FUNCTION: getHighestNode","color: green;"),this.highestNode}onWindowMouseDown$(){return this.windowMouseDown$.asObservable()}onWindowPointerMove$(){return this.windowPointerMove$.asObservable()}onWindowPointerMove(){return this.windowPointerMove$.value}onWindowPointerUp$(){return this.windowPointerUp$.asObservable()}onSelectionChange$(){return this.documentSelectionChange$.asObservable()}onWindowClick$(){return this.windowClick$.asObservable()}onWindowScroll$(){return this.windowScroll$.asObservable()}onWindowResize$(){return this.windowResize$.asObservable()}onWindowKeyupBackspace$(){return this.windowKeyupBackspace$.asObservable()}onWindowKeyupDelete$(){return this.windowKeyupDelete$.asObservable()}onWindowKeyupEsc$(){return this.windowKeyupEsc$.asObservable()}onWindowPopState$(){return this.windowPopState$.asObservable()}onDocumentClick$(){return this.documentClick$.asObservable()}getLastDocumentClick(){return this.documentClick$.value}onDocumentClickSubject$(){return this.documentClickSubject$.asObservable()}onDocumentFocus$(){return this.documentFocus$.asObservable()}onDomChange$(e){try{return this.mutationObserver||this.setMutationObserver(e),this.mutation$.asObservable()}catch(i){return this.loggingService.catch("Error in DomService onDomChange$: ",i),re([])}}getChildListMutation$(){return this.childListMutation$.asObservable()}onNetworkStatusChange$(){return this.networkStatus$.asObservable()}getElementOffset(e,i){try{let r={offsetTop:0,offsetLeft:0},a=e;if(a===i){let s=window.getComputedStyle(e);s.position==="static"&&s.transformStyle!="preserve-3d"&&s.transform=="none"&&(r.offsetLeft=e?.offsetLeft||0,r.offsetTop=e?.offsetTop||0)}if(a!==i)if(e?.closest("svg"))for(;a&&a!==i;){let c=window.getComputedStyle(a);if(a.tagName.toLowerCase()==="svg"||a instanceof SVGElement){let p=a.parentElement;if(p){let 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===i){let p=window.getComputedStyle(a);p.position==="static"&&p.transformStyle!="preserve-3d"&&p.transform=="none"&&(r.offsetLeft+=a?.offsetLeft||0,r.offsetTop+=a?.offsetTop||0)}}else{let c=window.getComputedStyle(a);c.position==="static"?c.transformStyle!="preserve-3d"&&c.transform=="none"&&(r.offsetLeft+=a?.offsetLeft||0,r.offsetTop+=a?.offsetTop||0):(r.offsetLeft+=a.offsetLeft,r.offsetTop+=a.offsetTop)}return r}catch(r){return this.loggingService.catch("Error in DomService getElementOffset: ",r),{offsetTop:0,offsetLeft:0}}}isElementVisible(e){try{if(typeof e?.getBoundingClientRect=="function"){let{width:i,height:r,top:a,bottom:s}=e?.getBoundingClientRect();return i>0||r>0||a<window.innerHeight&&s>0}else return!1}catch(i){return this.loggingService.catch("Error in DomService isElementVisible: ",i),!1}}isElementVisibleOnScreen(e){try{if(e){if(!(e instanceof Element))return!1;let i=e,r=window.getComputedStyle(i);return!(r.display==="none"||r.visibility==="hidden"||parseFloat(r.opacity)===0)}return!1}catch(i){return this.loggingService.catch("Error in DomService isElementVisibleOnScreen: ",i),!1}}getClickAndDragPointsObservable(){return new Lt(e=>{let i=ri(document,"mousedown").pipe(ce(p=>({type:p.type,x:p.clientX+window.scrollX,y:p.clientY+window.scrollY,event:p}))),r=ri(document,"mousemove").pipe(ce(p=>({type:p.type,x:p.clientX+window.scrollX,y:p.clientY+window.scrollY,event:p}))),a=ri(document,"mouseup").pipe(ce(p=>({type:p.type,x:p.clientX+window.scrollX,y:p.clientY+window.scrollY,event:p}))),c=i.pipe(ue(p=>r.pipe(Ai(),ce(([u,C])=>({startPoint:p,prevPoint:u,curPoint:C})),ro(a)))).subscribe(e);return()=>c.unsubscribe()})}drawRectangle(e,i){let r=document.querySelector(".rectangle");r||(r=document.createElement("div"),this.addClassToElement(r,"rectangle"),r.setAttribute(U.ATTRIBUTES.VELT_COMMENT_DISABLED,"true"),r.setAttribute(U.VELT_IGNORE_CHANGE_DETECTION,"true"),document.body.appendChild(r));let a=Math.abs(i.x-e.x),s=Math.abs(i.y-e.y),c=Math.min(e.x,i.x),p=Math.min(e.y,i.y);return r.style.width=`${a}px`,r.style.height=`${s}px`,r.style.left=`${c}px`,r.style.top=`${p}px`,r.style.position="absolute",r.style.border="2px dashed #f00",r.style.pointerEvents="none",r.style.zIndex="2147483577",r}getRange(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: getRange","color: green;"),window.getSelection()?.toString()){let e=window.getSelection();if(e?.rangeCount)return e.getRangeAt(0)}return null}catch(e){return this.loggingService.catch("Error in DomService getRange: ",e),null}}clearTextSelection(){try{this.loggingService.log("%c[WB] Calling FUNCTION: clearTextSelection","color: green;"),window.getSelection&&(window.getSelection()?.empty?window.getSelection()?.empty():window.getSelection()?.removeAllRanges&&window.getSelection()?.removeAllRanges())}catch(e){this.loggingService.catch("Error in DomService clearTextSelection: ",e)}}getTargetTextRangeFromSelectionRange(e){try{let i={},r=e.commonAncestorContainer;r?.nodeType===Node.TEXT_NODE&&(r=r.parentElement);let a=document.body;if(r){let c=this.getTextXPath(r);this.isXpathWithId(c)&&(a=r)}let s=this.getAdditionalLocationContainer(r);if(s&&(a=s),i.commonAncestorContainer=this.getTextXPath(a),i.commonAncestorContainer){let c=this.getElementFromXPath(i.commonAncestorContainer);c&&(i.commonAncestorContainerFXpath=this.getXPath(c,!0),i.commonAncestorContainerCFXpath=this.getXPath(c,!0,!0))}return i.text=e.toString(),i.occurrence=Lu(a,0,e.startContainer,e.startOffset,e.toString())+1,i}catch(i){this.loggingService.catch("Error in DomService getTargetTextRangeFromSelectionRange: ",i);return}}getTextXPath(e){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: getTextXPath","color: green;"),e.nodeType===Node.TEXT_NODE){let i=1,r=e.previousSibling;for(;r;)r.nodeType===Node.TEXT_NODE&&i++,r=r.previousSibling;return this.getXPath(e.parentElement)}else return this.getXPath(e)}catch(i){this.loggingService.catch("Error in DomService getTextXPath: ",i);return}}getHostElement(e){try{if(U.NON_NESTABLE_ELEMENTS[e?.tagName?.toLowerCase()]){let r=e?.closest("picture");return r?r?.parentElement:e.parentElement}let i=e.closest("svg");return i?i?.parentElement:e}catch(i){return this.loggingService.catch("Error in DomService getHostElement: ",i),e}}isElementInsideAdditionalLocationContainer(e){try{return!!e?.closest(`[${U.ATTRIBUTES.VELT_LOCATION}], [${U.ATTRIBUTES.VELT_LOCATION_ID}]`)}catch(i){return this.loggingService.catch("Error in DomService isElementInsideAdditionalLocationContainer: ",i),!1}}getAdditionalLocationContainer(e){try{return e?.closest(`[${U.ATTRIBUTES.VELT_LOCATION}], [${U.ATTRIBUTES.VELT_LOCATION_ID}]`)||null}catch(i){return this.loggingService.catch("Error in DomService getAdditionalLocationContainer: ",i),null}}isXpathWithId(e){try{return typeof e=="string"?!!e?.includes("[@id="):!1}catch(i){return this.loggingService.catch("Error in DomService isXpathWithId: ",i),!1}}getListedElements({elementIds:e,elementClassNames:i,elementQuerySelectors:r}){try{let a=[];if(e?.length)for(let s=0;s<e.length;s++){let c=document.getElementById(e[s]);c&&a.push(c)}if(i?.length)for(let s=0;s<i.length;s++){let c=document.getElementsByClassName(i[s]);for(let p=0;p<c.length;p++){let 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,i){try{if(i?.length){for(let r=0;r<i.length;r++){let a=document.getElementById(i[r]);if(a&&a.contains(e))return!0}return!1}return!0}catch(r){return this.loggingService.catch("Error in DomService isElementInsideListedElementIds: ",r),!1}}isElementInsideListedElementClassNames(e,i){try{if(i?.length){for(let r=0;r<i.length;r++){let a=document.getElementsByClassName(i[r]);for(let s=0;s<a.length;s++)if(a[s].contains(e))return!0}return!1}return!0}catch(r){return this.loggingService.catch("Error in DomService isElementInsideListedElementClassNames: ",r),!1}}isElementInsideListedElementQuerySelectors(e,i){try{if(i?.length){for(let r=0;r<i.length;r++){let a=document.querySelectorAll(i[r]);for(let s=0;s<a.length;s++)if(a[s].contains(e))return!0}return!1}return!0}catch(r){return this.loggingService.catch("Error in DomService isElementInsideListedElementQuerySelectors: ",r),!1}}addClassToElement(e,i){try{this.loggingService.log("%c[WB] Calling FUNCTION: addClassToElement","color: green;"),e&&(e.classList?.contains(i)||e.classList?.add(i))}catch(r){this.loggingService.catch("Error in DomService addClassToElement: ",r)}}removeClassFromElement(e,i){try{this.loggingService.log("%c[WB] Calling FUNCTION: removeClassFromElement","color: green;"),e&&e.classList?.contains(i)&&e.classList?.remove(i)}catch(r){this.loggingService.catch("Error in DomService removeClassFromElement: ",r)}}isElementInsideParentWithAttribute(e,i,r){try{let a=e;for(;a&&a!==document.body;){if(a?.getAttribute&&a?.getAttribute(i)===r)return!0;a=a.parentElement}return!1}catch(a){return this.loggingService.catch("Error in DomService isElementInsideParentWithAttribute: ",a),!1}}setVideoEditorHandlingDelete(e){try{this.isVideoEditorHandlingDelete=e}catch(i){this.loggingService.catch("Error in DomService setVideoEditorHandlingDelete: ",i)}}isVideoEditorHandlingDeleteKey(){try{return this.isVideoEditorHandlingDelete}catch(e){return this.loggingService.catch("Error in DomService isVideoEditorHandlingDeleteKey: ",e),!1}}setCustomCss(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setCustomCss","color: green;"),this.customCss$.next(e)}catch(i){this.loggingService.catch("Error in DomService setCustomCss: ",i)}}getCustomCss$(){try{return this.loggingService.log("%c[WB] Calling FUNCTION: getCustomCss$","color: green;"),this.customCss$.asObservable()}catch(e){return this.loggingService.catch("Error in DomService getCustomCss$: ",e),re(null)}}injectCustomCss(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: injectCustomCss","color: green;");let i=this.customCss$.value;if(i){let r=e?.shadowRoot?.querySelector(`[${U.VELT_CUSTOM_CSS}]`);if(r&&r.remove(),i?.type==="link"){let a=document.createElement("link");a.href=i?.value,a.rel="stylesheet",a.setAttribute(U.VELT_CUSTOM_CSS,"true"),e?.shadowRoot?.appendChild(a)}else{let a=document.createElement("style");a.innerHTML=this.sanitizeHtml(i?.value),a.setAttribute(U.VELT_CUSTOM_CSS,"true"),e?.shadowRoot?.appendChild(a)}}}catch(i){this.loggingService.catch("Error in DomService injectCustomCss: ",i)}}trimCommentHtml(e){try{let i=document.createElement("div");i.innerHTML=e,this.removeEmptyElements(i);let r=i.innerHTML;return r=r.replace(o.MULTIPLE_NBSP_REGEX," ").replace(o.TRIM_NBSP_REGEX,"").trim(),r}catch(i){return this.loggingService.catch("Error in DomService trimCommentHtml: ",i),e}}removeEmptyElements(e){try{let a=function(s){return r.test(s.innerHTML)};var i=a;let r=/^\s*(<br\s*\/?>)?\s*$/;for(;e.firstChild&&a(e.firstChild);)e.removeChild(e.firstChild);for(;e.lastChild&&a(e.lastChild);)e.removeChild(e.lastChild)}catch(r){this.loggingService.catch("Error in DomService removeEmptyElements: ",r)}}normalizeWhitespace(e){try{e.childNodes.forEach(i=>{i.nodeType===Node.TEXT_NODE?i.nodeValue=i.nodeValue?.replace(/\s+/g," ").trim()??"":i.nodeType===Node.ELEMENT_NODE&&this.normalizeWhitespace(i)})}catch(i){this.loggingService.catch("Error in DomService normalizeWhitespace: ",i)}}sanitizeHtml(e){try{return this.loggingService.log("%c[WB] Calling FUNCTION: sanitizeHtml","color: green;"),M$.sanitize(e,Ase)}catch(i){return this.loggingService.catch("Error in DomService sanitizeHtml: ",i),""}}sanitizeSvg(e){try{return M$.sanitize(e,Ase)}catch(i){return this.loggingService.catch("Error in DomService sanitizeSvg: ",i),e}}setDeviceInfo(){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDeviceInfo","color: green;");let e=new ei;this.deviceInfo$.next(e)}catch(e){this.loggingService.catch("Error in DomService setDeviceInfo: ",e)}}getDeviceInfo$(){try{return this.loggingService.log("%c[WB] Calling FUNCTION: getDeviceInfo$","color: green;"),this.deviceInfo$.asObservable()}catch(e){return this.loggingService.catch("Error in DomService getDeviceInfo$: ",e),re(new ei)}}getTabId(){try{let e=sessionStorage.getItem(U.SESSION_STORAGE.VELT_TAB_ID),i=this.getTabIdFromWindowName();return(!e||e!==i)&&(e=wn(),sessionStorage.setItem(U.SESSION_STORAGE.VELT_TAB_ID,e),this.setTabIdToWindowName(e)),e}catch(e){return this.loggingService.catch("Error in DomService getTabId: ",e),null}}getTabIdFromWindowName(){try{return window.name}catch(e){return this.loggingService.catch("Error in DomService getTabIdFromWindowName: ",e),null}}setTabIdToWindowName(e){try{window.name=e}catch(i){this.loggingService.catch("Error in DomService setTabIdToWindowName: ",i)}}getDeviceInfo(){try{return this.loggingService.log("%c[WB] Calling FUNCTION: getDeviceInfo","color: green;"),this.deviceInfo$.value}catch(e){return this.loggingService.catch("Error in DomService getDeviceInfo: ",e),new ei}}isMobileDevice(){try{return new ei().getDeviceType()===Xo.MOBILE}catch(e){return this.loggingService.catch("Error in DomService isMobileDevice: ",e),!1}}isTabletDevice(){try{return new ei().getDeviceType()===Xo.TABLET}catch(e){return this.loggingService.catch("Error in DomService isTabletDevice: ",e),!1}}isDesktopDevice(){try{return new ei().getDeviceType()===Xo.DESKTOP}catch(e){return this.loggingService.catch("Error in DomService isDesktopDevice: ",e),!1}}deepCloneElement(e){try{var i=document.createElement(e?.tagName);return Array.from(e.attributes).forEach(r=>{i.setAttribute(r.nodeName,r.nodeValue)}),e.childNodes.forEach(r=>{r.nodeType===Node.ELEMENT_NODE?i.appendChild(this.deepCloneElement(r)):r.nodeType===Node.TEXT_NODE&&i.appendChild(document.createTextNode(r.nodeValue))}),i}catch(r){return this.loggingService.catch("Error in DomService deepCloneElement: ",r),e}}setRandomNumberToElementRecursive(e){try{if(!e)return;let i=Math.random().toString(36).substring(7);e&&e.setAttribute&&typeof e.setAttribute=="function"&&(e.getAttribute("velt-wireframe-id")||e.setAttribute("velt-wireframe-id",i)),Array.from(e.children).forEach(a=>{this.setRandomNumberToElementRecursive(a)})}catch(i){this.loggingService.catch("Error in DomService setRandomNumberToElementRecursive: ",i)}}setDialogOpenedInSidebar(e){this.dialogOpenedInSidebar$.next(e)}getDialogOpenedInSidebar(){return this.dialogOpenedInSidebar$.asObservable()}removeWireframeSuffixFromTags(e){if(!e)return;Array.from(e.children).forEach(r=>{if(this.removeWireframeSuffixFromTags(r),r.tagName.toLowerCase().endsWith("-wireframe")){let a=r.tagName.toLowerCase().replace("-wireframe",""),s=document.createElement(a);for(Array.from(r.attributes).forEach(c=>{s.setAttribute(c.name,c.value)});r.firstChild;)s.appendChild(r.firstChild);r.parentNode.replaceChild(s,r)}})}isMonitorDevice(){try{return new ei().getDeviceType()===Xo.MONITOR}catch(e){return this.loggingService.catch("Error in DomService isMonitorDevice: ",e),!1}}};o.MULTIPLE_NBSP_REGEX=/(?: \s*){2,}/g,o.TRIM_NBSP_REGEX=/^(?: \s*)+|(?: \s*)+$/g,o.\u0275fac=function(i){return new(i||o)(Q(Yo),Q(y),Q(Rs))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var je=(()=>{let o=class o{constructor(e,i,r,a,s,c,p,u){this.afAuth=e,this.configService=i,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 Do,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.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(U.LOCAL_STORAGE.VELT_USER_FORCE_RE_LOGGED_IN)==="true",this.sessionReLoginSubscription=qn(this.afAuth).pipe(Wo(this.afAuth.currentUser),Ai(),ue(([C,E])=>this.domService.onNetworkStatusChange$().pipe(Ne(A=>A),et(1),ce(()=>({previousUser:C,currentUser:E}))))).subscribe(A=>te(this,[A],function*({previousUser:C,currentUser:E}){if(!E&&C){let B=C?.stsTokenManager?.expirationTime,G=new Date().getTime(),K=B-G;G>B&&(this.analyticsService.trackEvent(X.Events.Core.SDK_SESSION_TOKEN_EXPIRED,{apiKey:this.apiKey,user:this.user$.value,lastLoggedInUserData:this.lastLoggedInUserData,timeLeft:K,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(X.Events.Core.SDK_SESSION_RE_LOGIN_COUNT_EXCEEDED,{apiKey:this.apiKey,clientUserId:this.lastLoggedInUserData.user.userId,snippylyUserId:this.lastLoggedInUserData.user.userSnippylyId,timeLeft:K,forceReset:this.userOptions$.value?.forceReset,sessionReLoginCount:this.sessionReLoginCount},!0,this.user$.value?.userSnippylyId),this.sessionReLoginSubscription?.unsubscribe()):(this.sessionReLoginCount++,this.analyticsService.trackEvent(X.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:K,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(qt(Vi)).subscribe(C=>{let E=ua(C);this.coreActionsService.triggerAction(Id.USER_UPDATE,E)})}catch(C){this.loggingService.catch("Error in AuthService constructor: ",C)}}setApiKey(e,i){this.loggingService.log("%c[WB] Calling FUNCTION: setApiKey","color: green;",e);try{if(this.apiKey){this.loggingService.log("API key is already set");return}this.apiKey=e,this.configService.setApiKey(this.apiKey),i||(i=new EM),this.configService.initConfig(i),i.debugMode?sessionStorage.setItem("debugMode","true"):sessionStorage.removeItem("debugMode"),this.autoLoginCalled||qn(this.afAuth).pipe(et(1)).subscribe(r=>te(this,null,function*(){if(this.autoLoginCalled=!0,r){let a=yield fd(r,!0).catch(s=>null);if(a){let{user:s}=a?.claims;this.autoLoginRequired&&this.initializeClient(s,this.userOptions$?.value?T(I({},this.userOptions$?.value),{replaceContacts:!1,replaceGroupContacts:!1,replacePrivateContacts:!1}):{},new Date().getTime(),!0,"internal-autoLogin")}}}))}catch(r){this.loggingService.catch("Error in setApiKey: ",r)}}setUsersService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setUsersService","color: green;"),this.usersService=e}catch(i){this.loggingService.catch("Error in setUsersService: ",i)}}setDocService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocService","color: green;"),this.docService=e}catch(i){this.loggingService.catch("Error in setDocService: ",i)}}setContactService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setContactService","color: green;"),this.contactService=e}catch(i){this.loggingService.catch("Error in setContactService: ",i)}}setIamService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setIamService","color: green;"),this.iamService=e}catch(i){this.loggingService.catch("Error in setIamService: ",i)}}setAreaService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setAreaService","color: green;"),this.areaService=e}catch(i){this.loggingService.catch("Error in setAreaService: ",i)}}setCommentService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setCommentService","color: green;"),this.commentService=e}catch(i){this.loggingService.catch("Error in setCommentService: ",i)}}setReactionService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setReactionService","color: green;"),this.reactionService=e}catch(i){this.loggingService.catch("Error in setReactionService: ",i)}}setRecorderAnnotationService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setRecorderAnnotationService","color: green;"),this.recorderAnnotationService=e}catch(i){this.loggingService.catch("Error in setRecorderAnnotationService: ",i)}}setViewsService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setViewsService","color: green;"),this.viewsService=e}catch(i){this.loggingService.catch("Error in setViewsService: ",i)}}setCommonDbService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setCommonDbService","color: green;"),this.commonDbService=e}catch(i){this.loggingService.catch("Error in setCommonDbService: ",i)}}validateOrganizationId(e){if(this.isVersionGreaterThanOrEqualTo4()&&!e?.organizationId)if(this.analyticsService.trackEvent(X.Events.Core.SDK_VALIDATE_CLIENT_FAILED,{apiKey:this.apiKey,clientUserId:e.userId,snippylyUserId:e.userSnippylyId,message:"Organization Id is not set",forceReset:this.userOptions$.value?.forceReset,user:this.getUserWithoutContacts(e)},!0,e.userSnippylyId),this.configService.getSF())this.loggingService.catch("OrganizationId is not set in Identify method",void 0,void 0,!0);else throw new Error("OrganizationId is not set in Identify method")}initializeClient(e,i,r,a,s){return te(this,null,function*(){try{if(this.autoLoginRequired=!1,this.userOptions$.next(i),this.initializeClientToken)this.pendingUserLogin=e,this.pendingUserLoginSource=s;else{e.userSnippylyId=gm(this.configService.getApiKey(),e.userId),this.pendingUserLogin=void 0,this.pendingUserLoginSource=void 0,this.initializeClientToken=r;let c=yield qn(this.afAuth).pipe(et(1)).toPromise().catch(u=>null),p=!0;if(this.providedUser=JSON.parse(JSON.stringify(e)),c){let u=yield fd(c,!0).catch(A=>null);if(!u)return;let{user:C,firebaseConfig:E}=u.claims;if(c?.uid!==e?.userSnippylyId||e?.groupId!==C?.groupId||e?.organizationId!==C?.organizationId||i?.forceReset||!a&&e?.organizationId&&!this.forceReLoggedIn||this.forceReLoginRequiredForAdvancedQueries(e)||this.forceReLoginRequiredForRegion(e,E))localStorage.setItem(U.LOCAL_STORAGE.VELT_USER_FORCE_RE_LOGGED_IN,"true"),this.forceReLoggedIn=!0,yield this.signOutUser("internal");else{this.loggingService.log("%c[WB] Calling FUNCTION: reinitializeCurrentUser","color: green;"),this.loggingService.log("Keeping user");let A=yield fd(c,!0).catch(pe=>null);if(!A)return;let{firebaseConfig:B,user:G,advancedQueries:K}=A.claims;this.validateOrganizationId(e),this.setFirebaseConfig(B),this.setAdvancedQueries(K),G&&(this.providedUser.isAdmin=!!G.isAdmin),this.initializeSignedInUser(c,a),p=!1,this.analyticsService.trackEvent(X.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(X.Events.Core.SDK_VALIDATE_CLIENT_TRIGGERED,{apiKey:this.apiKey,clientUserId:e.userId,snippylyUserId:e.userSnippylyId,forceReset:this.userOptions$.value?.forceReset,user:this.getUserWithoutContacts(e),source:s},!0,e.userSnippylyId);let u=_r(this.functions,Sr({url:Xn.cloudFunction.validateClient,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:20*60*1e3}),C=pa(),E=(yield u({apiKey:this.apiKey,user:e,version:C,authToken:i?.authToken}))?.data;if(E.error){if(this.analyticsService.trackEvent(X.Events.Core.SDK_VALIDATE_CLIENT_FAILED,{apiKey:this.apiKey,clientUserId:e.userId,snippylyUserId:e.userSnippylyId,message:E.error,forceReset:this.userOptions$.value?.forceReset,user:this.getUserWithoutContacts(e),source:s},!0,e.userSnippylyId),E.error&&typeof E.error=="string"&&E.error?.toLowerCase()?.includes("token expired"))if(this.tokenExpiredErrorCount++,this.tokenExpiredErrorCount<=this.TOKEN_EXPIRED_ERROR_COUNT_LIMIT){let A={code:"token_expired",message:"Token expired"};this.coreActionsService.triggerAction(Id.ERROR,A)}else{let A={code:"too_many_retries",message:"Token expired. Too many retries."};this.coreActionsService.triggerAction(Id.ERROR,A),this.analyticsService.trackEvent(X.Events.Core.SDK_JWT_EXPIRED_RETRY_EXCEEDED,{apiKey:this.apiKey,clientUserId:e.userId,snippylyUserId:e.userSnippylyId,forceReset:this.userOptions$.value?.forceReset,source:s},!0,e.userSnippylyId)}throw E.error}else this.tokenExpiredErrorCount=0;if(this.analyticsService.trackEvent(X.Events.Core.SDK_VALIDATE_CLIENT_SUCCESS,{apiKey:this.apiKey,clientUserId:e.userId,snippylyUserId:e.userSnippylyId,forceReset:this.userOptions$.value?.forceReset,user:this.getUserWithoutContacts(e),source:s},!0,e.userSnippylyId),this.validateOrganizationId(e),E.firebaseConfig){this.setFirebaseConfig(E.firebaseConfig),yield this.signInWithCustomToken(e,E.token),this.loggingService.log("new signed in user",this.afAuth.currentUser);let A=yield fd(this.afAuth.currentUser,!0).catch(K=>null);if(!A)return;let{user:B,advancedQueries:G}=A.claims;this.setAdvancedQueries(G),this.providedUser.isAdmin=!!B?.isAdmin,this.initializeSignedInUser(this.afAuth.currentUser,a)}}this.initializeClientToken=0,this.lastLoggedInUserData={user:e,userOptions:i,initializeClientToken:r,autoLogin:a},this.checkForPendingLogin()}return e}catch(c){return this.initializeClientToken=0,this.checkForPendingLogin(),this.loggingService.catch("Error in initializeClient: ",c),Promise.resolve(null)}})}isVersionGreaterThanOrEqualTo4(){try{let e=pa();return(e?parseInt(e.split(".")?.[0]||"0"):0)>=4}catch(e){return this.loggingService.catch("Error in isVersionGreaterThanOrEqualTo4: ",e),!1}}forceReLoginRequiredForAdvancedQueries(e){try{let i=this.isVersionGreaterThanOrEqualTo4(),r=!1;try{let a=localStorage.getItem(U.LOCAL_STORAGE.VELT_ADVANCED_QUERIES);a&&(r=JSON.parse(a)?.advancedQueriesEnabled)}catch(a){this.loggingService.catch("Error in forceReLoginRequiredForAdvancedQueries: ",a)}return!!(i&&e.organizationId&&!r)}catch(i){return this.loggingService.catch("Error in forceReLoginRequiredForAdvancedQueries: ",i),!1}}forceReLoginRequiredForRegion(e,i){try{return!!(this.isVersionGreaterThanOrEqualTo4()&&e.organizationId&&!i?.region)}catch(r){return this.loggingService.catch("Error in forceReLoginRequiredForRegion: ",r),!1}}checkForPendingLogin(){this.pendingUserLogin&&this.initializeClient(this.pendingUserLogin,this.userOptions$?.value||{},new Date().getTime(),void 0,this.pendingUserLoginSource)}setFirebaseConfig(e){this.loggingService.log("%c[WB] Calling FUNCTION: setFirebaseConfig","color: green;");try{this.firebaseConfig$.value||this.firebaseConfig$.next({firebaseOptions:I(I({},Xn.firebaseConfig),e)})}catch(i){this.loggingService.catch("Error in setFirebaseConfig: ",i)}}getFirebaseConfig$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getFirebaseConfig","color: green;"),this.firebaseConfig$.asObservable()}getFirebaseConfig(){return this.loggingService.log("%c[WB] Calling FUNCTION: getFirebaseConfig","color: green;"),this.firebaseConfig$.value}setAdvancedQueries(e){this.loggingService.log("%c[WB] Calling FUNCTION: setAdvancedQueries","color: green;");try{e&&typeof e=="object"&&localStorage.setItem(U.LOCAL_STORAGE.VELT_ADVANCED_QUERIES,JSON.stringify(e)),this.advancedQueries$.next(e)}catch(i){this.loggingService.catch("Error in setAdvancedQueries: ",i)}}getAdvancedQueries$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getAdvancedQueries$","color: green;"),this.advancedQueries$.asObservable()}getAdvancedQueries(){return this.loggingService.log("%c[WB] Calling FUNCTION: getAdvancedQueries","color: green;"),this.advancedQueries$.value}getAdvancedQueriesEnabled$(){return Mn([this.configService.getConfig$(),this.getAdvancedQueries$()]).pipe(ce(()=>this.getAdvancedQueriesEnabled()),Vn(()=>re(!1)))}getAdvancedQueriesEnabled(){try{return!this.configService.getConfig()?.advancedQueriesDisabled&&!!this.getAdvancedQueries()?.advancedQueriesEnabled}catch(e){return this.loggingService.catch("Error in getAdvancedQueriesEnabled: ",e),!1}}signOutPreviousUser(){return this.signOutPreviousUser$.asObservable()}getUser(){return this.loggingService.log("%c[WB] Calling FUNCTION: getUser","color: green;"),this.afAuth?.currentUser?this.user$.value:null}getUser$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getUser$","color: green;"),qn(this.afAuth).pipe(ue(e=>e?this.user$.asObservable():re(null)))}getAuthUser(){return this.loggingService.log("%c[WB] Calling FUNCTION: getAuthUser","color: green;"),this.afAuth?.currentUser}getUserOptions(){return this.loggingService.log("%c[WB] Calling FUNCTION: getUserOptions","color: green;"),this.userOptions$.value}getUserOptions$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getUserOptions$","color: green;"),this.userOptions$.asObservable()}updateUser(e){this.loggingService.log("%c[WB] Calling FUNCTION: updateUser","color: green;");try{let i=this.user$.value;if(e.userId&&e.userId!==i?.userId||e?.groupId&&e?.groupId!==i?.groupId||e?.organizationId&&e?.organizationId!==i?.organizationId)this.providedUser=e,this.initializeClient(e,this.userOptions$?.value||{},new Date().getTime(),void 0,"internal-updateUser");else if(this.providedUser=I(I({},this.providedUser),e),i){let r=I(I({},i),e);this.updateUserInternally(r)}}catch(i){this.loggingService.catch("Error in updateUser: ",i)}}signInWithCustomToken(e,i,r="manual"){this.loggingService.log("%c[WB] Calling FUNCTION: signInWithCustomToken","color: green;");try{return BQ(this.afAuth,i).then(a=>(this.analyticsService.trackEvent(X.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(X.Events.Core.SDK_USER_AUTH_FAILED,{apiKey:this.apiKey,clientUserId:e.userId,snippylyUserId:e.userSnippylyId,authType:r,forceReset:this.userOptions$.value?.forceReset,message:a.message,user:this.getUserWithoutContacts(e)}),a))}catch(a){return this.loggingService.catch("Error in signInWithCustomToken: ",a),Promise.reject(a)}}resetServicesCache(){this.loggingService.log("%c[WB] Calling FUNCTION: resetServicesCache in AuthService","color: green;");try{this.commonDbService?.unsubscribeFromObservables(),this.docService?.clearCache(),this.contactService?.clearCache(),this.iamService?.clearCache(),this.areaService?.clearCache(),this.commentService?.clearCache(),this.reactionService?.clearCache(),this.recorderAnnotationService?.clearCache(),this.viewsService?.clearCache()}catch(e){this.loggingService.catch("Error in resetServicesCache: ",e)}}initializeSignedInUser(e,i){this.loggingService.log("%c[WB] Calling FUNCTION: initializeSignedInUser","color: green;");try{let r=new Do;r.userSnippylyId=e.uid,r.type="signedIn",this.mergeUserWithProvidedUserData(r,i)}catch(r){this.loggingService.catch("Error in initializeSignedInUser: ",r)}}mergeUserWithProvidedUserData(e,i){return te(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: mergeUserWithProvidedUserData","color: green;");try{e.userId=this.providedUser?.userId||e.userId;let r=null;if(this.usersService?.userDataProviderAvailable()){let a=yield this.usersService.resolveUsers([e.userId]);a&&a[e.userId]&&(r=JSON.parse(JSON.stringify(a[e.userId]||{}))),e=I(I({},e),r||{})}e.name=r?r?.name:this.providedUser?.name||e.name,e.clientUserName=r?r?.clientUserName:this.providedUser?.clientUserName||e.clientUserName,e.photoUrl=r?r?.photoUrl:this.providedUser?.photoUrl||e.photoUrl,e?.photoUrl===void 0&&(e.photoUrl=null),e.email=r?r?.email:this.providedUser?.email||e.email,e.color=r?r?.color:this.providedUser?.color||this.avatarService.generateUserColor(Cn(e.userId)),e.textColor=r?r?.textColor:this.providedUser?.textColor||"#FFFFFF",e.initial=r?r?.initial:this.providedUser?.initial||e.initial||e.name?.charAt(0).toUpperCase()||e.email?.charAt(0).toUpperCase(),e.contacts=this.providedUser?.contacts||e.contacts,e.plan=this.providedUser?.plan||e.plan,e.groupId=this.providedUser?.groupId||e.groupId,e.clientGroupId=this.providedUser?.clientGroupId||e.clientGroupId,e.clientOrganizationId=this.providedUser?.clientOrganizationId||e.clientOrganizationId,e.organizationId=this.providedUser?.organizationId||e.organizationId,e.isAdmin=this.providedUser?.isAdmin,e.isReadOnly=this.providedUser?.isReadOnly,e.isAnonymous=this.providedUser?.isAnonymous,e.isGuest=this.providedUser?.isGuest,this.updateUserInternally(e)}catch(r){this.loggingService.catch("Error in mergeUserWithProvidedUserData: ",r)}})}updateUserInternally(e){return te(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: updateUserInternally","color: green;");try{let i=Object.assign({},e);delete i.contacts,this.analyticsService.identifyUser(e.userSnippylyId,i,{forceReset:this.userOptions$.value?.forceReset}),this.getPlanDetailsCalled||(yield this.getPlanDetailsFromDb()),this.afAuth.currentUser&&(this.user$.next(e),this.updateUserToFirebase(e))}catch(i){this.loggingService.catch("Error in updateUserInternally: ",i)}})}updateUserToFirebase(e){this.loggingService.log("%c[WB] Calling FUNCTION: updateUserToFirebase","color: green;");try{let i=JSON.parse(JSON.stringify(e)),r=T(I({},i),{lastUpdated:new Date})}catch(i){this.loggingService.catch("Error in updateUserToFirebase: ",i)}}getPlanDetailsFromDb(){return te(this,null,function*(){try{this.getPlanDetailsCalled=!0;let i=yield _r(this.functions,Sr({url:Xn.cloudFunction.getPlanDetails,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:20*60*1e3})({apiKey:this.configService.getApiKey(),sdkVersion:pa(),sdkType:this.configService.getSdkType()});return i?.data?.isPlanExpired&&(this.analyticsService.trackEvent(X.Events.Core.SDK_PLAN_EXPIRED),this.configService.getSF()||console.warn("Velt SDK plan has expired.")),this.planDetails$.next(i?.data||{planInfo:null,isPlanExpired:!1}),i}catch(e){return this.loggingService.catch("Error in getPlanDetailsFromDb: ",e),this.planDetails$.next({planInfo:null,isPlanExpired:!1}),Promise.resolve(null)}})}isPlanExpired$(){return this.planDetails$.pipe(Ne(e=>!!e),ce(e=>!!e?.isPlanExpired))}isPlanExpired(){return this.planDetails$.getValue()?.isPlanExpired}addPreSignOutFuction(e,i){try{this.preSignOutFunctions.set(e,i)}catch(r){this.loggingService.catch("Error in addPreSignOutFuction: ",r)}}setUserOrganization(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setUserOrganization","color: green;");let i=JSON.parse(JSON.stringify(this.userOrganization$.value||{}));this.getUser()?.organizationId===e?.organizationId?(i.metadata=e,this.userOrganization$.next(i)):this.userOrganization$.next(null)}catch(i){this.loggingService.catch("Error in setUserOrganization: ",i)}}setOrganizationUserGroups(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setUserOrganizationGroups","color: green;");let i=JSON.parse(JSON.stringify(this.userOrganization$.value||{}));this.getUser()?.organizationId===i?.metadata?.organizationId&&(i.groups=e,this.userOrganization$.next(i))}catch(i){this.loggingService.catch("Error in setUserOrganizationGroups: ",i)}}getUserOrganization$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getUserOrganization$","color: green;"),this.getUser$().pipe(ue(e=>e?this.userOrganization$.asObservable().pipe(ce(i=>i?.metadata?.organizationId===e.organizationId?i:null)):re(null)))}signOutUser(e="internal"){return te(this,null,function*(){try{yield this.analyticsService.trackEvent(X.Events.Core.SDK_USER_SIGN_OUT,{apiKey:this.apiKey,clientUserId:this.user$?.value?.userId,snippylyUserId:this.user$?.value?.userSnippylyId,message:e==="external"?"User Sign out":"System Sign out",user:this.user$?.value?this.getUserWithoutContacts(this.user$?.value):null,forceReset:this.userOptions$.value?.forceReset,source:e});let i=yield qn(this.afAuth).pipe(et(1)).toPromise().catch(r=>null);if(i){this.user$.next(null);for(let[r,a]of this.preSignOutFunctions)try{yield a(i)}catch(s){this.loggingService.catch(`Error in signOutUser ${r} function: `,s)}return this.resetServicesCache(),this.user$.next(null),VQ(this.afAuth).catch(r=>{this.loggingService.catch("Error in signOutUser:",r)})}else return Promise.resolve()}catch(i){this.loggingService.catch("Error in signOutUser: ",i)}})}isFeatureAllowed(e){return Ji(this.config,this.user$.value,e)}getUserWithoutContacts(e){try{if(e){let i=JSON.parse(JSON.stringify(e));return delete i.contacts,i}else return null}catch(i){return this.loggingService.catch("Error in getUserWithoutContacts: ",i),null}}getUserForClient(e){try{return ua(e)}catch(i){return this.loggingService.catch("Error in getUserForClient: ",i),null}}};o.\u0275fac=function(i){return new(i||o)(Q(Si),Q(jt),Q(bm),Q(Hp),Q(Fe),Q(Uo),Q(Ke),Q(y))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Im=class{constructor({apiKey:o,documentId:t,organizationId:e,clientDocumentId:i,clientOrganizationId:r}){this.paths={},this.apiKey=o,this.documentId=t,this.organizationId=e,this.clientDocumentId=i,this.clientOrganizationId=r,i&&(this.documentId=dc(i)),r&&(this.organizationId=pc(r)),this.generateDocumentPaths()}generateDocumentPaths(){try{if(this.paths.clientDocumentId=this.clientDocumentId,this.paths.documentId=this.documentId,this.organizationId&&(this.paths.organizationId=this.organizationId,this.paths.clientOrganizationId=this.clientOrganizationId),this.apiKey){let o=`${this.apiKey}`;this.organizationId&&(o=`${o}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${this.paths.organizationId}`),this.documentId&&(this.paths.docs=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/`,this.paths.presence=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_PRESENCE}/`,this.paths.cursor=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_CURSOR}/`,this.paths.comment=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_COMMENT}/`,this.paths.multiThread=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_MULTI_THREAD}/`,this.paths.tag=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_TAG}/`,this.paths.area=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_AREA}/`,this.paths.arrow=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_ARROW}/`,this.paths.selection=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_SELECTION}/`,this.paths.audioHuddle=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_AUDIO_HUDDLE}/`,this.paths.huddle=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_HUDDLE}/`,this.paths.recorder=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_RECORDER}/`,this.paths.flock=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_FOLLOW_ALONG}/`,this.paths.syncVideoPlayer=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_SYNC_VIDEO_PLAYER}/`,this.paths.liveState=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_LIVE_STATE}/`,this.paths.liveStateSingleEditorMode=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_LIVE_STATE}/default/singleEditorMode`,this.paths.reaction=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_REACTION}/`,this.paths.views=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_VIEWS}/`,this.paths.notifications=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_NOTIFICATIONS}/`,this.paths.metadata=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_METADATA}/`,this.paths.users=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_USERS}/`,this.paths.documentIam=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_IAM}/`),this.paths.customerMetadata=`${o}/${U.FIREBASE_PARTIAL_PATH_CUSTOMER_METADATA}/`,this.paths.groupContacts=`${o}/${U.FIREBASE_PARTIAL_PATH_CONTACTS}/${U.FIREBASE_PARTIAL_PATH_GROUPS}/`,this.paths.globalContacts=`${o}/${U.FIREBASE_PARTIAL_PATH_CONTACTS}/${U.FIREBASE_PARTIAL_PATH_GLOBAL}/`,this.paths.logins=`${o}/${U.FIREBASE_PARTIAL_PATH_CONTACTS}/${U.FIREBASE_PARTIAL_PATH_LOGINS}/`,this.paths.userFeedback=`${o}/${U.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${U.FIREBASE_PARTIAL_PATH_FEEDBACK}/`,this.paths.userReportBugs=`${o}/${U.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${U.FIREBASE_PARTIAL_PATH_BUGS}/`,this.paths.userContactUs=`${o}/${U.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${U.FIREBASE_PARTIAL_PATH_CONTACT_US}/`,this.organizationId&&(this.paths.organizationMetadata=`${o}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_METADATA}/`,this.paths.organizationIam=`${o}/${U.FIREBASE_PARTIAL_PATH_IAM}/`,this.paths.organizationGroups=`${o}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_GROUPS}/`,this.paths.organizationNotifications=`${o}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/`,this.documentId&&(this.paths.organizationNotificationsWithDocumentId=`${o}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/`),this.paths.organizationNotificationsLastNotificationTimestamp=`${o}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${U.FIREBASE_PARTIAL_PATH_LAST_NOTIFICATION_TIMESTAMP}/${U.FIREBASE_PARTIAL_PATH_DOCS}/`,this.paths.organizationNotificationsUsers=`${o}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${U.FIREBASE_PARTIAL_PATH_USERS}/`),this.paths.workspaceIam=`${this.apiKey}/${U.FIREBASE_PARTIAL_PATH_IAM}/`}}catch{}}get workspaceIam(){return this.paths.workspaceIam?this.paths.workspaceIam:this.throwError("Workspace IAM path is not available.")}get docs(){return this.paths.docs?this.paths.docs:this.throwError("Docs path is not available.")}get presence(){return this.paths.presence?this.paths.presence:this.throwError("Presence path is not available.")}get cursor(){return this.paths.cursor?this.paths.cursor:this.throwError("Cursor path is not available.")}get area(){return this.paths.area?this.paths.area:this.throwError("Area path is not available.")}get arrow(){return this.paths.arrow?this.paths.arrow:this.throwError("Arrow path is not available.")}get comment(){return this.paths.comment?this.paths.comment:this.throwError("Comment path is not available.")}get multiThread(){return this.paths.multiThread?this.paths.multiThread:this.throwError("Multi thread path is not available.")}get tag(){return this.paths.tag?this.paths.tag:this.throwError("Tag path is not available.")}get selection(){return this.paths.selection?this.paths.selection:this.throwError("Selection path is not available.")}get audioHuddle(){return this.paths.audioHuddle?this.paths.audioHuddle:this.throwError("Audio huddle path is not available.")}get huddle(){return this.paths.huddle?this.paths.huddle:this.throwError("Huddle path is not available.")}get recorder(){return this.paths.recorder?this.paths.recorder:this.throwError("Recorder path is not available.")}get flock(){return this.paths.flock?this.paths.flock:this.throwError("Flock path is not available.")}get syncVideoPlayer(){return this.paths.syncVideoPlayer?this.paths.syncVideoPlayer:this.throwError("Sync video player path is not available.")}get liveState(){return this.paths.liveState?this.paths.liveState:this.throwError("Live state path is not available.")}get liveStateSingleEditorMode(){return this.paths.liveStateSingleEditorMode?this.paths.liveStateSingleEditorMode:this.throwError("Live state single editor mode path is not available.")}get reaction(){return this.paths.reaction?this.paths.reaction:this.throwError("Reaction path is not available.")}get views(){return this.paths.views?this.paths.views:this.throwError("Views path is not available.")}get notifications(){return this.paths.notifications?this.paths.notifications:this.throwError("Notifications path is not available.")}get metadata(){return this.paths.metadata?this.paths.metadata:this.throwError("Metadata path is not available.")}get users(){return this.paths.users?this.paths.users:this.throwError("Users path is not available.")}get documentIam(){return this.paths.documentIam?this.paths.documentIam:this.throwError("Document IAM path is not available.")}get organizationMetadata(){return this.paths.organizationMetadata?this.paths.organizationMetadata:this.throwError("Organization metadata path is not available.")}get organizationIam(){return this.paths.organizationIam?this.paths.organizationIam:this.throwError("Organization IAM path is not available.")}get customerMetadata(){return this.paths.customerMetadata?this.paths.customerMetadata:this.throwError("Customer metadata path is not available.")}get groupContacts(){return this.paths.groupContacts?this.paths.groupContacts:this.throwError("Group contacts path is not available.")}get globalContacts(){return this.paths.globalContacts?this.paths.globalContacts:this.throwError("Global contacts path is not available.")}get logins(){return this.paths.logins?this.paths.logins:this.throwError("Logins path is not available.")}get userFeedback(){return this.paths.userFeedback?this.paths.userFeedback:this.throwError("User feedback path is not available.")}get userReportBugs(){return this.paths.userReportBugs?this.paths.userReportBugs:this.throwError("User report bugs path is not available.")}get userContactUs(){return this.paths.userContactUs?this.paths.userContactUs:this.throwError("User contact us path is not available.")}get organizationGroups(){return this.paths.organizationGroups?this.paths.organizationGroups:this.throwError("Organization groups path is not available.")}get organizationNotifications(){return this.paths.organizationNotifications?this.paths.organizationNotifications:this.throwError("Organization notifications path is not available.")}get organizationNotificationsWithDocumentId(){return this.paths.organizationNotificationsWithDocumentId?this.paths.organizationNotificationsWithDocumentId:this.throwError("Organization notifications with document id path is not available.")}get organizationNotificationsUsers(){return this.paths.organizationNotificationsUsers?this.paths.organizationNotificationsUsers:this.throwError("Organization notifications users path is not available.")}get organizationNotificationsLastNotificationTimestamp(){return this.paths.organizationNotificationsLastNotificationTimestamp?this.paths.organizationNotificationsLastNotificationTimestamp:this.throwError("Organization notifications last notification timestamp path is not available.")}throwError(o){throw{type:"DocumentPaths",message:o,metadata:{apiKey:this.apiKey,documentId:this.documentId,organizationId:this.organizationId}}}};var HM=class{constructor({apiKey:o,documentId:t,organizationId:e,clientDocumentId:i,clientOrganizationId:r,folderId:a,veltFolderId:s}){this.paths={},this.apiKey=o,this.documentId=t,this.organizationId=e,this.veltFolderId=s,i&&(this.documentId=dc(i)),r&&(this.organizationId=pc(r)),a&&(this.folderId=a,this.veltFolderId=_l(a)),this.generateDocumentPaths()}generateDocumentPaths(){try{if(this.paths.clientDocumentId=this.clientDocumentId,this.paths.documentId=this.documentId,this.organizationId&&(this.paths.organizationId=this.organizationId,this.paths.clientOrganizationId=this.clientOrganizationId),this.veltFolderId&&(this.paths.folderId=this.folderId,this.paths.veltFolderId=this.veltFolderId),this.apiKey){let o=`apiKey/${this.apiKey}`;this.organizationId&&(o=`${o}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${this.paths.organizationId}`,this.paths.organization=o,this.paths.folder=`${o}/${U.FIREBASE_PARTIAL_PATH_FOLDERS}`,this.paths.organizationUsers=`${o}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_USERS}`,this.paths.notificationDocs=`${o}/${U.FIREBASE_PARTIAL_PATH_NOTIFICATION_DOCS}`,this.paths.notificationUsers=`${o}/${U.FIREBASE_PARTIAL_PATH_NOTIFICATION_USERS}`,this.paths.organizationGroups=`${o}/${U.FIREBASE_PARTIAL_PATH_GROUPS}`,this.paths.lastNotificationTimestamp=`${o}/${U.FIREBASE_PARTIAL_PATH_LAST_NOTIFICATION_TIMESTAMP}`),this.veltFolderId&&(this.paths.folderUsers=`${o}/${U.FIREBASE_PARTIAL_PATH_FOLDERS}/${this.veltFolderId}/${U.FIREBASE_PARTIAL_PATH_FOLDER_USERS}`),this.documentId&&(this.paths.document=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}`,this.paths.comment=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_COMMENT}`,this.paths.location=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_LOCATION}`,this.paths.multiThread=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_MULTI_THREAD}`,this.paths.area=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_AREA}`,this.paths.recorder=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_RECORDER}`,this.paths.reaction=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_REACTION}`,this.paths.commentViews=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_COMMENT_VIEWS}`,this.paths.notificationViews=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_NOTIFICATION_VIEWS}`,this.paths.documentViews=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_DOCUMENT_VIEWS}`,this.paths.locationViews=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_LOCATION_VIEWS}`,this.paths.documentUsers=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_DOCUMENT_USERS}`,this.paths.docNotification=`${this.paths.notificationDocs}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_DOC_NOTIFICATION}`)}}catch{}}get folder(){return this.paths.folder?this.paths.folder:this.throwError("Folder path is not available.")}get lastNotificationTimestamp(){return this.paths.lastNotificationTimestamp?this.paths.lastNotificationTimestamp:this.throwError("LastNotificationTimestamp path is not available.")}get organizationGroups(){return this.paths.organizationGroups?this.paths.organizationGroups:this.throwError("organizationGroups path is not available.")}get docNotification(){return this.paths.docNotification?this.paths.docNotification:this.throwError("DocNotification path is not available.")}get organization(){return this.paths.organization?this.paths.organization:this.throwError("Organization path is not available.")}get document(){return this.paths.document?this.paths.document:this.throwError("Document path is not available.")}get location(){return this.paths.location?this.paths.location:this.throwError("Location path is not available.")}get area(){return this.paths.area?this.paths.area:this.throwError("Area path is not available.")}get comment(){return this.paths.comment?this.paths.comment:this.throwError("Comment path is not available.")}get commentViews(){return this.paths.commentViews?this.paths.commentViews:this.throwError("CommentViews path is not available.")}get documentViews(){return this.paths.documentViews?this.paths.documentViews:this.throwError("DocumentViews path is not available.")}get locationViews(){return this.paths.locationViews?this.paths.locationViews:this.throwError("LocationViews path is not available.")}get notificationViews(){return this.paths.notificationViews?this.paths.notificationViews:this.throwError("NotificationViews path is not available.")}get documentUsers(){return this.paths.documentUsers?this.paths.documentUsers:this.throwError("DocumentUsers path is not available.")}get folderUsers(){return this.paths.folderUsers?this.paths.folderUsers:this.throwError("FolderUsers path is not available.")}get organizationUsers(){return this.paths.organizationUsers?this.paths.organizationUsers:this.throwError("OrganizationUsers path is not available.")}get notificationDocs(){return this.paths.notificationDocs?this.paths.notificationDocs:this.throwError("NotificationDocs path is not available.")}get notificationUsers(){return this.paths.notificationUsers?this.paths.notificationUsers:this.throwError("NotificationUsers path is not available.")}get multiThread(){return this.paths.multiThread?this.paths.multiThread:this.throwError("Multi thread path is not available.")}get recorder(){return this.paths.recorder?this.paths.recorder:this.throwError("Recorder path is not available.")}get reaction(){return this.paths.reaction?this.paths.reaction:this.throwError("Reaction path is not available.")}throwError(o){throw{type:"DocumentPaths",message:o,metadata:{apiKey:this.apiKey,documentId:this.documentId,organizationId:this.organizationId}}}};var zM=class{};var un=(()=>{let o=class o{constructor(e,i){this.authService=e,this.loggingService=i,this.db$=new ve(null);try{this.authService.getFirebaseConfig$().subscribe(r=>{r&&this.db$.next(Lf(void 0,r.firebaseOptions.databaseURL))},r=>{this.loggingService.catch("Error in DatabaseService constructor: ",r)})}catch(r){this.loggingService.catch("Error in DatabaseService constructor:",r)}}getDb(){return this.db$.asObservable()}};o.\u0275fac=function(i){return new(i||o)(Q(je),Q(y))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var bs=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.analyticsService=i,this.resolveTimeout=1*60*1e3,this.retrySaveConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.retryDeleteConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.retryGetConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.commentAnnotationDataProvider$=new ve(null),this.commentAnnotationById$=new ve({}),this.getCommentAnnotationById=r=>{try{return this.commentAnnotationDataProviderAvailable()?this.commentAnnotationById$.value?.[r]:void 0}catch(a){this.loggingService.catch("Error in CommentAnnotationsResolverService getCommentAnnotationById:",a);return}};try{this.loggingService.log("CommentAnnotationsResolverService initialized"),this.commentAnnotationDataProvider$.subscribe(r=>{r&&(r.config?.resolveTimeout&&(this.resolveTimeout=r.config.resolveTimeout),r.config?.saveRetryConfig&&(this.retrySaveConfig=r.config.saveRetryConfig),r.config?.deleteRetryConfig&&(this.retryDeleteConfig=r.config.deleteRetryConfig),r.config?.getRetryConfig&&(this.retryGetConfig=r.config.getRetryConfig))})}catch(r){this.loggingService.catch("Error in CommentAnnotationsResolverService constructor:",r)}}getProvider(){try{let e=this.commentAnnotationDataProvider$.getValue();return e||void 0}catch(e){this.loggingService.catch("Error in CommentAnnotationsResolverService getProvider:",e);return}}ngOnDestroy(){try{this.commentAnnotationById$.next({})}catch(e){this.loggingService.catch("Error in CommentAnnotationsResolverService ngOnDestroy:",e)}}resolveCommentAnnotations(e){return te(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling CommentAnnotationsResolverService FUNCTION: resolveCommentAnnotations","color: green;"),!this.commentAnnotationDataProviderAvailable())return{};let i,r=!1,a=!1,s=()=>{i&&(clearTimeout(i),i=void 0,a=!0)};return new Promise((c,p)=>{i=setTimeout(()=>{a||(r=!0,s(),p(new Error("Comment annotation resolution timeout")))},this.commentAnnotationDataProvider$.value?.config?.resolveTimeout||this.resolveTimeout);let u=this.getProvider();if(!u)return s(),c({});let C={},E=[...new Set(e.commentAnnotationIds||[])],A=T(I({},e),{commentAnnotationIds:E});te(this,null,function*(){try{if(E.length>0||e.documentIds?.length||e.folderId){let G=uc(()=>u?.get(A)||Promise.resolve(void 0),"getCommentAnnotations",this.retryGetConfig).then(K=>r?{}:(s(),K&&K.statusCode!==200?(this.loggingService.catch(K?.message??"Error in CommentAnnotationsResolverService resolveCommentAnnotations:"),{}):K?.data)).catch(K=>{throw s(),K});try{C=(yield G)||{},this.analyticsService.trackEvent(X.Events.Resolver.COMMENT_RESOLVER_GET,{sourceMethod:"resolveCommentAnnotations",source:"sdk",commentAnnotationIds:E});let K={};Object.entries(C).forEach(([pe,Ce])=>{let Ie=this.commentAnnotationById$.value?.[pe];Ie?Ie&&JSON.stringify(Ie)!==JSON.stringify(Ce)&&(K[pe]=Ce):K[pe]=Ce}),Object.keys(K).length>0&&this.commentAnnotationById$.next(I(I({},this.commentAnnotationById$.getValue()),K)),c(K)}catch(K){r||p(K),c(C)}}else s(),c({})}catch(G){s(),p(G)}})})}catch(i){return this.loggingService.catch("Error in CommentAnnotationsResolverService resolveCommentAnnotations:",i),{}}})}saveCommentAnnotation(e){return te(this,null,function*(){try{this.loggingService.log("%c[WB] Calling CommentAnnotationsResolverService FUNCTION: saveCommentAnnotation","color: green;");let i=this.getProvider();if(!this.commentAnnotationDataProviderAvailable())throw new Error("Comment annotation save data provider not available");let r=JSON.parse(JSON.stringify(this.commentAnnotationById$.getValue()));this.commentAnnotationById$._value=I(I({},r),e.commentAnnotation);let a=yield uc(()=>i?.save({commentAnnotation:e.commentAnnotation,event:e.eventType,commentId:e.commentId,metadata:Object.values(e.commentAnnotation??{})?.[0]?.metadata})||Promise.resolve(void 0),"saveCommentAnnotation",this.retrySaveConfig);return a&&a.statusCode!==200?(this.retrySaveConfig.revertOnFailure&&(this.commentAnnotationById$._value=r),this.loggingService.catch(a?.message??"Error in CommentAnnotationsResolverService saveCommentAnnotation:"),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(X.Events.Resolver.COMMENT_RESOLVER_SAVE,{sourceMethod:"saveCommentAnnotation",source:"sdk",commentAnnotationIds:Object.keys(e.commentAnnotation),eventType:e.eventType,commentId:e.commentId}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0})}catch(i){return this.loggingService.warn("Error in CommentAnnotationsResolverService saveCommentAnnotation:",i),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0}}})}deleteCommentAnnotation(e,i){return te(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 uc(()=>r?.delete({commentAnnotationId:e.toString(),metadata:i,event:Wa.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(X.Events.Resolver.COMMENT_RESOLVER_DELETE,{sourceMethod:"deleteCommentAnnotation",source:"sdk",commentAnnotationId:e.toString()}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0})}catch(r){return this.loggingService.warn("Error in CommentAnnotationsResolverService deleteCommentAnnotation:",r),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0}}})}getCommentAnnotationsById$(){try{return this.commentAnnotationDataProviderAvailable()?(this.loggingService.log("%c[WB] Calling CommentAnnotationsResolverService FUNCTION: getCommentAnnotationsById$","color: green;"),this.commentAnnotationById$.asObservable()):re(void 0)}catch(e){return this.loggingService.catch("Error in CommentAnnotationsResolverService getCommentAnnotationsById$:",e),re(void 0)}}getAnnotationById(e){try{return this.commentAnnotationDataProviderAvailable()?this.commentAnnotationById$.getValue()?.[e]:void 0}catch(i){this.loggingService.catch("Error in CommentAnnotationsResolverService getAnnotationById:",i);return}}setCommentAnnotationDataProvider(e){try{if(e){this.loggingService.log("Setting comment annotation data provider");let r=["get","save","delete"].filter(a=>!(a in e)||typeof e[a]!="function");if(r.length>0){let a=`DataProviders.comment is invalid. The following methods are missing or are not functions: ${r.join(", ")}.`;this.loggingService.catch(a);return}else this.commentAnnotationDataProvider$.next(e)}}catch(i){this.loggingService.catch("Error in CommentAnnotationsResolverService setCommentAnnotationDataProvider:",i)}}commentAnnotationDataProviderAvailable(){try{return!!this.commentAnnotationDataProvider$.getValue()}catch(e){return this.loggingService.catch("Error in CommentAnnotationsResolverService commentAnnotationDataProviderAvailable:",e),!1}}};o.\u0275fac=function(i){return new(i||o)(Q(y),Q(Ke))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Em=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.analyticsService=i,this.resolveTimeout=1*60*1e3,this.retrySaveConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.retryDeleteConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.retryGetConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.reactionAnnotationDataProvider$=new 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 te(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling ReactionAnnotationsResolverService FUNCTION: resolveReactionAnnotations","color: green;"),!this.reactionAnnotationDataProviderAvailable())return{};let i,r=!1,a=!1,s=()=>{i&&(clearTimeout(i),i=void 0,a=!0)};return new Promise((c,p)=>{i=setTimeout(()=>{a||(r=!0,s(),p(new Error("Reaction annotation resolution timeout")))},this.reactionAnnotationDataProvider$.value?.config?.resolveTimeout||this.resolveTimeout);let u=this.getProvider();if(!u)return s(),c({});let C={},E=[...new Set(e.reactionAnnotationIds||[])],A=T(I({},e),{reactionAnnotationIds:E});te(this,null,function*(){try{if(E.length>0||e.documentIds?.length||e.folderId){let G=uc(()=>u?.get(A)||Promise.resolve(void 0),"getReactionAnnotations",this.retryGetConfig).then(K=>r?{}:(s(),K&&K.statusCode!==200?(this.loggingService.catch(K?.message??"Error in ReactionAnnotationsResolverService resolveReactionAnnotations:"),{}):K?.data)).catch(K=>{throw s(),K});try{C=(yield G)||{},this.analyticsService.trackEvent(X.Events.Resolver.REACTION_RESOLVER_GET,{sourceMethod:"resolveReactionAnnotations",source:"sdk",reactionAnnotationIds:E});let K={};Object.entries(C).forEach(([pe,Ce])=>{let Ie=this.reactionAnnotationById$.value?.[pe];Ie?Ie&&JSON.stringify(Ie)!==JSON.stringify(Ce)&&(K[pe]=Ce):K[pe]=Ce}),Object.keys(K).length>0&&this.reactionAnnotationById$.next(I(I({},this.reactionAnnotationById$.getValue()),K)),c(K)}catch(K){r||p(K),c(C)}}else s(),c({})}catch(G){s(),p(G)}})})}catch(i){return this.loggingService.catch("Error in ReactionAnnotationsResolverService resolveReactionAnnotations:",i),{}}})}saveReactionAnnotation(e){return te(this,null,function*(){try{this.loggingService.log("%c[WB] Calling ReactionAnnotationsResolverService FUNCTION: saveReactionAnnotation","color: green;");let i=this.getProvider();if(!this.reactionAnnotationDataProviderAvailable())throw new Error("Reaction annotation save data provider not available");let r=JSON.parse(JSON.stringify(this.reactionAnnotationById$.getValue()));this.reactionAnnotationById$._value=I(I({},r),e);let a={reactionAnnotation:e,event:Wa.REACTION_ADD,metadata:Object.values(e??{})?.[0]?.metadata},s=yield uc(()=>i?.save(a)||Promise.resolve(void 0),"saveReactionAnnotation",this.retrySaveConfig);return s&&s.statusCode!==200?(this.retrySaveConfig.revertOnFailure&&(this.reactionAnnotationById$._value=r),this.loggingService.catch(s?.message??"Error in ReactionAnnotationsResolverService saveReactionAnnotation:"),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(X.Events.Resolver.REACTION_RESOLVER_SAVE,{sourceMethod:"saveReactionAnnotation",source:"sdk",reactionAnnotationIds:Object.keys(e),eventType:a.event}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0})}catch(i){return this.loggingService.warn("Error in ReactionAnnotationsResolverService saveReactionAnnotation:",i),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0}}})}deleteReactionAnnotation(e,i){return te(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 uc(()=>r?.delete({reactionAnnotationId:e.toString(),metadata:i,event:Wa.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(X.Events.Resolver.REACTION_RESOLVER_DELETE,{sourceMethod:"deleteReactionAnnotation",source:"sdk",reactionAnnotationId:e.toString()}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0})}catch(r){return this.loggingService.warn("Error in ReactionAnnotationsResolverService deleteReactionAnnotation:",r),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0}}})}getReactionAnnotationsById$(){try{return this.reactionAnnotationDataProviderAvailable()?(this.loggingService.log("%c[WB] Calling ReactionAnnotationsResolverService FUNCTION: getReactionAnnotationsById$","color: green;"),this.reactionAnnotationById$.asObservable()):re(void 0)}catch(e){return this.loggingService.catch("Error in ReactionAnnotationsResolverService getReactionAnnotationsById$:",e),re(void 0)}}getAnnotationById(e){try{return this.reactionAnnotationDataProviderAvailable()?this.reactionAnnotationById$.getValue()?.[e]:void 0}catch(i){this.loggingService.catch("Error in ReactionAnnotationsResolverService getAnnotationById:",i);return}}setReactionAnnotationDataProvider(e){try{if(e){this.loggingService.log("Setting reaction annotation data provider");let r=["get","save","delete"].filter(a=>!(a in e)||typeof e[a]!="function");if(r.length>0){let a=`DataProviders.reaction is invalid. The following methods are missing or are not functions: ${r.join(", ")}.`;this.loggingService.catch(a);return}else this.reactionAnnotationDataProvider$.next(e)}}catch(i){this.loggingService.catch("Error in ReactionAnnotationsResolverService setReactionAnnotationDataProvider:",i)}}reactionAnnotationDataProviderAvailable(){try{return!!this.reactionAnnotationDataProvider$.getValue()}catch(e){return this.loggingService.catch("Error in ReactionAnnotationsResolverService reactionAnnotationDataProviderAvailable:",e),!1}}};o.\u0275fac=function(i){return new(i||o)(Q(y),Q(Ke))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var lt=(()=>{let o=class o{constructor(e,i,r,a,s,c,p,u){this.analyticsService=e,this.authService=i,this.databaseService=r,this.domService=a,this.configService=s,this.loggingService=c,this.commentResolverService=p,this.reactionResolverService=u,this.documentPaths$=new ve(null),this.documentIds$=new ve([]),this.folderConfig$=new ve(null),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.draftDocumentId=null,this.clientDocumentMetadataMap={},this.uiState=new ve({}),this.lastSetDocumentIdExecutionTime=0,this.lastSetDocumentIdCallTime=0,this.setDocumentIdSubject=new Xe,this.DEBOUNCE_TIME=5e3,this.MAX_QUEUE_SIZE=100,this.queueSize=0,this.isDocumentIdInDebounceQueue=!1,this.draftLocationMap={location:null,locations:[]};try{this.loggingService.log("%c[WB] Creating CLASS: DocService","color: blue;"),this.domService.setDocService(this),this.authService.setDocService(this),this.setDocumentIdSubject.pipe(or(this.DEBOUNCE_TIME)).subscribe({next:C=>{try{this.setDocumentIdImpl(C.documentId,C.clientOrganizationId,C.auto,C.avoidAnalytics,C.options),this.lastSetDocumentIdExecutionTime=Date.now(),this.isDocumentIdInDebounceQueue=!1,this.draftLocationMap.location&&this.setLocation(this.draftLocationMap.location),this.draftLocationMap.locations.length>0&&this.draftLocationMap.locations.forEach(E=>{this.addLocation(E)}),this.draftLocationMap={location:null,locations:[]}}finally{this.queueSize--}},error:C=>{this.loggingService.catch("Error in setDocumentId subscription:",C),this.queueSize--}}),this.databaseService.getDb().pipe(Ne(C=>!!C),et(1)).subscribe(C=>{C&&(this.db=C)}),this.configService.getApiKey$().subscribe(C=>{if(this.apiKey=C,this.apiKey){if(!this.isCustomDocId){let E=u6(window.location.href);this.currentUrl=E}this.analyticsService.updateDefaultProperties({apiKey:C})}}),this.authService.getUser$().subscribe(C=>{C?(this.analyticsService.updateDefaultProperties({organizationId:C?.organizationId,clientOrganizationId:C?.clientOrganizationId}),this.draftDocumentId?(this.setDocumentId(this.draftDocumentId,this.draftOrganizationId,!1,!1,this.draftFolderConfig),this.draftDocumentId=null,this.draftLocationMap.location&&this.setLocation(this.draftLocationMap.location),this.draftLocationMap.locations.length>0&&this.draftLocationMap.locations.forEach(E=>{this.addLocation(E)}),this.draftLocationMap={location:null,locations:[]},this.draftOrganizationId=void 0,this.draftFolderConfig=void 0):this.documentPaths$?.value&&C?.organizationId&&this.documentPaths$.value?.organizationId!==C?.organizationId&&this.setDocumentId(this.documentPaths$.value?.clientDocumentId),this.updateDocumentLocationMetadata(),setTimeout(()=>{this.documentPaths$.value||this.loggingService.catch("Error in DocService constructor:","Please set document id to continue.")},1e4),C?.organizationId&&C?.clientOrganizationId&&this.organizationConfig$.next({organizationId:C?.organizationId,clientOrganizationId:C?.clientOrganizationId})):(this.organizationMetadataSubscription?.unsubscribe(),this.documentMetadataSubscription?.unsubscribe(),this.customerMetadataSubscription?.unsubscribe(),this.documentPaths$.value&&(this.draftDocumentId=this.documentPaths$.value?.clientDocumentId??null,this.draftFolderConfig=this.folderConfig$.value,this.draftLocationMap={location:this.location$.value?.location??null,locations:Object.values(this.locations$.value||{}).map(E=>E.location)},this.currentDocumentId=null,this.location$.next(null),this.documentPaths$.next(null),this.firestorePaths$.next(null)))}),this.documentPaths$.subscribe(C=>{let E={documentId:C?.documentId,clientDocumentId:C?.clientDocumentId};C?.organizationId&&(E.organizationId=C.organizationId,E.clientOrganizationId=C.clientOrganizationId),this.analyticsService.updateDefaultProperties(E),this.domService.resetSelectedAnnotationsMap()}),this.folderConfig$.subscribe(C=>{this.analyticsService.updateDefaultProperties({folderId:C?.folderId,veltFolderId:C?.veltFolderId,allDocuments:C?.allDocuments})}),this.location$.subscribe(C=>{this.analyticsService.updateDefaultProperties({clientLocation:C?.location,locationId:C?.locationId})}),this.organizationMetadata$.subscribe(C=>{this.authService.setUserOrganization(C?.[this.documentPaths$.value?.organizationId])}),this.organizationConfig$.subscribe(C=>{C&&this.updateOrganizationMetadata()}),this.documentPaths$.pipe(Ne(C=>!!C),et(1)).subscribe(()=>{try{this.subscribeToCustomerMetadata()}catch(C){this.loggingService.catch("Error in DocService subscribeToCustomerMetadata:",C)}},C=>{this.loggingService.catch("Error in DocService subscribeToCustomerMetadata:",C)}),this.loggingService.log("%c[WB] Creating CLASS: DocService 2","color: blue;"),this.onWindowPopstate(),this.onWindowClick()}catch(C){this.loggingService.catch("Error in DocService constructor:",C)}}clearCache(){this.loggingService.log("%c[WB] Calling FUNCTION: clearCache in DocService","color: green;");try{this.folderConfig$.next(null),this.organizationConfig$.next(null),this.organizationMetadata$.next(null),this.documentMetadata$.next(null),this.locationMetadata$.next(null),this.customerMetadata$.next(null)}catch(e){this.loggingService.catch("Error in DocService clearCache: ",e)}}setCommonDbService(e){try{this.commonDbService=e}catch(i){this.loggingService.catch("Error in setCommonDbService:",i)}}setCommentService(e){try{this.commentService=e}catch(i){this.loggingService.catch("Error in setCommentService:",i)}}onWindowPopstate(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowPopstate","color: green;");try{this.domService.onWindowPopState$().subscribe(()=>{this.loggingService.log("location",location.href);let e=u6(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=u6(location.href);this.currentUrl!==e&&(this.currentUrl=e,this.isCustomDocId||this.loggingService.log("current url in doc service",this.currentUrl))},e=>{this.loggingService.catch("Error in DocService onWindowClick subscription: ",e)})}catch(e){this.loggingService.catch("Error in onWindowClick: ",e)}}setDocument(e,i){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocument","color: green;"),this.documentIds$.value?.length&&this.documentIds$.next([]);let r=i?.organizationId;this.setDocumentId(e,r,!1,!0),i&&(i.organizationId&&delete i.organizationId,this.clientDocumentMetadata={clientDocumentId:e,documentMetadata:i},this.updateDocumentMetadata()),this.analyticsService.trackEvent(X.Events.Doc.DOCUMENT_SET,{documentId:e,documentMetadata:i},!0,this.getUserIdForAnalytics())}catch(r){this.loggingService.catch("Error in DocService setDocument:",r)}}shouldSetDocumentsAgain(e,i={}){try{this.loggingService.log("%c[WB] Calling FUNCTION: shouldSetDocumentsAgain","color: green;");let r=this.documentIds$.value.map(c=>c.clientDocumentId),a=this.folderConfig$.value??{};return!e.every(c=>r.includes(c.id))||!_o(a,i)}catch(r){return this.loggingService.catch("Error in DocService shouldSetDocumentsAgain:",r),!0}}setDocuments(e,i){try{if(!this.shouldSetDocumentsAgain(e,i)){this.loggingService.warn("setDocuments called with previous request");return}let r=[];if(e.forEach(a=>{let s=a.id,c=`${Cn(s)}`;a?.metadata&&typeof a.metadata=="object"&&(this.clientDocumentMetadataMap[s]=a.metadata),r.push({documentId:c,clientDocumentId:s})}),r?.length===0){this.loggingService.warn("Minimum one document must be set in setDocuments");return}this.documentIds$.next(r),e?.length&&this.setDocumentId(e[0]?.id,i?.organizationId,!1,!1,i),this.analyticsService.trackEvent(X.Events.Doc.DOCUMENTS_SET,{documentIds:r,options:i},!0,this.getUserIdForAnalytics())}catch(r){this.loggingService.catch("Error in DocService setDocuments:",r)}}setDocumentId(e,i,r=!1,a=!1,s){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocumentId","color: green;"),this.folderConfig$.value&&this.folderConfig$.next(null);let c=Date.now(),p=c-this.lastSetDocumentIdCallTime,u=c-this.lastSetDocumentIdExecutionTime;if(this.lastSetDocumentIdCallTime=c,this.queueSize>=this.MAX_QUEUE_SIZE){this.loggingService.warn("SetDocumentId queue size exceeded limit");return}if(!this.documentPaths$.value&&!this.isDocumentIdInDebounceQueue||p>this.DEBOUNCE_TIME&&u>this.DEBOUNCE_TIME){this.setDocumentIdImpl(e,i,r,a,s),this.lastSetDocumentIdExecutionTime=c;return}this.documentPaths$.next(null),this.isDocumentIdInDebounceQueue=!0,this.draftLocationMap={location:null,locations:[]},this.queueSize++,this.setDocumentIdSubject.next({documentId:e,clientOrganizationId:i,auto:r,avoidAnalytics:a})}catch(c){this.loggingService.catch("Error in setDocumentId:",c)}}setDocumentIdImpl(e,i,r=!1,a=!1,s){this.loggingService.log("%c[WB] Calling FUNCTION: setDocumentIdImpl","color: green;");try{r||(this.isCustomDocId=!0);let c=this.authService.getUser();if(!c){this.draftDocumentId=e,this.draftOrganizationId=i,this.draftFolderConfig=s;return}(s?.folderId||s?.locationId)&&this.folderConfig$.next({folderId:s?.folderId,allDocuments:s?.allDocuments,locationId:s?.locationId,veltFolderId:s?.folderId?_l(s?.folderId):void 0}),this.currentDocumentId&&this.documentPaths$.value&&this.callPreDocumentIdChangeFunctions(this.documentPaths$.value);let p=this.currentDocumentId;if(this.apiKey){let u=`${Cn(e)}`,C=c?.organizationId?i?Nt(i):c?.organizationId:void 0;if(this.commentResolverService.resolveCommentAnnotations({documentIds:this.documentIds$.value.map(E=>E.clientDocumentId),organizationId:i??c?.clientOrganizationId??""}),this.reactionResolverService.resolveReactionAnnotations({documentIds:this.documentIds$.value.map(E=>E.clientDocumentId),organizationId:i??c?.clientOrganizationId??""}),C&&this.documentPaths$.value?.organizationId&&C!==this.documentPaths$.value?.organizationId){let E=this.getFolderConfig();this.authService.resetServicesCache(),E&&this.folderConfig$.next(E)}if(this.currentDocumentId!==u||this.documentPaths$.value?.organizationId!==C){this.loggingService.log("setting new docid"),this.currentDocumentId=u;let E=new DM,A=new zM;E.clientDocumentId=e,A.clientDocumentId=e,E.documentId=u,A.documentId=u,C&&(E.organizationId=C,E.clientOrganizationId=i??c?.clientOrganizationId,A.organizationId=C,A.clientOrganizationId=i??c?.clientOrganizationId);let B=`${this.apiKey}`,G=`apiKey/${this.apiKey}`;C&&(B=`${B}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${E.organizationId}`,G=`${G}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${E.organizationId}`),A.organization=`apiKey/${this.apiKey}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}`,A.document=`${G}/${U.FIREBASE_PARTIAL_PATH_DOCS}`,E.presence=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${u}/${U.FIREBASE_PARTIAL_PATH_PRESENCE}/`,E.cursor=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${u}/${U.FIREBASE_PARTIAL_PATH_CURSOR}/`,E.comment=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${u}/${U.FIREBASE_PARTIAL_PATH_COMMENT}/`,A.comment=`${G}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${u}/${U.FIREBASE_PARTIAL_PATH_COMMENT}`,E.multiThread=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${u}/${U.FIREBASE_PARTIAL_PATH_MULTI_THREAD}/`,A.multiThread=`${G}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${u}/${U.FIREBASE_PARTIAL_PATH_MULTI_THREAD}`,E.tag=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${u}/${U.FIREBASE_PARTIAL_PATH_TAG}/`,E.area=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${u}/${U.FIREBASE_PARTIAL_PATH_AREA}/`,A.area=`${G}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${u}/${U.FIREBASE_PARTIAL_PATH_AREA}`,E.arrow=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${u}/${U.FIREBASE_PARTIAL_PATH_ARROW}/`,E.selection=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${u}/${U.FIREBASE_PARTIAL_PATH_SELECTION}/`,E.audioHuddle=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${u}/${U.FIREBASE_PARTIAL_PATH_AUDIO_HUDDLE}/`,E.huddle=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${u}/${U.FIREBASE_PARTIAL_PATH_HUDDLE}/`,E.recorder=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${u}/${U.FIREBASE_PARTIAL_PATH_RECORDER}/`,A.recorder=`${G}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${u}/${U.FIREBASE_PARTIAL_PATH_RECORDER}`,E.flock=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${u}/${U.FIREBASE_PARTIAL_PATH_FOLLOW_ALONG}/`,E.syncVideoPlayer=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${u}/${U.FIREBASE_PARTIAL_PATH_SYNC_VIDEO_PLAYER}/`,E.liveState=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${u}/${U.FIREBASE_PARTIAL_PATH_LIVE_STATE}/`,E.liveStateSingleEditorMode=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${u}/${U.FIREBASE_PARTIAL_PATH_LIVE_STATE}/default/singleEditorMode`,E.reaction=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${u}/${U.FIREBASE_PARTIAL_PATH_REACTION}/`,A.reaction=`${G}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${u}/${U.FIREBASE_PARTIAL_PATH_REACTION}`,E.customerMetadata=`${this.apiKey}/${U.FIREBASE_PARTIAL_PATH_CUSTOMER_METADATA}/`,E.views=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${u}/${U.FIREBASE_PARTIAL_PATH_VIEWS}/`,A.commentViews=`${G}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${u}/${U.FIREBASE_PARTIAL_PATH_COMMENT_VIEWS}`,A.notificationViews=`${G}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${u}/${U.FIREBASE_PARTIAL_PATH_NOTIFICATION_VIEWS}`,A.documentViews=`${G}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${u}/${U.FIREBASE_PARTIAL_PATH_DOCUMENT_VIEWS}`,A.locationViews=`${G}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${u}/${U.FIREBASE_PARTIAL_PATH_LOCATION_VIEWS}`,E.notifications=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${u}/${U.FIREBASE_PARTIAL_PATH_NOTIFICATIONS}/`,E.metadata=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${u}/${U.FIREBASE_PARTIAL_PATH_METADATA}/`,E.users=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${u}/${U.FIREBASE_PARTIAL_PATH_USERS}/`,E.documentIam=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${u}/${U.FIREBASE_PARTIAL_PATH_IAM}/`,E.workspaceIam=`${this.apiKey}/${U.FIREBASE_PARTIAL_PATH_IAM}/`,E.groupContacts=`${B}/${U.FIREBASE_PARTIAL_PATH_CONTACTS}/${U.FIREBASE_PARTIAL_PATH_GROUPS}/`,E.globalContacts=`${B}/${U.FIREBASE_PARTIAL_PATH_CONTACTS}/${U.FIREBASE_PARTIAL_PATH_GLOBAL}/`,E.logins=`${B}/${U.FIREBASE_PARTIAL_PATH_CONTACTS}/${U.FIREBASE_PARTIAL_PATH_LOGINS}/`,E.userFeedback=`${B}/${U.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${U.FIREBASE_PARTIAL_PATH_FEEDBACK}/`,E.userReportBugs=`${B}/${U.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${U.FIREBASE_PARTIAL_PATH_BUGS}/`,E.userContactUs=`${B}/${U.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${U.FIREBASE_PARTIAL_PATH_CONTACT_US}/`,C&&(E.organizationMetadata=`${B}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_METADATA}/`,E.organizationIam=`${B}/${U.FIREBASE_PARTIAL_PATH_IAM}/`,E.organizationGroups=`${B}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_GROUPS}/`,E.organizationNotifications=`${B}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/`,u&&(E.organizationNotificationsWithDocumentId=`${B}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${u}/`),E.organizationNotificationsLastNotificationTimestamp=`${B}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${U.FIREBASE_PARTIAL_PATH_LAST_NOTIFICATION_TIMESTAMP}/${U.FIREBASE_PARTIAL_PATH_DOCS}/`,E.organizationNotificationsUsers=`${B}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${U.FIREBASE_PARTIAL_PATH_USERS}/`),A.organizationUsers=`${G}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_USERS}`,A.documentUsers=`${G}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${u}/${U.FIREBASE_PARTIAL_PATH_DOCUMENT_USERS}`,A.notificationDocs=`${G}/${U.FIREBASE_PARTIAL_PATH_NOTIFICATION_DOCS}`,A.notificationUsers=`${G}/${U.FIREBASE_PARTIAL_PATH_NOTIFICATION_USERS}`,this.documentPaths$.next(E),this.firestorePaths$.next(A),E?.clientOrganizationId&&E?.organizationId&&!(E?.clientOrganizationId===this.organizationConfig$?.value?.clientOrganizationId&&E?.organizationId===this.organizationConfig$?.value?.organizationId)&&this.organizationConfig$.next({organizationId:E?.organizationId,clientOrganizationId:E?.clientOrganizationId}),this.updateFolderMetadata(),this.updateDocumentMetadata(),this.getLocationMetadata(),p&&this.location$.value&&this.removeLocation(),a||this.analyticsService.trackEvent(X.Events.Doc.DOCUMENT_ID_SET,{documentId:u,clientDocumentId:e},!0,this.getUserIdForAnalytics())}return u}else this.loggingService.catch("Error in setDocumentIdImpl: API key is not provided.")}catch(c){this.loggingService.catch("Error in setDocumentIdImpl: ",c)}}unsetDocumentId(e="internal"){this.loggingService.log("%c[WB] Calling FUNCTION: unsetDocumentId","color: green;");try{this.analyticsService.trackEvent(X.Events.Doc.DOCUMENT_UNSET,{documentId:this.currentDocumentId,documentMetadata:this.documentMetadata$.value?.[this.currentDocumentId??""],message:e==="external"?"User unset document id":"System unset document id",source:e},!0,this.getUserIdForAnalytics()),this.currentDocumentId&&this.documentPaths$.value&&this.callPreDocumentIdChangeFunctions(this.documentPaths$.value),this.currentDocumentId=null,this.documentPaths$.next(null),this.firestorePaths$.next(null),this.location$.next(null),this.excludedLocationIds$.next([]),this.documentMetadata$.next(null),this.locationMetadata$.next(null),this.customerMetadata$.next(null),this.locations$.next({})}catch(i){this.loggingService.catch("Error in unsetDocumentId: ",i)}}unsetDocuments(e="internal"){this.loggingService.log("%c[WB] Calling FUNCTION: unsetDocuments","color: green;");try{this.unsetDocumentId(e),this.documentIds$.next([])}catch(i){this.loggingService.catch("Error in unsetDocuments: ",i)}}addPreDocumentIdChangeFunction(e,i){try{this.loggingService.log("%c[WB] Calling FUNCTION: addPreDocumentIdChangeFunction","color: green;"),this.preDocumentIdChangeFunctions.set(e,i)}catch(r){this.loggingService.catch("Error in addPreDocumentIdChangeFunction: ",r)}}callPreDocumentIdChangeFunctions(e){return te(this,null,function*(){try{this.loggingService.log("%c[WB] Calling FUNCTION: callPreDocumentIdChangeFunctions","color: green;");for(let[i,r]of this.preDocumentIdChangeFunctions)try{yield r(e)}catch(a){this.loggingService.catch("Error in callPreDocumentIdChangeFunctions: ",a)}}catch(i){this.loggingService.catch("Error in callPreDocumentIdChangeFunctions: ",i)}})}subscribeToOrganizationMetadata(){this.loggingService.log("%c[WB] Calling FUNCTION: subscribeToOrganizationMetadata","color: green;");try{if(this.organizationMetadataSubscription&&this.organizationMetadataSubscription.unsubscribe(),this.db&&this.authService.getUser()?.organizationId){let e=this.organizationConfig$.value?.organizationId;this.commonDbService?.getData({feature:"organizationMetadata",properties:{apiKey:this.apiKey??"",organizationId:e,field:"metadata"}}).then(i=>{i&&this.organizationMetadata$.next(T(I({},this.organizationMetadata$.value),{[e]:i}))}).catch(i=>{this.loggingService.catch("Error in subscribeToOrganizationMetadata: ",i)})}}catch(e){this.loggingService.catch("Error in subscribeToOrganizationMetadata: ",e)}}subscribeToDocumentMetadata(e){try{if(this.documentMetadataSubscription&&this.documentMetadataSubscription.unsubscribe(),this.db&&this.authService.getUser()){let i=this.documentPaths$.value,r=this.documentMetadata$.value;if(e=e.filter(a=>!r?.[a.documentId]),e?.some(a=>!a?.documentId||!a?.clientDocumentId)||!i)return;if(this.commonDbService?.shouldUseFirestore()){let a=this.getFolderConfig()?.folderId,s=this.getFolderConfig()?.allDocuments,c=[],p={organizationId:i?.clientOrganizationId,folderId:a,allDocuments:s};if(a&&s)c.push(this.fetchDocuments(p));else{let C=[];for(let A=0;A<e.length;A+=20)C.push(e.slice(A,A+20));C.forEach(A=>{let B=JSON.parse(JSON.stringify(p));B.documentIds=A.map(G=>G.clientDocumentId),c.push(this.fetchDocuments(B))})}let u={};c.length>0&&Promise.all(c).then(C=>{C?.forEach(E=>{E?.forEach(A=>{A?.metadata?.documentId&&(u[A.metadata.documentId]=A.metadata)})}),this.documentMetadata$.next(I(I({},this.documentMetadata$.value),u))}).catch(C=>{this.loggingService.catch("Error in subscribeToDocumentMetadata: ",C)})}else r?.[i?.documentId??e?.[0]?.documentId]||this.commonDbService?.queryData({feature:"allDocuments",properties:{apiKey:this.apiKey??"",organizationId:i?.organizationId,documentId:i?.documentId??e?.[0]?.documentId,skipObjectValues:!0}}).then(a=>{a?.documentId&&this.documentMetadata$.next({[a.documentId]:a})}).catch(a=>{this.loggingService.catch("Error in subscribeToDocumentMetadata: ",a)})}}catch(i){this.loggingService.catch("Error in subscribeToDocumentMetadata: ",i)}}getLocationMetadata(){try{if(this.db&&this.authService.getUser()){let e=this.documentPaths$.value,i=this.documentIds$.value,r=this.getFolderConfig()?.folderId,a=this.getFolderConfig()?.allDocuments,s=[],c={organizationId:e?.clientOrganizationId,folderId:r,allDocuments:a};if(r&&a)s.push(this.fetchLocations(c));else{let u=[];for(let E=0;E<i.length;E+=20)u.push(i.slice(E,E+20));u.forEach(E=>{let A=JSON.parse(JSON.stringify(c));A.documentIds=E.map(B=>B.clientDocumentId),s.push(this.fetchLocations(A))})}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 getLocationMetadata: ",u)})}}catch(e){this.loggingService.catch("Error in getLocationMetadata: ",e)}}getLocationMetadatas(){return this.locationMetadata$.value}subscribeToCustomerMetadata(){this.loggingService.log("%c[WB] Calling FUNCTION: subscribeToCustomerMetadata","color: green;");try{if(this.customerMetadataSubscription)return;this.db&&this.authService.getUser()&&this.documentPaths$.value&&(this.customerMetadataSubscription=this.commonDbService?.dbListener({feature:"customerMetadata",properties:{skipFirestore:!0}}).pipe(Vn(i=>re(null))).subscribe(i=>{this.customerMetadata$.next(i?.data)}))}catch(e){this.loggingService.catch("Error in subscribeToCustomerMetadata: ",e)}}getDocumentId(){return this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentId","color: green;"),this.documentPaths$.value?.documentId}getClientDocumentId(){return this.loggingService.log("%c[WB] Calling FUNCTION: getClientDocumentId","color: green;"),this.documentPaths$.value?.clientDocumentId}getDocumentIds$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentIds$","color: green;"),this.documentIds$.asObservable().pipe(ce(e=>e?.slice()))}getFolderConfig$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getFolderConfig$","color: green;"),this.folderConfig$.asObservable()}getDocumentIds(){return this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentIds","color: green;"),this.documentIds$.value?.slice()}getFolderConfig(){return this.loggingService.log("%c[WB] Calling FUNCTION: getFolderConfig","color: green;"),this.folderConfig$.value}getLocationMetadata$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getLocationMetadata$","color: green;"),this.locationMetadata$.asObservable().pipe()}getDocumentPaths$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentPaths$","color: green;"),this.documentPaths$.asObservable()}getFirestorePaths$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getFirestorePaths$","color: green;"),this.firestorePaths$.asObservable()}getDocumentPaths(){return this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentPaths","color: green;"),this.documentPaths$.value}generateDocumentId(e){try{return`${Cn(e)}`}catch(i){return this.loggingService.catch("Error in generateDocumentId: ",i),""}}generateOrganizationId(e){try{return`${Nt(e)}`}catch(i){return this.loggingService.catch("Error in generateOrganizationId: ",i),""}}getFirestorePaths(){return this.loggingService.log("%c[WB] Calling FUNCTION: getFirestorePaths","color: green;"),this.firestorePaths$.value}setLocation(e){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: setLocationImpl","color: green;"),e&&typeof e=="object"){if(e?.version&&(!e?.version?.id||!e?.version?.name)){this.loggingService.catch("Error in setLocationImpl: ","If you're setting version then add id and name fields to version object.");return}let i=Qo(e),r=Cn(JSON.stringify(i));this.location$.next({locationId:r,location:i}),this.isDocumentIdInDebounceQueue&&(this.draftLocationMap.location=e),this.updateDocumentLocationMetadata().then(()=>{this.analyticsService.trackEvent(X.Events.Doc.LOCATION_SET,{location:i,locationId:r},!0,this.getUserIdForAnalytics())})}}catch(i){this.loggingService.catch("Error in setLocationImpl: ",i)}}removeLocation(e,i="internal"){try{if(this.analyticsService.trackEvent(X.Events.Doc.LOCATION_UNSET,{location:this.location$.value?.location,locationId:this.location$.value?.locationId,message:i==="external"?"User removed location":"System removed location",source:i},!0,this.getUserIdForAnalytics()),e){let r=this.genarateLocationId(e);this.getLocation()?.locationId===r&&(this.location$.next(null),i!=="internal"&&(this.draftLocationMap.location=null)),this.removeCustomLocation(e)}else this.location$.next(null),this.locations$.next({}),i!=="internal"&&(this.draftLocationMap.location=null,this.draftLocationMap.locations=[])}catch(r){this.loggingService.catch("Error in removeLocation: ",r)}}getLocation$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getLocation$","color: green;"),this.location$.asObservable()}getLocation(){return this.loggingService.log("%c[WB] Calling FUNCTION: getLocation$","color: green;"),this.location$.value?JSON.parse(JSON.stringify(this.location$.value)):null}excludeLocationIds(e){try{this.excludedLocationIds$.next([...e])}catch(i){this.loggingService.catch("Error in excludeLocationIds: ",i)}}getExcludedLocationIds$(){try{return this.excludedLocationIds$.asObservable()}catch(e){return this.loggingService.catch("Error in getExcludedLocationIds$: ",e),re([])}}updateOrganizationMetadata(){try{if(this.db&&this.authService.getUser()?.organizationId){let e=this.documentPaths$.value,i=this.organizationConfig$.value?.organizationId;if(!this.organizationMetadata$.value?.[i]){let a=new VM;a.apiKey=this.configService?.getApiKey()??"",a.organizationId=i,a.clientOrganizationId=this.organizationConfig$.value?.clientOrganizationId,this.commonDbService?.updateData({feature:"organizationMetadata",data:JSON.parse(JSON.stringify(a)),properties:{organizationId:i,documentId:e?.documentId??""}}),this.subscribeToOrganizationMetadata()}}}catch(e){this.loggingService.catch("Error in updateOrganizationMetadata: ",e)}}updateFolderMetadata(){return te(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: updateFolderMetadata","color: green;"),this.db&&this.authService.getUser()&&this.folderConfig$.value){let e=this.documentPaths$.value,i=this.folderConfig$.value;if(!(yield this.commonDbService?.getData({feature:"folderMetadata",properties:{organizationId:e?.organizationId??"",folderId:i?.veltFolderId??""}}))?.metadata){let a={folderId:i?.folderId,veltFolderId:i?.veltFolderId,apiKey:this.configService?.getApiKey()??"",organizationId:e?.organizationId,clientOrganizationId:e?.clientOrganizationId,createdAt:Date.now(),lastUpdated:Date.now(),parentFolderId:"root",veltParentFolderId:"root"};this.commonDbService?.updateData({feature:"folderMetadata",data:JSON.parse(JSON.stringify({metadata:a})),properties:{organizationId:e?.organizationId??"",folderId:i?.veltFolderId??""}})}}}catch(e){this.loggingService.catch("Error in updateFolderMetadata: ",e)}})}updateDocumentMetadata(){return te(this,null,function*(){try{if(this.db&&this.authService.getUser()){let e=this.documentPaths$.value;if(e){let i=this.getDocumentIds();i.find(a=>a.documentId===e.documentId)||i.push({documentId:e.documentId??"",clientDocumentId:e.clientDocumentId??""});let r=i.map(a=>te(this,null,function*(){let s=new TM;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=Ii();let c=this.getFolderConfig();s?.pageInfo?.deviceInfo&&delete s?.pageInfo?.deviceInfo;let p=!0,u=this.documentMetadata$.value?.[a.documentId];if(c){let C=yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:a?.documentId??"",organizationId:e?.organizationId??"",field:"metadata"}});C?.clientDocumentId?C?.folderId&&(C?.folderId!==c?.folderId||C?.veltFolderId!==c?.veltFolderId)?(this.loggingService.catch(`Folder id mismatch for document ${a?.clientDocumentId??""}`),p=!1):C?.folderId===c?.folderId?(c?.folderId&&(s.folderId=c.folderId),c?.veltFolderId&&(s.veltFolderId=c.veltFolderId)):(this.loggingService.catch(`Document ${a?.clientDocumentId??""} is not in the folder ${c?.folderId??""}`),p=!1):(c?.folderId&&(s.folderId=c.folderId),c?.veltFolderId&&(s.veltFolderId=c.veltFolderId))}if(u){let C={};Object.entries(s).forEach(([E,A])=>{C[E]=A}),_o(C,u)&&(p=!1)}p&&(yield this.commonDbService?.updateData({feature:"documentMetadata",data:JSON.parse(JSON.stringify(s)),properties:{organizationId:e?.organizationId??"",documentId:a?.documentId??""}}))}));yield Promise.all(r),this.subscribeToDocumentMetadata(i)}}}catch(e){this.loggingService.catch("Error in updateDocumentMetadata: ",e)}})}updateDocumentLocationMetadata(){return te(this,null,function*(){try{if(this.db&&this.authService.getUser()){let e=this.documentPaths$.value,i=this.location$.value;if(e&&i){let r=this.getDocumentIds();r.find(a=>a.documentId===e.documentId)||r.push({documentId:e.documentId??"",clientDocumentId:e.clientDocumentId??""});for(let a of r){let s=yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:a?.documentId??"",organizationId:e?.organizationId??"",field:"metadata"}}),c=new MM;c.locationId=i?.locationId,c.veltLocationId=BV(i?.location?.id??""),c.location=i?.location,c.pageInfo=Ii(),c?.pageInfo?.deviceInfo&&delete c?.pageInfo?.deviceInfo;let p=T(I({},s),{[U.FIREBASE_PARTIAL_PATH_LOCATIONS]:T(I({},s[U.FIREBASE_PARTIAL_PATH_LOCATIONS]??{}),{[i?.locationId]:c})}),u=T(I({},c),{metadata:I({},this.getBaseMetadata()??{})});this.commonDbService?.updateData({feature:"documentMetadata",data:JSON.parse(JSON.stringify(p)),properties:{documentId:a?.documentId??"",organizationId:e?.organizationId??""}}),this.commonDbService?.updateData({feature:"locationMetadata",data:JSON.parse(JSON.stringify(u)),properties:{documentId:a?.documentId??"",organizationId:e?.organizationId??"",id:c.veltLocationId}});let C=this.locationMetadata$.value;if(C||(C={}),i?.location?.id){let E=C?.[a.documentId],A=E?.[i?.location?.id??""];C&&(E||(C[a.documentId]={}),A||(C[a.documentId][i?.location?.id??""]={}),C[a.documentId][i?.location?.id??""]=T(I({},A),{location:i?.location})),Object.keys(C||{}).length>0&&this.locationMetadata$.next(C)}}}}}catch(e){this.loggingService.catch("Error in updateDocumentLocationMetadata: ",e)}})}genarateLocationId(e){try{return e&&typeof e=="object"?Cn(JSON.stringify(Qo(e))):0}catch(i){return this.loggingService.catch("Error in genarateLocationId: ",i),0}}addLocation(e){try{let i=null;if(e&&typeof e=="object"){if(e?.version&&(!e?.version?.id||!e?.version?.name)){this.loggingService.catch("Error in setLocation: ","If you're setting version then add id and name fields to version object.");return}let r=I({},e),a=this.locations$.value;e?.id&&Object.keys(a).forEach(p=>{let u=a[p];u.location?.id===e.id&&(r=I(I({},u.location),e),delete a[p])});let s=this.genarateLocationId(r),c={locationId:s,location:r};i=c,this.locations$.next(T(I({},a),{[s]:c})),this.isDocumentIdInDebounceQueue&&this.draftLocationMap.locations.push(r),this.analyticsService.trackEvent(X.Events.Doc.LOCATION_ADDED,{addedLocation:e,addedLocationId:s},!0,this.getUserIdForAnalytics())}return i}catch(i){return this.loggingService.catch("Error in DocService addLocation:",i),null}}removeCustomLocation(e,i="internal"){try{let r=this.genarateLocationId(e),a=this.locations$.value;a[r]&&(delete a[r],this.locations$.next(I({},a)),i!=="internal"&&this.isDocumentIdInDebounceQueue&&(this.draftLocationMap.locations=this.draftLocationMap.locations.filter(s=>s.id!==e.id)))}catch(r){this.loggingService.catch("Error in DocService removeLocation:",r)}}getLocationByClientLocationId(e){try{let i=this.getLocation()?.location;if(i?.id===e)return i;{let r=this.getLocations();Object.keys(r).forEach(a=>{let s=r[a];s.location?.id===e&&(i=s.location)})}return i}catch(i){this.loggingService.catch("Error in DocService getLocationByClientLocationId:",i);return}}removeLocationIfNotInDom(){try{let e=this.locations$.value,i=document.querySelectorAll(`[${U.ATTRIBUTES.VELT_LOCATION}]`),r=[];i.forEach(a=>{let s=a.getAttribute(U.ATTRIBUTES.VELT_LOCATION);if(s){let c=JSON.parse(s),p=this.genarateLocationId(c);r.push(p)}}),Object.keys(e).forEach(a=>{let s=e[a];r.includes(s.locationId)||delete e[a]}),this.locations$.next(I({},e))}catch(e){this.loggingService.catch("Error in DocService removeLocationIfNotInDom:",e)}}getLocations$(){try{return this.locations$.asObservable()}catch(e){return this.loggingService.catch("Error in DocService getLocations$:",e),re({})}}getLocations(){try{return this.locations$.value}catch(e){return this.loggingService.catch("Error in DocService getLocations:",e),{}}}getLocationFromElement(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: getLocationFromElement","color: green;");let i=null;if(e?.getAttribute(U.ATTRIBUTES.VELT_LOCATION)?i=e:i=e.closest(`[${U.ATTRIBUTES.VELT_LOCATION}]`),i){let r=i?.getAttribute(U.ATTRIBUTES.VELT_LOCATION);if(r){let a=JSON.parse(r);return{locationId:this.genarateLocationId(a),location:a}}}return null}catch(i){return this.loggingService.catch("Error in DocService getLocationFromElement:",i),null}}getElementMapWithLocation(){try{this.loggingService.log("%c[WB] Calling FUNCTION: getElementMapWithLocation","color: green;");let e={};return document.querySelectorAll(`[${U.ATTRIBUTES.VELT_LOCATION}], [${U.ATTRIBUTES.VELT_LOCATION_ID}]`).forEach(r=>{if(r.getAttribute(U.ATTRIBUTES.VELT_LOCATION)){let a=this.getLocationFromElement(r);a?.locationId&&(e[a.locationId]={element:r,location:a})}else if(r.getAttribute(U.ATTRIBUTES.VELT_LOCATION_ID)){let a=r.getAttribute(U.ATTRIBUTES.VELT_LOCATION_ID);if(a){let s=this.getLocationByClientLocationId(a);s?.locationId&&(e[s.locationId]={element:r,location:s});let c={id:a},p=this.genarateLocationId(c);e[a]={element:r,location:{locationId:p,location:c}}}}}),e}catch(e){return this.loggingService.catch("Error in DocService getElementMapWithLocation:",e),{}}}getAdditionLocationFromElement(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: getAdditionLocationFromElement","color: green;");let i;if(i=e?.closest(`[${U.ATTRIBUTES.VELT_LOCATION}], [${U.ATTRIBUTES.VELT_LOCATION_ID}]`),i){if(i?.getAttribute(U.ATTRIBUTES.VELT_LOCATION)){let r=i?.getAttribute(U.ATTRIBUTES.VELT_LOCATION);if(r)return JSON.parse(r)}else if(i?.getAttribute(U.ATTRIBUTES.VELT_LOCATION_ID)){let r=i?.getAttribute(U.ATTRIBUTES.VELT_LOCATION_ID);if(r)return{id:r}}}return null}catch(i){return this.loggingService.catch("Error in DocService getAdditionLocationFromElement:",i),null}}getAdditionalDocumentIdFromElement(e){try{return e?.closest(`[${U.ATTRIBUTES.VELT_DOCUMENT_ID}]`)?.getAttribute(U.ATTRIBUTES.VELT_DOCUMENT_ID)||null}catch(i){return this.loggingService.catch("Error in DocService getAdditionalDocumentIdFromElement:",i),null}}getDocumentMetadata(e){try{return e?this.documentMetadata$.value?.[e]||null:this.documentMetadata$.value?.[this.documentPaths$.value?.documentId??""]||null}catch(i){return this.loggingService.catch("Error in DocService getDocumentMetadata:",i),null}}getAllDocumentMetadata(){try{return Object.values(this.documentMetadata$.value||{})}catch(e){return this.loggingService.catch("Error in DocService getAllDocumentMetadata:",e),[]}}getDocumentMetadataOfAvailableDocuments(){try{this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentMetadataOfAvailableDocuments","color: green;");let e=this.documentMetadata$.value||{},i={},r=this.getFolderConfig();if(r?.veltFolderId&&r?.allDocuments)Object.values(e).forEach(a=>{a?.documentId&&a?.veltFolderId===r?.veltFolderId&&(i[a.documentId]=a)});else{let a=this.documentIds$.value;if(a?.length)a.forEach(s=>{let c=e?.[s.documentId];c&&(i[s.documentId]=c)});else if(this.documentPaths$.value?.documentId){let s=e?.[this.documentPaths$.value?.documentId];s&&(i[this.documentPaths$.value?.documentId]=s)}}return Object.values(i)}catch(e){return this.loggingService.catch("Error in DocService getDocumentMetadataOfAvailableDocuments:",e),[]}}getDocumentMetadata$(e){return this.documentMetadata$.asObservable().pipe(ce(i=>i?.[e??this.documentPaths$.value?.documentId??""]||null))}getOrganizationMetadata(e){return this.organizationMetadata$.value?.[e]||null}getOrganizationMetadata$(e){return this.organizationMetadata$.asObservable().pipe(ce(i=>i?.[e]||null))}getCustomerMetadata(){return this.customerMetadata$.value}getCustomerMetadata$(){return this.customerMetadata$.asObservable()}getOrganizationConfig$(){return this.organizationConfig$.asObservable()}getOrganizationConfig(){return this.organizationConfig$.value}getMetadataFromType(e,i){try{switch(e){case"area":return;case"comment":return i?.multiThreadAnnotationId?this.commentService?.getMultiThreadAnnotationById(i.multiThreadAnnotationId)?.metadata:void 0;case"reaction":case"recorder":return i?.commentAnnotationId?this.commentService?.getAnnotationById(i.commentAnnotationId)?.metadata:void 0;default:return}}catch(r){this.loggingService.catch("Error in DocService getMetadataFromType:",r);return}}getDefaultMetadata({clientDocumentId:e,documentId:i}){try{let r=this.documentPaths$.value;if(!r)return;let a=e||r.clientDocumentId,s=i||r.documentId,c=this.getDocumentMetadata(s);if(!c)return;let p=c?.folderId,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,i){try{let r,a;i?.element?r=this.getAdditionalDocumentIdFromElement(i.element)||void 0:i?.clientDocumentId&&(r=i.clientDocumentId),r&&(a=this.generateDocumentId(r));let s=this.getMetadataFromType(e,i),c=this.getDefaultMetadata({clientDocumentId:r,documentId:a});return s||c||{}}catch(r){return this.loggingService.catch("Error in DocService getBaseMetadata:",r),{}}}getServerId({documentId:e,organizationId:i}){try{return e&&(e=this.generateDocumentId(e)),i&&(i=this.generateOrganizationId(i)),{documentId:e,organizationId:i}}catch(r){return this.loggingService.catch("Error in DocService getServerId:",r),null}}fetchDocuments(e){return te(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=_l(e?.folderId);r.push(dt("metadata.veltFolderId","==",s))}return e?.documentIds?.length&&!e?.allDocuments&&r.push(dt("metadata.documentId","in",e?.documentIds?.map(s=>this.generateDocumentId(s)).slice(0,30))),yield this.commonDbService?.queryData({feature:"allDocuments",properties:{firestoreQuery:r,apiKey:this.apiKey??"",organizationId:this.generateOrganizationId(e?.organizationId)??this.documentPaths$.value?.organizationId,documentId:this.documentPaths$.value?.documentId}})}catch(i){return this.loggingService.catch("Error in DocService fetchDocuments:",i),[]}})}fetchLocations(e){return te(this,null,function*(){try{if(!this.authService.getUser())return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),[];let r=[];if(!e?.organizationId)return this.loggingService.catch("Error in fetchLocations: organizationId is required"),[];if(e?.folderId){let s=_l(e?.folderId);r.push(dt("metadata.veltFolderId","==",s))}return e?.documentIds?.length&&!e?.allDocuments&&r.push(dt("metadata.documentId","in",e?.documentIds?.map(s=>this.generateDocumentId(s)).slice(0,30))),yield this.commonDbService?.queryData({feature:"allLocations",properties:{firestoreQuery:r,apiKey:this.apiKey??"",organizationId:this.generateOrganizationId(e?.organizationId)??this.documentPaths$.value?.organizationId,documentId:this.documentPaths$.value?.documentId}})}catch(i){return this.loggingService.catch("Error in DocService fetchLocations:",i),[]}})}updateDocuments(e){return te(this,null,function*(){try{if(!this.authService.getUser())return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),[];let{organizationId:r,documents:a}=e;if(!r&&(r=this.documentPaths$.value?.clientOrganizationId,!r))return this.loggingService.catch("Error in updateDocuments: organizationId is required"),[];if(!a||a.length===0)return this.loggingService.catch("Error in updateDocuments: documents is required"),[];let s=[],c=this.documentMetadata$.value;a.forEach(p=>{delete p?.organizationId,delete p?.clientDocumentId,delete p?.clientOrganizationId,delete p?.apiKey;let u=dc(p.documentId),C=c?.[u];C&&(c[u]=I(I({},C),p)),p&&this.commonDbService&&s.push(this.commonDbService.updateData({feature:"documentMetadata",data:JSON.parse(JSON.stringify(p)),properties:{organizationId:pc(r),documentId:u}}))}),yield Promise.all(s),this.documentMetadata$.next(c)}catch(i){return this.loggingService.catch("Error in DocService updateDocuments:",i),[]}})}updateLocations(e){return te(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=>dc(C)),p=[],u=this.locationMetadata$.value;u||(u={}),c.forEach(C=>{a.forEach(E=>{let A=this.location$.value;if(E?.id===A?.location?.id&&this.location$.next({locationId:A?.locationId,location:E}),E?.id){delete E?.metadata;let B=BV(E.id),G=u?.[C],K=G?.[E.id];u&&(G||(u[C]={}),K||(u[C][E.id]={}),u[C][E.id]=T(I({},K),{location:E})),E&&this.commonDbService&&p.push(this.commonDbService.updateData({feature:"locationMetadata",data:JSON.parse(JSON.stringify({location:E})),properties:{organizationId:pc(r),documentId:C,id:B}}))}})}),yield Promise.all(p),Object.keys(u||{}).length>0&&this.locationMetadata$.next(u)}catch(i){return this.loggingService.catch("Error in DocService updateLocations:",i),[]}})}fetchFolders(e){return te(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=_l(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:[dt("metadata.veltParentFolderId","==",c)],folderId:c,apiKey:this.apiKey??"",organizationId:s,documentId:this.documentPaths$.value?.documentId}})}else r=yield this.commonDbService?.queryData({feature:"allFolders",properties:{apiKey:this.apiKey??"",organizationId:s,documentId:this.documentPaths$.value?.documentId}});return{data:r,parentFolders:a}}catch(i){return this.loggingService.catch("Error in DocService getFoldersRequest:",i),{data:[],parentFolders:[]}}})}getDocumentIam$(){return this.authService.getUser$().pipe(ue(e=>e?this.documentPaths$.pipe(ue(i=>i?.documentIam?this.commonDbService?.dbListener({feature:"documentIam",properties:{documentId:i.documentId,organizationId:i.organizationId,isCollection:!1}}).pipe(ce(r=>r?.data?.docIamConfig??r?.data),qt((r,a)=>JSON.stringify(r??{})===JSON.stringify(a??{}))):re(null))):re(null)))}getDocumentAccessType(e){try{return e&&e.features&&e.features.all?e.features.all.restricted?pi.RESTRICTED:pi.PUBLIC:e&&e.documentAccessType?e.documentAccessType:pi.PUBLIC}catch(i){return this.loggingService.catch("Error in DocService getDocumentAccessType:",i),pi.PUBLIC}}changeDocumentAccessType(e){return te(this,null,function*(){try{let i=this.documentPaths$.value;if(i){let r=yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:i?.documentId??"",organizationId:i?.organizationId??"",field:"docIamConfig"}});switch(delete r.documentAccessType,r.features||(r.features={}),r.features.all||(r.features.all={}),e){case pi.PUBLIC:r.features.all.restricted=!1;break;case pi.RESTRICTED:r.features.all.restricted=!0,r.features.all.guestMode=!1;break;default:break}this.commonDbService?.updateData({feature:"documentAccessType",data:JSON.parse(JSON.stringify(r)),properties:{documentId:i?.documentId??"",organizationId:i?.organizationId??""}})}}catch(i){this.loggingService.catch("Error in DocService changeDocumentAccessType:",i)}})}getUserIdForAnalytics(){try{return this.authService?.getAuthUser()?.uid||""}catch(e){return this.loggingService.catch("Error in DocService getUserIdForAnalytics:",e),""}}setUIState(e){try{this.uiState.next(I(I({},this.uiState.value),e))}catch(i){this.loggingService.catch("Error in DocService setUIState:",i)}}getUIState$(){return this.uiState.asObservable()}};o.\u0275fac=function(i){return new(i||o)(Q(Ke),Q(je),Q(un),Q(Fe),Q(jt),Q(y),Q(bs),Q(Em))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var zn=(()=>{let o=class o{constructor(e,i,r,a){this.analyticsService=e,this.authService=i,this.docService=r,this.loggingService=a,this.defaultUserDataProvider={get:s=>te(this,null,function*(){return{}})},this.resolveTimeout=1*60*1e3,this.maxResolveAttempts=1,this.resolveAttempts=new Map,this.subscriptions=new cn,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)}}ngOnDestroy(){try{this.subscriptions.unsubscribe(),this.pendingResolutions.clear(),this.resolveAttempts.clear()}catch(e){this.loggingService.catch("Error in UsersService ngOnDestroy:",e)}}resolveUsers(e,i=!1){return te(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling UsersService FUNCTION: resolveUsers","color: green;"),this.userDataProvider$.getValue()){let r={},a=[],s={};if(e?.forEach(c=>{let p=this.getUserById(c);p?r[c]=p:this.userByIdCalled$.getValue()[c]?i&&a.push(c):(a.push(c),this.userByIdCalled$.next(T(I({},this.userByIdCalled$.getValue()),{[c]:!0})))}),a.length>0){let c=this.userDataProvider$.getValue();if(c){let p={};try{let u,C=new Promise((E,A)=>{u=setTimeout(()=>{A(new Error("User resolution timeout"))},this.userDataProvider$.getValue()?.resolveTimeout||this.resolveTimeout)});p=yield Promise.race([c.get(a).finally(()=>{clearTimeout(u)}),C]),this.analyticsService.trackEvent(X.Events.Resolver.USER_RESOLVER_GET,{sourceMethod:"resolveUsers",source:"sdk",userIds:a})}catch(u){this.loggingService.catch("Error in UsersService resolveUsers getUsers:",u,{userIds:a})}finally{a?.forEach(u=>{p[u]||(p[u]={userId:u,name:`User ${u}`})})}Object.entries(p).forEach(([u,C])=>{C&&(r[u]=p?.[u],s[u]=p?.[u])})}}return Object.keys(s).length>0&&this.userById$.next(I(I({},this.userById$.getValue()),s)),r}else return{}}catch(r){return this.loggingService.catch("Error in UsersService resolveUsers:",r),{}}})}subscribeToDocuments(){return this.docService.getDocumentIds$().pipe(gn(e=>te(this,null,function*(){let i=yield this.getUsersFromCentralDb({documentIds:e?.map(r=>r.documentId)});this.resolveUsers(i)})))}getUsersFromCentralDb(i){return te(this,arguments,function*({documentIds:e}){try{return new Promise(r=>{r(["customuser1","customuser2","customuser3"])})}catch{return[]}})}getUserById$(){try{return this.loggingService.log("%c[WB] Calling UsersService FUNCTION: getUserById$","color: green;"),this.userById$.asObservable()}catch(e){return this.loggingService.catch("Error in UsersService getUserById$:",e),re({})}}setUserDataProvider(e){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setUserDataProvider","color: green;"),this.userDataProvider$.next(e)}catch(i){this.loggingService.catch("Error in UsersService setUserDataProvider:",i)}}userDataProviderAvailable(){try{return this.loggingService.log("%c[WB] Calling UsersService FUNCTION: userDataProviderAvailable","color: green;"),!!this.userDataProvider$.getValue()}catch(e){return this.loggingService.catch("Error in UsersService userDataProviderAvailable:",e),!1}}};o.\u0275fac=function(i){return new(i||o)(Q(Ke),Q(je),Q(lt),Q(y))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Mse=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.usersService=i}getUserIdsToResolveFromAreaAnnotations(e){try{this.loggingService.log("%c[WB] Calling AreaUtilsService FUNCTION: getUserIdsToResolveFromAreaAnnotations","color: green;");let i=new Set;for(let r of e)r?.from?.userId&&i.add(r?.from?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in AreaUtilsService getUserIdsToResolveFromAreaAnnotations:",i),[]}}mergeAreaWithUser(e){try{if(this.loggingService.log("%c[WB] Calling AreaUtilsService FUNCTION: mergeAreaWithUser","color: green;"),e?.from?.userId){let i=this.usersService.getUserById(e?.from?.userId);i&&(e.from=i)}return e}catch(i){return this.loggingService.catch("Error in AreaUtilsService mergeAreaWithUser:",i),e}}formatAreaData(e){try{return this.loggingService.log("%c[WB] Calling AreaUtilsService FUNCTION: formatAreaData","color: green;"),this.usersService.userDataProviderAvailable()&&e?.from?.userId&&(e.from={userId:e.from.userId}),e}catch(i){return this.loggingService.catch("Error in AreaUtilsService formatAreaData:",i),e}}};o.\u0275fac=function(i){return new(i||o)(Q(y),Q(zn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Pse=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.usersService=i}getUserIdsToResolveFromArrowAnnotations(e){try{this.loggingService.log("%c[WB] Calling ArrowUtilsService FUNCTION: getUserIdsToResolveFromArrowAnnotations","color: green;");let i=new Set;for(let r of e)r?.from?.userId&&i.add(r?.from?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in ArrowUtilsService getUserIdsToResolveFromArrowAnnotations:",i),[]}}mergeArrowWithUser(e){try{if(this.loggingService.log("%c[WB] Calling ArrowUtilsService FUNCTION: mergeArrowWithUser","color: green;"),e?.from?.userId){let i=this.usersService.getUserById(e?.from?.userId);i&&(e.from=i)}return e}catch(i){return this.loggingService.catch("Error in ArrowUtilsService mergeArrowWithUser:",i),e}}formatArrowData(e){try{return this.loggingService.log("%c[WB] Calling ArrowUtilsService FUNCTION: formatArrowData","color: green;"),this.usersService.userDataProviderAvailable()&&e?.from?.userId&&(e.from={userId:e.from.userId}),e}catch(i){return this.loggingService.catch("Error in ArrowUtilsService formatArrowData:",i),e}}};o.\u0275fac=function(i){return new(i||o)(Q(y),Q(zn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var zp=class{static getFirestoreProdDbName(o,t){return t?.storeDbId??(this.isTestingDb(t?.databaseURL??"")?"sdktest":`apikey${o.toLowerCase()}`)}static isTestingDb(o){try{return o.includes("-test")}catch(t){return mt.error("Error in isTestingDb:",t),!1}}};var Gp=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.analyticsService=i,this.retrySaveConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.retryDeleteConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.attachmentDataProvider$=new 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 te(this,null,function*(){try{this.loggingService.log("%c[WB] Calling AttachmentResolverService FUNCTION: saveAttachment","color: green;");let i=this.getProvider();if(!this.attachmentDataProviderAvailable())throw new Error("Attachment save data provider not available");let r=yield uc(()=>i?.save({attachment:e.attachment,event:e.eventType,metadata:e.attachment.metadata})||Promise.resolve(void 0),"saveAttachment",this.retrySaveConfig);if(r?.statusCode!==200){this.loggingService.catch(r?.message??"Error in AttachmentResolverService saveAttachment:");return}return this.analyticsService.trackEvent(X.Events.Resolver.ATTACHMENT_RESOLVER_SAVE,{sourceMethod:"saveAttachment",source:"sdk",attachmentId:e.attachment.attachmentId,eventType:e.eventType}),r}catch(i){this.loggingService.warn("Error in AttachmentResolverService saveAttachment:",i);return}})}deleteAttachment(r){return te(this,arguments,function*({attachmentId:e,metadata:i}){try{this.loggingService.log("%c[WB] Calling AttachmentResolverService FUNCTION: deleteAttachment","color: green;");let a=this.getProvider();if(!this.attachmentDataProviderAvailable())throw new Error("Attachment delete data provider not available");let s=yield uc(()=>a?.delete({attachmentId:e,metadata:i,event:Wa.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(X.Events.Resolver.ATTACHMENT_RESOLVER_DELETE,{sourceMethod:"deleteAttachment",source:"sdk",attachmentId:e}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0})}catch(a){return this.loggingService.warn("Error in AttachmentResolverService deleteAttachment:",a),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0}}})}setAttachmentDataProvider(e){try{if(e){this.loggingService.log("Setting attachment data provider");let r=["save","delete"].filter(a=>!(a in e)||typeof e[a]!="function");if(r.length>0){let a=`DataProviders.attachment is invalid. The following methods are missing or are not functions: ${r.join(", ")}.`;this.loggingService.catch(a);return}else this.attachmentDataProvider$.next(e)}}catch(i){this.loggingService.catch("Error in AttachmentResolverService setAttachmentDataProvider:",i)}}attachmentDataProviderAvailable(){try{return!!this.attachmentDataProvider$.getValue()}catch(e){return this.loggingService.catch("Error in AttachmentResolverService attachmentDataProviderAvailable:",e),!1}}};o.\u0275fac=function(i){return new(i||o)(Q(y),Q(Ke))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Yv=(()=>{let o=class o{constructor(e,i,r,a,s,c,p){this.loggingService=e,this.usersService=i,this.authService=r,this.functions=a,this.configService=s,this.commentAnnotationsResolverService=c,this.attachmentResolverService=p,this.notificationActionTypeMap={[Ut.NEWLY_ADDED]:Wa.COMMENT_ANNOTATION_ADD,[Ut.ADDED]:Wa.COMMENT_ADD,[Ut.UPDATED]:Wa.COMMENT_UPDATE,[Ut.DELETED]:Wa.COMMENT_DELETE}}setNotificationService(e){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: setNotificationService","color: green;"),this.notificationService=e}catch(i){this.loggingService.catch("Error in CommentUtilsService setNotificationService: ",i)}}getUserIdsToResolveFromComments(e){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: getUserIdsToResolveFromComments","color: green;");let i=new Set;for(let r of e){if(r?.from?.userId&&i.add(r?.from?.userId),r?.comments)for(let a of r?.comments){if(a?.from?.userId&&i.add(a?.from?.userId),a?.to)for(let s of a?.to)s?.userId&&i.add(s?.userId);if(a?.taggedUserContacts)for(let s of a?.taggedUserContacts)s?.userId&&i.add(s?.userId)}if(r?.assignedTo?.userId&&i.add(r?.assignedTo?.userId),r?.subscribedUsers)for(let a of Object.values(r?.subscribedUsers))a.user.userId&&i.add(a.user.userId);if(r?.unsubscribedUsers)for(let a of Object.values(r?.unsubscribedUsers))a.user.userId&&i.add(a.user.userId)}return Array.from(i)}catch(i){return this.loggingService.catch("Error in CommentUtilsService getUserIdsToResolveFromComments:",i),[]}}mergeCommentWithUser(e){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: mergeCommentWithUser","color: green;"),e?.from?.userId){let i=this.usersService.getUserById(e?.from?.userId);i&&(e.from=i)}if(e?.comments)for(let i of e?.comments){if(i?.from?.userId){let a=this.usersService.getUserById(i?.from?.userId);a&&(i.from=a)}i?.to&&(i.to=i?.to?.map(a=>{if(a?.userId){let s=this.usersService.getUserById(a?.userId);if(s)return I(I({},a),s)}return a})),i?.taggedUserContacts&&(i.taggedUserContacts=i?.taggedUserContacts?.map(a=>{if(a?.contact){let s=this.usersService.getUserById(a?.contact?.userId);s&&(a.contact=s,(s?.name||s?.email)&&(a.text=`@${s?.name||s?.email}`))}return a})),(i?.taggedUserContacts?.filter((a,s,c)=>c.findIndex(p=>p.text===a.text)===s)||[]).forEach(a=>{if(a?.text){let s=new RegExp(dm(`{{${a.userId}}}`),"g");i.commentText=i.commentText?.replaceAll(s,a.text),i.commentHtml=i.commentHtml?.replaceAll(s,a.text)}})}if(e?.assignedTo?.userId){let i=this.usersService.getUserById(e?.assignedTo?.userId);i&&(e.assignedTo=i)}if(e?.subscribedUsers)for(let i of Object.values(e?.subscribedUsers)){let r=this.usersService.getUserById(i.user.userId);r&&e?.subscribedUsers?.id?.user&&(e.subscribedUsers.id.user=r)}if(e?.unsubscribedUsers)for(let i of Object.values(e?.unsubscribedUsers)){let r=this.usersService.getUserById(i.user.userId);r&&e?.unsubscribedUsers?.id?.user&&(e.unsubscribedUsers.id.user=r)}return e}catch(i){return this.loggingService.catch("Error in CommentUtilsService mergeCommentWithUser:",i),e}}formatCommentData(e){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: formatCommentData","color: green;"),e?.comments?.forEach(i=>{i?.commentText&&i?.commentText?.length>0&&(i.isCommentTextAvailable=!0)}),this.usersService.userDataProviderAvailable()){if(e?.from?.userId&&(e.from={userId:e.from.userId}),e?.assignedTo?.userId&&(e.assignedTo={userId:e.assignedTo.userId}),e?.subscribedUsers)for(let i of Object.keys(e?.subscribedUsers))e.subscribedUsers[i].user={userId:e?.subscribedUsers[i].user.userId};if(e?.unsubscribedUsers)for(let i of Object.keys(e?.unsubscribedUsers))e.unsubscribedUsers[i].user={userId:e?.unsubscribedUsers[i].user.userId}}return e?.comments&&(e.comments=e?.comments?.map(i=>this.formatCommentThreadData(i))),e}catch(i){return this.loggingService.catch("Error in CommentUtilsService formatCommentData:",i),e}}mergeStrippedDataWithCommentAnnotations(e){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: mergeStrippedDataWithCommentAnnotations","color: green;"),!this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())return e;let i=this.commentAnnotationsResolverService.getAnnotationById(e?.annotationId),r=this.attachmentResolverService.attachmentDataProviderAvailable();return i&&e?.comments?.forEach(a=>{let s=i?.comments?.[a?.commentId];if(s){a.commentHtml=s?.commentHtml,a.commentText=s?.commentText;let c=s?.attachments;r&&c&&a.attachments?.forEach(p=>{let u=p?.attachmentId;c?.[u]&&(p.name=c?.[u]?.name,p.url=c?.[u]?.url)})}}),e}catch(i){return this.loggingService.catch("Error in CommentUtilsService mergeStrippedDataWithCommentAnnotations:",i),e}}mergeLocationWithCommentAnnotations(e,i){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: mergeLocationWithCommentAnnotations","color: green;");let r=e?.location?.id,a=e?.metadata?.documentId;if(!r||!a)return e;let s=i?.[a]?.[r];return s&&(e.location=s?.location),e}catch(r){return this.loggingService.catch("Error in CommentUtilsService mergeLocationWithCommentAnnotations:",r),e}}isCommentsDataChanged(e,i){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: isCommentsDataChanged","color: green;");let r=this.commentAnnotationsResolverService.getCommentAnnotationById(i);return r?!_o(e,r):!0}catch(r){return this.loggingService.catch("Error in CommentUtilsService isCommentsDataChanged:",r),!0}}stripCommentAnnotationData({data:e,actionType:i}){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: stripCommentAnnotationData","color: green;"),!this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable()||!i)return{originalData:e,strippedData:null};let r=this.attachmentResolverService.attachmentDataProviderAvailable(),a=this.notificationActionTypeMap?.[i];if(!a)return{originalData:e,strippedData:null};let s={},c=null;if(e&&e.annotationId){let p=e.annotationId;if(s[p]={annotationId:p,metadata:hv(e.metadata??{}),comments:{}},e.comments?.forEach(E=>{if(E.commentId){let A;r&&(A={},E.attachments?.forEach(B=>{A[B.attachmentId]={attachmentId:B.attachmentId,name:B.name,url:B.url}})),s[p].comments[E.commentId]=I(I(I({commentId:E.commentId},E?.commentHtml&&{commentHtml:E?.commentHtml}),E?.commentText&&{commentText:E?.commentText}),A&&{attachments:A})}}),!this.isCommentsDataChanged(s[p],p))return{strippedData:null,originalData:e};let C=new ko;Object.assign(C,e),C.comments=e.comments?.map(E=>{let A=new _c;if(Object.assign(A,E),A.isCommentResolverUsed=!0,r){let B=A.attachments?.map(G=>(G.isAttachmentResolverUsed=!0,delete G?.name,delete G?.url,G));A.attachments=B}return delete A?.commentHtml,delete A?.commentText,A})||[],c=C}return{strippedData:s,originalData:c,eventType:a}}catch(r){return this.loggingService.catch("Error in CommentAnnotationsResolverService stripCommentAnnotationData:",r),{strippedData:null,originalData:null}}}formatCommentThreadData(e){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: formatCommentThreadData","color: green;"),this.usersService.userDataProviderAvailable()){e?.from?.userId&&(e.from={userId:e.from.userId}),e?.to&&(e.to=e?.to?.map(r=>r?.userId?{userId:r.userId}:r)),e?.taggedUserContacts&&(e.taggedUserContacts=e?.taggedUserContacts?.map(r=>r?.contact?T(I({},r),{contact:{userId:r.userId}}):r));let i=e?.taggedUserContacts?.filter((r,a,s)=>s.findIndex(c=>c.text===r.text)===a)||[];i.forEach(r=>{if(r?.text){let a=new RegExp(dm(r.text),"g");e.commentText=e.commentText?.replaceAll(a,s=>`{{${r.userId}}}`),e.commentHtml=e.commentHtml?.replaceAll(a,s=>`{{${r.userId}}}`)}}),i.forEach(r=>{r?.text&&(r.text="")})}return e}catch(i){return this.loggingService.catch("Error in CommentUtilsService formatCommentThreadData:",i),e}}handleCommentEncryption(s){return te(this,arguments,function*({data:e,firestorePath:i,extraData:r,eventType:a}){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: handleCommentEncryption","color: green;");let c=c6(this.authService.getFirebaseConfig()?.firebaseOptions),p=_r(this.functions,Sr({url:Xn.cloudFunction?.[c]?.setEncryptedData,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:20*60*1e3});if(r){r=this.notificationService?.processNotificationData(r),r.annotationData=e;let A=r?.targetAnnotationData?.commentId;if(A){let B=e?.comments?.find(G=>G?.commentId===A);B&&(r.targetAnnotationData=B)}}let u=zp.getFirestoreProdDbName(this.configService.getApiKey()??"",this.authService.getFirebaseConfig()?.firebaseOptions),C={path:i??"",data:e??{},dbId:u??"",notificationData:r||void 0,notificationURL:Xn.firebaseNotificationsDatabaseURL,feature:"comment",eventType:a??"PATCH",sdkVersion:pa()},E=yield Ap(C,this.authService.getUser()?.userId??"");yield p({veltData:E})}catch(c){this.loggingService.catch("Error in CommentUtilsService handleCommentEncryption:",c)}})}};o.\u0275fac=function(i){return new(i||o)(Q(y),Q(zn),Q(je),Q(Uo),Q(jt),Q(bs),Q(Gp))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var kse=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.usersService=i}getUserIdsToResolveFromUserIamData(e){try{this.loggingService.log("%c[WB] Calling ContactUtilsService FUNCTION: getUserIdsToResolveFromUserIamData","color: green;");let i=new Set;if(e?.length)for(let r of e)r?.user?.userId&&i.add(r?.user?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in ContactUtilsService getUserIdsToResolveFromUserIamData: ",i),[]}}mergeUserIamWithUser(e){try{if(this.loggingService.log("%c[WB] Calling ContactUtilsService FUNCTION: mergeUserIamWithUser","color: green;"),e?.user?.userId){let i=this.usersService.getUserById(e?.user?.userId);i&&(e=T(I({},e),{user:i}))}return e}catch(i){return this.loggingService.catch("Error in ContactUtilsService mergeUserIamWithUser: ",i),e}}};o.\u0275fac=function(i){return new(i||o)(Q(y),Q(zn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Rse=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.usersService=i}getUserIdsToResolveFromCursorUsers(e){try{this.loggingService.log("%c[WB] Calling CursorUtilsService FUNCTION: getUserIdsToResolveFromCursorUsers","color: green;");let i=new Set;for(let r of e)r?.userId&&i.add(r?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in CursorUtilsService getUserIdsToResolveFromCursorUsers:",i),[]}}mergeCursorUserWithUser(e){try{if(this.loggingService.log("%c[WB] Calling CursorUtilsService FUNCTION: mergeCursorUserWithUser","color: green;"),this.usersService.userDataProviderAvailable()&&e?.userId){let i=this.usersService.getUserById(e?.userId);i&&(e=I(I({},e),i))}return e}catch(i){return this.loggingService.catch("Error in CursorUtilsService mergeCursorUserWithUser:",i),e}}formatCursorUserData(e){try{if(this.loggingService.log("%c[WB] Calling CursorUtilsService FUNCTION: formatCursorUserData","color: green;"),this.usersService.userDataProviderAvailable()){let i=["userId","comment","positionX","positionY","screenWidth","screenHeight","screenScrollHeight","onlineStatus","userSnippylyId","color","textColor","timestamp","type","selections","documentParamsId","documentParams","locationId","location","targetElement","position","isReadOnly","isAnonymous","pageInfo"];Object.keys(e).forEach(r=>{i.includes(r)||(e[r]=null)})}return e}catch(i){return this.loggingService.catch("Error in CursorUtilsService formatCursorUserData:",i),e}}};o.\u0275fac=function(i){return new(i||o)(Q(y),Q(zn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var WM=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.usersService=i}getUserIdsToResolveFromHuddleAttendees(e){try{this.loggingService.log("%c[WB] Calling HuddleUtilsService FUNCTION: getUserIdsToResolveFromHuddleAttendees","color: green;");let i=new Set;for(let r of e)r?.userId&&i.add(r?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in HuddleUtilsService getUserIdsToResolveFromHuddleAttendees:",i),[]}}mergeHuddleAttendeeWithUser(e){try{if(this.loggingService.log("%c[WB] Calling HuddleUtilsService FUNCTION: mergeHuddleAttendeeWithUser","color: green;"),e?.userId){let i=this.usersService.getUserById(e?.userId);i&&(e=I(I({},e),i))}return e}catch(i){return this.loggingService.catch("Error in HuddleUtilsService mergeHuddleAttendeeWithUser:",i),e}}formatHuddleAttendeeData(e){try{if(this.usersService.userDataProviderAvailable()){let i=["userId","userSnippylyId","state","timestamp","initialHuddleMode","streamMetadata","initialHuddleType","huddleOnCursorMode"];Object.keys(e).forEach(r=>{i.includes(r)||(e[r]=null)})}return e}catch(i){return this.loggingService.catch("Error in HuddleUtilsService formatHuddleAttendeeData:",i),e}}getUserIdsToResolveFromHuddleMessages(e){try{this.loggingService.log("%c[WB] Calling HuddleUtilsService FUNCTION: getUserIdsToResolveFromHuddleMessages","color: green;");let i=new Set;for(let r of e)r?.from?.userId&&i.add(r?.from?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in HuddleUtilsService getUserIdsToResolveFromHuddleMessages:",i),[]}}mergeHuddleMessageWithUser(e){try{if(this.loggingService.log("%c[WB] Calling HuddleUtilsService FUNCTION: mergeHuddleMessageWithUser","color: green;"),e?.from?.userId){let i=this.usersService.getUserById(e?.from?.userId);i&&(e.from=i)}return e}catch(i){return this.loggingService.catch("Error in HuddleUtilsService mergeHuddleMessageWithUser:",i),e}}resolveUsersFromHuddleMessages(e){return te(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling HuddleUtilsService FUNCTION: resolveUsersFromHuddleMessages","color: green;"),this.usersService.userDataProviderAvailable()){let i=this.getUserIdsToResolveFromHuddleMessages(e),r=yield this.usersService.resolveUsers(i);for(let a of e)a?.from?.userId&&r[a.from.userId]&&(a.from=r[a.from.userId])}return e}catch(i){return this.loggingService.catch("Error in HuddleUtilsService resolveUsersFromHuddleMessages:",i),e}})}formatHuddleMessageData(e){try{return this.loggingService.log("%c[WB] Calling HuddleUtilsService FUNCTION: formatHuddleMessageData","color: green;"),this.usersService.userDataProviderAvailable()&&e?.from?.userId&&(e.from={userId:e.from.userId}),e}catch(i){return this.loggingService.catch("Error in HuddleUtilsService formatHuddleMessageData:",i),e}}};o.\u0275fac=function(i){return new(i||o)(Q(y),Q(zn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Fse=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.usersService=i}getUserIdsToResolveFromLiveStateCustom(e){try{let i=new Set;return e?.updatedBy&&i.add(e?.updatedBy?.userId),Array.from(i)}catch(i){return this.loggingService.catch("Error in LiveStateUtilsService getUserIdsToResolveFromLiveStateCustom:",i),[]}}mergeLiveStateCustomWithUser(e){try{if(e?.updatedBy?.userId){let i=this.usersService.getUserById(e?.updatedBy?.userId);i&&(e.updatedBy=i)}return e}catch(i){return this.loggingService.catch("Error in LiveStateUtilsService mergeLiveStateCustomWithUser:",i),e}}formatLiveStateCustomData(e){try{return this.usersService.userDataProviderAvailable()&&e?.updatedBy&&(e.updatedBy={userId:e.updatedBy.userId}),e}catch(i){return this.loggingService.catch("Error in LiveStateUtilsService formatLiveStateCustomData:",i),e}}getUserIdsToResolveFromLiveStateCustoms(e){try{let i=new Set;for(let r of e)r?.updatedBy?.userId&&i.add(r?.updatedBy?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in LiveStateUtilsService getUserIdsToResolveFromLiveStateCustoms:",i),[]}}getUserIdsToResolveFromLiveStates(e){try{let i=new Set;return e?.default?.singleEditorMode?.editor?.userId&&i.add(e?.default?.singleEditorMode?.editor?.userId),Array.from(i)}catch(i){return this.loggingService.catch("Error in LiveStateUtilsService getUserIdsToResolveFromLiveStates:",i),[]}}mergeLiveStateWithUser(e){try{if(e?.default?.singleEditorMode?.editor?.userId){let i=this.usersService.getUserById(e?.default?.singleEditorMode?.editor?.userId);i&&(e.default.singleEditorMode.editor=i)}if(e?.default?.singleEditorMode?.requestEditorAccess?.user?.userId){let i=this.usersService.getUserById(e?.default?.singleEditorMode?.requestEditorAccess?.user?.userId);i&&(e.default.singleEditorMode.requestEditorAccess.user=i)}return e}catch(i){return this.loggingService.catch("Error in LiveStateUtilsService mergeLiveStateWithUser:",i),e}}formatLiveStateSingleEditorModeData(e){try{return this.usersService.userDataProviderAvailable()&&(e?.editor?.userId&&(e.editor={userId:e.editor.userId}),e?.requestEditorAccess?.user?.userId&&(e.requestEditorAccess.user={userId:e.requestEditorAccess.user.userId})),e}catch(i){return this.loggingService.catch("Error in LiveStateUtilsService formatLiveStateSingleEditorModeData:",i),e}}mergeLiveStateCustomsWithUsers(e){try{for(let i of e)if(i?.updatedBy?.userId){let r=this.usersService.getUserById(i?.updatedBy?.userId);r&&(i.updatedBy=r)}return e}catch(i){return this.loggingService.catch("Error in mergeLiveStateCustomsWithUsers:",i),e}}};o.\u0275fac=function(i){return new(i||o)(Q(y),Q(zn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Lse=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.usersService=i}getUserIdsToResolveFromMultiThreads(e){try{let i=new Set;for(let r of e)r?.from?.userId&&i.add(r?.from?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in MultiThreadUtilsService getUserIdsToResolveFromMultiThreads:",i),[]}}mergeMultiThreadWithUser(e){try{if(e?.from?.userId){let i=this.usersService.getUserById(e?.from?.userId);i&&(e.from=i)}return e}catch(i){return this.loggingService.catch("Error in MultiThreadUtilsService mergeMultiThreadWithUser:",i),e}}formatMultiThreadData(e){try{return this.usersService.userDataProviderAvailable()&&(e?.from?.userId&&(e.from={userId:e.from.userId}),e?.commentAnnotationsMap&&(e.commentAnnotationsMap=null)),e}catch(i){return this.loggingService.catch("Error in MultiThreadUtilsService formatMultiThreadData:",i),e}}};o.\u0275fac=function(i){return new(i||o)(Q(y),Q(zn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Kv=(()=>{let o=class o{constructor(e,i,r){this.authService=e,this.loggingService=i,this.usersService=r}getUserIdsToResolveFromRecorders(e){try{let i=new Set;for(let r of e)r?.from?.userId&&i.add(r?.from?.userId),r?.transcription?.from?.userId&&i.add(r?.transcription?.from?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in RecorderUtilsService getUserIdsToResolveFromRecorders:",i),[]}}mergeRecorderWithUser(e){try{if(e?.from?.userId){let i=this.usersService.getUserById(e?.from?.userId);i&&(e.from=i)}if(e?.transcription?.from?.userId){let i=this.usersService.getUserById(e?.transcription?.from?.userId);i&&(e.transcription.from=i)}return e}catch(i){return this.loggingService.catch("Error in RecorderUtilsService mergeRecorderWithUser:",i),e}}formatRecorderData(e,i){try{return e.transcription=e?.transcription?T(I({},e.transcription),{lastUpdated:i}):void 0,this.usersService.userDataProviderAvailable()&&(e?.from?.userId&&(e.from={userId:e.from.userId}),e?.transcription?.from?.userId&&(e.transcription.from={userId:e.transcription.from.userId})),e}catch(r){return this.loggingService.catch("Error in RecorderUtilsService formatRecorderData:",r),e}}formatRecorderDataForWhisperTranscription(e){try{return this.usersService.userDataProviderAvailable()&&e?.fromUser?.userId&&(e.fromUser={userId:e.fromUser?.userId}),e}catch(i){return this.loggingService.catch("Error in RecorderUtilsService formatRecorderDataForWhisperTranscription:",i),e}}encryptRecorderAnnotation(e){return te(this,null,function*(){try{return yield Ap(e,this.authService.getUser()?.userId??"")}catch(i){this.loggingService.catch("Error in RecorderUtilsService encryptRecorderAnnotation:",i);return}})}};o.\u0275fac=function(i){return new(i||o)(Q(je),Q(y),Q(zn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var qM=(()=>{let o=class o{constructor(e,i,r,a,s,c){this.commentUtilsService=e,this.recorderUtilsService=i,this.loggingService=r,this.usersService=a,this.authService=s,this.commentAnnotationsResolverService=c}getUserIdsToResolveFromNotifications(e){try{let i=new Set;for(let r of e){let{notification:a}=r;switch(a?.actionUser?.userId&&i.add(a?.actionUser?.userId),a?.displayHeadlineMessageTemplateData?.actionUser?.userId&&i.add(a?.displayHeadlineMessageTemplateData?.actionUser?.userId),a?.displayHeadlineMessageTemplateData?.recipientUser?.userId&&i.add(a?.displayHeadlineMessageTemplateData?.recipientUser?.userId),a?.notificationSource){case"comment":if(a?.notificationSourceData){let s=this.commentUtilsService.getUserIdsToResolveFromComments([a?.notificationSourceData]);for(let c of s)i.add(c)}break}}return Array.from(i)}catch(i){return this.loggingService.catch("Error in ReactionUtilsService getUserIdsToResolveFromRecorders:",i),[]}}mergeStrippedDataWithNotification(e){try{if(this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: mergeStrippedDataWithNotification","color: green;"),!this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())return e;let i=this.commentAnnotationsResolverService.getAnnotationById(e?.notification?.targetAnnotationId),r=e?.raw?.targetAnnotationData?.commentId,a=i?.comments?.[r]?.commentText,s=i?.comments?.[r]?.commentHtml;return a&&s&&e?.raw?.notificationSource==="comment"&&(e.notification.displayBodyMessageTemplate=a,e.raw.targetAnnotationData.commentText=a,e.raw.targetAnnotationData.commentHtml=s),e}catch(i){return this.loggingService.catch("Error in NotificationUtilsService mergeStrippedDataWithNotification:",i),e}}mergeLocationWithNotification(e,i){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: mergeLocationWithNotification","color: green;");let r=e?.notification?.notificationSourceData?.location?.id,a=e?.notification?.notificationSourceData?.metadata?.documentId;if(!r||!a)return e;let s=i?.[a]?.[r];return s&&(e.notification.notificationSourceData.location=s?.location,e?.raw?.annotationData?.location&&(e.raw.annotationData.location=s?.location)),e}catch(r){return this.loggingService.catch("Error in NotificationUtilsService mergeLocationWithNotification:",r),e}}mergeNotificationWithUser(e){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: mergeNotificationWithUser","color: green;");let{notification:i}=e;if(i?.actionUser?.userId){let r=this.usersService.getUserById(i?.actionUser?.userId);r&&(i.actionUser=r)}if(i?.displayHeadlineMessageTemplateData?.actionUser?.userId){let r=this.usersService.getUserById(i?.displayHeadlineMessageTemplateData?.actionUser?.userId);r&&(i.displayHeadlineMessageTemplateData.actionUser=r)}if(i?.displayHeadlineMessageTemplateData?.recipientUser?.userId){let r=this.usersService.getUserById(i?.displayHeadlineMessageTemplateData?.recipientUser?.userId);r&&(i.displayHeadlineMessageTemplateData.recipientUser=r)}switch(i?.notificationSource){case"comment":i?.notificationSourceData&&this.commentUtilsService.mergeCommentWithUser(i?.notificationSourceData);break}return e}catch(i){return this.loggingService.catch("Error in NotificationUtilsService mergeNotificationWithUser:",i),e}}formatNotification(e,i){try{switch(typeof e=="object"&&(e=JSON.parse(JSON.stringify(e))),this.usersService.userDataProviderAvailable()&&e?.actionUser&&(e.actionUser={userId:e.actionUser.userId}),e.notificationSource){case"comment":this.commentUtilsService.formatCommentData(e.annotationData),this.commentUtilsService.formatCommentThreadData(e.targetAnnotationData);break;case"recorder":this.recorderUtilsService.formatRecorderData(e.annotationData,i);break}return e}catch(r){return this.loggingService.catch("Error in NotificationUtilsService formatNotification: ",r),e}}getTargetAnnotationIdsFromNotifications(e){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: getTargetAnnotationIdsFromNotifications","color: green;");let i=[];return Object.values(e).forEach(r=>{r?.notification?.targetAnnotationId&&r?.raw?.notificationSource==="comment"&&i.push(r.notification.targetAnnotationId)}),i}catch(i){return this.loggingService.catch("Error in NotificationUtilsService getTargetAnnotationIdsFromNotifications:",i),[]}}handleNotificationEncryption(i){return te(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 Ap(e,r)}catch(r){return this.loggingService.catch("Error in NotificationUtilsService handleNotificationEncryption:",r),e}})}};o.\u0275fac=function(i){return new(i||o)(Q(Yv),Q(Kv),Q(y),Q(zn),Q(je),Q(bs))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Vse=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.usersService=i}getUserIdsToResolveFromPresenceUsers(e){try{let i=new Set;for(let r of e)r?.userId&&i.add(r?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in PresenceUtilsService getUserIdsToResolveFromPresenceUsers:",i),[]}}mergePresenceUserWithUser(e){try{if(this.usersService.userDataProviderAvailable()&&e?.userId){let i=this.usersService.getUserById(e?.userId);i&&(e=I(I({},e),i))}return e}catch(i){return this.loggingService.catch("Error in PresenceUtilsService mergePresenceUserWithUser:",i),e}}formatPresenceUserData(e){try{if(this.usersService.userDataProviderAvailable()){let i=["userId","onlineStatus","userSnippylyId","color","textColor","timestamp","type","selections","documentParamsId","documentParams","locationId","location","isReadOnly","isAnonymous","pageInfo"];Object.keys(e).forEach(r=>{i.includes(r)||(e[r]=null)})}return e}catch(i){return this.loggingService.catch("Error in PresenceUtilsService formatPresenceUserData:",i),e}}};o.\u0275fac=function(i){return new(i||o)(Q(y),Q(zn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Use=(()=>{let o=class o{constructor(e,i,r,a,s,c){this.loggingService=e,this.usersService=i,this.authService=r,this.functions=a,this.configService=s,this.reactionAnnotationsResolverService=c}getUserIdsToResolveFromReactions(e){try{let i=new Set;for(let r of e)if(r?.from?.userId&&i.add(r?.from?.userId),r?.reactions?.length)for(let a of r?.reactions)a?.from?.userId&&i.add(a?.from?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in ReactionUtilsService getUserIdsToResolveFromRecorders:",i),[]}}handleReactionEncryption(a){return te(this,arguments,function*({data:e,firestorePath:i,eventType:r}){try{let s=c6(this.authService.getFirebaseConfig()?.firebaseOptions),c=_r(this.functions,Sr({url:Xn.cloudFunction?.[s]?.setEncryptedData,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:20*60*1e3}),p=zp.getFirestoreProdDbName(this.configService.getApiKey()??"",this.authService.getFirebaseConfig()?.firebaseOptions),u=this.authService.getUser()?.userId??"",C={path:i??"",data:e??{},dbId:p??"",feature:"reaction",eventType:r??"PATCH",sdkVersion:pa()},E=yield Ap(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 i=this.usersService.getUserById(e?.from?.userId);i&&(e.from=i)}if(e?.reactions?.length){for(let i of e?.reactions)if(i?.from?.userId){let r=this.usersService.getUserById(i?.from?.userId);r&&(i.from=r)}}}return e}catch(i){return this.loggingService.catch("Error in ReactionUtilsService mergeReactionWithUser:",i),e}}formatReactionData(e){try{return this.usersService.userDataProviderAvailable()&&e?.from?.userId&&(e.from={userId:e.from.userId}),e.reactions=e?.reactions?.map(i=>(this.usersService.userDataProviderAvailable()&&i?.from?.userId&&(i.from={userId:i.from.userId}),i)),e}catch(i){return this.loggingService.catch("Error in ReactionUtilsService formatReactionData:",i),e}}isReactionDataChanged(e,i){try{this.loggingService.log("%c[WB] Calling ReactionUtilsService FUNCTION: isReactionDataChanged","color: green;");let r=this.reactionAnnotationsResolverService.getReactionAnnotationById(i);return r?!_o(e,r):!0}catch(r){return this.loggingService.catch("Error in ReactionUtilsService isReactionDataChanged:",r),!0}}stripReactionAnnotationData(e){try{if(this.loggingService.log("%c[WB] Calling ReactionUtilsService FUNCTION: stripReactionAnnotationData","color: green;"),!this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable())return{originalData:e,strippedData:null};let i={};if(e&&e.annotationId){let r=e.annotationId;if(i[r]={annotationId:r,metadata:hv(e.metadata??{}),icon:e.icon},!this.isReactionDataChanged(i[r],r))return{strippedData:null,originalData:e};delete e?.icon,e.isReactionResolverUsed=!0}return{strippedData:i,originalData:e}}catch(i){return this.loggingService.catch("Error in ReactionUtilsService stripReactionAnnotationData:",i),{strippedData:null,originalData:null}}}mergeStrippedDataWithReactionAnnotations(e){try{if(this.loggingService.log("%c[WB] Calling ReactionUtilsService FUNCTION: mergeStrippedDataWithReactionAnnotations","color: green;"),!this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable())return e;let i=this.reactionAnnotationsResolverService.getReactionAnnotationById(e?.annotationId);return i&&i.icon&&(e.icon=i.icon),e}catch(i){return this.loggingService.catch("Error in ReactionUtilsService mergeStrippedDataWithReactionAnnotations:",i),e}}};o.\u0275fac=function(i){return new(i||o)(Q(y),Q(zn),Q(je),Q(Uo),Q(jt),Q(Em))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var jse=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.usersService=i}getUserIdsToResolveFromSelections(e){try{let i=new Set;for(let r of e)r?.user?.userId&&i.add(r.user.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in SelectionUtilsService getUserIdsToResolveFromSelections:",i),[]}}mergeSelectionWithUser(e){try{if(e?.user?.userId){let i=this.usersService.getUserById(e?.user?.userId);i&&(e.user=i)}return e}catch(i){return this.loggingService.catch("Error in SelectionUtilsService mergeSelectionWithUser:",i),e}}formatSelectionData(e){try{return this.usersService.userDataProviderAvailable()&&e?.user?.userId&&(e.user={userId:e.user.userId}),e}catch(i){return this.loggingService.catch("Error in SelectionUtilsService formatSelectionData:",i),e}}};o.\u0275fac=function(i){return new(i||o)(Q(y),Q(zn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var $se=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.usersService=i}getUserIdsToResolveFromTags(e){try{let i=new Set;for(let r of e)if(r?.from?.userId&&i.add(r.from.userId),r?.to?.length)for(let a of r.to)a?.userId&&i.add(a.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in TagUtilsService getUserIdsToResolveFromTags:",i),[]}}mergeTagWithUser(e){try{if(e?.from?.userId){let i=this.usersService.getUserById(e?.from?.userId);i&&(e.from=i)}return e?.to?.length&&(e.to=e.to.map(i=>{if(i?.userId){let r=this.usersService.getUserById(i?.userId);r&&(i=r)}return i})),e}catch(i){return this.loggingService.catch("Error in TagUtilsService mergeTagWithUser:",i),e}}formatTagData(e){try{return this.usersService.userDataProviderAvailable()&&(e?.from?.userId&&(e.from={userId:e.from.userId}),e?.to?.length&&(e.to=e.to.map(i=>(i?.userId&&(i={userId:i.userId}),i)))),e}catch(i){return this.loggingService.catch("Error in TagUtilsService formatTagData:",i),e}}};o.\u0275fac=function(i){return new(i||o)(Q(y),Q(zn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Zv=(()=>{let o=class o{constructor(e,i,r,a,s,c,p,u,C,E,A,B,G,K,pe,Ce,Ie,$e,Ye){this.areaUtilsService=e,this.arrowUtilsService=i,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=A,this.reactionUtilsService=B,this.recorderUtilsService=G,this.selectionUtilsService=K,this.tagUtilsService=pe,this.usersService=Ce,this.docService=Ie,this.commentAnnotationsResolverService=$e,this.reactionAnnotationsResolverService=Ye}getFirestorePath({feature:e,properties:i,documentPaths:r,apiKey:a}){try{if(!a)return;let{documentId:s,organizationId:c,folderId:p}=i;c||(c=r?.organizationId);let u=new HM({apiKey:a,documentId:s?`${s}`:"",organizationId:c?`${c}`:"",veltFolderId:p?`${p}`:void 0});switch(e){case"comment":return i?.documentId&&i?.id&&u?.comment?`${u?.comment}/${i?.id}`:void 0;case"allComments":return i?.documentId&&u?.comment?`${u?.comment}`:void 0;case"multiThread":return i?.documentId&&i?.id&&u?.multiThread?`${u?.multiThread}/${i?.id}`:void 0;case"allMultiThreads":return i?.documentId&&u?.multiThread?`${u?.multiThread}`:void 0;case"allLastNotificationTimestamp":return u?.lastNotificationTimestamp?`${u?.lastNotificationTimestamp}`:void 0;case"lastNotificationTimestamp":return i?.id&&u?.lastNotificationTimestamp?`${u?.lastNotificationTimestamp}/${i?.id}`:void 0;case"area":return i?.documentId&&i?.id&&u?.area?`${u?.area}/${i?.id}`:void 0;case"allAreas":return i?.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&&i.folderId?`${u?.folder}/${i.folderId}`:void 0;case"documentUserAccess":return i?.documentId&&i?.id&&u?.documentUsers?`${u?.documentUsers}/${i?.id}`:void 0;case"reaction":return i?.documentId&&i?.id&&u?.reaction?`${u?.reaction}/${i?.id}`:void 0;case"allReactions":return i?.documentId&&u?.reaction?`${u?.reaction}`:void 0;case"recorder":return i?.documentId&&i?.id&&u?.recorder?`${u?.recorder}/${i?.id}`:void 0;case"allRecorders":return i?.documentId&&u?.recorder?`${u?.recorder}`:void 0;case"documentAccessType":return i?.documentId&&u?.document?`${u?.document}/${i?.documentId}`:void 0;case"organizationMetadata":return u?.organization?`${u?.organization}`:void 0;case"documentIam":case"documentMetadata":return i?.documentId&&u?.document?`${u?.document}/${i?.documentId}`:void 0;case"folderMetadata":return i?.folderId&&u?.folder?`${u?.folder}/${i?.folderId}`:void 0;case"locationMetadata":return i?.documentId&&u?.location&&i?.id?`${u?.location}/${i?.id}`:void 0;case"documentUser":return i?.documentId&&i?.id&&u?.documentUsers?`${u?.documentUsers}/${i?.id}`:void 0;case"allDocumentUsers":return i?.documentId&&u?.documentUsers?`${u?.documentUsers}`:void 0;case"allFolderUsers":return i?.folderId&&u?.folderUsers?`${u?.folderUsers}`:void 0;case"allOrganizationGroups":return u?.organizationGroups?`${u?.organizationGroups}`:void 0;case"allOrganizationUsers":return u?.organizationUsers?`${u?.organizationUsers}`:void 0;case"commentViews":return i?.documentId&&i?.id&&u?.commentViews?`${u?.commentViews}/${i?.id}`:void 0;case"allCommentViews":return i?.documentId&&u?.commentViews?`${u?.commentViews}`:void 0;case"notificationViewsTimestamp":return i?.documentId&&i?.id&&u?.notificationViews?`${u?.notificationViews}/${i?.id}`:void 0;case"allDocumentViews":return i?.documentId&&u?.documentViews?`${u?.documentViews}`:void 0;case"documentViews":case"documentMetadataViews":case"documentDayViews":case"documentUsersViews":return i?.documentId&&i?.id&&u?.documentViews?`${u?.documentViews}/${i?.id}`:void 0;case"locationDayViews":case"locationUsersViews":case"locationViews":case"locationMetadataViews":case"location":return i?.documentId&&i?.id&&u?.locationViews?`${u?.locationViews}/${i?.id}`:void 0;case"allLocationViews":return i?.documentId&&u?.locationViews?`${u?.locationViews}`:void 0;case"allDocNotifications":return i?.documentId&&u?.docNotification?`${u?.docNotification}`:void 0;case"docNotificationViews":case"docNotification":return i?.documentId&&i?.id&&u?.docNotification?`${u?.docNotification}/${i?.id}`:void 0;case"userNotificationViews":case"userNotification":return i?.userId&&i?.id&&u?.notificationUsers?`${u?.notificationUsers}/${i?.userId}/${U.FIREBASE_PARTIAL_PATH_USER_NOTIFICATION}/${i?.id}`:void 0;case"allDocNotifications":return i?.documentId&&u?.docNotification?`${u?.docNotification}`:void 0;case"allUserNotifications":return i?.userId&&u?.notificationUsers?`${u?.notificationUsers}/${i?.userId}/${U.FIREBASE_PARTIAL_PATH_USER_NOTIFICATION}`:void 0;default:throw new Error(`Unknown feature: ${e}`)}}catch(s){this.loggingService.catch("Error in CommonDbUtilsService getFirestorePath:",s);return}}getFirestoreCollectionGroupPath(e){try{switch(e){case"allComments":return U.FIREBASE_PARTIAL_PATH_COMMENT;case"allDocuments":return U.FIREBASE_PARTIAL_PATH_DOCS;case"allLocations":return U.FIREBASE_PARTIAL_PATH_LOCATION;case"allMultiThreads":return U.FIREBASE_PARTIAL_PATH_MULTI_THREAD;case"allAreas":return U.FIREBASE_PARTIAL_PATH_AREA;case"allReactions":return U.FIREBASE_PARTIAL_PATH_REACTION;case"allRecorders":return U.FIREBASE_PARTIAL_PATH_RECORDER;case"allDocumentViews":return U.FIREBASE_PARTIAL_PATH_DOCUMENT_VIEWS;case"allCommentViews":return U.FIREBASE_PARTIAL_PATH_COMMENT_VIEWS;case"allLocationViews":return U.FIREBASE_PARTIAL_PATH_LOCATION_VIEWS;case"allDocumentUsers":return U.FIREBASE_PARTIAL_PATH_DOCUMENT_USERS;case"allFolderUsers":return U.FIREBASE_PARTIAL_PATH_FOLDER_USERS;default:throw new Error(`Unknown feature: ${e}`)}}catch(i){this.loggingService.catch("Error in CommonDbUtilsService getFirestoreCollectionGroupPath:",i);return}}getDocumentPath({feature:e,properties:i,defaultDocumentPaths:r,apiKey:a,useFirestore:s}){try{if(!a)return;let{documentId:c,organizationId:p}=i;p||(p=r?.organizationId);let u=new Im({apiKey:a,documentId:c?`${c}`:"",organizationId:p?`${p}`:""});switch(e){case"allComments":return!s&&i?.documentId&&u?.comment?`${u?.comment}`:void 0;case"allGlobalContacts":return i?.documentId&&u?.globalContacts?`${u?.globalContacts}`:void 0;case"globalContacts":return i?.documentId&&i?.userId&&u?.globalContacts?`${u?.globalContacts}${i?.userId}`:void 0;case"groupContacts":return i?.documentId&&i?.groupId&&u?.groupContacts?`${u?.groupContacts}${i?.groupId}`:void 0;case"groupContactsUser":return i?.documentId&&i?.groupId&&i?.userId&&u?.groupContacts?`${u?.groupContacts}${i?.groupId}/${i?.userId}`:void 0;case"allLoginContacts":return i?.documentId&&i?.userId&&u?.logins?`${u?.logins}${i?.userId}/contacts`:void 0;case"allLogins":return i?.documentId&&u?.logins?`${u?.logins}`:void 0;case"logins":return i?.documentId&&i?.userId&&u?.logins?`${u?.logins}${i?.userId}`:void 0;case"customerMetadata":return u?.customerMetadata?`${u?.customerMetadata}`:void 0;case"allArrows":return i?.documentId&&u?.arrow?`${u?.arrow}`:void 0;case"arrow":return i?.documentId&&u?.arrow&&i.id?`${u?.arrow}${i.id}`:void 0;case"allCursors":return i?.documentId&&u?.cursor?`${u?.cursor}`:void 0;case"cursor":return i?.documentId&&u?.cursor&&i.id?`${u?.cursor}${i.id}`:void 0;case"flockUser":return i?.documentId&&u?.flock&&i.id?`${u?.flock}users/${i.id}`:void 0;case"flockSession":return i?.documentId&&u?.flock&&i.id?`${u?.flock}sessions/${i.id}`:void 0;case"allHuddleAttendees":return i?.documentId&&u?.huddle?`${u?.huddle}attendees`:void 0;case"huddleAttendee":return i?.documentId&&u?.huddle&&i.id?`${u?.huddle}attendees/${i.id}`:void 0;case"huddleAttendeeState":return i?.documentId&&u?.huddle&&i.id?`${u?.huddle}attendees/${i.id}/state`:void 0;case"allHuddleInvitees":return i?.documentId&&u?.huddle?`${u?.huddle}invitees`:void 0;case"huddleConnection":return i?.documentId&&u?.huddle&&i.id?`${u?.huddle}connections/${i.id}`:void 0;case"huddleIceCandidate":return i?.documentId&&u?.huddle&&i.id?`${u?.huddle}iceCandidates/${i.id}`:void 0;case"allHuddleIceCandidates":return i?.documentId&&u?.huddle?`${u?.huddle}iceCandidates`:void 0;case"allHuddleMessages":return i?.documentId&&u?.huddle?`${u?.huddle}messages`:void 0;case"huddleMessage":return i?.documentId&&u?.huddle&&i.id?`${u?.huddle}messages/${i.id}`:void 0;case"allLiveStates":return i?.documentId&&u?.liveState?`${u?.liveState}`:void 0;case"allLiveStateCustoms":return i?.documentId&&u?.liveState?`${u?.liveState}custom`:void 0;case"liveStateCustom":return i?.documentId&&u?.liveState&&i?.id?`${u?.liveState}custom/${i.id}`:void 0;case"liveStateSingleEditorMode":return i?.documentId&&u?.liveStateSingleEditorMode?`${u?.liveStateSingleEditorMode}`:void 0;case"liveStateAutoSyncStateCurrent":return i?.documentId&&u?.liveState?`${u?.liveState}default/autoSyncState/current`:void 0;case"liveStateAutoSyncStateHistoryId":return i?.documentId&&u?.liveState&&i?.id?`${u?.liveState}default/autoSyncState/history/${i.id}`:void 0;case"presence":return i?.documentId&&u?.presence&&i?.userId?`${u?.presence}${i?.userId}`:void 0;case"allPresence":return i?.documentId&&u?.presence?`${u?.presence}`:void 0;case"workspaceIam":return u?.workspaceIam?`${u?.workspaceIam}`:void 0;case"selection":return i?.documentId&&u?.selection&&i?.userId?`${u?.selection}${i?.userId}`:void 0;case"allSelections":return i?.documentId&&u?.selection?`${u?.selection}`:void 0;case"syncVideoPlayer":return i?.documentId&&u?.syncVideoPlayer?`${u?.syncVideoPlayer}`:void 0;case"allTags":return i?.documentId&&u?.tag?`${u?.tag}`:void 0;case"tag":return i?.documentId&&u?.tag&&i?.id?`${u?.tag}${i?.id}`:void 0;case"userContactUs":return i?.documentId&&u?.userContactUs?`${u?.userContactUs}`:void 0;case"userFeedback":return i?.documentId&&u?.userFeedback?`${u?.userFeedback}`:void 0;case"userReportBug":return i?.documentId&&u?.userReportBugs?`${u?.userReportBugs}`:void 0;case"comment":return!s&&i?.documentId&&i?.id&&u?.comment?`${u?.comment}${i?.id}`:void 0;case"allMultiThreads":return!s&&i?.documentId&&u?.multiThread?`${u?.multiThread}`:void 0;case"multiThread":return!s&&i?.documentId&&i?.id&&u?.multiThread?`${u?.multiThread}${i?.id}`:void 0;case"allLastNotificationTimestamp":return!s&&u?.organizationNotificationsLastNotificationTimestamp?`${u?.organizationNotificationsLastNotificationTimestamp}`:void 0;case"lastNotificationTimestamp":return!s&&i?.id&&u?.organizationNotificationsLastNotificationTimestamp?`${u?.organizationNotificationsLastNotificationTimestamp}${i?.id}`:void 0;case"documentIam":return!s&&i?.documentId&&u?.documentIam?`${u?.documentIam}`:void 0;case"documentMetadata":return!s&&i?.documentId&&u?.metadata?`${u?.metadata}`:void 0;case"allDocuments":return!s&&u?.docs&&i?.documentId?`${u?.docs}/${i?.documentId}/${U.FIREBASE_PARTIAL_PATH_METADATA}`:void 0;case"allAreas":return!s&&i?.documentId&&u?.area?`${u?.area}`:void 0;case"area":return!s&&i?.id&&u?.area?`${u?.area}${i?.id}`:void 0;case"documentUserAccess":return!s&&i?.id&&u?.documentIam?`${u?.documentIam}users/${i?.id}`:void 0;case"documentUser":return!s&&i?.documentId&&i?.id&&u?.documentIam?`${u?.documentIam}users/${i?.id}`:void 0;case"allDocumentUsers":return!s&&i?.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&&i?.id&&u?.reaction?`${u?.reaction}${i?.id}`:void 0;case"allReactions":return!s&&i?.documentId&&u?.reaction?`${u?.reaction}`:void 0;case"recorder":return!s&&i?.documentId&&i?.id&&u?.recorder?`${u?.recorder}${i?.id}`:void 0;case"allRecorders":return!s&&i?.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&&i?.documentId&&u?.metadata?`${u?.metadata}`:void 0;case"commentViews":return!s&&i?.documentId&&i?.id&&u?.views?`${u?.views}comment/${i?.id}`:void 0;case"allDocumentViews":return!s&&i?.documentId&&u?.views?`${u?.views}documentViews/`:void 0;case"documentViews":return!s&&i?.documentId&&i?.id&&u?.views?`${u?.views}documentViews/${i?.id}`:void 0;case"allCommentViews":return!s&&i?.documentId&&u?.views?`${u?.views}comment/`:void 0;case"allLocationViews":return!s&&i?.documentId&&u?.views?`${u?.views}locationViews/`:void 0;case"notificationViewsTimestamp":return!s&&i?.id&&i?.user&&u?.views?`${u?.views}notification/${i?.id}/views/${i?.user}`:void 0;case"documentUsersViews":return!s&&i?.id&&i?.user&&i?.date&&u?.views?`${u?.views}documentViews/${i?.id}/users/${i?.user}/${i?.date}`:void 0;case"documentMetadataViews":return!s&&i?.id&&u?.views?`${u?.views}documentViews/${i?.id}/metadata`:void 0;case"documentDayViews":return!s&&i?.id&&i?.date&&i?.user&&u?.views?`${u?.views}documentViews/${i?.id}/day/${i?.date}/${i?.user}`:void 0;case"locationViews":return!s&&i?.id&&u?.views?`${u?.views}locationViews/${i?.id}/location`:void 0;case"location":return!s&&i?.id&&u?.views?`${u?.views}locationViews/${i?.id}`:void 0;case"locationUsersViews":return!s&&i?.id&&i?.user&&i?.date&&u?.views?`${u?.views}locationViews/${i?.id}/users/${i?.user}/${i?.date}`:void 0;case"locationMetadataViews":return!s&&i?.id&&u?.views?`${u?.views}locationViews/${i?.id}/metadata`:void 0;case"locationDayViews":return!s&&i?.id&&i?.date&&i?.user&&u?.views?`${u?.views}locationViews/${i?.id}/day/${i?.date}/${i?.user}`:void 0;case"docNotificationViews":case"docNotification":return i?.documentId&&i?.id&&u?.organizationNotificationsWithDocumentId?`${u?.organizationNotificationsWithDocumentId}${i?.id}`:void 0;case"allDocNotifications":return i?.documentId&&u?.organizationNotificationsWithDocumentId?`${u?.organizationNotificationsWithDocumentId}`:void 0;case"allUserNotifications":return i?.userId&&u?.organizationNotificationsUsers?`${u?.organizationNotificationsUsers}${i?.userId}`:void 0;case"userNotificationViews":case"userNotification":return i?.userId&&i?.id&&u?.organizationNotificationsUsers?`${u?.organizationNotificationsUsers}${i?.userId}/${i?.id}`:void 0;case"locationMetadata":return;case"allLocations":return;case"folderMetadata":return;default:throw new Error(`Unknown feature: ${e}`)}}catch(c){this.loggingService.catch("Error in CommonDbUtilsService getDocumentPath:",c);return}}resolveAnnotations(r){return te(this,arguments,function*({data:e,feature:i}){try{if(e&&e?.length>0)switch(i){case"allComments":{this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable()&&this.commentAnnotationsResolverService.resolveCommentAnnotations({commentAnnotationIds:e,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""});break}case"allReactions":{this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable()&&this.reactionAnnotationsResolverService.resolveReactionAnnotations({reactionAnnotationIds:e,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""});break}default:break}}catch(a){this.loggingService.catch(`Error in CommonDbUtilsService resolveAnnotations: ${i}`,a)}})}formatResponse(c){return te(this,arguments,function*({feature:e,data:i,shouldAwait:r=!1,forceResolve:a=!1,shouldCommentAnnotationsResolverAwait:s=!1}){try{if(this.usersService.userDataProviderAvailable()){let p=[];switch(e){case"allAreas":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.areaUtilsService.getUserIdsToResolveFromAreaAnnotations(Object.values(i)));break}case"allArrows":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.arrowUtilsService.getUserIdsToResolveFromArrowAnnotations(Object.values(i)));break}case"allCursors":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.cursorUtilsService.getUserIdsToResolveFromCursorUsers(Object.values(i)));break}case"allComments":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.commentUtilsService.getUserIdsToResolveFromComments(Object.values(i)));break}case"allDocumentUsers":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.contactUtilsService.getUserIdsToResolveFromUserIamData(Object.values(i)));break}case"allFolderUsers":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.contactUtilsService.getUserIdsToResolveFromUserIamData(Object.values(i)));break}case"allOrganizationUsers":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.contactUtilsService.getUserIdsToResolveFromUserIamData(Object.values(i)));break}case"allMultiThreads":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.multiThreadUtilsService.getUserIdsToResolveFromMultiThreads(Object.values(i)));break}case"allDocNotifications":{i&&typeof i=="object"&&(p=this.notificationUtilsService.getUserIdsToResolveFromNotifications(Array.isArray(i)?i:Object.values(i)));break}case"allUserNotifications":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.notificationUtilsService.getUserIdsToResolveFromNotifications(Object.values(i)));break}case"allPresence":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.presenceUtilsService.getUserIdsToResolveFromPresenceUsers(Object.values(i)));break}case"allRecorders":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.recorderUtilsService.getUserIdsToResolveFromRecorders(Object.values(i)));break}case"allReactions":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.reactionUtilsService.getUserIdsToResolveFromReactions(Object.values(i)));break}case"allTags":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.tagUtilsService.getUserIdsToResolveFromTags(Object.values(i)));break}case"allHuddleAttendees":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.huddleUtilsService.getUserIdsToResolveFromHuddleAttendees(Object.values(i)));break}case"liveStateCustom":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.liveStateUtilsService.getUserIdsToResolveFromLiveStateCustom(i));break}case"allLiveStateCustoms":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.liveStateUtilsService.getUserIdsToResolveFromLiveStateCustoms(Object.values(i)));break}case"allLiveStates":{i&&typeof i=="object"&&(p=this.liveStateUtilsService.getUserIdsToResolveFromLiveStates(i));break}case"allSelections":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.selectionUtilsService.getUserIdsToResolveFromSelections(Object.values(i)));break}default:p=[]}p?.length&&(r?yield this.usersService.resolveUsers(p,a):this.usersService.resolveUsers(p,a))}if(this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable()){let p=[];switch(e){case"allDocNotifications":{if(i&&typeof i=="object"){let u=this.notificationUtilsService.getTargetAnnotationIdsFromNotifications(i);p=[...p,...u],p=p.filter(C=>!this.commentAnnotationsResolverService.getCommentAnnotationById(C))}break}case"allUserNotifications":{if(i&&typeof i=="object"&&!Array.isArray(i)){let u=this.notificationUtilsService.getTargetAnnotationIdsFromNotifications(i);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 i}catch(p){return this.loggingService.catch("Error in CommonDbUtilsService formatResponse:",p),i}})}mergeCommentAnnotationsWithData({data:e,feature:i}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeCommentAnnotationsWithData","color: green;"),this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())switch(i){case"allComments":return e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).reduce((r,[a,s])=>(r[a]=this.commentUtilsService.mergeStrippedDataWithCommentAnnotations(s),r),{}):e;case"allDocNotifications":case"allUserNotifications":return e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).reduce((r,[a,s])=>(r[a]=this.notificationUtilsService.mergeStrippedDataWithNotification(s),r),{}):e;default:return e}return e}catch(r){return this.loggingService.catch("Error in CommonDbUtilsService mergeCommentAnnotationsWithData:",r),e}}mergeReactionAnnotationsWithData({data:e,feature:i}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeReactionAnnotationsWithData","color: green;"),this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable())switch(i){case"allReactions":return e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).reduce((r,[a,s])=>(r[a]=this.reactionUtilsService.mergeStrippedDataWithReactionAnnotations(s),r),{}):e;default:return e}return e}catch(r){return this.loggingService.catch("Error in CommonDbUtilsService mergeReactionAnnotationsWithData:",r),e}}mergeLocationMetadataWithData({data:e,feature:i,locationMetadata:r}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeLocationMetadataWithData","color: green;"),r&&typeof r=="object"&&!Array.isArray(r))switch(i){case"allComments":return e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).reduce((a,[s,c])=>(a[s]=this.commentUtilsService.mergeLocationWithCommentAnnotations(c,r),a),{}):e;case"allDocNotifications":case"allUserNotifications":return e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).reduce((a,[s,c])=>(a[s]=this.notificationUtilsService.mergeLocationWithNotification(c,r),a),{}):e;default:return e}return e}catch(a){return this.loggingService.catch("Error in CommonDbUtilsService mergeLocationMetadataWithData:",a),e}}mergeUsersWithData({feature:e,data:i}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeUsersWithData","color: green;"),this.usersService.userDataProviderAvailable())switch(e){case"allAreas":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.areaUtilsService.mergeAreaWithUser(s),r),{}):i;case"allArrows":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.arrowUtilsService.mergeArrowWithUser(s),r),{}):i;case"allCursors":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.cursorUtilsService.mergeCursorUserWithUser(s),r),{}):i;case"allComments":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.commentUtilsService.mergeCommentWithUser(s),r),{}):i;case"allDocumentUsers":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.contactUtilsService.mergeUserIamWithUser(s),r),{}):i;case"allFolderUsers":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.contactUtilsService.mergeUserIamWithUser(s),r),{}):i;case"allOrganizationUsers":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.contactUtilsService.mergeUserIamWithUser(s),r),{}):i;case"allMultiThreads":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.multiThreadUtilsService.mergeMultiThreadWithUser(s),r),{}):i;case"allDocNotifications":return i&&typeof i=="object"?i?.map(r=>this.notificationUtilsService.mergeNotificationWithUser(r)):i;case"allUserNotifications":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.notificationUtilsService.mergeNotificationWithUser(s),r),{}):i;case"allPresence":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.presenceUtilsService.mergePresenceUserWithUser(s),r),{}):i;case"allRecorders":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.recorderUtilsService.mergeRecorderWithUser(s),r),{}):i;case"allReactions":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.reactionUtilsService.mergeReactionWithUser(s),r),{}):i;case"allTags":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.tagUtilsService.mergeTagWithUser(s),r),{}):i;case"allHuddleAttendees":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.huddleUtilsService.mergeHuddleAttendeeWithUser(s),r),{}):i;case"liveStateCustom":return i&&typeof i=="object"&&!Array.isArray(i)?this.liveStateUtilsService.mergeLiveStateCustomWithUser(i):i;case"allLiveStateCustoms":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.liveStateUtilsService.mergeLiveStateCustomWithUser(s),r),{}):i;case"allLiveStates":return i&&typeof i=="object"?this.liveStateUtilsService.mergeLiveStateWithUser(i):i;case"allSelections":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.selectionUtilsService.mergeSelectionWithUser(s),r),{}):i;default:return i}return i}catch(r){return this.loggingService.catch("Error in CommonDbUtilsService mergeUsersWithData:",r),i}}mergeCommentAnnotationsWithData$({data:e,feature:i}){try{return this.commentAnnotationsResolverService.getCommentAnnotationsById$().pipe(ce(()=>{let r=this.mergeCommentAnnotationsWithData({data:e?.data??{},feature:i}),a=this.mergeUsersWithData({feature:i,data:r??{}});return typeof a=="object"?{data:JSON.parse(JSON.stringify(a)),operation:e?.operation??null}:{data:a,operation:e?.operation??null}}),qt(Vi))}catch(r){return this.loggingService.catch("Error in mergeCommentAnnotationsWithData:",r),re(e)}}mergeReactionAnnotationsWithData$({data:e,feature:i}){try{return this.reactionAnnotationsResolverService.getReactionAnnotationsById$().pipe(ce(()=>{let r=this.mergeReactionAnnotationsWithData({data:e?.data??{},feature:i}),a=this.mergeUsersWithData({feature:i,data:r??{}});return typeof a=="object"?{data:JSON.parse(JSON.stringify(a)),operation:e?.operation??null}:{data:a,operation:e?.operation??null}}),qt(Vi))}catch(r){return this.loggingService.catch("Error in mergeReactionAnnotationsWithData:",r),re(e)}}mergeUsersWithData$({feature:e,data:i}){try{return this.usersService.getUserById$().pipe(ce(()=>{let r=this.mergeUsersWithData({feature:e,data:i?.data??{}});return typeof r=="object"?{data:JSON.parse(JSON.stringify(r)),operation:i?.operation??null}:{data:r,operation:i?.operation??null}}),qt(Vi))}catch(r){return this.loggingService.catch(`Error in mergeUsersWithData for ${e}:`,r),re(i)}}mergeLocationMetadataWithData$({data:e,feature:i}){try{return this.docService.getLocationMetadata$().pipe(ce(r=>{let a=this.mergeLocationMetadataWithData({data:e?.data??{},feature:i,locationMetadata:r});return typeof a=="object"?{data:JSON.parse(JSON.stringify(a)),operation:e?.operation??null}:{data:a,operation:e?.operation??null}}),qt(Vi))}catch(r){return this.loggingService.catch(`Error in mergeLocationMetadataWithData for ${i}:`,r),re(e)}}handleDataStripping({feature:e,data:i,actionType:r}){try{switch(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: handleDataStripping","color: green;"),e){case"comment":return this.commentUtilsService.stripCommentAnnotationData({data:i,actionType:r});case"reaction":return this.reactionUtilsService.stripReactionAnnotationData(i);default:return{originalData:i,strippedData:null}}}catch(a){return this.loggingService.catch("Error in CommonDbUtilsService handleDataStripping:",a),{originalData:i,strippedData:null}}}formatData({feature:e,data:i,properties:r,offset:a,isRealtimeDb:s}){try{this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: formatData","color: green;"),typeof i=="object"&&(i=JSON.parse(JSON.stringify(i)));let c=new Date().getTime()+a;switch(e){case"documentAccessType":return delete i?.users,{docIamConfig:i};case"organizationMetadata":case"documentMetadata":return s?i:{metadata:i};case"cursor":return this.cursorUtilsService.formatCursorUserData(i);case"comment":return this.commentUtilsService.formatCommentData(i);case"area":return this.areaUtilsService.formatAreaData(i);case"arrow":return this.arrowUtilsService.formatArrowData(i);case"liveStateCustom":return this.liveStateUtilsService.formatLiveStateCustomData(i);case"liveStateSingleEditorMode":return this.liveStateUtilsService.formatLiveStateSingleEditorModeData(i);case"multiThread":return this.multiThreadUtilsService.formatMultiThreadData(i);case"reaction":return this.reactionUtilsService.formatReactionData(i);case"recorder":return this.recorderUtilsService.formatRecorderData(i,c);case"notificationViewsTimestamp":return{views:{[r.user??""]:i}};case"documentUsersViews":return s?i:{users:{[r.user??""]:{[r.date??""]:i}}};case"documentDayViews":return s?i:{day:{[r.date??""]:{[r.user??""]:i}}};case"documentMetadataViews":return s?i:{metadata:i};case"huddleMessage":return this.huddleUtilsService.formatHuddleMessageData(i);case"locationMetadataViews":return s?i:{metadata:i};case"locationUsersViews":return s?i:{users:{[r.user??""]:{[r.date??""]:i}}};case"locationDayViews":return s?i:{day:{[r.date??""]:{[r.user??""]:i}}};case"locationViews":return s?i:{location:i};case"docNotificationViews":return s?i:{views:i.views};case"userNotificationViews":return s?i:{views:i.views};case"presence":return this.presenceUtilsService.formatPresenceUserData(i);case"selection":return this.selectionUtilsService.formatSelectionData(i);case"tag":return this.tagUtilsService.formatTagData(i);default:return i}}catch(c){return this.loggingService.catch("Error in CommonDbUtilsService formatData:",c),i}}modifyAndSetData(s){return te(this,arguments,function*({feature:e,data:i,subscriber:r,operation:a=null}){try{let c=yield this.modifyData({feature:e,data:i});r.next({data:c,operation:a})}catch(c){this.loggingService.catch("Error in CommonDbUtilsService modifyAndSetData:",c)}})}isDataAlreadyProcessedInLocalCache({feature:e,change:i,cache:r}){try{if(e==="allReactions"||e==="allComments"){if(i.type==="removed")return!Object.keys(r??{}).includes(i.doc.id);if(r?.[i.doc.id]){let a=i.doc.data(),s=r?.[i.doc.id];return a?.lastUpdated===s?.lastUpdated}}return!1}catch(a){return this.loggingService.catch("Error in CommonDbUtilsService isDataAlreadyProcessedInLocalCache:",a),!1}}modifyData(r){return te(this,arguments,function*({feature:e,data:i}){try{return yield this.formatResponse({feature:e,data:i})}catch(a){return this.loggingService.catch("Error in CommonDbUtilsService modifyData:",a),i}})}addMetadata(e,i){try{return e&&typeof e=="object"&&!Array.isArray(e)?T(I({},e),{metadata:e?.metadata??{documentId:i?.documentId,organizationId:i?.organizationId,apiKey:i?.apiKey}}):e}catch(r){return this.loggingService.catch("Error in CommonDbUtilsService addMetadata:",r),e}}setDataInLocal(p){return te(this,arguments,function*({feature:e,data:i,observablesCache:r,eventType:a,id:s,operation:c=null}){try{let C={comment:"allComments",reaction:"allReactions"}[e];if(!C)return null;let E=i?.metadata?.documentId,A=i?.metadata?.veltFolderId;return Object.keys(r).filter(B=>B.includes(C)&&(!E||B.includes(E)||A&&B.includes(A))).forEach(B=>{let G=r[B]?.subject?.getValue()??{};a==="DELETE"?s&&G?.data?.[s]&&(delete G?.data?.[s],r[B]?.subject&&r[B].subject.next({data:G?.data,operation:c})):r[B]?.subject?.next({data:T(I({},G?.data),{[i?.annotationId]:i}),operation:c})}),null}catch(u){return this.loggingService.catch("Error in CommonDbUtilsService setDataInLocal:",u),null}})}handleCommentEncryption(s){return te(this,arguments,function*({data:e,firestorePath:i,extraData:r,eventType:a}){try{return yield this.commentUtilsService.handleCommentEncryption({data:e,firestorePath:i,extraData:r,eventType:a})}catch(c){return this.loggingService.catch("Error in CommonDbUtilsService handleCommentEncryption:",c),e}})}handleReactionEncryption(a){return te(this,arguments,function*({data:e,firestorePath:i,eventType:r}){try{return yield this.reactionUtilsService.handleReactionEncryption({data:e,firestorePath:i,eventType:r})}catch(s){return this.loggingService.catch("Error in CommonDbUtilsService handleReactionEncryption:",s),e}})}};o.\u0275fac=function(i){return new(i||o)(Q(Mse),Q(Pse),Q(Yv),Q(kse),Q(Rse),Q(WM),Q(Fse),Q(y),Q(Lse),Q(qM),Q(Vse),Q(Use),Q(Kv),Q(jse),Q($se),Q(zn),Q(lt),Q(bs),Q(Em))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Hse=(()=>{let o=class o{constructor(e,i,r){this.configService=e,this.authService=i,this.loggingService=r,this.firestore$=new ve(null);try{Mn([this.authService.getFirebaseConfig$(),this.configService.getApiKey$()]).pipe(Ne(([a,s])=>!!a&&!!s),et(1)).subscribe(([a,s])=>{a&&s&&a?.firebaseOptions?.storeDbId&&this.firestore$.next(_M(zp.getFirestoreProdDbName(s,a.firebaseOptions)))},a=>{})}catch{}}getFirestore(){return this.firestore$.asObservable()}getFirestoreValue(){return this.firestore$.value}generateFirestoreDocumentId(){try{let e=this.getFirestoreValue()||_M("DocumentIdDb");if(e){let i=HS(e,"generateDocumentId");return jv(i).id}return}catch(e){this.loggingService.catch("Error in FirestoreService generateFirestoreDocumentId: ",e);return}}};o.\u0275fac=function(i){return new(i||o)(Q(jt),Q(je),Q(y))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var En=(()=>{let o=class o{constructor(e,i,r,a,s,c,p,u,C,E){this.authService=e,this.commonDbUtilsService=i,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.loggingService.log("%c[WB] Creating CLASS: CommonDbService","color: blue;"),this.docService.setCommonDbService(this),this.authService.setCommonDbService(this),this.subscriptions.push(this.databaseService.getDb().subscribe(A=>{if(A){this.db=A;let B=on(A,".info/serverTimeOffset");this.offsetListener=yu(B,G=>{let K=G.val();this.offset=K})}})),this.subscriptions.push(this.firestoreService.getFirestore().subscribe(A=>{A&&(this.firestore=A)}))}unsubscribeFromObservables(){try{Object.values(this.firestoreSubscriptions??{}).forEach(e=>{e?.unsubscribe()}),Object.entries(this.observablesCache??{}).forEach(([e,i])=>{i?.subject?.complete(),i?.subject?.unsubscribe()}),this.observablesCache={},this.firestoreSubscriptions={}}catch(e){this.loggingService.catch("Error in unsubscribeFromObservables:",e)}}ngOnDestroy(){this.subscriptions.forEach(e=>e.unsubscribe()),this.offsetListener&&this.offsetListener(),this.unsubscribeFromObservables()}getOffset(){return this.offset}getServerTimestamp(){return new Date().getTime()+this.getOffset()}subscribeToServices(e){Mn([this.databaseService.getDb(),this.firestoreService.getFirestore()]).pipe(Ne(([i,r])=>!!i),et(1),gn(([i,r])=>{e({db:i,firestore:r})})).subscribe({error:i=>{this.loggingService.catch("Error in CommonDbService subscription: ",i)}})}performDatabaseOperation(e,i,r,a,s,c){return te(this,null,function*(){try{if(!i){this.loggingService.warn(`%c[WB] No properties found for ${e}`,"color: red;");return}return this.subscribeToServices(C=>te(this,[C],function*({db:p,firestore:u}){let E;i?.skipFirestore||(E=this.commonDbUtilsService.getFirestorePath({feature:e,properties:i,documentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey()}));let A=this.commonDbUtilsService.getDocumentPath({feature:e,properties:i,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey(),useFirestore:this.shouldUseFirestore()});if(!p){this.loggingService.warn(`%c[WB] No database or firestore found for ${e}`,"color: red;");return}try{let B,G;try{A&&(B=on(p,`${A}`))}catch{this.loggingService.catch("Error in dbRef")}try{E?.includes("/organizations")&&u&&E&&(G=jv(u,`${E}`))}catch{this.loggingService.catch("Error in docRef")}yield r({dbRef:B,firestoreRef:G,data:a,firestorePath:E}),c&&c({firestoreAvailable:!!u})}catch(B){this.loggingService.catch(`Error in ${e} operation: `,B),s&&s(B)}}))}catch(p){this.loggingService.catch("Error in performDatabaseOperation:",p)}})}setData(p){return te(this,arguments,function*({feature:e,data:i,properties:r,callback:a,errorCallback:s,extraData:c}){try{return this.loggingService.log(`%c[WB] Calling FUNCTION: setData for ${e}`,"color: green;"),this.shouldUseFirestore()&&i?.metadata&&!i?.metadata?.apiKey?void 0:(this.commonDbUtilsService.setDataInLocal({feature:e,data:i,observablesCache:this.observablesCache,operation:null}),this.performDatabaseOperation(e,r,u=>te(this,null,function*(){if(u.dbRef){let C=this.commonDbUtilsService.formatData({feature:e,data:u.data,properties:r,offset:this.getOffset(),isRealtimeDb:!0});yield Vf(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:A,eventType:B}=this.commonDbUtilsService.handleDataStripping({feature:e,data:C,actionType:c?.actionType});if(e==="comment"){let G=null;E&&(G=yield this.commentAnnotationsResolverService.saveCommentAnnotation({commentAnnotation:E,eventType:B,commentId:c?.targetAnnotationData?.commentId})),A&&(G?.isSuccess||G===null)&&(yield this.commonDbUtilsService.handleCommentEncryption({data:A,firestorePath:u.firestorePath??"",extraData:c}))}else if(e==="reaction"){let G=null;E&&(G=yield this.reactionAnnotationsResolverService.saveReactionAnnotation(E)),A&&(G?.isSuccess||G===null)&&(yield this.commonDbUtilsService.handleReactionEncryption({data:A,firestorePath:u.firestorePath??""}))}else yield b$(u.firestoreRef,C)}}catch(C){this.loggingService.catch(`Error in setData for ${e}`,C)}}),i,s,a))}catch(u){this.loggingService.catch(`Error in setData for ${e}`,u)}})}updateData(p){return te(this,arguments,function*({feature:e,data:i,properties:r,callback:a,errorCallback:s,extraData:c}){try{return this.loggingService.log(`%c[WB] Calling FUNCTION: updateData for ${e}`,"color: green;"),this.shouldUseFirestore()&&i?.metadata&&!i?.metadata?.apiKey?void 0:(this.commonDbUtilsService.setDataInLocal({feature:e,data:i,observablesCache:this.observablesCache,operation:null}),this.performDatabaseOperation(e,r,u=>te(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});yield c5(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:A,eventType:B}=this.commonDbUtilsService.handleDataStripping({feature:e,data:C,actionType:c?.actionType});if(e==="comment"){let G=null;E&&(G=yield this.commentAnnotationsResolverService.saveCommentAnnotation({commentAnnotation:E,eventType:B,commentId:c?.targetAnnotationData?.commentId})),A&&(G?.isSuccess||G===null)&&(yield this.commonDbUtilsService.handleCommentEncryption({data:A,firestorePath:u.firestorePath??"",extraData:c}))}else if(e==="reaction"){let G=null;E&&(G=yield this.reactionAnnotationsResolverService.saveReactionAnnotation(E)),A&&(G?.isSuccess||G===null)&&(yield this.commonDbUtilsService.handleReactionEncryption({data:A,firestorePath:u.firestorePath??""}))}else yield b$(u.firestoreRef,C,{merge:!0})}}catch(C){this.loggingService.catch(`Error in updateDoc for ${e}`,C)}}),i,s,a))}catch(u){this.loggingService.catch(`Error in updateData for ${e}`,u)}})}deleteData(s){return te(this,arguments,function*({feature:e,properties:i,callback:r,errorCallback:a}){try{return this.loggingService.log(`%c[WB] Calling FUNCTION: deleteData for ${e}`,"color: green;"),this.commonDbUtilsService.setDataInLocal({feature:e,observablesCache:this.observablesCache,eventType:"DELETE",id:i?.id,operation:{type:"removed",ids:[i?.id]}}),this.performDatabaseOperation(e,i,c=>te(this,null,function*(){c.dbRef&&(yield s5(c.dbRef));try{if(c.firestoreRef&&!i?.skipFirestore)if(e==="comment"){let p=null;p=yield this.commentAnnotationsResolverService.deleteCommentAnnotation(i?.id??""),(p?.isSuccess||p===null)&&(yield this.commonDbUtilsService.handleCommentEncryption({firestorePath:c.firestorePath??"",eventType:"DELETE"}))}else if(e==="reaction"){let p=null;p=yield this.reactionAnnotationsResolverService.deleteReactionAnnotation(i?.id??""),(p?.isSuccess||p===null)&&(yield this.commonDbUtilsService.handleReactionEncryption({firestorePath:c.firestorePath??"",eventType:"DELETE"}))}else yield lse(c.firestoreRef)}catch(p){this.loggingService.catch(`Error in deleteData for ${e}`,p)}}),void 0,a,r)}catch(c){this.loggingService.catch(`Error in deleteData for ${e}`,c)}})}shouldUseFirestore(){try{return this.authService.getAdvancedQueriesEnabled()}catch(e){return this.loggingService.catch("Error in shouldUseFirestore:",e),!1}}generateDocumentId(){try{let e=this.firestoreService.generateFirestoreDocumentId();return e||(e=wn()),e||"noDocumentId"}catch(e){return this.loggingService.catch("Error in generateFirestoreDocumentId:",e),wn()||"noDocumentId"}}queryData(r){return te(this,arguments,function*({feature:e,properties:i}){try{let a=this.shouldUseFirestore();return!e||!i?(this.loggingService.warn("[WB] Missing required parameters in queryData"),[]):a?yield this.handleFirestoreQuery(e,i):yield this.handleRtdbQuery(e,i)}catch(a){return this.loggingService.catch(`Error in queryData for ${e}`,a),[]}})}handleFirestoreQuery(e,i){return te(this,null,function*(){try{if(!this.firestore)return this.loggingService.warn("[WB] Firestore not initialized"),[];let r=i?.useCollectionGroup?this.commonDbUtilsService.getFirestoreCollectionGroupPath(e):this.commonDbUtilsService.getFirestorePath({feature:e,properties:i,documentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey()});if(!r)return this.loggingService.warn(`[WB] No firestore path found for ${e}`),[];try{let a=HS(this.firestore,r);i?.useCollectionGroup&&(a=_$(this.firestore,r));let s=i?.firestoreQuery??[],c=S$(a,...s);if(i?.getCount){let p=yield mse(c).catch(u=>(this.loggingService.catch(`Error in getCountFromServer for ${e}`,u),null));return p?p.data().count:0}else{let p=yield pse(c).catch(E=>(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,i){return te(this,null,function*(){if(!this.db)return this.loggingService.warn("[WB] Realtime Database not initialized"),[];let r=this.commonDbUtilsService.getDocumentPath({feature:e,properties:i,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey()});if(!r)return this.loggingService.warn(`[WB] No database path found for ${e}`),[];try{let a=on(this.db,r),s=i?.rtdbQuery??[],c=YL(a,...s),p=yield GL(c).catch(C=>(this.loggingService.catch(`Error in get for ${e}`,C),null));if(!p)return[];let u=p.val();return u?i?.skipObjectValues?u:Object.values(u??{}):[]}catch(a){return this.loggingService.catch(`Error in RTDB query for ${e}:`,a),[]}})}getData(r){return te(this,arguments,function*({feature:e,properties:i}){try{let a=this.shouldUseFirestore();if(i?.skipFirestore&&(a=!1),!e||!i)return this.loggingService.warn("[WB] Missing required parameters in getData"),{};if(a&&this.firestore){let s=this.commonDbUtilsService.getFirestorePath({feature:e,properties:i,documentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey()});if(!s)return this.loggingService.warn(`[WB] No firestore path found for ${e}`),{};try{let c=yield dse(jv(this.firestore,s)).catch(u=>(this.loggingService.catch(`Error in getDoc for ${e}`,u),null));if(!c)return this.loggingService.warn(`[WB] No document found at ${s}`),{};let p=c.data();return i?.field?p?.[i.field]??{}:p??{}}catch(c){return this.loggingService.catch(`Error fetching Firestore data for ${e}:`,c),{}}}if(this.db){let s=this.commonDbUtilsService.getDocumentPath({feature:e,properties:i,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey()});if(!s)return this.loggingService.warn(`[WB] No database path found for ${e}`),{};try{let c=yield GL(on(this.db,s)).catch(u=>(this.loggingService.catch(`Error in get for ${e}`,u),null));if(!c)return this.loggingService.warn(`[WB] No data found at ${s}`),{};let p=c.val();return i?.field?p?.[i.field]??{}:p??{}}catch(c){return this.loggingService.catch(`Error fetching RTDB data for ${e}:`,c),{}}}return this.loggingService.warn("[WB] No database connection available"),{}}catch(a){return this.loggingService.catch("Unexpected error in getData:",a),{}}})}dbListener({feature:e,properties:i}){let r=this.shouldUseFirestore();i?.skipFirestore&&(r=!1);let a=`${e}-${JSON.stringify(i)}`;return Mn([this.databaseService.getDb(),this.firestoreService.getFirestore()]).pipe(Ne(([s,c])=>s?r&&!c?(this.loggingService.warn(`[WB] Firestore requested but not available for ${e}`),!1):!0:(this.loggingService.warn(`[WB] No database found for ${e}`),!1)),ue(([s,c])=>{try{if(r&&c){if(!!!this.observablesCache[a]){this.observablesCache[a]={subject:new ve({}),count:0};let C=this.handleFirestoreListener(e,i,c).subscribe(E=>{this.observablesCache[a]?.subject?.next(E)},E=>this.observablesCache[a]?.subject?.error(E));this.firestoreSubscriptions[a]=C}return new Lt(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)return this.handleRealtimeDbListener(e,i,s);return re({})}catch(p){return this.loggingService.catch(`Error setting up listener for ${e}:`,p),re({})}}),Mg(()=>{this.loggingService.log(`[WB] Cleaning up listener for ${e} and key ${a}`)}))}handleFirestoreListener(e,i,r){let a=i?.useCollectionGroup?this.commonDbUtilsService.getFirestoreCollectionGroupPath(e):this.commonDbUtilsService.getFirestorePath({feature:e,properties:i,documentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey()}),s=`${e}-${JSON.stringify(i)}`;return a?new Lt(c=>{let p=i.isCollection?this.setupCollectionListener(r,a,e,c,i):this.setupDocumentListener(r,a,e,c,i);return()=>{c.complete(),c.unsubscribe(),p(),this.observablesCache[s]?.subject?.complete(),this.observablesCache[s]?.subject?.unsubscribe(),delete this.observablesCache[s]}}).pipe(ue(c=>this.commonDbUtilsService.mergeUsersWithData$({feature:e,data:c})),ue(c=>["allComments","allUserNotifications"].includes(e)?this.commonDbUtilsService.mergeCommentAnnotationsWithData$({data:c,feature:e}):re(c)),ue(c=>["allReactions"].includes(e)?this.commonDbUtilsService.mergeReactionAnnotationsWithData$({data:c,feature:e}):re(c)),qt(Vi)):(this.loggingService.warn(`[WB] No firestore path found for ${e} and key ${s}`),re({}))}setupCollectionListener(e,i,r,a,s){let c=`${r}-${JSON.stringify(s)}`,p=HS(e,i);if(s?.useCollectionGroup&&(p=_$(e,i)),s?.useQuery&&s?.firestoreQuery){let E=s?.firestoreQuery??[];p=S$(p,...E)}let u=!0,C=[];return y$(p,E=>{try{let A=JSON.parse(JSON.stringify(this.observablesCache[c]?.subject?.getValue()?.data??{})),B=null,G=!1;E?.docChanges()?.length?E.docChanges().forEach(K=>{["allComments","allReactions"].includes(r)&&!u&&K.type!=="removed"&&C.push(K.doc.id),this.commonDbUtilsService.isDataAlreadyProcessedInLocalCache({feature:r,change:K,cache:this.observablesCache[c]?.subject?.getValue()?.data??{}})||(G=!0,Object.assign(A,this.handleCollectionChange(K,A)),K.type==="removed"&&(B||(B={type:K.type,ids:[]}),B.ids.push(K.doc.id)))}):G=!0,G&&(["allComments","allReactions"].includes(r)&&C?.length&&(this.commonDbUtilsService.resolveAnnotations({data:C,feature:r}),C=[]),this.commonDbUtilsService.modifyAndSetData({feature:r,data:A,subscriber:a,operation:B})),u=!1}catch(A){this.handleListenerError(A,r,a)}},E=>this.handleListenerError(E,r,a))}handleCollectionChange(e,i){switch(e.type){case"added":case"modified":i[e.doc.id]=e.doc.data();break;case"removed":delete i?.[e.doc.id];break}return i}setupDocumentListener(e,i,r,a,s){let c=jv(e,i);return y$(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,i,r){this.loggingService.catch(`Firestore listener error for ${i}:`,e),r.error(e)}handleRealtimeDbListener(e,i,r){let a=this.commonDbUtilsService.getDocumentPath({feature:e,properties:i,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey()});if(!a)return this.loggingService.warn(`[WB] No database path found for ${e}`),re({});let s=on(r,a);if(i?.useQuery&&i?.rtdbQuery){let c=i?.rtdbQuery??[];s=YL(s,...c)}return Bf(s).pipe(Vn(c=>(this.loggingService.catch(`RTDB listener error for ${e}:`,c),re({}))),ce(c=>(c===null&&(c={}),c&&typeof c=="object"?Object.entries(c??{}).reduce((u,[C,E])=>(u[C]=this.commonDbUtilsService.addMetadata(E,i),u),{}):this.commonDbUtilsService.addMetadata(c,i))),ue(c=>this.commonDbUtilsService.modifyData({feature:e,data:c})),ue(c=>this.usersService.getUserById$().pipe(ce(()=>({data:this.commonDbUtilsService.mergeUsersWithData({feature:e,data:c}),operation:null})))))}};o.\u0275fac=function(i){return new(i||o)(Q(je),Q(Zv),Q(y),Q(Hse),Q(un),Q(jt),Q(lt),Q(zn),Q(bs),Q(Em))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var vi=(()=>{let o=class o{constructor(e,i,r,a,s,c,p,u){this.analyticsService=e,this.authService=i,this.configService=r,this.databaseService=a,this.docService=s,this.loggingService=c,this.commonDbService=p,this.usersService=u,this.db=bi(),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 Xe,this.documentAccessType=null,this.atHereEnabled$=new ve(!1),this.atHereLabel$=new ve("here"),this.atHereDescription$=new ve(null),this.contactListScopeForOrganizationUsers$=new ve([Pi.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.usersByOrganizationIdAndDocumentId$=new ve({}),this.usersByOrganizationIdAndFolderId$=new ve({}),this.userById$=new ve({}),this.authService.setContactService(this),this.authService.getUser$().pipe(ue(C=>this.docService.getDocumentPaths$().pipe(gn(E=>{this.documentPaths=E}),ce(()=>C)))).subscribe(C=>te(this,null,function*(){this.user=C,C&&this.documentPaths?C?.organizationId?(this.getOrganizationContactsFromDb$(),this.getFolderContactsFromDb$(),this.getDocumentContactsFromDb$(),this.getOrganizationGroupsFromDb$()):(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(Ne(C=>!!C),et(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)}),Mn([this.getInternalUserContacts$(),this.getCustomUserContacts$(),this.getCustomUserContactsConfig$()]).subscribe(([C,E,A])=>{E?A?.merge?this.userContacts$.next([...C||[],...E||[]]):this.userContacts$.next(E||[]):this.userContacts$.next(C||[])}),this.getUserContacts$().subscribe(C=>{try{C?.forEach(E=>{let A=E?.userSnippylyId||gm(this.configService.getApiKey(),E.userId);A&&this.userSnippylyIdContacts$.next(T(I({},this.userSnippylyIdContacts$.value),{[A]:E}))})}catch{}})}clearCache(){this.loggingService.log("%c[WB] Calling FUNCTION: clearCache in ContactService","color: green;");try{this.documentPaths=null,this.usersByOrganizationId$.next({}),this.usersByOrganizationIdAndFolderId$.next({}),this.usersByOrganizationIdAndDocumentId$.next({}),this.userById$.next({}),this.userOrganizationContacts$.next([]),this.userFolderContacts$.next([]),this.userDocumentContacts$.next([]),this.userOrganizationGroups$.next([]),this.userContacts$.next([]),this.userSnippylyIdContacts$.next(null),this.userGlobalContact$.next(!1),this.userGroupContact$.next(null),this.users$.next([]),this.userPersonalContacts=[],this.userGroupContacts=[],this.userGlobalContacts=[],this.users=[]}catch(e){this.loggingService.catch("Error in ContactService clearCache: ",e)}}setDocumentAccessType(e){try{this.documentAccessType=e}catch(i){this.loggingService.catch("Error in ContactService setDocumentAccessType: ",i)}}checkIfUserGlobalContact(e){return te(this,null,function*(){try{if(e?.userId&&this.documentPaths?.globalContacts){let i=yield this.commonDbService?.getData({feature:"globalContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Nt(e?.userId),skipFirestore:!0}});if(Object.keys(i??{}).length>0)return!0}if(e?.email&&this.documentPaths?.globalContacts){let i=yield this.commonDbService?.getData({feature:"globalContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Nt(e?.email),skipFirestore:!0}});if(Object.keys(i??{}).length>0)return!0}return!1}catch(i){return this.loggingService.catch("Error in ContactService isUserGlobalContact: ",i),!1}})}setLoggedInUser(e){try{e?.userId&&this.documentPaths?.logins&&(this.commonDbService.updateData({feature:"logins",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Nt(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(T(I({},e),{contacts:void 0})))}),this.setLoggedInUserPrivateContacts(e,e?.contacts))}catch(i){this.loggingService.catch("Error in ContactService setLoggedInUser: ",i)}}migrateLoggedInUserFromEmailToUserIdPath(e){return te(this,null,function*(){try{if(e?.email&&this.documentPaths?.logins){let i=yield this.commonDbService?.getData({feature:"logins",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Nt(e?.email),skipFirestore:!0}});if(Object.keys(i??{}).length>0){let r=i;if(r){if(r?.contacts){let a={};Object.keys(r?.contacts??{})?.forEach(s=>{let c=r.contacts[s];if(c?.userId){let p=Nt(c?.userId);a[p]=c}}),r.contacts=a}yield this.commonDbService.updateData({feature:"logins",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Nt(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:Nt(e?.email),skipFirestore:!0}})}}}}catch(i){this.loggingService.catch("Error in ContactService migrateLoggedInUserFromEmailToUserIdPath: ",i)}})}addGlobalContact(e){try{e?.userId&&this.documentPaths?.globalContacts&&this.commonDbService.updateData({feature:"globalContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Nt(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(e))})}catch(i){this.loggingService.catch("Error in ContactService addGlobalContact: ",i)}}updateUserInGlobalContactsIfAvailable(e){return te(this,null,function*(){try{if(e?.userId&&this.documentPaths?.globalContacts&&(yield this.checkIfUserGlobalContact(e))){let r=new Do;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:Nt(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(r))})}}catch(i){this.loggingService.catch("Error in ContactService updateUserInGlobalContactsIfAvailable: ",i)}})}moveGlobalContactUserFromEmailToUserIdPath(e){return te(this,null,function*(){try{if(e?.email&&e?.userId&&this.documentPaths?.globalContacts){let i=yield this.commonDbService?.getData({feature:"globalContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Nt(e?.email),skipFirestore:!0}});if(Object.keys(i??{}).length>0){let r=i;r&&(yield this.commonDbService.updateData({feature:"globalContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Nt(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:Nt(e?.email),skipFirestore:!0}}))}}}catch(i){this.loggingService.catch("Error in ContactService removeUserFromGlobalContactsByEmail: ",i)}})}setLoggedInUserPrivateContacts(e,i){try{if(e?.userId&&this.documentPaths?.logins){let r,a=i?.filter(c=>c?.visibility!=="group"),s=!1;this.authService.getUserOptions()&&(s=!!this.authService.getUserOptions()?.replaceContacts||!!this.authService.getUserOptions()?.replacePrivateContacts),a?.length?(r={},a?.forEach(c=>{if(c?.userId){let p=Nt(c?.userId);r[p]=c}}),s?this.commonDbService.setData({feature:"allLoginContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Nt(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:Nt(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:Nt(e?.userId),skipFirestore:!0}})}}catch(r){this.loggingService.catch("Error in ContactService setLoggedInUserPrivateContacts: ",r)}}migrateGroupContactsFromEmailToUserIdPath(e){return te(this,null,function*(){try{if(this.documentPaths?.groupContacts&&e){let i=yield this.commonDbService?.getData({feature:"groupContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",groupId:e,skipFirestore:!0}});i&&Object.keys(i??{}).forEach(r=>te(this,null,function*(){let a=i[r];a?.email&&a?.userId&&Nt(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:Nt(a?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(a))}))}))}}catch(i){this.loggingService.catch("Error in ContactService migrateGroupContacts: ",i)}})}checkToSetLoggedInUserInGroupContacts(){return te(this,null,function*(){try{this.user?.groupId&&this.user?.userId&&((yield this.checkIfUserGlobalContact(this.user))||this.docService.getDocumentIam$().pipe(et(1)).subscribe(i=>te(this,null,function*(){if(this.user?.groupId&&this.user?.userId){let r=!1,a=this.docService.getDocumentAccessType(i);if(!a||a===pi.PUBLIC)r=!0;else if(a===pi.RESTRICTED){let s=Nt(this.user?.userId);if(i?.users?.[s]&&(r=!0),this.user?.email){let c=Nt(this.user?.email);i?.users?.[c]&&(r=!0)}}if(r){let s=new $p;s.email=this.user.email,s.visibility="group",s.name=this.user.name,s.photoUrl=this.user.photoUrl,s.userId=this.user.userId,(this.authService.getUserOptions()?.replaceContacts||this.authService.getUserOptions()?.replaceGroupContacts)&&(yield this.removeGroupContacts(this.user?.groupId)),this.setLoggedInUserGroupContacts(this.user?.groupId,[s]),this.user?.contacts&&this.user?.groupId&&this.setLoggedInUserGroupContacts(this.user?.groupId,this.user?.contacts)}}})))}catch(e){this.loggingService.catch("Error in ContactService checkToSetLoggedInUserInGroupContacts: ",e)}})}setLoggedInUserGroupContacts(e,i){try{let r=i?.filter(a=>a?.visibility==="group");r?.length&&r.forEach(a=>te(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:Nt(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:Nt(a?.email),skipFirestore:!0}}))}}))}catch(r){this.loggingService.catch("Error in ContactService setLoggedInUserGroupContacts: ",r)}}removeGroupContacts(e){return te(this,null,function*(){try{if(this.documentPaths?.groupContacts&&e)return this.commonDbService.deleteData({feature:"groupContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",groupId:e,skipFirestore:!0}})}catch(i){this.loggingService.catch("Error in ContactService removeGroupContacts: ",i)}})}mergeUserContacts(){try{let e=[];this.userPersonalContacts&&e.push(...this.userPersonalContacts),this.userGroupContacts&&e.push(...this.userGroupContacts),this.userGlobalContacts&&e.push(...this.userGlobalContacts);let i={};e.forEach(r=>{r?.userId?(!r?.email||!i[r.email])&&(i[r.userId]=r):r?.email&&(!r?.userId||!i[r.userId])&&(i[r.email]=r)}),e=Object.values(i??{}),this.internalUserContacts$.next(e)}catch(e){this.loggingService.catch("Error in ContactService mergeUserContacts: ",e)}}getInternalUserContacts(){return this.internalUserContacts$.value}getInternalUserContacts$(){return this.internalUserContacts$.asObservable()}getUserContacts$(e){try{let{organizationId:i,documentId:r,veltFolderId:a}=e||{};return i&&r?Mn([this.usersByOrganizationId$,this.usersByOrganizationIdAndFolderId$,this.usersByOrganizationIdAndDocumentId$,this.userById$,this.customUserContacts$,this.customUserContactsConfig$,this.getContactListScopeForOrganizationUsers$()]).pipe(ce(([s,c,p,u,C,E,A])=>{let B={},G=!1;E&&!E?.merge&&(G=!0);let K=Ye=>A.some(ke=>Ye.includes(ke)),pe=K([Pi.ALL,Pi.ORGANIZATION])?Object.keys(s?.[i]||{}):[],Ce=a?K([Pi.ALL,Pi.FOLDER])?Object.keys(c?.[i]?.[a]||{}):[]:[],Ie=K([Pi.ALL,Pi.DOCUMENT])?Object.keys(p?.[i]?.[r]||{}):[];if([...pe,...Ce||[],...Ie].forEach(Ye=>{let ke=u?.[Ye];ke&&(B[Ye]=ke)}),C){let{merge:Ye,options:ke}=E||{},{organizationId:Se,documentId:De,folderId:Pe}=ke||{},_e=Pe?_l(Pe):void 0;(!Se||Se===i)&&(!De||De===r)&&(!_e||_e===a)&&(Ye||(B={}),C.forEach(he=>{he?.userId&&(B[he.userId]=he)}))}return Object.values(B??{})})):this.userContacts$.asObservable().pipe(ce(s=>s))}catch(i){return this.loggingService.catch("Error in ContactService getUserContacts$ metadata: ",i),re([])}}getUserContactsBySnippylyId$(){return this.userSnippylyIdContacts$.asObservable()}getAtHereLabel(){return this.atHereLabel$.asObservable()}getAtHereDescription(){return this.atHereDescription$.asObservable()}getUserContactsFromDb$(){this.getUserContactSubscription||(this.getUserContactSubscription=this.authService.getUser$().pipe(Ne(e=>!!e),ue(e=>this.docService.getDocumentPaths$().pipe(Ne(i=>!!i),gn(i=>{this.documentPaths=i}),ce(()=>e))),ue(e=>{if(this.userGroupContacts=[],this.userPersonalContacts=[],!e)return re();if(!this.documentPaths)return re();let i=[];return i.push(this.commonDbService.dbListener({feature:"allGlobalContacts",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,skipFirestore:!0}}).pipe(ce(r=>r?.data),gn(r=>{r?(this.userGlobalContacts=Object.values(r??{}),this.userGlobalContacts?.find(a=>a.userId===this.user?.userId)?this.userGlobalContact$.next(!0):this.userGlobalContact$.next(!1)):(this.userGlobalContacts=[],this.userGlobalContact$.next(!1))}))),i.push(this.commonDbService.dbListener({feature:"groupContacts",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,skipFirestore:!0,groupId:e?.groupId}}).pipe(ce(r=>r?.data),gn(r=>{r?(this.userGroupContacts=Object.values(r??{}),this.userGroupContacts?.find(a=>a?.userId===this.user?.userId)?this.userGroupContact$.next(!0):this.userGroupContact$.next(!1)):(this.userGroupContacts=[],this.userGroupContact$.next(!1))}))),i.push(this.commonDbService.dbListener({feature:"allLoginContacts",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,skipFirestore:!0,userId:Nt(e?.userId)}}).pipe(ce(r=>r?.data),gn(r=>{r?this.userPersonalContacts=Object.values(r??{}):this.userPersonalContacts=[]}))),oo(...i).pipe(ro(this.authService.getUser$().pipe(Ne(r=>!r))))})).subscribe(()=>{this.mergeUserContacts()},e=>{this.loggingService.catch("Error in ContactService getUserContacts$ subscription: ",e)}))}addUserContact(e){try{this.user?.organizationId||this.user?.groupId&&(e.visibility="group",this.setLoggedInUserGroupContacts(this.user?.groupId,[e]))}catch(i){this.loggingService.catch("Error in ContactService addUserContact: ",i)}}isUserGlobalContact$(){return this.userGlobalContact$.asObservable()}isUserGlobalContact(){return this.userGlobalContact$.value}isUserGroupContact$(){return this.userGroupContact$.asObservable()}isUserGroupContact(){return this.userGroupContact$.value}getLoggedInUsers$(){return this.getLoggedInUsersSubscription||(this.getLoggedInUsersSubscription=this.authService.getUser$().pipe(ue(e=>e?this.documentPaths?e?.userId&&this.documentPaths?.logins?this.commonDbService.dbListener({feature:"allLogins",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,skipFirestore:!0}}).pipe(ce(i=>i?.data),gn(i=>{i?this.users=Object.values(i??{}):this.users=[]})):(this.users=[],re()):re():re())).subscribe(()=>{this.users$.next(this.users)},e=>{this.loggingService.catch("Error in ContactService getLoggedInUsers$ subscription: ",e)})),this.users$.asObservable()}getUsersMap$(){return this.authService.getUser$().pipe(ue(e=>e?.organizationId?this.userById$.pipe(ce(i=>{let r={};return Object.values(i||{}).forEach(a=>{a?.userSnippylyId&&(r[a?.userSnippylyId]=a)}),r})):this.users$.pipe(ce(i=>{let r={};return i.forEach(a=>{r[a.userSnippylyId]=a}),r}))))}getUserByEmail$(e){return this.users$.pipe(ce(i=>i.find(r=>r.email===e)))}getUserByEmail(e){return this.users?.find(i=>i.email===e)}getContactByEmail(e){return this.getInternalUserContacts().find(i=>i.email===e)}getUserByUserId$(e){return this.users$.pipe(ce(i=>i.find(r=>r.userId===e)))}getUserGroupContacts(){return this.userGroupContacts}getOrganizationContactsFromDb$(){try{this.getOrganizationContactsSubscription||(this.getOrganizationContactsSubscription=this.authService.getUser$().pipe(ue(e=>e?.organizationId?re(e).pipe(ue(i=>this.docService.getOrganizationConfig$().pipe(Ne(r=>!!r),ce(()=>i))),ue(i=>{let r=this.docService.getOrganizationConfig()?.organizationId;return this.setUserOrganizationContacts([],r),i?r?this.commonDbService.dbListener({feature:"allOrganizationUsers",properties:{organizationId:r,isCollection:!0}}).pipe(ce(a=>a?.data),ce(a=>{if(a){typeof a=="object"&&(a?.undefined&&delete a.undefined,a?.null&&delete a.null);let s=Object.values(a??{});this.setUserOrganizationContacts(s,r)}else this.setUserOrganizationContacts([],r)})):re():re()}),ue(()=>this.getContactListScopeForOrganizationUsers$())):(this.setUserOrganizationContacts([]),re()))).subscribe(()=>{this.mergeOrganizationAndDocumentContacts()},e=>{this.loggingService.catch("Error in ContactService getOrganizationContactsFromDb$ subscription: ",e)}))}catch{}}getFolderContactsFromDb$(){try{this.getFolderContactsSubscription||(this.getFolderContactsSubscription=this.authService.getUser$().pipe(ue(e=>e?re(e).pipe(ue(i=>this.docService.getOrganizationConfig$().pipe(Ne(r=>!!r),ce(()=>i))),ue(i=>this.docService.getFolderConfig$().pipe(ce(()=>i))),ue(i=>{let r=this.docService.getOrganizationConfig()?.organizationId;if(this.setUserFolderContacts([]),!i)return re();if(!this.commonDbService.shouldUseFirestore())return re();let a=this.docService.getFolderConfig();if(!a?.veltFolderId)return re();let s=re([]);return s=this.commonDbService.dbListener({feature:"allFolderUsers",properties:{organizationId:r,folderId:a?.veltFolderId,isCollection:!0}}).pipe(ce(c=>c?.data)),s.pipe(ce(c=>{if(c){typeof c=="object"&&(c?.undefined&&delete c.undefined,c?.null&&delete c.null);let p=Object.values(c??{});this.setUserFolderContacts(p)}else this.setUserFolderContacts([])}))}),ue(()=>this.getContactListScopeForOrganizationUsers$())):(this.setUserFolderContacts([]),re()))).subscribe(()=>{this.mergeOrganizationAndDocumentContacts()},e=>{this.loggingService.catch("Error in ContactService getFolderContactsFromDb$ subscription: ",e)}))}catch{}}getDocumentContactsFromDb$(){try{this.getDocumentContactsSubscription||(this.getDocumentContactsSubscription=this.authService.getUser$().pipe(ue(e=>e?re(e).pipe(ue(i=>this.docService.getDocumentPaths$().pipe(Ne(r=>!!r),gn(r=>{this.documentPaths=r}),ce(()=>i))),ue(i=>(this.setUserDocumentContacts([]),i?this.documentPaths?this.docService.getDocumentIds$().pipe(ue(r=>{let a=r?.length>0?r.map(u=>u.documentId):[this.documentPaths?.documentId??""];if(a.some(u=>!u)||!this.documentPaths)return re();let s=this.docService.getFolderConfig(),c=re([]),p={useCollectionGroup:!0,isCollection:!0,useQuery:!0};if(this.commonDbService.shouldUseFirestore()||(p.documentId=a?.length?a[0]:void 0,p.organizationId=this.documentPaths?.organizationId),s?.veltFolderId&&s?.allDocuments)c=this.commonDbService.dbListener({feature:"allDocumentUsers",properties:T(I({},p),{firestoreQuery:[Ui(dt("metadata.apiKey","==",this.configService?.getApiKey()),dt("metadata.veltFolderId","==",s?.veltFolderId),dt("metadata.organizationId","==",this.documentPaths?.organizationId))]})}).pipe(ce(u=>u?.data));else{let u=[];for(let C=0;C<a.length;C+=U.LISTENER_BATCH_SIZE)u.push(a.slice(C,C+U.LISTENER_BATCH_SIZE));c=Mn(u.map(C=>this.commonDbService.dbListener({feature:"allDocumentUsers",properties:T(I({},p),{firestoreQuery:[Ui(dt("metadata.apiKey","==",this.configService?.getApiKey()),dt("metadata.documentId","in",C),dt("metadata.organizationId","==",this.documentPaths?.organizationId),...s?.veltFolderId?[dt("metadata.veltFolderId","==",s?.veltFolderId)]:[])]})}).pipe(zr()))).pipe(ce(C=>ga(C)?.data))}return c.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([])}))})):re():re())),ue(()=>this.getContactListScopeForOrganizationUsers$())):(this.setUserDocumentContacts([]),re()))).subscribe(()=>{this.mergeOrganizationAndDocumentContacts()},e=>{this.loggingService.catch("Error in ContactService getDocumentContactsFromDb$ subscription: ",e)}))}catch{}}setUserOrganizationContacts(e,i){try{let r=e.find(s=>s.user.userId===this.user?.userId);r?this.currentOrganizationUserIAM$.next(r):this.currentOrganizationUserIAM$.next(null);let a=e.map(s=>s.user);if(this.userOrganizationContacts$.next(a),i){let s={};s[i]={},e.forEach(c=>{s[i][c.user.userId]=c,this.userById$.next(T(I({},this.userById$.value),{[c.user.userId]:c.user}))}),this.usersByOrganizationId$.next(T(I({},this.usersByOrganizationId$.value),{[i]:s[i]}))}else this.usersByOrganizationId$.next({})}catch(r){this.loggingService.catch("Error in ContactService setUserOrganizationContacts: ",r)}}getUserOrganizationContacts$(){return this.getContactListScopeForOrganizationUsers$().pipe(ue(()=>this.checkContactListScopeForOrganizationUsers([Pi.ALL,Pi.ORGANIZATION])?this.userOrganizationContacts$.asObservable():re([])))}getUserOrganizationContacts(){return this.checkContactListScopeForOrganizationUsers([Pi.ALL,Pi.ORGANIZATION])?this.userOrganizationContacts$.value:[]}setUserFolderContacts(e){try{this.userFolderContacts$.next(e?.map(r=>r?.user));let i={};e?.forEach(r=>{let{organizationId:a,veltFolderId:s}=r?.metadata||{};a&&s&&(i[a]||(i[a]={}),i[a][s]||(i[a][s]={}),i[a][s][r.user.userId]=r,this.userById$.next(T(I({},this.userById$.value),{[r.user.userId]:r.user})))}),this.usersByOrganizationIdAndFolderId$.next(i)}catch(i){this.loggingService.catch("Error in ContactService updateUserFolderContacts: ",i)}}getUserFolderContacts$(){return this.getContactListScopeForOrganizationUsers$().pipe(ue(()=>this.checkContactListScopeForOrganizationUsers([Pi.ALL,Pi.FOLDER])?this.userFolderContacts$.asObservable():re([])))}getUserFolderContacts(){return this.checkContactListScopeForOrganizationUsers([Pi.ALL,Pi.FOLDER])?this.userFolderContacts$.value:[]}setUserDocumentContacts(e){try{this.userDocumentContacts$.next(e?.map(r=>r?.user));let i={};e?.forEach(r=>{let{organizationId:a,documentId:s}=r?.metadata||{};a&&s&&(i[a]||(i[a]={}),i[a][s]||(i[a][s]={}),i[a][s][r.user.userId]=r,this.userById$.next(T(I({},this.userById$.value),{[r.user.userId]:r.user})))}),this.usersByOrganizationIdAndDocumentId$.next(i)}catch(i){this.loggingService.catch("Error in ContactService updateUserDocumentContacts: ",i)}}getUserDocumentContacts$(){return this.getContactListScopeForOrganizationUsers$().pipe(ue(()=>this.checkContactListScopeForOrganizationUsers([Pi.ALL,Pi.DOCUMENT])?this.userDocumentContacts$.asObservable():re([])))}getUserDocumentContacts(){return this.checkContactListScopeForOrganizationUsers([Pi.ALL,Pi.DOCUMENT])?this.userDocumentContacts$.value:[]}getCurrentOrganizationUserIAM$(){return this.currentOrganizationUserIAM$.asObservable()}getCurrentOrganizationUserIAM(){return this.currentOrganizationUserIAM$.value}mergeOrganizationAndDocumentContacts(){try{let e=[];this.getContactListScopeForOrganizationUsers().includes(Pi.ALL)?e=[...this.getUserOrganizationContacts(),...this.getUserFolderContacts(),...this.getUserDocumentContacts()]:this.getContactListScopeForOrganizationUsers().includes(Pi.ORGANIZATION)?e=[...this.getUserOrganizationContacts()]:this.getContactListScopeForOrganizationUsers().includes(Pi.FOLDER)?e=[...this.getUserFolderContacts()]:this.getContactListScopeForOrganizationUsers().includes(Pi.DOCUMENT)&&(e=[...this.getUserDocumentContacts()]);let i=[...new Map(e.filter(r=>r?.userId).map(r=>[r.userId,r])).values()];this.internalUserContacts$.next(i)}catch(e){this.loggingService.catch("Error in ContactService mergeOrganizationAndDocumentContacts: ",e)}}getOrganizationGroupsFromDb$(){try{this.getOrganizationGroupsSubscription||(this.getOrganizationGroupsSubscription=this.authService.getUser$().pipe(ue(e=>e?.organizationId?re(e).pipe(ue(i=>this.docService.getOrganizationConfig$().pipe(Ne(r=>!!r),ce(()=>i))),ue(i=>{if(this.setUserOrganizationGroups([]),!i)return re();let r=this.docService.getOrganizationConfig()?.organizationId;return r?this.commonDbService.dbListener({feature:"allOrganizationGroups",properties:{organizationId:r,isCollection:!0}}).pipe(ce(a=>a?.data),ce(a=>{a?(typeof a=="object"&&(a?.undefined&&delete a.undefined,a?.null&&delete a.null),this.setUserOrganizationGroups(Object.values(a??{}))):this.setUserOrganizationGroups([])})):re()})):(this.setUserOrganizationGroups([]),re()))).subscribe(()=>{},e=>{this.loggingService.catch("Error in ContactService getOrganizationGroupsFromDb$ subscription: ",e)}))}catch{}}setUserOrganizationGroups(e){try{this.userOrganizationGroups$.next(e)}catch(i){this.loggingService.catch("Error in ContactService setUserOrganizationGroups: ",i)}}onContactSelected(e){try{if(e?.userId){let i=!!this.getUserDocumentContacts().find(a=>a.userId===e.userId),r=!!this.getUserOrganizationContacts().find(a=>a.userId===e.userId);switch(this.documentAccessType){case pi.RESTRICTED:if(!i){let a={contact:e,isOrganizationContact:r,isDocumentContact:i,documentAccessType:this.documentAccessType};this.onContactSelectedSubject$.next(a)}break}}else{let i={contact:e,isOrganizationContact:!1,isDocumentContact:!1,documentAccessType:this.documentAccessType};this.onContactSelectedSubject$.next(i)}}catch(i){this.loggingService.catch("Error in ContactService onContactSelected: ",i)}}onContactSelected$(){return this.onContactSelectedSubject$.asObservable()}getOrganizationGroups$(){return this.getContactListScopeForOrganizationUsers$().pipe(ue(()=>this.checkContactListScopeForOrganizationUsers([Pi.ALL,Pi.ORGANIZATION_USER_GROUP])?this.userOrganizationGroups$.asObservable():re([])))}enableAtHere(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{atHereEnabled:!0}}),this.atHereEnabled$.value===!0)return;this.atHereEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in ContactService enableAtHere: ",e)}}setAtHereLabel(e){try{this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{atHereLabel:e}}),e&&this.atHereLabel$.next(e)}catch(i){this.loggingService.catch("Error in ContactService setAtHereLabel: ",i)}}setAtHereDescription(e){try{this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{atHereDescription:e}}),e&&this.atHereDescription$.next(e)}catch(i){this.loggingService.catch("Error in ContactService setAtHereDescription: ",i)}}disableAtHere(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{atHereEnabled:!1}}),this.atHereEnabled$.value===!1)return;this.atHereEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in ContactService disableAtHere: ",e)}}getAtHereEnabled$(){return this.getContactListScopeForOrganizationUsers$().pipe(ue(()=>this.checkContactListScopeForOrganizationUsers([Pi.ALL,Pi.DOCUMENT])?this.atHereEnabled$.asObservable():re(!1)))}getAtHereEnabled(){return this.checkContactListScopeForOrganizationUsers([Pi.ALL,Pi.DOCUMENT])?this.atHereEnabled$.value:!1}updateContactListScopeForOrganizationUsers(e){try{this.contactListScopeForOrganizationUsers$.next(e)}catch(i){this.loggingService.catch("Error in ContactService updateContactListScopeForOrganizationUsers: ",i)}}getContactListScopeForOrganizationUsers$(){return this.contactListScopeForOrganizationUsers$.asObservable()}getContactListScopeForOrganizationUsers(){return this.contactListScopeForOrganizationUsers$.value}checkContactListScopeForOrganizationUsers(e){return this.getContactListScopeForOrganizationUsers().some(i=>e.includes(i))}updateContactList(e,i){return te(this,null,function*(){try{if(this.analyticsService.trackEvent(X.Events.Contact.UPDATE_CONTACT_LIST_TRIGGERED,{contactsCount:e?.length,config:i}),this.usersService?.userDataProviderAvailable()){let r=e.map(s=>s?.userId).filter(s=>s);yield this.usersService.resolveUsers(r);let a=r.map(s=>this.usersService.getUserById(s)).filter(s=>!!s);this.customUserContacts$.next(a)}else this.customUserContacts$.next(e);this.customUserContactsConfig$.next(i)}catch(r){this.loggingService.catch("Error in CommentService updateContactList: ",r)}})}convert(e){try{if(e?.options){let{documentId:i,organizationId:r}=this.docService.getServerId(e?.options);e.options=T(I({},e?.options),{documentId:i,organizationId:r})}return this}catch(i){return this.loggingService.catch("Error in ContactService convert: ",i),this}}getContactList$(){try{return this.authService.getUser$().pipe(ue(e=>e?Mn([this.userOrganizationContacts$.asObservable(),this.userFolderContacts$.asObservable(),this.userDocumentContacts$.asObservable(),this.userOrganizationGroups$.asObservable(),this.customUserContacts$.asObservable()]).pipe(ce(([i,r,a,s,c])=>{let p={};p.organizationUsers=i?.map(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}),qt(Vi)):re(null)),Vn(e=>(this.loggingService.catch("Error in ContactService getContactList$: ",e),re(null))))}catch(e){return this.loggingService.catch("Error in ContactService getContactList$: ",e),re(null)}}convertToClientUserGroup(e,i){try{let r={groupId:e?.metadata?.clientGroupId,groupName:e?.metadata?.groupName,users:[]},a={};return i?.forEach(s=>{if(s?.userId){let c=Nt(s.userId);a[c]=s}}),Object.keys(e?.users??{}).forEach(s=>{a[s]&&r.users?.push(a[s])}),r}catch(r){return this.loggingService.catch("Error in ContactService convertToClientUserGroup: ",r),null}}convertToClientUser(e){try{return e&&(e=JSON.parse(JSON.stringify(e)),e?.clientGroupId&&(e.groupId=e.clientGroupId,delete e.clientGroupId),e?.clientOrganizationId&&(e.organizationId=e.clientOrganizationId,delete e.clientOrganizationId),e?.userSnippylyId&&delete e.userSnippylyId),e}catch(i){return this.loggingService.catch("Error in ContactService convertToClientUser: ",i),e}}getCustomUserContacts(){return this.customUserContacts$.value}getCustomUserContacts$(){return this.customUserContacts$.asObservable()}getCustomUserContactsConfig(){return this.customUserContactsConfig$.value}getCustomUserContactsConfig$(){return this.customUserContactsConfig$.asObservable()}};o.\u0275fac=function(i){return new(i||o)(Q(Ke),Q(je),Q(jt),Q(un),Q(lt),Q(y),Q(En),Q(zn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var zse=n=>{try{return n.name.split(".").slice(0,-1).join(".")}catch(o){mt.catch("Error in File utils getFileName: ",o);return}},F$=n=>{try{return/(?:\.([^.]+))?$/.exec(n?.name)[1]}catch(o){mt.catch("Error in File utils getFileExtension: ",o);return}},Gse=(n,o)=>{try{let t=n.slice(0,-1,n.type);return new File([t],o+"."+F$(n),{type:n.type})}catch(t){mt.catch("Error in File utils updateFile: ",t);return}},Wse=n=>new Promise((o,t)=>{let e=new FileReader;e.readAsDataURL(n),e.onload=()=>{o(e.result)},e.onerror=i=>{t(i)}}),qse={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 Wp=(()=>{let o=class o{constructor(e,i,r,a){this.authService=e,this.configService=i,this.loggingService=r,this.attachmentResolverService=a,this.storage=Ly();try{this.configService.getApiKey$().subscribe(s=>{this.apiKey=s}),this.authService.getFirebaseConfig$().subscribe(s=>{s&&s.firebaseOptions?.storageBucket&&(this.storage=Ly(void 0,s?.firebaseOptions?.storageBucket))},s=>{this.loggingService.catch("Error in StorageService constructor: ",s)})}catch(s){this.loggingService.catch("Error in StorageService constructor:",s)}}createAttachment({path:e,file:i}){try{let r=new Hv;r.name=i.name;let a=Gse(i,`${r.attachmentId}_${zse(i)}`),s=`${this.apiKey}/${e}/${a?.name}`;return r.bucketPath=s,r.size=i.size,r.type=F$(i),r?.type&&(r.mimeType=qse[r?.type]),r}catch(r){return this.loggingService.catch("Error in StorageService createAttachment: ",r),null}}uploadAttachmentToStorage({attachment:e,file:i,resolve:r,reject:a}){try{let s=By(this.storage,e.bucketPath),c=SB(s,i,{cacheControl:"public,max-age=3600"});c.on("state_changed",p=>{let u=p.bytesTransferred/p.totalBytes*100},p=>{a(p)},()=>{yB(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 te(this,arguments,function*({file:e,attachment:i,metadata:r,resolve:a,reject:s}){try{r.attachmentId=i.attachmentId;let p={attachmentId:i.attachmentId,name:i.name,file:e,metadata:r,mimeType:i.mimeType},u=yield this.attachmentResolverService.saveAttachment({attachment:p,eventType:Wa.ATTACHMENT_ADD});u&&u.data?.url?(i.url=u.data?.url,a(i)):s(new Error("Failed to upload attachment to resolver"))}catch(p){this.loggingService.catch("Error in StorageService uploadToResolver: ",p),s(p)}})}uploadFile({path:e,file:i,useAttachmentResolver:r,metadata:a}){return new Promise((s,c)=>{try{if(!this.apiKey)throw new Error("API key not configured");let p=this.createAttachment({path:e,file:i});if(!p)throw new Error("Attachment not created");r?this.uploadToResolver({file:i,attachment:p,metadata:a,resolve:s,reject:c}):this.uploadAttachmentToStorage({attachment:p,file:i,resolve:s,reject:c})}catch(p){this.loggingService.catch("Error in StorageService uploadFile:",p),c(p)}})}uploadChunk(e,i,r){return new Promise((a,s)=>{try{if(this.apiKey){let c=`${this.apiKey}/${e}/${i.name}`,p=By(this.storage,c),u=SB(p,i,{cacheControl:"public,max-age=3600"});u.on("state_changed",C=>{let E=C.bytesTransferred/C.totalBytes*100},C=>{s(C)},()=>{yB(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 i=new XMLHttpRequest;i.responseType="blob",i.onload=()=>{let r=i.response,a=document.createElement("a"),s=window.URL.createObjectURL(r);a.setAttribute("type","hidden"),a.setAttribute(U.ATTRIBUTES.VELT_DOWNLOAD_BUTTON,"true"),a.classList.add("snippyly-overlay-panel"),a.href=s,e?.name&&(a.download=e?.name),document.body.appendChild(a);let c=new MouseEvent("click",{view:window,bubbles:!0,cancelable:!1});a.dispatchEvent(c),window.URL.revokeObjectURL(s),a.remove()},i.onerror=()=>{window.open(e.url,"_blank")},i.open("GET",e.url),i.send()}}catch(i){this.loggingService.catch("Error in StorageService downloadAttachment: ",i)}}deleteAttachment({attachment:e,metadata:i,useAttachmentResolver:r}){return new Promise((a,s)=>{if(r)this.attachmentResolverService.deleteAttachment({attachmentId:e.attachmentId,metadata:i}).then(()=>{a(null)}).catch(c=>{s(c)});else{let c=By(this.storage,e.bucketPath);_B(c).then(()=>{a(null)}).catch(p=>{a(null)})}})}deleteFileFromPath(e){return new Promise((i,r)=>{let a=By(this.storage,e);_B(a).then(()=>{i(null)}).catch(s=>{r(s)})})}};o.\u0275fac=function(i){return new(i||o)(Q(je),Q(jt),Q(y),Q(Gp))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var hn=(()=>{let o=class o{constructor(e,i,r,a,s,c,p,u){this.analyticsService=e,this.authService=i,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(Ne(C=>!!C),et(1)).subscribe(C=>{C&&(this.db=C,this.getUser(),this.getDocumentPaths())},C=>{this.loggingService.catch("Error in CommentService getDb subscription: ",C)}),this.getRole$().pipe(et(1)).subscribe(C=>{this.authService?.getUser()&&!C&&this.analyticsService.trackEvent(X.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(Ne(e=>!!e)).subscribe(e=>{this.user=e,this.user?this.getDocumentIam():(this.getDocumentIamSubscription?.unsubscribe(),this.getOrganizationIamSubscription?.unsubscribe(),this.getWorkspaceIamSubscription?.unsubscribe())},e=>{this.loggingService.catch("Error in IamService getUser$ subscription: ",e)})}catch(e){this.loggingService.catch("Error in IamService getUser: ",e)}}getDocumentPaths(){try{this.docService.getDocumentPaths$().pipe(Ne(e=>!!e)).subscribe(e=>{this.documentPaths=e,this.getDocumentIam(),this.getWorkspaceIam()},e=>{this.loggingService.catch("Error in IamService getDocumentPaths$ subscription: ",e)})}catch(e){this.loggingService.catch("Error in IamService getDocumentPaths: ",e)}}getDocumentIam(){try{this.getDocumentIamSubscription&&(this.getDocumentIamSubscription.unsubscribe(),this.getDocumentIamSubscription=null),this.user?this.getDocumentIamSubscription=this.docService.getDocumentIam$().subscribe(e=>{let i=e||new xM;this.documentIAM$.next(i)},e=>{this.loggingService.catch("Error in IamService getDocumentIam$ subscription: ",e)}):this.documentIAM$.next(null)}catch(e){this.loggingService.catch("Error in IamService getDocumentIam: ",e)}}getWorkspaceIam(){try{this.getWorkspaceIamSubscription||(this.getWorkspaceIamSubscription=this.commonDbService.dbListener({feature:"workspaceIam",properties:{skipFirestore:!0}}).pipe(Vn(e=>re(null))).subscribe(e=>{this.workspaceIAM$.next(e?.data),this.roles$.next(e?.data?.roles||[])}))}catch(e){this.loggingService.catch("Error in IamService getWorkspaceIam: ",e)}}isUserAllowed$(){return this.getRole$().pipe(ce(e=>!!e),qt())}getDocumentIAM$(){return this.documentIAM$.asObservable()}getRoles$(){return this.roles$.asObservable().pipe(ce(e=>e?.length?e:U.WorkspaceRoles))}getFeaturesAccessLevel$(){return this.documentIAM$.asObservable().pipe(ce(e=>e?.features),ue(e=>this.getRole$().pipe(ce(i=>(i===po.ADMIN&&(e=e&&JSON.parse(JSON.stringify(e||{})),e?.all?.disabled&&(e.all.disabled=!1)),e)))))}hasRole(e){try{return e===this.getRole()}catch(i){return this.loggingService.catch("Error in IamService hasRole: ",i),!1}}hasRoleAny(e=[]){try{return e?.includes(this.getRole()||"")}catch(i){return this.loggingService.catch("Error in IamService hasRoleAny: ",i),!1}}hasRole$(e){try{return this.authService.getUser$().pipe(ue(()=>this.documentIAM$.pipe(Ne(i=>!!i),ue(()=>this.workspaceIAM$.pipe(ce(()=>e===this.getRole()))))))}catch(i){return this.loggingService.catch("Error in IamService hasRole$: ",i),re(!1)}}getRole$(){try{return this.authService.getUser$().pipe(ue(()=>this.configService.getSF$()),ue(()=>this.configService.getSF()?this.contactService.isUserGlobalContact$():re(null)),ue(()=>this.documentIAM$.pipe(Ne(e=>!!e))),ue(()=>this.workspaceIAM$),ce(()=>this.getRole()))}catch(e){return this.loggingService.catch("Error in IamService getRole$: ",e),re(null)}}getRole(){try{let e=this.configService.getSF();if(e&&this.contactService.isUserGlobalContact())return po.ADMIN;if(!e&&this.user?.isAdmin)return po.ADMIN;let i=null,r;if(this.user)switch((this.documentIAM$.value?this.documentIAM$.value?.features?.all?.restricted:!1)?pi.RESTRICTED:this.documentIAM$.value?this.documentIAM$.value?.documentAccessType||pi.PUBLIC:null){case pi.PUBLIC:r=this.getUserFromDocumentIAM(this.user?.email,this.user?.userId),r||(r=this.getUserFromWorkspaceIAM(this.user?.email,this.user?.userId)),i=r?.role?.name||po.COMMENTER;break;case pi.RESTRICTED:r=this.getUserFromDocumentIAM(this.user?.email,this.user?.userId),r||(r=this.getUserFromWorkspaceIAM(this.user?.email,this.user?.userId)),i=r?.role?.name||null;break;default:break}return i}catch(e){this.loggingService.catch("Error in IamService getRole: ",e)}return null}isUserAdmin$(){return this.getRole$().pipe(ce(e=>e===po.ADMIN),qt())}isUserAdmin(){try{return this.getRole()===po.ADMIN}catch(e){return this.loggingService.catch("Error in IamService isUserAdmin: ",e),!1}}getUserFromDocumentIAM(e,i){try{if(e||i){let r;return e&&(r=this.documentIAM$.value?.users?.[Nt(e)]),!r&&i&&(r=this.documentIAM$.value?.users?.[Nt(i)]),r}else return}catch(r){this.loggingService.catch("Error in IamService getUserFromDocumentIAM: ",r)}}getUserFromWorkspaceIAM(e,i){try{if(e||i){let r;return e&&(r=this.workspaceIAM$.value?.users?.[Nt(e)]),!r&&i&&(r=this.workspaceIAM$.value?.users?.[Nt(i)]),r}else return}catch(r){this.loggingService.catch("Error in IamService getUserFromWorkspaceIAM: ",r)}}};o.\u0275fac=function(i){return new(i||o)(Q(Ke),Q(je),Q(vi),Q(un),Q(lt),Q(jt),Q(y),Q(En))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var jn=(()=>{let o=class o{constructor(e,i,r,a,s,c,p,u,C,E,A,B,G,K,pe,Ce){this.afAuth=e,this.analyticsService=i,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=A,this.iamService=B,this.loggingService=G,this.notificationUtilsService=K,this.usersService=pe,this.functions=Ce,this.db=bi(),this.notificationsDb=bi(void 0,Xn.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}});try{this.subscribeNotificationsData().subscribe(),this.commentUtilsService.setNotificationService(this),this.databaseService.getDb().pipe(Ne(Ie=>!!Ie),et(1)).subscribe(Ie=>{Ie&&(this.db=Ie,this.getDocumentIds(),this.subscribeGetNotificationsForYou())},Ie=>{this.loggingService.catch("Error in NotificationService getDb subscription: ",Ie)}),this.authService.getUser$().subscribe(Ie=>{Ie?(this.subscribeGetNotificationsForYou(),this.getDocumentIds()):(Object.keys(this.notificationsByDocumentIdSubscription).forEach($e=>{this.notificationsByDocumentIdSubscription[$e]?.unsubscribe()}),this.notificationForYouSubscription?.unsubscribe(),this.documentIdsSubscription?.unsubscribe(),this.resetCacheData())}),this.docService.getLocationMetadata$().subscribe(Ie=>{if(Ie){let $e=this.notificationsByDocumentIdMap$.getValue()?JSON.parse(JSON.stringify(this.notificationsByDocumentIdMap$.getValue())):null;Object.keys(Ie||{}).forEach(Ye=>{let ke=$e?.[Ye]?.notifications;ke?.length&&ke.forEach(Se=>{this.notificationUtilsService.mergeLocationWithNotification({notification:Se},Ie)?.notification})}),this.notificationsByDocumentIdMap$.next($e)}})}catch(Ie){this.loggingService.catch("Error in NotificationService constructor: ",Ie)}}resetCacheData(){try{this.loggingService.log("%c[WB] Calling NotificationService FUNCTION: resetCacheData","color: green;"),this.notificationsByDocumentIdMap$.next(null),this.notificationsForYou$.next(null)}catch(e){this.loggingService.catch("Error in NotificationService resetCacheData: ",e)}}subscribeGetNotificationsForYou(){try{this.notificationForYouSubscription&&this.notificationForYouSubscription.unsubscribe(),this.notificationForYouSubscription=this.getNotificationsForYou().subscribe(()=>{},e=>{this.loggingService.catch("Error in NotificationService getNotificationsForYou subscription: ",e)})}catch(e){this.loggingService.catch("Error in NotificationService subscriveGetNotificationsForYou: ",e)}}setCommentService(e){try{this.commentService=e}catch(i){this.loggingService.catch("Error in NotificationService setCommentService: ",i)}}getDocumentIds(){try{this.documentIdsSubscription&&this.documentIdsSubscription.unsubscribe(),this.documentIdsSubscription=this.getDocumentIdsByLastNotificationTimestamp().pipe(Ai(),ce(([e,i])=>{let r=e?.map(u=>u.documentId),a=i?.map(u=>u.documentId),s=r?.filter(u=>!a?.includes(u)),c=a?.map(u=>({documentId:u,timestamp:i?.find(C=>C.documentId===u)?.timestamp})).filter(u=>!r?.includes(u.documentId)),p=a?.map(u=>{let C=i?.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)}),i&&!i?.length&&!this.notificationsByDocumentIdMap$.getValue()&&this.notificationsByDocumentIdMap$.next({})})).subscribe(()=>{},e=>{this.loggingService.catch("Error in NotificationService getDocumentIds subscription: ",e)})}catch(e){this.loggingService.catch("Error in NotificationService getDocumentIds: ",e)}}getDocumentIdsByLastNotificationTimestamp(e=15){try{return this.authService.getUser$().pipe(ue(i=>this.docService.getOrganizationConfig$().pipe(ce(r=>{let a=null,s=this.configService.getApiKey(),c=r?.organizationId||i?.organizationId;return s&&c&&(a=new Im({apiKey:s,organizationId:c})),{user:i,documentPaths:a}}))),ue(i=>{let{user:r,documentPaths:a}=i;if(r&&a?.organizationNotificationsLastNotificationTimestamp){let s=new Date,c=this.maxNotificationDays$.getValue()>0?this.maxNotificationDays$.getValue():15;s.setDate(s.getDate()-c);let p=s.getTime();return this.commonDbService.dbListener({feature:"allLastNotificationTimestamp",properties:{organizationId:a?.organizationId,isCollection:!0,useQuery:!0,firestoreQuery:[Ui(dt("timestamp",">=",p)),Ya("timestamp","desc"),$v(e)]}}).pipe(ce(u=>u?.data),ce(u=>{let C=[];return Object.keys(u||{}).forEach(E=>{let A=this.commonDbService.shouldUseFirestore()?u[E]?.timestamp??0:u[E],B=this.commonDbService.shouldUseFirestore()?u[E]?.deletedNotification??!1:!1;if(B&&B.id&&B?.timestamp===A){let G=B.id,K=u[E]?.metadata?.documentId,pe=JSON.parse(JSON.stringify(this.notificationsByDocumentIdMap$.getValue()??{})),Ce=pe?.[K]??{documentMetadata:null,notifications:[]},Ie=Ce.notifications??[],$e=Ie?.findIndex(Ye=>Ye.id===G);$e!==-1&&(Ie.splice($e,1),this.notificationsByDocumentIdMap$.next(T(I({},pe),{[K]:T(I({},Ce),{notifications:Ie})})))}C.push({documentId:E,timestamp:A})}),C}),Vn(u=>(this.loggingService.catch("Error in NotificationService getDocumentIdsByLastNotificationTimestamp: ",u),re([]))))}return re(null)}))}catch(i){return this.loggingService.catch("Error in NotificationService getDocumentIdsByLastNotificationTimestamp: ",i),re([])}}fetchNotificationsForDocumentIds(e,i=15){return te(this,null,function*(){try{if(e?.length){let r=_r(this.functions,Sr({url:Xn.cloudFunction.getNotificationsForDocuments,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:12e5}),a=this.docService.getOrganizationConfig()?.organizationId??"",s=this.getStartAtTimestamp(),c={};e.forEach(B=>{if(B?.documentId){let G=this.getAllowedDocumentMetadataByDocumentId(B.documentId);G&&(c[B.documentId]=G)}});let p={organizationId:a,documentIds:e,timestamp:s,limitToLast:i,documentMetadataByDocumentId:c},u=yield this.notificationUtilsService.handleNotificationEncryption({data:p}),C=(yield r({veltData:u}))?.data?.data?.veltData||{},E="notificationwithdocumentidstoencryptanddecryptonsdk"+(this.authService.getUser()?.userId??""),A=yield ioe(C,E);if(A&&typeof A=="object"){let B=this.usersService.userDataProviderAvailable(),G=this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable(),K=[],pe=[];Object.keys(A).forEach((Ce,Ie)=>{let $e=A[Ce].documentMetadata;if($e){let ke=this.allowedDocumentMetadataMap$.value||{};(!ke?.[Ce]||!_o(ke?.[Ce],$e))&&this.allowedDocumentMetadataMap$.next(T(I({},ke),{[Ce]:$e}))}let Ye=A[Ce].notifications||[];Ye.forEach(ke=>{ke.notification=this.getClientNotificationObject(ke)}),this.setNotificationForDocumentIdInCache(Ce,$e,Ye),B&&K.push(this.commonDbUtilsService.formatResponse({feature:"allDocNotifications",data:Ye,shouldAwait:!0,forceResolve:!0})),G&&pe.push(this.commonDbUtilsService.formatResponse({feature:"allDocNotifications",data:Ye,shouldCommentAnnotationsResolverAwait:!0}))}),B&&Promise.all(K).then(()=>{Object.keys(A).forEach(Ce=>{let Ie=A?.[Ce]?.documentMetadata||{},$e=this.commonDbUtilsService.mergeUsersWithData({feature:"allDocNotifications",data:A?.[Ce]?.notifications||[]});$e.forEach(Ye=>{Ye.notification=this.getClientNotificationObject(Ye)}),this.setNotificationForDocumentIdInCache(Ce,Ie,$e)})}),G&&Promise.all(pe).then(()=>{Object.keys(A).forEach(Ce=>{let Ie=A?.[Ce]?.documentMetadata||{},$e=A?.[Ce]?.notifications?.reduce((Ye,ke)=>(Ye[ke.notificationId]=ke,Ye),{});$e=this.commonDbUtilsService.mergeCommentAnnotationsWithData({feature:"allDocNotifications",data:$e}),$e=Object.values($e??{}),$e.forEach(Ye=>{Ye.notification=this.getClientNotificationObject(Ye)}),this.setNotificationForDocumentIdInCache(Ce,Ie,$e)})})}}}catch(r){return this.loggingService.catch("Error in NotificationService fetchNotificationsForDocumentIds: ",r),[]}})}setNotificationForDocumentIdInCache(e,i,r,a){try{let s=this.docService.getOrganizationConfig()?.organizationId??"",c=this.docService.getOrganizationMetadata(s);i||(i=JSON.parse(JSON.stringify(this.docService.getDocumentMetadata()||{}))),c||(c=JSON.parse(JSON.stringify(this.docService.getOrganizationMetadata(s)||{})));let p=this.notificationsByDocumentIdMap$.getValue(),u=p?.[e]?.notifications||[],C=this.docService.getLocationMetadatas(),E=r?.map(G=>{let K=G.notification;return K.metadata&&(K.metadata.documentName=i?.documentName||K.metadata.documentName,K.metadata.organizationMetadata=c||K.metadata.organizationMetadata,K.metadata.documentMetadata=i||K.metadata.documentMetadata),C&&(K=this.notificationUtilsService.mergeLocationWithNotification({notification:K},C)?.notification),K})?.filter(G=>!!G)||[],A=new Map(u.map(G=>[G.id,G]));E.forEach(G=>{A.set(G.id,G)});let B=Array.from(A.values()).sort((G,K)=>(K.timestamp||0)-(G.timestamp||0));this.notificationsByDocumentIdMap$.next(T(I({},p),{[e]:{notifications:B,documentMetadata:i}}))}catch(s){this.loggingService.catch("Error in NotificationService setNotificationForDocumentIdInCache: ",s)}}removeNotificationsForDocumentId(e){try{this.notificationsByDocumentIdSubscription[e]&&this.notificationsByDocumentIdSubscription[e].unsubscribe();let i=this.notificationsByDocumentIdMap$.getValue();delete i?.[e],this.notificationsByDocumentIdMap$.next(i)}catch(i){this.loggingService.catch("Error in NotificationService removeNotificationsForDocumentId: ",i)}}getNotificationsForDocumentId$(e,i=50){try{return this.authService.getUser$().pipe(ce(r=>({user:r})),ue(r=>this.maxNotificationDays$.pipe(ce(()=>r))),ue(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 bo(this.commonDbService.queryData({feature:"allDocNotifications",properties:{rtdbQuery:[qL("timestamp"),KL(u),WL(i)],firestoreQuery:[Ya("timestamp","desc"),dt("timestamp",">=",u),dt("notification.actionUser.userId","!=",a.userId),$v(i)],apiKey:s,organizationId:this.docService?.getDocumentPaths()?.organizationId||a?.organizationId,documentId:e}})).pipe(ue(C=>this.commonDbUtilsService.mergeUsersWithData$({feature:"allDocNotifications",data:{data:C,operation:null}})),ce(C=>C?.data??[]),ce(C=>(C.sort((E,A)=>A.timestamp-E.timestamp),C)),Vn(C=>(this.loggingService.catch("Error in NotificationService getNotificationsForDocumentId: ",C),re([]))),ce(C=>(C.forEach(E=>{E.notification=this.getClientNotificationObject(E)}),C)))}return re([])}))}catch(r){return this.loggingService.catch("Error in NotificationService getNotificationsForDocumentId: ",r),re([])}}getStartAtTimestamp(){try{let e=new Date,i=this.maxNotificationDays$.getValue()>0?this.maxNotificationDays$.getValue():15;return e.setDate(e.getDate()-i),e.getTime()}catch(e){return this.loggingService.catch("Error in NotificationService getStartAtTimestamp: ",e),0}}getNotificationsForYou(){try{return this.databaseService.getDb().pipe(ue(e=>this.authService.getUser$().pipe(ce(i=>({db:e,user:i})))),ue(e=>this.maxNotificationDays$.pipe(ce(()=>e))),ue(e=>{let{db:i,user:r}=e,a=this.configService.getApiKey();if(i&&r?.organizationId&&a){let s=Nt(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:[qL("timestamp"),KL(u),WL(50)],firestoreQuery:[Ya("timestamp","desc"),dt("timestamp",">=",u),dt("notification.actionUser.userId","!=",r.userId),$v(50)],apiKey:a,organizationId:this.docService?.getDocumentPaths()?.organizationId||r?.organizationId,documentId:this.docService.getDocumentPaths()?.documentId,userId:s}}).pipe(ue(C=>C?.data?re(C).pipe(ce(E=>E?.data),ce(E=>{let A=Object.values(E||{});return A.forEach(G=>{G.notification=this.getClientNotificationObject(G)}),A.sort((G,K)=>K.timestamp-G.timestamp),A.map(G=>G.notification).filter(G=>!!G)}),ue(E=>{let A={data:E?.reduce((B,G)=>(B[G.id]={notification:G},B),{}),operation:null};return this.commonDbUtilsService.mergeLocationMetadataWithData$({data:A,feature:"allUserNotifications"}).pipe(ce(B=>Object.values(B?.data||{}).map(G=>G?.notification)))})):re(null)))}return re(null)}),ue(e=>{let i=this.docService.getOrganizationConfig()?.organizationId??"";return this.docService.getOrganizationMetadata$(i).pipe(ce(()=>e))}),ue(e=>this.allowedDocumentMetadataMap$.pipe(ce(()=>e))),ce(e=>(e?.length&&(e=e.map(i=>{if(i?.metadata){let r=this.docService.getOrganizationConfig()?.organizationId??"",a=this.getAllowedDocumentMetadataByDocumentId(i.metadata.documentId),s=this.docService.getOrganizationMetadata(r);a||(a=JSON.parse(JSON.stringify(this.docService.getDocumentMetadata()||{}))),s||(s=JSON.parse(JSON.stringify(this.docService.getOrganizationMetadata(r)||{}))),i.metadata.documentName=a?.documentName||i.metadata.documentName,i.metadata.organizationMetadata=s||i.metadata.organizationMetadata,i.metadata.documentMetadata=a||i.metadata.documentMetadata}return i})),e===null?this.notificationsForYou$.next(null):e?.length?this.notificationsForYou$.next(e):this.notificationsForYou$.next([]),re(e))))}catch(e){return this.loggingService.catch("Error in NotificationService getNotificationsForYou: ",e),re({})}}subscribeNotificationsData(e,i){this.loggingService.log("%c[WB] Calling FUNCTION: subscribeViewsData","color: green;");let r,a;try{if(e&&(a=Cn(e)),i&&typeof i=="object"){let s=Qo(i);r=Cn(JSON.stringify(s))}}catch(s){this.loggingService.catch("Error in ViewsService subscribeViewsData: ",s)}return qn(this.afAuth).pipe(Ne(s=>!!s),ue(s=>this.isFeatureAllowed({firebaseUser:s})),ue(s=>s.featureAllowed?this.iamService.isUserAllowed$().pipe(ce(c=>(s.featureAllowed=c,s))):re(s)),ue(s=>!s.featureAllowed||s?.user?.organizationId?(this.notifications$.next([]),this.rawNotificationsByIdMap$.next(new Map),this.processedNotifications$.next([]),this.notificationsByIdMap$.next(new Map),this.notificationViews$.next({}),this.setNotificationsByIdMap(),re([])):re(s).pipe(ue(c=>this.docService.getDocumentPaths$().pipe(ce(p=>(this.documentPaths=p,c.documentPaths=p,c)))),ue(c=>this.getDataFromDocumentId(a)))))}isFeatureAllowed(e){return this.configService.getConfig$().pipe(Ne(i=>!!i),ce(i=>T(I({},e),{config:i})),ue(i=>this.authService.getUser$().pipe(ce(r=>T(I({},i),{user:r})))),ue(i=>Ji(i.config,i.user,Re.NOTIFICATION)?re(T(I({},i),{featureAllowed:!0})):(this.loggingService.warn("Notification feature is not allowed."),re(T(I({},i),{featureAllowed:!1})))))}getDataFromDocumentId(e){return this.databaseService.getDb().pipe(Ne(i=>!!i),ue(i=>{if(this.db=i,this.loggingService.log(this.db),this.configService?.getApiKey()&&this.documentPaths?.views){let r=`${this.configService.getApiKey()}`;this.documentPaths?.organizationId&&(r+=`/${U.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${this.documentPaths.organizationId}`);let a=on(this.db,`${e?r+"/"+U.FIREBASE_PARTIAL_PATH_DOCS+"/"+e+"/"+U.FIREBASE_PARTIAL_PATH_VIEWS+"/":this.documentPaths?.notifications}`);return Bf(a).pipe(Vn(s=>(this.loggingService.catch("Error in NotificationService getDataFromDocumentId: ",s),re(null))),ce(s=>{let c=[],p=new Map;s?.raw&&(Object.keys(s?.raw||{}).forEach(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 re(null)}))}setNotificationsByIdMap(){try{let e=this.authService.getUser();if(e){let i=this.notificationViews$.getValue(),r;e?.email&&(r=Nt(e?.email));let a;e?.userId&&(a=Nt(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 A=this.commentService?.getAnnotationById(C.targetAnnotationId);A||E?.annotationData&&(A=E.annotationData),A&&(C.notificationSourceData=Hn(A))}s.set(p.id,C)}}),s.forEach((p,u)=>{p.isUnread=p?.actionUser?.userSnippylyId!==e?.userSnippylyId&&!i?.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:i,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=Nt(c?.email));let C=null;c?.userId&&(C=Nt(c?.userId));let E=!1,A=!0;(u&&p.notifyUsers?.[u]||C&&p.notifyUsersByUserId?.[C])&&(E=!0),C&&a?.[C]&&(A=!1);let B={id:p.id};if(s?B=T(I(I({},B),s),{displayHeadlineMessage:this.getNotificationHeadlineMessage(s),displayBodyMessage:this.getNotificationBodyMessage(s),forYou:E,isUnread:A}):B={id:e.id,notificationSource:e.notificationSource,actionType:e.actionType,actionUser:e.actionUser,timestamp:e.timestamp,targetAnnotationId:e.targetAnnotationId,displayHeadlineMessage:this.getNotificationHeadlineMessage(e),displayBodyMessage:this.getNotificationBodyMessage(e),forYou:E,isUnread:A,metadata:r},B?.notificationSource==="comment"&&B?.targetAnnotationId){let G=this.commentService?.getAnnotationById(B.targetAnnotationId);G||s?.notificationSourceData&&(G=s?.notificationSourceData),G||i?.annotationData&&(G=i.annotationData),G&&(B.notificationSourceData=Hn(G))}return i?.targetAnnotationData?.isCommentResolverUsed&&(B.isCommentResolverUsed=i?.targetAnnotationData?.isCommentResolverUsed),B}return}catch(c){this.loggingService.catch("Error in NotificationService getClientNotificationObject: ",c);return}}getNotificationsForYou$(){return this.notificationsForYou$.asObservable()}getNotificationsByDocumentId$(){return this.notificationsByDocumentIdMap$.asObservable().pipe(ce(e=>e?Object.keys(e??{}).map(i=>{let r=e[i].notifications||[],a=r.filter(c=>c.isUnread).length,s=r.length>0&&r[0]?.timestamp||0;return{documentId:i,notifications:e[i]?.notifications,unreadNotificationsCount:a,latestNotificationTimestamp:s,documentMetadata:e[i]?.documentMetadata}}).filter(i=>i.notifications?.length>0).sort((i,r)=>r.latestNotificationTimestamp-i.latestNotificationTimestamp):null))}getAllNotifications$(){return this.getNotificationsByDocumentId$().pipe(ce(e=>{let i=null;return e?(i=[],e.forEach(r=>{r.notifications.forEach(a=>{i?.push(a)})}),i?.sort((r,a)=>a.timestamp-r.timestamp)):null}))}processNotificationData(e){try{let i=e?.annotationData?.metadata,r=this.docService.getOrganizationConfig()?.organizationId;e.metadata=JSON.parse(JSON.stringify(this.docService.getDocumentMetadata(i?.documentId)||{})),e.metadata||(e.metadata={},this.loggingService.catch("Warning in NotificationService updateNotificationDatabase: ","Document metadata not found")),delete e.metadata.locations,e.metadata.documentMetadata=JSON.parse(JSON.stringify(this.docService.getDocumentMetadata(i?.documentId)||{})),e?.metadata?.documentMetadata?.clientDocumentId&&e?.metadata?.documentMetadata?.documentId&&(e.metadata.documentMetadata.documentId=e?.metadata?.documentMetadata?.clientDocumentId),delete e.metadata.documentMetadata.locations,e.metadata.organizationMetadata=JSON.parse(JSON.stringify(r?this.docService.getOrganizationMetadata(r)||{}:{})),e?.metadata?.organizationMetadata?.clientOrganizationId&&e?.metadata?.organizationMetadata?.organizationId&&(e.metadata.organizationMetadata.organizationId=e?.metadata?.organizationMetadata?.clientOrganizationId);let a=this.configService.getApiKey();e.metadata.apiKey=a,e.platform=this.configService.getSF()?"sf":"sdk",e.actionUser=this.authService.getUser();let s=i?.documentId?new Im({apiKey:a,documentId:i.documentId,organizationId:i?.organizationId}):this.docService.getDocumentPaths();e?.actionUser?.organizationId&&(e.metadata.organizationId=s?.organizationId||e.actionUser.organizationId,e.metadata.clientOrganizationId=s?.clientOrganizationId||e.actionUser.clientOrganizationId);let c=this.docService.getLocation();c&&(e.location=c?.location,e.locationId=c?.locationId),this.loggingService.log(`[NOTIFICATION] ${e?.notificationSource} ${e?.actionType}`,e);let p=this.commonDbService.getServerTimestamp(),u=this.notificationUtilsService.formatNotification(e,p);return JSON.parse(JSON.stringify(u))}catch(i){return this.loggingService.catch("Error in NotificationService processNotificationData: ",i),null}}updateNotificationDatabase(e){try{let i=on(this.notificationsDb),r=this.processNotificationData(e);n5(i,JSON.parse(JSON.stringify(r)))}catch(i){this.loggingService.catch("Error in NotificationService updateNotificationDatabase: ",i)}}getRawNotifications$(){return this.notifications$.asObservable()}getProcessedNotifications$(){return this.processedNotifications$.asObservable()}getNotifications$(){return this.authService.getUser$().pipe(ue(e=>e?e.organizationId?this.getAllNotifications$().pipe(ue(i=>this.notificationsForYou$.pipe(ce(r=>{let a=new Map;return(i||[]).forEach(s=>{s.id&&a.set(s.id,s)}),(r||[]).forEach(s=>{s.id&&!a.has(s.id)&&a.set(s.id,s)}),Array.from(a.values()).sort((s,c)=>(c.timestamp||0)-(s.timestamp||0))})))):this.notificationsByIdMap$.asObservable().pipe(ce(i=>Array.from(i.values())),ce(i=>i.sort((r,a)=>a.timestamp-r.timestamp)),Pg()):re(null)))}getRawNotificationById(e){try{return this.rawNotificationsByIdMap$.getValue()?.get(e)}catch(i){this.loggingService.catch("Error in NotificationService getRawNotificationById: ",i);return}}setNotificationViews(e){try{this.notificationViews$.next(e),this.setNotificationsByIdMap()}catch(i){this.loggingService.catch("Error in NotificationService setNotificationViews: ",i)}}getNotificationHeadlineMessage(e){try{let i=this.authService.getUser();if(e?.displayHeadlineMessageTemplate&&e?.displayHeadlineMessageTemplateData){let r=e.displayHeadlineMessageTemplate,a=e.displayHeadlineMessageTemplateData,s=/\{(\w+)\}/g,c=r.replace(s,(p,u)=>(u==="actionUser"||u==="recipientUser")&&a[u]?i?.email&&a[u].email===i?.email||i?.userId&&a[u]?.userId===i?.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(i){return this.loggingService.catch("Error in NotificationService getNotificationHeadlineMessage: ",i),""}}getNotificationBodyMessage(e){try{if(e?.displayBodyMessageTemplate&&e?.displayBodyMessageTemplateData){let i=e?.displayBodyMessageTemplate;return e?.displayBodyMessageTemplateData&&e?.displayBodyMessageTemplateData?.users?.forEach(r=>{if(r?.userId){let a=this.usersService.getUserById(r?.userId);i=i?.replaceAll(`{{${r.userId}}}`,a?.name||a?.email||'<velt-skeleton-loader width="50px" height="20px" border-radius="4px"></velt-skeleton-loader>')}}),this.domService.sanitizeHtml(i)}return this.domService.sanitizeHtml(e.displayBodyMessage||"")}catch(i){return this.loggingService.catch("Error in NotificationService getNotificationBodyMessage: ",i),""}}setHistoryPanelVisibility(e,i=!1,r=!1){try{e?document.querySelector(U.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL)?this.historyPanelVisible$.next(e):this.loggingService.catch("Error in NotificationService setHistoryPanelVisibility: ",`<${U.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`):this.historyPanelVisible$.next(e),e?this.analyticsService.trackEvent(X.Events.Notifications.NOTIFICATION_HISTORY_PANEL_OPENED):this.analyticsService.trackEvent(X.Events.Notifications.NOTIFICATION_HISTORY_PANEL_CLOSED)}catch{this.loggingService.catch("Error in NotificationService setHistoryPanelVisibility: ",`<${U.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`)}}toggleHistoryPanelVisibility(e=!1,i=!1){try{this.historyPanelVisible$.value?this.historyPanelVisible$.next(!this.historyPanelVisible$.value):document.querySelector(U.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL)?(this.historyPanelVisible$.next(!this.historyPanelVisible$.value),this.historyPanelVisible$.value?this.analyticsService.trackEvent(X.Events.Notifications.NOTIFICATION_HISTORY_PANEL_TOGGLED,{action:"closed"}):this.analyticsService.trackEvent(X.Events.Notifications.NOTIFICATION_HISTORY_PANEL_TOGGLED,{action:"opened"})):this.loggingService.catch("Error in NotificationService toggleHistoryPanelVisibility: ",`<${U.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`)}catch{this.loggingService.catch("Error in NotificationService toggleHistoryPanelVisibility: ",`<${U.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`)}}getHistoryPanelVisibility$(){return this.historyPanelVisible$.asObservable()}setNotificationsAsRead(e){return te(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(i){this.loggingService.catch("Error in NotificationService setNotificationsAsRead: ",i)}})}setAllNotificationsAsRead(e){return te(this,null,function*(){try{if(e?.tabId==="for-you"){let i=this.notificationsForYou$.value||[];this.setNotificationsAsRead(i)}else this.getNotifications$().pipe(et(1)).subscribe(i=>{i&&this.setNotificationsAsRead(i)})}catch(i){this.loggingService.catch("Error in NotificationService setAllNotificationsAsRead: ",i)}})}getUnreadNotificationsCount$(){try{return this.notificationsForYou$.pipe(ce(e=>e?.filter(r=>r?.isUnread)?.length??null),ue(e=>this.getNotifications$().pipe(ce(i=>{let r=i?.filter(a=>a?.isUnread)?.length??null;return{forYou:e,all:r}}))))}catch(e){return this.loggingService.catch("Error in NotificationService getUnreadNotificationsCount$: ",e),re({forYou:null,all:null})}}setNotificationAsRead(e){return te(this,null,function*(){try{let i=this.authService.getUser();if(i&&e?.id){let r=Nt(i?.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(i){this.loggingService.catch("Error in NotificationService setNotificationAsRead: ",i)}})}setMaxDays(e){try{e>0?this.maxNotificationDays$.next(e):this.maxNotificationDays$.next(15)}catch(i){this.loggingService.catch("Error in NotificationService setMaxDays: ",i)}}setTabConfig(e){try{e&&this.tabConfig$.next(e)}catch(i){this.loggingService.catch("Error in NotificationService setTabConfig: ",i)}}getTabConfig$(){return this.tabConfig$.asObservable()}getTabConfig(){return this.tabConfig$.value}enableReadNotificationsOnForYouTab(){this.readNotificationsOnForYouTab$.next(!0)}disableReadNotificationsOnForYouTab(){this.readNotificationsOnForYouTab$.next(!1)}getReadNotificationsOnForYouTab$(){return this.readNotificationsOnForYouTab$.asObservable()}getReadNotificationsOnForYouTab(){return this.readNotificationsOnForYouTab$.value}markNotificationAsReadById(e){return te(this,null,function*(){try{this.getNotifications$().pipe(et(1)).subscribe(i=>{if(i){let r=i.filter(a=>a.id===e);this.setNotificationsAsRead(r)}})}catch(i){this.loggingService.catch("Error in NotificationService markNotificationAsReadById: ",i)}})}getAllowedDocumentMetadataByDocumentId(e){try{return this.allowedDocumentMetadataMap$.value?.[e]||null}catch(i){return this.loggingService.catch("Error in NotificationService getAllowedDocumentMetadataByDocumentId: ",i),null}}};o.\u0275fac=function(i){return new(i||o)(Q(Si),Q(Ke),Q(je),Q(jt),Q(En),Q(Zv),Q(Yv),Q(bs),Q(un),Q(lt),Q(Fe),Q(hn),Q(y),Q(qM),Q(zn),Q(Uo))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Ho=(()=>{let o=class o{constructor(e){this.loggingService=e,this._customStatusMap=new ve(U.CommentAnnotationStatusMap),this._customPriorityMap=new ve(U.CommentAnnotationPriorityMap),this._customCategoryMap=new ve(U.CommentCategoryMap);try{let i=sessionStorage.getItem(U.SESSION_STORAGE.VELT_CUSTOM_PRIORITY_MAP);i&&this._customPriorityMap.next(JSON.parse(i));let r=sessionStorage.getItem(U.SESSION_STORAGE.VELT_CUSTOM_STATUS_MAP);r&&this._customStatusMap.next(JSON.parse(r));let a=sessionStorage.getItem(U.SESSION_STORAGE.VELT_CUSTOM_CATEGORY_MAP);a&&this._customCategoryMap.next(JSON.parse(a))}catch(i){this.loggingService.catch("Error in CustomFilterService constructor: ",i)}}setCustomStatusFilters(e){try{if(e.length<2){this._customStatusMap.next(U.CommentAnnotationStatusMap),sessionStorage.setItem(U.SESSION_STORAGE.VELT_CUSTOM_STATUS_MAP,JSON.stringify(U.CommentAnnotationStatusMap)),this.loggingService.catch("Custom status filters must have at least 2 filters");return}let i={};e.forEach(r=>{i[r.id]=r,r.type||(r.type="ongoing")}),this._customStatusMap.next(i),sessionStorage.setItem(U.SESSION_STORAGE.VELT_CUSTOM_STATUS_MAP,JSON.stringify(i))}catch(i){this.loggingService.catch("Error in CustomFilterService setCustomStatusFilters: ",i)}}setCustomPriorityFilters(e){try{if(e.length<2){this._customPriorityMap.next(U.CommentAnnotationPriorityMap),sessionStorage.setItem(U.SESSION_STORAGE.VELT_CUSTOM_PRIORITY_MAP,JSON.stringify(U.CommentAnnotationPriorityMap)),this.loggingService.catch("Custom priority filters must have at least 2 filters");return}let i={};e.forEach(r=>{i[r.id]=r}),this._customPriorityMap.next(i),sessionStorage.setItem(U.SESSION_STORAGE.VELT_CUSTOM_PRIORITY_MAP,JSON.stringify(i))}catch(i){this.loggingService.catch("Error in CustomFilterService setCustomPriorityFilters: ",i)}}setCustomCategories(e){try{let i={};e.forEach(r=>{i[r.id]=r}),this._customCategoryMap.next(i),sessionStorage.setItem(U.SESSION_STORAGE.VELT_CUSTOM_CATEGORY_MAP,JSON.stringify(i))}catch(i){this.loggingService.catch("Error in CustomFilterService setCustomCategories: ",i)}}get customStatusMap$(){return this._customStatusMap.asObservable()}get customPriorityMap$(){return this._customPriorityMap.asObservable()}get customCategoryMap$(){return this._customCategoryMap.asObservable()}get defaultStatus(){try{let i=Object.entries(this._customStatusMap.value).find(([r,a])=>a.type==="default");if(i)return i[1]}catch(e){this.loggingService.catch("Error in CustomFilterService defaultStatus: ",e)}return U.CommentAnnotationStatusMap.OPEN}get resolvedStatus(){try{let i=Object.entries(this._customStatusMap.value).find(([r,a])=>a.type==="terminal");if(i)return i[1]}catch(e){this.loggingService.catch("Error in CustomFilterService resolvedStatus: ",e)}return U.CommentAnnotationStatusMap.OPEN}get ongoingStatuses(){try{let i=Object.entries(this._customStatusMap.value).filter(([r,a])=>a.type==="ongoing");if(i)return i.map(r=>r[1])}catch(e){this.loggingService.catch("Error in CustomFilterService ongoingStatuses: ",e)}return[U.CommentAnnotationStatusMap.IN_PROGRESS]}convertLegacyAnnotationStatus(e){try{if(typeof e.status=="string"||e.status===void 0){let i=Object.entries(this._customStatusMap.value),r=i.find(([a,s])=>s.type==="default");switch(e.status){case"open":r&&(e.status=r[1]);break;case"inProgress":let a=i.find(([c,p])=>p.type==="ongoing");a&&(e.status=a[1]);break;case"resolved":let s=i.find(([c,p])=>p.type==="terminal");s&&(e.status=s[1]);break;default:r&&(e.status=r[1]);break}}return e}catch(i){return this.loggingService.catch("Error in CustomFilterService convertLegacyAnnotation: ",i),e}}convertLegacyPriority(e){try{typeof e.priority=="string"&&(e.priority=U.CommentAnnotationPriorityMap[e.priority])}catch(i){this.loggingService.catch("Error in CustomFilterService convertLegacyPriority: ",i)}return e}convertLegacyCategory(e){try{if(e.commentCategories===void 0||e.commentCategories===null||!Array.isArray(e.commentCategories)||e.commentCategories.length===0)return e;typeof e.commentCategories[0]=="string"&&(e.commentCategories=e.commentCategories.map(i=>U.CommentCategoryMap[i]))}catch(i){this.loggingService.catch("Error in CustomFilterService convertLegacyCategory: ",i)}return e}};o.\u0275fac=function(i){return new(i||o)(Q(y))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var bc=(()=>{let o=class o{constructor(e,i,r){this.domService=e,this.loggingService=i,this.sanitizer=r,this.emojis={};try{this.loggingService.log("%c[WB] Creating CLASS: EmojiService","color: blue;"),Object.keys(o.Icons).forEach(a=>{let s=o.Icons[a];this.emojis[a]=this.sanitizer.bypassSecurityTrustHtml(this.domService.sanitizeSvg(s))}),Object.keys(o.GIF_PATHS).forEach(a=>{let s=`<img src="${o.GIF_PATHS[a]}" alt="${a}" />`;this.emojis[a]=this.sanitizer.bypassSecurityTrustHtml(this.domService.sanitizeHtml(s))})}catch(a){this.loggingService.catch("Error in EmojiService constructor: ",a)}}getEmoji(e){try{return this.emojis[e]}catch{return""}}getEmojiFromIconUrl(e){try{return this.sanitizer.bypassSecurityTrustHtml(this.domService.sanitizeHtml(`<img src="${e}" alt="emoji" />`))}catch{return""}}getEmojiFromIconEmoji(e,i){try{let r=`<span class="velt-emoji-icon velt-emoji-icon--emoji">${e}</span>`;return i&&(r=`<span class="velt-emoji-icon velt-emoji-icon--emoji" emoji-id=${i}>${e}</span>`),this.sanitizer.bypassSecurityTrustHtml(this.domService.sanitizeHtml(r))}catch{return""}}setEmojiList(e){try{this.emojis={},Object.keys(e).forEach(i=>{let r=e[i];if(r.svg)this.emojis[i]=this.sanitizer.bypassSecurityTrustHtml(this.domService.sanitizeSvg(r.svg));else if(r.url){let a=`<img src="${r.url}" alt="${i}" />`;this.emojis[i]=this.sanitizer.bypassSecurityTrustHtml(this.domService.sanitizeHtml(a))}else r.emoji&&(this.emojis[i]=this.getEmojiFromIconEmoji(this.domService.sanitizeHtml(r.emoji)))})}catch(i){this.loggingService.catch("Error in EmojiService setEmojiList: ",i)}}};o.Icons={RAISED_HANDS:`<svg width="58" height="57" viewBox="0 0 58 57" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
195
|
+
`+Ar),Tc&&UM([Le,Ee,xn],Ts=>{Ar=XS(Ar,Ts," ")}),$e&&ug?$e.createHTML(Ar):Ar},o.setConfig=function(){let Yt=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};zm(Yt),gg=!0},o.clearConfig=function(){Hm=null,gg=!1},o.isValidAttribute=function(Yt,Be,St){Hm||zm({});let Gt=ho(Yt),no=ho(Be);return d_(Gt,no,St)},o.addHook=function(Yt,Be){typeof Be=="function"&&ZS(he[Yt],Be)},o.removeHook=function(Yt,Be){if(Be!==void 0){let St=a9e(he[Yt],Be);return St===-1?void 0:s9e(he[Yt],St,1)[0]}return vse(he[Yt])},o.removeHooks=function(Yt){he[Yt]=[]},o.removeAllHooks=function(){he=Ese()},o}var M$=Ose();var Ase={ADD_TAGS:["velt-skeleton-loader"],ADD_ATTR:["border-radius"]},Fe=(()=>{let o=class o{constructor(e,i,r){this.rendererFactory2=e,this.loggingService=i,this.sanitizer=r,this.isVideoEditorHandlingDelete=!1,this.pageScrollHeight=0,this.enableRectSelectionSubject$=new ve(!1),this.enableRectSelection$=this.enableRectSelectionSubject$.asObservable(),this.scrollableElementsIds$=new ve([]),this.mousedown=!1,this.windowMouseDown$=new Xe,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 Xe,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 ei),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=a=>{try{let s=[];return a.forEach(c=>{if(!Hi(c))if(c instanceof HTMLElement){if(c.className.includes("cdk-overlay-container")||c.className.includes("cdk-overlay-connected-position-bounding-box"))return;if(c.className.includes("cdk-overlay")){let p=!1;c.childNodes.forEach(u=>{Hi(u)&&(p=!0)}),p||s.push(c)}else s.push(c)}else s.push(c)}),s}catch(s){return this.loggingService.catch("Error in DomService filterSnippylyNodes: ",s),[]}},this.loggingService.log("%c[WB] Creating CLASS: DomService","color: blue;");try{this.renderer=this.rendererFactory2.createRenderer(null,null);let a=this.calculateScreenSize();this.currentScreenSize$=new ve(a),this.currentMousePosition$=new ve(this.currentMousePosition),this.detectNetworkStatusChange(),this.getScrollableElementsIds$().pipe(Ai(),gn(([s,c])=>{try{let p=c.filter(C=>!s.includes(C)),u=s.filter(C=>!c.includes(C));u.length&&u.map(E=>document.getElementById(E)).filter(E=>E).forEach(E=>{this.unlistenElementScroll&&this.unlistenElementScroll[E.id]&&this.unlistenElementScroll[E.id]()}),p.length&&p.map(E=>document.getElementById(E)).filter(E=>E).forEach(E=>{this.unlistenElementScroll[E.id]=this.renderer.listen(E,"scroll",A=>{let B=this.calculateScreenSize();this.currentScreenSize$.next(B)})})}catch(p){this.loggingService.catch("Error in DomService getScrollableElementsIds subscription: ",p)}})).subscribe(()=>{},s=>{this.loggingService.catch("Error in DomService getScrollableElementsIds subscription: ",s)}),this.getSelectedAnnotationsMap$().subscribe(s=>{Object.keys(s||{})?.length?uoe("snippylyUserScalableNo","viewport","width=device-width, user-scalable=no"):hoe("snippylyUserScalableNo")},s=>{this.loggingService.catch("Error in DomService getSelectedAnnotationsMap$ subscription: ",s)})}catch(a){this.loggingService.catch("Error in DomService constructor: ",a)}}setDocService(e){try{this.docService=e,this.subscribeToDomEvents()}catch(i){this.loggingService.catch("Error in DomService setDocService: ",i)}}subscribeToDomEvents(){try{this.docService?.getDocumentPaths$().pipe(ce(e=>{e?(this.onWindowResize(),this.onWindowScroll(),this.onPointerDown(),this.onWindowClick(),this.onWindowKeyupBackspace(),this.onWindowKeyupDelete(),this.onWindowKeyupEsc(),this.onWindowPopState(),this.onWindowKeydownShift(),this.onWindowKeyupShift(),this.addPointerMoveListener(),this.addPointerUpListener(),this.addSelectionChangeListener(),this.onDocumentClick(),this.onDocumentFocus()):(this.unsubscribeFromWindowResize(),this.unsubscribeFromWindowScroll(),this.unsubscribeFromPointerDown(),this.unsubscribeFromWindowClick(),this.unsubscribeFromWindowKeyupBackspace(),this.unsubscribeFromWindowKeyupDelete(),this.unsubscribeFromWindowKeyupEsc(),this.unsubscribeFromWindowPopState(),this.unsubscribeFromWindowKeydownShift(),this.unsubscribeFromWindowKeyupShift(),this.unsubscribeFromPointerMoveListener(),this.unsubscribeFromPointerUpListener(),this.unsubscribeFromSelectionChangeListener(),this.unsubscribeFromDocumentClick(),this.unsubscribeFromDocumentFocus(),this.unsetMutationObserver())})).subscribe()}catch(e){this.loggingService.catch("Error in DomService subscribeToDomEvents: ",e)}}setScrollableElementsIds(e){try{e&&e.length&&this.scrollableElementsIds$.next(Array.from(new Set(e)))}catch(i){this.loggingService.catch("Error in DomService setScrollableElementsIds: ",i)}}getScrollableElementsIds$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getScrollableElementsIds$","color: green;"),this.scrollableElementsIds$.asObservable()}removeScrollableElementsIds(){this.scrollableElementsIds$.next([])}setMutationObserver(e){try{this.mutationObserver||(this.loggingService.log("%c[WB] Calling DomService FUNCTION: setMutationObserver","color: green;"),this.loggingService.log("%c[WB] setMutationObserver from: "+e,"color: green;"),this.mutationObserver=new MutationObserver(i=>{try{if(i?.find(a=>a?.attributeName===U.VELT_IGNORE_CHANGE_DETECTION))return;let r=i.filter(a=>a.type==="childList").filter(a=>{let s=a.target;return a.removedNodes.forEach(c=>{let p=c;if(typeof p.getAttribute=="function"){let u=p.getAttribute(U.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))}}}),Hi(s)?!1:!!(this.filterSnippylyNodes(a.addedNodes).length||this.filterSnippylyNodes(a.removedNodes).length)});this.childListMutation$.next(r),r.push(...i.filter(a=>a.type==="attributes").filter(a=>!Hi(a.target)).filter(a=>this.filterSnippylyNodes([a.target]).length).filter(a=>{if(a){let s=a.target;return s?.classList?.contains("snippyly-sidebar-panel")?!1:s?!s.getAttribute(U.VELT_IGNORE_CHANGE_DETECTION):!0}return!0})),r=r.filter(a=>{let s=!0;return Object.keys(U.INGNORE_MUTATION_OBSERVER_CHANGE_TAGS).forEach(c=>{a.target?.closest(c)&&(s=!1)}),s}),r=r.filter(a=>a.target&&xo(a.target)),r.length&&this.mutation$.next(r)}catch(r){this.loggingService.catch("Error in DomService change detection: ",r)}}),this.mutationObserver.observe(document.body,{childList:!0,subtree:!0,attributes:!0}))}catch(i){this.loggingService.catch("Error in DomService change detection: ",i)}}unsetMutationObserver(){try{this.mutationObserver&&(this.mutationObserver.disconnect(),this.mutationObserver=null)}catch(e){this.loggingService.catch("Error in DomService unsetMutationObserver: ",e)}}detectNetworkStatusChange(){this.loggingService.log("%c[WB] Calling FUNCTION: detectNetworkStatusChange","color: green;");try{oo(ri(window,"offline").pipe(ce(()=>!1)),ri(window,"online").pipe(ce(()=>!0)),new Lt(e=>{e.next(navigator.onLine),e.complete()})).subscribe(e=>{this.networkStatus$.next(e)})}catch(e){this.loggingService.catch("Error in DomService detectNetworkStatusChange: ",e)}}onWindowResize(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowResize","color: green;");try{this.unsubscribeFromWindowResize(),this.unlistenWindowResize=this.renderer.listen("window","resize",e=>{this.windowResize$.next(e);let i=this.calculateScreenSize();this.deviceInfo$.next(new ei),this.currentScreenSize$.next(i)})}catch(e){this.loggingService.catch("Error in DomService onWindowResize: ",e)}}unsubscribeFromWindowResize(){try{this.unlistenWindowResize&&typeof this.unlistenWindowResize=="function"&&(this.unlistenWindowResize(),this.unlistenWindowResize=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromWindowResize: ",e)}}onWindowScroll(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowScroll","color: green;");try{this.unsubscribeFromWindowScroll(),this.unlistenWindowScroll=this.renderer.listen("window","scroll",e=>{this.windowScroll$.next(e);let i=this.calculateScreenSize();this.currentScreenSize$.next(i)})}catch(e){this.loggingService.catch("Error in DomService onWindowScroll: ",e)}}unsubscribeFromWindowScroll(){try{this.unlistenWindowScroll&&typeof this.unlistenWindowScroll=="function"&&(this.unlistenWindowScroll(),this.unlistenWindowScroll=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromWindowScroll: ",e)}}onPointerDown(){this.loggingService.log("%c[WB] Calling FUNCTION: onPointerDown","color: green;");try{this.unsubscribeFromPointerDown(),this.unlistenPointerDown=this.renderer.listen("window","pointerdown",e=>{this.mousedown=!0,this.windowMouseDown$.next(e),this.setPointerPosition(e)})}catch(e){this.loggingService.catch("Error in DomService onPointerDown: ",e)}}unsubscribeFromPointerDown(){try{this.unlistenPointerDown&&typeof this.unlistenPointerDown=="function"&&(this.unlistenPointerDown(),this.unlistenPointerDown=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromPointerDown: ",e)}}onWindowClick(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowKeyupBackspace","color: green;");try{this.unsubscribeFromWindowClick(),this.unlistenWindowClick=this.renderer.listen("window","click",e=>{this.windowClick$.next(e)})}catch(e){this.loggingService.catch("Error in DomService onWindowClick: ",e)}}unsubscribeFromWindowClick(){try{this.unlistenWindowClick&&typeof this.unlistenWindowClick=="function"&&(this.unlistenWindowClick(),this.unlistenWindowClick=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromWindowClick: ",e)}}onWindowKeyupBackspace(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowKeyupBackspace","color: green;");try{this.unsubscribeFromWindowKeyupBackspace(),this.unlistenWindowKeyupBackspace=this.renderer.listen("window","keyup.backspace",e=>{this.isVideoEditorHandlingDelete||this.windowKeyupBackspace$.next(e)})}catch(e){this.loggingService.catch("Error in DomService onWindowKeyupBackspace: ",e)}}unsubscribeFromWindowKeyupBackspace(){try{this.unlistenWindowKeyupBackspace&&typeof this.unlistenWindowKeyupBackspace=="function"&&(this.unlistenWindowKeyupBackspace(),this.unlistenWindowKeyupBackspace=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromWindowKeyupBackspace: ",e)}}onWindowKeyupDelete(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowKeyupDelete","color: green;");try{this.unsubscribeFromWindowKeyupDelete(),this.unlistenWindowKeyupDelete=this.renderer.listen("window","keyup.delete",e=>{this.isVideoEditorHandlingDelete||this.windowKeyupDelete$.next(e)})}catch(e){this.loggingService.catch("Error in DomService onWindowKeyupDelete: ",e)}}unsubscribeFromWindowKeyupDelete(){try{this.unlistenWindowKeyupDelete&&typeof this.unlistenWindowKeyupDelete=="function"&&(this.unlistenWindowKeyupDelete(),this.unlistenWindowKeyupDelete=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromWindowKeyupDelete: ",e)}}onWindowKeyupEsc(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowKeyupEsc","color: green;");try{this.unsubscribeFromWindowKeyupEsc(),this.unlistenWindowKeyupEsc=this.renderer.listen("window","keyup.esc",e=>{this.windowKeyupEsc$.next(e)})}catch(e){this.loggingService.catch("Error in DomService onWindowKeyupEsc: ",e)}}unsubscribeFromWindowKeyupEsc(){try{this.unlistenWindowKeyupEsc&&typeof this.unlistenWindowKeyupEsc=="function"&&(this.unlistenWindowKeyupEsc(),this.unlistenWindowKeyupEsc=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromWindowKeyupEsc: ",e)}}onWindowPopState(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowPopState","color: green;");try{this.unsubscribeFromWindowPopState(),this.unlistenWindowPopState=this.renderer.listen("window","popstate",e=>{this.windowPopState$.next(e)})}catch(e){this.loggingService.catch("Error in DomService onWindowPopState: ",e)}}unsubscribeFromWindowPopState(){try{this.unlistenWindowPopState&&typeof this.unlistenWindowPopState=="function"&&(this.unlistenWindowPopState(),this.unlistenWindowPopState=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromWindowPopState: ",e)}}onDocumentClick(){this.loggingService.log("%c[WB] Calling FUNCTION: onDocumentClick","color: green;");try{this.unsubscribeFromDocumentClick(),this.documentClickListener=e=>{e?.target?.tagName?.toLowerCase()!==U.TAGS.SUPERFLOW_TOOLBAR&&(this.documentClick$.next(e),this.documentClickSubject$.next(e))},document.addEventListener("click",this.documentClickListener,!0)}catch(e){this.loggingService.catch("Error in DomService onDocumentClick: ",e)}}unsubscribeFromDocumentClick(){try{this.documentClickListener&&typeof this.documentClickListener=="function"&&(document.removeEventListener("click",this.documentClickListener,!0),this.documentClickListener=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromDocumentClick: ",e)}}onDocumentFocus(){this.loggingService.log("%c[WB] Calling FUNCTION: onDocumentFocus","color: green;");try{this.unsubscribeFromDocumentFocus(),this.documentFocusListener=e=>{this.documentFocus$.next(e)},document.addEventListener("focus",this.documentFocusListener,!0)}catch(e){this.loggingService.catch("Error in DomService onDocumentFocus: ",e)}}unsubscribeFromDocumentFocus(){try{this.documentFocusListener&&typeof this.documentFocusListener=="function"&&(document.removeEventListener("focus",this.documentFocusListener,!0),this.documentFocusListener=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromDocumentFocus: ",e)}}onWindowKeydownShift(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowKeydownShift","color: green;");try{this.unsubscribeFromWindowKeydownShift(),this.unlistenWindowKeydownShift=this.renderer.listen("window","keydown.shift",e=>{this.windowKeydownShift$.next(e),this.windowKeyupShift$.next(null)})}catch(e){this.loggingService.catch("Error in DomService onWindowKeydownShift: ",e)}}unsubscribeFromWindowKeydownShift(){try{this.unlistenWindowKeydownShift&&typeof this.unlistenWindowKeydownShift=="function"&&(this.unlistenWindowKeydownShift(),this.unlistenWindowKeydownShift=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromWindowKeydownShift: ",e)}}onWindowKeyupShift(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowKeyupShift","color: green;");try{this.unsubscribeFromWindowKeyupShift(),this.unlistenWindowKeyupShift=this.renderer.listen("window","keyup.shift",e=>{this.windowKeyupShift$.next(e),this.windowKeydownShift$.next(null)})}catch(e){this.loggingService.catch("Error in DomService onWindowKeyupShift: ",e)}}unsubscribeFromWindowKeyupShift(){try{this.unlistenWindowKeyupShift&&typeof this.unlistenWindowKeyupShift=="function"&&(this.unlistenWindowKeyupShift(),this.unlistenWindowKeyupShift=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromWindowKeyupShift: ",e)}}onWindowKeydown$(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowKeydown$","color: green;");try{return ri(window,"keydown")}catch(e){return this.loggingService.catch("Error in DomService onWindowKeydown$: ",e),Dg}}addPointerMoveListener(){this.loggingService.log("%c[WB] Calling FUNCTION: addPointerMoveListener","color: green;");try{this.unsubscribeFromPointerMoveListener(),this.unlistenPointerMoveListener=this.renderer.listen("document","pointermove",e=>{this.windowPointerMove$.next(e),this.mouseMoveEvent=e})}catch(e){this.loggingService.catch("Error in DomService addPointerMoveListener: ",e)}}unsubscribeFromPointerMoveListener(){try{this.unlistenPointerMoveListener&&typeof this.unlistenPointerMoveListener=="function"&&(this.unlistenPointerMoveListener(),this.unlistenPointerMoveListener=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromPointerMoveListener: ",e)}}addPointerUpListener(){this.loggingService.log("%c[WB] Calling FUNCTION: addPointerUpListener","color: green;");try{this.unsubscribeFromPointerUpListener(),this.unlistenPointerUpListener=this.renderer.listen("document","pointerup",e=>{this.windowPointerUp$.next(e)})}catch(e){this.loggingService.catch("Error in DomService addPointerUpListener: ",e)}}unsubscribeFromPointerUpListener(){try{this.unlistenPointerUpListener&&typeof this.unlistenPointerUpListener=="function"&&(this.unlistenPointerUpListener(),this.unlistenPointerUpListener=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromPointerUpListener: ",e)}}addSelectionChangeListener(){this.loggingService.log("%c[WB] Calling FUNCTION: addPointerUpListener","color: green;");try{this.unsubscribeFromSelectionChangeListener(),this.unlistenSelectionChangeListener=this.renderer.listen("document","selectionchange",e=>{this.documentSelectionChange$.next(e)})}catch(e){this.loggingService.catch("Error in DomService addPointerUpListener: ",e)}}unsubscribeFromSelectionChangeListener(){try{this.unlistenSelectionChangeListener&&typeof this.unlistenSelectionChangeListener=="function"&&(this.unlistenSelectionChangeListener(),this.unlistenSelectionChangeListener=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromSelectionChangeListener: ",e)}}updateCurrentMousePosition(e){try{if(this.currentMousePosition.pageX=e.pageX,this.currentMousePosition.pageY=e.pageY,this.currentMousePosition.clientX=e.clientX,this.currentMousePosition.clientY=e.clientY,e.target){let i=this.getXPath(e.target),r=e.target;if(i?.includes("name()='svg'")){let C=this.getXPath(i);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:i,topPercentage:u,leftPercentage:p}}else this.currentMousePosition.element=null;this.currentMousePosition$.next(this.currentMousePosition)}catch(i){this.loggingService.catch("Error in DomService updateCurrentMousePosition: ",i)}}getTargetElementForCursorPosition(e,i=!0,r=!1,a=!0,s){try{let c=e,p=c?.touches?.length?c.touches[0]?.clientX:c.clientX,u=c?.touches?.length?c.touches[0]?.clientY:c.clientY,C=this.getBackgroundElement(p,u,i,r);if(C&&s&&typeof s=="function"&&(C=s(C)),C){let E=this.getXPath(C),A=this.getXPath(C,!0),B=C.getBoundingClientRect(),G=p-B.x,K=u-B.y,pe=G*100/(B.width||1),Ce=K*100/(B.height||1),Ie={xpath:E,fXpath:A,leftPercentage:pe,topPercentage:Ce};if(a){let $e=this.getXPath(C,!0,!0);Ie.cfXpath=$e}return Ie}else return null}catch(c){return this.loggingService.catch("Error in DomService getTargetElementForCommentPinAnnotation: ",c),null}}getBackgroundElement(e,i,r=!0,a=!1){try{let s=document.elementsFromPoint(e,i),c=[];s.forEach(u=>{Hi(u)?c=[]:xo(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,i){try{let r=document.elementsFromPoint(e,i),a=[];return r.forEach(s=>{Hi(s)&&xo(s)&&a.push(s)}),a[0]}catch(r){return this.loggingService.catch("Error in DomService getBackgroundSnippylyElement: ",r),null}}setPointerPosition(e){this.loggingService.log("%c[WB] Calling FUNCTION: setPointerPosition","color: green;");try{this.previousMousePosition.pageX=e.pageX,this.previousMousePosition.pageY=e.pageY,this.currentMousePosition.pageX=e.pageX,this.currentMousePosition.pageY=e.pageY}catch(i){this.loggingService.catch("Error in DomService setPointerPosition: ",i)}}getCurrentWindowSize$(e){return this.loggingService.log("%c[WB] Calling FUNCTION: getCurrentWindowSize","color: green;"),this.currentScreenSize$.asObservable()}getCurrentMousePosition$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getCurrentMousePosition","color: green;"),this.currentMousePosition$.asObservable()}getCurrentWindowSizeValue(){return this.loggingService.log("%c[WB] Calling FUNCTION: getCurrentWindowSizeValue","color: green;"),this.currentScreenSize$.value}getTopLeftPosition(){this.loggingService.log("%c[WB] Calling FUNCTION: getTopLeftPosition","color: green;");try{let e=document?.body?.getBoundingClientRect()||document?.documentElement?.getBoundingClientRect(),i=this.currentMousePosition?.pageX||e.x+200,r=Math.min(i,e.width/2),a=Math.abs(e.y),s=e.y-20;return a>50&&(s=Math.abs(e.y)+180),this.loggingService.log(e),this.loggingService.log(r),this.loggingService.log(s),{topPositionX:r,topPositionY:s}}catch(e){return this.loggingService.catch("Error in DomService getTopLeftPosition: ",e),{topPositionX:0,topPositionY:0}}}toggleSelection(){this.enableRectSelectionSubject$.next(!this.enableRectSelectionSubject$.value)}enableSelection(){this.enableRectSelectionSubject$.next(!0)}disableSelection(){this.enableRectSelectionSubject$.next(!1)}setPinHighlighterClass(e){this.pinHighlighterClass$.next(e)}setTextHighlighterClass(e){this.textHighlighterClass$.next(e)}getTextHighlighterClass(){return this.textHighlighterClass$.asObservable()}enableCommentPinHighlighter(){this.commentPinHighlighter$.next(!0)}disableCommentPinHighlighter(){this.commentPinHighlighter$.next(!1)}getCommentPinHighlighter$(){return this.commentPinHighlighter$.asObservable()}getCommentPinHighlighter(){return this.commentPinHighlighter$?.value}highlightElement(e,i,r){if(e){if(!r&&this.getCommentPinHighlighter()&&(this.pinHighlighterClass$.value?this.addClassToElement(e,this.pinHighlighterClass$.value):this.addClassToElement(e,U.SNIPPYLY_HIGHLIGHT)),i&&!e.hasAttribute(U.ATTRIBUTES.DEFAULT_CURSOR)){let a=e.style.getPropertyValue("cursor"),s=e.style.getPropertyPriority("cursor"),c=a?{defaultCursorValue:a,defaultCursorPriority:s}:"";e.setAttribute(U.ATTRIBUTES.DEFAULT_CURSOR,c?JSON.stringify(c):""),e.style.setProperty("cursor",i,"important")}e.setAttribute(U.SNIPPYLY_HIGHLIGHT,"true"),e.setAttribute(U.VELT_IGNORE_CHANGE_DETECTION,"true")}}removeHighlightFromElement(e){if(e&&(this.pinHighlighterClass$.value&&this.removeClassFromElement(e,this.pinHighlighterClass$.value),this.removeClassFromElement(e,U.SNIPPYLY_HIGHLIGHT),e.removeAttribute(U.SNIPPYLY_HIGHLIGHT),e.removeAttribute(U.VELT_IGNORE_CHANGE_DETECTION),e.hasAttribute(U.ATTRIBUTES.DEFAULT_CURSOR))){try{if(e.style.removeProperty("cursor"),e.getAttribute(U.ATTRIBUTES.DEFAULT_CURSOR)){let i=JSON.parse(e.getAttribute(U.ATTRIBUTES.DEFAULT_CURSOR));e.style.setProperty("cursor",i.defaultCursorValue,i.defaultCursorPriority)}}catch{}e.removeAttribute(U.ATTRIBUTES.DEFAULT_CURSOR)}}highlightUserElement(e,i,r,a=!1){try{e&&(this.addClassToElement(e,U.VELT_LIVE_SELECTION_ON_ELEMENT),a&&this.addClassToElement(e,U.VELT_LIVE_SELECTION_ON_ELEMENT_DEFAULT),e.setAttribute(U.SNIPPYLY_HIGHLIGHT,"true"),e.setAttribute(U.VELT_IGNORE_CHANGE_DETECTION,"true"),i&&!e.style.getPropertyValue(U.VELT_SELECTION_COLOR)&&e.style.setProperty(U.VELT_SELECTION_COLOR,i),r&&e.setAttribute(U.SNIPPYLY_HIGHLIGHT_USER_NAME,r))}catch(s){this.loggingService.catch("Error in DomService highlightUserElement: ",s)}}removeHighlightUserFromElement(e){try{e&&(this.removeClassFromElement(e,U.VELT_LIVE_SELECTION_ON_ELEMENT),this.removeClassFromElement(e,U.VELT_LIVE_SELECTION_ON_ELEMENT_DEFAULT),e.removeAttribute(U.SNIPPYLY_HIGHLIGHT),e.removeAttribute(U.VELT_IGNORE_CHANGE_DETECTION),e.removeAttribute(U.VELT_SELECTION_COLOR),e.removeAttribute(U.SNIPPYLY_HIGHLIGHT_USER_NAME),e.style.removeProperty(U.VELT_SELECTION_COLOR))}catch(i){this.loggingService.catch("Error in DomService removeHighlightUserFromElement: ",i)}}previewHighlightElement(e){e&&e.setAttribute(U.SNIPPYLY_HIGHLIGHT_PREVIEW,"true")}removePreviewHighlightFromElement(e){e&&e.removeAttribute(U.SNIPPYLY_HIGHLIGHT_PREVIEW)}getXPath(e,i=!1,r=!1,a){try{let s=this.calculateXPath(e,i,r,a);if(s&&typeof s=="string"&&s.includes("/svg")){let c=s.split("/"),p=!1;c.forEach((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,i,r,a){try{if(e){if(typeof e=="string")return document.evaluate(e,a||document,this.namespaceResolver,XPathResult.ANY_TYPE,null);if(!e||e.nodeType!=1)return"";if(e.id&&document.querySelectorAll(`[id='${e.id}']`)?.length===1&&!i)return"//*[@id='"+e.id+"']";if(r&&e.className&&e.className.split){let c=e.className?.split(" ")?.filter(p=>!p?.includes("snippyly")&&!p?.includes("velt")&&!["show-pin-cursor"].includes(p))[0];if(c){let p=this.calculateXPath(e.parentNode,i,r,a)+"/"+e.tagName.toLowerCase(),u=Array.from(e.parentNode?.children||[]).filter(C=>C.nodeType===1&&C.tagName===e.tagName?C.className?.split(" ")?.filter(A=>A?.includes("snippyly")||A?.includes("velt")||["show-pin-cursor"].includes(A))[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,i,r)+"/"+e.tagName.toLowerCase()+(s.length>1?"["+([].indexOf.call(s,e)+1)+"]":"")}}catch(s){this.loggingService.catch("Error in DomService calculateXPath:",s)}}getElementFromXPath(e,i=document){try{if(this.xpathCache.has(e)){let a=this.xpathCache.get(e);if(a!==void 0&&document.contains(a))return a;this.xpathCache.delete(e)}let r=this.getXPath(e,!1,!1,i);if(r){let a=r?.iterateNext();if(a!==null&&typeof a.setAttribute=="function"){let s=wn();a.setAttribute(U.ATTRIBUTES.VELT_ELEMENT_CACHE_ID,s),this.xpathCacheId.set(s,e)}return this.xpathCache.set(e,a),a}return null}catch(r){return this.loggingService.catch("Error in DomService getElementFromXPath:",r),null}}calculateScreenSize(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowResize","color: green;");try{let e=[document?.body?.clientHeight||0,document?.documentElement?.clientHeight||0,window?.innerHeight||0],i=[document?.body?.clientWidth||0,document?.documentElement?.clientWidth||0,window?.innerWidth||0];this.calculatePageScrollHeight(),this.loggingService.log(this.pageScrollHeight),this.loggingService.log(this.nodeMap),this.highestNode=this.nodeMap[this.pageScrollHeight];let r=new GS;return r.screenWidth=Math.max(...i),r.screenHeight=Math.max(...e),r.screenScrollHeight=this.pageScrollHeight,r}catch(e){return this.loggingService.catch("Error in DomService calculateScreenSize:",e),new GS}}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(i){return this.loggingService.catch("Error in DomService removeSnippylyContent: ",i),e}}mergeAdjacentTextNodes(e){try{let i=e.firstChild;for(;i;){if(i.nodeType===Node.TEXT_NODE){let r=i.nextSibling;for(;r&&r.nodeType===Node.TEXT_NODE;)i.textContent+=r.textContent,r.remove(),r=i.nextSibling}i=i.nextSibling}}catch(i){this.loggingService.catch("Error in DomService mergeAdjacentTextNodes: ",i)}}findLongestNode(e){try{for(let i=e.length-1;i>=0;i--){if(e[i]?.scrollHeight&&e[i]?.clientHeight){let r=Math.max(e[i]?.scrollHeight,e[i]?.clientHeight);this.pageScrollHeight=Math.max(r,this.pageScrollHeight),this.nodeMap[r]=e[i]}e[i]?.childNodes?.length&&this.findLongestNode(e[i]?.childNodes)}}catch(i){this.loggingService.catch("Error in DomService findLongestNode: ",i)}}resetSelectedAnnotationsMap(e=!0,i){try{let r=Array.from(document.querySelectorAll(`[${U.ATTRIBUTES.VELT_ANNOTATION_DRAFT}]`)),a=this.getDraftCommentAnnotationDialogs()||[];r.push(...a),r=Array.from(new Set(r));let s=r.map(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(U.ATTRIBUTES.VELT_ANNOTATION_EDIT_COMMENT)||C.classList.contains("velt-annotation-draft-checked")||this.addClassToElement(C,"velt-annotation-draft-checked")},100),C.getAttribute(U.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 A=p[E];A?.to?.length||s.includes(E)||C.push(A)}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]),i)switch(i){case"comment":["comment","videoPin"].includes(p[C]?.type)||(u[C]=p[C]);break;default:p[C]?.type!==i&&(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,i){try{if(i)this.recordingInProgress$.next(T(I({},this.recordingInProgress$.value),{[e]:i}));else{let r=this.recordingInProgress$.value;delete r[e],this.recordingInProgress$.next(r)}}catch(r){this.loggingService.catch("Error in DomService setRecordingInProgress: ",r)}}resetRecordingInProgress(){try{this.recordingInProgress$.next({})}catch(e){this.loggingService.catch("Error in DomService resetRecordingInProgress: ",e)}}getRecordingInProgress(){try{return this.recordingInProgress$.value}catch(e){return this.loggingService.catch("Error in DomService getRecordingInProgress: ",e),{}}}getDraftCommentAnnotationDialogs(){try{let e=[];return Array.from(document.querySelectorAll(`${U.TAGS.SNIPPYLY_COMMENT_DIALOG}`)).forEach(r=>{if(r?.shadowRoot){let a=r.shadowRoot.querySelector(`[${U.ATTRIBUTES.VELT_ANNOTATION_DRAFT}]`);a&&e.push(a)}else{let a=r.querySelector(`${U.TAGS.VELT_SHADOW_DOM_INTERNAL}`);if(a?.shadowRoot){let s=a.shadowRoot?.querySelector(`[${U.ATTRIBUTES.VELT_ANNOTATION_DRAFT}]`);s&&e.push(s)}else{let s=r.querySelector(`[${U.ATTRIBUTES.VELT_ANNOTATION_DRAFT}]`);s&&e.push(s)}}}),e}catch(e){return this.loggingService.catch("Error in DomService getDraftCommentAnnotationDialogs: ",e),[]}}getSelectedAnnotationsMap(e){try{let i=this.selectedAnnotationsMap$.value;if(e){let r={};return Object.keys(i).forEach(a=>{switch(e){case"comment":["comment","videoPin"].includes(i[a].type)&&(r[a]=i[a]);break;default:i[a].type===e&&(r[a]=i[a]);break}}),r}else return i}catch(i){return this.loggingService.catch("Error in DomService getSelectedAnnotationsMap: ",i),{}}}getSelectedAnnotationsMap$(e){return this.selectedAnnotationsMap$.asObservable().pipe(ce(i=>{if(e){let r={};return Object.keys(i).forEach(a=>{i[a].type===e&&(r[a]=i[a])}),r}else return i}))}getSelectedComments$(){return this.selectedAnnotationsMap$.asObservable().pipe(ce(e=>Object.values(e)))}getSelectedAnnotationsLocationMap(){try{return this.selectedAnnotationsLocationMap$.value}catch(e){return this.loggingService.catch("Error in DomService getSelectedAnnotationsLocationMap: ",e),{}}}getSelectedAnnotationsLocationMap$(){return this.selectedAnnotationsLocationMap$.asObservable()}toggleAnnotationSelection(e,i,r,a=!1){try{r==="sidebarShowReplies"?this.setDialogOpenedInSidebar(!0):this.setDialogOpenedInSidebar(!1);let s=JSON.parse(JSON.stringify(this.selectedAnnotationsMap$.value||{})),c=JSON.parse(JSON.stringify(this.selectedAnnotationsLocationMap$.value||{}));if(s[e.annotationId]&&!a)delete s[e.annotationId];else{(!this.windowKeydownShift$.value||a)&&(s={}),s[e.annotationId]=e,c[e.annotationId]=i;let p=e?.multiThreadAnnotationId;p&&(s[p]={annotationId:p,type:"multiThread"},c[p]=i)}this.selectedAnnotationsMap$.next(s),Object.keys(c).forEach(p=>{s[p]||delete c[p]}),this.selectedAnnotationsLocationMap$.next(c)}catch(s){this.loggingService.catch("Error in DomService toggleAnnotationSelection: ",s)}}setSelectedAnnotationLocation(e,i){try{let r=JSON.parse(JSON.stringify(this.getSelectedAnnotationsLocationMap()||{}));r?.[e]!==i&&(r[e]=i,this.selectedAnnotationsLocationMap$.next(r))}catch(r){this.loggingService.catch("Error in DomService setSelectedAnnotationLocation: ",r)}}updateSelectedAnnotationInMap(e){try{let i=this.selectedAnnotationsMap$.value;e.forEach(r=>{i[r.annotationId]&&(i[r.annotationId]=r)}),this.selectedAnnotationsMap$.next(i)}catch(i){this.loggingService.catch("Error in DomService updateSelectedAnnotationInMap: ",i)}}getDeleteCommmentAnnotations$(){try{return this.deleteAnnotations$.asObservable()}catch(e){return this.loggingService.catch("Error in DomService getDeleteCommmentAnnotations$: ",e),re([])}}getHighestNode(){return this.loggingService.log("%c[WB] Calling FUNCTION: getHighestNode","color: green;"),this.highestNode}onWindowMouseDown$(){return this.windowMouseDown$.asObservable()}onWindowPointerMove$(){return this.windowPointerMove$.asObservable()}onWindowPointerMove(){return this.windowPointerMove$.value}onWindowPointerUp$(){return this.windowPointerUp$.asObservable()}onSelectionChange$(){return this.documentSelectionChange$.asObservable()}onWindowClick$(){return this.windowClick$.asObservable()}onWindowScroll$(){return this.windowScroll$.asObservable()}onWindowResize$(){return this.windowResize$.asObservable()}onWindowKeyupBackspace$(){return this.windowKeyupBackspace$.asObservable()}onWindowKeyupDelete$(){return this.windowKeyupDelete$.asObservable()}onWindowKeyupEsc$(){return this.windowKeyupEsc$.asObservable()}onWindowPopState$(){return this.windowPopState$.asObservable()}onDocumentClick$(){return this.documentClick$.asObservable()}getLastDocumentClick(){return this.documentClick$.value}onDocumentClickSubject$(){return this.documentClickSubject$.asObservable()}onDocumentFocus$(){return this.documentFocus$.asObservable()}onDomChange$(e){try{return this.mutationObserver||this.setMutationObserver(e),this.mutation$.asObservable()}catch(i){return this.loggingService.catch("Error in DomService onDomChange$: ",i),re([])}}getChildListMutation$(){return this.childListMutation$.asObservable()}onNetworkStatusChange$(){return this.networkStatus$.asObservable()}getElementOffset(e,i){try{let r={offsetTop:0,offsetLeft:0},a=e;if(a===i){let s=window.getComputedStyle(e);s.position==="static"&&s.transformStyle!="preserve-3d"&&s.transform=="none"&&(r.offsetLeft=e?.offsetLeft||0,r.offsetTop=e?.offsetTop||0)}if(a!==i)if(e?.closest("svg"))for(;a&&a!==i;){let c=window.getComputedStyle(a);if(a.tagName.toLowerCase()==="svg"||a instanceof SVGElement){let p=a.parentElement;if(p){let 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===i){let p=window.getComputedStyle(a);p.position==="static"&&p.transformStyle!="preserve-3d"&&p.transform=="none"&&(r.offsetLeft+=a?.offsetLeft||0,r.offsetTop+=a?.offsetTop||0)}}else{let c=window.getComputedStyle(a);c.position==="static"?c.transformStyle!="preserve-3d"&&c.transform=="none"&&(r.offsetLeft+=a?.offsetLeft||0,r.offsetTop+=a?.offsetTop||0):(r.offsetLeft+=a.offsetLeft,r.offsetTop+=a.offsetTop)}return r}catch(r){return this.loggingService.catch("Error in DomService getElementOffset: ",r),{offsetTop:0,offsetLeft:0}}}isElementVisible(e){try{if(typeof e?.getBoundingClientRect=="function"){let{width:i,height:r,top:a,bottom:s}=e?.getBoundingClientRect();return i>0||r>0||a<window.innerHeight&&s>0}else return!1}catch(i){return this.loggingService.catch("Error in DomService isElementVisible: ",i),!1}}isElementVisibleOnScreen(e){try{if(e){if(!(e instanceof Element))return!1;let i=e,r=window.getComputedStyle(i);return!(r.display==="none"||r.visibility==="hidden"||parseFloat(r.opacity)===0)}return!1}catch(i){return this.loggingService.catch("Error in DomService isElementVisibleOnScreen: ",i),!1}}getClickAndDragPointsObservable(){return new Lt(e=>{let i=ri(document,"mousedown").pipe(ce(p=>({type:p.type,x:p.clientX+window.scrollX,y:p.clientY+window.scrollY,event:p}))),r=ri(document,"mousemove").pipe(ce(p=>({type:p.type,x:p.clientX+window.scrollX,y:p.clientY+window.scrollY,event:p}))),a=ri(document,"mouseup").pipe(ce(p=>({type:p.type,x:p.clientX+window.scrollX,y:p.clientY+window.scrollY,event:p}))),c=i.pipe(ue(p=>r.pipe(Ai(),ce(([u,C])=>({startPoint:p,prevPoint:u,curPoint:C})),ro(a)))).subscribe(e);return()=>c.unsubscribe()})}drawRectangle(e,i){let r=document.querySelector(".rectangle");r||(r=document.createElement("div"),this.addClassToElement(r,"rectangle"),r.setAttribute(U.ATTRIBUTES.VELT_COMMENT_DISABLED,"true"),r.setAttribute(U.VELT_IGNORE_CHANGE_DETECTION,"true"),document.body.appendChild(r));let a=Math.abs(i.x-e.x),s=Math.abs(i.y-e.y),c=Math.min(e.x,i.x),p=Math.min(e.y,i.y);return r.style.width=`${a}px`,r.style.height=`${s}px`,r.style.left=`${c}px`,r.style.top=`${p}px`,r.style.position="absolute",r.style.border="2px dashed #f00",r.style.pointerEvents="none",r.style.zIndex="2147483577",r}getRange(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: getRange","color: green;"),window.getSelection()?.toString()){let e=window.getSelection();if(e?.rangeCount)return e.getRangeAt(0)}return null}catch(e){return this.loggingService.catch("Error in DomService getRange: ",e),null}}clearTextSelection(){try{this.loggingService.log("%c[WB] Calling FUNCTION: clearTextSelection","color: green;"),window.getSelection&&(window.getSelection()?.empty?window.getSelection()?.empty():window.getSelection()?.removeAllRanges&&window.getSelection()?.removeAllRanges())}catch(e){this.loggingService.catch("Error in DomService clearTextSelection: ",e)}}getTargetTextRangeFromSelectionRange(e){try{let i={},r=e.commonAncestorContainer;r?.nodeType===Node.TEXT_NODE&&(r=r.parentElement);let a=document.body;if(r){let c=this.getTextXPath(r);this.isXpathWithId(c)&&(a=r)}let s=this.getAdditionalLocationContainer(r);if(s&&(a=s),i.commonAncestorContainer=this.getTextXPath(a),i.commonAncestorContainer){let c=this.getElementFromXPath(i.commonAncestorContainer);c&&(i.commonAncestorContainerFXpath=this.getXPath(c,!0),i.commonAncestorContainerCFXpath=this.getXPath(c,!0,!0))}return i.text=e.toString(),i.occurrence=Lu(a,0,e.startContainer,e.startOffset,e.toString())+1,i}catch(i){this.loggingService.catch("Error in DomService getTargetTextRangeFromSelectionRange: ",i);return}}getTextXPath(e){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: getTextXPath","color: green;"),e.nodeType===Node.TEXT_NODE){let i=1,r=e.previousSibling;for(;r;)r.nodeType===Node.TEXT_NODE&&i++,r=r.previousSibling;return this.getXPath(e.parentElement)}else return this.getXPath(e)}catch(i){this.loggingService.catch("Error in DomService getTextXPath: ",i);return}}getHostElement(e){try{if(U.NON_NESTABLE_ELEMENTS[e?.tagName?.toLowerCase()]){let r=e?.closest("picture");return r?r?.parentElement:e.parentElement}let i=e.closest("svg");return i?i?.parentElement:e}catch(i){return this.loggingService.catch("Error in DomService getHostElement: ",i),e}}isElementInsideAdditionalLocationContainer(e){try{return!!e?.closest(`[${U.ATTRIBUTES.VELT_LOCATION}], [${U.ATTRIBUTES.VELT_LOCATION_ID}]`)}catch(i){return this.loggingService.catch("Error in DomService isElementInsideAdditionalLocationContainer: ",i),!1}}getAdditionalLocationContainer(e){try{return e?.closest(`[${U.ATTRIBUTES.VELT_LOCATION}], [${U.ATTRIBUTES.VELT_LOCATION_ID}]`)||null}catch(i){return this.loggingService.catch("Error in DomService getAdditionalLocationContainer: ",i),null}}isXpathWithId(e){try{return typeof e=="string"?!!e?.includes("[@id="):!1}catch(i){return this.loggingService.catch("Error in DomService isXpathWithId: ",i),!1}}getListedElements({elementIds:e,elementClassNames:i,elementQuerySelectors:r}){try{let a=[];if(e?.length)for(let s=0;s<e.length;s++){let c=document.getElementById(e[s]);c&&a.push(c)}if(i?.length)for(let s=0;s<i.length;s++){let c=document.getElementsByClassName(i[s]);for(let p=0;p<c.length;p++){let 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,i){try{if(i?.length){for(let r=0;r<i.length;r++){let a=document.getElementById(i[r]);if(a&&a.contains(e))return!0}return!1}return!0}catch(r){return this.loggingService.catch("Error in DomService isElementInsideListedElementIds: ",r),!1}}isElementInsideListedElementClassNames(e,i){try{if(i?.length){for(let r=0;r<i.length;r++){let a=document.getElementsByClassName(i[r]);for(let s=0;s<a.length;s++)if(a[s].contains(e))return!0}return!1}return!0}catch(r){return this.loggingService.catch("Error in DomService isElementInsideListedElementClassNames: ",r),!1}}isElementInsideListedElementQuerySelectors(e,i){try{if(i?.length){for(let r=0;r<i.length;r++){let a=document.querySelectorAll(i[r]);for(let s=0;s<a.length;s++)if(a[s].contains(e))return!0}return!1}return!0}catch(r){return this.loggingService.catch("Error in DomService isElementInsideListedElementQuerySelectors: ",r),!1}}addClassToElement(e,i){try{this.loggingService.log("%c[WB] Calling FUNCTION: addClassToElement","color: green;"),e&&(e.classList?.contains(i)||e.classList?.add(i))}catch(r){this.loggingService.catch("Error in DomService addClassToElement: ",r)}}removeClassFromElement(e,i){try{this.loggingService.log("%c[WB] Calling FUNCTION: removeClassFromElement","color: green;"),e&&e.classList?.contains(i)&&e.classList?.remove(i)}catch(r){this.loggingService.catch("Error in DomService removeClassFromElement: ",r)}}isElementInsideParentWithAttribute(e,i,r){try{let a=e;for(;a&&a!==document.body;){if(a?.getAttribute&&a?.getAttribute(i)===r)return!0;a=a.parentElement}return!1}catch(a){return this.loggingService.catch("Error in DomService isElementInsideParentWithAttribute: ",a),!1}}setVideoEditorHandlingDelete(e){try{this.isVideoEditorHandlingDelete=e}catch(i){this.loggingService.catch("Error in DomService setVideoEditorHandlingDelete: ",i)}}isVideoEditorHandlingDeleteKey(){try{return this.isVideoEditorHandlingDelete}catch(e){return this.loggingService.catch("Error in DomService isVideoEditorHandlingDeleteKey: ",e),!1}}setCustomCss(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setCustomCss","color: green;"),this.customCss$.next(e)}catch(i){this.loggingService.catch("Error in DomService setCustomCss: ",i)}}getCustomCss$(){try{return this.loggingService.log("%c[WB] Calling FUNCTION: getCustomCss$","color: green;"),this.customCss$.asObservable()}catch(e){return this.loggingService.catch("Error in DomService getCustomCss$: ",e),re(null)}}injectCustomCss(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: injectCustomCss","color: green;");let i=this.customCss$.value;if(i){let r=e?.shadowRoot?.querySelector(`[${U.VELT_CUSTOM_CSS}]`);if(r&&r.remove(),i?.type==="link"){let a=document.createElement("link");a.href=i?.value,a.rel="stylesheet",a.setAttribute(U.VELT_CUSTOM_CSS,"true"),e?.shadowRoot?.appendChild(a)}else{let a=document.createElement("style");a.innerHTML=this.sanitizeHtml(i?.value),a.setAttribute(U.VELT_CUSTOM_CSS,"true"),e?.shadowRoot?.appendChild(a)}}}catch(i){this.loggingService.catch("Error in DomService injectCustomCss: ",i)}}trimCommentHtml(e){try{let i=document.createElement("div");i.innerHTML=e,this.removeEmptyElements(i);let r=i.innerHTML;return r=r.replace(o.MULTIPLE_NBSP_REGEX," ").replace(o.TRIM_NBSP_REGEX,"").trim(),r}catch(i){return this.loggingService.catch("Error in DomService trimCommentHtml: ",i),e}}removeEmptyElements(e){try{let a=function(s){return r.test(s.innerHTML)};var i=a;let r=/^\s*(<br\s*\/?>)?\s*$/;for(;e.firstChild&&a(e.firstChild);)e.removeChild(e.firstChild);for(;e.lastChild&&a(e.lastChild);)e.removeChild(e.lastChild)}catch(r){this.loggingService.catch("Error in DomService removeEmptyElements: ",r)}}normalizeWhitespace(e){try{e.childNodes.forEach(i=>{i.nodeType===Node.TEXT_NODE?i.nodeValue=i.nodeValue?.replace(/\s+/g," ").trim()??"":i.nodeType===Node.ELEMENT_NODE&&this.normalizeWhitespace(i)})}catch(i){this.loggingService.catch("Error in DomService normalizeWhitespace: ",i)}}sanitizeHtml(e){try{return this.loggingService.log("%c[WB] Calling FUNCTION: sanitizeHtml","color: green;"),M$.sanitize(e,Ase)}catch(i){return this.loggingService.catch("Error in DomService sanitizeHtml: ",i),""}}sanitizeSvg(e){try{return M$.sanitize(e,Ase)}catch(i){return this.loggingService.catch("Error in DomService sanitizeSvg: ",i),e}}setDeviceInfo(){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDeviceInfo","color: green;");let e=new ei;this.deviceInfo$.next(e)}catch(e){this.loggingService.catch("Error in DomService setDeviceInfo: ",e)}}getDeviceInfo$(){try{return this.loggingService.log("%c[WB] Calling FUNCTION: getDeviceInfo$","color: green;"),this.deviceInfo$.asObservable()}catch(e){return this.loggingService.catch("Error in DomService getDeviceInfo$: ",e),re(new ei)}}getTabId(){try{let e=sessionStorage.getItem(U.SESSION_STORAGE.VELT_TAB_ID),i=this.getTabIdFromWindowName();return(!e||e!==i)&&(e=wn(),sessionStorage.setItem(U.SESSION_STORAGE.VELT_TAB_ID,e),this.setTabIdToWindowName(e)),e}catch(e){return this.loggingService.catch("Error in DomService getTabId: ",e),null}}getTabIdFromWindowName(){try{return window.name}catch(e){return this.loggingService.catch("Error in DomService getTabIdFromWindowName: ",e),null}}setTabIdToWindowName(e){try{window.name=e}catch(i){this.loggingService.catch("Error in DomService setTabIdToWindowName: ",i)}}getDeviceInfo(){try{return this.loggingService.log("%c[WB] Calling FUNCTION: getDeviceInfo","color: green;"),this.deviceInfo$.value}catch(e){return this.loggingService.catch("Error in DomService getDeviceInfo: ",e),new ei}}isMobileDevice(){try{return new ei().getDeviceType()===Xo.MOBILE}catch(e){return this.loggingService.catch("Error in DomService isMobileDevice: ",e),!1}}isTabletDevice(){try{return new ei().getDeviceType()===Xo.TABLET}catch(e){return this.loggingService.catch("Error in DomService isTabletDevice: ",e),!1}}isDesktopDevice(){try{return new ei().getDeviceType()===Xo.DESKTOP}catch(e){return this.loggingService.catch("Error in DomService isDesktopDevice: ",e),!1}}deepCloneElement(e){try{var i=document.createElement(e?.tagName);return Array.from(e.attributes).forEach(r=>{i.setAttribute(r.nodeName,r.nodeValue)}),e.childNodes.forEach(r=>{r.nodeType===Node.ELEMENT_NODE?i.appendChild(this.deepCloneElement(r)):r.nodeType===Node.TEXT_NODE&&i.appendChild(document.createTextNode(r.nodeValue))}),i}catch(r){return this.loggingService.catch("Error in DomService deepCloneElement: ",r),e}}setRandomNumberToElementRecursive(e){try{if(!e)return;let i=Math.random().toString(36).substring(7);e&&e.setAttribute&&typeof e.setAttribute=="function"&&(e.getAttribute("velt-wireframe-id")||e.setAttribute("velt-wireframe-id",i)),Array.from(e.children).forEach(a=>{this.setRandomNumberToElementRecursive(a)})}catch(i){this.loggingService.catch("Error in DomService setRandomNumberToElementRecursive: ",i)}}setDialogOpenedInSidebar(e){this.dialogOpenedInSidebar$.next(e)}getDialogOpenedInSidebar(){return this.dialogOpenedInSidebar$.asObservable()}removeWireframeSuffixFromTags(e){if(!e)return;Array.from(e.children).forEach(r=>{if(this.removeWireframeSuffixFromTags(r),r.tagName.toLowerCase().endsWith("-wireframe")){let a=r.tagName.toLowerCase().replace("-wireframe",""),s=document.createElement(a);for(Array.from(r.attributes).forEach(c=>{s.setAttribute(c.name,c.value)});r.firstChild;)s.appendChild(r.firstChild);r.parentNode.replaceChild(s,r)}})}isMonitorDevice(){try{return new ei().getDeviceType()===Xo.MONITOR}catch(e){return this.loggingService.catch("Error in DomService isMonitorDevice: ",e),!1}}};o.MULTIPLE_NBSP_REGEX=/(?: \s*){2,}/g,o.TRIM_NBSP_REGEX=/^(?: \s*)+|(?: \s*)+$/g,o.\u0275fac=function(i){return new(i||o)(Q(Yo),Q(y),Q(Rs))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var je=(()=>{let o=class o{constructor(e,i,r,a,s,c,p,u){this.afAuth=e,this.configService=i,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 Do,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.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(U.LOCAL_STORAGE.VELT_USER_FORCE_RE_LOGGED_IN)==="true",this.sessionReLoginSubscription=qn(this.afAuth).pipe(Wo(this.afAuth.currentUser),Ai(),ue(([C,E])=>this.domService.onNetworkStatusChange$().pipe(Ne(A=>A),et(1),ce(()=>({previousUser:C,currentUser:E}))))).subscribe(A=>te(this,[A],function*({previousUser:C,currentUser:E}){if(!E&&C){let B=C?.stsTokenManager?.expirationTime,G=new Date().getTime(),K=B-G;G>B&&(this.analyticsService.trackEvent(X.Events.Core.SDK_SESSION_TOKEN_EXPIRED,{apiKey:this.apiKey,user:this.user$.value,lastLoggedInUserData:this.lastLoggedInUserData,timeLeft:K,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(X.Events.Core.SDK_SESSION_RE_LOGIN_COUNT_EXCEEDED,{apiKey:this.apiKey,clientUserId:this.lastLoggedInUserData.user.userId,snippylyUserId:this.lastLoggedInUserData.user.userSnippylyId,timeLeft:K,forceReset:this.userOptions$.value?.forceReset,sessionReLoginCount:this.sessionReLoginCount},!0,this.user$.value?.userSnippylyId),this.sessionReLoginSubscription?.unsubscribe()):(this.sessionReLoginCount++,this.analyticsService.trackEvent(X.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:K,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(qt(Vi)).subscribe(C=>{let E=ua(C);this.coreActionsService.triggerAction(Id.USER_UPDATE,E)})}catch(C){this.loggingService.catch("Error in AuthService constructor: ",C)}}setApiKey(e,i){this.loggingService.log("%c[WB] Calling FUNCTION: setApiKey","color: green;",e);try{if(this.apiKey){this.loggingService.log("API key is already set");return}this.apiKey=e,this.configService.setApiKey(this.apiKey),i||(i=new EM),this.configService.initConfig(i),i.debugMode?sessionStorage.setItem("debugMode","true"):sessionStorage.removeItem("debugMode"),this.autoLoginCalled||qn(this.afAuth).pipe(et(1)).subscribe(r=>te(this,null,function*(){if(this.autoLoginCalled=!0,r){let a=yield fd(r,!0).catch(s=>null);if(a){let{user:s}=a?.claims;this.autoLoginRequired&&this.initializeClient(s,this.userOptions$?.value?T(I({},this.userOptions$?.value),{replaceContacts:!1,replaceGroupContacts:!1,replacePrivateContacts:!1}):{},new Date().getTime(),!0,"internal-autoLogin")}}}))}catch(r){this.loggingService.catch("Error in setApiKey: ",r)}}setUsersService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setUsersService","color: green;"),this.usersService=e}catch(i){this.loggingService.catch("Error in setUsersService: ",i)}}setDocService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocService","color: green;"),this.docService=e}catch(i){this.loggingService.catch("Error in setDocService: ",i)}}setContactService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setContactService","color: green;"),this.contactService=e}catch(i){this.loggingService.catch("Error in setContactService: ",i)}}setIamService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setIamService","color: green;"),this.iamService=e}catch(i){this.loggingService.catch("Error in setIamService: ",i)}}setAreaService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setAreaService","color: green;"),this.areaService=e}catch(i){this.loggingService.catch("Error in setAreaService: ",i)}}setCommentService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setCommentService","color: green;"),this.commentService=e}catch(i){this.loggingService.catch("Error in setCommentService: ",i)}}setReactionService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setReactionService","color: green;"),this.reactionService=e}catch(i){this.loggingService.catch("Error in setReactionService: ",i)}}setRecorderAnnotationService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setRecorderAnnotationService","color: green;"),this.recorderAnnotationService=e}catch(i){this.loggingService.catch("Error in setRecorderAnnotationService: ",i)}}setViewsService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setViewsService","color: green;"),this.viewsService=e}catch(i){this.loggingService.catch("Error in setViewsService: ",i)}}setCommonDbService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setCommonDbService","color: green;"),this.commonDbService=e}catch(i){this.loggingService.catch("Error in setCommonDbService: ",i)}}validateOrganizationId(e){if(this.isVersionGreaterThanOrEqualTo4()&&!e?.organizationId)if(this.analyticsService.trackEvent(X.Events.Core.SDK_VALIDATE_CLIENT_FAILED,{apiKey:this.apiKey,clientUserId:e.userId,snippylyUserId:e.userSnippylyId,message:"Organization Id is not set",forceReset:this.userOptions$.value?.forceReset,user:this.getUserWithoutContacts(e)},!0,e.userSnippylyId),this.configService.getSF())this.loggingService.catch("OrganizationId is not set in Identify method",void 0,void 0,!0);else throw new Error("OrganizationId is not set in Identify method")}initializeClient(e,i,r,a,s){return te(this,null,function*(){try{if(this.autoLoginRequired=!1,this.userOptions$.next(i),this.initializeClientToken)this.pendingUserLogin=e,this.pendingUserLoginSource=s;else{e.userSnippylyId=gm(this.configService.getApiKey(),e.userId),this.pendingUserLogin=void 0,this.pendingUserLoginSource=void 0,this.initializeClientToken=r;let c=yield qn(this.afAuth).pipe(et(1)).toPromise().catch(u=>null),p=!0;if(this.providedUser=JSON.parse(JSON.stringify(e)),c){let u=yield fd(c,!0).catch(A=>null);if(!u)return;let{user:C,firebaseConfig:E}=u.claims;if(c?.uid!==e?.userSnippylyId||e?.groupId!==C?.groupId||e?.organizationId!==C?.organizationId||i?.forceReset||!a&&e?.organizationId&&!this.forceReLoggedIn||this.forceReLoginRequiredForAdvancedQueries(e)||this.forceReLoginRequiredForRegion(e,E))localStorage.setItem(U.LOCAL_STORAGE.VELT_USER_FORCE_RE_LOGGED_IN,"true"),this.forceReLoggedIn=!0,yield this.signOutUser("internal");else{this.loggingService.log("%c[WB] Calling FUNCTION: reinitializeCurrentUser","color: green;"),this.loggingService.log("Keeping user");let A=yield fd(c,!0).catch(pe=>null);if(!A)return;let{firebaseConfig:B,user:G,advancedQueries:K}=A.claims;this.validateOrganizationId(e),this.setFirebaseConfig(B),this.setAdvancedQueries(K),G&&(this.providedUser.isAdmin=!!G.isAdmin),this.initializeSignedInUser(c,a),p=!1,this.analyticsService.trackEvent(X.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(X.Events.Core.SDK_VALIDATE_CLIENT_TRIGGERED,{apiKey:this.apiKey,clientUserId:e.userId,snippylyUserId:e.userSnippylyId,forceReset:this.userOptions$.value?.forceReset,user:this.getUserWithoutContacts(e),source:s},!0,e.userSnippylyId);let u=_r(this.functions,Sr({url:Xn.cloudFunction.validateClient,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:20*60*1e3}),C=pa(),E=(yield u({apiKey:this.apiKey,user:e,version:C,authToken:i?.authToken}))?.data;if(E.error){if(this.analyticsService.trackEvent(X.Events.Core.SDK_VALIDATE_CLIENT_FAILED,{apiKey:this.apiKey,clientUserId:e.userId,snippylyUserId:e.userSnippylyId,message:E.error,forceReset:this.userOptions$.value?.forceReset,user:this.getUserWithoutContacts(e),source:s},!0,e.userSnippylyId),E.error&&typeof E.error=="string"&&E.error?.toLowerCase()?.includes("token expired"))if(this.tokenExpiredErrorCount++,this.tokenExpiredErrorCount<=this.TOKEN_EXPIRED_ERROR_COUNT_LIMIT){let A={code:"token_expired",message:"Token expired"};this.coreActionsService.triggerAction(Id.ERROR,A)}else{let A={code:"too_many_retries",message:"Token expired. Too many retries."};this.coreActionsService.triggerAction(Id.ERROR,A),this.analyticsService.trackEvent(X.Events.Core.SDK_JWT_EXPIRED_RETRY_EXCEEDED,{apiKey:this.apiKey,clientUserId:e.userId,snippylyUserId:e.userSnippylyId,forceReset:this.userOptions$.value?.forceReset,source:s},!0,e.userSnippylyId)}throw E.error}else this.tokenExpiredErrorCount=0;if(this.analyticsService.trackEvent(X.Events.Core.SDK_VALIDATE_CLIENT_SUCCESS,{apiKey:this.apiKey,clientUserId:e.userId,snippylyUserId:e.userSnippylyId,forceReset:this.userOptions$.value?.forceReset,user:this.getUserWithoutContacts(e),source:s},!0,e.userSnippylyId),this.validateOrganizationId(e),E.firebaseConfig){this.setFirebaseConfig(E.firebaseConfig),yield this.signInWithCustomToken(e,E.token),this.loggingService.log("new signed in user",this.afAuth.currentUser);let A=yield fd(this.afAuth.currentUser,!0).catch(K=>null);if(!A)return;let{user:B,advancedQueries:G}=A.claims;this.setAdvancedQueries(G),this.providedUser.isAdmin=!!B?.isAdmin,this.initializeSignedInUser(this.afAuth.currentUser,a)}}this.initializeClientToken=0,this.lastLoggedInUserData={user:e,userOptions:i,initializeClientToken:r,autoLogin:a},this.checkForPendingLogin()}return e}catch(c){return this.initializeClientToken=0,this.checkForPendingLogin(),this.loggingService.catch("Error in initializeClient: ",c),Promise.resolve(null)}})}isVersionGreaterThanOrEqualTo4(){try{let e=pa();return(e?parseInt(e.split(".")?.[0]||"0"):0)>=4}catch(e){return this.loggingService.catch("Error in isVersionGreaterThanOrEqualTo4: ",e),!1}}forceReLoginRequiredForAdvancedQueries(e){try{let i=this.isVersionGreaterThanOrEqualTo4(),r=!1;try{let a=localStorage.getItem(U.LOCAL_STORAGE.VELT_ADVANCED_QUERIES);a&&(r=JSON.parse(a)?.advancedQueriesEnabled)}catch(a){this.loggingService.catch("Error in forceReLoginRequiredForAdvancedQueries: ",a)}return!!(i&&e.organizationId&&!r)}catch(i){return this.loggingService.catch("Error in forceReLoginRequiredForAdvancedQueries: ",i),!1}}forceReLoginRequiredForRegion(e,i){try{return!!(this.isVersionGreaterThanOrEqualTo4()&&e.organizationId&&!i?.region)}catch(r){return this.loggingService.catch("Error in forceReLoginRequiredForRegion: ",r),!1}}checkForPendingLogin(){this.pendingUserLogin&&this.initializeClient(this.pendingUserLogin,this.userOptions$?.value||{},new Date().getTime(),void 0,this.pendingUserLoginSource)}setFirebaseConfig(e){this.loggingService.log("%c[WB] Calling FUNCTION: setFirebaseConfig","color: green;");try{this.firebaseConfig$.value||this.firebaseConfig$.next({firebaseOptions:I(I({},Xn.firebaseConfig),e)})}catch(i){this.loggingService.catch("Error in setFirebaseConfig: ",i)}}getFirebaseConfig$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getFirebaseConfig","color: green;"),this.firebaseConfig$.asObservable()}getFirebaseConfig(){return this.loggingService.log("%c[WB] Calling FUNCTION: getFirebaseConfig","color: green;"),this.firebaseConfig$.value}setAdvancedQueries(e){this.loggingService.log("%c[WB] Calling FUNCTION: setAdvancedQueries","color: green;");try{e&&typeof e=="object"&&localStorage.setItem(U.LOCAL_STORAGE.VELT_ADVANCED_QUERIES,JSON.stringify(e)),this.advancedQueries$.next(e)}catch(i){this.loggingService.catch("Error in setAdvancedQueries: ",i)}}getAdvancedQueries$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getAdvancedQueries$","color: green;"),this.advancedQueries$.asObservable()}getAdvancedQueries(){return this.loggingService.log("%c[WB] Calling FUNCTION: getAdvancedQueries","color: green;"),this.advancedQueries$.value}getAdvancedQueriesEnabled$(){return Mn([this.configService.getConfig$(),this.getAdvancedQueries$()]).pipe(ce(()=>this.getAdvancedQueriesEnabled()),Vn(()=>re(!1)))}getAdvancedQueriesEnabled(){try{return!this.configService.getConfig()?.advancedQueriesDisabled&&!!this.getAdvancedQueries()?.advancedQueriesEnabled}catch(e){return this.loggingService.catch("Error in getAdvancedQueriesEnabled: ",e),!1}}signOutPreviousUser(){return this.signOutPreviousUser$.asObservable()}getUser(){return this.loggingService.log("%c[WB] Calling FUNCTION: getUser","color: green;"),this.afAuth?.currentUser?this.user$.value:null}getUser$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getUser$","color: green;"),qn(this.afAuth).pipe(ue(e=>e?this.user$.asObservable():re(null)))}getAuthUser(){return this.loggingService.log("%c[WB] Calling FUNCTION: getAuthUser","color: green;"),this.afAuth?.currentUser}getUserOptions(){return this.loggingService.log("%c[WB] Calling FUNCTION: getUserOptions","color: green;"),this.userOptions$.value}getUserOptions$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getUserOptions$","color: green;"),this.userOptions$.asObservable()}updateUser(e){this.loggingService.log("%c[WB] Calling FUNCTION: updateUser","color: green;");try{let i=this.user$.value;if(e.userId&&e.userId!==i?.userId||e?.groupId&&e?.groupId!==i?.groupId||e?.organizationId&&e?.organizationId!==i?.organizationId)this.providedUser=e,this.initializeClient(e,this.userOptions$?.value||{},new Date().getTime(),void 0,"internal-updateUser");else if(this.providedUser=I(I({},this.providedUser),e),i){let r=I(I({},i),e);this.updateUserInternally(r)}}catch(i){this.loggingService.catch("Error in updateUser: ",i)}}signInWithCustomToken(e,i,r="manual"){this.loggingService.log("%c[WB] Calling FUNCTION: signInWithCustomToken","color: green;");try{return BQ(this.afAuth,i).then(a=>(this.analyticsService.trackEvent(X.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(X.Events.Core.SDK_USER_AUTH_FAILED,{apiKey:this.apiKey,clientUserId:e.userId,snippylyUserId:e.userSnippylyId,authType:r,forceReset:this.userOptions$.value?.forceReset,message:a.message,user:this.getUserWithoutContacts(e)}),a))}catch(a){return this.loggingService.catch("Error in signInWithCustomToken: ",a),Promise.reject(a)}}resetServicesCache(){this.loggingService.log("%c[WB] Calling FUNCTION: resetServicesCache in AuthService","color: green;");try{this.commonDbService?.unsubscribeFromObservables(),this.docService?.clearCache(),this.contactService?.clearCache(),this.iamService?.clearCache(),this.areaService?.clearCache(),this.commentService?.clearCache(),this.reactionService?.clearCache(),this.recorderAnnotationService?.clearCache(),this.viewsService?.clearCache()}catch(e){this.loggingService.catch("Error in resetServicesCache: ",e)}}initializeSignedInUser(e,i){this.loggingService.log("%c[WB] Calling FUNCTION: initializeSignedInUser","color: green;");try{let r=new Do;r.userSnippylyId=e.uid,r.type="signedIn",this.mergeUserWithProvidedUserData(r,i)}catch(r){this.loggingService.catch("Error in initializeSignedInUser: ",r)}}mergeUserWithProvidedUserData(e,i){return te(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: mergeUserWithProvidedUserData","color: green;");try{e.userId=this.providedUser?.userId||e.userId;let r=null;if(this.usersService?.userDataProviderAvailable()){let a=yield this.usersService.resolveUsers([e.userId]);a&&a[e.userId]&&(r=JSON.parse(JSON.stringify(a[e.userId]||{}))),e=I(I({},e),r||{})}e.name=r?r?.name:this.providedUser?.name||e.name,e.clientUserName=r?r?.clientUserName:this.providedUser?.clientUserName||e.clientUserName,e.photoUrl=r?r?.photoUrl:this.providedUser?.photoUrl||e.photoUrl,e?.photoUrl===void 0&&(e.photoUrl=null),e.email=r?r?.email:this.providedUser?.email||e.email,e.color=r?r?.color:this.providedUser?.color||this.avatarService.generateUserColor(Cn(e.userId)),e.textColor=r?r?.textColor:this.providedUser?.textColor||"#FFFFFF",e.initial=r?r?.initial:this.providedUser?.initial||e.initial||e.name?.charAt(0).toUpperCase()||e.email?.charAt(0).toUpperCase(),e.contacts=this.providedUser?.contacts||e.contacts,e.plan=this.providedUser?.plan||e.plan,e.groupId=this.providedUser?.groupId||e.groupId,e.clientGroupId=this.providedUser?.clientGroupId||e.clientGroupId,e.clientOrganizationId=this.providedUser?.clientOrganizationId||e.clientOrganizationId,e.organizationId=this.providedUser?.organizationId||e.organizationId,e.isAdmin=this.providedUser?.isAdmin,e.isReadOnly=this.providedUser?.isReadOnly,e.isAnonymous=this.providedUser?.isAnonymous,e.isGuest=this.providedUser?.isGuest,this.updateUserInternally(e)}catch(r){this.loggingService.catch("Error in mergeUserWithProvidedUserData: ",r)}})}updateUserInternally(e){return te(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: updateUserInternally","color: green;");try{let i=Object.assign({},e);delete i.contacts,this.analyticsService.identifyUser(e.userSnippylyId,i,{forceReset:this.userOptions$.value?.forceReset}),this.getPlanDetailsCalled||(yield this.getPlanDetailsFromDb()),this.afAuth.currentUser&&(this.user$.next(e),this.updateUserToFirebase(e))}catch(i){this.loggingService.catch("Error in updateUserInternally: ",i)}})}updateUserToFirebase(e){this.loggingService.log("%c[WB] Calling FUNCTION: updateUserToFirebase","color: green;");try{let i=JSON.parse(JSON.stringify(e)),r=T(I({},i),{lastUpdated:new Date})}catch(i){this.loggingService.catch("Error in updateUserToFirebase: ",i)}}getPlanDetailsFromDb(){return te(this,null,function*(){try{this.getPlanDetailsCalled=!0;let i=yield _r(this.functions,Sr({url:Xn.cloudFunction.getPlanDetails,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:20*60*1e3})({apiKey:this.configService.getApiKey(),sdkVersion:pa(),sdkType:this.configService.getSdkType()});return i?.data?.isPlanExpired&&(this.analyticsService.trackEvent(X.Events.Core.SDK_PLAN_EXPIRED),this.configService.getSF()||console.warn("Velt SDK plan has expired.")),this.planDetails$.next(i?.data||{planInfo:null,isPlanExpired:!1}),i}catch(e){return this.loggingService.catch("Error in getPlanDetailsFromDb: ",e),this.planDetails$.next({planInfo:null,isPlanExpired:!1}),Promise.resolve(null)}})}isPlanExpired$(){return this.planDetails$.pipe(Ne(e=>!!e),ce(e=>!!e?.isPlanExpired))}isPlanExpired(){return this.planDetails$.getValue()?.isPlanExpired}addPreSignOutFuction(e,i){try{this.preSignOutFunctions.set(e,i)}catch(r){this.loggingService.catch("Error in addPreSignOutFuction: ",r)}}setUserOrganization(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setUserOrganization","color: green;");let i=JSON.parse(JSON.stringify(this.userOrganization$.value||{}));this.getUser()?.organizationId===e?.organizationId?(i.metadata=e,this.userOrganization$.next(i)):this.userOrganization$.next(null)}catch(i){this.loggingService.catch("Error in setUserOrganization: ",i)}}setOrganizationUserGroups(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setUserOrganizationGroups","color: green;");let i=JSON.parse(JSON.stringify(this.userOrganization$.value||{}));this.getUser()?.organizationId===i?.metadata?.organizationId&&(i.groups=e,this.userOrganization$.next(i))}catch(i){this.loggingService.catch("Error in setUserOrganizationGroups: ",i)}}getUserOrganization$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getUserOrganization$","color: green;"),this.getUser$().pipe(ue(e=>e?this.userOrganization$.asObservable().pipe(ce(i=>i?.metadata?.organizationId===e.organizationId?i:null)):re(null)))}signOutUser(e="internal"){return te(this,null,function*(){try{yield this.analyticsService.trackEvent(X.Events.Core.SDK_USER_SIGN_OUT,{apiKey:this.apiKey,clientUserId:this.user$?.value?.userId,snippylyUserId:this.user$?.value?.userSnippylyId,message:e==="external"?"User Sign out":"System Sign out",user:this.user$?.value?this.getUserWithoutContacts(this.user$?.value):null,forceReset:this.userOptions$.value?.forceReset,source:e});let i=yield qn(this.afAuth).pipe(et(1)).toPromise().catch(r=>null);if(i){this.user$.next(null);for(let[r,a]of this.preSignOutFunctions)try{yield a(i)}catch(s){this.loggingService.catch(`Error in signOutUser ${r} function: `,s)}return this.resetServicesCache(),this.user$.next(null),VQ(this.afAuth).catch(r=>{this.loggingService.catch("Error in signOutUser:",r)})}else return Promise.resolve()}catch(i){this.loggingService.catch("Error in signOutUser: ",i)}})}isFeatureAllowed(e){return Ji(this.config,this.user$.value,e)}getUserWithoutContacts(e){try{if(e){let i=JSON.parse(JSON.stringify(e));return delete i.contacts,i}else return null}catch(i){return this.loggingService.catch("Error in getUserWithoutContacts: ",i),null}}getUserForClient(e){try{return ua(e)}catch(i){return this.loggingService.catch("Error in getUserForClient: ",i),null}}};o.\u0275fac=function(i){return new(i||o)(Q(Si),Q(jt),Q(bm),Q(Hp),Q(Fe),Q(Uo),Q(Ke),Q(y))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Im=class{constructor({apiKey:o,documentId:t,organizationId:e,clientDocumentId:i,clientOrganizationId:r}){this.paths={},this.apiKey=o,this.documentId=t,this.organizationId=e,this.clientDocumentId=i,this.clientOrganizationId=r,i&&(this.documentId=dc(i)),r&&(this.organizationId=pc(r)),this.generateDocumentPaths()}generateDocumentPaths(){try{if(this.paths.clientDocumentId=this.clientDocumentId,this.paths.documentId=this.documentId,this.organizationId&&(this.paths.organizationId=this.organizationId,this.paths.clientOrganizationId=this.clientOrganizationId),this.apiKey){let o=`${this.apiKey}`;this.organizationId&&(o=`${o}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${this.paths.organizationId}`),this.documentId&&(this.paths.docs=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/`,this.paths.presence=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_PRESENCE}/`,this.paths.cursor=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_CURSOR}/`,this.paths.comment=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_COMMENT}/`,this.paths.multiThread=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_MULTI_THREAD}/`,this.paths.tag=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_TAG}/`,this.paths.area=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_AREA}/`,this.paths.arrow=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_ARROW}/`,this.paths.selection=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_SELECTION}/`,this.paths.audioHuddle=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_AUDIO_HUDDLE}/`,this.paths.huddle=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_HUDDLE}/`,this.paths.recorder=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_RECORDER}/`,this.paths.flock=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_FOLLOW_ALONG}/`,this.paths.syncVideoPlayer=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_SYNC_VIDEO_PLAYER}/`,this.paths.liveState=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_LIVE_STATE}/`,this.paths.liveStateSingleEditorMode=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_LIVE_STATE}/default/singleEditorMode`,this.paths.reaction=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_REACTION}/`,this.paths.views=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_VIEWS}/`,this.paths.notifications=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_NOTIFICATIONS}/`,this.paths.metadata=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_METADATA}/`,this.paths.users=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_USERS}/`,this.paths.documentIam=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_IAM}/`),this.paths.customerMetadata=`${o}/${U.FIREBASE_PARTIAL_PATH_CUSTOMER_METADATA}/`,this.paths.groupContacts=`${o}/${U.FIREBASE_PARTIAL_PATH_CONTACTS}/${U.FIREBASE_PARTIAL_PATH_GROUPS}/`,this.paths.globalContacts=`${o}/${U.FIREBASE_PARTIAL_PATH_CONTACTS}/${U.FIREBASE_PARTIAL_PATH_GLOBAL}/`,this.paths.logins=`${o}/${U.FIREBASE_PARTIAL_PATH_CONTACTS}/${U.FIREBASE_PARTIAL_PATH_LOGINS}/`,this.paths.userFeedback=`${o}/${U.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${U.FIREBASE_PARTIAL_PATH_FEEDBACK}/`,this.paths.userReportBugs=`${o}/${U.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${U.FIREBASE_PARTIAL_PATH_BUGS}/`,this.paths.userContactUs=`${o}/${U.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${U.FIREBASE_PARTIAL_PATH_CONTACT_US}/`,this.organizationId&&(this.paths.organizationMetadata=`${o}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_METADATA}/`,this.paths.organizationIam=`${o}/${U.FIREBASE_PARTIAL_PATH_IAM}/`,this.paths.organizationGroups=`${o}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_GROUPS}/`,this.paths.organizationNotifications=`${o}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/`,this.documentId&&(this.paths.organizationNotificationsWithDocumentId=`${o}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/`),this.paths.organizationNotificationsLastNotificationTimestamp=`${o}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${U.FIREBASE_PARTIAL_PATH_LAST_NOTIFICATION_TIMESTAMP}/${U.FIREBASE_PARTIAL_PATH_DOCS}/`,this.paths.organizationNotificationsUsers=`${o}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${U.FIREBASE_PARTIAL_PATH_USERS}/`),this.paths.workspaceIam=`${this.apiKey}/${U.FIREBASE_PARTIAL_PATH_IAM}/`}}catch{}}get workspaceIam(){return this.paths.workspaceIam?this.paths.workspaceIam:this.throwError("Workspace IAM path is not available.")}get docs(){return this.paths.docs?this.paths.docs:this.throwError("Docs path is not available.")}get presence(){return this.paths.presence?this.paths.presence:this.throwError("Presence path is not available.")}get cursor(){return this.paths.cursor?this.paths.cursor:this.throwError("Cursor path is not available.")}get area(){return this.paths.area?this.paths.area:this.throwError("Area path is not available.")}get arrow(){return this.paths.arrow?this.paths.arrow:this.throwError("Arrow path is not available.")}get comment(){return this.paths.comment?this.paths.comment:this.throwError("Comment path is not available.")}get multiThread(){return this.paths.multiThread?this.paths.multiThread:this.throwError("Multi thread path is not available.")}get tag(){return this.paths.tag?this.paths.tag:this.throwError("Tag path is not available.")}get selection(){return this.paths.selection?this.paths.selection:this.throwError("Selection path is not available.")}get audioHuddle(){return this.paths.audioHuddle?this.paths.audioHuddle:this.throwError("Audio huddle path is not available.")}get huddle(){return this.paths.huddle?this.paths.huddle:this.throwError("Huddle path is not available.")}get recorder(){return this.paths.recorder?this.paths.recorder:this.throwError("Recorder path is not available.")}get flock(){return this.paths.flock?this.paths.flock:this.throwError("Flock path is not available.")}get syncVideoPlayer(){return this.paths.syncVideoPlayer?this.paths.syncVideoPlayer:this.throwError("Sync video player path is not available.")}get liveState(){return this.paths.liveState?this.paths.liveState:this.throwError("Live state path is not available.")}get liveStateSingleEditorMode(){return this.paths.liveStateSingleEditorMode?this.paths.liveStateSingleEditorMode:this.throwError("Live state single editor mode path is not available.")}get reaction(){return this.paths.reaction?this.paths.reaction:this.throwError("Reaction path is not available.")}get views(){return this.paths.views?this.paths.views:this.throwError("Views path is not available.")}get notifications(){return this.paths.notifications?this.paths.notifications:this.throwError("Notifications path is not available.")}get metadata(){return this.paths.metadata?this.paths.metadata:this.throwError("Metadata path is not available.")}get users(){return this.paths.users?this.paths.users:this.throwError("Users path is not available.")}get documentIam(){return this.paths.documentIam?this.paths.documentIam:this.throwError("Document IAM path is not available.")}get organizationMetadata(){return this.paths.organizationMetadata?this.paths.organizationMetadata:this.throwError("Organization metadata path is not available.")}get organizationIam(){return this.paths.organizationIam?this.paths.organizationIam:this.throwError("Organization IAM path is not available.")}get customerMetadata(){return this.paths.customerMetadata?this.paths.customerMetadata:this.throwError("Customer metadata path is not available.")}get groupContacts(){return this.paths.groupContacts?this.paths.groupContacts:this.throwError("Group contacts path is not available.")}get globalContacts(){return this.paths.globalContacts?this.paths.globalContacts:this.throwError("Global contacts path is not available.")}get logins(){return this.paths.logins?this.paths.logins:this.throwError("Logins path is not available.")}get userFeedback(){return this.paths.userFeedback?this.paths.userFeedback:this.throwError("User feedback path is not available.")}get userReportBugs(){return this.paths.userReportBugs?this.paths.userReportBugs:this.throwError("User report bugs path is not available.")}get userContactUs(){return this.paths.userContactUs?this.paths.userContactUs:this.throwError("User contact us path is not available.")}get organizationGroups(){return this.paths.organizationGroups?this.paths.organizationGroups:this.throwError("Organization groups path is not available.")}get organizationNotifications(){return this.paths.organizationNotifications?this.paths.organizationNotifications:this.throwError("Organization notifications path is not available.")}get organizationNotificationsWithDocumentId(){return this.paths.organizationNotificationsWithDocumentId?this.paths.organizationNotificationsWithDocumentId:this.throwError("Organization notifications with document id path is not available.")}get organizationNotificationsUsers(){return this.paths.organizationNotificationsUsers?this.paths.organizationNotificationsUsers:this.throwError("Organization notifications users path is not available.")}get organizationNotificationsLastNotificationTimestamp(){return this.paths.organizationNotificationsLastNotificationTimestamp?this.paths.organizationNotificationsLastNotificationTimestamp:this.throwError("Organization notifications last notification timestamp path is not available.")}throwError(o){throw{type:"DocumentPaths",message:o,metadata:{apiKey:this.apiKey,documentId:this.documentId,organizationId:this.organizationId}}}};var HM=class{constructor({apiKey:o,documentId:t,organizationId:e,clientDocumentId:i,clientOrganizationId:r,folderId:a,veltFolderId:s}){this.paths={},this.apiKey=o,this.documentId=t,this.organizationId=e,this.veltFolderId=s,i&&(this.documentId=dc(i)),r&&(this.organizationId=pc(r)),a&&(this.folderId=a,this.veltFolderId=_l(a)),this.generateDocumentPaths()}generateDocumentPaths(){try{if(this.paths.clientDocumentId=this.clientDocumentId,this.paths.documentId=this.documentId,this.organizationId&&(this.paths.organizationId=this.organizationId,this.paths.clientOrganizationId=this.clientOrganizationId),this.veltFolderId&&(this.paths.folderId=this.folderId,this.paths.veltFolderId=this.veltFolderId),this.apiKey){let o=`apiKey/${this.apiKey}`;this.organizationId&&(o=`${o}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${this.paths.organizationId}`,this.paths.organization=o,this.paths.folder=`${o}/${U.FIREBASE_PARTIAL_PATH_FOLDERS}`,this.paths.organizationUsers=`${o}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_USERS}`,this.paths.notificationDocs=`${o}/${U.FIREBASE_PARTIAL_PATH_NOTIFICATION_DOCS}`,this.paths.notificationUsers=`${o}/${U.FIREBASE_PARTIAL_PATH_NOTIFICATION_USERS}`,this.paths.organizationGroups=`${o}/${U.FIREBASE_PARTIAL_PATH_GROUPS}`,this.paths.lastNotificationTimestamp=`${o}/${U.FIREBASE_PARTIAL_PATH_LAST_NOTIFICATION_TIMESTAMP}`),this.veltFolderId&&(this.paths.folderUsers=`${o}/${U.FIREBASE_PARTIAL_PATH_FOLDERS}/${this.veltFolderId}/${U.FIREBASE_PARTIAL_PATH_FOLDER_USERS}`),this.documentId&&(this.paths.document=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}`,this.paths.comment=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_COMMENT}`,this.paths.location=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_LOCATION}`,this.paths.multiThread=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_MULTI_THREAD}`,this.paths.area=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_AREA}`,this.paths.recorder=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_RECORDER}`,this.paths.reaction=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_REACTION}`,this.paths.commentViews=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_COMMENT_VIEWS}`,this.paths.notificationViews=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_NOTIFICATION_VIEWS}`,this.paths.documentViews=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_DOCUMENT_VIEWS}`,this.paths.locationViews=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_LOCATION_VIEWS}`,this.paths.documentUsers=`${o}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_DOCUMENT_USERS}`,this.paths.docNotification=`${this.paths.notificationDocs}/${this.documentId}/${U.FIREBASE_PARTIAL_PATH_DOC_NOTIFICATION}`)}}catch{}}get folder(){return this.paths.folder?this.paths.folder:this.throwError("Folder path is not available.")}get lastNotificationTimestamp(){return this.paths.lastNotificationTimestamp?this.paths.lastNotificationTimestamp:this.throwError("LastNotificationTimestamp path is not available.")}get organizationGroups(){return this.paths.organizationGroups?this.paths.organizationGroups:this.throwError("organizationGroups path is not available.")}get docNotification(){return this.paths.docNotification?this.paths.docNotification:this.throwError("DocNotification path is not available.")}get organization(){return this.paths.organization?this.paths.organization:this.throwError("Organization path is not available.")}get document(){return this.paths.document?this.paths.document:this.throwError("Document path is not available.")}get location(){return this.paths.location?this.paths.location:this.throwError("Location path is not available.")}get area(){return this.paths.area?this.paths.area:this.throwError("Area path is not available.")}get comment(){return this.paths.comment?this.paths.comment:this.throwError("Comment path is not available.")}get commentViews(){return this.paths.commentViews?this.paths.commentViews:this.throwError("CommentViews path is not available.")}get documentViews(){return this.paths.documentViews?this.paths.documentViews:this.throwError("DocumentViews path is not available.")}get locationViews(){return this.paths.locationViews?this.paths.locationViews:this.throwError("LocationViews path is not available.")}get notificationViews(){return this.paths.notificationViews?this.paths.notificationViews:this.throwError("NotificationViews path is not available.")}get documentUsers(){return this.paths.documentUsers?this.paths.documentUsers:this.throwError("DocumentUsers path is not available.")}get folderUsers(){return this.paths.folderUsers?this.paths.folderUsers:this.throwError("FolderUsers path is not available.")}get organizationUsers(){return this.paths.organizationUsers?this.paths.organizationUsers:this.throwError("OrganizationUsers path is not available.")}get notificationDocs(){return this.paths.notificationDocs?this.paths.notificationDocs:this.throwError("NotificationDocs path is not available.")}get notificationUsers(){return this.paths.notificationUsers?this.paths.notificationUsers:this.throwError("NotificationUsers path is not available.")}get multiThread(){return this.paths.multiThread?this.paths.multiThread:this.throwError("Multi thread path is not available.")}get recorder(){return this.paths.recorder?this.paths.recorder:this.throwError("Recorder path is not available.")}get reaction(){return this.paths.reaction?this.paths.reaction:this.throwError("Reaction path is not available.")}throwError(o){throw{type:"DocumentPaths",message:o,metadata:{apiKey:this.apiKey,documentId:this.documentId,organizationId:this.organizationId}}}};var zM=class{};var un=(()=>{let o=class o{constructor(e,i){this.authService=e,this.loggingService=i,this.db$=new ve(null);try{this.authService.getFirebaseConfig$().subscribe(r=>{r&&this.db$.next(Lf(void 0,r.firebaseOptions.databaseURL))},r=>{this.loggingService.catch("Error in DatabaseService constructor: ",r)})}catch(r){this.loggingService.catch("Error in DatabaseService constructor:",r)}}getDb(){return this.db$.asObservable()}};o.\u0275fac=function(i){return new(i||o)(Q(je),Q(y))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var bs=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.analyticsService=i,this.resolveTimeout=1*60*1e3,this.retrySaveConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.retryDeleteConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.retryGetConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.commentAnnotationDataProvider$=new ve(null),this.commentAnnotationById$=new ve({}),this.getCommentAnnotationById=r=>{try{return this.commentAnnotationDataProviderAvailable()?this.commentAnnotationById$.value?.[r]:void 0}catch(a){this.loggingService.catch("Error in CommentAnnotationsResolverService getCommentAnnotationById:",a);return}};try{this.loggingService.log("CommentAnnotationsResolverService initialized"),this.commentAnnotationDataProvider$.subscribe(r=>{r&&(r.config?.resolveTimeout&&(this.resolveTimeout=r.config.resolveTimeout),r.config?.saveRetryConfig&&(this.retrySaveConfig=r.config.saveRetryConfig),r.config?.deleteRetryConfig&&(this.retryDeleteConfig=r.config.deleteRetryConfig),r.config?.getRetryConfig&&(this.retryGetConfig=r.config.getRetryConfig))})}catch(r){this.loggingService.catch("Error in CommentAnnotationsResolverService constructor:",r)}}getProvider(){try{let e=this.commentAnnotationDataProvider$.getValue();return e||void 0}catch(e){this.loggingService.catch("Error in CommentAnnotationsResolverService getProvider:",e);return}}ngOnDestroy(){try{this.commentAnnotationById$.next({})}catch(e){this.loggingService.catch("Error in CommentAnnotationsResolverService ngOnDestroy:",e)}}resolveCommentAnnotations(e){return te(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling CommentAnnotationsResolverService FUNCTION: resolveCommentAnnotations","color: green;"),!this.commentAnnotationDataProviderAvailable())return{};let i,r=!1,a=!1,s=()=>{i&&(clearTimeout(i),i=void 0,a=!0)};return new Promise((c,p)=>{i=setTimeout(()=>{a||(r=!0,s(),p(new Error("Comment annotation resolution timeout")))},this.commentAnnotationDataProvider$.value?.config?.resolveTimeout||this.resolveTimeout);let u=this.getProvider();if(!u)return s(),c({});let C={},E=[...new Set(e.commentAnnotationIds||[])],A=T(I({},e),{commentAnnotationIds:E});te(this,null,function*(){try{if(E.length>0||e.documentIds?.length||e.folderId){let G=uc(()=>u?.get(A)||Promise.resolve(void 0),"getCommentAnnotations",this.retryGetConfig).then(K=>r?{}:(s(),K&&K.statusCode!==200?(this.loggingService.catch(K?.message??"Error in CommentAnnotationsResolverService resolveCommentAnnotations:"),{}):K?.data)).catch(K=>{throw s(),K});try{C=(yield G)||{},this.analyticsService.trackEvent(X.Events.Resolver.COMMENT_RESOLVER_GET,{sourceMethod:"resolveCommentAnnotations",source:"sdk",commentAnnotationIds:E});let K={};Object.entries(C).forEach(([pe,Ce])=>{let Ie=this.commentAnnotationById$.value?.[pe];Ie?Ie&&JSON.stringify(Ie)!==JSON.stringify(Ce)&&(K[pe]=Ce):K[pe]=Ce}),Object.keys(K).length>0&&this.commentAnnotationById$.next(I(I({},this.commentAnnotationById$.getValue()),K)),c(K)}catch(K){r||p(K),c(C)}}else s(),c({})}catch(G){s(),p(G)}})})}catch(i){return this.loggingService.catch("Error in CommentAnnotationsResolverService resolveCommentAnnotations:",i),{}}})}saveCommentAnnotation(e){return te(this,null,function*(){try{this.loggingService.log("%c[WB] Calling CommentAnnotationsResolverService FUNCTION: saveCommentAnnotation","color: green;");let i=this.getProvider();if(!this.commentAnnotationDataProviderAvailable())throw new Error("Comment annotation save data provider not available");let r=JSON.parse(JSON.stringify(this.commentAnnotationById$.getValue()));this.commentAnnotationById$._value=I(I({},r),e.commentAnnotation);let a=yield uc(()=>i?.save({commentAnnotation:e.commentAnnotation,event:e.eventType,commentId:e.commentId,metadata:Object.values(e.commentAnnotation??{})?.[0]?.metadata})||Promise.resolve(void 0),"saveCommentAnnotation",this.retrySaveConfig);return a&&a.statusCode!==200?(this.retrySaveConfig.revertOnFailure&&(this.commentAnnotationById$._value=r),this.loggingService.catch(a?.message??"Error in CommentAnnotationsResolverService saveCommentAnnotation:"),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(X.Events.Resolver.COMMENT_RESOLVER_SAVE,{sourceMethod:"saveCommentAnnotation",source:"sdk",commentAnnotationIds:Object.keys(e.commentAnnotation),eventType:e.eventType,commentId:e.commentId}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0})}catch(i){return this.loggingService.warn("Error in CommentAnnotationsResolverService saveCommentAnnotation:",i),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0}}})}deleteCommentAnnotation(e,i){return te(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 uc(()=>r?.delete({commentAnnotationId:e.toString(),metadata:i,event:Wa.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(X.Events.Resolver.COMMENT_RESOLVER_DELETE,{sourceMethod:"deleteCommentAnnotation",source:"sdk",commentAnnotationId:e.toString()}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0})}catch(r){return this.loggingService.warn("Error in CommentAnnotationsResolverService deleteCommentAnnotation:",r),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0}}})}getCommentAnnotationsById$(){try{return this.commentAnnotationDataProviderAvailable()?(this.loggingService.log("%c[WB] Calling CommentAnnotationsResolverService FUNCTION: getCommentAnnotationsById$","color: green;"),this.commentAnnotationById$.asObservable()):re(void 0)}catch(e){return this.loggingService.catch("Error in CommentAnnotationsResolverService getCommentAnnotationsById$:",e),re(void 0)}}getAnnotationById(e){try{return this.commentAnnotationDataProviderAvailable()?this.commentAnnotationById$.getValue()?.[e]:void 0}catch(i){this.loggingService.catch("Error in CommentAnnotationsResolverService getAnnotationById:",i);return}}setCommentAnnotationDataProvider(e){try{if(e){this.loggingService.log("Setting comment annotation data provider");let r=["get","save","delete"].filter(a=>!(a in e)||typeof e[a]!="function");if(r.length>0){let a=`DataProviders.comment is invalid. The following methods are missing or are not functions: ${r.join(", ")}.`;this.loggingService.catch(a);return}else this.commentAnnotationDataProvider$.next(e)}}catch(i){this.loggingService.catch("Error in CommentAnnotationsResolverService setCommentAnnotationDataProvider:",i)}}commentAnnotationDataProviderAvailable(){try{return!!this.commentAnnotationDataProvider$.getValue()}catch(e){return this.loggingService.catch("Error in CommentAnnotationsResolverService commentAnnotationDataProviderAvailable:",e),!1}}};o.\u0275fac=function(i){return new(i||o)(Q(y),Q(Ke))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Em=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.analyticsService=i,this.resolveTimeout=1*60*1e3,this.retrySaveConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.retryDeleteConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.retryGetConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.reactionAnnotationDataProvider$=new 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 te(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling ReactionAnnotationsResolverService FUNCTION: resolveReactionAnnotations","color: green;"),!this.reactionAnnotationDataProviderAvailable())return{};let i,r=!1,a=!1,s=()=>{i&&(clearTimeout(i),i=void 0,a=!0)};return new Promise((c,p)=>{i=setTimeout(()=>{a||(r=!0,s(),p(new Error("Reaction annotation resolution timeout")))},this.reactionAnnotationDataProvider$.value?.config?.resolveTimeout||this.resolveTimeout);let u=this.getProvider();if(!u)return s(),c({});let C={},E=[...new Set(e.reactionAnnotationIds||[])],A=T(I({},e),{reactionAnnotationIds:E});te(this,null,function*(){try{if(E.length>0||e.documentIds?.length||e.folderId){let G=uc(()=>u?.get(A)||Promise.resolve(void 0),"getReactionAnnotations",this.retryGetConfig).then(K=>r?{}:(s(),K&&K.statusCode!==200?(this.loggingService.catch(K?.message??"Error in ReactionAnnotationsResolverService resolveReactionAnnotations:"),{}):K?.data)).catch(K=>{throw s(),K});try{C=(yield G)||{},this.analyticsService.trackEvent(X.Events.Resolver.REACTION_RESOLVER_GET,{sourceMethod:"resolveReactionAnnotations",source:"sdk",reactionAnnotationIds:E});let K={};Object.entries(C).forEach(([pe,Ce])=>{let Ie=this.reactionAnnotationById$.value?.[pe];Ie?Ie&&JSON.stringify(Ie)!==JSON.stringify(Ce)&&(K[pe]=Ce):K[pe]=Ce}),Object.keys(K).length>0&&this.reactionAnnotationById$.next(I(I({},this.reactionAnnotationById$.getValue()),K)),c(K)}catch(K){r||p(K),c(C)}}else s(),c({})}catch(G){s(),p(G)}})})}catch(i){return this.loggingService.catch("Error in ReactionAnnotationsResolverService resolveReactionAnnotations:",i),{}}})}saveReactionAnnotation(e){return te(this,null,function*(){try{this.loggingService.log("%c[WB] Calling ReactionAnnotationsResolverService FUNCTION: saveReactionAnnotation","color: green;");let i=this.getProvider();if(!this.reactionAnnotationDataProviderAvailable())throw new Error("Reaction annotation save data provider not available");let r=JSON.parse(JSON.stringify(this.reactionAnnotationById$.getValue()));this.reactionAnnotationById$._value=I(I({},r),e);let a={reactionAnnotation:e,event:Wa.REACTION_ADD,metadata:Object.values(e??{})?.[0]?.metadata},s=yield uc(()=>i?.save(a)||Promise.resolve(void 0),"saveReactionAnnotation",this.retrySaveConfig);return s&&s.statusCode!==200?(this.retrySaveConfig.revertOnFailure&&(this.reactionAnnotationById$._value=r),this.loggingService.catch(s?.message??"Error in ReactionAnnotationsResolverService saveReactionAnnotation:"),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(X.Events.Resolver.REACTION_RESOLVER_SAVE,{sourceMethod:"saveReactionAnnotation",source:"sdk",reactionAnnotationIds:Object.keys(e),eventType:a.event}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0})}catch(i){return this.loggingService.warn("Error in ReactionAnnotationsResolverService saveReactionAnnotation:",i),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0}}})}deleteReactionAnnotation(e,i){return te(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 uc(()=>r?.delete({reactionAnnotationId:e.toString(),metadata:i,event:Wa.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(X.Events.Resolver.REACTION_RESOLVER_DELETE,{sourceMethod:"deleteReactionAnnotation",source:"sdk",reactionAnnotationId:e.toString()}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0})}catch(r){return this.loggingService.warn("Error in ReactionAnnotationsResolverService deleteReactionAnnotation:",r),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0}}})}getReactionAnnotationsById$(){try{return this.reactionAnnotationDataProviderAvailable()?(this.loggingService.log("%c[WB] Calling ReactionAnnotationsResolverService FUNCTION: getReactionAnnotationsById$","color: green;"),this.reactionAnnotationById$.asObservable()):re(void 0)}catch(e){return this.loggingService.catch("Error in ReactionAnnotationsResolverService getReactionAnnotationsById$:",e),re(void 0)}}getAnnotationById(e){try{return this.reactionAnnotationDataProviderAvailable()?this.reactionAnnotationById$.getValue()?.[e]:void 0}catch(i){this.loggingService.catch("Error in ReactionAnnotationsResolverService getAnnotationById:",i);return}}setReactionAnnotationDataProvider(e){try{if(e){this.loggingService.log("Setting reaction annotation data provider");let r=["get","save","delete"].filter(a=>!(a in e)||typeof e[a]!="function");if(r.length>0){let a=`DataProviders.reaction is invalid. The following methods are missing or are not functions: ${r.join(", ")}.`;this.loggingService.catch(a);return}else this.reactionAnnotationDataProvider$.next(e)}}catch(i){this.loggingService.catch("Error in ReactionAnnotationsResolverService setReactionAnnotationDataProvider:",i)}}reactionAnnotationDataProviderAvailable(){try{return!!this.reactionAnnotationDataProvider$.getValue()}catch(e){return this.loggingService.catch("Error in ReactionAnnotationsResolverService reactionAnnotationDataProviderAvailable:",e),!1}}};o.\u0275fac=function(i){return new(i||o)(Q(y),Q(Ke))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var lt=(()=>{let o=class o{constructor(e,i,r,a,s,c,p,u){this.analyticsService=e,this.authService=i,this.databaseService=r,this.domService=a,this.configService=s,this.loggingService=c,this.commentResolverService=p,this.reactionResolverService=u,this.documentPaths$=new ve(null),this.documentIds$=new ve([]),this.folderConfig$=new ve(null),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.draftDocumentId=null,this.clientDocumentMetadataMap={},this.uiState=new ve({}),this.lastSetDocumentIdExecutionTime=0,this.lastSetDocumentIdCallTime=0,this.setDocumentIdSubject=new Xe,this.DEBOUNCE_TIME=5e3,this.MAX_QUEUE_SIZE=100,this.queueSize=0,this.isDocumentIdInDebounceQueue=!1,this.draftLocationMap={location:null,locations:[]};try{this.loggingService.log("%c[WB] Creating CLASS: DocService","color: blue;"),this.domService.setDocService(this),this.authService.setDocService(this),this.setDocumentIdSubject.pipe(or(this.DEBOUNCE_TIME)).subscribe({next:C=>{try{this.setDocumentIdImpl(C.documentId,C.clientOrganizationId,C.auto,C.avoidAnalytics,C.options),this.lastSetDocumentIdExecutionTime=Date.now(),this.isDocumentIdInDebounceQueue=!1,this.draftLocationMap.location&&this.setLocation(this.draftLocationMap.location),this.draftLocationMap.locations.length>0&&this.draftLocationMap.locations.forEach(E=>{this.addLocation(E)}),this.draftLocationMap={location:null,locations:[]}}finally{this.queueSize--}},error:C=>{this.loggingService.catch("Error in setDocumentId subscription:",C),this.queueSize--}}),this.databaseService.getDb().pipe(Ne(C=>!!C),et(1)).subscribe(C=>{C&&(this.db=C)}),this.configService.getApiKey$().subscribe(C=>{if(this.apiKey=C,this.apiKey){if(!this.isCustomDocId){let E=u6(window.location.href);this.currentUrl=E}this.analyticsService.updateDefaultProperties({apiKey:C})}}),this.authService.getUser$().subscribe(C=>{C?(this.analyticsService.updateDefaultProperties({organizationId:C?.organizationId,clientOrganizationId:C?.clientOrganizationId}),this.draftDocumentId?(this.setDocumentId(this.draftDocumentId,this.draftOrganizationId,!1,!1,this.draftFolderConfig),this.draftDocumentId=null,this.draftLocationMap.location&&this.setLocation(this.draftLocationMap.location),this.draftLocationMap.locations.length>0&&this.draftLocationMap.locations.forEach(E=>{this.addLocation(E)}),this.draftLocationMap={location:null,locations:[]},this.draftOrganizationId=void 0,this.draftFolderConfig=void 0):this.documentPaths$?.value&&C?.organizationId&&this.documentPaths$.value?.organizationId!==C?.organizationId&&this.setDocumentId(this.documentPaths$.value?.clientDocumentId),this.updateDocumentLocationMetadata(),setTimeout(()=>{this.documentPaths$.value||this.loggingService.catch("Error in DocService constructor:","Please set document id to continue.")},1e4),C?.organizationId&&C?.clientOrganizationId&&this.organizationConfig$.next({organizationId:C?.organizationId,clientOrganizationId:C?.clientOrganizationId})):(this.organizationMetadataSubscription?.unsubscribe(),this.documentMetadataSubscription?.unsubscribe(),this.customerMetadataSubscription?.unsubscribe(),this.documentPaths$.value&&(this.draftDocumentId=this.documentPaths$.value?.clientDocumentId??null,this.draftFolderConfig=this.folderConfig$.value,this.draftLocationMap={location:this.location$.value?.location??null,locations:Object.values(this.locations$.value||{}).map(E=>E.location)},this.currentDocumentId=null,this.location$.next(null),this.documentPaths$.next(null),this.firestorePaths$.next(null)))}),this.documentPaths$.subscribe(C=>{let E={documentId:C?.documentId,clientDocumentId:C?.clientDocumentId};C?.organizationId&&(E.organizationId=C.organizationId,E.clientOrganizationId=C.clientOrganizationId),this.analyticsService.updateDefaultProperties(E),this.domService.resetSelectedAnnotationsMap()}),this.folderConfig$.subscribe(C=>{this.analyticsService.updateDefaultProperties({folderId:C?.folderId,veltFolderId:C?.veltFolderId,allDocuments:C?.allDocuments})}),this.location$.subscribe(C=>{this.analyticsService.updateDefaultProperties({clientLocation:C?.location,locationId:C?.locationId})}),this.organizationMetadata$.subscribe(C=>{this.authService.setUserOrganization(C?.[this.documentPaths$.value?.organizationId])}),this.organizationConfig$.subscribe(C=>{C&&this.updateOrganizationMetadata()}),this.documentPaths$.pipe(Ne(C=>!!C),et(1)).subscribe(()=>{try{this.subscribeToCustomerMetadata()}catch(C){this.loggingService.catch("Error in DocService subscribeToCustomerMetadata:",C)}},C=>{this.loggingService.catch("Error in DocService subscribeToCustomerMetadata:",C)}),this.loggingService.log("%c[WB] Creating CLASS: DocService 2","color: blue;"),this.onWindowPopstate(),this.onWindowClick()}catch(C){this.loggingService.catch("Error in DocService constructor:",C)}}clearCache(){this.loggingService.log("%c[WB] Calling FUNCTION: clearCache in DocService","color: green;");try{this.folderConfig$.next(null),this.organizationConfig$.next(null),this.organizationMetadata$.next(null),this.documentMetadata$.next(null),this.locationMetadata$.next(null),this.customerMetadata$.next(null)}catch(e){this.loggingService.catch("Error in DocService clearCache: ",e)}}setCommonDbService(e){try{this.commonDbService=e}catch(i){this.loggingService.catch("Error in setCommonDbService:",i)}}setCommentService(e){try{this.commentService=e}catch(i){this.loggingService.catch("Error in setCommentService:",i)}}onWindowPopstate(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowPopstate","color: green;");try{this.domService.onWindowPopState$().subscribe(()=>{this.loggingService.log("location",location.href);let e=u6(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=u6(location.href);this.currentUrl!==e&&(this.currentUrl=e,this.isCustomDocId||this.loggingService.log("current url in doc service",this.currentUrl))},e=>{this.loggingService.catch("Error in DocService onWindowClick subscription: ",e)})}catch(e){this.loggingService.catch("Error in onWindowClick: ",e)}}setDocument(e,i){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocument","color: green;"),this.documentIds$.value?.length&&this.documentIds$.next([]);let r=i?.organizationId;this.setDocumentId(e,r,!1,!0),i&&(i.organizationId&&delete i.organizationId,this.clientDocumentMetadata={clientDocumentId:e,documentMetadata:i},this.updateDocumentMetadata()),this.analyticsService.trackEvent(X.Events.Doc.DOCUMENT_SET,{documentId:e,documentMetadata:i},!0,this.getUserIdForAnalytics())}catch(r){this.loggingService.catch("Error in DocService setDocument:",r)}}shouldSetDocumentsAgain(e,i={}){try{this.loggingService.log("%c[WB] Calling FUNCTION: shouldSetDocumentsAgain","color: green;");let r=this.documentIds$.value.map(c=>c.clientDocumentId),a=this.folderConfig$.value??{};return!e.every(c=>r.includes(c.id))||!_o(a,i)}catch(r){return this.loggingService.catch("Error in DocService shouldSetDocumentsAgain:",r),!0}}setDocuments(e,i){try{if(!this.shouldSetDocumentsAgain(e,i)){this.loggingService.warn("setDocuments called with previous request");return}let r=[];if(e.forEach(a=>{let s=a.id,c=`${Cn(s)}`;a?.metadata&&typeof a.metadata=="object"&&(this.clientDocumentMetadataMap[s]=a.metadata),r.push({documentId:c,clientDocumentId:s})}),r?.length===0){this.loggingService.warn("Minimum one document must be set in setDocuments");return}this.documentIds$.next(r),e?.length&&this.setDocumentId(e[0]?.id,i?.organizationId,!1,!1,i),this.analyticsService.trackEvent(X.Events.Doc.DOCUMENTS_SET,{documentIds:r,options:i},!0,this.getUserIdForAnalytics())}catch(r){this.loggingService.catch("Error in DocService setDocuments:",r)}}setDocumentId(e,i,r=!1,a=!1,s){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocumentId","color: green;"),this.folderConfig$.value&&this.folderConfig$.next(null);let c=Date.now(),p=c-this.lastSetDocumentIdCallTime,u=c-this.lastSetDocumentIdExecutionTime;if(this.lastSetDocumentIdCallTime=c,this.queueSize>=this.MAX_QUEUE_SIZE){this.loggingService.warn("SetDocumentId queue size exceeded limit");return}if(!this.documentPaths$.value&&!this.isDocumentIdInDebounceQueue||p>this.DEBOUNCE_TIME&&u>this.DEBOUNCE_TIME){this.setDocumentIdImpl(e,i,r,a,s),this.lastSetDocumentIdExecutionTime=c;return}this.documentPaths$.next(null),this.isDocumentIdInDebounceQueue=!0,this.draftLocationMap={location:null,locations:[]},this.queueSize++,this.setDocumentIdSubject.next({documentId:e,clientOrganizationId:i,auto:r,avoidAnalytics:a,options:s??void 0})}catch(c){this.loggingService.catch("Error in setDocumentId:",c)}}setDocumentIdImpl(e,i,r=!1,a=!1,s){this.loggingService.log("%c[WB] Calling FUNCTION: setDocumentIdImpl","color: green;");try{r||(this.isCustomDocId=!0);let c=this.authService.getUser();if(!c){this.draftDocumentId=e,this.draftOrganizationId=i,this.draftFolderConfig=s;return}(s?.folderId||s?.locationId)&&this.folderConfig$.next({folderId:s?.folderId,allDocuments:s?.allDocuments,locationId:s?.locationId,veltFolderId:s?.folderId?_l(s?.folderId):void 0}),this.currentDocumentId&&this.documentPaths$.value&&this.callPreDocumentIdChangeFunctions(this.documentPaths$.value);let p=this.currentDocumentId;if(this.apiKey){let u=`${Cn(e)}`,C=c?.organizationId?i?Nt(i):c?.organizationId:void 0;if(this.commentResolverService.resolveCommentAnnotations({documentIds:this.documentIds$.value.map(E=>E.clientDocumentId),organizationId:i??c?.clientOrganizationId??""}),this.reactionResolverService.resolveReactionAnnotations({documentIds:this.documentIds$.value.map(E=>E.clientDocumentId),organizationId:i??c?.clientOrganizationId??""}),C&&this.documentPaths$.value?.organizationId&&C!==this.documentPaths$.value?.organizationId){let E=this.getFolderConfig();this.authService.resetServicesCache(),E&&this.folderConfig$.next(E)}if(this.currentDocumentId!==u||this.documentPaths$.value?.organizationId!==C){this.loggingService.log("setting new docid"),this.currentDocumentId=u;let E=new DM,A=new zM;E.clientDocumentId=e,A.clientDocumentId=e,E.documentId=u,A.documentId=u,C&&(E.organizationId=C,E.clientOrganizationId=i??c?.clientOrganizationId,A.organizationId=C,A.clientOrganizationId=i??c?.clientOrganizationId);let B=`${this.apiKey}`,G=`apiKey/${this.apiKey}`;C&&(B=`${B}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${E.organizationId}`,G=`${G}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${E.organizationId}`),A.organization=`apiKey/${this.apiKey}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}`,A.document=`${G}/${U.FIREBASE_PARTIAL_PATH_DOCS}`,E.presence=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${u}/${U.FIREBASE_PARTIAL_PATH_PRESENCE}/`,E.cursor=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${u}/${U.FIREBASE_PARTIAL_PATH_CURSOR}/`,E.comment=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${u}/${U.FIREBASE_PARTIAL_PATH_COMMENT}/`,A.comment=`${G}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${u}/${U.FIREBASE_PARTIAL_PATH_COMMENT}`,E.multiThread=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${u}/${U.FIREBASE_PARTIAL_PATH_MULTI_THREAD}/`,A.multiThread=`${G}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${u}/${U.FIREBASE_PARTIAL_PATH_MULTI_THREAD}`,E.tag=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${u}/${U.FIREBASE_PARTIAL_PATH_TAG}/`,E.area=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${u}/${U.FIREBASE_PARTIAL_PATH_AREA}/`,A.area=`${G}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${u}/${U.FIREBASE_PARTIAL_PATH_AREA}`,E.arrow=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${u}/${U.FIREBASE_PARTIAL_PATH_ARROW}/`,E.selection=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${u}/${U.FIREBASE_PARTIAL_PATH_SELECTION}/`,E.audioHuddle=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${u}/${U.FIREBASE_PARTIAL_PATH_AUDIO_HUDDLE}/`,E.huddle=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${u}/${U.FIREBASE_PARTIAL_PATH_HUDDLE}/`,E.recorder=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${u}/${U.FIREBASE_PARTIAL_PATH_RECORDER}/`,A.recorder=`${G}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${u}/${U.FIREBASE_PARTIAL_PATH_RECORDER}`,E.flock=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${u}/${U.FIREBASE_PARTIAL_PATH_FOLLOW_ALONG}/`,E.syncVideoPlayer=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${u}/${U.FIREBASE_PARTIAL_PATH_SYNC_VIDEO_PLAYER}/`,E.liveState=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${u}/${U.FIREBASE_PARTIAL_PATH_LIVE_STATE}/`,E.liveStateSingleEditorMode=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${u}/${U.FIREBASE_PARTIAL_PATH_LIVE_STATE}/default/singleEditorMode`,E.reaction=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${u}/${U.FIREBASE_PARTIAL_PATH_REACTION}/`,A.reaction=`${G}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${u}/${U.FIREBASE_PARTIAL_PATH_REACTION}`,E.customerMetadata=`${this.apiKey}/${U.FIREBASE_PARTIAL_PATH_CUSTOMER_METADATA}/`,E.views=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${u}/${U.FIREBASE_PARTIAL_PATH_VIEWS}/`,A.commentViews=`${G}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${u}/${U.FIREBASE_PARTIAL_PATH_COMMENT_VIEWS}`,A.notificationViews=`${G}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${u}/${U.FIREBASE_PARTIAL_PATH_NOTIFICATION_VIEWS}`,A.documentViews=`${G}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${u}/${U.FIREBASE_PARTIAL_PATH_DOCUMENT_VIEWS}`,A.locationViews=`${G}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${u}/${U.FIREBASE_PARTIAL_PATH_LOCATION_VIEWS}`,E.notifications=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${u}/${U.FIREBASE_PARTIAL_PATH_NOTIFICATIONS}/`,E.metadata=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${u}/${U.FIREBASE_PARTIAL_PATH_METADATA}/`,E.users=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${u}/${U.FIREBASE_PARTIAL_PATH_USERS}/`,E.documentIam=`${B}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${u}/${U.FIREBASE_PARTIAL_PATH_IAM}/`,E.workspaceIam=`${this.apiKey}/${U.FIREBASE_PARTIAL_PATH_IAM}/`,E.groupContacts=`${B}/${U.FIREBASE_PARTIAL_PATH_CONTACTS}/${U.FIREBASE_PARTIAL_PATH_GROUPS}/`,E.globalContacts=`${B}/${U.FIREBASE_PARTIAL_PATH_CONTACTS}/${U.FIREBASE_PARTIAL_PATH_GLOBAL}/`,E.logins=`${B}/${U.FIREBASE_PARTIAL_PATH_CONTACTS}/${U.FIREBASE_PARTIAL_PATH_LOGINS}/`,E.userFeedback=`${B}/${U.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${U.FIREBASE_PARTIAL_PATH_FEEDBACK}/`,E.userReportBugs=`${B}/${U.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${U.FIREBASE_PARTIAL_PATH_BUGS}/`,E.userContactUs=`${B}/${U.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${U.FIREBASE_PARTIAL_PATH_CONTACT_US}/`,C&&(E.organizationMetadata=`${B}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_METADATA}/`,E.organizationIam=`${B}/${U.FIREBASE_PARTIAL_PATH_IAM}/`,E.organizationGroups=`${B}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_GROUPS}/`,E.organizationNotifications=`${B}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/`,u&&(E.organizationNotificationsWithDocumentId=`${B}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${u}/`),E.organizationNotificationsLastNotificationTimestamp=`${B}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${U.FIREBASE_PARTIAL_PATH_LAST_NOTIFICATION_TIMESTAMP}/${U.FIREBASE_PARTIAL_PATH_DOCS}/`,E.organizationNotificationsUsers=`${B}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${U.FIREBASE_PARTIAL_PATH_USERS}/`),A.organizationUsers=`${G}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_USERS}`,A.documentUsers=`${G}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${u}/${U.FIREBASE_PARTIAL_PATH_DOCUMENT_USERS}`,A.notificationDocs=`${G}/${U.FIREBASE_PARTIAL_PATH_NOTIFICATION_DOCS}`,A.notificationUsers=`${G}/${U.FIREBASE_PARTIAL_PATH_NOTIFICATION_USERS}`,this.documentPaths$.next(E),this.firestorePaths$.next(A),E?.clientOrganizationId&&E?.organizationId&&!(E?.clientOrganizationId===this.organizationConfig$?.value?.clientOrganizationId&&E?.organizationId===this.organizationConfig$?.value?.organizationId)&&this.organizationConfig$.next({organizationId:E?.organizationId,clientOrganizationId:E?.clientOrganizationId}),this.updateFolderMetadata(),this.updateDocumentMetadata(),this.getLocationMetadata(),p&&this.location$.value&&this.removeLocation(),a||this.analyticsService.trackEvent(X.Events.Doc.DOCUMENT_ID_SET,{documentId:u,clientDocumentId:e},!0,this.getUserIdForAnalytics())}return u}else this.loggingService.catch("Error in setDocumentIdImpl: API key is not provided.")}catch(c){this.loggingService.catch("Error in setDocumentIdImpl: ",c)}}unsetDocumentId(e="internal"){this.loggingService.log("%c[WB] Calling FUNCTION: unsetDocumentId","color: green;");try{this.analyticsService.trackEvent(X.Events.Doc.DOCUMENT_UNSET,{documentId:this.currentDocumentId,documentMetadata:this.documentMetadata$.value?.[this.currentDocumentId??""],message:e==="external"?"User unset document id":"System unset document id",source:e},!0,this.getUserIdForAnalytics()),this.currentDocumentId&&this.documentPaths$.value&&this.callPreDocumentIdChangeFunctions(this.documentPaths$.value),this.currentDocumentId=null,this.documentPaths$.next(null),this.firestorePaths$.next(null),this.location$.next(null),this.excludedLocationIds$.next([]),this.documentMetadata$.next(null),this.locationMetadata$.next(null),this.customerMetadata$.next(null),this.locations$.next({})}catch(i){this.loggingService.catch("Error in unsetDocumentId: ",i)}}unsetDocuments(e="internal"){this.loggingService.log("%c[WB] Calling FUNCTION: unsetDocuments","color: green;");try{this.unsetDocumentId(e),this.documentIds$.next([])}catch(i){this.loggingService.catch("Error in unsetDocuments: ",i)}}addPreDocumentIdChangeFunction(e,i){try{this.loggingService.log("%c[WB] Calling FUNCTION: addPreDocumentIdChangeFunction","color: green;"),this.preDocumentIdChangeFunctions.set(e,i)}catch(r){this.loggingService.catch("Error in addPreDocumentIdChangeFunction: ",r)}}callPreDocumentIdChangeFunctions(e){return te(this,null,function*(){try{this.loggingService.log("%c[WB] Calling FUNCTION: callPreDocumentIdChangeFunctions","color: green;");for(let[i,r]of this.preDocumentIdChangeFunctions)try{yield r(e)}catch(a){this.loggingService.catch("Error in callPreDocumentIdChangeFunctions: ",a)}}catch(i){this.loggingService.catch("Error in callPreDocumentIdChangeFunctions: ",i)}})}subscribeToOrganizationMetadata(){this.loggingService.log("%c[WB] Calling FUNCTION: subscribeToOrganizationMetadata","color: green;");try{if(this.organizationMetadataSubscription&&this.organizationMetadataSubscription.unsubscribe(),this.db&&this.authService.getUser()?.organizationId){let e=this.organizationConfig$.value?.organizationId;this.commonDbService?.getData({feature:"organizationMetadata",properties:{apiKey:this.apiKey??"",organizationId:e,field:"metadata"}}).then(i=>{i&&this.organizationMetadata$.next(T(I({},this.organizationMetadata$.value),{[e]:i}))}).catch(i=>{this.loggingService.catch("Error in subscribeToOrganizationMetadata: ",i)})}}catch(e){this.loggingService.catch("Error in subscribeToOrganizationMetadata: ",e)}}subscribeToDocumentMetadata(e){try{if(this.documentMetadataSubscription&&this.documentMetadataSubscription.unsubscribe(),this.db&&this.authService.getUser()){let i=this.documentPaths$.value,r=this.documentMetadata$.value;if(e=e.filter(a=>!r?.[a.documentId]),e?.some(a=>!a?.documentId||!a?.clientDocumentId)||!i)return;if(this.commonDbService?.shouldUseFirestore()){let a=this.getFolderConfig()?.folderId,s=this.getFolderConfig()?.allDocuments,c=[],p={organizationId:i?.clientOrganizationId,folderId:a,allDocuments:s};if(a&&s)c.push(this.fetchDocuments(p));else{let C=[];for(let A=0;A<e.length;A+=20)C.push(e.slice(A,A+20));C.forEach(A=>{let B=JSON.parse(JSON.stringify(p));B.documentIds=A.map(G=>G.clientDocumentId),c.push(this.fetchDocuments(B))})}let u={};c.length>0&&Promise.all(c).then(C=>{C?.forEach(E=>{E?.forEach(A=>{A?.metadata?.documentId&&(u[A.metadata.documentId]=A.metadata)})}),this.documentMetadata$.next(I(I({},this.documentMetadata$.value),u))}).catch(C=>{this.loggingService.catch("Error in subscribeToDocumentMetadata: ",C)})}else r?.[i?.documentId??e?.[0]?.documentId]||this.commonDbService?.queryData({feature:"allDocuments",properties:{apiKey:this.apiKey??"",organizationId:i?.organizationId,documentId:i?.documentId??e?.[0]?.documentId,skipObjectValues:!0}}).then(a=>{a?.documentId&&this.documentMetadata$.next({[a.documentId]:a})}).catch(a=>{this.loggingService.catch("Error in subscribeToDocumentMetadata: ",a)})}}catch(i){this.loggingService.catch("Error in subscribeToDocumentMetadata: ",i)}}getLocationMetadata(){try{if(this.db&&this.authService.getUser()){let e=this.documentPaths$.value,i=this.documentIds$.value,r=this.getFolderConfig()?.folderId,a=this.getFolderConfig()?.allDocuments,s=[],c={organizationId:e?.clientOrganizationId,folderId:r,allDocuments:a};if(r&&a)s.push(this.fetchLocations(c));else{let u=[];for(let E=0;E<i.length;E+=20)u.push(i.slice(E,E+20));u.forEach(E=>{let A=JSON.parse(JSON.stringify(c));A.documentIds=E.map(B=>B.clientDocumentId),s.push(this.fetchLocations(A))})}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 getLocationMetadata: ",u)})}}catch(e){this.loggingService.catch("Error in getLocationMetadata: ",e)}}getLocationMetadatas(){return this.locationMetadata$.value}subscribeToCustomerMetadata(){this.loggingService.log("%c[WB] Calling FUNCTION: subscribeToCustomerMetadata","color: green;");try{if(this.customerMetadataSubscription)return;this.db&&this.authService.getUser()&&this.documentPaths$.value&&(this.customerMetadataSubscription=this.commonDbService?.dbListener({feature:"customerMetadata",properties:{skipFirestore:!0}}).pipe(Vn(i=>re(null))).subscribe(i=>{this.customerMetadata$.next(i?.data)}))}catch(e){this.loggingService.catch("Error in subscribeToCustomerMetadata: ",e)}}getDocumentId(){return this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentId","color: green;"),this.documentPaths$.value?.documentId}getClientDocumentId(){return this.loggingService.log("%c[WB] Calling FUNCTION: getClientDocumentId","color: green;"),this.documentPaths$.value?.clientDocumentId}getDocumentIds$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentIds$","color: green;"),this.documentIds$.asObservable().pipe(ce(e=>e?.slice()))}getFolderConfig$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getFolderConfig$","color: green;"),this.folderConfig$.asObservable()}getDocumentIds(){return this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentIds","color: green;"),this.documentIds$.value?.slice()}getFolderConfig(){return this.loggingService.log("%c[WB] Calling FUNCTION: getFolderConfig","color: green;"),this.folderConfig$.value}getLocationMetadata$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getLocationMetadata$","color: green;"),this.locationMetadata$.asObservable().pipe()}getDocumentPaths$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentPaths$","color: green;"),this.documentPaths$.asObservable()}getFirestorePaths$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getFirestorePaths$","color: green;"),this.firestorePaths$.asObservable()}getDocumentPaths(){return this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentPaths","color: green;"),this.documentPaths$.value}generateDocumentId(e){try{return`${Cn(e)}`}catch(i){return this.loggingService.catch("Error in generateDocumentId: ",i),""}}generateOrganizationId(e){try{return`${Nt(e)}`}catch(i){return this.loggingService.catch("Error in generateOrganizationId: ",i),""}}getFirestorePaths(){return this.loggingService.log("%c[WB] Calling FUNCTION: getFirestorePaths","color: green;"),this.firestorePaths$.value}setLocation(e){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: setLocationImpl","color: green;"),e&&typeof e=="object"){if(e?.version&&(!e?.version?.id||!e?.version?.name)){this.loggingService.catch("Error in setLocationImpl: ","If you're setting version then add id and name fields to version object.");return}let i=Qo(e),r=Cn(JSON.stringify(i));this.location$.next({locationId:r,location:i}),this.isDocumentIdInDebounceQueue&&(this.draftLocationMap.location=e),this.updateDocumentLocationMetadata().then(()=>{this.analyticsService.trackEvent(X.Events.Doc.LOCATION_SET,{location:i,locationId:r},!0,this.getUserIdForAnalytics())})}}catch(i){this.loggingService.catch("Error in setLocationImpl: ",i)}}removeLocation(e,i="internal"){try{if(this.analyticsService.trackEvent(X.Events.Doc.LOCATION_UNSET,{location:this.location$.value?.location,locationId:this.location$.value?.locationId,message:i==="external"?"User removed location":"System removed location",source:i},!0,this.getUserIdForAnalytics()),e){let r=this.genarateLocationId(e);this.getLocation()?.locationId===r&&(this.location$.next(null),i!=="internal"&&(this.draftLocationMap.location=null)),this.removeCustomLocation(e)}else this.location$.next(null),this.locations$.next({}),i!=="internal"&&(this.draftLocationMap.location=null,this.draftLocationMap.locations=[])}catch(r){this.loggingService.catch("Error in removeLocation: ",r)}}getLocation$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getLocation$","color: green;"),this.location$.asObservable()}getLocation(){return this.loggingService.log("%c[WB] Calling FUNCTION: getLocation$","color: green;"),this.location$.value?JSON.parse(JSON.stringify(this.location$.value)):null}excludeLocationIds(e){try{this.excludedLocationIds$.next([...e])}catch(i){this.loggingService.catch("Error in excludeLocationIds: ",i)}}getExcludedLocationIds$(){try{return this.excludedLocationIds$.asObservable()}catch(e){return this.loggingService.catch("Error in getExcludedLocationIds$: ",e),re([])}}updateOrganizationMetadata(){try{if(this.db&&this.authService.getUser()?.organizationId){let e=this.documentPaths$.value,i=this.organizationConfig$.value?.organizationId;if(!this.organizationMetadata$.value?.[i]){let a=new VM;a.apiKey=this.configService?.getApiKey()??"",a.organizationId=i,a.clientOrganizationId=this.organizationConfig$.value?.clientOrganizationId,this.commonDbService?.updateData({feature:"organizationMetadata",data:JSON.parse(JSON.stringify(a)),properties:{organizationId:i,documentId:e?.documentId??""}}),this.subscribeToOrganizationMetadata()}}}catch(e){this.loggingService.catch("Error in updateOrganizationMetadata: ",e)}}updateFolderMetadata(){return te(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: updateFolderMetadata","color: green;"),this.db&&this.authService.getUser()&&this.folderConfig$.value){let e=this.documentPaths$.value,i=this.folderConfig$.value;if(!(yield this.commonDbService?.getData({feature:"folderMetadata",properties:{organizationId:e?.organizationId??"",folderId:i?.veltFolderId??""}}))?.metadata){let a={folderId:i?.folderId,veltFolderId:i?.veltFolderId,apiKey:this.configService?.getApiKey()??"",organizationId:e?.organizationId,clientOrganizationId:e?.clientOrganizationId,createdAt:Date.now(),lastUpdated:Date.now(),parentFolderId:"root",veltParentFolderId:"root"};this.commonDbService?.updateData({feature:"folderMetadata",data:JSON.parse(JSON.stringify({metadata:a})),properties:{organizationId:e?.organizationId??"",folderId:i?.veltFolderId??""}})}}}catch(e){this.loggingService.catch("Error in updateFolderMetadata: ",e)}})}updateDocumentMetadata(){return te(this,null,function*(){try{if(this.db&&this.authService.getUser()){let e=this.documentPaths$.value;if(e){let i=this.getDocumentIds();i.find(a=>a.documentId===e.documentId)||i.push({documentId:e.documentId??"",clientDocumentId:e.clientDocumentId??""});let r=i.map(a=>te(this,null,function*(){let s=new TM;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=Ii();let c=this.getFolderConfig();s?.pageInfo?.deviceInfo&&delete s?.pageInfo?.deviceInfo;let p=!0,u=this.documentMetadata$.value?.[a.documentId];if(c){let C=yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:a?.documentId??"",organizationId:e?.organizationId??"",field:"metadata"}});C?.clientDocumentId?C?.folderId&&(C?.folderId!==c?.folderId||C?.veltFolderId!==c?.veltFolderId)?(this.loggingService.catch(`Folder id mismatch for document ${a?.clientDocumentId??""}`),p=!1):C?.folderId===c?.folderId?(c?.folderId&&(s.folderId=c.folderId),c?.veltFolderId&&(s.veltFolderId=c.veltFolderId)):(this.loggingService.catch(`Document ${a?.clientDocumentId??""} is not in the folder ${c?.folderId??""}`),p=!1):(c?.folderId&&(s.folderId=c.folderId),c?.veltFolderId&&(s.veltFolderId=c.veltFolderId))}if(u){let C={};Object.entries(s).forEach(([E,A])=>{C[E]=A}),_o(C,u)&&(p=!1)}p&&(yield this.commonDbService?.updateData({feature:"documentMetadata",data:JSON.parse(JSON.stringify(s)),properties:{organizationId:e?.organizationId??"",documentId:a?.documentId??""}}))}));yield Promise.all(r),this.subscribeToDocumentMetadata(i)}}}catch(e){this.loggingService.catch("Error in updateDocumentMetadata: ",e)}})}updateDocumentLocationMetadata(){return te(this,null,function*(){try{if(this.db&&this.authService.getUser()){let e=this.documentPaths$.value,i=this.location$.value;if(e&&i){let r=this.getDocumentIds();r.find(a=>a.documentId===e.documentId)||r.push({documentId:e.documentId??"",clientDocumentId:e.clientDocumentId??""});for(let a of r){let s=yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:a?.documentId??"",organizationId:e?.organizationId??"",field:"metadata"}}),c=new MM;c.locationId=i?.locationId,c.veltLocationId=BV(i?.location?.id??""),c.location=i?.location,c.pageInfo=Ii(),c?.pageInfo?.deviceInfo&&delete c?.pageInfo?.deviceInfo;let p=T(I({},s),{[U.FIREBASE_PARTIAL_PATH_LOCATIONS]:T(I({},s[U.FIREBASE_PARTIAL_PATH_LOCATIONS]??{}),{[i?.locationId]:c})}),u=T(I({},c),{metadata:I({},this.getBaseMetadata()??{})});this.commonDbService?.updateData({feature:"documentMetadata",data:JSON.parse(JSON.stringify(p)),properties:{documentId:a?.documentId??"",organizationId:e?.organizationId??""}}),this.commonDbService?.updateData({feature:"locationMetadata",data:JSON.parse(JSON.stringify(u)),properties:{documentId:a?.documentId??"",organizationId:e?.organizationId??"",id:c.veltLocationId}});let C=this.locationMetadata$.value;if(C||(C={}),i?.location?.id){let E=C?.[a.documentId],A=E?.[i?.location?.id??""];C&&(E||(C[a.documentId]={}),A||(C[a.documentId][i?.location?.id??""]={}),C[a.documentId][i?.location?.id??""]=T(I({},A),{location:i?.location})),Object.keys(C||{}).length>0&&this.locationMetadata$.next(C)}}}}}catch(e){this.loggingService.catch("Error in updateDocumentLocationMetadata: ",e)}})}genarateLocationId(e){try{return e&&typeof e=="object"?Cn(JSON.stringify(Qo(e))):0}catch(i){return this.loggingService.catch("Error in genarateLocationId: ",i),0}}addLocation(e){try{let i=null;if(e&&typeof e=="object"){if(e?.version&&(!e?.version?.id||!e?.version?.name)){this.loggingService.catch("Error in setLocation: ","If you're setting version then add id and name fields to version object.");return}let r=I({},e),a=this.locations$.value;e?.id&&Object.keys(a).forEach(p=>{let u=a[p];u.location?.id===e.id&&(r=I(I({},u.location),e),delete a[p])});let s=this.genarateLocationId(r),c={locationId:s,location:r};i=c,this.locations$.next(T(I({},a),{[s]:c})),this.isDocumentIdInDebounceQueue&&this.draftLocationMap.locations.push(r),this.analyticsService.trackEvent(X.Events.Doc.LOCATION_ADDED,{addedLocation:e,addedLocationId:s},!0,this.getUserIdForAnalytics())}return i}catch(i){return this.loggingService.catch("Error in DocService addLocation:",i),null}}removeCustomLocation(e,i="internal"){try{let r=this.genarateLocationId(e),a=this.locations$.value;a[r]&&(delete a[r],this.locations$.next(I({},a)),i!=="internal"&&this.isDocumentIdInDebounceQueue&&(this.draftLocationMap.locations=this.draftLocationMap.locations.filter(s=>s.id!==e.id)))}catch(r){this.loggingService.catch("Error in DocService removeLocation:",r)}}getLocationByClientLocationId(e){try{let i=this.getLocation()?.location;if(i?.id===e)return i;{let r=this.getLocations();Object.keys(r).forEach(a=>{let s=r[a];s.location?.id===e&&(i=s.location)})}return i}catch(i){this.loggingService.catch("Error in DocService getLocationByClientLocationId:",i);return}}removeLocationIfNotInDom(){try{let e=this.locations$.value,i=document.querySelectorAll(`[${U.ATTRIBUTES.VELT_LOCATION}]`),r=[];i.forEach(a=>{let s=a.getAttribute(U.ATTRIBUTES.VELT_LOCATION);if(s){let c=JSON.parse(s),p=this.genarateLocationId(c);r.push(p)}}),Object.keys(e).forEach(a=>{let s=e[a];r.includes(s.locationId)||delete e[a]}),this.locations$.next(I({},e))}catch(e){this.loggingService.catch("Error in DocService removeLocationIfNotInDom:",e)}}getLocations$(){try{return this.locations$.asObservable()}catch(e){return this.loggingService.catch("Error in DocService getLocations$:",e),re({})}}getLocations(){try{return this.locations$.value}catch(e){return this.loggingService.catch("Error in DocService getLocations:",e),{}}}getLocationFromElement(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: getLocationFromElement","color: green;");let i=null;if(e?.getAttribute(U.ATTRIBUTES.VELT_LOCATION)?i=e:i=e.closest(`[${U.ATTRIBUTES.VELT_LOCATION}]`),i){let r=i?.getAttribute(U.ATTRIBUTES.VELT_LOCATION);if(r){let a=JSON.parse(r);return{locationId:this.genarateLocationId(a),location:a}}}return null}catch(i){return this.loggingService.catch("Error in DocService getLocationFromElement:",i),null}}getElementMapWithLocation(){try{this.loggingService.log("%c[WB] Calling FUNCTION: getElementMapWithLocation","color: green;");let e={};return document.querySelectorAll(`[${U.ATTRIBUTES.VELT_LOCATION}], [${U.ATTRIBUTES.VELT_LOCATION_ID}]`).forEach(r=>{if(r.getAttribute(U.ATTRIBUTES.VELT_LOCATION)){let a=this.getLocationFromElement(r);a?.locationId&&(e[a.locationId]={element:r,location:a})}else if(r.getAttribute(U.ATTRIBUTES.VELT_LOCATION_ID)){let a=r.getAttribute(U.ATTRIBUTES.VELT_LOCATION_ID);if(a){let s=this.getLocationByClientLocationId(a);s?.locationId&&(e[s.locationId]={element:r,location:s});let c={id:a},p=this.genarateLocationId(c);e[a]={element:r,location:{locationId:p,location:c}}}}}),e}catch(e){return this.loggingService.catch("Error in DocService getElementMapWithLocation:",e),{}}}getAdditionLocationFromElement(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: getAdditionLocationFromElement","color: green;");let i;if(i=e?.closest(`[${U.ATTRIBUTES.VELT_LOCATION}], [${U.ATTRIBUTES.VELT_LOCATION_ID}]`),i){if(i?.getAttribute(U.ATTRIBUTES.VELT_LOCATION)){let r=i?.getAttribute(U.ATTRIBUTES.VELT_LOCATION);if(r)return JSON.parse(r)}else if(i?.getAttribute(U.ATTRIBUTES.VELT_LOCATION_ID)){let r=i?.getAttribute(U.ATTRIBUTES.VELT_LOCATION_ID);if(r)return{id:r}}}return null}catch(i){return this.loggingService.catch("Error in DocService getAdditionLocationFromElement:",i),null}}getAdditionalDocumentIdFromElement(e){try{return e?.closest(`[${U.ATTRIBUTES.VELT_DOCUMENT_ID}]`)?.getAttribute(U.ATTRIBUTES.VELT_DOCUMENT_ID)||null}catch(i){return this.loggingService.catch("Error in DocService getAdditionalDocumentIdFromElement:",i),null}}getDocumentMetadata(e){try{return e?this.documentMetadata$.value?.[e]||null:this.documentMetadata$.value?.[this.documentPaths$.value?.documentId??""]||null}catch(i){return this.loggingService.catch("Error in DocService getDocumentMetadata:",i),null}}getAllDocumentMetadata(){try{return Object.values(this.documentMetadata$.value||{})}catch(e){return this.loggingService.catch("Error in DocService getAllDocumentMetadata:",e),[]}}getDocumentMetadataOfAvailableDocuments(){try{this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentMetadataOfAvailableDocuments","color: green;");let e=this.documentMetadata$.value||{},i={},r=this.getFolderConfig();if(r?.veltFolderId&&r?.allDocuments)Object.values(e).forEach(a=>{a?.documentId&&a?.veltFolderId===r?.veltFolderId&&(i[a.documentId]=a)});else{let a=this.documentIds$.value;if(a?.length)a.forEach(s=>{let c=e?.[s.documentId];c&&(i[s.documentId]=c)});else if(this.documentPaths$.value?.documentId){let s=e?.[this.documentPaths$.value?.documentId];s&&(i[this.documentPaths$.value?.documentId]=s)}}return Object.values(i)}catch(e){return this.loggingService.catch("Error in DocService getDocumentMetadataOfAvailableDocuments:",e),[]}}getDocumentMetadata$(e){return this.documentMetadata$.asObservable().pipe(ce(i=>i?.[e??this.documentPaths$.value?.documentId??""]||null))}getOrganizationMetadata(e){return this.organizationMetadata$.value?.[e]||null}getOrganizationMetadata$(e){return this.organizationMetadata$.asObservable().pipe(ce(i=>i?.[e]||null))}getCustomerMetadata(){return this.customerMetadata$.value}getCustomerMetadata$(){return this.customerMetadata$.asObservable()}getOrganizationConfig$(){return this.organizationConfig$.asObservable()}getOrganizationConfig(){return this.organizationConfig$.value}getMetadataFromType(e,i){try{switch(e){case"area":return;case"comment":return i?.multiThreadAnnotationId?this.commentService?.getMultiThreadAnnotationById(i.multiThreadAnnotationId)?.metadata:void 0;case"reaction":case"recorder":return i?.commentAnnotationId?this.commentService?.getAnnotationById(i.commentAnnotationId)?.metadata:void 0;default:return}}catch(r){this.loggingService.catch("Error in DocService getMetadataFromType:",r);return}}getDefaultMetadata({clientDocumentId:e,documentId:i}){try{let r=this.documentPaths$.value;if(!r)return;let a=e||r.clientDocumentId,s=i||r.documentId,c=this.getDocumentMetadata(s);if(!c)return;let p=c?.folderId,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,i){try{let r,a;i?.element?r=this.getAdditionalDocumentIdFromElement(i.element)||void 0:i?.clientDocumentId&&(r=i.clientDocumentId),r&&(a=this.generateDocumentId(r));let s=this.getMetadataFromType(e,i),c=this.getDefaultMetadata({clientDocumentId:r,documentId:a});return s||c||{}}catch(r){return this.loggingService.catch("Error in DocService getBaseMetadata:",r),{}}}getServerId({documentId:e,organizationId:i}){try{return e&&(e=this.generateDocumentId(e)),i&&(i=this.generateOrganizationId(i)),{documentId:e,organizationId:i}}catch(r){return this.loggingService.catch("Error in DocService getServerId:",r),null}}fetchDocuments(e){return te(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=_l(e?.folderId);r.push(dt("metadata.veltFolderId","==",s))}return e?.documentIds?.length&&!e?.allDocuments&&r.push(dt("metadata.documentId","in",e?.documentIds?.map(s=>this.generateDocumentId(s)).slice(0,30))),yield this.commonDbService?.queryData({feature:"allDocuments",properties:{firestoreQuery:r,apiKey:this.apiKey??"",organizationId:this.generateOrganizationId(e?.organizationId)??this.documentPaths$.value?.organizationId,documentId:this.documentPaths$.value?.documentId}})}catch(i){return this.loggingService.catch("Error in DocService fetchDocuments:",i),[]}})}fetchLocations(e){return te(this,null,function*(){try{if(!this.authService.getUser())return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),[];let r=[];if(!e?.organizationId)return this.loggingService.catch("Error in fetchLocations: organizationId is required"),[];if(e?.folderId){let s=_l(e?.folderId);r.push(dt("metadata.veltFolderId","==",s))}return e?.documentIds?.length&&!e?.allDocuments&&r.push(dt("metadata.documentId","in",e?.documentIds?.map(s=>this.generateDocumentId(s)).slice(0,30))),yield this.commonDbService?.queryData({feature:"allLocations",properties:{firestoreQuery:r,apiKey:this.apiKey??"",organizationId:this.generateOrganizationId(e?.organizationId)??this.documentPaths$.value?.organizationId,documentId:this.documentPaths$.value?.documentId}})}catch(i){return this.loggingService.catch("Error in DocService fetchLocations:",i),[]}})}updateDocuments(e){return te(this,null,function*(){try{if(!this.authService.getUser())return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),[];let{organizationId:r,documents:a}=e;if(!r&&(r=this.documentPaths$.value?.clientOrganizationId,!r))return this.loggingService.catch("Error in updateDocuments: organizationId is required"),[];if(!a||a.length===0)return this.loggingService.catch("Error in updateDocuments: documents is required"),[];let s=[],c=this.documentMetadata$.value;a.forEach(p=>{delete p?.organizationId,delete p?.clientDocumentId,delete p?.clientOrganizationId,delete p?.apiKey;let u=dc(p.documentId),C=c?.[u];C&&(c[u]=I(I({},C),p)),p&&this.commonDbService&&s.push(this.commonDbService.updateData({feature:"documentMetadata",data:JSON.parse(JSON.stringify(p)),properties:{organizationId:pc(r),documentId:u}}))}),yield Promise.all(s),this.documentMetadata$.next(c)}catch(i){return this.loggingService.catch("Error in DocService updateDocuments:",i),[]}})}updateLocations(e){return te(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=>dc(C)),p=[],u=this.locationMetadata$.value;u||(u={}),c.forEach(C=>{a.forEach(E=>{let A=this.location$.value;if(E?.id===A?.location?.id&&this.location$.next({locationId:A?.locationId,location:E}),E?.id){delete E?.metadata;let B=BV(E.id),G=u?.[C],K=G?.[E.id];u&&(G||(u[C]={}),K||(u[C][E.id]={}),u[C][E.id]=T(I({},K),{location:E})),E&&this.commonDbService&&p.push(this.commonDbService.updateData({feature:"locationMetadata",data:JSON.parse(JSON.stringify({location:E})),properties:{organizationId:pc(r),documentId:C,id:B}}))}})}),yield Promise.all(p),Object.keys(u||{}).length>0&&this.locationMetadata$.next(u)}catch(i){return this.loggingService.catch("Error in DocService updateLocations:",i),[]}})}fetchFolders(e){return te(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=_l(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:[dt("metadata.veltParentFolderId","==",c)],folderId:c,apiKey:this.apiKey??"",organizationId:s,documentId:this.documentPaths$.value?.documentId}})}else r=yield this.commonDbService?.queryData({feature:"allFolders",properties:{apiKey:this.apiKey??"",organizationId:s,documentId:this.documentPaths$.value?.documentId}});return{data:r,parentFolders:a}}catch(i){return this.loggingService.catch("Error in DocService getFoldersRequest:",i),{data:[],parentFolders:[]}}})}getDocumentIam$(){return this.authService.getUser$().pipe(ue(e=>e?this.documentPaths$.pipe(ue(i=>i?.documentIam?this.commonDbService?.dbListener({feature:"documentIam",properties:{documentId:i.documentId,organizationId:i.organizationId,isCollection:!1}}).pipe(ce(r=>r?.data?.docIamConfig??r?.data),qt((r,a)=>JSON.stringify(r??{})===JSON.stringify(a??{}))):re(null))):re(null)))}getDocumentAccessType(e){try{return e&&e.features&&e.features.all?e.features.all.restricted?pi.RESTRICTED:pi.PUBLIC:e&&e.documentAccessType?e.documentAccessType:pi.PUBLIC}catch(i){return this.loggingService.catch("Error in DocService getDocumentAccessType:",i),pi.PUBLIC}}changeDocumentAccessType(e){return te(this,null,function*(){try{let i=this.documentPaths$.value;if(i){let r=yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:i?.documentId??"",organizationId:i?.organizationId??"",field:"docIamConfig"}});switch(delete r.documentAccessType,r.features||(r.features={}),r.features.all||(r.features.all={}),e){case pi.PUBLIC:r.features.all.restricted=!1;break;case pi.RESTRICTED:r.features.all.restricted=!0,r.features.all.guestMode=!1;break;default:break}this.commonDbService?.updateData({feature:"documentAccessType",data:JSON.parse(JSON.stringify(r)),properties:{documentId:i?.documentId??"",organizationId:i?.organizationId??""}})}}catch(i){this.loggingService.catch("Error in DocService changeDocumentAccessType:",i)}})}getUserIdForAnalytics(){try{return this.authService?.getAuthUser()?.uid||""}catch(e){return this.loggingService.catch("Error in DocService getUserIdForAnalytics:",e),""}}setUIState(e){try{this.uiState.next(I(I({},this.uiState.value),e))}catch(i){this.loggingService.catch("Error in DocService setUIState:",i)}}getUIState$(){return this.uiState.asObservable()}};o.\u0275fac=function(i){return new(i||o)(Q(Ke),Q(je),Q(un),Q(Fe),Q(jt),Q(y),Q(bs),Q(Em))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var zn=(()=>{let o=class o{constructor(e,i,r,a){this.analyticsService=e,this.authService=i,this.docService=r,this.loggingService=a,this.defaultUserDataProvider={get:s=>te(this,null,function*(){return{}})},this.resolveTimeout=1*60*1e3,this.maxResolveAttempts=1,this.resolveAttempts=new Map,this.subscriptions=new cn,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)}}ngOnDestroy(){try{this.subscriptions.unsubscribe(),this.pendingResolutions.clear(),this.resolveAttempts.clear()}catch(e){this.loggingService.catch("Error in UsersService ngOnDestroy:",e)}}resolveUsers(e,i=!1){return te(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling UsersService FUNCTION: resolveUsers","color: green;"),this.userDataProvider$.getValue()){let r={},a=[],s={};if(e?.forEach(c=>{let p=this.getUserById(c);p?r[c]=p:this.userByIdCalled$.getValue()[c]?i&&a.push(c):(a.push(c),this.userByIdCalled$.next(T(I({},this.userByIdCalled$.getValue()),{[c]:!0})))}),a.length>0){let c=this.userDataProvider$.getValue();if(c){let p={};try{let u,C=new Promise((E,A)=>{u=setTimeout(()=>{A(new Error("User resolution timeout"))},this.userDataProvider$.getValue()?.resolveTimeout||this.resolveTimeout)});p=yield Promise.race([c.get(a).finally(()=>{clearTimeout(u)}),C]),this.analyticsService.trackEvent(X.Events.Resolver.USER_RESOLVER_GET,{sourceMethod:"resolveUsers",source:"sdk",userIds:a})}catch(u){this.loggingService.catch("Error in UsersService resolveUsers getUsers:",u,{userIds:a})}finally{a?.forEach(u=>{p[u]||(p[u]={userId:u,name:`User ${u}`})})}Object.entries(p).forEach(([u,C])=>{C&&(r[u]=p?.[u],s[u]=p?.[u])})}}return Object.keys(s).length>0&&this.userById$.next(I(I({},this.userById$.getValue()),s)),r}else return{}}catch(r){return this.loggingService.catch("Error in UsersService resolveUsers:",r),{}}})}subscribeToDocuments(){return this.docService.getDocumentIds$().pipe(gn(e=>te(this,null,function*(){let i=yield this.getUsersFromCentralDb({documentIds:e?.map(r=>r.documentId)});this.resolveUsers(i)})))}getUsersFromCentralDb(i){return te(this,arguments,function*({documentIds:e}){try{return new Promise(r=>{r(["customuser1","customuser2","customuser3"])})}catch{return[]}})}getUserById$(){try{return this.loggingService.log("%c[WB] Calling UsersService FUNCTION: getUserById$","color: green;"),this.userById$.asObservable()}catch(e){return this.loggingService.catch("Error in UsersService getUserById$:",e),re({})}}setUserDataProvider(e){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setUserDataProvider","color: green;"),this.userDataProvider$.next(e)}catch(i){this.loggingService.catch("Error in UsersService setUserDataProvider:",i)}}userDataProviderAvailable(){try{return this.loggingService.log("%c[WB] Calling UsersService FUNCTION: userDataProviderAvailable","color: green;"),!!this.userDataProvider$.getValue()}catch(e){return this.loggingService.catch("Error in UsersService userDataProviderAvailable:",e),!1}}};o.\u0275fac=function(i){return new(i||o)(Q(Ke),Q(je),Q(lt),Q(y))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Mse=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.usersService=i}getUserIdsToResolveFromAreaAnnotations(e){try{this.loggingService.log("%c[WB] Calling AreaUtilsService FUNCTION: getUserIdsToResolveFromAreaAnnotations","color: green;");let i=new Set;for(let r of e)r?.from?.userId&&i.add(r?.from?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in AreaUtilsService getUserIdsToResolveFromAreaAnnotations:",i),[]}}mergeAreaWithUser(e){try{if(this.loggingService.log("%c[WB] Calling AreaUtilsService FUNCTION: mergeAreaWithUser","color: green;"),e?.from?.userId){let i=this.usersService.getUserById(e?.from?.userId);i&&(e.from=i)}return e}catch(i){return this.loggingService.catch("Error in AreaUtilsService mergeAreaWithUser:",i),e}}formatAreaData(e){try{return this.loggingService.log("%c[WB] Calling AreaUtilsService FUNCTION: formatAreaData","color: green;"),this.usersService.userDataProviderAvailable()&&e?.from?.userId&&(e.from={userId:e.from.userId}),e}catch(i){return this.loggingService.catch("Error in AreaUtilsService formatAreaData:",i),e}}};o.\u0275fac=function(i){return new(i||o)(Q(y),Q(zn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Pse=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.usersService=i}getUserIdsToResolveFromArrowAnnotations(e){try{this.loggingService.log("%c[WB] Calling ArrowUtilsService FUNCTION: getUserIdsToResolveFromArrowAnnotations","color: green;");let i=new Set;for(let r of e)r?.from?.userId&&i.add(r?.from?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in ArrowUtilsService getUserIdsToResolveFromArrowAnnotations:",i),[]}}mergeArrowWithUser(e){try{if(this.loggingService.log("%c[WB] Calling ArrowUtilsService FUNCTION: mergeArrowWithUser","color: green;"),e?.from?.userId){let i=this.usersService.getUserById(e?.from?.userId);i&&(e.from=i)}return e}catch(i){return this.loggingService.catch("Error in ArrowUtilsService mergeArrowWithUser:",i),e}}formatArrowData(e){try{return this.loggingService.log("%c[WB] Calling ArrowUtilsService FUNCTION: formatArrowData","color: green;"),this.usersService.userDataProviderAvailable()&&e?.from?.userId&&(e.from={userId:e.from.userId}),e}catch(i){return this.loggingService.catch("Error in ArrowUtilsService formatArrowData:",i),e}}};o.\u0275fac=function(i){return new(i||o)(Q(y),Q(zn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var zp=class{static getFirestoreProdDbName(o,t){return t?.storeDbId??(this.isTestingDb(t?.databaseURL??"")?"sdktest":`apikey${o.toLowerCase()}`)}static isTestingDb(o){try{return o.includes("-test")}catch(t){return mt.error("Error in isTestingDb:",t),!1}}};var Gp=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.analyticsService=i,this.retrySaveConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.retryDeleteConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.attachmentDataProvider$=new 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 te(this,null,function*(){try{this.loggingService.log("%c[WB] Calling AttachmentResolverService FUNCTION: saveAttachment","color: green;");let i=this.getProvider();if(!this.attachmentDataProviderAvailable())throw new Error("Attachment save data provider not available");let r=yield uc(()=>i?.save({attachment:e.attachment,event:e.eventType,metadata:e.attachment.metadata})||Promise.resolve(void 0),"saveAttachment",this.retrySaveConfig);if(r?.statusCode!==200){this.loggingService.catch(r?.message??"Error in AttachmentResolverService saveAttachment:");return}return this.analyticsService.trackEvent(X.Events.Resolver.ATTACHMENT_RESOLVER_SAVE,{sourceMethod:"saveAttachment",source:"sdk",attachmentId:e.attachment.attachmentId,eventType:e.eventType}),r}catch(i){this.loggingService.warn("Error in AttachmentResolverService saveAttachment:",i);return}})}deleteAttachment(r){return te(this,arguments,function*({attachmentId:e,metadata:i}){try{this.loggingService.log("%c[WB] Calling AttachmentResolverService FUNCTION: deleteAttachment","color: green;");let a=this.getProvider();if(!this.attachmentDataProviderAvailable())throw new Error("Attachment delete data provider not available");let s=yield uc(()=>a?.delete({attachmentId:e,metadata:i,event:Wa.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(X.Events.Resolver.ATTACHMENT_RESOLVER_DELETE,{sourceMethod:"deleteAttachment",source:"sdk",attachmentId:e}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0})}catch(a){return this.loggingService.warn("Error in AttachmentResolverService deleteAttachment:",a),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0}}})}setAttachmentDataProvider(e){try{if(e){this.loggingService.log("Setting attachment data provider");let r=["save","delete"].filter(a=>!(a in e)||typeof e[a]!="function");if(r.length>0){let a=`DataProviders.attachment is invalid. The following methods are missing or are not functions: ${r.join(", ")}.`;this.loggingService.catch(a);return}else this.attachmentDataProvider$.next(e)}}catch(i){this.loggingService.catch("Error in AttachmentResolverService setAttachmentDataProvider:",i)}}attachmentDataProviderAvailable(){try{return!!this.attachmentDataProvider$.getValue()}catch(e){return this.loggingService.catch("Error in AttachmentResolverService attachmentDataProviderAvailable:",e),!1}}};o.\u0275fac=function(i){return new(i||o)(Q(y),Q(Ke))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Yv=(()=>{let o=class o{constructor(e,i,r,a,s,c,p){this.loggingService=e,this.usersService=i,this.authService=r,this.functions=a,this.configService=s,this.commentAnnotationsResolverService=c,this.attachmentResolverService=p,this.notificationActionTypeMap={[Ut.NEWLY_ADDED]:Wa.COMMENT_ANNOTATION_ADD,[Ut.ADDED]:Wa.COMMENT_ADD,[Ut.UPDATED]:Wa.COMMENT_UPDATE,[Ut.DELETED]:Wa.COMMENT_DELETE}}setNotificationService(e){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: setNotificationService","color: green;"),this.notificationService=e}catch(i){this.loggingService.catch("Error in CommentUtilsService setNotificationService: ",i)}}getUserIdsToResolveFromComments(e){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: getUserIdsToResolveFromComments","color: green;");let i=new Set;for(let r of e){if(r?.from?.userId&&i.add(r?.from?.userId),r?.comments)for(let a of r?.comments){if(a?.from?.userId&&i.add(a?.from?.userId),a?.to)for(let s of a?.to)s?.userId&&i.add(s?.userId);if(a?.taggedUserContacts)for(let s of a?.taggedUserContacts)s?.userId&&i.add(s?.userId)}if(r?.assignedTo?.userId&&i.add(r?.assignedTo?.userId),r?.subscribedUsers)for(let a of Object.values(r?.subscribedUsers))a.user.userId&&i.add(a.user.userId);if(r?.unsubscribedUsers)for(let a of Object.values(r?.unsubscribedUsers))a.user.userId&&i.add(a.user.userId)}return Array.from(i)}catch(i){return this.loggingService.catch("Error in CommentUtilsService getUserIdsToResolveFromComments:",i),[]}}mergeCommentWithUser(e){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: mergeCommentWithUser","color: green;"),e?.from?.userId){let i=this.usersService.getUserById(e?.from?.userId);i&&(e.from=i)}if(e?.comments)for(let i of e?.comments){if(i?.from?.userId){let a=this.usersService.getUserById(i?.from?.userId);a&&(i.from=a)}i?.to&&(i.to=i?.to?.map(a=>{if(a?.userId){let s=this.usersService.getUserById(a?.userId);if(s)return I(I({},a),s)}return a})),i?.taggedUserContacts&&(i.taggedUserContacts=i?.taggedUserContacts?.map(a=>{if(a?.contact){let s=this.usersService.getUserById(a?.contact?.userId);s&&(a.contact=s,(s?.name||s?.email)&&(a.text=`@${s?.name||s?.email}`))}return a})),(i?.taggedUserContacts?.filter((a,s,c)=>c.findIndex(p=>p.text===a.text)===s)||[]).forEach(a=>{if(a?.text){let s=new RegExp(dm(`{{${a.userId}}}`),"g");i.commentText=i.commentText?.replaceAll(s,a.text),i.commentHtml=i.commentHtml?.replaceAll(s,a.text)}})}if(e?.assignedTo?.userId){let i=this.usersService.getUserById(e?.assignedTo?.userId);i&&(e.assignedTo=i)}if(e?.subscribedUsers)for(let i of Object.values(e?.subscribedUsers)){let r=this.usersService.getUserById(i.user.userId);r&&e?.subscribedUsers?.id?.user&&(e.subscribedUsers.id.user=r)}if(e?.unsubscribedUsers)for(let i of Object.values(e?.unsubscribedUsers)){let r=this.usersService.getUserById(i.user.userId);r&&e?.unsubscribedUsers?.id?.user&&(e.unsubscribedUsers.id.user=r)}return e}catch(i){return this.loggingService.catch("Error in CommentUtilsService mergeCommentWithUser:",i),e}}formatCommentData(e){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: formatCommentData","color: green;"),e?.comments?.forEach(i=>{i?.commentText&&i?.commentText?.length>0&&(i.isCommentTextAvailable=!0)}),this.usersService.userDataProviderAvailable()){if(e?.from?.userId&&(e.from={userId:e.from.userId}),e?.assignedTo?.userId&&(e.assignedTo={userId:e.assignedTo.userId}),e?.subscribedUsers)for(let i of Object.keys(e?.subscribedUsers))e.subscribedUsers[i].user={userId:e?.subscribedUsers[i].user.userId};if(e?.unsubscribedUsers)for(let i of Object.keys(e?.unsubscribedUsers))e.unsubscribedUsers[i].user={userId:e?.unsubscribedUsers[i].user.userId}}return e?.comments&&(e.comments=e?.comments?.map(i=>this.formatCommentThreadData(i))),e}catch(i){return this.loggingService.catch("Error in CommentUtilsService formatCommentData:",i),e}}mergeStrippedDataWithCommentAnnotations(e){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: mergeStrippedDataWithCommentAnnotations","color: green;"),!this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())return e;let i=this.commentAnnotationsResolverService.getAnnotationById(e?.annotationId),r=this.attachmentResolverService.attachmentDataProviderAvailable();return i&&e?.comments?.forEach(a=>{let s=i?.comments?.[a?.commentId];if(s){a.commentHtml=s?.commentHtml,a.commentText=s?.commentText;let c=s?.attachments;r&&c&&a.attachments?.forEach(p=>{let u=p?.attachmentId;c?.[u]&&(p.name=c?.[u]?.name,p.url=c?.[u]?.url)})}}),e}catch(i){return this.loggingService.catch("Error in CommentUtilsService mergeStrippedDataWithCommentAnnotations:",i),e}}mergeLocationWithCommentAnnotations(e,i){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: mergeLocationWithCommentAnnotations","color: green;");let r=e?.location?.id,a=e?.metadata?.documentId;if(!r||!a)return e;let s=i?.[a]?.[r];return s&&(e.location=s?.location),e}catch(r){return this.loggingService.catch("Error in CommentUtilsService mergeLocationWithCommentAnnotations:",r),e}}isCommentsDataChanged(e,i){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: isCommentsDataChanged","color: green;");let r=this.commentAnnotationsResolverService.getCommentAnnotationById(i);return r?!_o(e,r):!0}catch(r){return this.loggingService.catch("Error in CommentUtilsService isCommentsDataChanged:",r),!0}}stripCommentAnnotationData({data:e,actionType:i}){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: stripCommentAnnotationData","color: green;"),!this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable()||!i)return{originalData:e,strippedData:null};let r=this.attachmentResolverService.attachmentDataProviderAvailable(),a=this.notificationActionTypeMap?.[i];if(!a)return{originalData:e,strippedData:null};let s={},c=null;if(e&&e.annotationId){let p=e.annotationId;if(s[p]={annotationId:p,metadata:hv(e.metadata??{}),comments:{}},e.comments?.forEach(E=>{if(E.commentId){let A;r&&(A={},E.attachments?.forEach(B=>{A[B.attachmentId]={attachmentId:B.attachmentId,name:B.name,url:B.url}})),s[p].comments[E.commentId]=I(I(I({commentId:E.commentId},E?.commentHtml&&{commentHtml:E?.commentHtml}),E?.commentText&&{commentText:E?.commentText}),A&&{attachments:A})}}),!this.isCommentsDataChanged(s[p],p))return{strippedData:null,originalData:e};let C=new ko;Object.assign(C,e),C.comments=e.comments?.map(E=>{let A=new _c;if(Object.assign(A,E),A.isCommentResolverUsed=!0,r){let B=A.attachments?.map(G=>(G.isAttachmentResolverUsed=!0,delete G?.name,delete G?.url,G));A.attachments=B}return delete A?.commentHtml,delete A?.commentText,A})||[],c=C}return{strippedData:s,originalData:c,eventType:a}}catch(r){return this.loggingService.catch("Error in CommentAnnotationsResolverService stripCommentAnnotationData:",r),{strippedData:null,originalData:null}}}formatCommentThreadData(e){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: formatCommentThreadData","color: green;"),this.usersService.userDataProviderAvailable()){e?.from?.userId&&(e.from={userId:e.from.userId}),e?.to&&(e.to=e?.to?.map(r=>r?.userId?{userId:r.userId}:r)),e?.taggedUserContacts&&(e.taggedUserContacts=e?.taggedUserContacts?.map(r=>r?.contact?T(I({},r),{contact:{userId:r.userId}}):r));let i=e?.taggedUserContacts?.filter((r,a,s)=>s.findIndex(c=>c.text===r.text)===a)||[];i.forEach(r=>{if(r?.text){let a=new RegExp(dm(r.text),"g");e.commentText=e.commentText?.replaceAll(a,s=>`{{${r.userId}}}`),e.commentHtml=e.commentHtml?.replaceAll(a,s=>`{{${r.userId}}}`)}}),i.forEach(r=>{r?.text&&(r.text="")})}return e}catch(i){return this.loggingService.catch("Error in CommentUtilsService formatCommentThreadData:",i),e}}handleCommentEncryption(s){return te(this,arguments,function*({data:e,firestorePath:i,extraData:r,eventType:a}){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: handleCommentEncryption","color: green;");let c=c6(this.authService.getFirebaseConfig()?.firebaseOptions),p=_r(this.functions,Sr({url:Xn.cloudFunction?.[c]?.setEncryptedData,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:20*60*1e3});if(r){r=this.notificationService?.processNotificationData(r),r.annotationData=e;let A=r?.targetAnnotationData?.commentId;if(A){let B=e?.comments?.find(G=>G?.commentId===A);B&&(r.targetAnnotationData=B)}}let u=zp.getFirestoreProdDbName(this.configService.getApiKey()??"",this.authService.getFirebaseConfig()?.firebaseOptions),C={path:i??"",data:e??{},dbId:u??"",notificationData:r||void 0,notificationURL:Xn.firebaseNotificationsDatabaseURL,feature:"comment",eventType:a??"PATCH",sdkVersion:pa()},E=yield Ap(C,this.authService.getUser()?.userId??"");yield p({veltData:E})}catch(c){this.loggingService.catch("Error in CommentUtilsService handleCommentEncryption:",c)}})}};o.\u0275fac=function(i){return new(i||o)(Q(y),Q(zn),Q(je),Q(Uo),Q(jt),Q(bs),Q(Gp))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var kse=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.usersService=i}getUserIdsToResolveFromUserIamData(e){try{this.loggingService.log("%c[WB] Calling ContactUtilsService FUNCTION: getUserIdsToResolveFromUserIamData","color: green;");let i=new Set;if(e?.length)for(let r of e)r?.user?.userId&&i.add(r?.user?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in ContactUtilsService getUserIdsToResolveFromUserIamData: ",i),[]}}mergeUserIamWithUser(e){try{if(this.loggingService.log("%c[WB] Calling ContactUtilsService FUNCTION: mergeUserIamWithUser","color: green;"),e?.user?.userId){let i=this.usersService.getUserById(e?.user?.userId);i&&(e=T(I({},e),{user:i}))}return e}catch(i){return this.loggingService.catch("Error in ContactUtilsService mergeUserIamWithUser: ",i),e}}};o.\u0275fac=function(i){return new(i||o)(Q(y),Q(zn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Rse=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.usersService=i}getUserIdsToResolveFromCursorUsers(e){try{this.loggingService.log("%c[WB] Calling CursorUtilsService FUNCTION: getUserIdsToResolveFromCursorUsers","color: green;");let i=new Set;for(let r of e)r?.userId&&i.add(r?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in CursorUtilsService getUserIdsToResolveFromCursorUsers:",i),[]}}mergeCursorUserWithUser(e){try{if(this.loggingService.log("%c[WB] Calling CursorUtilsService FUNCTION: mergeCursorUserWithUser","color: green;"),this.usersService.userDataProviderAvailable()&&e?.userId){let i=this.usersService.getUserById(e?.userId);i&&(e=I(I({},e),i))}return e}catch(i){return this.loggingService.catch("Error in CursorUtilsService mergeCursorUserWithUser:",i),e}}formatCursorUserData(e){try{if(this.loggingService.log("%c[WB] Calling CursorUtilsService FUNCTION: formatCursorUserData","color: green;"),this.usersService.userDataProviderAvailable()){let i=["userId","comment","positionX","positionY","screenWidth","screenHeight","screenScrollHeight","onlineStatus","userSnippylyId","color","textColor","timestamp","type","selections","documentParamsId","documentParams","locationId","location","targetElement","position","isReadOnly","isAnonymous","pageInfo"];Object.keys(e).forEach(r=>{i.includes(r)||(e[r]=null)})}return e}catch(i){return this.loggingService.catch("Error in CursorUtilsService formatCursorUserData:",i),e}}};o.\u0275fac=function(i){return new(i||o)(Q(y),Q(zn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var WM=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.usersService=i}getUserIdsToResolveFromHuddleAttendees(e){try{this.loggingService.log("%c[WB] Calling HuddleUtilsService FUNCTION: getUserIdsToResolveFromHuddleAttendees","color: green;");let i=new Set;for(let r of e)r?.userId&&i.add(r?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in HuddleUtilsService getUserIdsToResolveFromHuddleAttendees:",i),[]}}mergeHuddleAttendeeWithUser(e){try{if(this.loggingService.log("%c[WB] Calling HuddleUtilsService FUNCTION: mergeHuddleAttendeeWithUser","color: green;"),e?.userId){let i=this.usersService.getUserById(e?.userId);i&&(e=I(I({},e),i))}return e}catch(i){return this.loggingService.catch("Error in HuddleUtilsService mergeHuddleAttendeeWithUser:",i),e}}formatHuddleAttendeeData(e){try{if(this.usersService.userDataProviderAvailable()){let i=["userId","userSnippylyId","state","timestamp","initialHuddleMode","streamMetadata","initialHuddleType","huddleOnCursorMode"];Object.keys(e).forEach(r=>{i.includes(r)||(e[r]=null)})}return e}catch(i){return this.loggingService.catch("Error in HuddleUtilsService formatHuddleAttendeeData:",i),e}}getUserIdsToResolveFromHuddleMessages(e){try{this.loggingService.log("%c[WB] Calling HuddleUtilsService FUNCTION: getUserIdsToResolveFromHuddleMessages","color: green;");let i=new Set;for(let r of e)r?.from?.userId&&i.add(r?.from?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in HuddleUtilsService getUserIdsToResolveFromHuddleMessages:",i),[]}}mergeHuddleMessageWithUser(e){try{if(this.loggingService.log("%c[WB] Calling HuddleUtilsService FUNCTION: mergeHuddleMessageWithUser","color: green;"),e?.from?.userId){let i=this.usersService.getUserById(e?.from?.userId);i&&(e.from=i)}return e}catch(i){return this.loggingService.catch("Error in HuddleUtilsService mergeHuddleMessageWithUser:",i),e}}resolveUsersFromHuddleMessages(e){return te(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling HuddleUtilsService FUNCTION: resolveUsersFromHuddleMessages","color: green;"),this.usersService.userDataProviderAvailable()){let i=this.getUserIdsToResolveFromHuddleMessages(e),r=yield this.usersService.resolveUsers(i);for(let a of e)a?.from?.userId&&r[a.from.userId]&&(a.from=r[a.from.userId])}return e}catch(i){return this.loggingService.catch("Error in HuddleUtilsService resolveUsersFromHuddleMessages:",i),e}})}formatHuddleMessageData(e){try{return this.loggingService.log("%c[WB] Calling HuddleUtilsService FUNCTION: formatHuddleMessageData","color: green;"),this.usersService.userDataProviderAvailable()&&e?.from?.userId&&(e.from={userId:e.from.userId}),e}catch(i){return this.loggingService.catch("Error in HuddleUtilsService formatHuddleMessageData:",i),e}}};o.\u0275fac=function(i){return new(i||o)(Q(y),Q(zn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Fse=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.usersService=i}getUserIdsToResolveFromLiveStateCustom(e){try{let i=new Set;return e?.updatedBy&&i.add(e?.updatedBy?.userId),Array.from(i)}catch(i){return this.loggingService.catch("Error in LiveStateUtilsService getUserIdsToResolveFromLiveStateCustom:",i),[]}}mergeLiveStateCustomWithUser(e){try{if(e?.updatedBy?.userId){let i=this.usersService.getUserById(e?.updatedBy?.userId);i&&(e.updatedBy=i)}return e}catch(i){return this.loggingService.catch("Error in LiveStateUtilsService mergeLiveStateCustomWithUser:",i),e}}formatLiveStateCustomData(e){try{return this.usersService.userDataProviderAvailable()&&e?.updatedBy&&(e.updatedBy={userId:e.updatedBy.userId}),e}catch(i){return this.loggingService.catch("Error in LiveStateUtilsService formatLiveStateCustomData:",i),e}}getUserIdsToResolveFromLiveStateCustoms(e){try{let i=new Set;for(let r of e)r?.updatedBy?.userId&&i.add(r?.updatedBy?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in LiveStateUtilsService getUserIdsToResolveFromLiveStateCustoms:",i),[]}}getUserIdsToResolveFromLiveStates(e){try{let i=new Set;return e?.default?.singleEditorMode?.editor?.userId&&i.add(e?.default?.singleEditorMode?.editor?.userId),Array.from(i)}catch(i){return this.loggingService.catch("Error in LiveStateUtilsService getUserIdsToResolveFromLiveStates:",i),[]}}mergeLiveStateWithUser(e){try{if(e?.default?.singleEditorMode?.editor?.userId){let i=this.usersService.getUserById(e?.default?.singleEditorMode?.editor?.userId);i&&(e.default.singleEditorMode.editor=i)}if(e?.default?.singleEditorMode?.requestEditorAccess?.user?.userId){let i=this.usersService.getUserById(e?.default?.singleEditorMode?.requestEditorAccess?.user?.userId);i&&(e.default.singleEditorMode.requestEditorAccess.user=i)}return e}catch(i){return this.loggingService.catch("Error in LiveStateUtilsService mergeLiveStateWithUser:",i),e}}formatLiveStateSingleEditorModeData(e){try{return this.usersService.userDataProviderAvailable()&&(e?.editor?.userId&&(e.editor={userId:e.editor.userId}),e?.requestEditorAccess?.user?.userId&&(e.requestEditorAccess.user={userId:e.requestEditorAccess.user.userId})),e}catch(i){return this.loggingService.catch("Error in LiveStateUtilsService formatLiveStateSingleEditorModeData:",i),e}}mergeLiveStateCustomsWithUsers(e){try{for(let i of e)if(i?.updatedBy?.userId){let r=this.usersService.getUserById(i?.updatedBy?.userId);r&&(i.updatedBy=r)}return e}catch(i){return this.loggingService.catch("Error in mergeLiveStateCustomsWithUsers:",i),e}}};o.\u0275fac=function(i){return new(i||o)(Q(y),Q(zn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Lse=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.usersService=i}getUserIdsToResolveFromMultiThreads(e){try{let i=new Set;for(let r of e)r?.from?.userId&&i.add(r?.from?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in MultiThreadUtilsService getUserIdsToResolveFromMultiThreads:",i),[]}}mergeMultiThreadWithUser(e){try{if(e?.from?.userId){let i=this.usersService.getUserById(e?.from?.userId);i&&(e.from=i)}return e}catch(i){return this.loggingService.catch("Error in MultiThreadUtilsService mergeMultiThreadWithUser:",i),e}}formatMultiThreadData(e){try{return this.usersService.userDataProviderAvailable()&&(e?.from?.userId&&(e.from={userId:e.from.userId}),e?.commentAnnotationsMap&&(e.commentAnnotationsMap=null)),e}catch(i){return this.loggingService.catch("Error in MultiThreadUtilsService formatMultiThreadData:",i),e}}};o.\u0275fac=function(i){return new(i||o)(Q(y),Q(zn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Kv=(()=>{let o=class o{constructor(e,i,r){this.authService=e,this.loggingService=i,this.usersService=r}getUserIdsToResolveFromRecorders(e){try{let i=new Set;for(let r of e)r?.from?.userId&&i.add(r?.from?.userId),r?.transcription?.from?.userId&&i.add(r?.transcription?.from?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in RecorderUtilsService getUserIdsToResolveFromRecorders:",i),[]}}mergeRecorderWithUser(e){try{if(e?.from?.userId){let i=this.usersService.getUserById(e?.from?.userId);i&&(e.from=i)}if(e?.transcription?.from?.userId){let i=this.usersService.getUserById(e?.transcription?.from?.userId);i&&(e.transcription.from=i)}return e}catch(i){return this.loggingService.catch("Error in RecorderUtilsService mergeRecorderWithUser:",i),e}}formatRecorderData(e,i){try{return e.transcription=e?.transcription?T(I({},e.transcription),{lastUpdated:i}):void 0,this.usersService.userDataProviderAvailable()&&(e?.from?.userId&&(e.from={userId:e.from.userId}),e?.transcription?.from?.userId&&(e.transcription.from={userId:e.transcription.from.userId})),e}catch(r){return this.loggingService.catch("Error in RecorderUtilsService formatRecorderData:",r),e}}formatRecorderDataForWhisperTranscription(e){try{return this.usersService.userDataProviderAvailable()&&e?.fromUser?.userId&&(e.fromUser={userId:e.fromUser?.userId}),e}catch(i){return this.loggingService.catch("Error in RecorderUtilsService formatRecorderDataForWhisperTranscription:",i),e}}encryptRecorderAnnotation(e){return te(this,null,function*(){try{return yield Ap(e,this.authService.getUser()?.userId??"")}catch(i){this.loggingService.catch("Error in RecorderUtilsService encryptRecorderAnnotation:",i);return}})}};o.\u0275fac=function(i){return new(i||o)(Q(je),Q(y),Q(zn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var qM=(()=>{let o=class o{constructor(e,i,r,a,s,c){this.commentUtilsService=e,this.recorderUtilsService=i,this.loggingService=r,this.usersService=a,this.authService=s,this.commentAnnotationsResolverService=c}getUserIdsToResolveFromNotifications(e){try{let i=new Set;for(let r of e){let{notification:a}=r;switch(a?.actionUser?.userId&&i.add(a?.actionUser?.userId),a?.displayHeadlineMessageTemplateData?.actionUser?.userId&&i.add(a?.displayHeadlineMessageTemplateData?.actionUser?.userId),a?.displayHeadlineMessageTemplateData?.recipientUser?.userId&&i.add(a?.displayHeadlineMessageTemplateData?.recipientUser?.userId),a?.notificationSource){case"comment":if(a?.notificationSourceData){let s=this.commentUtilsService.getUserIdsToResolveFromComments([a?.notificationSourceData]);for(let c of s)i.add(c)}break}}return Array.from(i)}catch(i){return this.loggingService.catch("Error in ReactionUtilsService getUserIdsToResolveFromRecorders:",i),[]}}mergeStrippedDataWithNotification(e){try{if(this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: mergeStrippedDataWithNotification","color: green;"),!this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())return e;let i=this.commentAnnotationsResolverService.getAnnotationById(e?.notification?.targetAnnotationId),r=e?.raw?.targetAnnotationData?.commentId,a=i?.comments?.[r]?.commentText,s=i?.comments?.[r]?.commentHtml;return a&&s&&e?.raw?.notificationSource==="comment"&&(e.notification.displayBodyMessageTemplate=a,e.raw.targetAnnotationData.commentText=a,e.raw.targetAnnotationData.commentHtml=s),e}catch(i){return this.loggingService.catch("Error in NotificationUtilsService mergeStrippedDataWithNotification:",i),e}}mergeLocationWithNotification(e,i){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: mergeLocationWithNotification","color: green;");let r=e?.notification?.notificationSourceData?.location?.id,a=e?.notification?.notificationSourceData?.metadata?.documentId;if(!r||!a)return e;let s=i?.[a]?.[r];return s&&(e.notification.notificationSourceData.location=s?.location,e?.raw?.annotationData?.location&&(e.raw.annotationData.location=s?.location)),e}catch(r){return this.loggingService.catch("Error in NotificationUtilsService mergeLocationWithNotification:",r),e}}mergeNotificationWithUser(e){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: mergeNotificationWithUser","color: green;");let{notification:i}=e;if(i?.actionUser?.userId){let r=this.usersService.getUserById(i?.actionUser?.userId);r&&(i.actionUser=r)}if(i?.displayHeadlineMessageTemplateData?.actionUser?.userId){let r=this.usersService.getUserById(i?.displayHeadlineMessageTemplateData?.actionUser?.userId);r&&(i.displayHeadlineMessageTemplateData.actionUser=r)}if(i?.displayHeadlineMessageTemplateData?.recipientUser?.userId){let r=this.usersService.getUserById(i?.displayHeadlineMessageTemplateData?.recipientUser?.userId);r&&(i.displayHeadlineMessageTemplateData.recipientUser=r)}switch(i?.notificationSource){case"comment":i?.notificationSourceData&&this.commentUtilsService.mergeCommentWithUser(i?.notificationSourceData);break}return e}catch(i){return this.loggingService.catch("Error in NotificationUtilsService mergeNotificationWithUser:",i),e}}formatNotification(e,i){try{switch(typeof e=="object"&&(e=JSON.parse(JSON.stringify(e))),this.usersService.userDataProviderAvailable()&&e?.actionUser&&(e.actionUser={userId:e.actionUser.userId}),e.notificationSource){case"comment":this.commentUtilsService.formatCommentData(e.annotationData),this.commentUtilsService.formatCommentThreadData(e.targetAnnotationData);break;case"recorder":this.recorderUtilsService.formatRecorderData(e.annotationData,i);break}return e}catch(r){return this.loggingService.catch("Error in NotificationUtilsService formatNotification: ",r),e}}getTargetAnnotationIdsFromNotifications(e){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: getTargetAnnotationIdsFromNotifications","color: green;");let i=[];return Object.values(e).forEach(r=>{r?.notification?.targetAnnotationId&&r?.raw?.notificationSource==="comment"&&i.push(r.notification.targetAnnotationId)}),i}catch(i){return this.loggingService.catch("Error in NotificationUtilsService getTargetAnnotationIdsFromNotifications:",i),[]}}handleNotificationEncryption(i){return te(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 Ap(e,r)}catch(r){return this.loggingService.catch("Error in NotificationUtilsService handleNotificationEncryption:",r),e}})}};o.\u0275fac=function(i){return new(i||o)(Q(Yv),Q(Kv),Q(y),Q(zn),Q(je),Q(bs))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Vse=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.usersService=i}getUserIdsToResolveFromPresenceUsers(e){try{let i=new Set;for(let r of e)r?.userId&&i.add(r?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in PresenceUtilsService getUserIdsToResolveFromPresenceUsers:",i),[]}}mergePresenceUserWithUser(e){try{if(this.usersService.userDataProviderAvailable()&&e?.userId){let i=this.usersService.getUserById(e?.userId);i&&(e=I(I({},e),i))}return e}catch(i){return this.loggingService.catch("Error in PresenceUtilsService mergePresenceUserWithUser:",i),e}}formatPresenceUserData(e){try{if(this.usersService.userDataProviderAvailable()){let i=["userId","onlineStatus","userSnippylyId","color","textColor","timestamp","type","selections","documentParamsId","documentParams","locationId","location","isReadOnly","isAnonymous","pageInfo"];Object.keys(e).forEach(r=>{i.includes(r)||(e[r]=null)})}return e}catch(i){return this.loggingService.catch("Error in PresenceUtilsService formatPresenceUserData:",i),e}}};o.\u0275fac=function(i){return new(i||o)(Q(y),Q(zn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Use=(()=>{let o=class o{constructor(e,i,r,a,s,c){this.loggingService=e,this.usersService=i,this.authService=r,this.functions=a,this.configService=s,this.reactionAnnotationsResolverService=c}getUserIdsToResolveFromReactions(e){try{let i=new Set;for(let r of e)if(r?.from?.userId&&i.add(r?.from?.userId),r?.reactions?.length)for(let a of r?.reactions)a?.from?.userId&&i.add(a?.from?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in ReactionUtilsService getUserIdsToResolveFromRecorders:",i),[]}}handleReactionEncryption(a){return te(this,arguments,function*({data:e,firestorePath:i,eventType:r}){try{let s=c6(this.authService.getFirebaseConfig()?.firebaseOptions),c=_r(this.functions,Sr({url:Xn.cloudFunction?.[s]?.setEncryptedData,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:20*60*1e3}),p=zp.getFirestoreProdDbName(this.configService.getApiKey()??"",this.authService.getFirebaseConfig()?.firebaseOptions),u=this.authService.getUser()?.userId??"",C={path:i??"",data:e??{},dbId:p??"",feature:"reaction",eventType:r??"PATCH",sdkVersion:pa()},E=yield Ap(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 i=this.usersService.getUserById(e?.from?.userId);i&&(e.from=i)}if(e?.reactions?.length){for(let i of e?.reactions)if(i?.from?.userId){let r=this.usersService.getUserById(i?.from?.userId);r&&(i.from=r)}}}return e}catch(i){return this.loggingService.catch("Error in ReactionUtilsService mergeReactionWithUser:",i),e}}formatReactionData(e){try{return this.usersService.userDataProviderAvailable()&&e?.from?.userId&&(e.from={userId:e.from.userId}),e.reactions=e?.reactions?.map(i=>(this.usersService.userDataProviderAvailable()&&i?.from?.userId&&(i.from={userId:i.from.userId}),i)),e}catch(i){return this.loggingService.catch("Error in ReactionUtilsService formatReactionData:",i),e}}isReactionDataChanged(e,i){try{this.loggingService.log("%c[WB] Calling ReactionUtilsService FUNCTION: isReactionDataChanged","color: green;");let r=this.reactionAnnotationsResolverService.getReactionAnnotationById(i);return r?!_o(e,r):!0}catch(r){return this.loggingService.catch("Error in ReactionUtilsService isReactionDataChanged:",r),!0}}stripReactionAnnotationData(e){try{if(this.loggingService.log("%c[WB] Calling ReactionUtilsService FUNCTION: stripReactionAnnotationData","color: green;"),!this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable())return{originalData:e,strippedData:null};let i={};if(e&&e.annotationId){let r=e.annotationId;if(i[r]={annotationId:r,metadata:hv(e.metadata??{}),icon:e.icon},!this.isReactionDataChanged(i[r],r))return{strippedData:null,originalData:e};delete e?.icon,e.isReactionResolverUsed=!0}return{strippedData:i,originalData:e}}catch(i){return this.loggingService.catch("Error in ReactionUtilsService stripReactionAnnotationData:",i),{strippedData:null,originalData:null}}}mergeStrippedDataWithReactionAnnotations(e){try{if(this.loggingService.log("%c[WB] Calling ReactionUtilsService FUNCTION: mergeStrippedDataWithReactionAnnotations","color: green;"),!this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable())return e;let i=this.reactionAnnotationsResolverService.getReactionAnnotationById(e?.annotationId);return i&&i.icon&&(e.icon=i.icon),e}catch(i){return this.loggingService.catch("Error in ReactionUtilsService mergeStrippedDataWithReactionAnnotations:",i),e}}};o.\u0275fac=function(i){return new(i||o)(Q(y),Q(zn),Q(je),Q(Uo),Q(jt),Q(Em))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var jse=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.usersService=i}getUserIdsToResolveFromSelections(e){try{let i=new Set;for(let r of e)r?.user?.userId&&i.add(r.user.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in SelectionUtilsService getUserIdsToResolveFromSelections:",i),[]}}mergeSelectionWithUser(e){try{if(e?.user?.userId){let i=this.usersService.getUserById(e?.user?.userId);i&&(e.user=i)}return e}catch(i){return this.loggingService.catch("Error in SelectionUtilsService mergeSelectionWithUser:",i),e}}formatSelectionData(e){try{return this.usersService.userDataProviderAvailable()&&e?.user?.userId&&(e.user={userId:e.user.userId}),e}catch(i){return this.loggingService.catch("Error in SelectionUtilsService formatSelectionData:",i),e}}};o.\u0275fac=function(i){return new(i||o)(Q(y),Q(zn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var $se=(()=>{let o=class o{constructor(e,i){this.loggingService=e,this.usersService=i}getUserIdsToResolveFromTags(e){try{let i=new Set;for(let r of e)if(r?.from?.userId&&i.add(r.from.userId),r?.to?.length)for(let a of r.to)a?.userId&&i.add(a.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in TagUtilsService getUserIdsToResolveFromTags:",i),[]}}mergeTagWithUser(e){try{if(e?.from?.userId){let i=this.usersService.getUserById(e?.from?.userId);i&&(e.from=i)}return e?.to?.length&&(e.to=e.to.map(i=>{if(i?.userId){let r=this.usersService.getUserById(i?.userId);r&&(i=r)}return i})),e}catch(i){return this.loggingService.catch("Error in TagUtilsService mergeTagWithUser:",i),e}}formatTagData(e){try{return this.usersService.userDataProviderAvailable()&&(e?.from?.userId&&(e.from={userId:e.from.userId}),e?.to?.length&&(e.to=e.to.map(i=>(i?.userId&&(i={userId:i.userId}),i)))),e}catch(i){return this.loggingService.catch("Error in TagUtilsService formatTagData:",i),e}}};o.\u0275fac=function(i){return new(i||o)(Q(y),Q(zn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Zv=(()=>{let o=class o{constructor(e,i,r,a,s,c,p,u,C,E,A,B,G,K,pe,Ce,Ie,$e,Ye){this.areaUtilsService=e,this.arrowUtilsService=i,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=A,this.reactionUtilsService=B,this.recorderUtilsService=G,this.selectionUtilsService=K,this.tagUtilsService=pe,this.usersService=Ce,this.docService=Ie,this.commentAnnotationsResolverService=$e,this.reactionAnnotationsResolverService=Ye}getFirestorePath({feature:e,properties:i,documentPaths:r,apiKey:a}){try{if(!a)return;let{documentId:s,organizationId:c,folderId:p}=i;c||(c=r?.organizationId);let u=new HM({apiKey:a,documentId:s?`${s}`:"",organizationId:c?`${c}`:"",veltFolderId:p?`${p}`:void 0});switch(e){case"comment":return i?.documentId&&i?.id&&u?.comment?`${u?.comment}/${i?.id}`:void 0;case"allComments":return i?.documentId&&u?.comment?`${u?.comment}`:void 0;case"multiThread":return i?.documentId&&i?.id&&u?.multiThread?`${u?.multiThread}/${i?.id}`:void 0;case"allMultiThreads":return i?.documentId&&u?.multiThread?`${u?.multiThread}`:void 0;case"allLastNotificationTimestamp":return u?.lastNotificationTimestamp?`${u?.lastNotificationTimestamp}`:void 0;case"lastNotificationTimestamp":return i?.id&&u?.lastNotificationTimestamp?`${u?.lastNotificationTimestamp}/${i?.id}`:void 0;case"area":return i?.documentId&&i?.id&&u?.area?`${u?.area}/${i?.id}`:void 0;case"allAreas":return i?.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&&i.folderId?`${u?.folder}/${i.folderId}`:void 0;case"documentUserAccess":return i?.documentId&&i?.id&&u?.documentUsers?`${u?.documentUsers}/${i?.id}`:void 0;case"reaction":return i?.documentId&&i?.id&&u?.reaction?`${u?.reaction}/${i?.id}`:void 0;case"allReactions":return i?.documentId&&u?.reaction?`${u?.reaction}`:void 0;case"recorder":return i?.documentId&&i?.id&&u?.recorder?`${u?.recorder}/${i?.id}`:void 0;case"allRecorders":return i?.documentId&&u?.recorder?`${u?.recorder}`:void 0;case"documentAccessType":return i?.documentId&&u?.document?`${u?.document}/${i?.documentId}`:void 0;case"organizationMetadata":return u?.organization?`${u?.organization}`:void 0;case"documentIam":case"documentMetadata":return i?.documentId&&u?.document?`${u?.document}/${i?.documentId}`:void 0;case"folderMetadata":return i?.folderId&&u?.folder?`${u?.folder}/${i?.folderId}`:void 0;case"locationMetadata":return i?.documentId&&u?.location&&i?.id?`${u?.location}/${i?.id}`:void 0;case"documentUser":return i?.documentId&&i?.id&&u?.documentUsers?`${u?.documentUsers}/${i?.id}`:void 0;case"allDocumentUsers":return i?.documentId&&u?.documentUsers?`${u?.documentUsers}`:void 0;case"allFolderUsers":return i?.folderId&&u?.folderUsers?`${u?.folderUsers}`:void 0;case"allOrganizationGroups":return u?.organizationGroups?`${u?.organizationGroups}`:void 0;case"allOrganizationUsers":return u?.organizationUsers?`${u?.organizationUsers}`:void 0;case"commentViews":return i?.documentId&&i?.id&&u?.commentViews?`${u?.commentViews}/${i?.id}`:void 0;case"allCommentViews":return i?.documentId&&u?.commentViews?`${u?.commentViews}`:void 0;case"notificationViewsTimestamp":return i?.documentId&&i?.id&&u?.notificationViews?`${u?.notificationViews}/${i?.id}`:void 0;case"allDocumentViews":return i?.documentId&&u?.documentViews?`${u?.documentViews}`:void 0;case"documentViews":case"documentMetadataViews":case"documentDayViews":case"documentUsersViews":return i?.documentId&&i?.id&&u?.documentViews?`${u?.documentViews}/${i?.id}`:void 0;case"locationDayViews":case"locationUsersViews":case"locationViews":case"locationMetadataViews":case"location":return i?.documentId&&i?.id&&u?.locationViews?`${u?.locationViews}/${i?.id}`:void 0;case"allLocationViews":return i?.documentId&&u?.locationViews?`${u?.locationViews}`:void 0;case"allDocNotifications":return i?.documentId&&u?.docNotification?`${u?.docNotification}`:void 0;case"docNotificationViews":case"docNotification":return i?.documentId&&i?.id&&u?.docNotification?`${u?.docNotification}/${i?.id}`:void 0;case"userNotificationViews":case"userNotification":return i?.userId&&i?.id&&u?.notificationUsers?`${u?.notificationUsers}/${i?.userId}/${U.FIREBASE_PARTIAL_PATH_USER_NOTIFICATION}/${i?.id}`:void 0;case"allDocNotifications":return i?.documentId&&u?.docNotification?`${u?.docNotification}`:void 0;case"allUserNotifications":return i?.userId&&u?.notificationUsers?`${u?.notificationUsers}/${i?.userId}/${U.FIREBASE_PARTIAL_PATH_USER_NOTIFICATION}`:void 0;default:throw new Error(`Unknown feature: ${e}`)}}catch(s){this.loggingService.catch("Error in CommonDbUtilsService getFirestorePath:",s);return}}getFirestoreCollectionGroupPath(e){try{switch(e){case"allComments":return U.FIREBASE_PARTIAL_PATH_COMMENT;case"allDocuments":return U.FIREBASE_PARTIAL_PATH_DOCS;case"allLocations":return U.FIREBASE_PARTIAL_PATH_LOCATION;case"allMultiThreads":return U.FIREBASE_PARTIAL_PATH_MULTI_THREAD;case"allAreas":return U.FIREBASE_PARTIAL_PATH_AREA;case"allReactions":return U.FIREBASE_PARTIAL_PATH_REACTION;case"allRecorders":return U.FIREBASE_PARTIAL_PATH_RECORDER;case"allDocumentViews":return U.FIREBASE_PARTIAL_PATH_DOCUMENT_VIEWS;case"allCommentViews":return U.FIREBASE_PARTIAL_PATH_COMMENT_VIEWS;case"allLocationViews":return U.FIREBASE_PARTIAL_PATH_LOCATION_VIEWS;case"allDocumentUsers":return U.FIREBASE_PARTIAL_PATH_DOCUMENT_USERS;case"allFolderUsers":return U.FIREBASE_PARTIAL_PATH_FOLDER_USERS;default:throw new Error(`Unknown feature: ${e}`)}}catch(i){this.loggingService.catch("Error in CommonDbUtilsService getFirestoreCollectionGroupPath:",i);return}}getDocumentPath({feature:e,properties:i,defaultDocumentPaths:r,apiKey:a,useFirestore:s}){try{if(!a)return;let{documentId:c,organizationId:p}=i;p||(p=r?.organizationId);let u=new Im({apiKey:a,documentId:c?`${c}`:"",organizationId:p?`${p}`:""});switch(e){case"allComments":return!s&&i?.documentId&&u?.comment?`${u?.comment}`:void 0;case"allGlobalContacts":return i?.documentId&&u?.globalContacts?`${u?.globalContacts}`:void 0;case"globalContacts":return i?.documentId&&i?.userId&&u?.globalContacts?`${u?.globalContacts}${i?.userId}`:void 0;case"groupContacts":return i?.documentId&&i?.groupId&&u?.groupContacts?`${u?.groupContacts}${i?.groupId}`:void 0;case"groupContactsUser":return i?.documentId&&i?.groupId&&i?.userId&&u?.groupContacts?`${u?.groupContacts}${i?.groupId}/${i?.userId}`:void 0;case"allLoginContacts":return i?.documentId&&i?.userId&&u?.logins?`${u?.logins}${i?.userId}/contacts`:void 0;case"allLogins":return i?.documentId&&u?.logins?`${u?.logins}`:void 0;case"logins":return i?.documentId&&i?.userId&&u?.logins?`${u?.logins}${i?.userId}`:void 0;case"customerMetadata":return u?.customerMetadata?`${u?.customerMetadata}`:void 0;case"allArrows":return i?.documentId&&u?.arrow?`${u?.arrow}`:void 0;case"arrow":return i?.documentId&&u?.arrow&&i.id?`${u?.arrow}${i.id}`:void 0;case"allCursors":return i?.documentId&&u?.cursor?`${u?.cursor}`:void 0;case"cursor":return i?.documentId&&u?.cursor&&i.id?`${u?.cursor}${i.id}`:void 0;case"flockUser":return i?.documentId&&u?.flock&&i.id?`${u?.flock}users/${i.id}`:void 0;case"flockSession":return i?.documentId&&u?.flock&&i.id?`${u?.flock}sessions/${i.id}`:void 0;case"allHuddleAttendees":return i?.documentId&&u?.huddle?`${u?.huddle}attendees`:void 0;case"huddleAttendee":return i?.documentId&&u?.huddle&&i.id?`${u?.huddle}attendees/${i.id}`:void 0;case"huddleAttendeeState":return i?.documentId&&u?.huddle&&i.id?`${u?.huddle}attendees/${i.id}/state`:void 0;case"allHuddleInvitees":return i?.documentId&&u?.huddle?`${u?.huddle}invitees`:void 0;case"huddleConnection":return i?.documentId&&u?.huddle&&i.id?`${u?.huddle}connections/${i.id}`:void 0;case"huddleIceCandidate":return i?.documentId&&u?.huddle&&i.id?`${u?.huddle}iceCandidates/${i.id}`:void 0;case"allHuddleIceCandidates":return i?.documentId&&u?.huddle?`${u?.huddle}iceCandidates`:void 0;case"allHuddleMessages":return i?.documentId&&u?.huddle?`${u?.huddle}messages`:void 0;case"huddleMessage":return i?.documentId&&u?.huddle&&i.id?`${u?.huddle}messages/${i.id}`:void 0;case"allLiveStates":return i?.documentId&&u?.liveState?`${u?.liveState}`:void 0;case"allLiveStateCustoms":return i?.documentId&&u?.liveState?`${u?.liveState}custom`:void 0;case"liveStateCustom":return i?.documentId&&u?.liveState&&i?.id?`${u?.liveState}custom/${i.id}`:void 0;case"liveStateSingleEditorMode":return i?.documentId&&u?.liveStateSingleEditorMode?`${u?.liveStateSingleEditorMode}`:void 0;case"liveStateAutoSyncStateCurrent":return i?.documentId&&u?.liveState?`${u?.liveState}default/autoSyncState/current`:void 0;case"liveStateAutoSyncStateHistoryId":return i?.documentId&&u?.liveState&&i?.id?`${u?.liveState}default/autoSyncState/history/${i.id}`:void 0;case"presence":return i?.documentId&&u?.presence&&i?.userId?`${u?.presence}${i?.userId}`:void 0;case"allPresence":return i?.documentId&&u?.presence?`${u?.presence}`:void 0;case"workspaceIam":return u?.workspaceIam?`${u?.workspaceIam}`:void 0;case"selection":return i?.documentId&&u?.selection&&i?.userId?`${u?.selection}${i?.userId}`:void 0;case"allSelections":return i?.documentId&&u?.selection?`${u?.selection}`:void 0;case"syncVideoPlayer":return i?.documentId&&u?.syncVideoPlayer?`${u?.syncVideoPlayer}`:void 0;case"allTags":return i?.documentId&&u?.tag?`${u?.tag}`:void 0;case"tag":return i?.documentId&&u?.tag&&i?.id?`${u?.tag}${i?.id}`:void 0;case"userContactUs":return i?.documentId&&u?.userContactUs?`${u?.userContactUs}`:void 0;case"userFeedback":return i?.documentId&&u?.userFeedback?`${u?.userFeedback}`:void 0;case"userReportBug":return i?.documentId&&u?.userReportBugs?`${u?.userReportBugs}`:void 0;case"comment":return!s&&i?.documentId&&i?.id&&u?.comment?`${u?.comment}${i?.id}`:void 0;case"allMultiThreads":return!s&&i?.documentId&&u?.multiThread?`${u?.multiThread}`:void 0;case"multiThread":return!s&&i?.documentId&&i?.id&&u?.multiThread?`${u?.multiThread}${i?.id}`:void 0;case"allLastNotificationTimestamp":return!s&&u?.organizationNotificationsLastNotificationTimestamp?`${u?.organizationNotificationsLastNotificationTimestamp}`:void 0;case"lastNotificationTimestamp":return!s&&i?.id&&u?.organizationNotificationsLastNotificationTimestamp?`${u?.organizationNotificationsLastNotificationTimestamp}${i?.id}`:void 0;case"documentIam":return!s&&i?.documentId&&u?.documentIam?`${u?.documentIam}`:void 0;case"documentMetadata":return!s&&i?.documentId&&u?.metadata?`${u?.metadata}`:void 0;case"allDocuments":return!s&&u?.docs&&i?.documentId?`${u?.docs}/${i?.documentId}/${U.FIREBASE_PARTIAL_PATH_METADATA}`:void 0;case"allAreas":return!s&&i?.documentId&&u?.area?`${u?.area}`:void 0;case"area":return!s&&i?.id&&u?.area?`${u?.area}${i?.id}`:void 0;case"documentUserAccess":return!s&&i?.id&&u?.documentIam?`${u?.documentIam}users/${i?.id}`:void 0;case"documentUser":return!s&&i?.documentId&&i?.id&&u?.documentIam?`${u?.documentIam}users/${i?.id}`:void 0;case"allDocumentUsers":return!s&&i?.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&&i?.id&&u?.reaction?`${u?.reaction}${i?.id}`:void 0;case"allReactions":return!s&&i?.documentId&&u?.reaction?`${u?.reaction}`:void 0;case"recorder":return!s&&i?.documentId&&i?.id&&u?.recorder?`${u?.recorder}${i?.id}`:void 0;case"allRecorders":return!s&&i?.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&&i?.documentId&&u?.metadata?`${u?.metadata}`:void 0;case"commentViews":return!s&&i?.documentId&&i?.id&&u?.views?`${u?.views}comment/${i?.id}`:void 0;case"allDocumentViews":return!s&&i?.documentId&&u?.views?`${u?.views}documentViews/`:void 0;case"documentViews":return!s&&i?.documentId&&i?.id&&u?.views?`${u?.views}documentViews/${i?.id}`:void 0;case"allCommentViews":return!s&&i?.documentId&&u?.views?`${u?.views}comment/`:void 0;case"allLocationViews":return!s&&i?.documentId&&u?.views?`${u?.views}locationViews/`:void 0;case"notificationViewsTimestamp":return!s&&i?.id&&i?.user&&u?.views?`${u?.views}notification/${i?.id}/views/${i?.user}`:void 0;case"documentUsersViews":return!s&&i?.id&&i?.user&&i?.date&&u?.views?`${u?.views}documentViews/${i?.id}/users/${i?.user}/${i?.date}`:void 0;case"documentMetadataViews":return!s&&i?.id&&u?.views?`${u?.views}documentViews/${i?.id}/metadata`:void 0;case"documentDayViews":return!s&&i?.id&&i?.date&&i?.user&&u?.views?`${u?.views}documentViews/${i?.id}/day/${i?.date}/${i?.user}`:void 0;case"locationViews":return!s&&i?.id&&u?.views?`${u?.views}locationViews/${i?.id}/location`:void 0;case"location":return!s&&i?.id&&u?.views?`${u?.views}locationViews/${i?.id}`:void 0;case"locationUsersViews":return!s&&i?.id&&i?.user&&i?.date&&u?.views?`${u?.views}locationViews/${i?.id}/users/${i?.user}/${i?.date}`:void 0;case"locationMetadataViews":return!s&&i?.id&&u?.views?`${u?.views}locationViews/${i?.id}/metadata`:void 0;case"locationDayViews":return!s&&i?.id&&i?.date&&i?.user&&u?.views?`${u?.views}locationViews/${i?.id}/day/${i?.date}/${i?.user}`:void 0;case"docNotificationViews":case"docNotification":return i?.documentId&&i?.id&&u?.organizationNotificationsWithDocumentId?`${u?.organizationNotificationsWithDocumentId}${i?.id}`:void 0;case"allDocNotifications":return i?.documentId&&u?.organizationNotificationsWithDocumentId?`${u?.organizationNotificationsWithDocumentId}`:void 0;case"allUserNotifications":return i?.userId&&u?.organizationNotificationsUsers?`${u?.organizationNotificationsUsers}${i?.userId}`:void 0;case"userNotificationViews":case"userNotification":return i?.userId&&i?.id&&u?.organizationNotificationsUsers?`${u?.organizationNotificationsUsers}${i?.userId}/${i?.id}`:void 0;case"locationMetadata":return;case"allLocations":return;case"folderMetadata":return;default:throw new Error(`Unknown feature: ${e}`)}}catch(c){this.loggingService.catch("Error in CommonDbUtilsService getDocumentPath:",c);return}}resolveAnnotations(r){return te(this,arguments,function*({data:e,feature:i}){try{if(e&&e?.length>0)switch(i){case"allComments":{this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable()&&this.commentAnnotationsResolverService.resolveCommentAnnotations({commentAnnotationIds:e,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""});break}case"allReactions":{this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable()&&this.reactionAnnotationsResolverService.resolveReactionAnnotations({reactionAnnotationIds:e,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""});break}default:break}}catch(a){this.loggingService.catch(`Error in CommonDbUtilsService resolveAnnotations: ${i}`,a)}})}formatResponse(c){return te(this,arguments,function*({feature:e,data:i,shouldAwait:r=!1,forceResolve:a=!1,shouldCommentAnnotationsResolverAwait:s=!1}){try{if(this.usersService.userDataProviderAvailable()){let p=[];switch(e){case"allAreas":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.areaUtilsService.getUserIdsToResolveFromAreaAnnotations(Object.values(i)));break}case"allArrows":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.arrowUtilsService.getUserIdsToResolveFromArrowAnnotations(Object.values(i)));break}case"allCursors":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.cursorUtilsService.getUserIdsToResolveFromCursorUsers(Object.values(i)));break}case"allComments":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.commentUtilsService.getUserIdsToResolveFromComments(Object.values(i)));break}case"allDocumentUsers":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.contactUtilsService.getUserIdsToResolveFromUserIamData(Object.values(i)));break}case"allFolderUsers":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.contactUtilsService.getUserIdsToResolveFromUserIamData(Object.values(i)));break}case"allOrganizationUsers":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.contactUtilsService.getUserIdsToResolveFromUserIamData(Object.values(i)));break}case"allMultiThreads":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.multiThreadUtilsService.getUserIdsToResolveFromMultiThreads(Object.values(i)));break}case"allDocNotifications":{i&&typeof i=="object"&&(p=this.notificationUtilsService.getUserIdsToResolveFromNotifications(Array.isArray(i)?i:Object.values(i)));break}case"allUserNotifications":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.notificationUtilsService.getUserIdsToResolveFromNotifications(Object.values(i)));break}case"allPresence":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.presenceUtilsService.getUserIdsToResolveFromPresenceUsers(Object.values(i)));break}case"allRecorders":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.recorderUtilsService.getUserIdsToResolveFromRecorders(Object.values(i)));break}case"allReactions":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.reactionUtilsService.getUserIdsToResolveFromReactions(Object.values(i)));break}case"allTags":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.tagUtilsService.getUserIdsToResolveFromTags(Object.values(i)));break}case"allHuddleAttendees":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.huddleUtilsService.getUserIdsToResolveFromHuddleAttendees(Object.values(i)));break}case"liveStateCustom":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.liveStateUtilsService.getUserIdsToResolveFromLiveStateCustom(i));break}case"allLiveStateCustoms":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.liveStateUtilsService.getUserIdsToResolveFromLiveStateCustoms(Object.values(i)));break}case"allLiveStates":{i&&typeof i=="object"&&(p=this.liveStateUtilsService.getUserIdsToResolveFromLiveStates(i));break}case"allSelections":{i&&typeof i=="object"&&!Array.isArray(i)&&(p=this.selectionUtilsService.getUserIdsToResolveFromSelections(Object.values(i)));break}default:p=[]}p?.length&&(r?yield this.usersService.resolveUsers(p,a):this.usersService.resolveUsers(p,a))}if(this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable()){let p=[];switch(e){case"allDocNotifications":{if(i&&typeof i=="object"){let u=this.notificationUtilsService.getTargetAnnotationIdsFromNotifications(i);p=[...p,...u],p=p.filter(C=>!this.commentAnnotationsResolverService.getCommentAnnotationById(C))}break}case"allUserNotifications":{if(i&&typeof i=="object"&&!Array.isArray(i)){let u=this.notificationUtilsService.getTargetAnnotationIdsFromNotifications(i);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 i}catch(p){return this.loggingService.catch("Error in CommonDbUtilsService formatResponse:",p),i}})}mergeCommentAnnotationsWithData({data:e,feature:i}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeCommentAnnotationsWithData","color: green;"),this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())switch(i){case"allComments":return e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).reduce((r,[a,s])=>(r[a]=this.commentUtilsService.mergeStrippedDataWithCommentAnnotations(s),r),{}):e;case"allDocNotifications":case"allUserNotifications":return e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).reduce((r,[a,s])=>(r[a]=this.notificationUtilsService.mergeStrippedDataWithNotification(s),r),{}):e;default:return e}return e}catch(r){return this.loggingService.catch("Error in CommonDbUtilsService mergeCommentAnnotationsWithData:",r),e}}mergeReactionAnnotationsWithData({data:e,feature:i}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeReactionAnnotationsWithData","color: green;"),this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable())switch(i){case"allReactions":return e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).reduce((r,[a,s])=>(r[a]=this.reactionUtilsService.mergeStrippedDataWithReactionAnnotations(s),r),{}):e;default:return e}return e}catch(r){return this.loggingService.catch("Error in CommonDbUtilsService mergeReactionAnnotationsWithData:",r),e}}mergeLocationMetadataWithData({data:e,feature:i,locationMetadata:r}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeLocationMetadataWithData","color: green;"),r&&typeof r=="object"&&!Array.isArray(r))switch(i){case"allComments":return e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).reduce((a,[s,c])=>(a[s]=this.commentUtilsService.mergeLocationWithCommentAnnotations(c,r),a),{}):e;case"allDocNotifications":case"allUserNotifications":return e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).reduce((a,[s,c])=>(a[s]=this.notificationUtilsService.mergeLocationWithNotification(c,r),a),{}):e;default:return e}return e}catch(a){return this.loggingService.catch("Error in CommonDbUtilsService mergeLocationMetadataWithData:",a),e}}mergeUsersWithData({feature:e,data:i}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeUsersWithData","color: green;"),this.usersService.userDataProviderAvailable())switch(e){case"allAreas":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.areaUtilsService.mergeAreaWithUser(s),r),{}):i;case"allArrows":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.arrowUtilsService.mergeArrowWithUser(s),r),{}):i;case"allCursors":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.cursorUtilsService.mergeCursorUserWithUser(s),r),{}):i;case"allComments":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.commentUtilsService.mergeCommentWithUser(s),r),{}):i;case"allDocumentUsers":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.contactUtilsService.mergeUserIamWithUser(s),r),{}):i;case"allFolderUsers":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.contactUtilsService.mergeUserIamWithUser(s),r),{}):i;case"allOrganizationUsers":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.contactUtilsService.mergeUserIamWithUser(s),r),{}):i;case"allMultiThreads":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.multiThreadUtilsService.mergeMultiThreadWithUser(s),r),{}):i;case"allDocNotifications":return i&&typeof i=="object"?i?.map(r=>this.notificationUtilsService.mergeNotificationWithUser(r)):i;case"allUserNotifications":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.notificationUtilsService.mergeNotificationWithUser(s),r),{}):i;case"allPresence":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.presenceUtilsService.mergePresenceUserWithUser(s),r),{}):i;case"allRecorders":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.recorderUtilsService.mergeRecorderWithUser(s),r),{}):i;case"allReactions":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.reactionUtilsService.mergeReactionWithUser(s),r),{}):i;case"allTags":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.tagUtilsService.mergeTagWithUser(s),r),{}):i;case"allHuddleAttendees":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.huddleUtilsService.mergeHuddleAttendeeWithUser(s),r),{}):i;case"liveStateCustom":return i&&typeof i=="object"&&!Array.isArray(i)?this.liveStateUtilsService.mergeLiveStateCustomWithUser(i):i;case"allLiveStateCustoms":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.liveStateUtilsService.mergeLiveStateCustomWithUser(s),r),{}):i;case"allLiveStates":return i&&typeof i=="object"?this.liveStateUtilsService.mergeLiveStateWithUser(i):i;case"allSelections":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((r,[a,s])=>(r[a]=this.selectionUtilsService.mergeSelectionWithUser(s),r),{}):i;default:return i}return i}catch(r){return this.loggingService.catch("Error in CommonDbUtilsService mergeUsersWithData:",r),i}}mergeCommentAnnotationsWithData$({data:e,feature:i}){try{return this.commentAnnotationsResolverService.getCommentAnnotationsById$().pipe(ce(()=>{let r=this.mergeCommentAnnotationsWithData({data:e?.data??{},feature:i}),a=this.mergeUsersWithData({feature:i,data:r??{}});return typeof a=="object"?{data:JSON.parse(JSON.stringify(a)),operation:e?.operation??null}:{data:a,operation:e?.operation??null}}),qt(Vi))}catch(r){return this.loggingService.catch("Error in mergeCommentAnnotationsWithData:",r),re(e)}}mergeReactionAnnotationsWithData$({data:e,feature:i}){try{return this.reactionAnnotationsResolverService.getReactionAnnotationsById$().pipe(ce(()=>{let r=this.mergeReactionAnnotationsWithData({data:e?.data??{},feature:i}),a=this.mergeUsersWithData({feature:i,data:r??{}});return typeof a=="object"?{data:JSON.parse(JSON.stringify(a)),operation:e?.operation??null}:{data:a,operation:e?.operation??null}}),qt(Vi))}catch(r){return this.loggingService.catch("Error in mergeReactionAnnotationsWithData:",r),re(e)}}mergeUsersWithData$({feature:e,data:i}){try{return this.usersService.getUserById$().pipe(ce(()=>{let r=this.mergeUsersWithData({feature:e,data:i?.data??{}});return typeof r=="object"?{data:JSON.parse(JSON.stringify(r)),operation:i?.operation??null}:{data:r,operation:i?.operation??null}}),qt(Vi))}catch(r){return this.loggingService.catch(`Error in mergeUsersWithData for ${e}:`,r),re(i)}}mergeLocationMetadataWithData$({data:e,feature:i}){try{return this.docService.getLocationMetadata$().pipe(ce(r=>{let a=this.mergeLocationMetadataWithData({data:e?.data??{},feature:i,locationMetadata:r});return typeof a=="object"?{data:JSON.parse(JSON.stringify(a)),operation:e?.operation??null}:{data:a,operation:e?.operation??null}}),qt(Vi))}catch(r){return this.loggingService.catch(`Error in mergeLocationMetadataWithData for ${i}:`,r),re(e)}}handleDataStripping({feature:e,data:i,actionType:r}){try{switch(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: handleDataStripping","color: green;"),e){case"comment":return this.commentUtilsService.stripCommentAnnotationData({data:i,actionType:r});case"reaction":return this.reactionUtilsService.stripReactionAnnotationData(i);default:return{originalData:i,strippedData:null}}}catch(a){return this.loggingService.catch("Error in CommonDbUtilsService handleDataStripping:",a),{originalData:i,strippedData:null}}}formatData({feature:e,data:i,properties:r,offset:a,isRealtimeDb:s}){try{this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: formatData","color: green;"),typeof i=="object"&&(i=JSON.parse(JSON.stringify(i)));let c=new Date().getTime()+a;switch(e){case"documentAccessType":return delete i?.users,{docIamConfig:i};case"organizationMetadata":case"documentMetadata":return s?i:{metadata:i};case"cursor":return this.cursorUtilsService.formatCursorUserData(i);case"comment":return this.commentUtilsService.formatCommentData(i);case"area":return this.areaUtilsService.formatAreaData(i);case"arrow":return this.arrowUtilsService.formatArrowData(i);case"liveStateCustom":return this.liveStateUtilsService.formatLiveStateCustomData(i);case"liveStateSingleEditorMode":return this.liveStateUtilsService.formatLiveStateSingleEditorModeData(i);case"multiThread":return this.multiThreadUtilsService.formatMultiThreadData(i);case"reaction":return this.reactionUtilsService.formatReactionData(i);case"recorder":return this.recorderUtilsService.formatRecorderData(i,c);case"notificationViewsTimestamp":return{views:{[r.user??""]:i}};case"documentUsersViews":return s?i:{users:{[r.user??""]:{[r.date??""]:i}}};case"documentDayViews":return s?i:{day:{[r.date??""]:{[r.user??""]:i}}};case"documentMetadataViews":return s?i:{metadata:i};case"huddleMessage":return this.huddleUtilsService.formatHuddleMessageData(i);case"locationMetadataViews":return s?i:{metadata:i};case"locationUsersViews":return s?i:{users:{[r.user??""]:{[r.date??""]:i}}};case"locationDayViews":return s?i:{day:{[r.date??""]:{[r.user??""]:i}}};case"locationViews":return s?i:{location:i};case"docNotificationViews":return s?i:{views:i.views};case"userNotificationViews":return s?i:{views:i.views};case"presence":return this.presenceUtilsService.formatPresenceUserData(i);case"selection":return this.selectionUtilsService.formatSelectionData(i);case"tag":return this.tagUtilsService.formatTagData(i);default:return i}}catch(c){return this.loggingService.catch("Error in CommonDbUtilsService formatData:",c),i}}modifyAndSetData(s){return te(this,arguments,function*({feature:e,data:i,subscriber:r,operation:a=null}){try{let c=yield this.modifyData({feature:e,data:i});r.next({data:c,operation:a})}catch(c){this.loggingService.catch("Error in CommonDbUtilsService modifyAndSetData:",c)}})}isDataAlreadyProcessedInLocalCache({feature:e,change:i,cache:r}){try{if(e==="allReactions"||e==="allComments"){if(i.type==="removed")return!Object.keys(r??{}).includes(i.doc.id);if(r?.[i.doc.id]){let a=i.doc.data(),s=r?.[i.doc.id];return a?.lastUpdated===s?.lastUpdated}}return!1}catch(a){return this.loggingService.catch("Error in CommonDbUtilsService isDataAlreadyProcessedInLocalCache:",a),!1}}modifyData(r){return te(this,arguments,function*({feature:e,data:i}){try{return yield this.formatResponse({feature:e,data:i})}catch(a){return this.loggingService.catch("Error in CommonDbUtilsService modifyData:",a),i}})}addMetadata(e,i){try{return e&&typeof e=="object"&&!Array.isArray(e)?T(I({},e),{metadata:e?.metadata??{documentId:i?.documentId,organizationId:i?.organizationId,apiKey:i?.apiKey}}):e}catch(r){return this.loggingService.catch("Error in CommonDbUtilsService addMetadata:",r),e}}setDataInLocal(p){return te(this,arguments,function*({feature:e,data:i,observablesCache:r,eventType:a,id:s,operation:c=null}){try{let C={comment:"allComments",reaction:"allReactions"}[e];if(!C)return null;let E=i?.metadata?.documentId,A=i?.metadata?.veltFolderId;return Object.keys(r).filter(B=>B.includes(C)&&(!E||B.includes(E)||A&&B.includes(A))).forEach(B=>{let G=r[B]?.subject?.getValue()??{};a==="DELETE"?s&&G?.data?.[s]&&(delete G?.data?.[s],r[B]?.subject&&r[B].subject.next({data:G?.data,operation:c})):r[B]?.subject?.next({data:T(I({},G?.data),{[i?.annotationId]:i}),operation:c})}),null}catch(u){return this.loggingService.catch("Error in CommonDbUtilsService setDataInLocal:",u),null}})}handleCommentEncryption(s){return te(this,arguments,function*({data:e,firestorePath:i,extraData:r,eventType:a}){try{return yield this.commentUtilsService.handleCommentEncryption({data:e,firestorePath:i,extraData:r,eventType:a})}catch(c){return this.loggingService.catch("Error in CommonDbUtilsService handleCommentEncryption:",c),e}})}handleReactionEncryption(a){return te(this,arguments,function*({data:e,firestorePath:i,eventType:r}){try{return yield this.reactionUtilsService.handleReactionEncryption({data:e,firestorePath:i,eventType:r})}catch(s){return this.loggingService.catch("Error in CommonDbUtilsService handleReactionEncryption:",s),e}})}};o.\u0275fac=function(i){return new(i||o)(Q(Mse),Q(Pse),Q(Yv),Q(kse),Q(Rse),Q(WM),Q(Fse),Q(y),Q(Lse),Q(qM),Q(Vse),Q(Use),Q(Kv),Q(jse),Q($se),Q(zn),Q(lt),Q(bs),Q(Em))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Hse=(()=>{let o=class o{constructor(e,i,r){this.configService=e,this.authService=i,this.loggingService=r,this.firestore$=new ve(null);try{Mn([this.authService.getFirebaseConfig$(),this.configService.getApiKey$()]).pipe(Ne(([a,s])=>!!a&&!!s),et(1)).subscribe(([a,s])=>{a&&s&&a?.firebaseOptions?.storeDbId&&this.firestore$.next(_M(zp.getFirestoreProdDbName(s,a.firebaseOptions)))},a=>{})}catch{}}getFirestore(){return this.firestore$.asObservable()}getFirestoreValue(){return this.firestore$.value}generateFirestoreDocumentId(){try{let e=this.getFirestoreValue()||_M("DocumentIdDb");if(e){let i=HS(e,"generateDocumentId");return jv(i).id}return}catch(e){this.loggingService.catch("Error in FirestoreService generateFirestoreDocumentId: ",e);return}}};o.\u0275fac=function(i){return new(i||o)(Q(jt),Q(je),Q(y))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var En=(()=>{let o=class o{constructor(e,i,r,a,s,c,p,u,C,E){this.authService=e,this.commonDbUtilsService=i,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.loggingService.log("%c[WB] Creating CLASS: CommonDbService","color: blue;"),this.docService.setCommonDbService(this),this.authService.setCommonDbService(this),this.subscriptions.push(this.databaseService.getDb().subscribe(A=>{if(A){this.db=A;let B=on(A,".info/serverTimeOffset");this.offsetListener=yu(B,G=>{let K=G.val();this.offset=K})}})),this.subscriptions.push(this.firestoreService.getFirestore().subscribe(A=>{A&&(this.firestore=A)}))}unsubscribeFromObservables(){try{Object.values(this.firestoreSubscriptions??{}).forEach(e=>{e?.unsubscribe()}),Object.entries(this.observablesCache??{}).forEach(([e,i])=>{i?.subject?.complete(),i?.subject?.unsubscribe()}),this.observablesCache={},this.firestoreSubscriptions={}}catch(e){this.loggingService.catch("Error in unsubscribeFromObservables:",e)}}ngOnDestroy(){this.subscriptions.forEach(e=>e.unsubscribe()),this.offsetListener&&this.offsetListener(),this.unsubscribeFromObservables()}getOffset(){return this.offset}getServerTimestamp(){return new Date().getTime()+this.getOffset()}subscribeToServices(e){Mn([this.databaseService.getDb(),this.firestoreService.getFirestore()]).pipe(Ne(([i,r])=>!!i),et(1),gn(([i,r])=>{e({db:i,firestore:r})})).subscribe({error:i=>{this.loggingService.catch("Error in CommonDbService subscription: ",i)}})}performDatabaseOperation(e,i,r,a,s,c){return te(this,null,function*(){try{if(!i){this.loggingService.warn(`%c[WB] No properties found for ${e}`,"color: red;");return}return this.subscribeToServices(C=>te(this,[C],function*({db:p,firestore:u}){let E;i?.skipFirestore||(E=this.commonDbUtilsService.getFirestorePath({feature:e,properties:i,documentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey()}));let A=this.commonDbUtilsService.getDocumentPath({feature:e,properties:i,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey(),useFirestore:this.shouldUseFirestore()});if(!p){this.loggingService.warn(`%c[WB] No database or firestore found for ${e}`,"color: red;");return}try{let B,G;try{A&&(B=on(p,`${A}`))}catch{this.loggingService.catch("Error in dbRef")}try{E?.includes("/organizations")&&u&&E&&(G=jv(u,`${E}`))}catch{this.loggingService.catch("Error in docRef")}yield r({dbRef:B,firestoreRef:G,data:a,firestorePath:E}),c&&c({firestoreAvailable:!!u})}catch(B){this.loggingService.catch(`Error in ${e} operation: `,B),s&&s(B)}}))}catch(p){this.loggingService.catch("Error in performDatabaseOperation:",p)}})}setData(p){return te(this,arguments,function*({feature:e,data:i,properties:r,callback:a,errorCallback:s,extraData:c}){try{return this.loggingService.log(`%c[WB] Calling FUNCTION: setData for ${e}`,"color: green;"),this.shouldUseFirestore()&&i?.metadata&&!i?.metadata?.apiKey?void 0:(this.commonDbUtilsService.setDataInLocal({feature:e,data:i,observablesCache:this.observablesCache,operation:null}),this.performDatabaseOperation(e,r,u=>te(this,null,function*(){if(u.dbRef){let C=this.commonDbUtilsService.formatData({feature:e,data:u.data,properties:r,offset:this.getOffset(),isRealtimeDb:!0});yield Vf(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:A,eventType:B}=this.commonDbUtilsService.handleDataStripping({feature:e,data:C,actionType:c?.actionType});if(e==="comment"){let G=null;E&&(G=yield this.commentAnnotationsResolverService.saveCommentAnnotation({commentAnnotation:E,eventType:B,commentId:c?.targetAnnotationData?.commentId})),A&&(G?.isSuccess||G===null)&&(yield this.commonDbUtilsService.handleCommentEncryption({data:A,firestorePath:u.firestorePath??"",extraData:c}))}else if(e==="reaction"){let G=null;E&&(G=yield this.reactionAnnotationsResolverService.saveReactionAnnotation(E)),A&&(G?.isSuccess||G===null)&&(yield this.commonDbUtilsService.handleReactionEncryption({data:A,firestorePath:u.firestorePath??""}))}else yield b$(u.firestoreRef,C)}}catch(C){this.loggingService.catch(`Error in setData for ${e}`,C)}}),i,s,a))}catch(u){this.loggingService.catch(`Error in setData for ${e}`,u)}})}updateData(p){return te(this,arguments,function*({feature:e,data:i,properties:r,callback:a,errorCallback:s,extraData:c}){try{return this.loggingService.log(`%c[WB] Calling FUNCTION: updateData for ${e}`,"color: green;"),this.shouldUseFirestore()&&i?.metadata&&!i?.metadata?.apiKey?void 0:(this.commonDbUtilsService.setDataInLocal({feature:e,data:i,observablesCache:this.observablesCache,operation:null}),this.performDatabaseOperation(e,r,u=>te(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});yield c5(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:A,eventType:B}=this.commonDbUtilsService.handleDataStripping({feature:e,data:C,actionType:c?.actionType});if(e==="comment"){let G=null;E&&(G=yield this.commentAnnotationsResolverService.saveCommentAnnotation({commentAnnotation:E,eventType:B,commentId:c?.targetAnnotationData?.commentId})),A&&(G?.isSuccess||G===null)&&(yield this.commonDbUtilsService.handleCommentEncryption({data:A,firestorePath:u.firestorePath??"",extraData:c}))}else if(e==="reaction"){let G=null;E&&(G=yield this.reactionAnnotationsResolverService.saveReactionAnnotation(E)),A&&(G?.isSuccess||G===null)&&(yield this.commonDbUtilsService.handleReactionEncryption({data:A,firestorePath:u.firestorePath??""}))}else yield b$(u.firestoreRef,C,{merge:!0})}}catch(C){this.loggingService.catch(`Error in updateDoc for ${e}`,C)}}),i,s,a))}catch(u){this.loggingService.catch(`Error in updateData for ${e}`,u)}})}deleteData(s){return te(this,arguments,function*({feature:e,properties:i,callback:r,errorCallback:a}){try{return this.loggingService.log(`%c[WB] Calling FUNCTION: deleteData for ${e}`,"color: green;"),this.commonDbUtilsService.setDataInLocal({feature:e,observablesCache:this.observablesCache,eventType:"DELETE",id:i?.id,operation:{type:"removed",ids:[i?.id]}}),this.performDatabaseOperation(e,i,c=>te(this,null,function*(){c.dbRef&&(yield s5(c.dbRef));try{if(c.firestoreRef&&!i?.skipFirestore)if(e==="comment"){let p=null;p=yield this.commentAnnotationsResolverService.deleteCommentAnnotation(i?.id??""),(p?.isSuccess||p===null)&&(yield this.commonDbUtilsService.handleCommentEncryption({firestorePath:c.firestorePath??"",eventType:"DELETE"}))}else if(e==="reaction"){let p=null;p=yield this.reactionAnnotationsResolverService.deleteReactionAnnotation(i?.id??""),(p?.isSuccess||p===null)&&(yield this.commonDbUtilsService.handleReactionEncryption({firestorePath:c.firestorePath??"",eventType:"DELETE"}))}else yield lse(c.firestoreRef)}catch(p){this.loggingService.catch(`Error in deleteData for ${e}`,p)}}),void 0,a,r)}catch(c){this.loggingService.catch(`Error in deleteData for ${e}`,c)}})}shouldUseFirestore(){try{return this.authService.getAdvancedQueriesEnabled()}catch(e){return this.loggingService.catch("Error in shouldUseFirestore:",e),!1}}generateDocumentId(){try{let e=this.firestoreService.generateFirestoreDocumentId();return e||(e=wn()),e||"noDocumentId"}catch(e){return this.loggingService.catch("Error in generateFirestoreDocumentId:",e),wn()||"noDocumentId"}}queryData(r){return te(this,arguments,function*({feature:e,properties:i}){try{let a=this.shouldUseFirestore();return!e||!i?(this.loggingService.warn("[WB] Missing required parameters in queryData"),[]):a?yield this.handleFirestoreQuery(e,i):yield this.handleRtdbQuery(e,i)}catch(a){return this.loggingService.catch(`Error in queryData for ${e}`,a),[]}})}handleFirestoreQuery(e,i){return te(this,null,function*(){try{if(!this.firestore)return this.loggingService.warn("[WB] Firestore not initialized"),[];let r=i?.useCollectionGroup?this.commonDbUtilsService.getFirestoreCollectionGroupPath(e):this.commonDbUtilsService.getFirestorePath({feature:e,properties:i,documentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey()});if(!r)return this.loggingService.warn(`[WB] No firestore path found for ${e}`),[];try{let a=HS(this.firestore,r);i?.useCollectionGroup&&(a=_$(this.firestore,r));let s=i?.firestoreQuery??[],c=S$(a,...s);if(i?.getCount){let p=yield mse(c).catch(u=>(this.loggingService.catch(`Error in getCountFromServer for ${e}`,u),null));return p?p.data().count:0}else{let p=yield pse(c).catch(E=>(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,i){return te(this,null,function*(){if(!this.db)return this.loggingService.warn("[WB] Realtime Database not initialized"),[];let r=this.commonDbUtilsService.getDocumentPath({feature:e,properties:i,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey()});if(!r)return this.loggingService.warn(`[WB] No database path found for ${e}`),[];try{let a=on(this.db,r),s=i?.rtdbQuery??[],c=YL(a,...s),p=yield GL(c).catch(C=>(this.loggingService.catch(`Error in get for ${e}`,C),null));if(!p)return[];let u=p.val();return u?i?.skipObjectValues?u:Object.values(u??{}):[]}catch(a){return this.loggingService.catch(`Error in RTDB query for ${e}:`,a),[]}})}getData(r){return te(this,arguments,function*({feature:e,properties:i}){try{let a=this.shouldUseFirestore();if(i?.skipFirestore&&(a=!1),!e||!i)return this.loggingService.warn("[WB] Missing required parameters in getData"),{};if(a&&this.firestore){let s=this.commonDbUtilsService.getFirestorePath({feature:e,properties:i,documentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey()});if(!s)return this.loggingService.warn(`[WB] No firestore path found for ${e}`),{};try{let c=yield dse(jv(this.firestore,s)).catch(u=>(this.loggingService.catch(`Error in getDoc for ${e}`,u),null));if(!c)return this.loggingService.warn(`[WB] No document found at ${s}`),{};let p=c.data();return i?.field?p?.[i.field]??{}:p??{}}catch(c){return this.loggingService.catch(`Error fetching Firestore data for ${e}:`,c),{}}}if(this.db){let s=this.commonDbUtilsService.getDocumentPath({feature:e,properties:i,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey()});if(!s)return this.loggingService.warn(`[WB] No database path found for ${e}`),{};try{let c=yield GL(on(this.db,s)).catch(u=>(this.loggingService.catch(`Error in get for ${e}`,u),null));if(!c)return this.loggingService.warn(`[WB] No data found at ${s}`),{};let p=c.val();return i?.field?p?.[i.field]??{}:p??{}}catch(c){return this.loggingService.catch(`Error fetching RTDB data for ${e}:`,c),{}}}return this.loggingService.warn("[WB] No database connection available"),{}}catch(a){return this.loggingService.catch("Unexpected error in getData:",a),{}}})}dbListener({feature:e,properties:i}){let r=this.shouldUseFirestore();i?.skipFirestore&&(r=!1);let a=`${e}-${JSON.stringify(i)}`;return Mn([this.databaseService.getDb(),this.firestoreService.getFirestore()]).pipe(Ne(([s,c])=>s?r&&!c?(this.loggingService.warn(`[WB] Firestore requested but not available for ${e}`),!1):!0:(this.loggingService.warn(`[WB] No database found for ${e}`),!1)),ue(([s,c])=>{try{if(r&&c){if(!!!this.observablesCache[a]){this.observablesCache[a]={subject:new ve({}),count:0};let C=this.handleFirestoreListener(e,i,c).subscribe(E=>{this.observablesCache[a]?.subject?.next(E)},E=>this.observablesCache[a]?.subject?.error(E));this.firestoreSubscriptions[a]=C}return new Lt(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)return this.handleRealtimeDbListener(e,i,s);return re({})}catch(p){return this.loggingService.catch(`Error setting up listener for ${e}:`,p),re({})}}),Mg(()=>{this.loggingService.log(`[WB] Cleaning up listener for ${e} and key ${a}`)}))}handleFirestoreListener(e,i,r){let a=i?.useCollectionGroup?this.commonDbUtilsService.getFirestoreCollectionGroupPath(e):this.commonDbUtilsService.getFirestorePath({feature:e,properties:i,documentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey()}),s=`${e}-${JSON.stringify(i)}`;return a?new Lt(c=>{let p=i.isCollection?this.setupCollectionListener(r,a,e,c,i):this.setupDocumentListener(r,a,e,c,i);return()=>{c.complete(),c.unsubscribe(),p(),this.observablesCache[s]?.subject?.complete(),this.observablesCache[s]?.subject?.unsubscribe(),delete this.observablesCache[s]}}).pipe(ue(c=>this.commonDbUtilsService.mergeUsersWithData$({feature:e,data:c})),ue(c=>["allComments","allUserNotifications"].includes(e)?this.commonDbUtilsService.mergeCommentAnnotationsWithData$({data:c,feature:e}):re(c)),ue(c=>["allReactions"].includes(e)?this.commonDbUtilsService.mergeReactionAnnotationsWithData$({data:c,feature:e}):re(c)),qt(Vi)):(this.loggingService.warn(`[WB] No firestore path found for ${e} and key ${s}`),re({}))}setupCollectionListener(e,i,r,a,s){let c=`${r}-${JSON.stringify(s)}`,p=HS(e,i);if(s?.useCollectionGroup&&(p=_$(e,i)),s?.useQuery&&s?.firestoreQuery){let E=s?.firestoreQuery??[];p=S$(p,...E)}let u=!0,C=[];return y$(p,E=>{try{let A=JSON.parse(JSON.stringify(this.observablesCache[c]?.subject?.getValue()?.data??{})),B=null,G=!1;E?.docChanges()?.length?E.docChanges().forEach(K=>{["allComments","allReactions"].includes(r)&&!u&&K.type!=="removed"&&C.push(K.doc.id),this.commonDbUtilsService.isDataAlreadyProcessedInLocalCache({feature:r,change:K,cache:this.observablesCache[c]?.subject?.getValue()?.data??{}})||(G=!0,Object.assign(A,this.handleCollectionChange(K,A)),K.type==="removed"&&(B||(B={type:K.type,ids:[]}),B.ids.push(K.doc.id)))}):G=!0,G&&(["allComments","allReactions"].includes(r)&&C?.length&&(this.commonDbUtilsService.resolveAnnotations({data:C,feature:r}),C=[]),this.commonDbUtilsService.modifyAndSetData({feature:r,data:A,subscriber:a,operation:B})),u=!1}catch(A){this.handleListenerError(A,r,a)}},E=>this.handleListenerError(E,r,a))}handleCollectionChange(e,i){switch(e.type){case"added":case"modified":i[e.doc.id]=e.doc.data();break;case"removed":delete i?.[e.doc.id];break}return i}setupDocumentListener(e,i,r,a,s){let c=jv(e,i);return y$(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,i,r){this.loggingService.catch(`Firestore listener error for ${i}:`,e),r.error(e)}handleRealtimeDbListener(e,i,r){let a=this.commonDbUtilsService.getDocumentPath({feature:e,properties:i,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey()});if(!a)return this.loggingService.warn(`[WB] No database path found for ${e}`),re({});let s=on(r,a);if(i?.useQuery&&i?.rtdbQuery){let c=i?.rtdbQuery??[];s=YL(s,...c)}return Bf(s).pipe(Vn(c=>(this.loggingService.catch(`RTDB listener error for ${e}:`,c),re({}))),ce(c=>(c===null&&(c={}),c&&typeof c=="object"?Object.entries(c??{}).reduce((u,[C,E])=>(u[C]=this.commonDbUtilsService.addMetadata(E,i),u),{}):this.commonDbUtilsService.addMetadata(c,i))),ue(c=>this.commonDbUtilsService.modifyData({feature:e,data:c})),ue(c=>this.usersService.getUserById$().pipe(ce(()=>({data:this.commonDbUtilsService.mergeUsersWithData({feature:e,data:c}),operation:null})))))}};o.\u0275fac=function(i){return new(i||o)(Q(je),Q(Zv),Q(y),Q(Hse),Q(un),Q(jt),Q(lt),Q(zn),Q(bs),Q(Em))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var vi=(()=>{let o=class o{constructor(e,i,r,a,s,c,p,u){this.analyticsService=e,this.authService=i,this.configService=r,this.databaseService=a,this.docService=s,this.loggingService=c,this.commonDbService=p,this.usersService=u,this.db=bi(),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 Xe,this.documentAccessType=null,this.atHereEnabled$=new ve(!1),this.atHereLabel$=new ve("here"),this.atHereDescription$=new ve(null),this.contactListScopeForOrganizationUsers$=new ve([Pi.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.usersByOrganizationIdAndDocumentId$=new ve({}),this.usersByOrganizationIdAndFolderId$=new ve({}),this.userById$=new ve({}),this.authService.setContactService(this),this.authService.getUser$().pipe(ue(C=>this.docService.getDocumentPaths$().pipe(gn(E=>{this.documentPaths=E}),ce(()=>C)))).subscribe(C=>te(this,null,function*(){this.user=C,C&&this.documentPaths?C?.organizationId?(this.getOrganizationContactsFromDb$(),this.getFolderContactsFromDb$(),this.getDocumentContactsFromDb$(),this.getOrganizationGroupsFromDb$()):(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(Ne(C=>!!C),et(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)}),Mn([this.getInternalUserContacts$(),this.getCustomUserContacts$(),this.getCustomUserContactsConfig$()]).subscribe(([C,E,A])=>{E?A?.merge?this.userContacts$.next([...C||[],...E||[]]):this.userContacts$.next(E||[]):this.userContacts$.next(C||[])}),this.getUserContacts$().subscribe(C=>{try{C?.forEach(E=>{let A=E?.userSnippylyId||gm(this.configService.getApiKey(),E.userId);A&&this.userSnippylyIdContacts$.next(T(I({},this.userSnippylyIdContacts$.value),{[A]:E}))})}catch{}})}clearCache(){this.loggingService.log("%c[WB] Calling FUNCTION: clearCache in ContactService","color: green;");try{this.documentPaths=null,this.usersByOrganizationId$.next({}),this.usersByOrganizationIdAndFolderId$.next({}),this.usersByOrganizationIdAndDocumentId$.next({}),this.userById$.next({}),this.userOrganizationContacts$.next([]),this.userFolderContacts$.next([]),this.userDocumentContacts$.next([]),this.userOrganizationGroups$.next([]),this.userContacts$.next([]),this.userSnippylyIdContacts$.next(null),this.userGlobalContact$.next(!1),this.userGroupContact$.next(null),this.users$.next([]),this.userPersonalContacts=[],this.userGroupContacts=[],this.userGlobalContacts=[],this.users=[]}catch(e){this.loggingService.catch("Error in ContactService clearCache: ",e)}}setDocumentAccessType(e){try{this.documentAccessType=e}catch(i){this.loggingService.catch("Error in ContactService setDocumentAccessType: ",i)}}checkIfUserGlobalContact(e){return te(this,null,function*(){try{if(e?.userId&&this.documentPaths?.globalContacts){let i=yield this.commonDbService?.getData({feature:"globalContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Nt(e?.userId),skipFirestore:!0}});if(Object.keys(i??{}).length>0)return!0}if(e?.email&&this.documentPaths?.globalContacts){let i=yield this.commonDbService?.getData({feature:"globalContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Nt(e?.email),skipFirestore:!0}});if(Object.keys(i??{}).length>0)return!0}return!1}catch(i){return this.loggingService.catch("Error in ContactService isUserGlobalContact: ",i),!1}})}setLoggedInUser(e){try{e?.userId&&this.documentPaths?.logins&&(this.commonDbService.updateData({feature:"logins",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Nt(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(T(I({},e),{contacts:void 0})))}),this.setLoggedInUserPrivateContacts(e,e?.contacts))}catch(i){this.loggingService.catch("Error in ContactService setLoggedInUser: ",i)}}migrateLoggedInUserFromEmailToUserIdPath(e){return te(this,null,function*(){try{if(e?.email&&this.documentPaths?.logins){let i=yield this.commonDbService?.getData({feature:"logins",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Nt(e?.email),skipFirestore:!0}});if(Object.keys(i??{}).length>0){let r=i;if(r){if(r?.contacts){let a={};Object.keys(r?.contacts??{})?.forEach(s=>{let c=r.contacts[s];if(c?.userId){let p=Nt(c?.userId);a[p]=c}}),r.contacts=a}yield this.commonDbService.updateData({feature:"logins",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Nt(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:Nt(e?.email),skipFirestore:!0}})}}}}catch(i){this.loggingService.catch("Error in ContactService migrateLoggedInUserFromEmailToUserIdPath: ",i)}})}addGlobalContact(e){try{e?.userId&&this.documentPaths?.globalContacts&&this.commonDbService.updateData({feature:"globalContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Nt(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(e))})}catch(i){this.loggingService.catch("Error in ContactService addGlobalContact: ",i)}}updateUserInGlobalContactsIfAvailable(e){return te(this,null,function*(){try{if(e?.userId&&this.documentPaths?.globalContacts&&(yield this.checkIfUserGlobalContact(e))){let r=new Do;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:Nt(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(r))})}}catch(i){this.loggingService.catch("Error in ContactService updateUserInGlobalContactsIfAvailable: ",i)}})}moveGlobalContactUserFromEmailToUserIdPath(e){return te(this,null,function*(){try{if(e?.email&&e?.userId&&this.documentPaths?.globalContacts){let i=yield this.commonDbService?.getData({feature:"globalContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Nt(e?.email),skipFirestore:!0}});if(Object.keys(i??{}).length>0){let r=i;r&&(yield this.commonDbService.updateData({feature:"globalContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Nt(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:Nt(e?.email),skipFirestore:!0}}))}}}catch(i){this.loggingService.catch("Error in ContactService removeUserFromGlobalContactsByEmail: ",i)}})}setLoggedInUserPrivateContacts(e,i){try{if(e?.userId&&this.documentPaths?.logins){let r,a=i?.filter(c=>c?.visibility!=="group"),s=!1;this.authService.getUserOptions()&&(s=!!this.authService.getUserOptions()?.replaceContacts||!!this.authService.getUserOptions()?.replacePrivateContacts),a?.length?(r={},a?.forEach(c=>{if(c?.userId){let p=Nt(c?.userId);r[p]=c}}),s?this.commonDbService.setData({feature:"allLoginContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Nt(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:Nt(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:Nt(e?.userId),skipFirestore:!0}})}}catch(r){this.loggingService.catch("Error in ContactService setLoggedInUserPrivateContacts: ",r)}}migrateGroupContactsFromEmailToUserIdPath(e){return te(this,null,function*(){try{if(this.documentPaths?.groupContacts&&e){let i=yield this.commonDbService?.getData({feature:"groupContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",groupId:e,skipFirestore:!0}});i&&Object.keys(i??{}).forEach(r=>te(this,null,function*(){let a=i[r];a?.email&&a?.userId&&Nt(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:Nt(a?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(a))}))}))}}catch(i){this.loggingService.catch("Error in ContactService migrateGroupContacts: ",i)}})}checkToSetLoggedInUserInGroupContacts(){return te(this,null,function*(){try{this.user?.groupId&&this.user?.userId&&((yield this.checkIfUserGlobalContact(this.user))||this.docService.getDocumentIam$().pipe(et(1)).subscribe(i=>te(this,null,function*(){if(this.user?.groupId&&this.user?.userId){let r=!1,a=this.docService.getDocumentAccessType(i);if(!a||a===pi.PUBLIC)r=!0;else if(a===pi.RESTRICTED){let s=Nt(this.user?.userId);if(i?.users?.[s]&&(r=!0),this.user?.email){let c=Nt(this.user?.email);i?.users?.[c]&&(r=!0)}}if(r){let s=new $p;s.email=this.user.email,s.visibility="group",s.name=this.user.name,s.photoUrl=this.user.photoUrl,s.userId=this.user.userId,(this.authService.getUserOptions()?.replaceContacts||this.authService.getUserOptions()?.replaceGroupContacts)&&(yield this.removeGroupContacts(this.user?.groupId)),this.setLoggedInUserGroupContacts(this.user?.groupId,[s]),this.user?.contacts&&this.user?.groupId&&this.setLoggedInUserGroupContacts(this.user?.groupId,this.user?.contacts)}}})))}catch(e){this.loggingService.catch("Error in ContactService checkToSetLoggedInUserInGroupContacts: ",e)}})}setLoggedInUserGroupContacts(e,i){try{let r=i?.filter(a=>a?.visibility==="group");r?.length&&r.forEach(a=>te(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:Nt(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:Nt(a?.email),skipFirestore:!0}}))}}))}catch(r){this.loggingService.catch("Error in ContactService setLoggedInUserGroupContacts: ",r)}}removeGroupContacts(e){return te(this,null,function*(){try{if(this.documentPaths?.groupContacts&&e)return this.commonDbService.deleteData({feature:"groupContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",groupId:e,skipFirestore:!0}})}catch(i){this.loggingService.catch("Error in ContactService removeGroupContacts: ",i)}})}mergeUserContacts(){try{let e=[];this.userPersonalContacts&&e.push(...this.userPersonalContacts),this.userGroupContacts&&e.push(...this.userGroupContacts),this.userGlobalContacts&&e.push(...this.userGlobalContacts);let i={};e.forEach(r=>{r?.userId?(!r?.email||!i[r.email])&&(i[r.userId]=r):r?.email&&(!r?.userId||!i[r.userId])&&(i[r.email]=r)}),e=Object.values(i??{}),this.internalUserContacts$.next(e)}catch(e){this.loggingService.catch("Error in ContactService mergeUserContacts: ",e)}}getInternalUserContacts(){return this.internalUserContacts$.value}getInternalUserContacts$(){return this.internalUserContacts$.asObservable()}getUserContacts$(e){try{let{organizationId:i,documentId:r,veltFolderId:a}=e||{};return i&&r?Mn([this.usersByOrganizationId$,this.usersByOrganizationIdAndFolderId$,this.usersByOrganizationIdAndDocumentId$,this.userById$,this.customUserContacts$,this.customUserContactsConfig$,this.getContactListScopeForOrganizationUsers$()]).pipe(ce(([s,c,p,u,C,E,A])=>{let B={},G=!1;E&&!E?.merge&&(G=!0);let K=Ye=>A.some(ke=>Ye.includes(ke)),pe=K([Pi.ALL,Pi.ORGANIZATION])?Object.keys(s?.[i]||{}):[],Ce=a?K([Pi.ALL,Pi.FOLDER])?Object.keys(c?.[i]?.[a]||{}):[]:[],Ie=K([Pi.ALL,Pi.DOCUMENT])?Object.keys(p?.[i]?.[r]||{}):[];if([...pe,...Ce||[],...Ie].forEach(Ye=>{let ke=u?.[Ye];ke&&(B[Ye]=ke)}),C){let{merge:Ye,options:ke}=E||{},{organizationId:Se,documentId:De,folderId:Pe}=ke||{},_e=Pe?_l(Pe):void 0;(!Se||Se===i)&&(!De||De===r)&&(!_e||_e===a)&&(Ye||(B={}),C.forEach(he=>{he?.userId&&(B[he.userId]=he)}))}return Object.values(B??{})})):this.userContacts$.asObservable().pipe(ce(s=>s))}catch(i){return this.loggingService.catch("Error in ContactService getUserContacts$ metadata: ",i),re([])}}getUserContactsBySnippylyId$(){return this.userSnippylyIdContacts$.asObservable()}getAtHereLabel(){return this.atHereLabel$.asObservable()}getAtHereDescription(){return this.atHereDescription$.asObservable()}getUserContactsFromDb$(){this.getUserContactSubscription||(this.getUserContactSubscription=this.authService.getUser$().pipe(Ne(e=>!!e),ue(e=>this.docService.getDocumentPaths$().pipe(Ne(i=>!!i),gn(i=>{this.documentPaths=i}),ce(()=>e))),ue(e=>{if(this.userGroupContacts=[],this.userPersonalContacts=[],!e)return re();if(!this.documentPaths)return re();let i=[];return i.push(this.commonDbService.dbListener({feature:"allGlobalContacts",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,skipFirestore:!0}}).pipe(ce(r=>r?.data),gn(r=>{r?(this.userGlobalContacts=Object.values(r??{}),this.userGlobalContacts?.find(a=>a.userId===this.user?.userId)?this.userGlobalContact$.next(!0):this.userGlobalContact$.next(!1)):(this.userGlobalContacts=[],this.userGlobalContact$.next(!1))}))),i.push(this.commonDbService.dbListener({feature:"groupContacts",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,skipFirestore:!0,groupId:e?.groupId}}).pipe(ce(r=>r?.data),gn(r=>{r?(this.userGroupContacts=Object.values(r??{}),this.userGroupContacts?.find(a=>a?.userId===this.user?.userId)?this.userGroupContact$.next(!0):this.userGroupContact$.next(!1)):(this.userGroupContacts=[],this.userGroupContact$.next(!1))}))),i.push(this.commonDbService.dbListener({feature:"allLoginContacts",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,skipFirestore:!0,userId:Nt(e?.userId)}}).pipe(ce(r=>r?.data),gn(r=>{r?this.userPersonalContacts=Object.values(r??{}):this.userPersonalContacts=[]}))),oo(...i).pipe(ro(this.authService.getUser$().pipe(Ne(r=>!r))))})).subscribe(()=>{this.mergeUserContacts()},e=>{this.loggingService.catch("Error in ContactService getUserContacts$ subscription: ",e)}))}addUserContact(e){try{this.user?.organizationId||this.user?.groupId&&(e.visibility="group",this.setLoggedInUserGroupContacts(this.user?.groupId,[e]))}catch(i){this.loggingService.catch("Error in ContactService addUserContact: ",i)}}isUserGlobalContact$(){return this.userGlobalContact$.asObservable()}isUserGlobalContact(){return this.userGlobalContact$.value}isUserGroupContact$(){return this.userGroupContact$.asObservable()}isUserGroupContact(){return this.userGroupContact$.value}getLoggedInUsers$(){return this.getLoggedInUsersSubscription||(this.getLoggedInUsersSubscription=this.authService.getUser$().pipe(ue(e=>e?this.documentPaths?e?.userId&&this.documentPaths?.logins?this.commonDbService.dbListener({feature:"allLogins",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,skipFirestore:!0}}).pipe(ce(i=>i?.data),gn(i=>{i?this.users=Object.values(i??{}):this.users=[]})):(this.users=[],re()):re():re())).subscribe(()=>{this.users$.next(this.users)},e=>{this.loggingService.catch("Error in ContactService getLoggedInUsers$ subscription: ",e)})),this.users$.asObservable()}getUsersMap$(){return this.authService.getUser$().pipe(ue(e=>e?.organizationId?this.userById$.pipe(ce(i=>{let r={};return Object.values(i||{}).forEach(a=>{a?.userSnippylyId&&(r[a?.userSnippylyId]=a)}),r})):this.users$.pipe(ce(i=>{let r={};return i.forEach(a=>{r[a.userSnippylyId]=a}),r}))))}getUserByEmail$(e){return this.users$.pipe(ce(i=>i.find(r=>r.email===e)))}getUserByEmail(e){return this.users?.find(i=>i.email===e)}getContactByEmail(e){return this.getInternalUserContacts().find(i=>i.email===e)}getUserByUserId$(e){return this.users$.pipe(ce(i=>i.find(r=>r.userId===e)))}getUserGroupContacts(){return this.userGroupContacts}getOrganizationContactsFromDb$(){try{this.getOrganizationContactsSubscription||(this.getOrganizationContactsSubscription=this.authService.getUser$().pipe(ue(e=>e?.organizationId?re(e).pipe(ue(i=>this.docService.getOrganizationConfig$().pipe(Ne(r=>!!r),ce(()=>i))),ue(i=>{let r=this.docService.getOrganizationConfig()?.organizationId;return this.setUserOrganizationContacts([],r),i?r?this.commonDbService.dbListener({feature:"allOrganizationUsers",properties:{organizationId:r,isCollection:!0}}).pipe(ce(a=>a?.data),ce(a=>{if(a){typeof a=="object"&&(a?.undefined&&delete a.undefined,a?.null&&delete a.null);let s=Object.values(a??{});this.setUserOrganizationContacts(s,r)}else this.setUserOrganizationContacts([],r)})):re():re()}),ue(()=>this.getContactListScopeForOrganizationUsers$())):(this.setUserOrganizationContacts([]),re()))).subscribe(()=>{this.mergeOrganizationAndDocumentContacts()},e=>{this.loggingService.catch("Error in ContactService getOrganizationContactsFromDb$ subscription: ",e)}))}catch{}}getFolderContactsFromDb$(){try{this.getFolderContactsSubscription||(this.getFolderContactsSubscription=this.authService.getUser$().pipe(ue(e=>e?re(e).pipe(ue(i=>this.docService.getOrganizationConfig$().pipe(Ne(r=>!!r),ce(()=>i))),ue(i=>this.docService.getFolderConfig$().pipe(ce(()=>i))),ue(i=>{let r=this.docService.getOrganizationConfig()?.organizationId;if(this.setUserFolderContacts([]),!i)return re();if(!this.commonDbService.shouldUseFirestore())return re();let a=this.docService.getFolderConfig();if(!a?.veltFolderId)return re();let s=re([]);return s=this.commonDbService.dbListener({feature:"allFolderUsers",properties:{organizationId:r,folderId:a?.veltFolderId,isCollection:!0}}).pipe(ce(c=>c?.data)),s.pipe(ce(c=>{if(c){typeof c=="object"&&(c?.undefined&&delete c.undefined,c?.null&&delete c.null);let p=Object.values(c??{});this.setUserFolderContacts(p)}else this.setUserFolderContacts([])}))}),ue(()=>this.getContactListScopeForOrganizationUsers$())):(this.setUserFolderContacts([]),re()))).subscribe(()=>{this.mergeOrganizationAndDocumentContacts()},e=>{this.loggingService.catch("Error in ContactService getFolderContactsFromDb$ subscription: ",e)}))}catch{}}getDocumentContactsFromDb$(){try{this.getDocumentContactsSubscription||(this.getDocumentContactsSubscription=this.authService.getUser$().pipe(ue(e=>e?re(e).pipe(ue(i=>this.docService.getDocumentPaths$().pipe(Ne(r=>!!r),gn(r=>{this.documentPaths=r}),ce(()=>i))),ue(i=>(this.setUserDocumentContacts([]),i?this.documentPaths?this.docService.getDocumentIds$().pipe(ue(r=>{let a=r?.length>0?r.map(u=>u.documentId):[this.documentPaths?.documentId??""];if(a.some(u=>!u)||!this.documentPaths)return re();let s=this.docService.getFolderConfig(),c=re([]),p={useCollectionGroup:!0,isCollection:!0,useQuery:!0};if(this.commonDbService.shouldUseFirestore()||(p.documentId=a?.length?a[0]:void 0,p.organizationId=this.documentPaths?.organizationId),s?.veltFolderId&&s?.allDocuments)c=this.commonDbService.dbListener({feature:"allDocumentUsers",properties:T(I({},p),{firestoreQuery:[Ui(dt("metadata.apiKey","==",this.configService?.getApiKey()),dt("metadata.veltFolderId","==",s?.veltFolderId),dt("metadata.organizationId","==",this.documentPaths?.organizationId))]})}).pipe(ce(u=>u?.data));else{let u=[];for(let C=0;C<a.length;C+=U.LISTENER_BATCH_SIZE)u.push(a.slice(C,C+U.LISTENER_BATCH_SIZE));c=Mn(u.map(C=>this.commonDbService.dbListener({feature:"allDocumentUsers",properties:T(I({},p),{firestoreQuery:[Ui(dt("metadata.apiKey","==",this.configService?.getApiKey()),dt("metadata.documentId","in",C),dt("metadata.organizationId","==",this.documentPaths?.organizationId),...s?.veltFolderId?[dt("metadata.veltFolderId","==",s?.veltFolderId)]:[])]})}).pipe(zr()))).pipe(ce(C=>ga(C)?.data))}return c.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([])}))})):re():re())),ue(()=>this.getContactListScopeForOrganizationUsers$())):(this.setUserDocumentContacts([]),re()))).subscribe(()=>{this.mergeOrganizationAndDocumentContacts()},e=>{this.loggingService.catch("Error in ContactService getDocumentContactsFromDb$ subscription: ",e)}))}catch{}}setUserOrganizationContacts(e,i){try{let r=e.find(s=>s.user.userId===this.user?.userId);r?this.currentOrganizationUserIAM$.next(r):this.currentOrganizationUserIAM$.next(null);let a=e.map(s=>s.user);if(this.userOrganizationContacts$.next(a),i){let s={};s[i]={},e.forEach(c=>{s[i][c.user.userId]=c,this.userById$.next(T(I({},this.userById$.value),{[c.user.userId]:c.user}))}),this.usersByOrganizationId$.next(T(I({},this.usersByOrganizationId$.value),{[i]:s[i]}))}else this.usersByOrganizationId$.next({})}catch(r){this.loggingService.catch("Error in ContactService setUserOrganizationContacts: ",r)}}getUserOrganizationContacts$(){return this.getContactListScopeForOrganizationUsers$().pipe(ue(()=>this.checkContactListScopeForOrganizationUsers([Pi.ALL,Pi.ORGANIZATION])?this.userOrganizationContacts$.asObservable():re([])))}getUserOrganizationContacts(){return this.checkContactListScopeForOrganizationUsers([Pi.ALL,Pi.ORGANIZATION])?this.userOrganizationContacts$.value:[]}setUserFolderContacts(e){try{this.userFolderContacts$.next(e?.map(r=>r?.user));let i={};e?.forEach(r=>{let{organizationId:a,veltFolderId:s}=r?.metadata||{};a&&s&&(i[a]||(i[a]={}),i[a][s]||(i[a][s]={}),i[a][s][r.user.userId]=r,this.userById$.next(T(I({},this.userById$.value),{[r.user.userId]:r.user})))}),this.usersByOrganizationIdAndFolderId$.next(i)}catch(i){this.loggingService.catch("Error in ContactService updateUserFolderContacts: ",i)}}getUserFolderContacts$(){return this.getContactListScopeForOrganizationUsers$().pipe(ue(()=>this.checkContactListScopeForOrganizationUsers([Pi.ALL,Pi.FOLDER])?this.userFolderContacts$.asObservable():re([])))}getUserFolderContacts(){return this.checkContactListScopeForOrganizationUsers([Pi.ALL,Pi.FOLDER])?this.userFolderContacts$.value:[]}setUserDocumentContacts(e){try{this.userDocumentContacts$.next(e?.map(r=>r?.user));let i={};e?.forEach(r=>{let{organizationId:a,documentId:s}=r?.metadata||{};a&&s&&(i[a]||(i[a]={}),i[a][s]||(i[a][s]={}),i[a][s][r.user.userId]=r,this.userById$.next(T(I({},this.userById$.value),{[r.user.userId]:r.user})))}),this.usersByOrganizationIdAndDocumentId$.next(i)}catch(i){this.loggingService.catch("Error in ContactService updateUserDocumentContacts: ",i)}}getUserDocumentContacts$(){return this.getContactListScopeForOrganizationUsers$().pipe(ue(()=>this.checkContactListScopeForOrganizationUsers([Pi.ALL,Pi.DOCUMENT])?this.userDocumentContacts$.asObservable():re([])))}getUserDocumentContacts(){return this.checkContactListScopeForOrganizationUsers([Pi.ALL,Pi.DOCUMENT])?this.userDocumentContacts$.value:[]}getCurrentOrganizationUserIAM$(){return this.currentOrganizationUserIAM$.asObservable()}getCurrentOrganizationUserIAM(){return this.currentOrganizationUserIAM$.value}mergeOrganizationAndDocumentContacts(){try{let e=[];this.getContactListScopeForOrganizationUsers().includes(Pi.ALL)?e=[...this.getUserOrganizationContacts(),...this.getUserFolderContacts(),...this.getUserDocumentContacts()]:this.getContactListScopeForOrganizationUsers().includes(Pi.ORGANIZATION)?e=[...this.getUserOrganizationContacts()]:this.getContactListScopeForOrganizationUsers().includes(Pi.FOLDER)?e=[...this.getUserFolderContacts()]:this.getContactListScopeForOrganizationUsers().includes(Pi.DOCUMENT)&&(e=[...this.getUserDocumentContacts()]);let i=[...new Map(e.filter(r=>r?.userId).map(r=>[r.userId,r])).values()];this.internalUserContacts$.next(i)}catch(e){this.loggingService.catch("Error in ContactService mergeOrganizationAndDocumentContacts: ",e)}}getOrganizationGroupsFromDb$(){try{this.getOrganizationGroupsSubscription||(this.getOrganizationGroupsSubscription=this.authService.getUser$().pipe(ue(e=>e?.organizationId?re(e).pipe(ue(i=>this.docService.getOrganizationConfig$().pipe(Ne(r=>!!r),ce(()=>i))),ue(i=>{if(this.setUserOrganizationGroups([]),!i)return re();let r=this.docService.getOrganizationConfig()?.organizationId;return r?this.commonDbService.dbListener({feature:"allOrganizationGroups",properties:{organizationId:r,isCollection:!0}}).pipe(ce(a=>a?.data),ce(a=>{a?(typeof a=="object"&&(a?.undefined&&delete a.undefined,a?.null&&delete a.null),this.setUserOrganizationGroups(Object.values(a??{}))):this.setUserOrganizationGroups([])})):re()})):(this.setUserOrganizationGroups([]),re()))).subscribe(()=>{},e=>{this.loggingService.catch("Error in ContactService getOrganizationGroupsFromDb$ subscription: ",e)}))}catch{}}setUserOrganizationGroups(e){try{this.userOrganizationGroups$.next(e)}catch(i){this.loggingService.catch("Error in ContactService setUserOrganizationGroups: ",i)}}onContactSelected(e){try{if(e?.userId){let i=!!this.getUserDocumentContacts().find(a=>a.userId===e.userId),r=!!this.getUserOrganizationContacts().find(a=>a.userId===e.userId);switch(this.documentAccessType){case pi.RESTRICTED:if(!i){let a={contact:e,isOrganizationContact:r,isDocumentContact:i,documentAccessType:this.documentAccessType};this.onContactSelectedSubject$.next(a)}break}}else{let i={contact:e,isOrganizationContact:!1,isDocumentContact:!1,documentAccessType:this.documentAccessType};this.onContactSelectedSubject$.next(i)}}catch(i){this.loggingService.catch("Error in ContactService onContactSelected: ",i)}}onContactSelected$(){return this.onContactSelectedSubject$.asObservable()}getOrganizationGroups$(){return this.getContactListScopeForOrganizationUsers$().pipe(ue(()=>this.checkContactListScopeForOrganizationUsers([Pi.ALL,Pi.ORGANIZATION_USER_GROUP])?this.userOrganizationGroups$.asObservable():re([])))}enableAtHere(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{atHereEnabled:!0}}),this.atHereEnabled$.value===!0)return;this.atHereEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in ContactService enableAtHere: ",e)}}setAtHereLabel(e){try{this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{atHereLabel:e}}),e&&this.atHereLabel$.next(e)}catch(i){this.loggingService.catch("Error in ContactService setAtHereLabel: ",i)}}setAtHereDescription(e){try{this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{atHereDescription:e}}),e&&this.atHereDescription$.next(e)}catch(i){this.loggingService.catch("Error in ContactService setAtHereDescription: ",i)}}disableAtHere(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{atHereEnabled:!1}}),this.atHereEnabled$.value===!1)return;this.atHereEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in ContactService disableAtHere: ",e)}}getAtHereEnabled$(){return this.getContactListScopeForOrganizationUsers$().pipe(ue(()=>this.checkContactListScopeForOrganizationUsers([Pi.ALL,Pi.DOCUMENT])?this.atHereEnabled$.asObservable():re(!1)))}getAtHereEnabled(){return this.checkContactListScopeForOrganizationUsers([Pi.ALL,Pi.DOCUMENT])?this.atHereEnabled$.value:!1}updateContactListScopeForOrganizationUsers(e){try{this.contactListScopeForOrganizationUsers$.next(e)}catch(i){this.loggingService.catch("Error in ContactService updateContactListScopeForOrganizationUsers: ",i)}}getContactListScopeForOrganizationUsers$(){return this.contactListScopeForOrganizationUsers$.asObservable()}getContactListScopeForOrganizationUsers(){return this.contactListScopeForOrganizationUsers$.value}checkContactListScopeForOrganizationUsers(e){return this.getContactListScopeForOrganizationUsers().some(i=>e.includes(i))}updateContactList(e,i){return te(this,null,function*(){try{if(this.analyticsService.trackEvent(X.Events.Contact.UPDATE_CONTACT_LIST_TRIGGERED,{contactsCount:e?.length,config:i}),this.usersService?.userDataProviderAvailable()){let r=e.map(s=>s?.userId).filter(s=>s);yield this.usersService.resolveUsers(r);let a=r.map(s=>this.usersService.getUserById(s)).filter(s=>!!s);this.customUserContacts$.next(a)}else this.customUserContacts$.next(e);this.customUserContactsConfig$.next(i)}catch(r){this.loggingService.catch("Error in CommentService updateContactList: ",r)}})}convert(e){try{if(e?.options){let{documentId:i,organizationId:r}=this.docService.getServerId(e?.options);e.options=T(I({},e?.options),{documentId:i,organizationId:r})}return this}catch(i){return this.loggingService.catch("Error in ContactService convert: ",i),this}}getContactList$(){try{return this.authService.getUser$().pipe(ue(e=>e?Mn([this.userOrganizationContacts$.asObservable(),this.userFolderContacts$.asObservable(),this.userDocumentContacts$.asObservable(),this.userOrganizationGroups$.asObservable(),this.customUserContacts$.asObservable()]).pipe(ce(([i,r,a,s,c])=>{let p={};p.organizationUsers=i?.map(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}),qt(Vi)):re(null)),Vn(e=>(this.loggingService.catch("Error in ContactService getContactList$: ",e),re(null))))}catch(e){return this.loggingService.catch("Error in ContactService getContactList$: ",e),re(null)}}convertToClientUserGroup(e,i){try{let r={groupId:e?.metadata?.clientGroupId,groupName:e?.metadata?.groupName,users:[]},a={};return i?.forEach(s=>{if(s?.userId){let c=Nt(s.userId);a[c]=s}}),Object.keys(e?.users??{}).forEach(s=>{a[s]&&r.users?.push(a[s])}),r}catch(r){return this.loggingService.catch("Error in ContactService convertToClientUserGroup: ",r),null}}convertToClientUser(e){try{return e&&(e=JSON.parse(JSON.stringify(e)),e?.clientGroupId&&(e.groupId=e.clientGroupId,delete e.clientGroupId),e?.clientOrganizationId&&(e.organizationId=e.clientOrganizationId,delete e.clientOrganizationId),e?.userSnippylyId&&delete e.userSnippylyId),e}catch(i){return this.loggingService.catch("Error in ContactService convertToClientUser: ",i),e}}getCustomUserContacts(){return this.customUserContacts$.value}getCustomUserContacts$(){return this.customUserContacts$.asObservable()}getCustomUserContactsConfig(){return this.customUserContactsConfig$.value}getCustomUserContactsConfig$(){return this.customUserContactsConfig$.asObservable()}};o.\u0275fac=function(i){return new(i||o)(Q(Ke),Q(je),Q(jt),Q(un),Q(lt),Q(y),Q(En),Q(zn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var zse=n=>{try{return n.name.split(".").slice(0,-1).join(".")}catch(o){mt.catch("Error in File utils getFileName: ",o);return}},F$=n=>{try{return/(?:\.([^.]+))?$/.exec(n?.name)[1]}catch(o){mt.catch("Error in File utils getFileExtension: ",o);return}},Gse=(n,o)=>{try{let t=n.slice(0,-1,n.type);return new File([t],o+"."+F$(n),{type:n.type})}catch(t){mt.catch("Error in File utils updateFile: ",t);return}},Wse=n=>new Promise((o,t)=>{let e=new FileReader;e.readAsDataURL(n),e.onload=()=>{o(e.result)},e.onerror=i=>{t(i)}}),qse={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 Wp=(()=>{let o=class o{constructor(e,i,r,a){this.authService=e,this.configService=i,this.loggingService=r,this.attachmentResolverService=a,this.storage=Ly();try{this.configService.getApiKey$().subscribe(s=>{this.apiKey=s}),this.authService.getFirebaseConfig$().subscribe(s=>{s&&s.firebaseOptions?.storageBucket&&(this.storage=Ly(void 0,s?.firebaseOptions?.storageBucket))},s=>{this.loggingService.catch("Error in StorageService constructor: ",s)})}catch(s){this.loggingService.catch("Error in StorageService constructor:",s)}}createAttachment({path:e,file:i}){try{let r=new Hv;r.name=i.name;let a=Gse(i,`${r.attachmentId}_${zse(i)}`),s=`${this.apiKey}/${e}/${a?.name}`;return r.bucketPath=s,r.size=i.size,r.type=F$(i),r?.type&&(r.mimeType=qse[r?.type]),r}catch(r){return this.loggingService.catch("Error in StorageService createAttachment: ",r),null}}uploadAttachmentToStorage({attachment:e,file:i,resolve:r,reject:a}){try{let s=By(this.storage,e.bucketPath),c=SB(s,i,{cacheControl:"public,max-age=3600"});c.on("state_changed",p=>{let u=p.bytesTransferred/p.totalBytes*100},p=>{a(p)},()=>{yB(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 te(this,arguments,function*({file:e,attachment:i,metadata:r,resolve:a,reject:s}){try{r.attachmentId=i.attachmentId;let p={attachmentId:i.attachmentId,name:i.name,file:e,metadata:r,mimeType:i.mimeType},u=yield this.attachmentResolverService.saveAttachment({attachment:p,eventType:Wa.ATTACHMENT_ADD});u&&u.data?.url?(i.url=u.data?.url,a(i)):s(new Error("Failed to upload attachment to resolver"))}catch(p){this.loggingService.catch("Error in StorageService uploadToResolver: ",p),s(p)}})}uploadFile({path:e,file:i,useAttachmentResolver:r,metadata:a}){return new Promise((s,c)=>{try{if(!this.apiKey)throw new Error("API key not configured");let p=this.createAttachment({path:e,file:i});if(!p)throw new Error("Attachment not created");r?this.uploadToResolver({file:i,attachment:p,metadata:a,resolve:s,reject:c}):this.uploadAttachmentToStorage({attachment:p,file:i,resolve:s,reject:c})}catch(p){this.loggingService.catch("Error in StorageService uploadFile:",p),c(p)}})}uploadChunk(e,i,r){return new Promise((a,s)=>{try{if(this.apiKey){let c=`${this.apiKey}/${e}/${i.name}`,p=By(this.storage,c),u=SB(p,i,{cacheControl:"public,max-age=3600"});u.on("state_changed",C=>{let E=C.bytesTransferred/C.totalBytes*100},C=>{s(C)},()=>{yB(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 i=new XMLHttpRequest;i.responseType="blob",i.onload=()=>{let r=i.response,a=document.createElement("a"),s=window.URL.createObjectURL(r);a.setAttribute("type","hidden"),a.setAttribute(U.ATTRIBUTES.VELT_DOWNLOAD_BUTTON,"true"),a.classList.add("snippyly-overlay-panel"),a.href=s,e?.name&&(a.download=e?.name),document.body.appendChild(a);let c=new MouseEvent("click",{view:window,bubbles:!0,cancelable:!1});a.dispatchEvent(c),window.URL.revokeObjectURL(s),a.remove()},i.onerror=()=>{window.open(e.url,"_blank")},i.open("GET",e.url),i.send()}}catch(i){this.loggingService.catch("Error in StorageService downloadAttachment: ",i)}}deleteAttachment({attachment:e,metadata:i,useAttachmentResolver:r}){return new Promise((a,s)=>{if(r)this.attachmentResolverService.deleteAttachment({attachmentId:e.attachmentId,metadata:i}).then(()=>{a(null)}).catch(c=>{s(c)});else{let c=By(this.storage,e.bucketPath);_B(c).then(()=>{a(null)}).catch(p=>{a(null)})}})}deleteFileFromPath(e){return new Promise((i,r)=>{let a=By(this.storage,e);_B(a).then(()=>{i(null)}).catch(s=>{r(s)})})}};o.\u0275fac=function(i){return new(i||o)(Q(je),Q(jt),Q(y),Q(Gp))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var hn=(()=>{let o=class o{constructor(e,i,r,a,s,c,p,u){this.analyticsService=e,this.authService=i,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(Ne(C=>!!C),et(1)).subscribe(C=>{C&&(this.db=C,this.getUser(),this.getDocumentPaths())},C=>{this.loggingService.catch("Error in CommentService getDb subscription: ",C)}),this.getRole$().pipe(et(1)).subscribe(C=>{this.authService?.getUser()&&!C&&this.analyticsService.trackEvent(X.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(Ne(e=>!!e)).subscribe(e=>{this.user=e,this.user?this.getDocumentIam():(this.getDocumentIamSubscription?.unsubscribe(),this.getOrganizationIamSubscription?.unsubscribe(),this.getWorkspaceIamSubscription?.unsubscribe())},e=>{this.loggingService.catch("Error in IamService getUser$ subscription: ",e)})}catch(e){this.loggingService.catch("Error in IamService getUser: ",e)}}getDocumentPaths(){try{this.docService.getDocumentPaths$().pipe(Ne(e=>!!e)).subscribe(e=>{this.documentPaths=e,this.getDocumentIam(),this.getWorkspaceIam()},e=>{this.loggingService.catch("Error in IamService getDocumentPaths$ subscription: ",e)})}catch(e){this.loggingService.catch("Error in IamService getDocumentPaths: ",e)}}getDocumentIam(){try{this.getDocumentIamSubscription&&(this.getDocumentIamSubscription.unsubscribe(),this.getDocumentIamSubscription=null),this.user?this.getDocumentIamSubscription=this.docService.getDocumentIam$().subscribe(e=>{let i=e||new xM;this.documentIAM$.next(i)},e=>{this.loggingService.catch("Error in IamService getDocumentIam$ subscription: ",e)}):this.documentIAM$.next(null)}catch(e){this.loggingService.catch("Error in IamService getDocumentIam: ",e)}}getWorkspaceIam(){try{this.getWorkspaceIamSubscription||(this.getWorkspaceIamSubscription=this.commonDbService.dbListener({feature:"workspaceIam",properties:{skipFirestore:!0}}).pipe(Vn(e=>re(null))).subscribe(e=>{this.workspaceIAM$.next(e?.data),this.roles$.next(e?.data?.roles||[])}))}catch(e){this.loggingService.catch("Error in IamService getWorkspaceIam: ",e)}}isUserAllowed$(){return this.getRole$().pipe(ce(e=>!!e),qt())}getDocumentIAM$(){return this.documentIAM$.asObservable()}getRoles$(){return this.roles$.asObservable().pipe(ce(e=>e?.length?e:U.WorkspaceRoles))}getFeaturesAccessLevel$(){return this.documentIAM$.asObservable().pipe(ce(e=>e?.features),ue(e=>this.getRole$().pipe(ce(i=>(i===po.ADMIN&&(e=e&&JSON.parse(JSON.stringify(e||{})),e?.all?.disabled&&(e.all.disabled=!1)),e)))))}hasRole(e){try{return e===this.getRole()}catch(i){return this.loggingService.catch("Error in IamService hasRole: ",i),!1}}hasRoleAny(e=[]){try{return e?.includes(this.getRole()||"")}catch(i){return this.loggingService.catch("Error in IamService hasRoleAny: ",i),!1}}hasRole$(e){try{return this.authService.getUser$().pipe(ue(()=>this.documentIAM$.pipe(Ne(i=>!!i),ue(()=>this.workspaceIAM$.pipe(ce(()=>e===this.getRole()))))))}catch(i){return this.loggingService.catch("Error in IamService hasRole$: ",i),re(!1)}}getRole$(){try{return this.authService.getUser$().pipe(ue(()=>this.configService.getSF$()),ue(()=>this.configService.getSF()?this.contactService.isUserGlobalContact$():re(null)),ue(()=>this.documentIAM$.pipe(Ne(e=>!!e))),ue(()=>this.workspaceIAM$),ce(()=>this.getRole()))}catch(e){return this.loggingService.catch("Error in IamService getRole$: ",e),re(null)}}getRole(){try{let e=this.configService.getSF();if(e&&this.contactService.isUserGlobalContact())return po.ADMIN;if(!e&&this.user?.isAdmin)return po.ADMIN;let i=null,r;if(this.user)switch((this.documentIAM$.value?this.documentIAM$.value?.features?.all?.restricted:!1)?pi.RESTRICTED:this.documentIAM$.value?this.documentIAM$.value?.documentAccessType||pi.PUBLIC:null){case pi.PUBLIC:r=this.getUserFromDocumentIAM(this.user?.email,this.user?.userId),r||(r=this.getUserFromWorkspaceIAM(this.user?.email,this.user?.userId)),i=r?.role?.name||po.COMMENTER;break;case pi.RESTRICTED:r=this.getUserFromDocumentIAM(this.user?.email,this.user?.userId),r||(r=this.getUserFromWorkspaceIAM(this.user?.email,this.user?.userId)),i=r?.role?.name||null;break;default:break}return i}catch(e){this.loggingService.catch("Error in IamService getRole: ",e)}return null}isUserAdmin$(){return this.getRole$().pipe(ce(e=>e===po.ADMIN),qt())}isUserAdmin(){try{return this.getRole()===po.ADMIN}catch(e){return this.loggingService.catch("Error in IamService isUserAdmin: ",e),!1}}getUserFromDocumentIAM(e,i){try{if(e||i){let r;return e&&(r=this.documentIAM$.value?.users?.[Nt(e)]),!r&&i&&(r=this.documentIAM$.value?.users?.[Nt(i)]),r}else return}catch(r){this.loggingService.catch("Error in IamService getUserFromDocumentIAM: ",r)}}getUserFromWorkspaceIAM(e,i){try{if(e||i){let r;return e&&(r=this.workspaceIAM$.value?.users?.[Nt(e)]),!r&&i&&(r=this.workspaceIAM$.value?.users?.[Nt(i)]),r}else return}catch(r){this.loggingService.catch("Error in IamService getUserFromWorkspaceIAM: ",r)}}};o.\u0275fac=function(i){return new(i||o)(Q(Ke),Q(je),Q(vi),Q(un),Q(lt),Q(jt),Q(y),Q(En))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var jn=(()=>{let o=class o{constructor(e,i,r,a,s,c,p,u,C,E,A,B,G,K,pe,Ce){this.afAuth=e,this.analyticsService=i,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=A,this.iamService=B,this.loggingService=G,this.notificationUtilsService=K,this.usersService=pe,this.functions=Ce,this.db=bi(),this.notificationsDb=bi(void 0,Xn.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}});try{this.subscribeNotificationsData().subscribe(),this.commentUtilsService.setNotificationService(this),this.databaseService.getDb().pipe(Ne(Ie=>!!Ie),et(1)).subscribe(Ie=>{Ie&&(this.db=Ie,this.getDocumentIds(),this.subscribeGetNotificationsForYou())},Ie=>{this.loggingService.catch("Error in NotificationService getDb subscription: ",Ie)}),this.authService.getUser$().subscribe(Ie=>{Ie?(this.subscribeGetNotificationsForYou(),this.getDocumentIds()):(Object.keys(this.notificationsByDocumentIdSubscription).forEach($e=>{this.notificationsByDocumentIdSubscription[$e]?.unsubscribe()}),this.notificationForYouSubscription?.unsubscribe(),this.documentIdsSubscription?.unsubscribe(),this.resetCacheData())}),this.docService.getLocationMetadata$().subscribe(Ie=>{if(Ie){let $e=this.notificationsByDocumentIdMap$.getValue()?JSON.parse(JSON.stringify(this.notificationsByDocumentIdMap$.getValue())):null;Object.keys(Ie||{}).forEach(Ye=>{let ke=$e?.[Ye]?.notifications;ke?.length&&ke.forEach(Se=>{this.notificationUtilsService.mergeLocationWithNotification({notification:Se},Ie)?.notification})}),this.notificationsByDocumentIdMap$.next($e)}})}catch(Ie){this.loggingService.catch("Error in NotificationService constructor: ",Ie)}}resetCacheData(){try{this.loggingService.log("%c[WB] Calling NotificationService FUNCTION: resetCacheData","color: green;"),this.notificationsByDocumentIdMap$.next(null),this.notificationsForYou$.next(null)}catch(e){this.loggingService.catch("Error in NotificationService resetCacheData: ",e)}}subscribeGetNotificationsForYou(){try{this.notificationForYouSubscription&&this.notificationForYouSubscription.unsubscribe(),this.notificationForYouSubscription=this.getNotificationsForYou().subscribe(()=>{},e=>{this.loggingService.catch("Error in NotificationService getNotificationsForYou subscription: ",e)})}catch(e){this.loggingService.catch("Error in NotificationService subscriveGetNotificationsForYou: ",e)}}setCommentService(e){try{this.commentService=e}catch(i){this.loggingService.catch("Error in NotificationService setCommentService: ",i)}}getDocumentIds(){try{this.documentIdsSubscription&&this.documentIdsSubscription.unsubscribe(),this.documentIdsSubscription=this.getDocumentIdsByLastNotificationTimestamp().pipe(Ai(),ce(([e,i])=>{let r=e?.map(u=>u.documentId),a=i?.map(u=>u.documentId),s=r?.filter(u=>!a?.includes(u)),c=a?.map(u=>({documentId:u,timestamp:i?.find(C=>C.documentId===u)?.timestamp})).filter(u=>!r?.includes(u.documentId)),p=a?.map(u=>{let C=i?.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)}),i&&!i?.length&&!this.notificationsByDocumentIdMap$.getValue()&&this.notificationsByDocumentIdMap$.next({})})).subscribe(()=>{},e=>{this.loggingService.catch("Error in NotificationService getDocumentIds subscription: ",e)})}catch(e){this.loggingService.catch("Error in NotificationService getDocumentIds: ",e)}}getDocumentIdsByLastNotificationTimestamp(e=15){try{return this.authService.getUser$().pipe(ue(i=>this.docService.getOrganizationConfig$().pipe(ce(r=>{let a=null,s=this.configService.getApiKey(),c=r?.organizationId||i?.organizationId;return s&&c&&(a=new Im({apiKey:s,organizationId:c})),{user:i,documentPaths:a}}))),ue(i=>{let{user:r,documentPaths:a}=i;if(r&&a?.organizationNotificationsLastNotificationTimestamp){let s=new Date,c=this.maxNotificationDays$.getValue()>0?this.maxNotificationDays$.getValue():15;s.setDate(s.getDate()-c);let p=s.getTime();return this.commonDbService.dbListener({feature:"allLastNotificationTimestamp",properties:{organizationId:a?.organizationId,isCollection:!0,useQuery:!0,firestoreQuery:[Ui(dt("timestamp",">=",p)),Ya("timestamp","desc"),$v(e)]}}).pipe(ce(u=>u?.data),ce(u=>{let C=[];return Object.keys(u||{}).forEach(E=>{let A=this.commonDbService.shouldUseFirestore()?u[E]?.timestamp??0:u[E],B=this.commonDbService.shouldUseFirestore()?u[E]?.deletedNotification??!1:!1;if(B&&B.id&&B?.timestamp===A){let G=B.id,K=u[E]?.metadata?.documentId,pe=JSON.parse(JSON.stringify(this.notificationsByDocumentIdMap$.getValue()??{})),Ce=pe?.[K]??{documentMetadata:null,notifications:[]},Ie=Ce.notifications??[],$e=Ie?.findIndex(Ye=>Ye.id===G);$e!==-1&&(Ie.splice($e,1),this.notificationsByDocumentIdMap$.next(T(I({},pe),{[K]:T(I({},Ce),{notifications:Ie})})))}C.push({documentId:E,timestamp:A})}),C}),Vn(u=>(this.loggingService.catch("Error in NotificationService getDocumentIdsByLastNotificationTimestamp: ",u),re([]))))}return re(null)}))}catch(i){return this.loggingService.catch("Error in NotificationService getDocumentIdsByLastNotificationTimestamp: ",i),re([])}}fetchNotificationsForDocumentIds(e,i=15){return te(this,null,function*(){try{if(e?.length){let r=_r(this.functions,Sr({url:Xn.cloudFunction.getNotificationsForDocuments,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:12e5}),a=this.docService.getOrganizationConfig()?.organizationId??"",s=this.getStartAtTimestamp(),c={};e.forEach(B=>{if(B?.documentId){let G=this.getAllowedDocumentMetadataByDocumentId(B.documentId);G&&(c[B.documentId]=G)}});let p={organizationId:a,documentIds:e,timestamp:s,limitToLast:i,documentMetadataByDocumentId:c},u=yield this.notificationUtilsService.handleNotificationEncryption({data:p}),C=(yield r({veltData:u}))?.data?.data?.veltData||{},E="notificationwithdocumentidstoencryptanddecryptonsdk"+(this.authService.getUser()?.userId??""),A=yield ioe(C,E);if(A&&typeof A=="object"){let B=this.usersService.userDataProviderAvailable(),G=this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable(),K=[],pe=[];Object.keys(A).forEach((Ce,Ie)=>{let $e=A[Ce].documentMetadata;if($e){let ke=this.allowedDocumentMetadataMap$.value||{};(!ke?.[Ce]||!_o(ke?.[Ce],$e))&&this.allowedDocumentMetadataMap$.next(T(I({},ke),{[Ce]:$e}))}let Ye=A[Ce].notifications||[];Ye.forEach(ke=>{ke.notification=this.getClientNotificationObject(ke)}),this.setNotificationForDocumentIdInCache(Ce,$e,Ye),B&&K.push(this.commonDbUtilsService.formatResponse({feature:"allDocNotifications",data:Ye,shouldAwait:!0,forceResolve:!0})),G&&pe.push(this.commonDbUtilsService.formatResponse({feature:"allDocNotifications",data:Ye,shouldCommentAnnotationsResolverAwait:!0}))}),B&&Promise.all(K).then(()=>{Object.keys(A).forEach(Ce=>{let Ie=A?.[Ce]?.documentMetadata||{},$e=this.commonDbUtilsService.mergeUsersWithData({feature:"allDocNotifications",data:A?.[Ce]?.notifications||[]});$e.forEach(Ye=>{Ye.notification=this.getClientNotificationObject(Ye)}),this.setNotificationForDocumentIdInCache(Ce,Ie,$e)})}),G&&Promise.all(pe).then(()=>{Object.keys(A).forEach(Ce=>{let Ie=A?.[Ce]?.documentMetadata||{},$e=A?.[Ce]?.notifications?.reduce((Ye,ke)=>(Ye[ke.notificationId]=ke,Ye),{});$e=this.commonDbUtilsService.mergeCommentAnnotationsWithData({feature:"allDocNotifications",data:$e}),$e=Object.values($e??{}),$e.forEach(Ye=>{Ye.notification=this.getClientNotificationObject(Ye)}),this.setNotificationForDocumentIdInCache(Ce,Ie,$e)})})}}}catch(r){return this.loggingService.catch("Error in NotificationService fetchNotificationsForDocumentIds: ",r),[]}})}setNotificationForDocumentIdInCache(e,i,r,a){try{let s=this.docService.getOrganizationConfig()?.organizationId??"",c=this.docService.getOrganizationMetadata(s);i||(i=JSON.parse(JSON.stringify(this.docService.getDocumentMetadata()||{}))),c||(c=JSON.parse(JSON.stringify(this.docService.getOrganizationMetadata(s)||{})));let p=this.notificationsByDocumentIdMap$.getValue(),u=p?.[e]?.notifications||[],C=this.docService.getLocationMetadatas(),E=r?.map(G=>{let K=G.notification;return K.metadata&&(K.metadata.documentName=i?.documentName||K.metadata.documentName,K.metadata.organizationMetadata=c||K.metadata.organizationMetadata,K.metadata.documentMetadata=i||K.metadata.documentMetadata),C&&(K=this.notificationUtilsService.mergeLocationWithNotification({notification:K},C)?.notification),K})?.filter(G=>!!G)||[],A=new Map(u.map(G=>[G.id,G]));E.forEach(G=>{A.set(G.id,G)});let B=Array.from(A.values()).sort((G,K)=>(K.timestamp||0)-(G.timestamp||0));this.notificationsByDocumentIdMap$.next(T(I({},p),{[e]:{notifications:B,documentMetadata:i}}))}catch(s){this.loggingService.catch("Error in NotificationService setNotificationForDocumentIdInCache: ",s)}}removeNotificationsForDocumentId(e){try{this.notificationsByDocumentIdSubscription[e]&&this.notificationsByDocumentIdSubscription[e].unsubscribe();let i=this.notificationsByDocumentIdMap$.getValue();delete i?.[e],this.notificationsByDocumentIdMap$.next(i)}catch(i){this.loggingService.catch("Error in NotificationService removeNotificationsForDocumentId: ",i)}}getNotificationsForDocumentId$(e,i=50){try{return this.authService.getUser$().pipe(ce(r=>({user:r})),ue(r=>this.maxNotificationDays$.pipe(ce(()=>r))),ue(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 bo(this.commonDbService.queryData({feature:"allDocNotifications",properties:{rtdbQuery:[qL("timestamp"),KL(u),WL(i)],firestoreQuery:[Ya("timestamp","desc"),dt("timestamp",">=",u),dt("notification.actionUser.userId","!=",a.userId),$v(i)],apiKey:s,organizationId:this.docService?.getDocumentPaths()?.organizationId||a?.organizationId,documentId:e}})).pipe(ue(C=>this.commonDbUtilsService.mergeUsersWithData$({feature:"allDocNotifications",data:{data:C,operation:null}})),ce(C=>C?.data??[]),ce(C=>(C.sort((E,A)=>A.timestamp-E.timestamp),C)),Vn(C=>(this.loggingService.catch("Error in NotificationService getNotificationsForDocumentId: ",C),re([]))),ce(C=>(C.forEach(E=>{E.notification=this.getClientNotificationObject(E)}),C)))}return re([])}))}catch(r){return this.loggingService.catch("Error in NotificationService getNotificationsForDocumentId: ",r),re([])}}getStartAtTimestamp(){try{let e=new Date,i=this.maxNotificationDays$.getValue()>0?this.maxNotificationDays$.getValue():15;return e.setDate(e.getDate()-i),e.getTime()}catch(e){return this.loggingService.catch("Error in NotificationService getStartAtTimestamp: ",e),0}}getNotificationsForYou(){try{return this.databaseService.getDb().pipe(ue(e=>this.authService.getUser$().pipe(ce(i=>({db:e,user:i})))),ue(e=>this.maxNotificationDays$.pipe(ce(()=>e))),ue(e=>{let{db:i,user:r}=e,a=this.configService.getApiKey();if(i&&r?.organizationId&&a){let s=Nt(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:[qL("timestamp"),KL(u),WL(50)],firestoreQuery:[Ya("timestamp","desc"),dt("timestamp",">=",u),dt("notification.actionUser.userId","!=",r.userId),$v(50)],apiKey:a,organizationId:this.docService?.getDocumentPaths()?.organizationId||r?.organizationId,documentId:this.docService.getDocumentPaths()?.documentId,userId:s}}).pipe(ue(C=>C?.data?re(C).pipe(ce(E=>E?.data),ce(E=>{let A=Object.values(E||{});return A.forEach(G=>{G.notification=this.getClientNotificationObject(G)}),A.sort((G,K)=>K.timestamp-G.timestamp),A.map(G=>G.notification).filter(G=>!!G)}),ue(E=>{let A={data:E?.reduce((B,G)=>(B[G.id]={notification:G},B),{}),operation:null};return this.commonDbUtilsService.mergeLocationMetadataWithData$({data:A,feature:"allUserNotifications"}).pipe(ce(B=>Object.values(B?.data||{}).map(G=>G?.notification)))})):re(null)))}return re(null)}),ue(e=>{let i=this.docService.getOrganizationConfig()?.organizationId??"";return this.docService.getOrganizationMetadata$(i).pipe(ce(()=>e))}),ue(e=>this.allowedDocumentMetadataMap$.pipe(ce(()=>e))),ce(e=>(e?.length&&(e=e.map(i=>{if(i?.metadata){let r=this.docService.getOrganizationConfig()?.organizationId??"",a=this.getAllowedDocumentMetadataByDocumentId(i.metadata.documentId),s=this.docService.getOrganizationMetadata(r);a||(a=JSON.parse(JSON.stringify(this.docService.getDocumentMetadata()||{}))),s||(s=JSON.parse(JSON.stringify(this.docService.getOrganizationMetadata(r)||{}))),i.metadata.documentName=a?.documentName||i.metadata.documentName,i.metadata.organizationMetadata=s||i.metadata.organizationMetadata,i.metadata.documentMetadata=a||i.metadata.documentMetadata}return i})),e===null?this.notificationsForYou$.next(null):e?.length?this.notificationsForYou$.next(e):this.notificationsForYou$.next([]),re(e))))}catch(e){return this.loggingService.catch("Error in NotificationService getNotificationsForYou: ",e),re({})}}subscribeNotificationsData(e,i){this.loggingService.log("%c[WB] Calling FUNCTION: subscribeViewsData","color: green;");let r,a;try{if(e&&(a=Cn(e)),i&&typeof i=="object"){let s=Qo(i);r=Cn(JSON.stringify(s))}}catch(s){this.loggingService.catch("Error in ViewsService subscribeViewsData: ",s)}return qn(this.afAuth).pipe(Ne(s=>!!s),ue(s=>this.isFeatureAllowed({firebaseUser:s})),ue(s=>s.featureAllowed?this.iamService.isUserAllowed$().pipe(ce(c=>(s.featureAllowed=c,s))):re(s)),ue(s=>!s.featureAllowed||s?.user?.organizationId?(this.notifications$.next([]),this.rawNotificationsByIdMap$.next(new Map),this.processedNotifications$.next([]),this.notificationsByIdMap$.next(new Map),this.notificationViews$.next({}),this.setNotificationsByIdMap(),re([])):re(s).pipe(ue(c=>this.docService.getDocumentPaths$().pipe(ce(p=>(this.documentPaths=p,c.documentPaths=p,c)))),ue(c=>this.getDataFromDocumentId(a)))))}isFeatureAllowed(e){return this.configService.getConfig$().pipe(Ne(i=>!!i),ce(i=>T(I({},e),{config:i})),ue(i=>this.authService.getUser$().pipe(ce(r=>T(I({},i),{user:r})))),ue(i=>Ji(i.config,i.user,Re.NOTIFICATION)?re(T(I({},i),{featureAllowed:!0})):(this.loggingService.warn("Notification feature is not allowed."),re(T(I({},i),{featureAllowed:!1})))))}getDataFromDocumentId(e){return this.databaseService.getDb().pipe(Ne(i=>!!i),ue(i=>{if(this.db=i,this.loggingService.log(this.db),this.configService?.getApiKey()&&this.documentPaths?.views){let r=`${this.configService.getApiKey()}`;this.documentPaths?.organizationId&&(r+=`/${U.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${this.documentPaths.organizationId}`);let a=on(this.db,`${e?r+"/"+U.FIREBASE_PARTIAL_PATH_DOCS+"/"+e+"/"+U.FIREBASE_PARTIAL_PATH_VIEWS+"/":this.documentPaths?.notifications}`);return Bf(a).pipe(Vn(s=>(this.loggingService.catch("Error in NotificationService getDataFromDocumentId: ",s),re(null))),ce(s=>{let c=[],p=new Map;s?.raw&&(Object.keys(s?.raw||{}).forEach(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 re(null)}))}setNotificationsByIdMap(){try{let e=this.authService.getUser();if(e){let i=this.notificationViews$.getValue(),r;e?.email&&(r=Nt(e?.email));let a;e?.userId&&(a=Nt(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 A=this.commentService?.getAnnotationById(C.targetAnnotationId);A||E?.annotationData&&(A=E.annotationData),A&&(C.notificationSourceData=Hn(A))}s.set(p.id,C)}}),s.forEach((p,u)=>{p.isUnread=p?.actionUser?.userSnippylyId!==e?.userSnippylyId&&!i?.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:i,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=Nt(c?.email));let C=null;c?.userId&&(C=Nt(c?.userId));let E=!1,A=!0;(u&&p.notifyUsers?.[u]||C&&p.notifyUsersByUserId?.[C])&&(E=!0),C&&a?.[C]&&(A=!1);let B={id:p.id};if(s?B=T(I(I({},B),s),{displayHeadlineMessage:this.getNotificationHeadlineMessage(s),displayBodyMessage:this.getNotificationBodyMessage(s),forYou:E,isUnread:A}):B={id:e.id,notificationSource:e.notificationSource,actionType:e.actionType,actionUser:e.actionUser,timestamp:e.timestamp,targetAnnotationId:e.targetAnnotationId,displayHeadlineMessage:this.getNotificationHeadlineMessage(e),displayBodyMessage:this.getNotificationBodyMessage(e),forYou:E,isUnread:A,metadata:r},B?.notificationSource==="comment"&&B?.targetAnnotationId){let G=this.commentService?.getAnnotationById(B.targetAnnotationId);G||s?.notificationSourceData&&(G=s?.notificationSourceData),G||i?.annotationData&&(G=i.annotationData),G&&(B.notificationSourceData=Hn(G))}return i?.targetAnnotationData?.isCommentResolverUsed&&(B.isCommentResolverUsed=i?.targetAnnotationData?.isCommentResolverUsed),B}return}catch(c){this.loggingService.catch("Error in NotificationService getClientNotificationObject: ",c);return}}getNotificationsForYou$(){return this.notificationsForYou$.asObservable()}getNotificationsByDocumentId$(){return this.notificationsByDocumentIdMap$.asObservable().pipe(ce(e=>e?Object.keys(e??{}).map(i=>{let r=e[i].notifications||[],a=r.filter(c=>c.isUnread).length,s=r.length>0&&r[0]?.timestamp||0;return{documentId:i,notifications:e[i]?.notifications,unreadNotificationsCount:a,latestNotificationTimestamp:s,documentMetadata:e[i]?.documentMetadata}}).filter(i=>i.notifications?.length>0).sort((i,r)=>r.latestNotificationTimestamp-i.latestNotificationTimestamp):null))}getAllNotifications$(){return this.getNotificationsByDocumentId$().pipe(ce(e=>{let i=null;return e?(i=[],e.forEach(r=>{r.notifications.forEach(a=>{i?.push(a)})}),i?.sort((r,a)=>a.timestamp-r.timestamp)):null}))}processNotificationData(e){try{let i=e?.annotationData?.metadata,r=this.docService.getOrganizationConfig()?.organizationId;e.metadata=JSON.parse(JSON.stringify(this.docService.getDocumentMetadata(i?.documentId)||{})),e.metadata||(e.metadata={},this.loggingService.catch("Warning in NotificationService updateNotificationDatabase: ","Document metadata not found")),delete e.metadata.locations,e.metadata.documentMetadata=JSON.parse(JSON.stringify(this.docService.getDocumentMetadata(i?.documentId)||{})),e?.metadata?.documentMetadata?.clientDocumentId&&e?.metadata?.documentMetadata?.documentId&&(e.metadata.documentMetadata.documentId=e?.metadata?.documentMetadata?.clientDocumentId),delete e.metadata.documentMetadata.locations,e.metadata.organizationMetadata=JSON.parse(JSON.stringify(r?this.docService.getOrganizationMetadata(r)||{}:{})),e?.metadata?.organizationMetadata?.clientOrganizationId&&e?.metadata?.organizationMetadata?.organizationId&&(e.metadata.organizationMetadata.organizationId=e?.metadata?.organizationMetadata?.clientOrganizationId);let a=this.configService.getApiKey();e.metadata.apiKey=a,e.platform=this.configService.getSF()?"sf":"sdk",e.actionUser=this.authService.getUser();let s=i?.documentId?new Im({apiKey:a,documentId:i.documentId,organizationId:i?.organizationId}):this.docService.getDocumentPaths();e?.actionUser?.organizationId&&(e.metadata.organizationId=s?.organizationId||e.actionUser.organizationId,e.metadata.clientOrganizationId=s?.clientOrganizationId||e.actionUser.clientOrganizationId);let c=this.docService.getLocation();c&&(e.location=c?.location,e.locationId=c?.locationId),this.loggingService.log(`[NOTIFICATION] ${e?.notificationSource} ${e?.actionType}`,e);let p=this.commonDbService.getServerTimestamp(),u=this.notificationUtilsService.formatNotification(e,p);return JSON.parse(JSON.stringify(u))}catch(i){return this.loggingService.catch("Error in NotificationService processNotificationData: ",i),null}}updateNotificationDatabase(e){try{let i=on(this.notificationsDb),r=this.processNotificationData(e);n5(i,JSON.parse(JSON.stringify(r)))}catch(i){this.loggingService.catch("Error in NotificationService updateNotificationDatabase: ",i)}}getRawNotifications$(){return this.notifications$.asObservable()}getProcessedNotifications$(){return this.processedNotifications$.asObservable()}getNotifications$(){return this.authService.getUser$().pipe(ue(e=>e?e.organizationId?this.getAllNotifications$().pipe(ue(i=>this.notificationsForYou$.pipe(ce(r=>{let a=new Map;return(i||[]).forEach(s=>{s.id&&a.set(s.id,s)}),(r||[]).forEach(s=>{s.id&&!a.has(s.id)&&a.set(s.id,s)}),Array.from(a.values()).sort((s,c)=>(c.timestamp||0)-(s.timestamp||0))})))):this.notificationsByIdMap$.asObservable().pipe(ce(i=>Array.from(i.values())),ce(i=>i.sort((r,a)=>a.timestamp-r.timestamp)),Pg()):re(null)))}getRawNotificationById(e){try{return this.rawNotificationsByIdMap$.getValue()?.get(e)}catch(i){this.loggingService.catch("Error in NotificationService getRawNotificationById: ",i);return}}setNotificationViews(e){try{this.notificationViews$.next(e),this.setNotificationsByIdMap()}catch(i){this.loggingService.catch("Error in NotificationService setNotificationViews: ",i)}}getNotificationHeadlineMessage(e){try{let i=this.authService.getUser();if(e?.displayHeadlineMessageTemplate&&e?.displayHeadlineMessageTemplateData){let r=e.displayHeadlineMessageTemplate,a=e.displayHeadlineMessageTemplateData,s=/\{(\w+)\}/g,c=r.replace(s,(p,u)=>(u==="actionUser"||u==="recipientUser")&&a[u]?i?.email&&a[u].email===i?.email||i?.userId&&a[u]?.userId===i?.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(i){return this.loggingService.catch("Error in NotificationService getNotificationHeadlineMessage: ",i),""}}getNotificationBodyMessage(e){try{if(e?.displayBodyMessageTemplate&&e?.displayBodyMessageTemplateData){let i=e?.displayBodyMessageTemplate;return e?.displayBodyMessageTemplateData&&e?.displayBodyMessageTemplateData?.users?.forEach(r=>{if(r?.userId){let a=this.usersService.getUserById(r?.userId);i=i?.replaceAll(`{{${r.userId}}}`,a?.name||a?.email||'<velt-skeleton-loader width="50px" height="20px" border-radius="4px"></velt-skeleton-loader>')}}),this.domService.sanitizeHtml(i)}return this.domService.sanitizeHtml(e.displayBodyMessage||"")}catch(i){return this.loggingService.catch("Error in NotificationService getNotificationBodyMessage: ",i),""}}setHistoryPanelVisibility(e,i=!1,r=!1){try{e?document.querySelector(U.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL)?this.historyPanelVisible$.next(e):this.loggingService.catch("Error in NotificationService setHistoryPanelVisibility: ",`<${U.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`):this.historyPanelVisible$.next(e),e?this.analyticsService.trackEvent(X.Events.Notifications.NOTIFICATION_HISTORY_PANEL_OPENED):this.analyticsService.trackEvent(X.Events.Notifications.NOTIFICATION_HISTORY_PANEL_CLOSED)}catch{this.loggingService.catch("Error in NotificationService setHistoryPanelVisibility: ",`<${U.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`)}}toggleHistoryPanelVisibility(e=!1,i=!1){try{this.historyPanelVisible$.value?this.historyPanelVisible$.next(!this.historyPanelVisible$.value):document.querySelector(U.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL)?(this.historyPanelVisible$.next(!this.historyPanelVisible$.value),this.historyPanelVisible$.value?this.analyticsService.trackEvent(X.Events.Notifications.NOTIFICATION_HISTORY_PANEL_TOGGLED,{action:"closed"}):this.analyticsService.trackEvent(X.Events.Notifications.NOTIFICATION_HISTORY_PANEL_TOGGLED,{action:"opened"})):this.loggingService.catch("Error in NotificationService toggleHistoryPanelVisibility: ",`<${U.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`)}catch{this.loggingService.catch("Error in NotificationService toggleHistoryPanelVisibility: ",`<${U.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`)}}getHistoryPanelVisibility$(){return this.historyPanelVisible$.asObservable()}setNotificationsAsRead(e){return te(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(i){this.loggingService.catch("Error in NotificationService setNotificationsAsRead: ",i)}})}setAllNotificationsAsRead(e){return te(this,null,function*(){try{if(e?.tabId==="for-you"){let i=this.notificationsForYou$.value||[];this.setNotificationsAsRead(i)}else this.getNotifications$().pipe(et(1)).subscribe(i=>{i&&this.setNotificationsAsRead(i)})}catch(i){this.loggingService.catch("Error in NotificationService setAllNotificationsAsRead: ",i)}})}getUnreadNotificationsCount$(){try{return this.notificationsForYou$.pipe(ce(e=>e?.filter(r=>r?.isUnread)?.length??null),ue(e=>this.getNotifications$().pipe(ce(i=>{let r=i?.filter(a=>a?.isUnread)?.length??null;return{forYou:e,all:r}}))))}catch(e){return this.loggingService.catch("Error in NotificationService getUnreadNotificationsCount$: ",e),re({forYou:null,all:null})}}setNotificationAsRead(e){return te(this,null,function*(){try{let i=this.authService.getUser();if(i&&e?.id){let r=Nt(i?.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(i){this.loggingService.catch("Error in NotificationService setNotificationAsRead: ",i)}})}setMaxDays(e){try{e>0?this.maxNotificationDays$.next(e):this.maxNotificationDays$.next(15)}catch(i){this.loggingService.catch("Error in NotificationService setMaxDays: ",i)}}setTabConfig(e){try{e&&this.tabConfig$.next(e)}catch(i){this.loggingService.catch("Error in NotificationService setTabConfig: ",i)}}getTabConfig$(){return this.tabConfig$.asObservable()}getTabConfig(){return this.tabConfig$.value}enableReadNotificationsOnForYouTab(){this.readNotificationsOnForYouTab$.next(!0)}disableReadNotificationsOnForYouTab(){this.readNotificationsOnForYouTab$.next(!1)}getReadNotificationsOnForYouTab$(){return this.readNotificationsOnForYouTab$.asObservable()}getReadNotificationsOnForYouTab(){return this.readNotificationsOnForYouTab$.value}markNotificationAsReadById(e){return te(this,null,function*(){try{this.getNotifications$().pipe(et(1)).subscribe(i=>{if(i){let r=i.filter(a=>a.id===e);this.setNotificationsAsRead(r)}})}catch(i){this.loggingService.catch("Error in NotificationService markNotificationAsReadById: ",i)}})}getAllowedDocumentMetadataByDocumentId(e){try{return this.allowedDocumentMetadataMap$.value?.[e]||null}catch(i){return this.loggingService.catch("Error in NotificationService getAllowedDocumentMetadataByDocumentId: ",i),null}}};o.\u0275fac=function(i){return new(i||o)(Q(Si),Q(Ke),Q(je),Q(jt),Q(En),Q(Zv),Q(Yv),Q(bs),Q(un),Q(lt),Q(Fe),Q(hn),Q(y),Q(qM),Q(zn),Q(Uo))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Ho=(()=>{let o=class o{constructor(e){this.loggingService=e,this._customStatusMap=new ve(U.CommentAnnotationStatusMap),this._customPriorityMap=new ve(U.CommentAnnotationPriorityMap),this._customCategoryMap=new ve(U.CommentCategoryMap);try{let i=sessionStorage.getItem(U.SESSION_STORAGE.VELT_CUSTOM_PRIORITY_MAP);i&&this._customPriorityMap.next(JSON.parse(i));let r=sessionStorage.getItem(U.SESSION_STORAGE.VELT_CUSTOM_STATUS_MAP);r&&this._customStatusMap.next(JSON.parse(r));let a=sessionStorage.getItem(U.SESSION_STORAGE.VELT_CUSTOM_CATEGORY_MAP);a&&this._customCategoryMap.next(JSON.parse(a))}catch(i){this.loggingService.catch("Error in CustomFilterService constructor: ",i)}}setCustomStatusFilters(e){try{if(e.length<2){this._customStatusMap.next(U.CommentAnnotationStatusMap),sessionStorage.setItem(U.SESSION_STORAGE.VELT_CUSTOM_STATUS_MAP,JSON.stringify(U.CommentAnnotationStatusMap)),this.loggingService.catch("Custom status filters must have at least 2 filters");return}let i={};e.forEach(r=>{i[r.id]=r,r.type||(r.type="ongoing")}),this._customStatusMap.next(i),sessionStorage.setItem(U.SESSION_STORAGE.VELT_CUSTOM_STATUS_MAP,JSON.stringify(i))}catch(i){this.loggingService.catch("Error in CustomFilterService setCustomStatusFilters: ",i)}}setCustomPriorityFilters(e){try{if(e.length<2){this._customPriorityMap.next(U.CommentAnnotationPriorityMap),sessionStorage.setItem(U.SESSION_STORAGE.VELT_CUSTOM_PRIORITY_MAP,JSON.stringify(U.CommentAnnotationPriorityMap)),this.loggingService.catch("Custom priority filters must have at least 2 filters");return}let i={};e.forEach(r=>{i[r.id]=r}),this._customPriorityMap.next(i),sessionStorage.setItem(U.SESSION_STORAGE.VELT_CUSTOM_PRIORITY_MAP,JSON.stringify(i))}catch(i){this.loggingService.catch("Error in CustomFilterService setCustomPriorityFilters: ",i)}}setCustomCategories(e){try{let i={};e.forEach(r=>{i[r.id]=r}),this._customCategoryMap.next(i),sessionStorage.setItem(U.SESSION_STORAGE.VELT_CUSTOM_CATEGORY_MAP,JSON.stringify(i))}catch(i){this.loggingService.catch("Error in CustomFilterService setCustomCategories: ",i)}}get customStatusMap$(){return this._customStatusMap.asObservable()}get customPriorityMap$(){return this._customPriorityMap.asObservable()}get customCategoryMap$(){return this._customCategoryMap.asObservable()}get defaultStatus(){try{let i=Object.entries(this._customStatusMap.value).find(([r,a])=>a.type==="default");if(i)return i[1]}catch(e){this.loggingService.catch("Error in CustomFilterService defaultStatus: ",e)}return U.CommentAnnotationStatusMap.OPEN}get resolvedStatus(){try{let i=Object.entries(this._customStatusMap.value).find(([r,a])=>a.type==="terminal");if(i)return i[1]}catch(e){this.loggingService.catch("Error in CustomFilterService resolvedStatus: ",e)}return U.CommentAnnotationStatusMap.OPEN}get ongoingStatuses(){try{let i=Object.entries(this._customStatusMap.value).filter(([r,a])=>a.type==="ongoing");if(i)return i.map(r=>r[1])}catch(e){this.loggingService.catch("Error in CustomFilterService ongoingStatuses: ",e)}return[U.CommentAnnotationStatusMap.IN_PROGRESS]}convertLegacyAnnotationStatus(e){try{if(typeof e.status=="string"||e.status===void 0){let i=Object.entries(this._customStatusMap.value),r=i.find(([a,s])=>s.type==="default");switch(e.status){case"open":r&&(e.status=r[1]);break;case"inProgress":let a=i.find(([c,p])=>p.type==="ongoing");a&&(e.status=a[1]);break;case"resolved":let s=i.find(([c,p])=>p.type==="terminal");s&&(e.status=s[1]);break;default:r&&(e.status=r[1]);break}}return e}catch(i){return this.loggingService.catch("Error in CustomFilterService convertLegacyAnnotation: ",i),e}}convertLegacyPriority(e){try{typeof e.priority=="string"&&(e.priority=U.CommentAnnotationPriorityMap[e.priority])}catch(i){this.loggingService.catch("Error in CustomFilterService convertLegacyPriority: ",i)}return e}convertLegacyCategory(e){try{if(e.commentCategories===void 0||e.commentCategories===null||!Array.isArray(e.commentCategories)||e.commentCategories.length===0)return e;typeof e.commentCategories[0]=="string"&&(e.commentCategories=e.commentCategories.map(i=>U.CommentCategoryMap[i]))}catch(i){this.loggingService.catch("Error in CustomFilterService convertLegacyCategory: ",i)}return e}};o.\u0275fac=function(i){return new(i||o)(Q(y))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var bc=(()=>{let o=class o{constructor(e,i,r){this.domService=e,this.loggingService=i,this.sanitizer=r,this.emojis={};try{this.loggingService.log("%c[WB] Creating CLASS: EmojiService","color: blue;"),Object.keys(o.Icons).forEach(a=>{let s=o.Icons[a];this.emojis[a]=this.sanitizer.bypassSecurityTrustHtml(this.domService.sanitizeSvg(s))}),Object.keys(o.GIF_PATHS).forEach(a=>{let s=`<img src="${o.GIF_PATHS[a]}" alt="${a}" />`;this.emojis[a]=this.sanitizer.bypassSecurityTrustHtml(this.domService.sanitizeHtml(s))})}catch(a){this.loggingService.catch("Error in EmojiService constructor: ",a)}}getEmoji(e){try{return this.emojis[e]}catch{return""}}getEmojiFromIconUrl(e){try{return this.sanitizer.bypassSecurityTrustHtml(this.domService.sanitizeHtml(`<img src="${e}" alt="emoji" />`))}catch{return""}}getEmojiFromIconEmoji(e,i){try{let r=`<span class="velt-emoji-icon velt-emoji-icon--emoji">${e}</span>`;return i&&(r=`<span class="velt-emoji-icon velt-emoji-icon--emoji" emoji-id=${i}>${e}</span>`),this.sanitizer.bypassSecurityTrustHtml(this.domService.sanitizeHtml(r))}catch{return""}}setEmojiList(e){try{this.emojis={},Object.keys(e).forEach(i=>{let r=e[i];if(r.svg)this.emojis[i]=this.sanitizer.bypassSecurityTrustHtml(this.domService.sanitizeSvg(r.svg));else if(r.url){let a=`<img src="${r.url}" alt="${i}" />`;this.emojis[i]=this.sanitizer.bypassSecurityTrustHtml(this.domService.sanitizeHtml(a))}else r.emoji&&(this.emojis[i]=this.getEmojiFromIconEmoji(this.domService.sanitizeHtml(r.emoji)))})}catch(i){this.loggingService.catch("Error in EmojiService setEmojiList: ",i)}}};o.Icons={RAISED_HANDS:`<svg width="58" height="57" viewBox="0 0 58 57" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
196
196
|
<path d="M35.8477 11.6603L40.4962 5.23427" stroke="#B0BEC5" stroke-width="1.92685" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/>
|
|
197
197
|
<path d="M21.8298 11.617L17.4655 6.02428" stroke="#B0BEC5" stroke-width="1.92685" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/>
|
|
198
198
|
<path d="M28.7568 9.77682L28.7761 1" stroke="#B0BEC5" stroke-width="1.92685" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/>
|