@veltdev/sdk-staging 6.0.0-beta.3 → 6.0.0-beta.4
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/app/models/data/reaction-resolver.data.model.d.ts +1 -0
- package/{chunk-OPFSWVO4.js → chunk-2CSNE6K3.js} +1 -1
- package/{chunk-YTPDG6FY.js → chunk-3HVKHN3C.js} +1 -1
- package/{chunk-B53CSXPI.js → chunk-4HTRJDUT.js} +1 -1
- package/{chunk-5Y3GWVF6.js → chunk-4KHSKSMM.js} +1 -1
- package/{chunk-S6JEPTGO.js → chunk-4RKIO2W6.js} +1 -1
- package/{chunk-AHFE2P66.js → chunk-62IPFSNC.js} +1 -1
- package/{chunk-QMH32YWC.js → chunk-6YAEGDTT.js} +1 -1
- package/{chunk-3NQO7KT2.js → chunk-6YU4HPC3.js} +1 -1
- package/{chunk-JBQSOLQ4.js → chunk-A7KXFTE5.js} +1 -1
- package/{chunk-M3Z3OPKG.js → chunk-AUXK5IGY.js} +1 -1
- package/{chunk-PFQD3ZHE.js → chunk-BLOVLKDQ.js} +1 -1
- package/{chunk-DVSWAW3V.js → chunk-CAH7LK67.js} +1 -1
- package/{chunk-TO3QMX6L.js → chunk-DEKTLMP2.js} +1 -1
- package/{chunk-5WUV64V6.js → chunk-EJCDV3ZL.js} +1 -1
- package/{chunk-TMURKDBH.js → chunk-GG5L5Y4V.js} +1 -1
- package/{chunk-LHFXU553.js → chunk-GUCATQJB.js} +1 -1
- package/{chunk-LE6ADPBN.js → chunk-GY4HESRT.js} +1 -1
- package/{chunk-PRJU4HJ5.js → chunk-H4F2DT7C.js} +1 -1
- package/{chunk-DNCQDV54.js → chunk-HPCGJVBV.js} +1 -1
- package/{chunk-4ZCY365X.js → chunk-HRMFENXY.js} +7 -7
- package/{chunk-NRZ34IWA.js → chunk-I3QEZDJJ.js} +1 -1
- package/{chunk-K2RBYFUJ.js → chunk-JWZNY6MR.js} +1 -1
- package/{chunk-PLHC4BWM.js → chunk-M6OYNJUV.js} +1 -1
- package/{chunk-QJJZ7GBM.js → chunk-NM7DOIHZ.js} +1 -1
- package/{chunk-FGJMQQP7.js → chunk-NREV2I2E.js} +1 -1
- package/{chunk-4ICELJP6.js → chunk-NVSEAZ7V.js} +1 -1
- package/{chunk-X7A6MBGM.js → chunk-ONMQQFFH.js} +1 -1
- package/{chunk-MTS7WSOI.js → chunk-OSPUUVRC.js} +1 -1
- package/{chunk-D5GNGKKF.js → chunk-S6BGMPB5.js} +1 -1
- package/{chunk-S7XRWLIA.js → chunk-WEQZFWL6.js} +1 -1
- package/{chunk-TV5S4EJP.js → chunk-XQKUJSNO.js} +1 -1
- package/{chunk-3BBCVKQ5.js → chunk-ZOEYUSVF.js} +1 -1
- package/{chunk-SYNPZ2XP.js → chunk-ZOM7FOLY.js} +1 -1
- package/package.json +1 -1
- package/velt-activity-log.js +1 -1
- package/velt-area.js +1 -1
- package/velt-arrow.js +1 -1
- package/velt-comment.js +1 -1
- package/velt-crdt.js +1 -1
- package/velt-cursor.js +1 -1
- package/velt-huddle.js +1 -1
- package/velt-live-state-sync.js +1 -1
- package/velt-notification.js +1 -1
- package/velt-presence.js +1 -1
- package/velt-reaction.js +1 -1
- package/velt-recorder.js +1 -1
- package/velt-rewriter.js +1 -1
- package/velt-selection.js +1 -1
- package/velt-tag.js +1 -1
- package/velt-user-invite.js +1 -1
- package/velt-user-request.js +1 -1
- package/velt-video-player.js +1 -1
- package/velt-views.js +1 -1
- package/velt.js +2 -2
|
@@ -164,4 +164,4 @@ This typically indicates that your device does not have a healthy Internet conne
|
|
|
164
164
|
`+e.join(`
|
|
165
165
|
`)+`
|
|
166
166
|
)`}copy(e,r){let t=new n;return t.comparator=this.comparator,t.keyedMap=e,t.sortedSet=r,t}};var _y=class{constructor(){this.fa=new Dt(ie.comparator)}track(e){let r=e.doc.key,t=this.fa.get(r);t?e.type!==0&&t.type===3?this.fa=this.fa.insert(r,e):e.type===3&&t.type!==1?this.fa=this.fa.insert(r,{type:t.type,doc:e.doc}):e.type===2&&t.type===2?this.fa=this.fa.insert(r,{type:2,doc:e.doc}):e.type===2&&t.type===0?this.fa=this.fa.insert(r,{type:0,doc:e.doc}):e.type===1&&t.type===0?this.fa=this.fa.remove(r):e.type===1&&t.type===2?this.fa=this.fa.insert(r,{type:1,doc:t.doc}):e.type===0&&t.type===1?this.fa=this.fa.insert(r,{type:2,doc:e.doc}):ae(63341,{At:e,ga:t}):this.fa=this.fa.insert(r,e)}pa(){let e=[];return this.fa.inorderTraversal((r,t)=>{e.push(t)}),e}},Mh=class n{constructor(e,r,t,i,o,s,a,c,l){this.query=e,this.docs=r,this.oldDocs=t,this.docChanges=i,this.mutatedKeys=o,this.fromCache=s,this.syncStateChanged=a,this.excludesMetadataChanges=c,this.hasCachedResults=l}static fromInitialDocuments(e,r,t,i,o){let s=[];return r.forEach(a=>{s.push({type:0,doc:a})}),new n(e,r,Ey.emptySet(r),s,t,i,!0,!1,o)}get hasPendingWrites(){return!this.mutatedKeys.isEmpty()}isEqual(e){if(!(this.fromCache===e.fromCache&&this.hasCachedResults===e.hasCachedResults&&this.syncStateChanged===e.syncStateChanged&&this.mutatedKeys.isEqual(e.mutatedKeys)&&Fy(this.query,e.query)&&this.docs.isEqual(e.docs)&&this.oldDocs.isEqual(e.oldDocs)))return!1;let r=this.docChanges,t=e.docChanges;if(r.length!==t.length)return!1;for(let i=0;i<r.length;i++)if(r[i].type!==t[i].type||!r[i].doc.isEqual(t[i].doc))return!1;return!0}};var IL=class{constructor(){this.ya=void 0,this.wa=[]}Sa(){return this.wa.some(e=>e.ba())}},vL=class{constructor(){this.queries=lH(),this.onlineState="Unknown",this.Da=new Set}terminate(){(function(r,t){let i=de(r),o=i.queries;i.queries=lH(),o.forEach((s,a)=>{for(let c of a.wa)c.onError(t)})})(this,new Q(j.ABORTED,"Firestore shutting down"))}};function lH(){return new Ki(n=>nW(n),Fy)}function _M(n,e){return I(this,null,function*(){let r=de(n),t=3,i=e.query,o=r.queries.get(i);o?!o.Sa()&&e.ba()&&(t=2):(o=new IL,t=e.ba()?0:1);try{switch(t){case 0:o.ya=yield r.onListen(i,!0);break;case 1:o.ya=yield r.onListen(i,!1);break;case 2:yield r.onFirstRemoteStoreListen(i)}}catch(s){let a=EM(s,`Initialization of query '${sh(e.query)}' failed`);return void e.onError(a)}r.queries.set(i,o),o.wa.push(e),e.va(r.onlineState),o.ya&&e.Ca(o.ya)&&IM(r)})}function TM(n,e){return I(this,null,function*(){let r=de(n),t=e.query,i=3,o=r.queries.get(t);if(o){let s=o.wa.indexOf(e);s>=0&&(o.wa.splice(s,1),o.wa.length===0?i=e.ba()?0:1:!o.Sa()&&e.ba()&&(i=2))}switch(i){case 0:return r.queries.delete(t),r.onUnlisten(t,!0);case 1:return r.queries.delete(t),r.onUnlisten(t,!1);case 2:return r.onLastRemoteStoreUnlisten(t);default:return}})}function Coe(n,e){let r=de(n),t=!1;for(let i of e){let o=i.query,s=r.queries.get(o);if(s){for(let a of s.wa)a.Ca(i)&&(t=!0);s.ya=i}}t&&IM(r)}function Noe(n,e,r){let t=de(n),i=t.queries.get(e);if(i)for(let o of i.wa)o.onError(r);t.queries.delete(e)}function IM(n){n.Da.forEach(e=>{e.next()})}var yL,uH;(uH=yL||(yL={})).Fa="default",uH.Cache="cache";var hp=class{constructor(e,r,t){this.query=e,this.Ma=r,this.xa=!1,this.Oa=null,this.onlineState="Unknown",this.options=t||{}}Ca(e){if(!this.options.includeMetadataChanges){let t=[];for(let i of e.docChanges)i.type!==3&&t.push(i);e=new Mh(e.query,e.docs,e.oldDocs,t,e.mutatedKeys,e.fromCache,e.syncStateChanged,!0,e.hasCachedResults)}let r=!1;return this.xa?this.Na(e)&&(this.Ma.next(e),r=!0):this.Ba(e,this.onlineState)&&(this.La(e),r=!0),this.Oa=e,r}onError(e){this.Ma.error(e)}va(e){this.onlineState=e;let r=!1;return this.Oa&&!this.xa&&this.Ba(this.Oa,e)&&(this.La(this.Oa),r=!0),r}Ba(e,r){if(!e.fromCache||!this.ba())return!0;let t=r!=="Offline";return(!this.options.ka||!t)&&(!e.docs.isEmpty()||e.hasCachedResults||r==="Offline")}Na(e){if(e.docChanges.length>0)return!0;let r=this.Oa&&this.Oa.hasPendingWrites!==e.hasPendingWrites;return!(!e.syncStateChanged&&!r)&&this.options.includeMetadataChanges===!0}La(e){e=Mh.fromInitialDocuments(e.query,e.docs,e.mutatedKeys,e.fromCache,e.hasCachedResults),this.xa=!0,this.Ma.next(e)}ba(){return this.options.source!==yL.Cache}};var Ty=class{constructor(e){this.key=e}},Iy=class{constructor(e){this.key=e}},SL=class{constructor(e,r){this.query=e,this.Ha=r,this.Ya=null,this.hasCachedResults=!1,this.current=!1,this.Za=Ve(),this.mutatedKeys=Ve(),this.Xa=iW(e),this.eu=new Ey(this.Xa)}get tu(){return this.Ha}nu(e,r){let t=r?r.ru:new _y,i=r?r.eu:this.eu,o=r?r.mutatedKeys:this.mutatedKeys,s=i,a=!1,c=this.query.limitType==="F"&&i.size===this.query.limit?i.last():null,l=this.query.limitType==="L"&&i.size===this.query.limit?i.first():null;if(e.inorderTraversal((u,d)=>{let f=i.get(u),g=yp(this.query,d)?d:null,p=!!f&&this.mutatedKeys.has(f.key),_=!!g&&(g.hasLocalMutations||this.mutatedKeys.has(g.key)&&g.hasCommittedMutations),T=!1;f&&g?f.data.isEqual(g.data)?p!==_&&(t.track({type:3,doc:g}),T=!0):this.iu(f,g)||(t.track({type:2,doc:g}),T=!0,(c&&this.Xa(g,c)>0||l&&this.Xa(g,l)<0)&&(a=!0)):!f&&g?(t.track({type:0,doc:g}),T=!0):f&&!g&&(t.track({type:1,doc:f}),T=!0,(c||l)&&(a=!0)),T&&(g?(s=s.add(g),o=_?o.add(u):o.delete(u)):(s=s.delete(u),o=o.delete(u)))}),this.query.limit!==null)for(;s.size>this.query.limit;){let u=this.query.limitType==="F"?s.last():s.first();s=s.delete(u.key),o=o.delete(u.key),t.track({type:1,doc:u})}return{eu:s,ru:t,Ds:a,mutatedKeys:o}}iu(e,r){return e.hasLocalMutations&&r.hasCommittedMutations&&!r.hasLocalMutations}applyChanges(e,r,t,i){let o=this.eu;this.eu=e.eu,this.mutatedKeys=e.mutatedKeys;let s=e.ru.pa();s.sort((u,d)=>(function(g,p){let _=T=>{switch(T){case 0:return 1;case 2:case 3:return 2;case 1:return 0;default:return ae(20277,{At:T})}};return _(g)-_(p)})(u.type,d.type)||this.Xa(u.doc,d.doc)),this.su(t),i=i!=null&&i;let a=r&&!i?this.ou():[],c=this.Za.size===0&&this.current&&!i?1:0,l=c!==this.Ya;return this.Ya=c,s.length!==0||l?{snapshot:new Mh(this.query,e.eu,o,s,e.mutatedKeys,c===0,l,!1,!!t&&t.resumeToken.approximateByteSize()>0),_u:a}:{_u:a}}va(e){return this.current&&e==="Offline"?(this.current=!1,this.applyChanges({eu:this.eu,ru:new _y,mutatedKeys:this.mutatedKeys,Ds:!1},!1)):{_u:[]}}au(e){return!this.Ha.has(e)&&!!this.eu.has(e)&&!this.eu.get(e).hasLocalMutations}su(e){e&&(e.addedDocuments.forEach(r=>this.Ha=this.Ha.add(r)),e.modifiedDocuments.forEach(r=>{}),e.removedDocuments.forEach(r=>this.Ha=this.Ha.delete(r)),this.current=e.current)}ou(){if(!this.current)return[];let e=this.Za;this.Za=Ve(),this.eu.forEach(t=>{this.au(t.key)&&(this.Za=this.Za.add(t.key))});let r=[];return e.forEach(t=>{this.Za.has(t)||r.push(new Iy(t))}),this.Za.forEach(t=>{e.has(t)||r.push(new Ty(t))}),r}uu(e){this.Ha=e.qs,this.Za=Ve();let r=this.nu(e.documents);return this.applyChanges(r,!0)}cu(){return Mh.fromInitialDocuments(this.query,this.eu,this.mutatedKeys,this.Ya===0,this.hasCachedResults)}},Gh="SyncEngine",AL=class{constructor(e,r,t){this.query=e,this.targetId=r,this.view=t}},DL=class{constructor(e){this.key=e,this.lu=!1}},RL=class{constructor(e,r,t,i,o,s){this.localStore=e,this.remoteStore=r,this.eventManager=t,this.sharedClientState=i,this.currentUser=o,this.maxConcurrentLimboResolutions=s,this.hu={},this.Pu=new Ki(a=>nW(a),Fy),this.Tu=new Map,this.Iu=new Set,this.du=new Dt(ie.comparator),this.Eu=new Map,this.Au=new cp,this.Ru={},this.Vu=new Map,this.mu=wh.ur(),this.onlineState="Unknown",this.fu=void 0}get isPrimaryClient(){return this.fu===!0}};function Ooe(n,e,r=!0){return I(this,null,function*(){let t=By(n),i,o=t.Pu.get(e);return o?(t.sharedClientState.addLocalQueryTarget(o.targetId),i=o.view.cu()):i=yield ez(t,e,r,!0),i})}function woe(n,e){return I(this,null,function*(){let r=By(n);yield ez(r,e,!0,!1)})}function ez(n,e,r,t){return I(this,null,function*(){let i=yield uy(n.localStore,Xr(e)),o=i.targetId,s=n.sharedClientState.addLocalQueryTarget(o,r),a;return t&&(a=yield vM(n,e,o,s==="current",i.resumeToken)),n.isPrimaryClient&&r&&Vy(n.remoteStore,i),a})}function vM(n,e,r,t,i){return I(this,null,function*(){n.gu=(d,f,g)=>(function(_,T,D,b){return I(this,null,function*(){let G=T.view.nu(D);G.Ds&&(G=yield oL(_.localStore,T.query,!1).then(({documents:S})=>T.view.nu(S,G)));let M=b&&b.targetChanges.get(T.targetId),U=b&&b.targetMismatches.get(T.targetId)!=null,k=T.view.applyChanges(G,_.isPrimaryClient,M,U);return CL(_,T.targetId,k._u),k.snapshot})})(n,d,f,g);let o=yield oL(n.localStore,e,!0),s=new SL(e,o.qs),a=s.nu(o.documents),c=ip.createSynthesizedTargetChangeForCurrentChange(r,t&&n.onlineState!=="Offline",i),l=s.applyChanges(a,n.isPrimaryClient,c);CL(n,r,l._u);let u=new AL(e,r,s);return n.Pu.set(e,u),n.Tu.has(r)?n.Tu.get(r).push(e):n.Tu.set(r,[e]),l.snapshot})}function boe(n,e,r){return I(this,null,function*(){let t=de(n),i=t.Pu.get(e),o=t.Tu.get(i.targetId);if(o.length>1)return t.Tu.set(i.targetId,o.filter(s=>!Fy(s,e))),void t.Pu.delete(e);t.isPrimaryClient?(t.sharedClientState.removeLocalQueryTarget(i.targetId),t.sharedClientState.isActiveQueryTarget(i.targetId)||(yield bh(t.localStore,i.targetId,!1).then(()=>{t.sharedClientState.clearQueryState(i.targetId),r&&Lh(t.remoteStore,i.targetId),Ph(t,i.targetId)}).catch(Qa))):(Ph(t,i.targetId),yield bh(t.localStore,i.targetId,!0))})}function Loe(n,e){return I(this,null,function*(){let r=de(n),t=r.Pu.get(e),i=r.Tu.get(t.targetId);r.isPrimaryClient&&i.length===1&&(r.sharedClientState.removeLocalQueryTarget(t.targetId),Lh(r.remoteStore,t.targetId))})}function Moe(n,e,r){return I(this,null,function*(){let t=DM(n);try{let i=yield(function(s,a){let c=de(s),l=Pt.now(),u=a.reduce((g,p)=>g.add(p.key),Ve()),d,f;return c.persistence.runTransaction("Locally write mutations","readwrite",g=>{let p=Qr(),_=Ve();return c.Os.getEntries(g,u).next(T=>{p=T,p.forEach((D,b)=>{b.isValidDocument()||(_=_.add(D))})}).next(()=>c.localDocuments.getOverlayedDocuments(g,p)).next(T=>{d=T;let D=[];for(let b of a){let G=Wie(b,d.get(b.key).overlayedDocument);G!=null&&D.push(new Yi(b.key,G,KH(G.value.mapValue),Gn.exists(!0)))}return c.mutationQueue.addMutationBatch(g,l,D,a)}).next(T=>{f=T;let D=T.applyToLocalDocumentSet(d,_);return c.documentOverlayCache.saveOverlays(g,T.batchId,D)})}).then(()=>({batchId:f.batchId,changes:sW(d)}))})(t.localStore,e);t.sharedClientState.addPendingMutation(i.batchId),(function(s,a,c){let l=s.Ru[s.currentUser.toKey()];l||(l=new Dt(Re)),l=l.insert(a,c),s.Ru[s.currentUser.toKey()]=l})(t,i.batchId,r),yield Za(t,i.changes),yield Vh(t.remoteStore)}catch(i){let o=EM(i,"Failed to persist write");r.reject(o)}})}function tz(n,e){return I(this,null,function*(){let r=de(n);try{let t=yield foe(r.localStore,e);e.targetChanges.forEach((i,o)=>{let s=r.Eu.get(o);s&&(he(i.addedDocuments.size+i.modifiedDocuments.size+i.removedDocuments.size<=1,22616),i.addedDocuments.size>0?s.lu=!0:i.modifiedDocuments.size>0?he(s.lu,14607):i.removedDocuments.size>0&&(he(s.lu,42227),s.lu=!1))}),yield Za(r,t,e)}catch(t){yield Qa(t)}})}function dH(n,e,r){let t=de(n);if(t.isPrimaryClient&&r===0||!t.isPrimaryClient&&r===1){let i=[];t.Pu.forEach((o,s)=>{let a=s.view.va(e);a.snapshot&&i.push(a.snapshot)}),(function(s,a){let c=de(s);c.onlineState=a;let l=!1;c.queries.forEach((u,d)=>{for(let f of d.wa)f.va(a)&&(l=!0)}),l&&IM(c)})(t.eventManager,e),i.length&&t.hu.J_(i),t.onlineState=e,t.isPrimaryClient&&t.sharedClientState.setOnlineState(e)}}function Poe(n,e,r){return I(this,null,function*(){let t=de(n);t.sharedClientState.updateQueryState(e,"rejected",r);let i=t.Eu.get(e),o=i&&i.key;if(o){let s=new Dt(ie.comparator);s=s.insert(o,In.newNoDocument(o,me.min()));let a=Ve().add(o),c=new rp(me.min(),new Map,new Dt(Re),s,a);yield tz(t,c),t.du=t.du.remove(o),t.Eu.delete(e),AM(t)}else yield bh(t.localStore,e,!1).then(()=>Ph(t,e,r)).catch(Qa)})}function xoe(n,e){return I(this,null,function*(){let r=de(n),t=e.batch.batchId;try{let i=yield hoe(r.localStore,e);SM(r,t,null),yM(r,t),r.sharedClientState.updateMutationState(t,"acknowledged"),yield Za(r,i)}catch(i){yield Qa(i)}})}function Foe(n,e,r){return I(this,null,function*(){let t=de(n);try{let i=yield(function(s,a){let c=de(s);return c.persistence.runTransaction("Reject batch","readwrite-primary",l=>{let u;return c.mutationQueue.lookupMutationBatch(l,a).next(d=>(he(d!==null,37113),u=d.keys(),c.mutationQueue.removeMutationBatch(l,d))).next(()=>c.mutationQueue.performConsistencyCheck(l)).next(()=>c.documentOverlayCache.removeOverlaysForBatchId(l,u,a)).next(()=>c.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(l,u)).next(()=>c.localDocuments.getDocuments(l,u))})})(t.localStore,e);SM(t,e,r),yM(t,e),t.sharedClientState.updateMutationState(e,"rejected",r),yield Za(t,i)}catch(i){yield Qa(i)}})}function yM(n,e){(n.Vu.get(e)||[]).forEach(r=>{r.resolve()}),n.Vu.delete(e)}function SM(n,e,r){let t=de(n),i=t.Ru[t.currentUser.toKey()];if(i){let o=i.get(e);o&&(r?o.reject(r):o.resolve(),i=i.remove(e)),t.Ru[t.currentUser.toKey()]=i}}function Ph(n,e,r=null){n.sharedClientState.removeLocalQueryTarget(e);for(let t of n.Tu.get(e))n.Pu.delete(t),r&&n.hu.pu(t,r);n.Tu.delete(e),n.isPrimaryClient&&n.Au.zr(e).forEach(t=>{n.Au.containsKey(t)||nz(n,t)})}function nz(n,e){n.Iu.delete(e.path.canonicalString());let r=n.du.get(e);r!==null&&(Lh(n.remoteStore,r),n.du=n.du.remove(e),n.Eu.delete(r),AM(n))}function CL(n,e,r){for(let t of r)t instanceof Ty?(n.Au.addReference(t.key,e),koe(n,t)):t instanceof Iy?(X(Gh,"Document no longer in limbo: "+t.key),n.Au.removeReference(t.key,e),n.Au.containsKey(t.key)||nz(n,t.key)):ae(19791,{yu:t})}function koe(n,e){let r=e.key,t=r.path.canonicalString();n.du.get(r)||n.Iu.has(t)||(X(Gh,"New document in limbo: "+r),n.Iu.add(t),AM(n))}function AM(n){for(;n.Iu.size>0&&n.du.size<n.maxConcurrentLimboResolutions;){let e=n.Iu.values().next().value;n.Iu.delete(e);let r=new ie(We.fromString(e)),t=n.mu.next();n.Eu.set(t,new DL(r)),n.du=n.du.insert(r,t),Vy(n.remoteStore,new Oh(Xr(vp(r.path)),t,"TargetPurposeLimboResolution",Kr.ue))}}function Za(n,e,r){return I(this,null,function*(){let t=de(n),i=[],o=[],s=[];t.Pu.isEmpty()||(t.Pu.forEach((a,c)=>{s.push(t.gu(c,e,r).then(l=>{var u;if((l||r)&&t.isPrimaryClient){let d=l?!l.fromCache:(u=r?.targetChanges.get(c.targetId))===null||u===void 0?void 0:u.current;t.sharedClientState.updateQueryState(c.targetId,d?"current":"not-current")}if(l){i.push(l);let d=nL.Es(c.targetId,l);o.push(d)}}))}),yield Promise.all(s),t.hu.J_(i),yield(function(c,l){return I(this,null,function*(){let u=de(c);try{yield u.persistence.runTransaction("notifyLocalViewChanges","readwrite",d=>B.forEach(l,f=>B.forEach(f.Is,g=>u.persistence.referenceDelegate.addReference(d,f.targetId,g)).next(()=>B.forEach(f.ds,g=>u.persistence.referenceDelegate.removeReference(d,f.targetId,g)))))}catch(d){if(!Xa(d))throw d;X(fM,"Failed to update sequence numbers: "+d)}for(let d of l){let f=d.targetId;if(!d.fromCache){let g=u.Fs.get(f),p=g.snapshotVersion,_=g.withLastLimboFreeSnapshotVersion(p);u.Fs=u.Fs.insert(f,_)}}})})(t.localStore,o))})}function Uoe(n,e){return I(this,null,function*(){let r=de(n);if(!r.currentUser.isEqual(e)){X(Gh,"User change. New user:",e.toKey());let t=yield BW(r.localStore,e);r.currentUser=e,(function(o,s){o.Vu.forEach(a=>{a.forEach(c=>{c.reject(new Q(j.CANCELLED,s))})}),o.Vu.clear()})(r,"'waitForPendingWrites' promise is rejected due to a user change."),r.sharedClientState.handleUserChange(e,t.removedBatchIds,t.addedBatchIds),yield Za(r,t.Bs)}})}function Voe(n,e){let r=de(n),t=r.Eu.get(e);if(t&&t.lu)return Ve().add(t.key);{let i=Ve(),o=r.Tu.get(e);if(!o)return i;for(let s of o){let a=r.Pu.get(s);i=i.unionWith(a.view.tu)}return i}}function Boe(n,e){return I(this,null,function*(){let r=de(n),t=yield oL(r.localStore,e.query,!0),i=e.view.uu(t);return r.isPrimaryClient&&CL(r,e.targetId,i._u),i})}function Goe(n,e){return I(this,null,function*(){let r=de(n);return jW(r.localStore,e).then(t=>Za(r,t))})}function $oe(n,e,r,t){return I(this,null,function*(){let i=de(n),o=yield(function(a,c){let l=de(a),u=de(l.mutationQueue);return l.persistence.runTransaction("Lookup mutation documents","readonly",d=>u.Xn(d,c).next(f=>f?l.localDocuments.getDocuments(d,f):B.resolve(null)))})(i.localStore,e);o!==null?(r==="pending"?yield Vh(i.remoteStore):r==="acknowledged"||r==="rejected"?(SM(i,e,t||null),yM(i,e),(function(a,c){de(de(a).mutationQueue).rr(c)})(i.localStore,e)):ae(6720,"Unknown batchState",{wu:r}),yield Za(i,o)):X(Gh,"Cannot apply mutation batch with id: "+e)})}function joe(n,e){return I(this,null,function*(){let r=de(n);if(By(r),DM(r),e===!0&&r.fu!==!0){let t=r.sharedClientState.getAllActiveQueryTargets(),i=yield hH(r,t.toArray());r.fu=!0,yield _L(r.remoteStore,!0);for(let o of i)Vy(r.remoteStore,o)}else if(e===!1&&r.fu!==!1){let t=[],i=Promise.resolve();r.Tu.forEach((o,s)=>{r.sharedClientState.isLocalQueryTarget(s)?t.push(s):i=i.then(()=>(Ph(r,s),bh(r.localStore,s,!0))),Lh(r.remoteStore,s)}),yield i,yield hH(r,t),(function(s){let a=de(s);a.Eu.forEach((c,l)=>{Lh(a.remoteStore,l)}),a.Au.jr(),a.Eu=new Map,a.du=new Dt(ie.comparator)})(r),r.fu=!1,yield _L(r.remoteStore,!1)}})}function hH(n,e,r){return I(this,null,function*(){let t=de(n),i=[],o=[];for(let s of e){let a,c=t.Tu.get(s);if(c&&c.length!==0){a=yield uy(t.localStore,Xr(c[0]));for(let l of c){let u=t.Pu.get(l),d=yield Boe(t,u);d.snapshot&&o.push(d.snapshot)}}else{let l=yield $W(t.localStore,s);a=yield uy(t.localStore,l),yield vM(t,rz(l),s,!1,a.resumeToken)}i.push(a)}return t.hu.J_(o),i})}function rz(n){return eW(n.path,n.collectionGroup,n.orderBy,n.filters,n.limit,"F",n.startAt,n.endAt)}function Hoe(n){return(function(r){return de(de(r).persistence).Ps()})(de(n).localStore)}function Woe(n,e,r,t){return I(this,null,function*(){let i=de(n);if(i.fu)return void X(Gh,"Ignoring unexpected query state notification.");let o=i.Tu.get(e);if(o&&o.length>0)switch(r){case"current":case"not-current":{let s=yield jW(i.localStore,rW(o[0])),a=rp.createSynthesizedRemoteEventForCurrentChange(e,r==="current",un.EMPTY_BYTE_STRING);yield Za(i,s,a);break}case"rejected":yield bh(i.localStore,e,!0),Ph(i,e,t);break;default:ae(64155,r)}})}function zoe(n,e,r){return I(this,null,function*(){let t=By(n);if(t.fu){for(let i of e){if(t.Tu.has(i)&&t.sharedClientState.isActiveQueryTarget(i)){X(Gh,"Adding an already active target "+i);continue}let o=yield $W(t.localStore,i),s=yield uy(t.localStore,o);yield vM(t,rz(o),s.targetId,!1,s.resumeToken),Vy(t.remoteStore,s)}for(let i of r)t.Tu.has(i)&&(yield bh(t.localStore,i,!1).then(()=>{Lh(t.remoteStore,i),Ph(t,i)}).catch(Qa))}})}function By(n){let e=de(n);return e.remoteStore.remoteSyncer.applyRemoteEvent=tz.bind(null,e),e.remoteStore.remoteSyncer.getRemoteKeysForTarget=Voe.bind(null,e),e.remoteStore.remoteSyncer.rejectListen=Poe.bind(null,e),e.hu.J_=Coe.bind(null,e.eventManager),e.hu.pu=Noe.bind(null,e.eventManager),e}function DM(n){let e=de(n);return e.remoteStore.remoteSyncer.applySuccessfulWrite=xoe.bind(null,e),e.remoteStore.remoteSyncer.rejectFailedWrite=Foe.bind(null,e),e}var RM=(()=>{class n{constructor(){this.kind="memory",this.synchronizeTabs=!1}initialize(r){return I(this,null,function*(){this.serializer=ky(r.databaseInfo.databaseId),this.sharedClientState=this.bu(r),this.persistence=this.Du(r),yield this.persistence.start(),this.localStore=this.vu(r),this.gcScheduler=this.Cu(r,this.localStore),this.indexBackfillerScheduler=this.Fu(r,this.localStore)})}Cu(r,t){return null}Fu(r,t){return null}vu(r){return VW(this.persistence,new ly,r.initialUser,this.serializer)}Du(r){return new lp(ay.Vi,this.serializer)}bu(r){return new fy}terminate(){return I(this,null,function*(){var r,t;(r=this.gcScheduler)===null||r===void 0||r.stop(),(t=this.indexBackfillerScheduler)===null||t===void 0||t.stop(),this.sharedClientState.shutdown(),yield this.persistence.shutdown()})}}return n.provider={build:()=>new n},n})(),NL=class extends RM{constructor(e){super(),this.cacheSizeBytes=e}Cu(e,r){he(this.persistence.referenceDelegate instanceof cy,46915);let t=this.persistence.referenceDelegate.garbageCollector;return new iy(t,e.asyncQueue,r)}Du(e){let r=this.cacheSizeBytes!==void 0?Nr.withCacheSize(this.cacheSizeBytes):Nr.DEFAULT;return new lp(t=>cy.Vi(t,r),this.serializer)}},vy=class n extends RM{constructor(e,r,t){super(),this.Mu=e,this.cacheSizeBytes=r,this.forceOwnership=t,this.kind="persistent",this.synchronizeTabs=!1}initialize(e){return I(this,null,function*(){yield pc(n.prototype,this,"initialize").call(this,e),yield this.Mu.initialize(this,e),yield DM(this.Mu.syncEngine),yield Vh(this.Mu.remoteStore),yield this.persistence.ji(()=>(this.gcScheduler&&!this.gcScheduler.started&&this.gcScheduler.start(),this.indexBackfillerScheduler&&!this.indexBackfillerScheduler.started&&this.indexBackfillerScheduler.start(),Promise.resolve()))})}vu(e){return VW(this.persistence,new ly,e.initialUser,this.serializer)}Cu(e,r){let t=this.persistence.referenceDelegate.garbageCollector;return new iy(t,e.asyncQueue,r)}Fu(e,r){let t=new Zw(r,this.persistence);return new Jw(e.asyncQueue,t)}Du(e){let r=UW(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey),t=this.cacheSizeBytes!==void 0?Nr.withCacheSize(this.cacheSizeBytes):Nr.DEFAULT;return new tL(this.synchronizeTabs,r,e.clientId,t,e.asyncQueue,KW(),Lv(),this.serializer,this.sharedClientState,!!this.forceOwnership)}bu(e){return new fy}},OL=class n extends vy{constructor(e,r){super(e,r,!1),this.Mu=e,this.cacheSizeBytes=r,this.synchronizeTabs=!0}initialize(e){return I(this,null,function*(){yield pc(n.prototype,this,"initialize").call(this,e);let r=this.Mu.syncEngine;this.sharedClientState instanceof $m&&(this.sharedClientState.syncEngine={Do:$oe.bind(null,r),vo:Woe.bind(null,r),Co:zoe.bind(null,r),Ps:Hoe.bind(null,r),bo:Goe.bind(null,r)},yield this.sharedClientState.start()),yield this.persistence.ji(t=>I(this,null,function*(){yield joe(this.Mu.syncEngine,t),this.gcScheduler&&(t&&!this.gcScheduler.started?this.gcScheduler.start():t||this.gcScheduler.stop()),this.indexBackfillerScheduler&&(t&&!this.indexBackfillerScheduler.started?this.indexBackfillerScheduler.start():t||this.indexBackfillerScheduler.stop())}))})}bu(e){let r=KW();if(!$m.C(r))throw new Q(j.UNIMPLEMENTED,"IndexedDB persistence is only available on platforms that support LocalStorage.");let t=UW(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey);return new $m(r,e.asyncQueue,t,e.clientId,e.initialUser)}},CM=(()=>{class n{initialize(r,t){return I(this,null,function*(){this.localStore||(this.localStore=r.localStore,this.sharedClientState=r.sharedClientState,this.datastore=this.createDatastore(t),this.remoteStore=this.createRemoteStore(t),this.eventManager=this.createEventManager(t),this.syncEngine=this.createSyncEngine(t,!r.synchronizeTabs),this.sharedClientState.onlineStateHandler=i=>dH(this.syncEngine,i,1),this.remoteStore.remoteSyncer.handleCredentialChange=Uoe.bind(null,this.syncEngine),yield _L(this.remoteStore,this.syncEngine.isPrimaryClient))})}createEventManager(r){return(function(){return new vL})()}createDatastore(r){let t=ky(r.databaseInfo.databaseId),i=(function(s){return new dL(s)})(r.databaseInfo);return(function(s,a,c,l){return new mL(s,a,c,l)})(r.authCredentials,r.appCheckCredentials,i,t)}createRemoteStore(r){return(function(i,o,s,a,c){return new EL(i,o,s,a,c)})(this.localStore,this.datastore,r.asyncQueue,t=>dH(this.syncEngine,t,0),(function(){return gy.C()?new gy:new aL})())}createSyncEngine(r,t){return(function(o,s,a,c,l,u,d){let f=new RL(o,s,a,c,l,u);return d&&(f.fu=!0),f})(this.localStore,this.remoteStore,this.eventManager,this.sharedClientState,r.initialUser,r.maxConcurrentLimboResolutions,t)}terminate(){return I(this,null,function*(){var r,t;yield(function(o){return I(this,null,function*(){let s=de(o);X(Jl,"RemoteStore shutting down."),s.Ia.add(5),yield Sp(s),s.Ea.shutdown(),s.Aa.set("Unknown")})})(this.remoteStore),(r=this.datastore)===null||r===void 0||r.terminate(),(t=this.eventManager)===null||t===void 0||t.terminate()})}}return n.provider={build:()=>new n},n})();var fp=class{constructor(e){this.observer=e,this.muted=!1}next(e){this.muted||this.observer.next&&this.xu(this.observer.next,e)}error(e){this.muted||(this.observer.error?this.xu(this.observer.error,e):Xt("Uncaught Error in snapshot listener:",e.toString()))}Ou(){this.muted=!0}xu(e,r){setTimeout(()=>{this.muted||e(r)},0)}};var wL=class{constructor(e){this.datastore=e,this.readVersions=new Map,this.mutations=[],this.committed=!1,this.lastTransactionError=null,this.writtenDocs=new Set}lookup(e){return I(this,null,function*(){if(this.ensureCommitNotCalled(),this.mutations.length>0)throw this.lastTransactionError=new Q(j.INVALID_ARGUMENT,"Firestore transactions require all reads to be executed before all writes."),this.lastTransactionError;let r=yield(function(i,o){return I(this,null,function*(){let s=de(i),a={documents:o.map(d=>op(s.serializer,d))},c=yield s.Jo("BatchGetDocuments",s.serializer.databaseId,We.emptyPath(),a,o.length),l=new Map;c.forEach(d=>{let f=Jie(s.serializer,d);l.set(f.key.toString(),f)});let u=[];return o.forEach(d=>{let f=l.get(d.toString());he(!!f,55234,{key:d}),u.push(f)}),u})})(this.datastore,e);return r.forEach(t=>this.recordVersion(t)),r})}set(e,r){this.write(r.toMutation(e,this.precondition(e))),this.writtenDocs.add(e.toString())}update(e,r){try{this.write(r.toMutation(e,this.preconditionForUpdate(e)))}catch(t){this.lastTransactionError=t}this.writtenDocs.add(e.toString())}delete(e){this.write(new Yl(e,this.precondition(e))),this.writtenDocs.add(e.toString())}commit(){return I(this,null,function*(){if(this.ensureCommitNotCalled(),this.lastTransactionError)throw this.lastTransactionError;let e=this.readVersions;this.mutations.forEach(r=>{e.delete(r.key.toString())}),e.forEach((r,t)=>{let i=ie.fromPath(t);this.mutations.push(new ep(i,this.precondition(i)))}),yield(function(t,i){return I(this,null,function*(){let o=de(t),s={writes:i.map(a=>sp(o.serializer,a))};yield o.Wo("Commit",o.serializer.databaseId,We.emptyPath(),s)})})(this.datastore,this.mutations),this.committed=!0})}recordVersion(e){let r;if(e.isFoundDocument())r=e.version;else{if(!e.isNoDocument())throw ae(50498,{Wu:e.constructor.name});r=me.min()}let t=this.readVersions.get(e.key.toString());if(t){if(!r.isEqual(t))throw new Q(j.ABORTED,"Document version changed between two reads.")}else this.readVersions.set(e.key.toString(),r)}precondition(e){let r=this.readVersions.get(e.toString());return!this.writtenDocs.has(e.toString())&&r?r.isEqual(me.min())?Gn.exists(!1):Gn.updateTime(r):Gn.none()}preconditionForUpdate(e){let r=this.readVersions.get(e.toString());if(!this.writtenDocs.has(e.toString())&&r){if(r.isEqual(me.min()))throw new Q(j.INVALID_ARGUMENT,"Can't update a document that doesn't exist.");return Gn.updateTime(r)}return Gn.exists(!0)}write(e){this.ensureCommitNotCalled(),this.mutations.push(e)}ensureCommitNotCalled(){}};var bL=class{constructor(e,r,t,i,o){this.asyncQueue=e,this.datastore=r,this.options=t,this.updateFunction=i,this.deferred=o,this.Gu=t.maxAttempts,this.F_=new dp(this.asyncQueue,"transaction_retry")}zu(){this.Gu-=1,this.ju()}ju(){this.F_.g_(()=>I(this,null,function*(){let e=new wL(this.datastore),r=this.Ju(e);r&&r.then(t=>{this.asyncQueue.enqueueAndForget(()=>e.commit().then(()=>{this.deferred.resolve(t)}).catch(i=>{this.Hu(i)}))}).catch(t=>{this.Hu(t)})}))}Ju(e){try{let r=this.updateFunction(e);return!_p(r)&&r.catch&&r.then?r:(this.deferred.reject(Error("Transaction callback must return a Promise")),null)}catch(r){return this.deferred.reject(r),null}}Hu(e){this.Gu>0&&this.Yu(e)?(this.Gu-=1,this.asyncQueue.enqueueAndForget(()=>(this.ju(),Promise.resolve()))):this.deferred.reject(e)}Yu(e){if(e.name==="FirebaseError"){let r=e.code;return r==="aborted"||r==="failed-precondition"||r==="already-exists"||!mW(r)}return!1}};var Ya="FirestoreClient",LL=class{constructor(e,r,t,i,o){this.authCredentials=e,this.appCheckCredentials=r,this.asyncQueue=t,this.databaseInfo=i,this.user=cn.UNAUTHENTICATED,this.clientId=jm.newId(),this.authCredentialListener=()=>Promise.resolve(),this.appCheckCredentialListener=()=>Promise.resolve(),this._uninitializedComponentsProvider=o,this.authCredentials.start(t,s=>I(this,null,function*(){X(Ya,"Received user=",s.uid),yield this.authCredentialListener(s),this.user=s})),this.appCheckCredentials.start(t,s=>(X(Ya,"Received new app check token=",s),this.appCheckCredentialListener(s,this.user)))}get configuration(){return{asyncQueue:this.asyncQueue,databaseInfo:this.databaseInfo,clientId:this.clientId,authCredentials:this.authCredentials,appCheckCredentials:this.appCheckCredentials,initialUser:this.user,maxConcurrentLimboResolutions:100}}setCredentialChangeListener(e){this.authCredentialListener=e}setAppCheckTokenChangeListener(e){this.appCheckCredentialListener=e}terminate(){this.asyncQueue.enterRestrictedMode();let e=new Or;return this.asyncQueue.enqueueAndForgetEvenWhileRestricted(()=>I(this,null,function*(){try{this._onlineComponents&&(yield this._onlineComponents.terminate()),this._offlineComponents&&(yield this._offlineComponents.terminate()),this.authCredentials.shutdown(),this.appCheckCredentials.shutdown(),e.resolve()}catch(r){let t=EM(r,"Failed to shutdown persistence");e.reject(t)}})),e.promise}};function Gw(n,e){return I(this,null,function*(){n.asyncQueue.verifyOperationInProgress(),X(Ya,"Initializing OfflineComponentProvider");let r=n.configuration;yield e.initialize(r);let t=r.initialUser;n.setCredentialChangeListener(i=>I(null,null,function*(){t.isEqual(i)||(yield BW(e.localStore,i),t=i)})),e.persistence.setDatabaseDeletedListener(()=>{ws("Terminating Firestore due to IndexedDb database deletion"),n.terminate().then(()=>{X("Terminating Firestore due to IndexedDb database deletion completed successfully")}).catch(i=>{ws("Terminating Firestore due to IndexedDb database deletion failed",i)})}),n._offlineComponents=e})}function fH(n,e){return I(this,null,function*(){n.asyncQueue.verifyOperationInProgress();let r=yield qoe(n);X(Ya,"Initializing OnlineComponentProvider"),yield e.initialize(r,n.configuration),n.setCredentialChangeListener(t=>cH(e.remoteStore,t)),n.setAppCheckTokenChangeListener((t,i)=>cH(e.remoteStore,i)),n._onlineComponents=e})}function qoe(n){return I(this,null,function*(){if(!n._offlineComponents)if(n._uninitializedComponentsProvider){X(Ya,"Using user provided OfflineComponentProvider");try{yield Gw(n,n._uninitializedComponentsProvider._offline)}catch(e){let r=e;if(!(function(i){return i.name==="FirebaseError"?i.code===j.FAILED_PRECONDITION||i.code===j.UNIMPLEMENTED:!(typeof DOMException<"u"&&i instanceof DOMException)||i.code===22||i.code===20||i.code===11})(r))throw r;ws("Error using user provided cache. Falling back to memory cache: "+r),yield Gw(n,new RM)}}else X(Ya,"Using default OfflineComponentProvider"),yield Gw(n,new NL(void 0));return n._offlineComponents})}function NM(n){return I(this,null,function*(){return n._onlineComponents||(n._uninitializedComponentsProvider?(X(Ya,"Using user provided OnlineComponentProvider"),yield fH(n,n._uninitializedComponentsProvider._online)):(X(Ya,"Using default OnlineComponentProvider"),yield fH(n,new CM))),n._onlineComponents})}function Koe(n){return NM(n).then(e=>e.syncEngine)}function iz(n){return NM(n).then(e=>e.datastore)}function yy(n){return I(this,null,function*(){let e=yield NM(n),r=e.eventManager;return r.onListen=Ooe.bind(null,e.syncEngine),r.onUnlisten=boe.bind(null,e.syncEngine),r.onFirstRemoteStoreListen=woe.bind(null,e.syncEngine),r.onLastRemoteStoreUnlisten=Loe.bind(null,e.syncEngine),r})}function Yoe(n,e,r={}){let t=new Or;return n.asyncQueue.enqueueAndForget(()=>I(null,null,function*(){return(function(o,s,a,c,l){let u=new fp({next:f=>{u.Ou(),s.enqueueAndForget(()=>TM(o,d));let g=f.docs.has(a);!g&&f.fromCache?l.reject(new Q(j.UNAVAILABLE,"Failed to get document because the client is offline.")):g&&f.fromCache&&c&&c.source==="server"?l.reject(new Q(j.UNAVAILABLE,'Failed to get document from server. (However, this document does exist in the local cache. Run again without setting source to "server" to retrieve the cached document.)')):l.resolve(f)},error:f=>l.reject(f)}),d=new hp(vp(a.path),u,{includeMetadataChanges:!0,ka:!0});return _M(o,d)})(yield yy(n),n.asyncQueue,e,r,t)})),t.promise}function Qoe(n,e,r={}){let t=new Or;return n.asyncQueue.enqueueAndForget(()=>I(null,null,function*(){return(function(o,s,a,c,l){let u=new fp({next:f=>{u.Ou(),s.enqueueAndForget(()=>TM(o,d)),f.fromCache&&c.source==="server"?l.reject(new Q(j.UNAVAILABLE,'Failed to get documents from server. (However, these documents may exist in the local cache. Run again without setting source to "server" to retrieve the cached documents.)')):l.resolve(f)},error:f=>l.reject(f)}),d=new hp(a,u,{includeMetadataChanges:!0,ka:!0});return _M(o,d)})(yield yy(n),n.asyncQueue,e,r,t)})),t.promise}function Xoe(n,e,r){let t=new Or;return n.asyncQueue.enqueueAndForget(()=>I(null,null,function*(){try{let i=yield iz(n);t.resolve((function(s,a,c){return I(this,null,function*(){var l;let u=de(s),{request:d,ft:f,parent:g}=toe(u.serializer,Pie(a),c);u.connection.Qo||delete d.parent;let p=(yield u.Jo("RunAggregationQuery",u.serializer.databaseId,g,d,1)).filter(T=>!!T.result);he(p.length===1,64727);let _=(l=p[0].result)===null||l===void 0?void 0:l.aggregateFields;return Object.keys(_).reduce((T,D)=>(T[f[D]]=_[D],T),{})})})(i,e,r))}catch(i){t.reject(i)}})),t.promise}function oz(n){let e={};return n.timeoutSeconds!==void 0&&(e.timeoutSeconds=n.timeoutSeconds),e}var gH=new Map;var sz="firestore.googleapis.com",mH=!0,Sy=class{constructor(e){var r,t;if(e.host===void 0){if(e.ssl!==void 0)throw new Q(j.INVALID_ARGUMENT,"Can't provide ssl option if host option is not set");this.host=sz,this.ssl=mH}else this.host=e.host,this.ssl=(r=e.ssl)!==null&&r!==void 0?r:mH;if(this.isUsingEmulator=e.emulatorOptions!==void 0,this.credentials=e.credentials,this.ignoreUndefinedProperties=!!e.ignoreUndefinedProperties,this.localCache=e.localCache,e.cacheSizeBytes===void 0)this.cacheSizeBytes=bW;else{if(e.cacheSizeBytes!==-1&&e.cacheSizeBytes<xW)throw new Q(j.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");this.cacheSizeBytes=e.cacheSizeBytes}tie("experimentalForceLongPolling",e.experimentalForceLongPolling,"experimentalAutoDetectLongPolling",e.experimentalAutoDetectLongPolling),this.experimentalForceLongPolling=!!e.experimentalForceLongPolling,this.experimentalForceLongPolling?this.experimentalAutoDetectLongPolling=!1:e.experimentalAutoDetectLongPolling===void 0?this.experimentalAutoDetectLongPolling=!0:this.experimentalAutoDetectLongPolling=!!e.experimentalAutoDetectLongPolling,this.experimentalLongPollingOptions=oz((t=e.experimentalLongPollingOptions)!==null&&t!==void 0?t:{}),(function(o){if(o.timeoutSeconds!==void 0){if(isNaN(o.timeoutSeconds))throw new Q(j.INVALID_ARGUMENT,`invalid long polling timeout: ${o.timeoutSeconds} (must not be NaN)`);if(o.timeoutSeconds<5)throw new Q(j.INVALID_ARGUMENT,`invalid long polling timeout: ${o.timeoutSeconds} (minimum allowed value is 5)`);if(o.timeoutSeconds>30)throw new Q(j.INVALID_ARGUMENT,`invalid long polling timeout: ${o.timeoutSeconds} (maximum allowed value is 30)`)}})(this.experimentalLongPollingOptions),this.useFetchStreams=!!e.useFetchStreams}isEqual(e){return this.host===e.host&&this.ssl===e.ssl&&this.credentials===e.credentials&&this.cacheSizeBytes===e.cacheSizeBytes&&this.experimentalForceLongPolling===e.experimentalForceLongPolling&&this.experimentalAutoDetectLongPolling===e.experimentalAutoDetectLongPolling&&(function(t,i){return t.timeoutSeconds===i.timeoutSeconds})(this.experimentalLongPollingOptions,e.experimentalLongPollingOptions)&&this.ignoreUndefinedProperties===e.ignoreUndefinedProperties&&this.useFetchStreams===e.useFetchStreams}},Zl=class{constructor(e,r,t,i){this._authCredentials=e,this._appCheckCredentials=r,this._databaseId=t,this._app=i,this.type="firestore-lite",this._persistenceKey="(lite)",this._settings=new Sy({}),this._settingsFrozen=!1,this._emulatorOptions={},this._terminateTask="notTerminated"}get app(){if(!this._app)throw new Q(j.FAILED_PRECONDITION,"Firestore was not initialized using the Firebase SDK. 'app' is not available");return this._app}get _initialized(){return this._settingsFrozen}get _terminated(){return this._terminateTask!=="notTerminated"}_setSettings(e){if(this._settingsFrozen)throw new Q(j.FAILED_PRECONDITION,"Firestore has already been started and its settings can no longer be changed. You can only modify settings before calling any other methods on a Firestore object.");this._settings=new Sy(e),this._emulatorOptions=e.emulatorOptions||{},e.credentials!==void 0&&(this._authCredentials=(function(t){if(!t)return new $w;switch(t.type){case"firstParty":return new zw(t.sessionIndex||"0",t.iamToken||null,t.authTokenFactory||null);case"provider":return t.client;default:throw new Q(j.INVALID_ARGUMENT,"makeAuthCredentialsProvider failed due to invalid credential type")}})(e.credentials))}_getSettings(){return this._settings}_getEmulatorOptions(){return this._emulatorOptions}_freezeSettings(){return this._settingsFrozen=!0,this._settings}_delete(){return this._terminateTask==="notTerminated"&&(this._terminateTask=this._terminate()),this._terminateTask}_restart(){return I(this,null,function*(){this._terminateTask==="notTerminated"?yield this._terminate():this._terminateTask="notTerminated"})}toJSON(){return{app:this._app,databaseId:this._databaseId,settings:this._settings}}_terminate(){return(function(r){let t=gH.get(r);t&&(X("ComponentProvider","Removing Datastore"),gH.delete(r),t.terminate())})(this),Promise.resolve()}};function az(n,e,r,t={}){var i;n=wr(n,Zl);let o=Hr(e),s=n._getSettings(),a=Object.assign(Object.assign({},s),{emulatorOptions:n._getEmulatorOptions()}),c=`${e}:${r}`;o&&(ha(`https://${c}`),sl("Firestore",!0)),s.host!==sz&&s.host!==c&&ws("Host has been set in both settings() and connectFirestoreEmulator(), emulator host will be used.");let l=Object.assign(Object.assign({},s),{host:c,ssl:o,emulatorOptions:t});if(!Vi(l,a)&&(n._setSettings(l),t.mockUserToken)){let u,d;if(typeof t.mockUserToken=="string")u=t.mockUserToken,d=cn.MOCK_USER;else{u=KT(t.mockUserToken,(i=n._app)===null||i===void 0?void 0:i.options.projectId);let f=t.mockUserToken.sub||t.mockUserToken.user_id;if(!f)throw new Q(j.INVALID_ARGUMENT,"mockUserToken must contain 'sub' or 'user_id' field!");d=new cn(f)}n._authCredentials=new jw(new Mv(u,d))}}var Qi=class n{constructor(e,r,t){this.converter=r,this._query=t,this.type="query",this.firestore=e}withConverter(e){return new n(this.firestore,e,this._query)}},vn=class n{constructor(e,r,t){this.converter=r,this._key=t,this.type="document",this.firestore=e}get _path(){return this._key.path}get id(){return this._key.path.lastSegment()}get path(){return this._key.path.canonicalString()}get parent(){return new Ua(this.firestore,this.converter,this._key.path.popLast())}withConverter(e){return new n(this.firestore,e,this._key)}toJSON(){return{type:n._jsonSchemaVersion,referencePath:this._key.toString()}}static fromJSON(e,r,t){if(Ep(r,n._jsonSchema))return new n(e,t||null,new ie(We.fromString(r.referencePath)))}};vn._jsonSchemaVersion="firestore/documentReference/1.0",vn._jsonSchema={type:ln("string",vn._jsonSchemaVersion),referencePath:ln("string")};var Ua=class n extends Qi{constructor(e,r,t){super(e,r,vp(t)),this._path=t,this.type="collection"}get id(){return this._query.path.lastSegment()}get path(){return this._query.path.canonicalString()}get parent(){let e=this._path.popLast();return e.isEmpty()?null:new vn(this.firestore,null,new ie(e))}withConverter(e){return new n(this.firestore,e,this._path)}};function cz(n,e,...r){if(n=Ge(n),XL("collection","path",e),n instanceof Zl){let t=We.fromString(e,...r);return uj(t),new Ua(n,null,t)}{if(!(n instanceof vn||n instanceof Ua))throw new Q(j.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");let t=n._path.child(We.fromString(e,...r));return uj(t),new Ua(n.firestore,null,t)}}function lz(n,e){if(n=wr(n,Zl),XL("collectionGroup","collection id",e),e.indexOf("/")>=0)throw new Q(j.INVALID_ARGUMENT,`Invalid collection ID '${e}' passed to function collectionGroup(). Collection IDs must not contain '/'.`);return new Qi(n,null,(function(t){return new Wo(We.emptyPath(),t)})(e))}function uz(n,e,...r){if(n=Ge(n),arguments.length===1&&(e=jm.newId()),XL("doc","path",e),n instanceof Zl){let t=We.fromString(e,...r);return lj(t),new vn(n,null,new ie(t))}{if(!(n instanceof vn||n instanceof Ua))throw new Q(j.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");let t=n._path.child(We.fromString(e,...r));return lj(t),new vn(n.firestore,n instanceof Ua?n.converter:null,new ie(t))}}var pH="AsyncQueue",Ay=class{constructor(e=Promise.resolve()){this.Zu=[],this.Xu=!1,this.ec=[],this.tc=null,this.nc=!1,this.rc=!1,this.sc=[],this.F_=new dp(this,"async_queue_retry"),this.oc=()=>{let t=Lv();t&&X(pH,"Visibility state changed to "+t.visibilityState),this.F_.y_()},this._c=e;let r=Lv();r&&typeof r.addEventListener=="function"&&r.addEventListener("visibilitychange",this.oc)}get isShuttingDown(){return this.Xu}enqueueAndForget(e){this.enqueue(e)}enqueueAndForgetEvenWhileRestricted(e){this.ac(),this.uc(e)}enterRestrictedMode(e){if(!this.Xu){this.Xu=!0,this.rc=e||!1;let r=Lv();r&&typeof r.removeEventListener=="function"&&r.removeEventListener("visibilitychange",this.oc)}}enqueue(e){if(this.ac(),this.Xu)return new Promise(()=>{});let r=new Or;return this.uc(()=>this.Xu&&this.rc?Promise.resolve():(e().then(r.resolve,r.reject),r.promise)).then(()=>r.promise)}enqueueRetryable(e){this.enqueueAndForget(()=>(this.Zu.push(e),this.cc()))}cc(){return I(this,null,function*(){if(this.Zu.length!==0){try{yield this.Zu[0](),this.Zu.shift(),this.F_.reset()}catch(e){if(!Xa(e))throw e;X(pH,"Operation failed with retryable error: "+e)}this.Zu.length>0&&this.F_.g_(()=>this.cc())}})}uc(e){let r=this._c.then(()=>(this.nc=!0,e().catch(t=>{throw this.tc=t,this.nc=!1,Xt("INTERNAL UNHANDLED ERROR: ",EH(t)),t}).then(t=>(this.nc=!1,t))));return this._c=r,r}enqueueAfterDelay(e,r,t){this.ac(),this.sc.indexOf(e)>-1&&(r=0);let i=TL.createAndSchedule(this,e,r,t,o=>this.lc(o));return this.ec.push(i),i}ac(){this.tc&&ae(47125,{hc:EH(this.tc)})}verifyOperationInProgress(){}Pc(){return I(this,null,function*(){let e;do e=this._c,yield e;while(e!==this._c)})}Tc(e){for(let r of this.ec)if(r.timerId===e)return!0;return!1}Ic(e){return this.Pc().then(()=>{this.ec.sort((r,t)=>r.targetTimeMs-t.targetTimeMs);for(let r of this.ec)if(r.skipDelay(),e!=="all"&&r.timerId===e)break;return this.Pc()})}dc(e){this.sc.push(e)}lc(e){let r=this.ec.indexOf(e);this.ec.splice(r,1)}};function EH(n){let e=n.message||"";return n.stack&&(e=n.stack.includes(n.message)?n.stack:n.message+`
|
|
167
|
-
`+n.stack),e}function _H(n){return(function(r,t){if(typeof r!="object"||r===null)return!1;let i=r;for(let o of t)if(o in i&&typeof i[o]=="function")return!0;return!1})(n,["next","error","complete"])}var Xi=class extends Zl{constructor(e,r,t,i){super(e,r,t,i),this.type="firestore",this._queue=new Ay,this._persistenceKey=i?.name||"[DEFAULT]"}_terminate(){return I(this,null,function*(){if(this._firestoreClient){let e=this._firestoreClient.terminate();this._queue=new Ay(e),this._firestoreClient=void 0,yield e}})}};function Gy(n,e,r){r||(r=Xm);let t=Po(n,"firestore");if(t.isInitialized(r)){let i=t.getImmediate({identifier:r}),o=t.getOptions(r);if(Vi(o,e))return i;throw new Q(j.FAILED_PRECONDITION,"initializeFirestore() has already been called with different options. To avoid this error, call initializeFirestore() with the same options as when it was originally called, or call getFirestore() to return the already initialized instance.")}if(e.cacheSizeBytes!==void 0&&e.localCache!==void 0)throw new Q(j.INVALID_ARGUMENT,"cache and cacheSizeBytes cannot be specified at the same time as cacheSizeBytes willbe deprecated. Instead, specify the cache size in the cache object");if(e.cacheSizeBytes!==void 0&&e.cacheSizeBytes!==-1&&e.cacheSizeBytes<xW)throw new Q(j.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");return e.host&&Hr(e.host)&&ha(e.host),t.initialize({options:e,instanceIdentifier:r})}function $h(n,e){let r=typeof n=="object"?n:Sr(),t=typeof n=="string"?n:e||Xm,i=Po(r,"firestore").getImmediate({identifier:t});if(!i._initialized){let o=Nd("firestore");o&&az(i,...o)}return i}function jh(n){if(n._terminated)throw new Q(j.FAILED_PRECONDITION,"The client has already been terminated.");return n._firestoreClient||Joe(n),n._firestoreClient}function Joe(n){var e,r,t;let i=n._freezeSettings(),o=(function(a,c,l,u){return new rb(a,c,l,u.host,u.ssl,u.experimentalForceLongPolling,u.experimentalAutoDetectLongPolling,oz(u.experimentalLongPollingOptions),u.useFetchStreams,u.isUsingEmulator)})(n._databaseId,((e=n._app)===null||e===void 0?void 0:e.options.appId)||"",n._persistenceKey,i);n._componentsProvider||!((r=i.localCache)===null||r===void 0)&&r._offlineComponentProvider&&(!((t=i.localCache)===null||t===void 0)&&t._onlineComponentProvider)&&(n._componentsProvider={_offline:i.localCache._offlineComponentProvider,_online:i.localCache._onlineComponentProvider}),n._firestoreClient=new LL(n._authCredentials,n._appCheckCredentials,n._queue,o,n._componentsProvider&&(function(a){let c=a?._online.build();return{_offline:a?._offline.build(c),_online:c}})(n._componentsProvider))}var ML=class{constructor(e="count",r){this._internalFieldPath=r,this.type="AggregateField",this.aggregateType=e}},PL=class{constructor(e,r,t){this._userDataWriter=r,this._data=t,this.type="AggregateQuerySnapshot",this.query=e}data(){return this._userDataWriter.convertObjectMap(this._data)}};var Os=class n{constructor(e){this._byteString=e}static fromBase64String(e){try{return new n(un.fromBase64String(e))}catch(r){throw new Q(j.INVALID_ARGUMENT,"Failed to construct data from Base64 string: "+r)}}static fromUint8Array(e){return new n(un.fromUint8Array(e))}toBase64(){return this._byteString.toBase64()}toUint8Array(){return this._byteString.toUint8Array()}toString(){return"Bytes(base64: "+this.toBase64()+")"}isEqual(e){return this._byteString.isEqual(e._byteString)}toJSON(){return{type:n._jsonSchemaVersion,bytes:this.toBase64()}}static fromJSON(e){if(Ep(e,n._jsonSchema))return n.fromBase64String(e.bytes)}};Os._jsonSchemaVersion="firestore/bytes/1.0",Os._jsonSchema={type:ln("string",Os._jsonSchemaVersion),bytes:ln("string")};var xh=class{constructor(...e){for(let r=0;r<e.length;++r)if(e[r].length===0)throw new Q(j.INVALID_ARGUMENT,"Invalid field name at argument $(i + 1). Field names must not be empty.");this._internalPath=new Tn(e)}isEqual(e){return this._internalPath.isEqual(e._internalPath)}};var gp=class{constructor(e){this._methodName=e}};var Va=class n{constructor(e,r){if(!isFinite(e)||e<-90||e>90)throw new Q(j.INVALID_ARGUMENT,"Latitude must be a number between -90 and 90, but was: "+e);if(!isFinite(r)||r<-180||r>180)throw new Q(j.INVALID_ARGUMENT,"Longitude must be a number between -180 and 180, but was: "+r);this._lat=e,this._long=r}get latitude(){return this._lat}get longitude(){return this._long}isEqual(e){return this._lat===e._lat&&this._long===e._long}_compareTo(e){return Re(this._lat,e._lat)||Re(this._long,e._long)}toJSON(){return{latitude:this._lat,longitude:this._long,type:n._jsonSchemaVersion}}static fromJSON(e){if(Ep(e,n._jsonSchema))return new n(e.latitude,e.longitude)}};Va._jsonSchemaVersion="firestore/geoPoint/1.0",Va._jsonSchema={type:ln("string",Va._jsonSchemaVersion),latitude:ln("number"),longitude:ln("number")};var Ba=class n{constructor(e){this._values=(e||[]).map(r=>r)}toArray(){return this._values.map(e=>e)}isEqual(e){return(function(t,i){if(t.length!==i.length)return!1;for(let o=0;o<t.length;++o)if(t[o]!==i[o])return!1;return!0})(this._values,e._values)}toJSON(){return{type:n._jsonSchemaVersion,vectorValues:this._values}}static fromJSON(e){if(Ep(e,n._jsonSchema)){if(Array.isArray(e.vectorValues)&&e.vectorValues.every(r=>typeof r=="number"))return new n(e.vectorValues);throw new Q(j.INVALID_ARGUMENT,"Expected 'vectorValues' field to be a number array")}}};Ba._jsonSchemaVersion="firestore/vectorValue/1.0",Ba._jsonSchema={type:ln("string",Ba._jsonSchemaVersion),vectorValues:ln("object")};var Zoe=/^__.*__$/,xL=class{constructor(e,r,t){this.data=e,this.fieldMask=r,this.fieldTransforms=t}toMutation(e,r){return this.fieldMask!==null?new Yi(e,this.data,this.fieldMask,r,this.fieldTransforms):new qa(e,this.data,r,this.fieldTransforms)}},Dy=class{constructor(e,r,t){this.data=e,this.fieldMask=r,this.fieldTransforms=t}toMutation(e,r){return new Yi(e,this.data,this.fieldMask,r,this.fieldTransforms)}};function dz(n){switch(n){case 0:case 2:case 1:return!0;case 3:case 4:return!1;default:throw ae(40011,{Ec:n})}}var FL=class n{constructor(e,r,t,i,o,s){this.settings=e,this.databaseId=r,this.serializer=t,this.ignoreUndefinedProperties=i,o===void 0&&this.Ac(),this.fieldTransforms=o||[],this.fieldMask=s||[]}get path(){return this.settings.path}get Ec(){return this.settings.Ec}Rc(e){return new n(Object.assign(Object.assign({},this.settings),e),this.databaseId,this.serializer,this.ignoreUndefinedProperties,this.fieldTransforms,this.fieldMask)}Vc(e){var r;let t=(r=this.path)===null||r===void 0?void 0:r.child(e),i=this.Rc({path:t,mc:!1});return i.fc(e),i}gc(e){var r;let t=(r=this.path)===null||r===void 0?void 0:r.child(e),i=this.Rc({path:t,mc:!1});return i.Ac(),i}yc(e){return this.Rc({path:void 0,mc:!0})}wc(e){return Cy(e,this.settings.methodName,this.settings.Sc||!1,this.path,this.settings.bc)}contains(e){return this.fieldMask.find(r=>e.isPrefixOf(r))!==void 0||this.fieldTransforms.find(r=>e.isPrefixOf(r.field))!==void 0}Ac(){if(this.path)for(let e=0;e<this.path.length;e++)this.fc(this.path.get(e))}fc(e){if(e.length===0)throw this.wc("Document fields must not be empty");if(dz(this.Ec)&&Zoe.test(e))throw this.wc('Document fields cannot begin and end with "__"')}},kL=class{constructor(e,r,t){this.databaseId=e,this.ignoreUndefinedProperties=r,this.serializer=t||ky(e)}Dc(e,r,t,i=!1){return new FL({Ec:e,methodName:r,bc:t,path:Tn.emptyPath(),mc:!1,Sc:i},this.databaseId,this.serializer,this.ignoreUndefinedProperties)}};function $y(n){let e=n._freezeSettings(),r=ky(n._databaseId);return new kL(n._databaseId,!!e.ignoreUndefinedProperties,r)}function hz(n,e,r,t,i,o={}){let s=n.Dc(o.merge||o.mergeFields?2:0,e,r,i);OM("Data must be an object, but it was:",s,t);let a=gz(t,s),c,l;if(o.merge)c=new Yr(s.fieldMask),l=s.fieldTransforms;else if(o.mergeFields){let u=[];for(let d of o.mergeFields){let f=UL(e,d,r);if(!s.contains(f))throw new Q(j.INVALID_ARGUMENT,`Field '${f}' is specified in your field mask but missing from your input data.`);pz(u,f)||u.push(f)}c=new Yr(u),l=s.fieldTransforms.filter(d=>c.covers(d.field))}else c=null,l=s.fieldTransforms;return new xL(new nr(a),c,l)}var Ry=class n extends gp{_toFieldTransform(e){if(e.Ec!==2)throw e.Ec===1?e.wc(`${this._methodName}() can only appear at the top level of your update data`):e.wc(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`);return e.fieldMask.push(e.path),null}isEqual(e){return e instanceof n}};function ese(n,e,r,t){let i=n.Dc(1,e,r);OM("Data must be an object, but it was:",i,t);let o=[],s=nr.empty();Ja(t,(c,l)=>{let u=wM(e,c,r);l=Ge(l);let d=i.gc(u);if(l instanceof Ry)o.push(u);else{let f=Ap(l,d);f!=null&&(o.push(u),s.set(u,f))}});let a=new Yr(o);return new Dy(s,a,i.fieldTransforms)}function tse(n,e,r,t,i,o){let s=n.Dc(1,e,r),a=[UL(e,t,r)],c=[i];if(o.length%2!=0)throw new Q(j.INVALID_ARGUMENT,`Function ${e}() needs to be called with an even number of arguments that alternate between field names and values.`);for(let f=0;f<o.length;f+=2)a.push(UL(e,o[f])),c.push(o[f+1]);let l=[],u=nr.empty();for(let f=a.length-1;f>=0;--f)if(!pz(l,a[f])){let g=a[f],p=c[f];p=Ge(p);let _=s.gc(g);if(p instanceof Ry)l.push(g);else{let T=Ap(p,_);T!=null&&(l.push(g),u.set(g,T))}}let d=new Yr(l);return new Dy(u,d,s.fieldTransforms)}function fz(n,e,r,t=!1){return Ap(r,n.Dc(t?4:3,e))}function Ap(n,e){if(mz(n=Ge(n)))return OM("Unsupported field value:",e,n),gz(n,e);if(n instanceof gp)return(function(t,i){if(!dz(i.Ec))throw i.wc(`${t._methodName}() can only be used with update() and set()`);if(!i.path)throw i.wc(`${t._methodName}() is not currently supported inside arrays`);let o=t._toFieldTransform(i);o&&i.fieldTransforms.push(o)})(n,e),null;if(n===void 0&&e.ignoreUndefinedProperties)return null;if(e.path&&e.fieldMask.push(e.path),n instanceof Array){if(e.settings.mc&&e.Ec!==4)throw e.wc("Nested arrays are not supported");return(function(t,i){let o=[],s=0;for(let a of t){let c=Ap(a,i.yc(s));c==null&&(c={nullValue:"NULL_VALUE"}),o.push(c),s++}return{arrayValue:{values:o}}})(n,e)}return(function(t,i){if((t=Ge(t))===null)return{nullValue:"NULL_VALUE"};if(typeof t=="number")return Bie(i.serializer,t);if(typeof t=="boolean")return{booleanValue:t};if(typeof t=="string")return{stringValue:t};if(t instanceof Date){let o=Pt.fromDate(t);return{timestampValue:Nh(i.serializer,o)}}if(t instanceof Pt){let o=new Pt(t.seconds,1e3*Math.floor(t.nanoseconds/1e3));return{timestampValue:Nh(i.serializer,o)}}if(t instanceof Va)return{geoPointValue:{latitude:t.latitude,longitude:t.longitude}};if(t instanceof Os)return{bytesValue:EW(i.serializer,t._byteString)};if(t instanceof vn){let o=i.databaseId,s=t.firestore._databaseId;if(!s.isEqual(o))throw i.wc(`Document reference is for database ${s.projectId}/${s.database} but should be for database ${o.projectId}/${o.database}`);return{referenceValue:uM(t.firestore._databaseId||i.databaseId,t._key.path)}}if(t instanceof Ba)return(function(s,a){return{mapValue:{fields:{[iM]:{stringValue:oM},[Sh]:{arrayValue:{values:s.toArray().map(l=>{if(typeof l!="number")throw a.wc("VectorValues must only contain numeric values.");return lM(a.serializer,l)})}}}}}})(t,i);throw i.wc(`Unsupported field value: ${Oy(t)}`)})(n,e)}function gz(n,e){let r={};return BH(n)?e.path&&e.path.length>0&&e.fieldMask.push(e.path):Ja(n,(t,i)=>{let o=Ap(i,e.Vc(t));o!=null&&(r[t]=o)}),{mapValue:{fields:r}}}function mz(n){return!(typeof n!="object"||n===null||n instanceof Array||n instanceof Date||n instanceof Pt||n instanceof Va||n instanceof Os||n instanceof vn||n instanceof gp||n instanceof Ba)}function OM(n,e,r){if(!mz(r)||!AH(r)){let t=Oy(r);throw t==="an object"?e.wc(n+" a custom object"):e.wc(n+" "+t)}}function UL(n,e,r){if((e=Ge(e))instanceof xh)return e._internalPath;if(typeof e=="string")return wM(n,e);throw Cy("Field path arguments must be of type string or ",n,!1,void 0,r)}var nse=new RegExp("[~\\*/\\[\\]]");function wM(n,e,r){if(e.search(nse)>=0)throw Cy(`Invalid field path (${e}). Paths must not contain '~', '*', '/', '[', or ']'`,n,!1,void 0,r);try{return new xh(...e.split("."))._internalPath}catch{throw Cy(`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`,n,!1,void 0,r)}}function Cy(n,e,r,t,i){let o=t&&!t.isEmpty(),s=i!==void 0,a=`Function ${e}() called with invalid data`;r&&(a+=" (via `toFirestore()`)"),a+=". ";let c="";return(o||s)&&(c+=" (found",o&&(c+=` in field ${t}`),s&&(c+=` in document ${i}`),c+=")"),new Q(j.INVALID_ARGUMENT,a+n+c)}function pz(n,e){return n.some(r=>r.isEqual(e))}var eu=class{constructor(e,r,t,i,o){this._firestore=e,this._userDataWriter=r,this._key=t,this._document=i,this._converter=o}get id(){return this._key.path.lastSegment()}get ref(){return new vn(this._firestore,this._converter,this._key)}exists(){return this._document!==null}data(){if(this._document){if(this._converter){let e=new VL(this._firestore,this._userDataWriter,this._key,this._document,null);return this._converter.fromFirestore(e)}return this._userDataWriter.convertValue(this._document.data.value)}}get(e){if(this._document){let r=this._document.data.field(jy("DocumentSnapshot.get",e));if(r!==null)return this._userDataWriter.convertValue(r)}}},VL=class extends eu{data(){return super.data()}};function jy(n,e){return typeof e=="string"?wM(n,e):e instanceof xh?e._internalPath:e._delegate._internalPath}function Ez(n){if(n.limitType==="L"&&n.explicitOrderBy.length===0)throw new Q(j.UNIMPLEMENTED,"limitToLast() queries require specifying at least one orderBy() clause")}var mp=class{},Fh=class extends mp{};function _z(n,e,...r){let t=[];e instanceof mp&&t.push(e),t=t.concat(r),(function(o){let s=o.filter(c=>c instanceof kh).length,a=o.filter(c=>c instanceof pp).length;if(s>1||s>0&&a>0)throw new Q(j.INVALID_ARGUMENT,"InvalidQuery. When using composite filters, you cannot use more than one filter at the top level. Consider nesting the multiple filters within an `and(...)` statement. For example: change `query(query, where(...), or(...))` to `query(query, and(where(...), or(...)))`.")})(t);for(let i of t)n=i._apply(n);return n}var pp=class n extends Fh{constructor(e,r,t){super(),this._field=e,this._op=r,this._value=t,this.type="where"}static _create(e,r,t){return new n(e,r,t)}_apply(e){let r=this._parse(e);return Dz(e._query,r),new Qi(e.firestore,e.converter,pb(e._query,r))}_parse(e){let r=$y(e.firestore);return(function(o,s,a,c,l,u,d){let f;if(l.isKeyField()){if(u==="array-contains"||u==="array-contains-any")throw new Q(j.INVALID_ARGUMENT,`Invalid Query. You can't perform '${u}' queries on documentId().`);if(u==="in"||u==="not-in"){IH(d,u);let p=[];for(let _ of d)p.push(TH(c,o,_));f={arrayValue:{values:p}}}else f=TH(c,o,d)}else u!=="in"&&u!=="not-in"&&u!=="array-contains-any"||IH(d,u),f=fz(a,s,d,u==="in"||u==="not-in");return $e.create(l,u,f)})(e._query,"where",r,e.firestore._databaseId,this._field,this._op,this._value)}};function Tz(n,e,r){let t=e,i=jy("where",n);return pp._create(i,t,r)}var kh=class n extends mp{constructor(e,r){super(),this.type=e,this._queryConstraints=r}static _create(e,r){return new n(e,r)}_parse(e){let r=this._queryConstraints.map(t=>t._parse(e)).filter(t=>t.getFilters().length>0);return r.length===1?r[0]:nt.create(r,this._getOperator())}_apply(e){let r=this._parse(e);return r.getFilters().length===0?e:((function(i,o){let s=i,a=o.getFlattenedFilters();for(let c of a)Dz(s,c),s=pb(s,c)})(e._query,r),new Qi(e.firestore,e.converter,pb(e._query,r)))}_getQueryConstraints(){return this._queryConstraints}_getOperator(){return this.type==="and"?"and":"or"}};function Iz(...n){return n.forEach(e=>Rz("or",e)),kh._create("or",n)}function vz(...n){return n.forEach(e=>Rz("and",e)),kh._create("and",n)}var BL=class n extends Fh{constructor(e,r){super(),this._field=e,this._direction=r,this.type="orderBy"}static _create(e,r){return new n(e,r)}_apply(e){let r=(function(i,o,s){if(i.startAt!==null)throw new Q(j.INVALID_ARGUMENT,"Invalid query. You must not call startAt() or startAfter() before calling orderBy().");if(i.endAt!==null)throw new Q(j.INVALID_ARGUMENT,"Invalid query. You must not call endAt() or endBefore() before calling orderBy().");return new Wl(o,s)})(e._query,this._field,this._direction);return new Qi(e.firestore,e.converter,(function(i,o){let s=i.explicitOrderBy.concat([o]);return new Wo(i.path,i.collectionGroup,s,i.filters.slice(),i.limit,i.limitType,i.startAt,i.endAt)})(e._query,r))}};function yz(n,e="asc"){let r=e,t=jy("orderBy",n);return BL._create(t,r)}var GL=class n extends Fh{constructor(e,r,t){super(),this.type=e,this._limit=r,this._limitType=t}static _create(e,r,t){return new n(e,r,t)}_apply(e){return new Qi(e.firestore,e.converter,qv(e._query,this._limit,this._limitType))}};function Sz(n){return nie("limit",n),GL._create("limit",n,"F")}var $L=class n extends Fh{constructor(e,r,t){super(),this.type=e,this._docOrFields=r,this._inclusive=t}static _create(e,r,t){return new n(e,r,t)}_apply(e){let r=rse(e,this.type,this._docOrFields,this._inclusive);return new Qi(e.firestore,e.converter,(function(i,o){return new Wo(i.path,i.collectionGroup,i.explicitOrderBy.slice(),i.filters.slice(),i.limit,i.limitType,o,i.endAt)})(e._query,r))}};function Az(...n){return $L._create("startAfter",n,!1)}function rse(n,e,r,t){if(r[0]=Ge(r[0]),r[0]instanceof eu)return(function(o,s,a,c,l){if(!c)throw new Q(j.NOT_FOUND,`Can't use a DocumentSnapshot that doesn't exist for ${a}().`);let u=[];for(let d of dh(o))if(d.field.isKeyField())u.push(Hl(s,c.key));else{let f=c.data.field(d.field);if(My(f))throw new Q(j.INVALID_ARGUMENT,'Invalid query. You are trying to start or end a query using a document for which the field "'+d.field+'" is an uncommitted server timestamp. (Since the value of this field is unknown, you cannot start/end a query with it.)');if(f===null){let g=d.field.canonicalString();throw new Q(j.INVALID_ARGUMENT,`Invalid query. You are trying to start or end a query using a document for which the field '${g}' (used as the orderBy) does not exist.`)}u.push(f)}return new Ho(u,l)})(n._query,n.firestore._databaseId,e,r[0]._document,t);{let i=$y(n.firestore);return(function(s,a,c,l,u,d){let f=s.explicitOrderBy;if(u.length>f.length)throw new Q(j.INVALID_ARGUMENT,`Too many arguments provided to ${l}(). The number of arguments must be less than or equal to the number of orderBy() clauses`);let g=[];for(let p=0;p<u.length;p++){let _=u[p];if(f[p].field.isKeyField()){if(typeof _!="string")throw new Q(j.INVALID_ARGUMENT,`Invalid query. Expected a string for document ID in ${l}(), but got a ${typeof _}`);if(!aM(s)&&_.indexOf("/")!==-1)throw new Q(j.INVALID_ARGUMENT,`Invalid query. When querying a collection and ordering by documentId(), the value passed to ${l}() must be a plain document ID, but '${_}' contains a slash.`);let T=s.path.child(We.fromString(_));if(!ie.isDocumentKey(T))throw new Q(j.INVALID_ARGUMENT,`Invalid query. When querying a collection group and ordering by documentId(), the value passed to ${l}() must result in a valid document path, but '${T}' is not because it contains an odd number of segments.`);let D=new ie(T);g.push(Hl(a,D))}else{let T=fz(c,l,_);g.push(T)}}return new Ho(g,d)})(n._query,n.firestore._databaseId,i,e,r,t)}}function TH(n,e,r){if(typeof(r=Ge(r))=="string"){if(r==="")throw new Q(j.INVALID_ARGUMENT,"Invalid query. When querying with documentId(), you must provide a valid document ID, but it was an empty string.");if(!aM(e)&&r.indexOf("/")!==-1)throw new Q(j.INVALID_ARGUMENT,`Invalid query. When querying a collection by documentId(), you must provide a plain document ID, but '${r}' contains a '/' character.`);let t=e.path.child(We.fromString(r));if(!ie.isDocumentKey(t))throw new Q(j.INVALID_ARGUMENT,`Invalid query. When querying a collection group by documentId(), the value provided must result in a valid document path, but '${t}' is not because it has an odd number of segments (${t.length}).`);return Hl(n,new ie(t))}if(r instanceof vn)return Hl(n,r._key);throw new Q(j.INVALID_ARGUMENT,`Invalid query. When querying with documentId(), you must provide a valid string or a DocumentReference, but it was: ${Oy(r)}.`)}function IH(n,e){if(!Array.isArray(n)||n.length===0)throw new Q(j.INVALID_ARGUMENT,`Invalid Query. A non-empty array is required for '${e.toString()}' filters.`)}function Dz(n,e){let r=(function(i,o){for(let s of i)for(let a of s.getFlattenedFilters())if(o.indexOf(a.op)>=0)return a.op;return null})(n.filters,(function(i){switch(i){case"!=":return["!=","not-in"];case"array-contains-any":case"in":return["not-in"];case"not-in":return["array-contains-any","in","not-in","!="];default:return[]}})(e.op));if(r!==null)throw r===e.op?new Q(j.INVALID_ARGUMENT,`Invalid query. You cannot use more than one '${e.op.toString()}' filter.`):new Q(j.INVALID_ARGUMENT,`Invalid query. You cannot use '${e.op.toString()}' filters with '${r.toString()}' filters.`)}function Rz(n,e){if(!(e instanceof pp||e instanceof kh))throw new Q(j.INVALID_ARGUMENT,`Function ${n}() requires AppliableConstraints created with a call to 'where(...)', 'or(...)', or 'and(...)'.`)}var Ny=class{convertValue(e,r="none"){switch(ja(e)){case 0:return null;case 1:return e.booleanValue;case 2:return Mt(e.integerValue||e.doubleValue);case 3:return this.convertTimestamp(e.timestampValue);case 4:return this.convertServerTimestamp(e,r);case 5:return e.stringValue;case 6:return this.convertBytes(Ls(e.bytesValue));case 7:return this.convertReference(e.referenceValue);case 8:return this.convertGeoPoint(e.geoPointValue);case 9:return this.convertArray(e.arrayValue,r);case 11:return this.convertObject(e.mapValue,r);case 10:return this.convertVectorValue(e.mapValue);default:throw ae(62114,{value:e})}}convertObject(e,r){return this.convertObjectMap(e.fields,r)}convertObjectMap(e,r="none"){let t={};return Ja(e,(i,o)=>{t[i]=this.convertValue(o,r)}),t}convertVectorValue(e){var r,t,i;let o=(i=(t=(r=e.fields)===null||r===void 0?void 0:r[Sh].arrayValue)===null||t===void 0?void 0:t.values)===null||i===void 0?void 0:i.map(s=>Mt(s.doubleValue));return new Ba(o)}convertGeoPoint(e){return new Va(Mt(e.latitude),Mt(e.longitude))}convertArray(e,r){return(e.values||[]).map(t=>this.convertValue(t,r))}convertServerTimestamp(e,r){switch(r){case"previous":let t=Py(e);return t==null?null:this.convertValue(t,r);case"estimate":return this.convertTimestamp(Qm(e));default:return null}}convertTimestamp(e){let r=bs(e);return new Pt(r.seconds,r.nanos)}convertDocumentKey(e,r){let t=We.fromString(e);he(RW(t),9688,{name:e});let i=new yh(t.get(1),t.get(3)),o=new ie(t.popFirst(5));return i.isEqual(r)||Xt(`Document ${o} contains a document reference within a different database (${i.projectId}/${i.database}) which is not supported. It will be treated as a reference in the current database (${r.projectId}/${r.database}) instead.`),o}};function Cz(n,e,r){let t;return t=n?r&&(r.merge||r.mergeFields)?n.toFirestore(e,r):n.toFirestore(e):e,t}var jL=class extends Ny{constructor(e){super(),this.firestore=e}convertBytes(e){return new Os(e)}convertReference(e){let r=this.convertDocumentKey(e,this.firestore._databaseId);return new vn(this.firestore,null,r)}};function ise(){return new ML("count")}var ka=class{constructor(e,r){this.hasPendingWrites=e,this.fromCache=r}isEqual(e){return this.hasPendingWrites===e.hasPendingWrites&&this.fromCache===e.fromCache}},Ga=class n extends eu{constructor(e,r,t,i,o,s){super(e,r,t,i,s),this._firestore=e,this._firestoreImpl=e,this.metadata=o}exists(){return super.exists()}data(e={}){if(this._document){if(this._converter){let r=new fh(this._firestore,this._userDataWriter,this._key,this._document,this.metadata,null);return this._converter.fromFirestore(r,e)}return this._userDataWriter.convertValue(this._document.data.value,e.serverTimestamps)}}get(e,r={}){if(this._document){let t=this._document.data.field(jy("DocumentSnapshot.get",e));if(t!==null)return this._userDataWriter.convertValue(t,r.serverTimestamps)}}toJSON(){if(this.metadata.hasPendingWrites)throw new Q(j.FAILED_PRECONDITION,"DocumentSnapshot.toJSON() attempted to serialize a document with pending writes. Await waitForPendingWrites() before invoking toJSON().");let e=this._document,r={};return r.type=n._jsonSchemaVersion,r.bundle="",r.bundleSource="DocumentSnapshot",r.bundleName=this._key.toString(),!e||!e.isValidDocument()||!e.isFoundDocument()?r:(this._userDataWriter.convertObjectMap(e.data.value.mapValue.fields,"previous"),r.bundle=(this._firestore,this.ref.path,"NOT SUPPORTED"),r)}};Ga._jsonSchemaVersion="firestore/documentSnapshot/1.0",Ga._jsonSchema={type:ln("string",Ga._jsonSchemaVersion),bundleSource:ln("string","DocumentSnapshot"),bundleName:ln("string"),bundle:ln("string")};var fh=class extends Ga{data(e={}){return super.data(e)}},jl=class n{constructor(e,r,t,i){this._firestore=e,this._userDataWriter=r,this._snapshot=i,this.metadata=new ka(i.hasPendingWrites,i.fromCache),this.query=t}get docs(){let e=[];return this.forEach(r=>e.push(r)),e}get size(){return this._snapshot.docs.size}get empty(){return this.size===0}forEach(e,r){this._snapshot.docs.forEach(t=>{e.call(r,new fh(this._firestore,this._userDataWriter,t.key,t,new ka(this._snapshot.mutatedKeys.has(t.key),this._snapshot.fromCache),this.query.converter))})}docChanges(e={}){let r=!!e.includeMetadataChanges;if(r&&this._snapshot.excludesMetadataChanges)throw new Q(j.INVALID_ARGUMENT,"To include metadata changes with your document changes, you must also pass { includeMetadataChanges:true } to onSnapshot().");return this._cachedChanges&&this._cachedChangesIncludeMetadataChanges===r||(this._cachedChanges=(function(i,o){if(i._snapshot.oldDocs.isEmpty()){let s=0;return i._snapshot.docChanges.map(a=>{let c=new fh(i._firestore,i._userDataWriter,a.doc.key,a.doc,new ka(i._snapshot.mutatedKeys.has(a.doc.key),i._snapshot.fromCache),i.query.converter);return a.doc,{type:"added",doc:c,oldIndex:-1,newIndex:s++}})}{let s=i._snapshot.oldDocs;return i._snapshot.docChanges.filter(a=>o||a.type!==3).map(a=>{let c=new fh(i._firestore,i._userDataWriter,a.doc.key,a.doc,new ka(i._snapshot.mutatedKeys.has(a.doc.key),i._snapshot.fromCache),i.query.converter),l=-1,u=-1;return a.type!==0&&(l=s.indexOf(a.doc.key),s=s.delete(a.doc.key)),a.type!==1&&(s=s.add(a.doc),u=s.indexOf(a.doc.key)),{type:ose(a.type),doc:c,oldIndex:l,newIndex:u}})}})(this,r),this._cachedChangesIncludeMetadataChanges=r),this._cachedChanges}toJSON(){if(this.metadata.hasPendingWrites)throw new Q(j.FAILED_PRECONDITION,"QuerySnapshot.toJSON() attempted to serialize a document with pending writes. Await waitForPendingWrites() before invoking toJSON().");let e={};e.type=n._jsonSchemaVersion,e.bundleSource="QuerySnapshot",e.bundleName=jm.newId(),this._firestore._databaseId.database,this._firestore._databaseId.projectId;let r=[],t=[],i=[];return this.docs.forEach(o=>{o._document!==null&&(r.push(o._document),t.push(this._userDataWriter.convertObjectMap(o._document.data.value.mapValue.fields,"previous")),i.push(o.ref.path))}),e.bundle=(this._firestore,this.query._query,e.bundleName,"NOT SUPPORTED"),e}};function ose(n){switch(n){case 0:return"added";case 2:case 3:return"modified";case 1:return"removed";default:return ae(61501,{type:n})}}function Nz(n){n=wr(n,vn);let e=wr(n.firestore,Xi);return Yoe(jh(e),n._key).then(r=>Pz(e,n,r))}jl._jsonSchemaVersion="firestore/querySnapshot/1.0",jl._jsonSchema={type:ln("string",jl._jsonSchemaVersion),bundleSource:ln("string","QuerySnapshot"),bundleName:ln("string"),bundle:ln("string")};var tu=class extends Ny{constructor(e){super(),this.firestore=e}convertBytes(e){return new Os(e)}convertReference(e){let r=this.convertDocumentKey(e,this.firestore._databaseId);return new vn(this.firestore,null,r)}};function Oz(n){n=wr(n,Qi);let e=wr(n.firestore,Xi),r=jh(e),t=new tu(e);return Ez(n._query),Qoe(r,n._query).then(i=>new jl(e,t,n,i))}function wz(n,e,r){n=wr(n,vn);let t=wr(n.firestore,Xi),i=Cz(n.converter,e,r);return Mz(t,[hz($y(t),"setDoc",n._key,i,n.converter!==null,r).toMutation(n._key,Gn.none())])}function bz(n){return Mz(wr(n.firestore,Xi),[new Yl(n._key,Gn.none())])}function Lz(n,...e){var r,t,i;n=Ge(n);let o={includeMetadataChanges:!1,source:"default"},s=0;typeof e[s]!="object"||_H(e[s])||(o=e[s++]);let a={includeMetadataChanges:o.includeMetadataChanges,source:o.source};if(_H(e[s])){let d=e[s];e[s]=(r=d.next)===null||r===void 0?void 0:r.bind(d),e[s+1]=(t=d.error)===null||t===void 0?void 0:t.bind(d),e[s+2]=(i=d.complete)===null||i===void 0?void 0:i.bind(d)}let c,l,u;if(n instanceof vn)l=wr(n.firestore,Xi),u=vp(n._key.path),c={next:d=>{e[s]&&e[s](Pz(l,n,d))},error:e[s+1],complete:e[s+2]};else{let d=wr(n,Qi);l=wr(d.firestore,Xi),u=d._query;let f=new tu(l);c={next:g=>{e[s]&&e[s](new jl(l,f,d,g))},error:e[s+1],complete:e[s+2]},Ez(n._query)}return(function(f,g,p,_){let T=new fp(_),D=new hp(g,T,p);return f.asyncQueue.enqueueAndForget(()=>I(null,null,function*(){return _M(yield yy(f),D)})),()=>{T.Ou(),f.asyncQueue.enqueueAndForget(()=>I(null,null,function*(){return TM(yield yy(f),D)}))}})(jh(l),u,a,c)}function Mz(n,e){return(function(t,i){let o=new Or;return t.asyncQueue.enqueueAndForget(()=>I(null,null,function*(){return Moe(yield Koe(t),i,o)})),o.promise})(jh(n),e)}function Pz(n,e,r){let t=r.docs.get(e._key),i=new tu(n);return new Ga(n,i,e._key,t,new ka(r.hasPendingWrites,r.fromCache),e.converter)}function xz(n){return Fz(n,{count:ise()})}function Fz(n,e){let r=wr(n.firestore,Xi),t=jh(r),i=Oie(e,(o,s)=>new Ib(s,o.aggregateType,o._internalFieldPath));return Xoe(t,n._query,i).then(o=>(function(a,c,l){let u=new tu(a);return new PL(c,u,l)})(r,n,o))}var HL=class{constructor(e){let r;this.kind="persistent",e?.tabManager?(e.tabManager._initialize(e),r=e.tabManager):(r=sse(void 0),r._initialize(e)),this._onlineComponentProvider=r._onlineComponentProvider,this._offlineComponentProvider=r._offlineComponentProvider}toJSON(){return{kind:this.kind}}};function bM(n){return new HL(n)}var WL=class{constructor(e){this.forceOwnership=e,this.kind="persistentSingleTab"}toJSON(){return{kind:this.kind}}_initialize(e){this._onlineComponentProvider=CM.provider,this._offlineComponentProvider={build:r=>new vy(r,e?.cacheSizeBytes,this.forceOwnership)}}},zL=class{constructor(){this.kind="PersistentMultipleTab"}toJSON(){return{kind:this.kind}}_initialize(e){this._onlineComponentProvider=CM.provider,this._offlineComponentProvider={build:r=>new OL(r,e?.cacheSizeBytes)}}};function sse(n){return new WL(n?.forceOwnership)}function LM(){return new zL}var ase={maxAttempts:5};function Pm(n,e){if((n=Ge(n)).firestore!==e)throw new Q(j.INVALID_ARGUMENT,"Provided document reference is from a different Firestore instance.");return n}var qL=class{constructor(e,r){this._firestore=e,this._transaction=r,this._dataReader=$y(e)}get(e){let r=Pm(e,this._firestore),t=new jL(this._firestore);return this._transaction.lookup([r._key]).then(i=>{if(!i||i.length!==1)return ae(24041);let o=i[0];if(o.isFoundDocument())return new eu(this._firestore,t,o.key,o,r.converter);if(o.isNoDocument())return new eu(this._firestore,t,r._key,null,r.converter);throw ae(18433,{doc:o})})}set(e,r,t){let i=Pm(e,this._firestore),o=Cz(i.converter,r,t),s=hz(this._dataReader,"Transaction.set",i._key,o,i.converter!==null,t);return this._transaction.set(i._key,s),this}update(e,r,t,...i){let o=Pm(e,this._firestore),s;return s=typeof(r=Ge(r))=="string"||r instanceof xh?tse(this._dataReader,"Transaction.update",o._key,r,t,i):ese(this._dataReader,"Transaction.update",o._key,r),this._transaction.update(o._key,s),this}delete(e){let r=Pm(e,this._firestore);return this._transaction.delete(r._key),this}};var KL=class extends qL{constructor(e,r){super(e,r),this._firestore=e}get(e){let r=Pm(e,this._firestore),t=new tu(this._firestore);return super.get(e).then(i=>new Ga(this._firestore,t,r._key,i._document,new ka(!1,!1),r.converter))}};function kz(n,e,r){n=wr(n,Xi);let t=Object.assign(Object.assign({},ase),r);return(function(o){if(o.maxAttempts<1)throw new Q(j.INVALID_ARGUMENT,"Max attempts must be at least 1")})(t),(function(o,s,a){let c=new Or;return o.asyncQueue.enqueueAndForget(()=>I(null,null,function*(){let l=yield iz(o);new bL(o.asyncQueue,l,a,s,c).zu()})),c.promise})(jh(n),i=>e(new KL(n,i)),t)}(function(e,r=!0){(function(i){Uh=i})(pa),ur(new _n("firestore",(t,{instanceIdentifier:i,options:o})=>{let s=t.getProvider("app").getImmediate(),a=new Xi(new Hw(t.getProvider("auth-internal")),new qw(s,t.getProvider("app-check-internal")),(function(l,u){if(!Object.prototype.hasOwnProperty.apply(l.options,["projectId"]))throw new Q(j.INVALID_ARGUMENT,'"projectId" not provided in firebase.initializeApp.');return new yh(l.options.projectId,u)})(s,i),s);return o=Object.assign({useFetchStreams:r},o),a._setSettings(o),a},"PUBLIC").setMultipleInstances(!0)),Qe(oj,sj,e),Qe(oj,sj,"esm2017")})();var MM=pe(vz,!0,2);var Dp=pe(cz,!0,2),PM=pe(lz,!0,2);var Hy=pe(bz,!0,2);var Hh=pe(uz,!0,2);var Uz=pe(xz,!0),Vz=pe(Nz,!0);var Bz=pe(Oz,!0);var Lxe=pe(Sz,!0,2);var xM=pe(Lz,!0);var Mxe=pe(Iz,!0,2),Pxe=pe(yz,!0,2),FM=pe(_z,!0,2);var kM=pe(kz,!0),UM=pe(wz,!0,2);var xxe=pe(Az,!0,2);var Ji=pe(Tz,!0,2);var Wy=(()=>{let e=class e{constructor(t,i,o){this.authService=t,this.configService=i,this.loggingService=o,this.db$=new Y(null);try{this.authService.getFirebaseConfig$().subscribe(s=>{if(s){let a=this.configService.getProxyConfig(),c=s.firebaseOptions.databaseURL;a?.v1DbHost&&c&&(c=OV(c,a.v1DbHost),a?.forceLongPolling&&hw());let l=dv(void 0,c);a?.v1DbHost&&c&&this.lockDatabaseHost(l),this.db$.next(l)}},s=>{this.loggingService.catch("Error in DatabaseService constructor: ",s)})}catch(s){this.loggingService.catch("Error in DatabaseService constructor:",s)}}getDb(){return this.db$.asObservable()}getDbValue(){return this.db$.getValue()}lockDatabaseHost(t){try{let o=t?._repo?.repoInfo_;if(o){let s=o.host;Object.defineProperty(o,"host",{get:()=>s,set:()=>{},configurable:!0}),o.internalHost=s}}catch(i){this.loggingService.catch("Error in DatabaseService lockDatabaseHost: ",i)}}};e.\u0275fac=function(i){return new(i||e)(w(Cr),w(Rr),w(_e))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let n=e;return n})();var zo=(()=>{let e=class e{constructor(t,i,o){this.coreActionsService=t,this.loggingService=i,this.analyticsService=o,this.resolveTimeout=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 Y(null),this.commentAnnotationById$=new Y({}),this.fieldsToRemove=[],this.additionalFields=[],this.additionalSaveEvents=[],this.getCommentAnnotationById=s=>{try{return this.commentAnnotationDataProviderAvailable()?this.commentAnnotationById$.value?.[s]:void 0}catch(a){this.loggingService.catch("Error in CommentAnnotationsResolverService getCommentAnnotationById:",a);return}};try{this.loggingService.log("CommentAnnotationsResolverService initialized"),this.commentAnnotationDataProvider$.subscribe(s=>{s&&(s.config?.resolveTimeout&&(this.resolveTimeout=s.config.resolveTimeout),s.config?.saveRetryConfig&&(this.retrySaveConfig=s.config.saveRetryConfig),s.config?.deleteRetryConfig&&(this.retryDeleteConfig=s.config.deleteRetryConfig),s.config?.getRetryConfig&&(this.retryGetConfig=s.config.getRetryConfig),s.config?.fieldsToRemove&&(this.fieldsToRemove=s.config.fieldsToRemove),s.config?.additionalFields&&(this.additionalFields=s.config.additionalFields||[]),this.additionalSaveEvents=(s.config?.additionalSaveEvents||[]).map(a=>a?.event).filter(a=>!!a))})}catch(s){this.loggingService.catch("Error in CommentAnnotationsResolverService constructor:",s)}}getProvider(){try{let t=this.commentAnnotationDataProvider$.getValue();return t||void 0}catch(t){this.loggingService.catch("Error in CommentAnnotationsResolverService getProvider:",t);return}}ngOnDestroy(){try{this.commentAnnotationById$.next({})}catch(t){this.loggingService.catch("Error in CommentAnnotationsResolverService ngOnDestroy:",t)}}resolveCommentAnnotations(s){return I(this,arguments,function*({request:t,uniqueId:i,moduleName:o}){try{if(this.loggingService.log("%c[WB] Calling CommentAnnotationsResolverService FUNCTION: resolveCommentAnnotations","color: green;"),!this.commentAnnotationDataProviderAvailable())return{};let a,c=!1,l=!1,u=()=>{a&&(clearTimeout(a),a=void 0,l=!0)};return new Promise((d,f)=>{a=setTimeout(()=>{if(!l){c=!0,u();let b=i||J();this.coreActionsService.triggerAction($.COMMENT_RESOLVER,{event:L.Events.Resolver.COMMENT_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:b,methodName:Et.RESOLVE_COMMENT_ANNOTATIONS,moduleName:o,source:"internal",payload:{error:new Error("Comment annotation resolution timeout"),request:t}}),f(new Error("Comment annotation resolution timeout"))}},this.commentAnnotationDataProvider$.value?.config?.resolveTimeout||this.resolveTimeout);let g=this.getProvider();if(!g)return u(),d({});let p={},_=[...new Set(t.commentAnnotationIds||[])],T=le(x({},t),{commentAnnotationIds:_});I(this,null,function*(){try{if(_.length>0||t.documentIds?.length||t.folderId){let b=i||J();this.coreActionsService.triggerAction($.COMMENT_RESOLVER,{event:L.Events.Resolver.COMMENT_RESOLUTION_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:b,methodName:Et.RESOLVE_COMMENT_ANNOTATIONS,moduleName:o,source:"internal",payload:{request:T}});let G=kt(()=>g?.config?.getConfig?.url?Ht(g.config.getConfig.url,g.config.getConfig.headers,T,!0,g.config.getConfig.credentials):g?.get?.(T)||Promise.resolve(void 0),"getCommentAnnotations",this.retryGetConfig).then(M=>c?{}:(u(),M&&M.statusCode!==200?(this.coreActionsService.triggerAction($.COMMENT_RESOLVER,{event:L.Events.Resolver.COMMENT_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:b,methodName:Et.RESOLVE_COMMENT_ANNOTATIONS,moduleName:o,source:"internal",payload:{result:M,request:T}}),this.loggingService.catch(M?.message??"Error in CommentAnnotationsResolverService resolveCommentAnnotations:"),{}):M?.data)).catch(M=>{throw u(),M});try{p=(yield G)||{},this.analyticsService.trackEvent(L.Events.Resolver.COMMENT_RESOLVER_GET,{sourceMethod:"resolveCommentAnnotations",source:"sdk",commentAnnotationIds:_});let M={};Object.entries(p).forEach(([U,k])=>{let S=this.commentAnnotationById$.value?.[U];S?S&&JSON.stringify(S)!==JSON.stringify(k)&&(M[U]=k):M[U]=k}),Object.keys(M).length>0&&this.commentAnnotationById$.next(x(x({},this.commentAnnotationById$.getValue()),M)),this.coreActionsService.triggerAction($.COMMENT_RESOLVER,{event:L.Events.Resolver.COMMENT_RESOLUTION_RESULT,timestamp:new Date().getTime(),uniqueId:b,methodName:Et.RESOLVE_COMMENT_ANNOTATIONS,moduleName:o,source:"internal",payload:{result:M,request:T}}),d(M)}catch(M){let U=i||J();this.coreActionsService.triggerAction($.COMMENT_RESOLVER,{event:L.Events.Resolver.COMMENT_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:U,methodName:Et.RESOLVE_COMMENT_ANNOTATIONS,moduleName:o,source:"internal",payload:{error:M,request:T}}),c||f(M),d(p)}}else u(),d({})}catch(b){u();let G=i||J();this.coreActionsService.triggerAction($.COMMENT_RESOLVER,{event:L.Events.Resolver.COMMENT_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:G,methodName:Et.RESOLVE_COMMENT_ANNOTATIONS,moduleName:o,source:"internal",payload:{error:b,request:T}}),f(b)}})})}catch(a){this.loggingService.catch("Error in CommentAnnotationsResolverService resolveCommentAnnotations:",a);let c=i||J();return this.coreActionsService.triggerAction($.COMMENT_RESOLVER,{event:L.Events.Resolver.COMMENT_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:c,methodName:Et.RESOLVE_COMMENT_ANNOTATIONS,moduleName:o,source:"internal",payload:{error:a,request:t}}),{}}})}saveCommentAnnotation(t,i){return I(this,null,function*(){try{this.loggingService.log("%c[WB] Calling CommentAnnotationsResolverService FUNCTION: saveCommentAnnotation","color: green;");let o=this.getProvider();if(!this.commentAnnotationDataProviderAvailable())throw new Error("Comment annotation save data provider not available");let s=i||J();this.coreActionsService.triggerAction($.COMMENT_RESOLVER,{event:L.Events.Resolver.COMMENT_SAVE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:s,methodName:Et.SAVE_COMMENT_ANNOTATION,source:"internal",payload:{request:t}});let a=JSON.parse(JSON.stringify(this.commentAnnotationById$.getValue()));this.commentAnnotationById$._value=x(x({},a),t.commentAnnotation);let c=this.getTargetComment(t.commentAnnotation,t.commentId),l=yield kt(()=>{if(o?.config?.saveConfig?.url){let u={commentAnnotation:t.commentAnnotation,event:t.eventType,commentId:t.commentId,targetComment:c,metadata:Object.values(t.commentAnnotation??{})?.[0]?.metadata};return Ht(o.config.saveConfig.url,o.config.saveConfig.headers,u,!1,o.config.saveConfig.credentials)}return o?.save?.({commentAnnotation:t.commentAnnotation,event:t.eventType,commentId:t.commentId,targetComment:c,metadata:Object.values(t.commentAnnotation??{})?.[0]?.metadata})||Promise.resolve(void 0)},"saveCommentAnnotation",this.retrySaveConfig);return l&&l.statusCode!==200?(this.retrySaveConfig.revertOnFailure&&(this.commentAnnotationById$._value=a),this.loggingService.catch(l?.message??"Error in CommentAnnotationsResolverService saveCommentAnnotation:"),this.coreActionsService.triggerAction($.COMMENT_RESOLVER,{event:L.Events.Resolver.COMMENT_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:s,methodName:Et.SAVE_COMMENT_ANNOTATION,source:"internal",payload:{error:l,request:t}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(L.Events.Resolver.COMMENT_RESOLVER_SAVE,{sourceMethod:"saveCommentAnnotation",source:"sdk",commentAnnotationIds:Object.keys(t.commentAnnotation),eventType:t.eventType,commentId:t.commentId}),this.coreActionsService.triggerAction($.COMMENT_RESOLVER,{event:L.Events.Resolver.COMMENT_SAVE_RESULT,timestamp:new Date().getTime(),uniqueId:s,methodName:Et.SAVE_COMMENT_ANNOTATION,source:"internal",payload:{result:{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0},request:t}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0})}catch(o){this.loggingService.warn("Error in CommentAnnotationsResolverService saveCommentAnnotation:",o);let s=i||J();return this.coreActionsService.triggerAction($.COMMENT_RESOLVER,{event:L.Events.Resolver.COMMENT_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:s,methodName:Et.SAVE_COMMENT_ANNOTATION,source:"internal",payload:{error:o,request:t}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0}}})}getTargetComment(t,i){if(!(!i||!t))for(let o of Object.values(t)){let s=o?.comments?.[i];if(s)return s}}deleteCommentAnnotation(t,i,o){return I(this,null,function*(){try{this.loggingService.log("%c[WB] Calling CommentAnnotationsResolverService FUNCTION: deleteCommentAnnotation","color: green;");let s=this.getProvider();if(!this.commentAnnotationDataProviderAvailable())throw new Error("Comment annotation delete data provider not available");let a=this.commentAnnotationById$.getValue(),l=a?.[t]?.metadata??(i?Cn(i):void 0),u=l?x({apiKey:l.apiKey??null,documentId:l.documentId??null,organizationId:l.organizationId??null},l.folderId&&{folderId:l.folderId}):void 0,d=o||J();this.coreActionsService.triggerAction($.COMMENT_RESOLVER,{event:L.Events.Resolver.COMMENT_DELETE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:d,methodName:Et.DELETE_COMMENT_ANNOTATION,source:"internal",payload:{commentAnnotationId:t.toString(),metadata:u}});let f=x({},a);delete f?.[t],this.commentAnnotationById$._value=f;let g=yield kt(()=>{if(s?.config?.deleteConfig?.url){let p={commentAnnotationId:t.toString(),metadata:u,event:Qt.COMMENT_ANNOTATION_DELETE};return Ht(s.config.deleteConfig.url,s.config.deleteConfig.headers,p,!1,s.config.deleteConfig.credentials)}return s?.delete?.({commentAnnotationId:t.toString(),metadata:u,event:Qt.COMMENT_ANNOTATION_DELETE})||Promise.resolve(void 0)},"deleteCommentAnnotation",this.retryDeleteConfig);return g&&g.statusCode!==200?(this.retryDeleteConfig.revertOnFailure&&(this.commentAnnotationById$._value=a),this.loggingService.catch(g?.message??"Error in CommentAnnotationsResolverService deleteCommentAnnotation:"),this.coreActionsService.triggerAction($.COMMENT_RESOLVER,{event:L.Events.Resolver.COMMENT_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:d,methodName:Et.DELETE_COMMENT_ANNOTATION,source:"internal",payload:{error:g,commentAnnotationId:t.toString(),metadata:u}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(L.Events.Resolver.COMMENT_RESOLVER_DELETE,{sourceMethod:"deleteCommentAnnotation",source:"sdk",commentAnnotationId:t.toString()}),this.coreActionsService.triggerAction($.COMMENT_RESOLVER,{event:L.Events.Resolver.COMMENT_DELETE_RESULT,timestamp:new Date().getTime(),uniqueId:d,methodName:Et.DELETE_COMMENT_ANNOTATION,source:"internal",payload:{result:{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0},commentAnnotationId:t.toString(),metadata:u}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0})}catch(s){this.loggingService.warn("Error in CommentAnnotationsResolverService deleteCommentAnnotation:",s);let a=o||J(),c=i?Cn(i):void 0;return this.coreActionsService.triggerAction($.COMMENT_RESOLVER,{event:L.Events.Resolver.COMMENT_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:a,methodName:Et.DELETE_COMMENT_ANNOTATION,source:"internal",payload:{error:s,commentAnnotationId:t.toString(),metadata:c}}),{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()):ue(void 0)}catch(t){return this.loggingService.catch("Error in CommentAnnotationsResolverService getCommentAnnotationsById$:",t),ue(void 0)}}getAnnotationById(t){try{return this.commentAnnotationDataProviderAvailable()?this.commentAnnotationById$.getValue()?.[t]:void 0}catch(i){this.loggingService.catch("Error in CommentAnnotationsResolverService getAnnotationById:",i);return}}getFieldsToRemove(){try{return this.fieldsToRemove}catch(t){return this.loggingService.catch("Error in CommentAnnotationsResolverService getFieldsToRemove:",t),this.fieldsToRemove}}getAdditionalFields(){try{return this.additionalFields}catch(t){return this.loggingService.catch("Error in CommentAnnotationsResolverService getAdditionalFields:",t),this.additionalFields}}getAdditionalSaveEvents(){try{return this.additionalSaveEvents}catch(t){return this.loggingService.catch("Error in CommentAnnotationsResolverService getAdditionalSaveEvents:",t),this.additionalSaveEvents}}setCommentAnnotationDataProvider(t){try{if(t){this.loggingService.log("Setting comment annotation data provider");let i=t.config,o=[{method:"get",configKey:"getConfig"},{method:"save",configKey:"saveConfig"},{method:"delete",configKey:"deleteConfig"}],s=[];if(o.forEach(({method:a,configKey:c})=>{let l=i?.[c]?.url,u=a in t&&typeof t[a]=="function";!l&&!u&&s.push(a)}),s.length>0){let a=`DataProviders.comment is invalid. The following methods are missing or are not functions (and no corresponding config provided): ${s.join(", ")}.`;this.loggingService.catch(a);return}else this.commentAnnotationDataProvider$.next(t)}}catch(i){this.loggingService.catch("Error in CommentAnnotationsResolverService setCommentAnnotationDataProvider:",i)}}commentAnnotationDataProviderAvailable(){try{return!!this.commentAnnotationDataProvider$.getValue()}catch(t){return this.loggingService.catch("Error in CommentAnnotationsResolverService commentAnnotationDataProviderAvailable:",t),!1}}};e.\u0275fac=function(i){return new(i||e)(w(It),w(_e),w(Lt))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let n=e;return n})();var qo=(()=>{let e=class e{constructor(t,i,o){this.coreActionsService=t,this.loggingService=i,this.analyticsService=o,this.resolveTimeout=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 Y(null),this.reactionAnnotationById$=new Y({}),this.getReactionAnnotationById=s=>{try{return this.reactionAnnotationDataProviderAvailable()?this.reactionAnnotationById$.value?.[s]:void 0}catch(a){this.loggingService.catch("Error in ReactionAnnotationsResolverService getReactionAnnotationById:",a);return}};try{this.loggingService.log("ReactionAnnotationsResolverService initialized"),this.reactionAnnotationDataProvider$.subscribe(s=>{s&&(s.config?.resolveTimeout&&(this.resolveTimeout=s.config.resolveTimeout),s.config?.saveRetryConfig&&(this.retrySaveConfig=s.config.saveRetryConfig),s.config?.deleteRetryConfig&&(this.retryDeleteConfig=s.config.deleteRetryConfig),s.config?.getRetryConfig&&(this.retryGetConfig=s.config.getRetryConfig))})}catch(s){this.loggingService.catch("Error in ReactionAnnotationsResolverService constructor:",s)}}getProvider(){try{let t=this.reactionAnnotationDataProvider$.getValue();return t||void 0}catch(t){this.loggingService.catch("Error in ReactionAnnotationsResolverService getProvider:",t);return}}ngOnDestroy(){try{this.reactionAnnotationById$.next({})}catch(t){this.loggingService.catch("Error in ReactionAnnotationsResolverService ngOnDestroy:",t)}}resolveReactionAnnotations(s){return I(this,arguments,function*({request:t,uniqueId:i,moduleName:o}){try{if(this.loggingService.log("%c[WB] Calling ReactionAnnotationsResolverService FUNCTION: resolveReactionAnnotations","color: green;"),!this.reactionAnnotationDataProviderAvailable())return{};let a,c=!1,l=!1,u=()=>{a&&(clearTimeout(a),a=void 0,l=!0)};return new Promise((d,f)=>{a=setTimeout(()=>{if(!l){c=!0,u();let b=i||J();this.coreActionsService.triggerAction($.REACTION_RESOLVER,{event:L.Events.Resolver.REACTION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:b,methodName:_t.RESOLVE_REACTION_ANNOTATIONS,moduleName:o,source:"internal",payload:{error:new Error("Reaction annotation resolution timeout"),request:t}}),f(new Error("Reaction annotation resolution timeout"))}},this.reactionAnnotationDataProvider$.value?.config?.resolveTimeout||this.resolveTimeout);let g=this.getProvider();if(!g)return u(),d({});let p={},_=[...new Set(t.reactionAnnotationIds||[])],T=le(x({},t),{reactionAnnotationIds:_});I(this,null,function*(){try{if(_.length>0||t.documentIds?.length||t.folderId){let b=i||J();this.coreActionsService.triggerAction($.REACTION_RESOLVER,{event:L.Events.Resolver.REACTION_RESOLUTION_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:b,methodName:_t.RESOLVE_REACTION_ANNOTATIONS,moduleName:o,source:"internal",payload:{request:T}});let G=kt(()=>g?.config?.getConfig?.url?Ht(g.config.getConfig.url,g.config.getConfig.headers,T,!0,g.config.getConfig.credentials):g?.get?.(T)||Promise.resolve(void 0),"getReactionAnnotations",this.retryGetConfig).then(M=>c?{}:(u(),M&&M.statusCode!==200?(this.coreActionsService.triggerAction($.REACTION_RESOLVER,{event:L.Events.Resolver.REACTION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:b,methodName:_t.RESOLVE_REACTION_ANNOTATIONS,moduleName:o,source:"internal",payload:{result:M,request:T}}),this.loggingService.catch(M?.message??"Error in ReactionAnnotationsResolverService resolveReactionAnnotations:"),{}):M?.data)).catch(M=>{throw u(),M});try{p=(yield G)||{},this.analyticsService.trackEvent(L.Events.Resolver.REACTION_RESOLVER_GET,{sourceMethod:"resolveReactionAnnotations",source:"sdk",reactionAnnotationIds:_});let M={};Object.entries(p).forEach(([U,k])=>{let S=this.reactionAnnotationById$.value?.[U];S?S&&JSON.stringify(S)!==JSON.stringify(k)&&(M[U]=k):M[U]=k}),Object.keys(M).length>0&&this.reactionAnnotationById$.next(x(x({},this.reactionAnnotationById$.getValue()),M)),this.coreActionsService.triggerAction($.REACTION_RESOLVER,{event:L.Events.Resolver.REACTION_RESOLUTION_RESULT,timestamp:new Date().getTime(),uniqueId:b,methodName:_t.RESOLVE_REACTION_ANNOTATIONS,moduleName:o,source:"internal",payload:{result:M,request:T}}),d(M)}catch(M){let U=i||J();this.coreActionsService.triggerAction($.REACTION_RESOLVER,{event:L.Events.Resolver.REACTION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:U,methodName:_t.RESOLVE_REACTION_ANNOTATIONS,moduleName:o,source:"internal",payload:{error:M,request:T}}),c||f(M),d(p)}}else u(),d({})}catch(b){u();let G=i||J();this.coreActionsService.triggerAction($.REACTION_RESOLVER,{event:L.Events.Resolver.REACTION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:G,methodName:_t.RESOLVE_REACTION_ANNOTATIONS,moduleName:o,source:"internal",payload:{error:b,request:T}}),f(b)}})})}catch(a){this.loggingService.catch("Error in ReactionAnnotationsResolverService resolveReactionAnnotations:",a);let c=i||J();return this.coreActionsService.triggerAction($.REACTION_RESOLVER,{event:L.Events.Resolver.REACTION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:c,methodName:_t.RESOLVE_REACTION_ANNOTATIONS,moduleName:o,source:"internal",payload:{error:a,request:t}}),{}}})}saveReactionAnnotation(t,i){return I(this,null,function*(){try{this.loggingService.log("%c[WB] Calling ReactionAnnotationsResolverService FUNCTION: saveReactionAnnotation","color: green;");let o=this.getProvider();if(!this.reactionAnnotationDataProviderAvailable())throw new Error("Reaction annotation save data provider not available");let s=i||J();this.coreActionsService.triggerAction($.REACTION_RESOLVER,{event:L.Events.Resolver.REACTION_SAVE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:s,methodName:_t.SAVE_REACTION_ANNOTATION,source:"internal",payload:{request:t}});let a=JSON.parse(JSON.stringify(this.reactionAnnotationById$.getValue()));this.reactionAnnotationById$._value=x(x({},a),t);let c={reactionAnnotation:t,event:Qt.REACTION_ADD,metadata:Object.values(t??{})?.[0]?.metadata},l=yield kt(()=>o?.config?.saveConfig?.url?Ht(o.config.saveConfig.url,o.config.saveConfig.headers,c,!1,o.config.saveConfig.credentials):o?.save?.(c)||Promise.resolve(void 0),"saveReactionAnnotation",this.retrySaveConfig);return l&&l.statusCode!==200?(this.retrySaveConfig.revertOnFailure&&(this.reactionAnnotationById$._value=a),this.loggingService.catch(l?.message??"Error in ReactionAnnotationsResolverService saveReactionAnnotation:"),this.coreActionsService.triggerAction($.REACTION_RESOLVER,{event:L.Events.Resolver.REACTION_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:s,methodName:_t.SAVE_REACTION_ANNOTATION,source:"internal",payload:{error:l,request:t}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(L.Events.Resolver.REACTION_RESOLVER_SAVE,{sourceMethod:"saveReactionAnnotation",source:"sdk",reactionAnnotationIds:Object.keys(t),eventType:c.event}),this.coreActionsService.triggerAction($.REACTION_RESOLVER,{event:L.Events.Resolver.REACTION_SAVE_RESULT,timestamp:new Date().getTime(),uniqueId:s,methodName:_t.SAVE_REACTION_ANNOTATION,source:"internal",payload:{result:{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0},request:t}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0})}catch(o){this.loggingService.warn("Error in ReactionAnnotationsResolverService saveReactionAnnotation:",o);let s=i||J();return this.coreActionsService.triggerAction($.REACTION_RESOLVER,{event:L.Events.Resolver.REACTION_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:s,methodName:_t.SAVE_REACTION_ANNOTATION,source:"internal",payload:{error:o,request:t}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0}}})}deleteReactionAnnotation(t,i,o){return I(this,null,function*(){try{this.loggingService.log("%c[WB] Calling ReactionAnnotationsResolverService FUNCTION: deleteReactionAnnotation","color: green;");let s=this.getProvider();if(!this.reactionAnnotationDataProviderAvailable())throw new Error("Reaction annotation delete data provider not available");let a=JSON.parse(JSON.stringify(this.reactionAnnotationById$.getValue())),c=i??a?.[t]?.metadata,l=c?Cn(c):void 0,u=l?x({apiKey:l.apiKey??null,documentId:l.documentId??null,organizationId:l.organizationId??null},l.folderId&&{folderId:l.folderId}):void 0,d=o||J();this.coreActionsService.triggerAction($.REACTION_RESOLVER,{event:L.Events.Resolver.REACTION_DELETE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:d,methodName:_t.DELETE_REACTION_ANNOTATION,source:"internal",payload:{reactionAnnotationId:t.toString(),metadata:u}});let f=x({},a);delete f?.[t],this.reactionAnnotationById$._value=f;let g=yield kt(()=>{if(s?.config?.deleteConfig?.url){let p={reactionAnnotationId:t.toString(),metadata:u,event:Qt.REACTION_DELETE};return Ht(s.config.deleteConfig.url,s.config.deleteConfig.headers,p,!1,s.config.deleteConfig.credentials)}return s?.delete?.({reactionAnnotationId:t.toString(),metadata:u,event:Qt.REACTION_DELETE})||Promise.resolve(void 0)},"deleteReactionAnnotation",this.retryDeleteConfig);return g&&g.statusCode!==200?(this.retryDeleteConfig.revertOnFailure&&(this.reactionAnnotationById$._value=a),this.loggingService.catch(g?.message??"Error in ReactionAnnotationsResolverService deleteReactionAnnotation:"),this.coreActionsService.triggerAction($.REACTION_RESOLVER,{event:L.Events.Resolver.REACTION_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:d,methodName:_t.DELETE_REACTION_ANNOTATION,source:"internal",payload:{error:g,reactionAnnotationId:t.toString(),metadata:u}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(L.Events.Resolver.REACTION_RESOLVER_DELETE,{sourceMethod:"deleteReactionAnnotation",source:"sdk",reactionAnnotationId:t.toString()}),this.coreActionsService.triggerAction($.REACTION_RESOLVER,{event:L.Events.Resolver.REACTION_DELETE_RESULT,timestamp:new Date().getTime(),uniqueId:d,methodName:_t.DELETE_REACTION_ANNOTATION,source:"internal",payload:{result:{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0},reactionAnnotationId:t.toString(),metadata:u}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0})}catch(s){this.loggingService.warn("Error in ReactionAnnotationsResolverService deleteReactionAnnotation:",s);let a=o||J(),c=i?Cn(i):void 0;return this.coreActionsService.triggerAction($.REACTION_RESOLVER,{event:L.Events.Resolver.REACTION_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:a,methodName:_t.DELETE_REACTION_ANNOTATION,source:"internal",payload:{error:s,reactionAnnotationId:t.toString(),metadata:c}}),{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()):ue(void 0)}catch(t){return this.loggingService.catch("Error in ReactionAnnotationsResolverService getReactionAnnotationsById$:",t),ue(void 0)}}getAnnotationById(t){try{return this.reactionAnnotationDataProviderAvailable()?this.reactionAnnotationById$.getValue()?.[t]:void 0}catch(i){this.loggingService.catch("Error in ReactionAnnotationsResolverService getAnnotationById:",i);return}}setReactionAnnotationDataProvider(t){try{if(t){this.loggingService.log("Setting reaction annotation data provider");let i=t.config,o=[{method:"get",configKey:"getConfig"},{method:"save",configKey:"saveConfig"},{method:"delete",configKey:"deleteConfig"}],s=[];if(o.forEach(({method:a,configKey:c})=>{let l=i?.[c]?.url,u=a in t&&typeof t[a]=="function";!l&&!u&&s.push(a)}),s.length>0){let a=`DataProviders.reaction is invalid. The following methods are missing or are not functions (and no corresponding config provided): ${s.join(", ")}.`;this.loggingService.catch(a);return}else this.reactionAnnotationDataProvider$.next(t)}}catch(i){this.loggingService.catch("Error in ReactionAnnotationsResolverService setReactionAnnotationDataProvider:",i)}}reactionAnnotationDataProviderAvailable(){try{return!!this.reactionAnnotationDataProvider$.getValue()}catch(t){return this.loggingService.catch("Error in ReactionAnnotationsResolverService reactionAnnotationDataProviderAvailable:",t),!1}}};e.\u0275fac=function(i){return new(i||e)(w(It),w(_e),w(Lt))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let n=e;return n})();var Wh=(()=>{let e=class e{constructor(t,i,o){this.coreActionsService=t,this.loggingService=i,this.analyticsService=o,this.providers=new Map,this.retrySaveConfigs=new Map,this.retryDeleteConfigs=new Map,this.defaultRetryConfig={retryCount:0,retryDelay:0,revertOnFailure:!1};try{this.loggingService.log("AttachmentResolverService initialized")}catch(s){this.loggingService.catch("Error in AttachmentResolverService constructor:",s)}}getProvider(t){try{let i=t||"default";return this.providers.get(i)||void 0}catch(i){this.loggingService.catch("Error in AttachmentResolverService getProvider:",i);return}}getRetrySaveConfig(t){let i=t||"default";return this.retrySaveConfigs.get(i)||this.defaultRetryConfig}getRetryDeleteConfig(t){let i=t||"default";return this.retryDeleteConfigs.get(i)||this.defaultRetryConfig}makeAttachmentConfigBasedRequest(t,i,o,s,a){return I(this,null,function*(){try{let c=typeof i=="function"?yield i():i||{},l=new FormData;l.append("file",o);let u={attachment:{attachmentId:s.attachment.attachmentId,name:s.attachment.name,mimeType:s.attachment.mimeType},metadata:s.metadata,event:s.event};l.append("request",JSON.stringify(u));let d={};Object.entries(c).forEach(([p,_])=>{p.toLowerCase()!=="content-type"&&(d[p]=_)});let f=yield fetch(t,x({method:"POST",headers:d,body:l},a?{credentials:a}:{}));return f.ok?{data:(yield f.json())?.data??{},success:!0,statusCode:200}:(H.catch(`Error in makeAttachmentConfigBasedRequest: ${f.status} ${f.statusText}`),{data:{},success:!1,statusCode:f.status})}catch(c){return H.catch("Error in makeAttachmentConfigBasedRequest:",c),{data:{},success:!1,statusCode:500}}})}saveAttachment(t,i,o){return I(this,null,function*(){try{this.loggingService.log("%c[WB] Calling AttachmentResolverService FUNCTION: saveAttachment","color: green;");let s=this.getProvider(o);if(!this.attachmentDataProviderAvailable(o))throw new Error("Attachment save data provider not available");let a=this.getRetrySaveConfig(o),c=i||J();this.coreActionsService.triggerAction($.ATTACHMENT_RESOLVER,{event:L.Events.Resolver.ATTACHMENT_SAVE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:c,methodName:No.SAVE_ATTACHMENT,source:"internal",payload:{request:t}});let l=yield kt(()=>I(this,null,function*(){if(s?.config?.saveConfig?.url){let u=t.attachment,{file:d}=u,f=dS(u,["file"]);return this.makeAttachmentConfigBasedRequest(s.config.saveConfig.url,s.config.saveConfig.headers,d,{attachment:f,event:t.eventType,metadata:t.attachment.metadata},s.config.saveConfig.credentials)}return s?.save?.({attachment:t.attachment,event:t.eventType,metadata:t.attachment.metadata})||Promise.resolve(void 0)}),"saveAttachment",a);if(l?.statusCode!==200){this.loggingService.catch(l?.message??"Error in AttachmentResolverService saveAttachment:"),this.coreActionsService.triggerAction($.ATTACHMENT_RESOLVER,{event:L.Events.Resolver.ATTACHMENT_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:c,methodName:No.SAVE_ATTACHMENT,source:"internal",payload:{error:l,request:t}});return}return this.analyticsService.trackEvent(L.Events.Resolver.ATTACHMENT_RESOLVER_SAVE,{sourceMethod:"saveAttachment",source:"sdk",attachmentId:t.attachment.attachmentId,eventType:t.eventType}),this.coreActionsService.triggerAction($.ATTACHMENT_RESOLVER,{event:L.Events.Resolver.ATTACHMENT_SAVE_RESULT,timestamp:new Date().getTime(),uniqueId:c,methodName:No.SAVE_ATTACHMENT,source:"internal",payload:{result:l,request:t}}),l}catch(s){this.loggingService.warn("Error in AttachmentResolverService saveAttachment:",s);let a=i||J();this.coreActionsService.triggerAction($.ATTACHMENT_RESOLVER,{event:L.Events.Resolver.ATTACHMENT_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:a,methodName:No.SAVE_ATTACHMENT,source:"internal",payload:{error:s,request:t}});return}})}deleteAttachment(a,c,l){return I(this,arguments,function*({attachmentId:t,metadata:i},o,s){try{this.loggingService.log("%c[WB] Calling AttachmentResolverService FUNCTION: deleteAttachment","color: green;");let u=this.getProvider(s);if(!this.attachmentDataProviderAvailable(s))throw new Error("Attachment delete data provider not available");let d=i?x({apiKey:i.apiKey??null,documentId:i.documentId??null,organizationId:i.organizationId??null},i.folderId&&{folderId:i.folderId}):void 0,f=this.getRetryDeleteConfig(s),g=o||J();this.coreActionsService.triggerAction($.ATTACHMENT_RESOLVER,{event:L.Events.Resolver.ATTACHMENT_DELETE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:g,methodName:No.DELETE_ATTACHMENT,source:"internal",payload:{attachmentId:t,metadata:d}});let p=yield kt(()=>{if(u?.config?.deleteConfig?.url){let _={attachmentId:t,metadata:d,event:Qt.ATTACHMENT_DELETE};return Ht(u.config.deleteConfig.url,u.config.deleteConfig.headers,_,!1,u.config.deleteConfig.credentials)}return u?.delete?.({attachmentId:t,metadata:d,event:Qt.ATTACHMENT_DELETE})||Promise.resolve(void 0)},"deleteAttachment",f);return p?.statusCode!==200?(this.loggingService.catch(p?.message??"Error in AttachmentResolverService deleteAttachment:"),this.coreActionsService.triggerAction($.ATTACHMENT_RESOLVER,{event:L.Events.Resolver.ATTACHMENT_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:g,methodName:No.DELETE_ATTACHMENT,source:"internal",payload:{error:p,attachmentId:t,metadata:d}}),{revertOnFailure:f.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(L.Events.Resolver.ATTACHMENT_RESOLVER_DELETE,{sourceMethod:"deleteAttachment",source:"sdk",attachmentId:t}),this.coreActionsService.triggerAction($.ATTACHMENT_RESOLVER,{event:L.Events.Resolver.ATTACHMENT_DELETE_RESULT,timestamp:new Date().getTime(),uniqueId:g,methodName:No.DELETE_ATTACHMENT,source:"internal",payload:{result:{revertOnFailure:f.revertOnFailure,isSuccess:!0},attachmentId:t,metadata:d}}),{revertOnFailure:f.revertOnFailure,isSuccess:!0})}catch(u){this.loggingService.warn("Error in AttachmentResolverService deleteAttachment:",u);let d=this.getRetryDeleteConfig(s),f=o||J(),g=i?x({apiKey:i.apiKey??null,documentId:i.documentId??null,organizationId:i.organizationId??null},i.folderId&&{folderId:i.folderId}):void 0;return this.coreActionsService.triggerAction($.ATTACHMENT_RESOLVER,{event:L.Events.Resolver.ATTACHMENT_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:f,methodName:No.DELETE_ATTACHMENT,source:"internal",payload:{error:u,attachmentId:t,metadata:g}}),{revertOnFailure:d.revertOnFailure,isSuccess:!0}}})}setAttachmentDataProvider(t,i="default"){try{if(t){this.loggingService.log(`Setting attachment data provider for scope: ${i}`);let o=t.config,s=[{method:"save",configKey:"saveConfig"},{method:"delete",configKey:"deleteConfig"}],a=[];if(s.forEach(({method:c,configKey:l})=>{let u=o?.[l]?.url,d=c in t&&typeof t[c]=="function";!u&&!d&&a.push(c)}),a.length>0){let c=`DataProviders.attachment is invalid. The following methods are missing or are not functions (and no corresponding config provided): ${a.join(", ")}.`;this.loggingService.catch(c);return}else this.providers.set(i,t),t.config?.saveRetryConfig&&this.retrySaveConfigs.set(i,t.config.saveRetryConfig),t.config?.deleteRetryConfig&&this.retryDeleteConfigs.set(i,t.config.deleteRetryConfig)}}catch(o){this.loggingService.catch("Error in AttachmentResolverService setAttachmentDataProvider:",o)}}attachmentDataProviderAvailable(t){try{let i=t||"default";return this.providers.has(i)}catch(i){return this.loggingService.catch("Error in AttachmentResolverService attachmentDataProviderAvailable:",i),!1}}};e.\u0275fac=function(i){return new(i||e)(w(It),w(_e),w(Lt))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let n=e;return n})();var ec=(()=>{let e=class e{constructor(t,i,o,s){this.coreActionsService=t,this.loggingService=i,this.analyticsService=o,this.attachmentResolverService=s,this.resolveTimeout=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.recorderAnnotationDataProvider$=new Y(null),this.recorderAnnotationById$=new Y({}),this.additionalFields=[],this.uploadChunks=!1,this.getRecorderAnnotationById=a=>{try{return this.recorderAnnotationDataProviderAvailable()?this.recorderAnnotationById$.value?.[a]:void 0}catch(c){this.loggingService.catch("Error in RecorderAnnotationsResolverService getRecorderAnnotationById:",c);return}};try{this.loggingService.log("RecorderAnnotationsResolverService initialized"),this.recorderAnnotationDataProvider$.subscribe(a=>{a&&(a.config?.resolveTimeout&&(this.resolveTimeout=a.config.resolveTimeout),a.config?.saveRetryConfig&&(this.retrySaveConfig=a.config.saveRetryConfig),a.config?.deleteRetryConfig&&(this.retryDeleteConfig=a.config.deleteRetryConfig),a.config?.getRetryConfig&&(this.retryGetConfig=a.config.getRetryConfig),a.config?.additionalFields&&(this.additionalFields=a.config.additionalFields||[]),this.uploadChunks=a.uploadChunks??!1)})}catch(a){this.loggingService.catch("Error in RecorderAnnotationsResolverService constructor:",a)}}getProvider(){try{let t=this.recorderAnnotationDataProvider$.getValue();return t||void 0}catch(t){this.loggingService.catch("Error in RecorderAnnotationsResolverService getProvider:",t);return}}ngOnDestroy(){try{this.recorderAnnotationById$.next({})}catch(t){this.loggingService.catch("Error in RecorderAnnotationsResolverService ngOnDestroy:",t)}}resolveRecorderAnnotations(s){return I(this,arguments,function*({request:t,uniqueId:i,moduleName:o}){try{if(this.loggingService.log("%c[WB] Calling RecorderAnnotationsResolverService FUNCTION: resolveRecorderAnnotations","color: green;"),!this.recorderAnnotationDataProviderAvailable())return{};let a,c=!1,l=!1,u=()=>{a&&(clearTimeout(a),a=void 0,l=!0)};return new Promise((d,f)=>{a=setTimeout(()=>{if(!l){c=!0,u();let b=i||J();this.coreActionsService.triggerAction($.RECORDER_RESOLVER,{event:L.Events.Resolver.RECORDER_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:b,methodName:Tt.RESOLVE_RECORDER_ANNOTATIONS,moduleName:o,source:"internal",payload:{error:new Error("Recorder annotation resolution timeout"),request:t}}),f(new Error("Recorder annotation resolution timeout"))}},this.recorderAnnotationDataProvider$.value?.config?.resolveTimeout||this.resolveTimeout);let g=this.getProvider();if(!g)return u(),d({});let p={},_=[...new Set(t.recorderAnnotationIds||[])],T=le(x({},t),{recorderAnnotationIds:_});I(this,null,function*(){try{if(_.length>0||t.documentIds?.length){let b=i||J();this.coreActionsService.triggerAction($.RECORDER_RESOLVER,{event:L.Events.Resolver.RECORDER_RESOLUTION_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:b,methodName:Tt.RESOLVE_RECORDER_ANNOTATIONS,moduleName:o,source:"internal",payload:{request:T}});let G=kt(()=>g?.config?.getConfig?.url?Ht(g.config.getConfig.url,g.config.getConfig.headers,T,!0,g.config.getConfig.credentials):g?.get?.(T)||Promise.resolve(void 0),"getRecorderAnnotations",this.retryGetConfig).then(M=>c?{}:(u(),M&&M.statusCode!==200?(this.coreActionsService.triggerAction($.RECORDER_RESOLVER,{event:L.Events.Resolver.RECORDER_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:b,methodName:Tt.RESOLVE_RECORDER_ANNOTATIONS,moduleName:o,source:"internal",payload:{result:M,request:T}}),this.loggingService.catch(M?.message??"Error in RecorderAnnotationsResolverService resolveRecorderAnnotations:"),{}):M?.data)).catch(M=>{throw u(),M});try{p=(yield G)||{},this.analyticsService.trackEvent(L.Events.Resolver.RECORDER_RESOLVER_GET,{sourceMethod:"resolveRecorderAnnotations",source:"sdk",recorderAnnotationIds:_});let M={};Object.entries(p).forEach(([U,k])=>{let S=this.recorderAnnotationById$.value?.[U];S?S&&JSON.stringify(S)!==JSON.stringify(k)&&(M[U]=k):M[U]=k}),Object.keys(M).length>0&&this.recorderAnnotationById$.next(x(x({},this.recorderAnnotationById$.getValue()),M)),this.coreActionsService.triggerAction($.RECORDER_RESOLVER,{event:L.Events.Resolver.RECORDER_RESOLUTION_RESULT,timestamp:new Date().getTime(),uniqueId:b,methodName:Tt.RESOLVE_RECORDER_ANNOTATIONS,moduleName:o,source:"internal",payload:{result:M,request:T}}),d(M)}catch(M){let U=i||J();this.coreActionsService.triggerAction($.RECORDER_RESOLVER,{event:L.Events.Resolver.RECORDER_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:U,methodName:Tt.RESOLVE_RECORDER_ANNOTATIONS,moduleName:o,source:"internal",payload:{error:M,request:T}}),c||f(M),d(p)}}else u(),d({})}catch(b){u();let G=i||J();this.coreActionsService.triggerAction($.RECORDER_RESOLVER,{event:L.Events.Resolver.RECORDER_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:G,methodName:Tt.RESOLVE_RECORDER_ANNOTATIONS,moduleName:o,source:"internal",payload:{error:b,request:T}}),f(b)}})})}catch(a){this.loggingService.catch("Error in RecorderAnnotationsResolverService resolveRecorderAnnotations:",a);let c=i||J();return this.coreActionsService.triggerAction($.RECORDER_RESOLVER,{event:L.Events.Resolver.RECORDER_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:c,methodName:Tt.RESOLVE_RECORDER_ANNOTATIONS,moduleName:o,source:"internal",payload:{error:a,request:t}}),{}}})}saveRecorderAnnotation(t,i){return I(this,null,function*(){try{this.loggingService.log("%c[WB] Calling RecorderAnnotationsResolverService FUNCTION: saveRecorderAnnotation","color: green;");let o=this.getProvider();if(!this.recorderAnnotationDataProviderAvailable())throw new Error("Recorder annotation save data provider not available");let s=i||J();this.coreActionsService.triggerAction($.RECORDER_RESOLVER,{event:L.Events.Resolver.RECORDER_SAVE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:s,methodName:Tt.SAVE_RECORDER_ANNOTATION,source:"internal",payload:{request:t}});let a=JSON.parse(JSON.stringify(this.recorderAnnotationById$.getValue()));this.recorderAnnotationById$._value=x(x({},a),t.recorderAnnotation);let c=yield kt(()=>{if(o?.config?.saveConfig?.url){let l={recorderAnnotation:t.recorderAnnotation,event:t.eventType,metadata:Object.values(t.recorderAnnotation??{})?.[0]?.metadata};return Ht(o.config.saveConfig.url,o.config.saveConfig.headers,l,!1,o.config.saveConfig.credentials)}return o?.save?.({recorderAnnotation:t.recorderAnnotation,event:t.eventType,metadata:Object.values(t.recorderAnnotation??{})?.[0]?.metadata})||Promise.resolve(void 0)},"saveRecorderAnnotation",this.retrySaveConfig);return c&&c.statusCode!==200?(this.retrySaveConfig.revertOnFailure&&(this.recorderAnnotationById$._value=a),this.loggingService.catch(c?.message??"Error in RecorderAnnotationsResolverService saveRecorderAnnotation:"),this.coreActionsService.triggerAction($.RECORDER_RESOLVER,{event:L.Events.Resolver.RECORDER_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:s,methodName:Tt.SAVE_RECORDER_ANNOTATION,source:"internal",payload:{error:c,request:t}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(L.Events.Resolver.RECORDER_RESOLVER_SAVE,{sourceMethod:"saveRecorderAnnotation",source:"sdk",recorderAnnotationIds:Object.keys(t.recorderAnnotation),eventType:t.eventType}),this.coreActionsService.triggerAction($.RECORDER_RESOLVER,{event:L.Events.Resolver.RECORDER_SAVE_RESULT,timestamp:new Date().getTime(),uniqueId:s,methodName:Tt.SAVE_RECORDER_ANNOTATION,source:"internal",payload:{result:{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0},request:t}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0})}catch(o){this.loggingService.warn("Error in RecorderAnnotationsResolverService saveRecorderAnnotation:",o);let s=i||J();return this.coreActionsService.triggerAction($.RECORDER_RESOLVER,{event:L.Events.Resolver.RECORDER_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:s,methodName:Tt.SAVE_RECORDER_ANNOTATION,source:"internal",payload:{error:o,request:t}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0}}})}deleteRecorderAnnotation(t,i,o){return I(this,null,function*(){try{this.loggingService.log("%c[WB] Calling RecorderAnnotationsResolverService FUNCTION: deleteRecorderAnnotation","color: green;");let s=this.getProvider();if(!this.recorderAnnotationDataProviderAvailable())throw new Error("Recorder annotation delete data provider not available");let a=this.recorderAnnotationById$.getValue(),l=a?.[t]?.metadata??(i?Cn(i):void 0),u=l?x({apiKey:l.apiKey??null,documentId:l.documentId??null,organizationId:l.organizationId??null},l.folderId&&{folderId:l.folderId}):void 0,d=o||J();this.coreActionsService.triggerAction($.RECORDER_RESOLVER,{event:L.Events.Resolver.RECORDER_DELETE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:d,methodName:Tt.DELETE_RECORDER_ANNOTATION,source:"internal",payload:{recorderAnnotationId:t.toString(),metadata:u}});let f=x({},a);delete f?.[t],this.recorderAnnotationById$._value=f;let g=yield kt(()=>{if(s?.config?.deleteConfig?.url){let p={recorderAnnotationId:t.toString(),metadata:u,event:Qt.RECORDER_ANNOTATION_DELETE};return Ht(s.config.deleteConfig.url,s.config.deleteConfig.headers,p,!1,s.config.deleteConfig.credentials)}return s?.delete?.({recorderAnnotationId:t.toString(),metadata:u,event:Qt.RECORDER_ANNOTATION_DELETE})||Promise.resolve(void 0)},"deleteRecorderAnnotation",this.retryDeleteConfig);return g&&g.statusCode!==200?(this.retryDeleteConfig.revertOnFailure&&(this.recorderAnnotationById$._value=a),this.loggingService.catch(g?.message??"Error in RecorderAnnotationsResolverService deleteRecorderAnnotation:"),this.coreActionsService.triggerAction($.RECORDER_RESOLVER,{event:L.Events.Resolver.RECORDER_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:d,methodName:Tt.DELETE_RECORDER_ANNOTATION,source:"internal",payload:{error:g,recorderAnnotationId:t.toString(),metadata:u}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(L.Events.Resolver.RECORDER_RESOLVER_DELETE,{sourceMethod:"deleteRecorderAnnotation",source:"sdk",recorderAnnotationId:t.toString()}),this.coreActionsService.triggerAction($.RECORDER_RESOLVER,{event:L.Events.Resolver.RECORDER_DELETE_RESULT,timestamp:new Date().getTime(),uniqueId:d,methodName:Tt.DELETE_RECORDER_ANNOTATION,source:"internal",payload:{result:{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0},recorderAnnotationId:t.toString(),metadata:u}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0})}catch(s){this.loggingService.warn("Error in RecorderAnnotationsResolverService deleteRecorderAnnotation:",s);let a=o||J(),c=i?Cn(i):void 0;return this.coreActionsService.triggerAction($.RECORDER_RESOLVER,{event:L.Events.Resolver.RECORDER_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:a,methodName:Tt.DELETE_RECORDER_ANNOTATION,source:"internal",payload:{error:s,recorderAnnotationId:t.toString(),metadata:c}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0}}})}getRecorderAnnotationsById$(){try{return this.recorderAnnotationDataProviderAvailable()?(this.loggingService.log("%c[WB] Calling RecorderAnnotationsResolverService FUNCTION: getRecorderAnnotationsById$","color: green;"),this.recorderAnnotationById$.asObservable()):ue(void 0)}catch(t){return this.loggingService.catch("Error in RecorderAnnotationsResolverService getRecorderAnnotationsById$:",t),ue(void 0)}}getAnnotationById(t){try{return this.recorderAnnotationDataProviderAvailable()?this.recorderAnnotationById$.getValue()?.[t]:void 0}catch(i){this.loggingService.catch("Error in RecorderAnnotationsResolverService getAnnotationById:",i);return}}getAdditionalFields(){try{return this.additionalFields}catch(t){return this.loggingService.catch("Error in RecorderAnnotationsResolverService getAdditionalFields:",t),this.additionalFields}}shouldUploadChunks(){return this.uploadChunks}shouldUploadFullRecording(){return this.recorderAnnotationDataProviderAvailable()&&!this.uploadChunks}setRecorderAnnotationDataProvider(t){try{if(t){this.loggingService.log("Setting recorder annotation data provider");let i=t.config,o=[{method:"get",configKey:"getConfig"},{method:"save",configKey:"saveConfig"},{method:"delete",configKey:"deleteConfig"}],s=[];if(o.forEach(({method:a,configKey:c})=>{let l=i?.[c]?.url,u=a in t&&typeof t[a]=="function";!l&&!u&&s.push(a)}),s.length>0){let a=`DataProviders.recorder is invalid. The following methods are missing or are not functions (and no corresponding config provided): ${s.join(", ")}.`;this.loggingService.catch(a);return}else t.storage&&this.attachmentResolverService.setAttachmentDataProvider(t.storage,"recorder"),this.attachmentResolverService.attachmentDataProviderAvailable("recorder")||this.loggingService.catch("Recording resolver is configured without storage resolver. Recording files (chunks, thumbnails) will be stored on Velt's infrastructure. Configure storage resolver for full self-hosting.",void 0,void 0,!0),this.recorderAnnotationDataProvider$.next(t)}}catch(i){this.loggingService.catch("Error in RecorderAnnotationsResolverService setRecorderAnnotationDataProvider:",i)}}recorderAnnotationDataProviderAvailable(){try{return!!this.recorderAnnotationDataProvider$.getValue()}catch(t){return this.loggingService.catch("Error in RecorderAnnotationsResolverService recorderAnnotationDataProviderAvailable:",t),!1}}};e.\u0275fac=function(i){return new(i||e)(w(It),w(_e),w(Lt),w(Wh))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let n=e;return n})();var qy=class{};var zh=(()=>{let e=class e{constructor(t,i,o,s,a,c,l,u,d,f,g,p){this.analyticsService=t,this.authService=i,this.databaseService=o,this.domService=s,this.configService=a,this.loggingService=c,this.commentResolverService=l,this.reactionResolverService=u,this.recorderResolverService=d,this.coreActionsService=f,this.functions=g,this.serviceBook=p,this.documentPaths$=new Y(null),this.docContext$=new Y(null),this.documentIds$=new Y([]),this.organizationConfig$=new Y(null),this.firestorePaths$=new Y(null),this.location$=new Y(null),this.excludedLocationIds$=new Y([]),this.organizationMetadata$=new Y(null),this.documentMetadata$=new Y(null),this.locationMetadata$=new Y(null),this.customerMetadata$=new Y(null),this.currentDocumentId=null,this.isCustomDocId=!1,this.locations$=new Y({}),this.preDocumentIdChangeFunctions=new Map,this.draftDocuments=[],this.clientDocumentMetadataMap={},this.uiState=new Y({}),this.lastSetDocumentIdExecutionTime=0,this.lastSetDocumentIdCallTime=0,this.setDocumentIdSubject=new Ot,this.DEBOUNCE_TIME=5e3,this.currentDebounceTime=this.DEBOUNCE_TIME,this.MAX_QUEUE_SIZE=100,this.queueSize=0,this.isDocumentIdInDebounceQueue=!1,this.currentValidationToken=null,this.pendingDocumentIds=[],this.pendingOptions={},this.draftLocationMap={locations:[],options:void 0};try{this.loggingService.log("%c[WB] Creating CLASS: DocService","color: blue;"),this.domService.setDocService(this),this.authService.setDocService(this),this.serviceBook.observe(pd).subscribe(_=>{this.commentService=_??void 0}),B1(()=>this.documentPaths$.value?.clientDocumentId),this.setDocumentIdSubject.pipe(SS(()=>Ci(this.currentDebounceTime))).subscribe({next:_=>I(this,null,function*(){try{yield this.setDocumentIdImpl(_.documentId,_.clientOrganizationId,_.options),this.lastSetDocumentIdExecutionTime=Date.now(),this.isDocumentIdInDebounceQueue=!1,this.draftLocationMap.locations.length&&(yield this.setLocations({locations:this.draftLocationMap.locations,options:this.draftLocationMap.options,source:"internal"})),this.draftLocationMap={locations:[],options:void 0}}finally{this.queueSize--}}),error:_=>{this.loggingService.catch("Error in setDocumentId subscription:",_),this.queueSize--}}),this.databaseService.getDb().pipe(Ct(_=>!!_),Nt(1)).subscribe(_=>{_&&(this.db=_)}),this.configService.getApiKey$().subscribe(_=>{if(this.apiKey=_,this.apiKey){if(!this.isCustomDocId){let T=HT(window.location.href);this.currentUrl=T}this.analyticsService.updateDefaultProperties({apiKey:_})}}),this.authService.getUser$().subscribe(_=>I(this,null,function*(){if(_&&(this.analyticsService.updateDefaultProperties({organizationId:_?.organizationId,clientOrganizationId:_?.clientOrganizationId}),this.draftDocuments?.length?(yield this.setDocuments({documents:this.draftDocuments,options:this.draftOptions??void 0,source:"internal"}),this.draftDocuments=[],this.draftOptions=void 0,this.draftLocationMap.locations.length&&(yield this.setLocations({locations:this.draftLocationMap.locations,options:this.draftLocationMap.options,source:"internal"}).then(()=>this.draftLocationMap={locations:[],options:void 0}))):this.documentPaths$?.value&&_?.organizationId&&this.documentPaths$.value?.organizationId!==_?.organizationId&&(yield this.setDocuments({documents:this.documentIds$.value.length?this.documentIds$.value.map(T=>({id:T.clientDocumentId})):[{id:this.documentPaths$.value?.clientDocumentId}],options:void 0,source:"internal"})),setTimeout(()=>{this.documentPaths$.value||this.loggingService.catch("Error in DocService constructor:","Please set document id to continue.")},1e4),_?.organizationId&&_?.clientOrganizationId)){let T={organizationId:_?.organizationId,clientOrganizationId:_?.clientOrganizationId};this.getOrganizationConfig()||this.setOrganizationConfig({organizationId:_?.organizationId,clientOrganizationId:_?.clientOrganizationId}),yield this.updateOrganizationMetadata(T)}})),this.documentPaths$.subscribe(_=>{let T={documentId:_?.documentId,clientDocumentId:_?.clientDocumentId,folderId:_?.folderId,allDocuments:_?.allDocuments,veltFolderId:_?.veltFolderId};_?.organizationId&&(T.organizationId=_.organizationId,T.clientOrganizationId=_.clientOrganizationId),this.analyticsService.updateDefaultProperties(T),this.domService.resetSelectedAnnotationsMap()}),this.location$.subscribe(_=>{this.analyticsService.updateDefaultProperties({clientLocation:_?.location,locationId:_?.locationId})}),this.organizationMetadata$.subscribe(_=>{this.authService.setUserOrganization(_?.[this.documentPaths$.value?.organizationId])}),this.documentPaths$.pipe(Ct(_=>!!_),Nt(1)).subscribe(()=>{try{this.subscribeToCustomerMetadata()}catch(_){this.loggingService.catch("Error in DocService subscribeToCustomerMetadata:",_)}},_=>{this.loggingService.catch("Error in DocService subscribeToCustomerMetadata:",_)}),this.loggingService.log("%c[WB] Creating CLASS: DocService 2","color: blue;"),this.onWindowPopstate(),this.onWindowClick()}catch(_){this.loggingService.catch("Error in DocService constructor:",_)}}getOptionsFromDocumentPaths(){try{return this.documentPaths$.value?{organizationId:this.documentPaths$.value?.clientOrganizationId,folderId:this.documentPaths$.value?.folderId,allDocuments:this.documentPaths$.value?.allDocuments,locationId:this.documentPaths$.value?.locationId,optimisticPermissions:this.documentPaths$.value?.optimisticPermissions}:null}catch(t){return this.loggingService.catch("Error in getOptionsFromDocumentPaths:",t),null}}clearCacheOnUserCascade(){this.loggingService.log("%c[WB] Calling FUNCTION: clearCacheOnUserCascade in DocService","color: green;");try{this.setOrganizationConfig(null),this.organizationMetadata$.next(null),this.customerMetadata$.next(null),this.customerMetadataSubscription?.unsubscribe(),this.documentPaths$.value&&(this.draftOptions=this.getOptionsFromDocumentPaths(),this.draftDocuments=this.documentIds$.value.map(t=>({id:t.clientDocumentId})),this.draftLocationMap={locations:[this.location$.value?.location??null,...Object.values(this.locations$.value||{}).map(t=>t.location)].filter(t=>t!==null),options:{rootLocationId:this.location$.value?.location?.id}},this.currentDocumentId=null,this.documentPaths$.next(null),this.firestorePaths$.next(null)),this.unsetDocuments({source:"internal"})}catch(t){this.loggingService.catch("Error in DocService clearCacheOnUserCascade: ",t)}}setUsersService(t){try{this.usersService=t}catch(i){this.loggingService.catch("Error in setUsersService:",i)}}setCommonDbService(t){try{this.commonDbService=t}catch(i){this.loggingService.catch("Error in setCommonDbService:",i)}}setUserPermissionService(t){try{this.userPermissionService=t}catch(i){this.loggingService.catch("Error in setUserPermissionService:",i)}}setCommentService(t){try{this.commentService=t}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 t=HT(location.href);this.currentUrl!==t&&(this.currentUrl=t,!this.isCustomDocId&&this.apiKey&&this.loggingService.log("current url in doc service",this.currentUrl))},t=>{this.loggingService.catch("Error in DocService onWindowPopstate subscription: ",t)})}catch(t){this.loggingService.catch("Error in onWindowPopstate: ",t)}}onWindowClick(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowClick","color: green;");try{this.domService.onWindowClick$().subscribe(()=>{let t=HT(location.href);this.currentUrl!==t&&(this.currentUrl=t,this.isCustomDocId||this.loggingService.log("current url in doc service",this.currentUrl))},t=>{this.loggingService.catch("Error in DocService onWindowClick subscription: ",t)})}catch(t){this.loggingService.catch("Error in onWindowClick: ",t)}}setDocument(a){return I(this,arguments,function*({documentId:t,documentMetadata:i,options:o,source:s="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocument","color: green;"),s==="internal"&&this.analyticsService.trackEvent(L.Events.Core.SET_DOCUMENTS_TRIGGERED,{payload:{id:t,documentMetadata:i,methodName:"setDocument",source:s}}),this.coreActionsService.triggerAction($.INIT_UPDATE,{event:L.Events.Core.SET_DOCUMENTS_TRIGGERED,methodName:kn.SET_DOCUMENTS,source:s,payload:{documentId:t,documentMetadata:i,options:o}}),yield this.setDocumentsImpl({documents:[{id:t,metadata:i}],options:x({organizationId:i?.organizationId},o??{}),source:s})}catch(c){this.loggingService.catch("Error in DocService setDocument:",c)}})}shouldSetDocumentsAgain(t,i={}){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: shouldSetDocumentsAgain","color: green;"),this.pendingDocumentIds.length>0&&t.length===this.pendingDocumentIds.length&&t.every(d=>this.pendingDocumentIds.includes(d.id))&&ki(i,this.pendingOptions))return!1;let o=this.documentPaths$.value?.clientDocumentId,s=i?.rootDocumentId??t[0]?.id,a=this.documentIds$.value.map(u=>u.clientDocumentId),c=jT(this.getOptionsFromDocumentPaths()??{})??{};return!t.every(u=>a.includes(u.id))||!ki(c,i)||o!==s}catch(o){return this.loggingService.catch("Error in DocService shouldSetDocumentsAgain:",o),!0}}getDocumentIdsFromDocuments({documents:t,setClientDocumentMetadataMap:i=!1}){try{let o=[];return t.forEach(s=>{let a=s.id,c=`${Tr(a)}`;i&&s?.metadata&&typeof s.metadata=="object"&&(this.clientDocumentMetadataMap[a]=s.metadata),o.push({documentId:c,clientDocumentId:a})}),o}catch(o){return this.loggingService.catch("Error in DocService getDocumentIdsFromDocuments:",o),[]}}setDocuments(a){return I(this,arguments,function*({documents:t,options:i,source:o="internal",skipPermissionValidation:s=!1}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocuments","color: green;"),o==="internal"&&this.analyticsService.trackEvent(L.Events.Core.SET_DOCUMENTS_TRIGGERED,{payload:{documents:t,options:i,methodName:"setDocuments",source:o}}),this.coreActionsService.triggerAction($.INIT_UPDATE,{event:L.Events.Core.SET_DOCUMENTS_TRIGGERED,methodName:kn.SET_DOCUMENTS,source:o,payload:{documents:t,options:i}}),yield this.setDocumentsImpl({documents:t,options:i??{},source:o,skipPermissionValidation:s})}catch(c){this.loggingService.catch("Error in DocService setDocuments:",c)}})}setRootDocument(o){return I(this,arguments,function*({document:t,source:i="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setRootDocument","color: green;"),this.coreActionsService.triggerAction($.INIT_UPDATE,{event:L.Events.Core.SET_ROOT_DOCUMENT_TRIGGERED,methodName:kn.SET_ROOT_DOCUMENT,source:i,payload:{document:t}});let s=this.getOptionsFromDocumentPaths()??{},a=this.documentIds$.value.map(c=>c.clientDocumentId);if(!a.includes(t.id)){let c=[...a.map(u=>({id:u})),{id:t.id}],l=this.getDocumentIdsFromDocuments({documents:c,setClientDocumentMetadataMap:!0});this.documentIds$.next(l)}yield this.setDocumentIdImpl(t.id,this.documentPaths$.value?.clientOrganizationId,s)}catch(s){this.loggingService.catch("Error in DocService setRootDocument:",s)}})}setDocContext(t){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocContext","color: green;");let i=JSON.parse(JSON.stringify(t??null));this.docContext$.next(i)}catch(i){this.loggingService.catch("Error in setDocContext: ",i)}}getDocContext(){return this.docContext$.getValue()}getDocContext$(){return this.docContext$.asObservable().pipe(it(Ft))}getProcessedDocContext(){return GV(this.getDocContext())}filterRelevantDocuments(s){return I(this,arguments,function*({options:t,documentIds:i,skipPermissionValidation:o=!1}){try{let a=this.authService.getUser();return!a||!this.commonDbService?.shouldUseFirestore()||(i=yield this.fetchDocumentsFromFolder(t,i,a),yield this.handlePermissionProvider(t,i,a),i=yield this.filterDocumentsByPermissions(t,i,a,o),i=i.slice(0,50)),i}catch(a){return this.loggingService.catch("Error in DocService filterRelevantDocuments:",a),i}})}fetchDocumentsFromFolder(t,i,o){return I(this,null,function*(){if(!t?.folderId||!t?.allDocuments)return i;try{let s=Dr(this.functions,Ir({url:st?.cloudFunction?.sdkProxy,apiProxyDomain:this.configService?.getApiProxyDomain()}));(yield Ad({methodName:"getDocuments",data:{type:"getDocuments",metadata:{organizationId:t?.organizationId??o?.clientOrganizationId,folderId:t?.folderId}},getSdkProxy:s,userId:o?.userId??""}))?.data?.forEach(c=>{i.find(l=>l.clientDocumentId===c.id)||i.push({documentId:da(c.id),clientDocumentId:c.id})})}catch(s){this.loggingService.warn("Error in DocService fetchDocumentsFromFolder:",s)}return i})}buildPermissionRequests(t,i,o){try{let s=[];return t.organizationId&&t.organizationId!==o.clientOrganizationId&&s.push({userId:o.userId,resource:{id:t.organizationId,type:di.ORGANIZATION,source:Un.SET_DOCUMENTS,organizationId:t.organizationId,context:t?.context}}),t.folderId&&s.push({userId:o.userId,resource:{id:t.folderId,type:di.FOLDER,source:Un.SET_DOCUMENTS,organizationId:t?.organizationId??o?.clientOrganizationId??"",context:t?.context}}),i&&i.forEach(a=>{s.push({userId:o.userId,resource:x({id:a.clientDocumentId,type:di.DOCUMENT,source:Un.SET_DOCUMENTS,organizationId:t?.organizationId??o?.clientOrganizationId??"",context:t?.context},t?.folderId&&{parentFolderId:t.folderId})})}),t?.context&&this.userPermissionService?.getIsContextEnabled()&&$V({input:t?.context}).forEach(c=>{let l=JSON.stringify(c.access);s.push({userId:o.userId,resource:{id:l,type:di.CONTEXT,source:Un.SET_DOCUMENTS,organizationId:t?.organizationId??o?.clientOrganizationId??"",context:c}})}),s}catch(s){return this.loggingService.catch("Error in buildPermissionRequests:",s),[]}}processAccessibleContexts(t,i){try{if(!t?.success||!t?.data?.length||!this.userPermissionService?.getIsContextEnabled())return;let o=t.data.filter(s=>s.type===di.CONTEXT&&s.hasAccess).map(s=>s.resourceId);if(this.loggingService.logContext("[CONTEXT] processAccessibleContexts called with accessibleContextIds:",JSON.parse(JSON.stringify(o??"nil"))),o?.length){let s=i.filter(c=>o.includes(c.resource.id)).map(c=>c.resource.context).filter(c=>!!c),a=jV({input:s});this.loggingService.logContext("[CONTEXT] processAccessibleContexts called with accessibleContext:",JSON.parse(JSON.stringify(a??"nil"))),a?.access&&(this.loggingService.logContext("[CONTEXT] setting accessibleContext in docContext:",JSON.parse(JSON.stringify(a??"nil"))),this.setDocContext(a))}}catch(o){this.loggingService.catch("Error in processAccessibleContexts:",o)}}handlePermissionProvider(t,i,o){return I(this,null,function*(){if(this.userPermissionService?.isPermissionProviderAvailable())try{this.loggingService.logContext("[CONTEXT] handlePermissionProvider called with options:",JSON.parse(JSON.stringify(t??"nil")),"documentIds:",JSON.parse(JSON.stringify(i??"nil")),"user:",JSON.parse(JSON.stringify(o??"nil")));let s=this.buildPermissionRequests(t,i,o),a=J();this.coreActionsService.triggerAction($.PERMISSION_PROVIDER,{event:L.Events.PermissionProvider.RESOURCE_ACCESS_REQUEST_FORMED,methodName:Un.SET_DOCUMENTS,uniqueId:a,timestamp:new Date().getTime(),source:"internal",payload:{requests:s}}),this.userPermissionService?.cancelPendingRevokes(s);let c=yield this.userPermissionService?.onResourceAccessRequired({requests:s,uniqueId:a,methodName:Un.SET_DOCUMENTS,fromCache:!1});this.loggingService.logContext("[CONTEXT] handlePermissionProvider called with res:",JSON.parse(JSON.stringify(c??"nil")),"requests:",JSON.parse(JSON.stringify(s??"nil"))),this.processAccessibleContexts(c,s)}catch(s){this.loggingService.catch("Error in handlePermissionProvider:",s)}})}filterDocumentsByPermissions(t,i,o,s=!1){return I(this,null,function*(){if(s)return i;if(this.loggingService.logContext("[CONTEXT] filterDocumentsByPermissions called with options:",JSON.parse(JSON.stringify(t??"nil")),"documentIds:",JSON.parse(JSON.stringify(i??"nil")),"user:",JSON.parse(JSON.stringify(o??"nil"))),!(t?.optimisticPermissions!==!1))return yield this.validateAndFilterPermissions(t,i,o);let c=this.currentValidationToken,l=[...i];return c&&this.validatePermissionsInBackground(t,i,o,c),l})}validateAndFilterPermissions(t,i,o){return I(this,null,function*(){try{let s=t?.organizationId??o?.clientOrganizationId,a=yield this.userPermissionService?.getUserPermissions({organizationId:s,documentIds:i.map(u=>u.clientDocumentId),folderIds:t?.folderId?[t?.folderId]:[]});if(!a)return i;this.userPermissionService?.setCurrentUserPermissions(a),s&&a?.[o.userId]?.organization?.[s]?.errorCode===Oo.PERMISSION_DENIED&&this.loggingService.catch(`User does not have access to organization: ${s}`,void 0,void 0,!0),t?.folderId&&a?.[o.userId]?.folders?.[t?.folderId]?.errorCode===Oo.PERMISSION_DENIED&&this.loggingService.catch(`User does not have access to folder: ${t?.folderId}`,void 0,void 0,!0);let c=new Set;Object.entries(a?.[o.userId]?.documents??{}).forEach(([u,d])=>{d?.errorCode===Oo.PERMISSION_DENIED&&c.add(u)}),c.size>0&&(this.loggingService.catch(`User does not have access to documents: ${[...c].join(", ")}`,void 0,void 0,!0),this.coreActionsService.triggerAction($.ERROR,{event:L.Events.Core.SDK_ERROR,sourceMethod:"validateAndFilterPermissions",message:"Access denied to documents in strict validation mode",documentIds:[...c],userId:o.userId,timestamp:new Date().getTime()}));let l=i.filter(u=>!c.has(u.clientDocumentId));return l.length===0&&i.length>0&&this.loggingService.catch("Error in validateAndFilterPermissions: All documents provided are denied"),l}catch(s){return this.loggingService.catch("Error in validateAndFilterPermissions:",s),i}})}validatePermissionsInBackground(t,i,o,s){let a=t?.organizationId??o?.clientOrganizationId;this.userPermissionService?.getUserPermissions({organizationId:a,documentIds:i.map(c=>c.clientDocumentId),folderIds:t?.folderId?[t?.folderId]:[]}).then(c=>{if(this.currentValidationToken===s&&c){this.userPermissionService?.setCurrentUserPermissions(c);let l=[];Object.entries(c?.[o.userId]?.documents??{}).forEach(([u,d])=>{d?.errorCode===Oo.PERMISSION_DENIED&&l.push(u)}),a&&c?.[o.userId]?.organization?.[a]?.errorCode===Oo.PERMISSION_DENIED&&this.loggingService.catch(`User does not have access to organization: ${a}`,void 0,void 0,!0),t?.folderId&&c?.[o.userId]?.folders?.[t?.folderId]?.errorCode===Oo.PERMISSION_DENIED&&this.loggingService.catch(`User does not have access to folder: ${t?.folderId}`,void 0,void 0,!0),l.length>0&&(this.loggingService.catch(`User does not have access to documents: ${l.join(", ")}`,void 0,void 0,!0),this.handleDeniedDocumentAccess(l,o,s))}}).catch(c=>{this.loggingService.catch("Error in background permission validation:",c)})}handleDeniedDocumentAccess(t,i,o){try{if(this.currentValidationToken!==o)return;let s=this.documentPaths$.value;this.coreActionsService.triggerAction($.ERROR,{event:L.Events.Core.SDK_ERROR,sourceMethod:"handleDeniedDocumentAccess",message:"Access denied to document after optimistic load",documentIds:t,userId:i.userId,timestamp:new Date().getTime()});let a=this.documentIds$.value||[],c=a.filter(l=>!t.includes(l.clientDocumentId));c.length!==a.length&&(c.length>0?this.setDocuments({documents:c.map(l=>({id:l.clientDocumentId})),options:{organizationId:s?.clientOrganizationId},source:"internal",skipPermissionValidation:!0}):(this.loggingService.catch("Error in DocService handleDeniedDocumentAccess: Documents provided are all denied"),this.coreActionsService.triggerAction($.ERROR,{event:L.Events.Core.SDK_ERROR,sourceMethod:"handleDeniedDocumentAccess",message:"All documents provided are denied",documentIds:t,userId:i.userId,timestamp:new Date().getTime()}),this.unsetDocuments({source:"internal"})))}catch(s){this.loggingService.catch("Error in handleDeniedDocumentAccess:",s)}}addUserInfoToOrganization(a){return I(this,arguments,function*({organizationId:t,user:i,notificationsConfig:o,currentUserId:s}){try{let c=Dr(this.functions,Ir({url:st?.cloudFunction?.sdkProxy,apiProxyDomain:this.configService?.getApiProxyDomain()}));yield Ad({data:x({type:"addUserInfoToOrganization",metadata:{organizationId:t},user:this.usersService?.externalUserDataProviderAvailable()?{userId:i?.userId}:i},o&&{notificationsConfig:o}),getSdkProxy:c,userId:s??i?.userId??""})}catch(c){this.loggingService.warn("Error in DocService addUserInfoToOrganization:",c)}})}setDocumentsImpl(a){return I(this,arguments,function*({documents:t,options:i,source:o,skipPermissionValidation:s=!1}){try{if(this.loggingService.logContext("[CONTEXT] setDocumentsImpl called with documents:",JSON.parse(JSON.stringify(t??"nil")),"options:",JSON.parse(JSON.stringify(i??"nil"))),!this.shouldSetDocumentsAgain(t,jT(i))){o==="external"&&this.loggingService.catch("setDocuments called with previous request");return}let c=J();this.currentValidationToken=c;let l=this.getDocumentIdsFromDocuments({documents:t,setClientDocumentMetadataMap:!0});if(l?.length===0){this.loggingService.warn("Minimum one document must be set in setDocuments");return}let u=this.authService.getUser();if(!u){this.draftDocuments=t,this.draftOptions=i;return}this.pendingDocumentIds=t.map(f=>f.id),this.pendingOptions=jT(i)??{},this.documentPaths$.value?.organizationId&&i?.organizationId&&this.documentPaths$.value?.clientOrganizationId!==i?.organizationId?this.authService.resetServicesCache():this.unsetDocuments({source:"internal",unsetDocumentPaths:!1});let d=i?.organizationId??u?.clientOrganizationId;if(d&&this.addUserInfoToOrganization({organizationId:d,user:u}),l=yield this.filterRelevantDocuments({options:i,documentIds:l,skipPermissionValidation:s}),this.documentIds$.next(l),l?.length){let f=l[0]?.clientDocumentId;i?.rootDocumentId&&l.find(g=>g.clientDocumentId===i?.rootDocumentId)&&(f=i?.rootDocumentId),yield this.debounceSetDocuments({documentId:f,clientOrganizationId:i?.organizationId,options:i})}this.pendingDocumentIds=[],this.pendingOptions={};return}catch(c){this.pendingDocumentIds=[],this.pendingOptions={},this.loggingService.catch("Error in DocService setDocumentsImpl:",c)}})}setDocumentId(s){return I(this,arguments,function*({documentId:t,clientOrganizationId:i,source:o="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocumentId","color: green;"),o==="internal"&&this.analyticsService.trackEvent(L.Events.Core.SET_DOCUMENTS_TRIGGERED,{payload:{id:t,clientOrganizationId:i,methodName:"setDocumentId",source:o}}),this.coreActionsService.triggerAction($.INIT_UPDATE,{event:L.Events.Core.SET_DOCUMENTS_TRIGGERED,methodName:kn.SET_DOCUMENT_ID,source:o,payload:{documentId:t,clientOrganizationId:i}}),yield this.setDocumentsImpl({documents:[{id:t}],options:{organizationId:i},source:o})}catch(a){this.loggingService.catch("Error in setDocumentId:",a);return}})}debounceSetDocuments(s){return I(this,arguments,function*({documentId:t,clientOrganizationId:i,options:o}){try{this.loggingService.log("%c[WB] Calling FUNCTION: debounceSetDocuments","color: green;");let a=o?.debounceTime??this.DEBOUNCE_TIME;this.currentDebounceTime=a;let c=Date.now(),l=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||l>a&&u>a){yield this.setDocumentIdImpl(t,i,o),this.lastSetDocumentIdExecutionTime=c;return}this.documentPaths$.next(null),this.isDocumentIdInDebounceQueue=!0,this.draftLocationMap={locations:[],options:void 0},this.queueSize++,this.setDocumentIdSubject.next({documentId:t,clientOrganizationId:i,options:o??void 0});return}catch(a){this.loggingService.catch("Error in debounceSetDocuments:",a)}})}setDocumentIdImpl(t,i,o){return I(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: setDocumentIdImpl","color: green;");try{let s=this.authService.getUser();if(!s)return;this.currentDocumentId&&this.documentPaths$.value&&(yield this.callPreDocumentIdChangeFunctions(this.documentPaths$.value));let a=this.currentDocumentId;if(this.apiKey){let c=`${Tr(t)}`,l=o?.folderId,u=o?.folderId?wo(o?.folderId):void 0,d=o?.locationId,f=o?.allDocuments,g=o?.optimisticPermissions,p=s?.organizationId?i?Fi(i):s?.organizationId:void 0,_=J(),T=Td.SET_DOCUMENTS;this.coreActionsService.triggerAction($.COMMENT_RESOLVER,{event:L.Events.Resolver.COMMENT_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:_,methodName:Et.INIT_DOCUMENTS,moduleName:T,source:"internal",payload:{documentIds:this.documentIds$.value.map(U=>U.clientDocumentId),organizationId:i??s?.clientOrganizationId??""}});let D=J(),b=Id.SET_DOCUMENTS;this.coreActionsService.triggerAction($.REACTION_RESOLVER,{event:L.Events.Resolver.REACTION_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:D,moduleName:b,methodName:_t.INIT_DOCUMENTS,source:"internal",payload:{documentIds:this.documentIds$.value.map(U=>U.clientDocumentId),organizationId:i??s?.clientOrganizationId??""}});let G=J(),M=vd.GET_RECORDER_ANNOTATIONS;if(this.coreActionsService.triggerAction($.RECORDER_RESOLVER,{event:L.Events.Resolver.RECORDER_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:G,moduleName:M,methodName:Tt.RESOLVE_RECORDER_ANNOTATIONS,source:"internal",payload:{documentIds:this.documentIds$.value.map(U=>U.clientDocumentId),organizationId:i??s?.clientOrganizationId??""}}),yield Promise.allSettled([this.commentResolverService.resolveCommentAnnotations({request:{documentIds:this.documentIds$.value.map(U=>U.clientDocumentId),organizationId:i??s?.clientOrganizationId??""},uniqueId:_,moduleName:T}),this.reactionResolverService.resolveReactionAnnotations({request:{documentIds:this.documentIds$.value.map(U=>U.clientDocumentId),organizationId:i??s?.clientOrganizationId??""},uniqueId:D,moduleName:b}),this.recorderResolverService.resolveRecorderAnnotations({request:{documentIds:this.documentIds$.value.map(U=>U.clientDocumentId),organizationId:i??s?.clientOrganizationId??""},uniqueId:G,moduleName:M})]),this.currentDocumentId!==c||this.documentPaths$.value?.organizationId!==p){this.loggingService.log("setting new docid"),this.currentDocumentId=c;let U=new xT,k=new qy;U.clientDocumentId=t,k.clientDocumentId=t,U.folderId=l,k.folderId=l,U.locationId=d,k.locationId=d,U.allDocuments=f,U.optimisticPermissions=g,k.allDocuments=f,k.optimisticPermissions=g,U.veltFolderId=u,k.veltFolderId=u,U.documentId=c,k.documentId=c,p&&(U.organizationId=p,U.clientOrganizationId=i??s?.clientOrganizationId,k.organizationId=p,k.clientOrganizationId=i??s?.clientOrganizationId);let S=`${this.apiKey}`,A=`apiKey/${this.apiKey}`;p&&(S=`${S}/${v.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${U.organizationId}`,A=`${A}/${v.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${U.organizationId}`),k.organization=`apiKey/${this.apiKey}/${v.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}`,k.document=`${A}/${v.FIREBASE_PARTIAL_PATH_DOCS}`,U.presence=`${S}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_PRESENCE}/`,U.cursor=`${S}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_CURSOR}/`,U.comment=`${S}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_COMMENT}/`,k.comment=`${A}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_COMMENT}`,U.multiThread=`${S}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_MULTI_THREAD}/`,k.multiThread=`${A}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_MULTI_THREAD}`,U.tag=`${S}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_TAG}/`,U.area=`${S}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_AREA}/`,k.area=`${A}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_AREA}`,U.arrow=`${S}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_ARROW}/`,U.selection=`${S}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_SELECTION}/`,U.audioHuddle=`${S}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_AUDIO_HUDDLE}/`,U.huddle=`${S}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_HUDDLE}/`,U.recorder=`${S}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_RECORDER}/`,k.recorder=`${A}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_RECORDER}`,U.flock=`${S}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_FOLLOW_ALONG}/`,U.syncVideoPlayer=`${S}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_SYNC_VIDEO_PLAYER}/`,U.liveState=`${S}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_LIVE_STATE}/`,U.liveStateSingleEditorMode=`${S}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_LIVE_STATE}/default/singleEditorMode`,U.reaction=`${S}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_REACTION}/`,k.reaction=`${A}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_REACTION}`,U.crdt=`${S}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_CRDT}/`,k.crdt=`${A}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_CRDT}`,U.customerMetadata=`${this.apiKey}/${v.FIREBASE_PARTIAL_PATH_CUSTOMER_METADATA}/`,U.views=`${S}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_VIEWS}/`,k.notificationViews=`${A}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_NOTIFICATION_VIEWS}`,k.documentViews=`${A}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_DOCUMENT_VIEWS}`,k.locationViews=`${A}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_LOCATION_VIEWS}`,U.notifications=`${S}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_NOTIFICATIONS}/`,U.metadata=`${S}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_METADATA}/`,U.users=`${S}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_USERS}/`,U.documentIam=`${S}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_IAM}/`,U.workspaceIam=`${this.apiKey}/${v.FIREBASE_PARTIAL_PATH_IAM}/`,U.groupContacts=`${S}/${v.FIREBASE_PARTIAL_PATH_CONTACTS}/${v.FIREBASE_PARTIAL_PATH_GROUPS}/`,U.globalContacts=`${S}/${v.FIREBASE_PARTIAL_PATH_CONTACTS}/${v.FIREBASE_PARTIAL_PATH_GLOBAL}/`,U.logins=`${S}/${v.FIREBASE_PARTIAL_PATH_CONTACTS}/${v.FIREBASE_PARTIAL_PATH_LOGINS}/`,U.userFeedback=`${S}/${v.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${v.FIREBASE_PARTIAL_PATH_FEEDBACK}/`,U.userReportBugs=`${S}/${v.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${v.FIREBASE_PARTIAL_PATH_BUGS}/`,U.userContactUs=`${S}/${v.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${v.FIREBASE_PARTIAL_PATH_CONTACT_US}/`,p&&(U.organizationMetadata=`${S}/${v.FIREBASE_PARTIAL_PATH_ORGANIZATION_METADATA}/`,U.organizationIam=`${S}/${v.FIREBASE_PARTIAL_PATH_IAM}/`,U.organizationGroups=`${S}/${v.FIREBASE_PARTIAL_PATH_ORGANIZATION_GROUPS}/`,U.organizationNotifications=`${S}/${v.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/`,c&&(U.organizationNotificationsWithDocumentId=`${S}/${v.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/`,U.heartbeatByDocument=`${S}/${v.FIREBASE_PARTIAL_PATH_HEARTBEAT_BY_DOCUMENT}/${c}/`),U.organizationNotificationsLastNotificationTimestamp=`${S}/${v.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${v.FIREBASE_PARTIAL_PATH_LAST_NOTIFICATION_TIMESTAMP}/${v.FIREBASE_PARTIAL_PATH_DOCS}/`,U.organizationNotificationsUsers=`${S}/${v.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${v.FIREBASE_PARTIAL_PATH_USERS}/`,U.heartbeat=`${S}/${v.FIREBASE_PARTIAL_PATH_HEARTBEAT}/`),k.organizationUsers=`${A}/${v.FIREBASE_PARTIAL_PATH_ORGANIZATION_USERS}`,k.users=`${A}/${v.FIREBASE_PARTIAL_PATH_CENTRAL_USERS}`,k.documentUsers=`${A}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_DOCUMENT_USERS}`,k.notificationDocs=`${A}/${v.FIREBASE_PARTIAL_PATH_NOTIFICATION_DOCS}`,k.notificationUsers=`${A}/${v.FIREBASE_PARTIAL_PATH_NOTIFICATION_USERS}`,this.documentPaths$.next(U),this.firestorePaths$.next(k),U?.clientOrganizationId&&U?.organizationId&&!(U?.clientOrganizationId===this.getOrganizationConfig()?.clientOrganizationId&&U?.organizationId===this.getOrganizationConfig()?.organizationId)&&this.setOrganizationConfig({organizationId:U?.organizationId,clientOrganizationId:U?.clientOrganizationId}),Promise.allSettled([this.updateFolderMetadata(),this.updateDocumentMetadata(),this.fetchLocationMetadata(),this.updateOrganizationMetadata()]),a&&this.location$.value&&this.removeLocation({}),this.coreActionsService.triggerAction($.INIT_UPDATE,{event:L.Events.Doc.SET_DOCUMENTS_SUCCESS,payload:{documentId:c,clientDocumentId:t}}),this.analyticsService.trackEvent(L.Events.Doc.SET_DOCUMENTS_SUCCESS,{documentId:c,clientDocumentId:t},!0,this.getUserIdForAnalytics())}}else this.loggingService.catch("Error in setDocumentIdImpl: API key is not provided.")}catch(s){this.loggingService.catch("Error in setDocumentIdImpl: ",s)}})}unsetDocumentId({source:t,unsetDocumentPaths:i}){this.loggingService.log("%c[WB] Calling FUNCTION: unsetDocumentId","color: green;");try{t==="internal"&&this.analyticsService.trackEvent(L.Events.Core.UNSET_DOCUMENTS_TRIGGERED,{payload:{methodName:"unsetDocumentId",source:t}}),this.coreActionsService.triggerAction($.INIT_UPDATE,{event:L.Events.Doc.UNSET_DOCUMENTS_TRIGGERED,methodName:kn.UNSET_DOCUMENT_ID,source:t}),this.unsetDocumentImpl({source:t,unsetDocumentPaths:i})}catch(o){this.loggingService.catch("Error in unsetDocumentId: ",o)}}unsetDocumentImpl({source:t,unsetDocumentPaths:i}){this.loggingService.log("%c[WB] Calling FUNCTION: unsetDocumentImpl","color: green;");try{let o=JSON.parse(JSON.stringify(this.documentIds$.value??[])),s=JSON.parse(JSON.stringify(this.documentPaths$.value?.folderId??"")),a=this.getDocContext();this.currentDocumentId&&this.documentPaths$.value&&this.callPreDocumentIdChangeFunctions(this.documentPaths$.value),i&&(this.documentPaths$.next(null),this.firestorePaths$.next(null)),this.currentDocumentId=null,this.location$.next(null),this.excludedLocationIds$.next([]),this.documentMetadata$.next(null),this.locationMetadata$.next(null),this.locations$.next({}),this.documentIds$.next([]),this.setDocContext(null),this.userPermissionService?.revokeAccessOnDocumentUnset({documentIds:o,folderId:s,context:a}),this.coreActionsService.triggerAction($.INIT_UPDATE,{event:L.Events.Doc.UNSET_DOCUMENTS_SUCCESS,source:t}),this.analyticsService.trackEvent(L.Events.Doc.UNSET_DOCUMENTS_SUCCESS,{documentId:this.currentDocumentId,documentMetadata:this.documentMetadata$.value?.[this.currentDocumentId??""],message:t==="external"?"User unset document id":"System unset document id",source:t},!0,this.getUserIdForAnalytics())}catch(o){this.loggingService.catch("Error in unsetDocumentImpl: ",o)}}unsetDocuments({source:t,unsetDocumentPaths:i=!0}){this.loggingService.log("%c[WB] Calling FUNCTION: unsetDocuments","color: green;");try{t==="internal"&&this.analyticsService.trackEvent(L.Events.Core.UNSET_DOCUMENTS_TRIGGERED,{payload:{methodName:"unsetDocuments",source:t}}),this.coreActionsService.triggerAction($.INIT_UPDATE,{event:L.Events.Doc.UNSET_DOCUMENTS_TRIGGERED,source:t,methodName:kn.UNSET_DOCUMENTS}),this.unsetDocumentImpl({source:t,unsetDocumentPaths:i})}catch(o){this.loggingService.catch("Error in unsetDocuments: ",o)}}addPreDocumentIdChangeFunction(t,i){try{this.loggingService.log("%c[WB] Calling FUNCTION: addPreDocumentIdChangeFunction","color: green;"),this.preDocumentIdChangeFunctions.set(t,i)}catch(o){this.loggingService.catch("Error in addPreDocumentIdChangeFunction: ",o)}}callPreDocumentIdChangeFunctions(t){return I(this,null,function*(){try{this.loggingService.log("%c[WB] Calling FUNCTION: callPreDocumentIdChangeFunctions","color: green;");for(let[i,o]of this.preDocumentIdChangeFunctions)try{yield o(t)}catch(s){this.loggingService.catch("Error in callPreDocumentIdChangeFunctions: ",s)}}catch(i){this.loggingService.catch("Error in callPreDocumentIdChangeFunctions: ",i)}})}fetchOrganizationMetadata(t){return I(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: fetchOrganizationMetadata","color: green;");try{if(!t&&this.getOrganizationConfig()&&(t=this.getOrganizationConfig()),this.db&&t?.organizationId){let i=t?.organizationId,o=t?.clientOrganizationId,s=this.authService.getUser()?.userId??"",a=yield this.userPermissionService?.getUserPermissionsFromCacheOrFetch({organizationId:o});if(s&&a?.[s]?.organization?.[o]?.errorCode===Oo.PERMISSION_DENIED)return;yield this.commonDbService?.getData({feature:"organizationMetadata",properties:{apiKey:this.apiKey??"",organizationId:i,field:"metadata"}}).then(c=>{c&&!c?.errorCode&&this.organizationMetadata$.next(le(x({},this.organizationMetadata$.value),{[i]:c}))}).catch(c=>{this.loggingService.catch("Error in fetchOrganizationMetadata: ",c)})}}catch(i){this.loggingService.catch("Error in fetchOrganizationMetadata: ",i)}})}fetchDocumentMetadata(t){return I(this,null,function*(){try{if(this.db&&this.authService.getUser()){let i=this.documentPaths$.value,o=this.documentMetadata$.value;if(t=t.filter(s=>!o?.[s.documentId]),t?.some(s=>!s?.documentId||!s?.clientDocumentId)||!i)return;if(this.commonDbService?.shouldUseFirestore()){let s=i?.folderId,a=[],c={organizationId:i?.clientOrganizationId,folderId:s},l=[],u=20;for(let f=0;f<t.length;f+=u)l.push(t.slice(f,f+u));l.forEach(f=>{let g=JSON.parse(JSON.stringify(c));g.documentIds=f.map(p=>p.clientDocumentId),a.push(this.fetchDocuments(g))});let d={};a.length>0&&(yield Promise.all(a).then(f=>{f?.forEach(g=>{g?.forEach(p=>{p?.metadata?.documentId&&(d[p.metadata.documentId]=p.metadata)})}),this.setAllDocumentMetadata(x(x({},this.documentMetadata$.value),d))}).catch(f=>{this.loggingService.catch("Error in fetchDocumentMetadata: ",f)}))}else o?.[i?.documentId??t?.[0]?.documentId]||this.commonDbService?.queryData({feature:"allDocuments",properties:{apiKey:this.apiKey??"",organizationId:i?.organizationId,documentId:i?.documentId??t?.[0]?.documentId,skipObjectValues:!0}}).then(s=>{s?.documentId&&this.setDocumentMetadata(s.documentId,s)}).catch(s=>{this.loggingService.catch("Error in fetchDocumentMetadata: ",s)})}}catch(i){this.loggingService.catch("Error in fetchDocumentMetadata: ",i)}})}fetchLocationMetadata(){return I(this,null,function*(){try{if(this.db&&this.authService.getUser()){let t=this.documentPaths$.value,i=this.documentIds$.value,o=t?.folderId,s=t?.allDocuments,a=[],c={organizationId:t?.clientOrganizationId,folderId:o,allDocuments:s},l=[],u=20;for(let f=0;f<i.length;f+=u)l.push(i.slice(f,f+u));l.forEach(f=>{let g=JSON.parse(JSON.stringify(c));g.documentIds=f.map(p=>p.clientDocumentId),a.push(this.fetchLocations(g))});let d=this.locationMetadata$.value??{};a.length>0&&Promise.all(a).then(f=>{f?.forEach(g=>{g?.forEach(p=>{p?.metadata?.documentId&&(d[p.metadata.documentId]=le(x({},d?.[p.metadata.documentId]??{}),{[p.location.id]:p}))})}),Object.keys(d||{}).length>0&&this.locationMetadata$.next(d)}).catch(f=>{this.loggingService.catch("Error in fetchLocationMetadata: ",f)})}}catch(t){this.loggingService.catch("Error in fetchLocationMetadata: ",t)}})}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(ts(i=>ue(null))).subscribe(i=>{this.customerMetadata$.next(i?.data)}))}catch(t){this.loggingService.catch("Error in subscribeToCustomerMetadata: ",t)}}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(fe(t=>t?.slice()))}getDocumentIds(){return this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentIds","color: green;"),this.documentIds$.value?.slice()}getLocationMetadata$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getLocationMetadata$","color: green;"),this.locationMetadata$.asObservable().pipe()}getDocumentPaths$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentPaths$","color: green;"),this.documentPaths$.asObservable()}getFirestorePaths$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getFirestorePaths$","color: green;"),this.firestorePaths$.asObservable()}getDocumentPaths(){return this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentPaths","color: green;"),this.documentPaths$.value}generateDocumentId(t){try{return`${Tr(t)}`}catch(i){return this.loggingService.catch("Error in generateDocumentId: ",i),""}}generateOrganizationId(t){try{return`${Fi(t)}`}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(o){return I(this,arguments,function*({location:t,source:i="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setLocation","color: green;"),i==="internal"&&this.analyticsService.trackEvent(L.Events.Core.SET_LOCATIONS_TRIGGERED,{payload:{locations:[t],options:void 0,methodName:"setLocation",source:i}}),this.coreActionsService.triggerAction($.INIT_UPDATE,{event:L.Events.Core.SET_LOCATIONS_TRIGGERED,source:i,methodName:kn.SET_LOCATION,payload:{locations:[t],options:void 0}}),this.setLocationsImpl({locations:[t]})}catch(s){this.loggingService.catch("Error in setLocation: ",s)}})}setLocations(s){return I(this,arguments,function*({locations:t,options:i,source:o="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setLocations","color: green;"),o==="internal"&&this.analyticsService.trackEvent(L.Events.Core.SET_LOCATIONS_TRIGGERED,{payload:{locations:t,options:i,methodName:"setLocations",source:o}}),this.coreActionsService.triggerAction($.INIT_UPDATE,{event:L.Events.Core.SET_LOCATIONS_TRIGGERED,methodName:kn.SET_LOCATIONS,source:o,payload:{locations:t,options:i}}),this.setLocationsImpl({locations:t,options:i})}catch(a){this.loggingService.catch("Error in setLocations: ",a)}})}getValidLocations(t){try{let i=[];return t&&Array.isArray(t)&&t.forEach(o=>{if(o&&typeof o=="object"){let s=!0;o?.version&&(!o?.version?.id||!o?.version?.name)&&(this.loggingService.catch(`Error in setting location for locationId: ${o?.id}, If you're setting version then add id and name fields to version object.`),s=!1),s&&i.push(o)}}),i}catch(i){this.loggingService.catch("Error in getValidLocations: ",i)}return t}setRootLocation(o){return I(this,arguments,function*({location:t,source:i="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setRootLocation","color: green;"),i==="internal"&&this.analyticsService.trackEvent(L.Events.Core.SET_ROOT_LOCATION_TRIGGERED,{payload:{location:t,methodName:"setRootLocation",source:i}}),this.coreActionsService.triggerAction($.INIT_UPDATE,{event:L.Events.Core.SET_ROOT_LOCATION_TRIGGERED,methodName:kn.SET_ROOT_LOCATION,source:i,payload:{location:t}});let s=Object.values(this.locations$.value).map(a=>a.location).filter(a=>String(a.id)!==String(t.id));this.setLocationsImpl({locations:[t,...s],options:{rootLocationId:t.id}})}catch(s){this.loggingService.catch("Error in DocService setRootLocation:",s)}})}setLocationsImpl({locations:t,options:i}){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: setLocationsImpl","color: green;"),t.length===0)return;if(!this.authService.getUser()){!i?.appendLocation&&t.length>0&&(this.draftLocationMap.options=le(x(x({},this.draftLocationMap.options??{}),i??{}),{rootLocationId:t[0].id})),this.draftLocationMap.locations=[...this.draftLocationMap.locations,...t],this.draftLocationMap.options=x(x({},this.draftLocationMap.options),i);return}let s=this.getValidLocations(t),a=[],c=[];this.location$.value?.location.id&&c.push(this.location$.value?.location.id),c=[...c,...Object.values(this.locations$.value).map(d=>d.location.id)].filter(d=>d!==void 0);let l;if(i?.rootLocationId&&i?.rootLocationId!==this.location$.value?.location.id&&(l=s.find(d=>d.id===i?.rootLocationId),!l)){this.loggingService.catch(`Error in setting locations, rootLocationId: ${i?.rootLocationId} not found in locations.`);return}if(i?.appendLocation){if(l){let d=Sd(l),f=Tr(JSON.stringify(d));d.id&&a.push({locationId:f,location:d}),this.location$.next({locationId:f,location:d})}}else{l||(l=s[0]);let d=Sd(l),f=Tr(JSON.stringify(d));d.id&&a.push({locationId:f,location:d}),this.location$.next({locationId:f,location:d})}let u=[];return s.slice(i?.appendLocation?0:1).forEach(d=>{if(d.id!==this.location$.value?.location.id){let f=x({},d),g=this.locations$.value;d?.id&&Object.keys(g).forEach(D=>{let b=g[D];b.location?.id===d.id&&(f=x(x({},b.location),d),delete g?.[D])});let p=this.genarateLocationId(f),_={locationId:p,location:f};f.id&&a.push({locationId:p,location:f}),u.push(_);let T=le(x({},g),{[p]:_});this.locations$.next(T)}}),this.updateDocumentLocationMetadata(a),this.coreActionsService.triggerAction($.INIT_UPDATE,{event:L.Events.Doc.SET_LOCATIONS_SUCCESS,methodName:kn.SET_LOCATIONS,payload:{locations:s,options:i}}),this.analyticsService.trackEvent(L.Events.Doc.SET_LOCATIONS_SUCCESS,{locations:s,options:i},!0,this.getUserIdForAnalytics()),u}catch(o){this.loggingService.catch("Error in setLocationImpl: ",o);return}}addLocation({location:t,source:i="internal"}){try{return this.loggingService.log("%c[WB] Calling FUNCTION: addLocation","color: green;"),i==="internal"&&this.analyticsService.trackEvent(L.Events.Core.SET_LOCATIONS_TRIGGERED,{payload:{locations:[t],options:{appendLocation:!0},methodName:"addLocation",source:i}}),this.coreActionsService.triggerAction($.INIT_UPDATE,{event:L.Events.Core.SET_LOCATIONS_TRIGGERED,methodName:kn.ADD_LOCATION,source:i,payload:{locations:[t],options:{appendLocation:!0}}}),this.setLocationsImpl({locations:[t],options:{appendLocation:!0}})}catch(o){this.loggingService.catch("Error in DocService addLocation:",o);return}}removeLocation({location:t,source:i="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: removeLocation","color: green;"),i==="internal"&&this.analyticsService.trackEvent(L.Events.Core.REMOVE_LOCATIONS_TRIGGERED,{payload:{locations:[t],methodName:"removeLocation",source:i}}),this.coreActionsService.triggerAction($.INIT_UPDATE,{event:L.Events.Core.REMOVE_LOCATIONS_TRIGGERED,source:i,methodName:kn.REMOVE_LOCATION,payload:{locations:[t]}}),t&&this.removeLocationsImpl([t],i)}catch(o){this.loggingService.catch("Error in removeLocation: ",o)}}removeLocations({locations:t,source:i="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: removeLocations","color: green;"),i==="internal"&&this.analyticsService.trackEvent(L.Events.Core.REMOVE_LOCATIONS_TRIGGERED,{payload:{locations:t,methodName:"removeLocations",source:i}}),this.coreActionsService.triggerAction($.INIT_UPDATE,{event:L.Events.Core.REMOVE_LOCATIONS_TRIGGERED,methodName:kn.REMOVE_LOCATIONS,source:i,payload:{locations:t}}),this.removeLocationsImpl(t,i)}catch(o){this.loggingService.catch("Error in removeLocations: ",o)}}removeLocationsImpl(t,i="internal"){try{this.loggingService.log("%c[WB] Calling FUNCTION: removeLocations","color: green;"),i==="internal"&&this.analyticsService.trackEvent(L.Events.Core.REMOVE_LOCATIONS_TRIGGERED,{payload:{locations:t},methodName:"removeLocations",message:"System removed locations",source:i},!0,this.getUserIdForAnalytics()),t?t.forEach(o=>{let s=this.genarateLocationId(o);this.getLocation()?.locationId===s&&(this.location$.next(null),i!=="internal"&&(this.draftLocationMap.locations=this.draftLocationMap.locations.filter(a=>a.id!==o.id))),this.removeCustomLocation(o)}):(this.location$.next(null),this.locations$.next({}),i!=="internal"&&(this.draftLocationMap.options=void 0,this.draftLocationMap.locations=[])),this.analyticsService.trackEvent(L.Events.Doc.REMOVE_LOCATIONS_SUCCESS,{payload:{locations:t},source:i},!0,this.getUserIdForAnalytics())}catch(o){this.loggingService.catch("Error in removeLocation: ",o)}}unsetLocationIds(t,i="internal"){try{this.loggingService.log("%c[WB] Calling FUNCTION: unsetLocationIds","color: green;"),this.coreActionsService.triggerAction($.INIT_UPDATE,{event:L.Events.Core.UNSET_LOCATIONS_TRIGGERED,methodName:kn.UNSET_LOCATION_IDS,source:i,payload:{locationIds:t}}),i==="internal"&&this.analyticsService.trackEvent(L.Events.Core.UNSET_LOCATIONS_TRIGGERED,{payload:{locationIds:t},methodName:"unsetLocationIds",message:"System unset location ids",source:i},!0,this.getUserIdForAnalytics()),t?.length?t.forEach(o=>{this.getLocation()?.location.id===o&&(this.location$.next(null),i!=="internal"&&(this.draftLocationMap.locations=this.draftLocationMap.locations.filter(s=>s.id!==o))),this.removeCustomLocationId(o)}):(this.location$.next(null),this.locations$.next({}),i!=="internal"&&(this.draftLocationMap.options=void 0,this.draftLocationMap.locations=[])),this.coreActionsService.triggerAction($.INIT_UPDATE,{event:L.Events.Doc.REMOVE_LOCATIONS_SUCCESS,methodName:kn.REMOVE_LOCATIONS_SUCCESS,source:i,payload:{locationIds:t}}),this.analyticsService.trackEvent(L.Events.Doc.REMOVE_LOCATIONS_SUCCESS,{payload:{locationIds:t},source:i},!0,this.getUserIdForAnalytics())}catch(o){this.loggingService.catch("Error in unsetLocationIds: ",o)}}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(t){try{this.excludedLocationIds$.next([...t])}catch(i){this.loggingService.catch("Error in excludeLocationIds: ",i)}}getExcludedLocationIds$(){try{return this.excludedLocationIds$.asObservable()}catch(t){return this.loggingService.catch("Error in getExcludedLocationIds$: ",t),ue([])}}updateOrganizationMetadata(t){return I(this,null,function*(){try{!t&&this.getOrganizationConfig()&&(t=this.getOrganizationConfig());let i=t?.organizationId,o=t?.clientOrganizationId,s=this.documentPaths$.value;if(this.db&&i&&s?.documentId){if(this.organizationMetadata$.value?.[i])return;let c=new kT;c.apiKey=this.configService?.getApiKey()??"",c.organizationId=i,c.clientOrganizationId=o;let l=this.authService.getUser()?.userId??"",u=o?yield this.userPermissionService?.getUserPermissionsFromCacheOrFetch({organizationId:o}):null;!!(l&&o&&u?.[l]?.organization?.[o]?.errorCode===Oo.PERMISSION_DENIED)?this.loggingService.log(`%c[WB] updateOrganizationMetadata skipped \u2014 user does not have access to organization: ${o}`,"color: orange;"):this.userPermissionService?.hasEditAccess({organizationId:i})&&(yield this.commonDbService?.updateData({feature:"organizationMetadata",data:JSON.parse(JSON.stringify(c)),properties:{organizationId:i,documentId:s?.documentId??""}})),yield this.fetchOrganizationMetadata(t)}}catch(i){this.loggingService.catch("Error in updateOrganizationMetadata: ",i)}})}updateFolderMetadata(){return I(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: updateFolderMetadata","color: green;"),this.db&&this.authService.getUser()&&this.documentPaths$.value?.folderId){let t=this.documentPaths$.value;if(!t?.veltFolderId||!t?.organizationId)return;if(!(yield this.commonDbService?.getData({feature:"folderMetadata",properties:{organizationId:t?.organizationId??"",folderId:t?.veltFolderId??""}}))?.metadata){let o={folderId:this.documentPaths$.value?.folderId,clientOrganizationId:t?.clientOrganizationId,parentFolderId:"root"};if(this.userPermissionService?.hasEditAccess({folderId:this.documentPaths$.value?.veltFolderId??""})){let s=Dr(this.functions,Ir({url:st?.cloudFunction?.sdkProxy,apiProxyDomain:this.configService?.getApiProxyDomain()}));yield Ad({methodName:"createFolder",data:{type:"createFolder",metadata:o},getSdkProxy:s,userId:this.authService.getUser()?.userId??""})}}}}catch(t){this.loggingService.catch("Error in updateFolderMetadata: ",t)}})}updateDocumentMetadata(){return I(this,null,function*(){try{if(this.db&&this.authService.getUser()){let t=this.documentPaths$.value;if(t){let i=this.getDocumentIds();i.find(s=>s.documentId===t.documentId)||i.push({documentId:t.documentId??"",clientDocumentId:t.clientDocumentId??""});let o=i.map(s=>I(this,null,function*(){let a=new PT;this.clientDocumentMetadataMap?.[s.clientDocumentId]&&(a=x(x({},this.clientDocumentMetadataMap[s.clientDocumentId]),a)),a.apiKey=this.configService?.getApiKey()??"",a.documentId=s.documentId,a.clientDocumentId=s.clientDocumentId,a.organizationId=t.organizationId,a.clientOrganizationId=t.clientOrganizationId,a.pageInfo=Cg(s.clientDocumentId);let c=t?.folderId,l=t?.veltFolderId;a?.pageInfo?.deviceInfo&&delete a?.pageInfo?.deviceInfo;let u=!0,d=this.documentMetadata$.value?.[s.documentId];if(c&&l){let f=this.getDocumentMetadata(s?.documentId??"")??(yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:s?.documentId??"",organizationId:t?.organizationId??"",field:"metadata"}}));f?.clientDocumentId&&!f?.errorCode?f?.folderId&&(f?.folderId!==c||f?.veltFolderId!==l)?(this.loggingService.catch(`Folder id mismatch for document ${s?.clientDocumentId??""}`),u=!1):f?.folderId===c?(c&&(a.folderId=c),l&&(a.veltFolderId=l)):(this.loggingService.catch(`Document ${s?.clientDocumentId??""} is not in the folder ${c??""}`),u=!1):(c&&(a.folderId=c),l&&(a.veltFolderId=l))}if(d){let f={};Object.entries(a).forEach(([g,p])=>{f[g]=p}),ki(f,d)&&(u=!1)}u&&this.userPermissionService?.hasEditAccess({documentId:s?.documentId??"",folderId:t?.allDocuments&&t?.veltFolderId?t?.veltFolderId:void 0})&&(yield this.commonDbService?.updateData({feature:"documentMetadata",data:JSON.parse(JSON.stringify(a)),properties:{organizationId:t?.organizationId??"",documentId:s?.documentId??""}}))}));yield Promise.allSettled(o),yield this.fetchDocumentMetadata(i)}}}catch(t){this.loggingService.catch("Error in updateDocumentMetadata: ",t)}})}updateDocumentLocationMetadata(t){return I(this,null,function*(){try{if(this.db&&this.authService.getUser()){let i=this.documentPaths$.value;if(i){let o=this.getDocumentIds();o.find(s=>s.documentId===i.documentId)||o.push({documentId:i.documentId??"",clientDocumentId:i.clientDocumentId??""});for(let s of o){let a=yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:s?.documentId??"",organizationId:i?.organizationId??"",field:"metadata"}});a?.errorCode&&(a={});let c=[];for(let l of t){let u=new FT;u.locationId=l?.locationId,u.veltLocationId=CC(l?.location?.id??""),u.location=l?.location,u.pageInfo=Cg(s?.clientDocumentId),u?.pageInfo?.deviceInfo&&delete u?.pageInfo?.deviceInfo;let d=le(x({},a),{[v.FIREBASE_PARTIAL_PATH_LOCATIONS]:le(x({},a[v.FIREBASE_PARTIAL_PATH_LOCATIONS]??{}),{[l?.locationId]:u})});this.commonDbService?.shouldUseFirestore()||c.push(this.commonDbService?.updateData({feature:"documentMetadata",data:JSON.parse(JSON.stringify(d)),properties:{documentId:s?.documentId??"",organizationId:i?.organizationId??""}}));let f=this.locationMetadata$.value;if(f||(f={}),l?.location?.id){let g=f?.[s.documentId],p=g?.[l?.location?.id??""];f&&(g||(f[s.documentId]={}),p||(f[s.documentId][l?.location?.id??""]={}),f[s.documentId][l?.location?.id??""]=le(x({},p),{location:l?.location})),Object.keys(f||{}).length>0&&this.locationMetadata$.next(f)}}yield Promise.allSettled(c)}}}}catch(i){this.loggingService.catch("Error in updateDocumentLocationMetadata: ",i)}})}genarateLocationId(t){try{return t&&typeof t=="object"?Tr(JSON.stringify(Sd(t))):0}catch(i){return this.loggingService.catch("Error in genarateLocationId: ",i),0}}removeCustomLocation(t,i="internal"){try{let o=this.genarateLocationId(t),s=this.locations$.value;s[o]&&(delete s[o],this.locations$.next(x({},s)),i!=="internal"&&this.isDocumentIdInDebounceQueue&&(this.draftLocationMap.locations=this.draftLocationMap.locations.filter(a=>a.id!==t.id)))}catch(o){this.loggingService.catch("Error in DocService removeLocation:",o)}}removeCustomLocationId(t,i="internal"){try{this.loggingService.log("%c[WB] Calling FUNCTION: removeCustomLocationId","color: green;");let o=this.locations$.value;Object.entries(o).forEach(([s,a])=>{a.location.id===t&&(delete o[s],this.locations$.next(x({},o)),i!=="internal"&&this.isDocumentIdInDebounceQueue&&(this.draftLocationMap.locations=this.draftLocationMap.locations.filter(c=>c.id!==t)))})}catch(o){this.loggingService.catch("Error in DocService removeCustomLocationId:",o)}}getLocationByClientLocationId(t){try{let i=this.getLocation()?.location;if(i?.id===t)return i;{let o=this.getLocations();Object.keys(o).forEach(s=>{let a=o[s];a.location?.id===t&&(i=a.location)})}return i}catch(i){this.loggingService.catch("Error in DocService getLocationByClientLocationId:",i);return}}removeLocationIfNotInDom(){try{let t=this.locations$.value,i=document.querySelectorAll(`[${v.ATTRIBUTES.VELT_LOCATION}]`),o=[];i.forEach(s=>{let a=s.getAttribute(v.ATTRIBUTES.VELT_LOCATION);if(a){let c=JSON.parse(a),l=this.genarateLocationId(c);o.push(l)}}),Object.keys(t).forEach(s=>{let a=t[s];o.includes(a.locationId)||delete t[s]}),this.locations$.next(x({},t))}catch(t){this.loggingService.catch("Error in DocService removeLocationIfNotInDom:",t)}}getLocations$(){try{return this.locations$.asObservable()}catch(t){return this.loggingService.catch("Error in DocService getLocations$:",t),ue({})}}getLocations(){try{return this.locations$.value}catch(t){return this.loggingService.catch("Error in DocService getLocations:",t),{}}}getLocationFromElement(t){try{this.loggingService.log("%c[WB] Calling FUNCTION: getLocationFromElement","color: green;");let i=null;if(t?.getAttribute(v.ATTRIBUTES.VELT_LOCATION)?i=t:i=t.closest(`[${v.ATTRIBUTES.VELT_LOCATION}]`),i){let o=i?.getAttribute(v.ATTRIBUTES.VELT_LOCATION);if(o){let s=JSON.parse(o);return{locationId:this.genarateLocationId(s),location:s}}}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 t={};return document.querySelectorAll(`[${v.ATTRIBUTES.VELT_LOCATION}], [${v.ATTRIBUTES.VELT_LOCATION_ID}]`).forEach(o=>{if(o.getAttribute(v.ATTRIBUTES.VELT_LOCATION)){let s=this.getLocationFromElement(o);s?.locationId&&(t[s.locationId]={element:o,location:s})}else if(o.getAttribute(v.ATTRIBUTES.VELT_LOCATION_ID)){let s=o.getAttribute(v.ATTRIBUTES.VELT_LOCATION_ID);if(s){let a=this.getLocationByClientLocationId(s);a?.locationId&&(t[a.locationId]={element:o,location:a});let c={id:s},l=this.genarateLocationId(c);t[s]={element:o,location:{locationId:l,location:c}}}}}),t}catch(t){return this.loggingService.catch("Error in DocService getElementMapWithLocation:",t),{}}}getAdditionLocationFromElement(t){try{this.loggingService.log("%c[WB] Calling FUNCTION: getAdditionLocationFromElement","color: green;");let i;if(i=t?.closest(`[${v.ATTRIBUTES.VELT_LOCATION}], [${v.ATTRIBUTES.VELT_LOCATION_ID}]`),i){if(i?.getAttribute(v.ATTRIBUTES.VELT_LOCATION)){let o=i?.getAttribute(v.ATTRIBUTES.VELT_LOCATION);if(o)return JSON.parse(o)}else if(i?.getAttribute(v.ATTRIBUTES.VELT_LOCATION_ID)){let o=i?.getAttribute(v.ATTRIBUTES.VELT_LOCATION_ID);if(o)return{id:o}}}return null}catch(i){return this.loggingService.catch("Error in DocService getAdditionLocationFromElement:",i),null}}getAdditionalDocumentIdFromElement(t){try{return t?.closest(`[${v.ATTRIBUTES.VELT_DOCUMENT_ID}]`)?.getAttribute(v.ATTRIBUTES.VELT_DOCUMENT_ID)||null}catch(i){return this.loggingService.catch("Error in DocService getAdditionalDocumentIdFromElement:",i),null}}getDocumentMetadata(t){try{return t?this.documentMetadata$.value?.[t]||null:this.documentMetadata$.value?.[this.documentPaths$.value?.documentId??""]||null}catch(i){return this.loggingService.catch("Error in DocService getDocumentMetadata:",i),null}}getAllDocumentMetadata$(t){return this.getAllDocumentMetadataMap$().pipe(fe(i=>i?.[t??this.documentPaths$.value?.documentId??""]||null),it(Ft))}getAllDocumentMetadata(){try{return Object.values(this.documentMetadata$.value||{})}catch(t){return this.loggingService.catch("Error in DocService getAllDocumentMetadata:",t),[]}}getAllDocumentMetadataMap$(){return this.documentMetadata$.asObservable().pipe(fe(t=>t||{}),it(Ft))}getAllDocumentMetadataMap(){try{return this.documentMetadata$.value||{}}catch(t){return this.loggingService.catch("Error in DocService getAllDocumentMetadata:",t),{}}}getDocumentMetadataOfAvailableDocuments(){try{this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentMetadataOfAvailableDocuments","color: green;");let t=this.documentMetadata$.value||{},i={},o=this.documentPaths$.value?.veltFolderId,s=this.documentPaths$.value?.allDocuments;if(o&&s)Object.values(t).forEach(a=>{a?.documentId&&a?.veltFolderId===o&&(i[a.documentId]=a)});else{let a=this.documentIds$.value;if(a?.length)a.forEach(c=>{let l=t?.[c.documentId];l&&(i[c.documentId]=l)});else if(this.documentPaths$.value?.documentId){let c=t?.[this.documentPaths$.value?.documentId];c&&(i[this.documentPaths$.value?.documentId]=c)}}return Object.values(i)}catch(t){return this.loggingService.catch("Error in DocService getDocumentMetadataOfAvailableDocuments:",t),[]}}getDocumentMetadata$(t){return this.documentMetadata$.asObservable().pipe(fe(i=>i?.[t??this.documentPaths$.value?.documentId??""]||null),it(Ft))}setDocumentMetadata(t,i){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocumentMetadata","color: green;");let o=JSON.parse(JSON.stringify(this.documentMetadata$.value??{}));o[t]=i,this.documentMetadata$.next(o)}catch(o){this.loggingService.catch("Error in DocService setDocumentMetadata:",o)}}setAllDocumentMetadata(t){try{this.loggingService.log("%c[WB] Calling FUNCTION: setAllDocumentMetadata","color: green;"),this.documentMetadata$.next(t)}catch(i){this.loggingService.catch("Error in DocService setAllDocumentMetadata:",i)}}getOrganizationMetadata(t){return this.organizationMetadata$.value?.[t]||null}getOrganizationMetadata$(t){return this.organizationMetadata$.asObservable().pipe(fe(i=>i?.[t]||null))}getOrganizationMetadataMap$(){return this.organizationMetadata$.asObservable().pipe(fe(t=>t||{}),it(Ft))}getCustomerMetadata(){return this.customerMetadata$.value}getCustomerMetadata$(){return this.customerMetadata$.asObservable()}getOrganizationConfig$(){return this.organizationConfig$.asObservable().pipe(it(Ft))}getOrganizationConfig(){return this.organizationConfig$.value}setOrganizationConfig(t){try{this.loggingService.log("%c[WB] Calling FUNCTION: setOrganizationConfig","color: green;");let i=JSON.parse(JSON.stringify(t));this.organizationConfig$.next(i)}catch(i){return this.loggingService.catch("Error in DocService setOrganizationConfig:",i),!1}return!0}getMetadataFromType(t,i){try{switch(t){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(o){this.loggingService.catch("Error in DocService getMetadataFromType:",o);return}}getDefaultMetadata({clientDocumentId:t,documentId:i}){try{let o=this.documentPaths$.value;if(!o)return;let s=t||o.clientDocumentId,a=i||o.documentId,c=this.getDocumentMetadata(a);if(!c)return;let l=c?.folderId,u=c?.veltFolderId;return x(x({apiKey:this.configService.getApiKey()??void 0,clientDocumentId:s,clientOrganizationId:o.clientOrganizationId,documentId:a,organizationId:o.organizationId},l?{folderId:l}:{}),u?{veltFolderId:u}:{})}catch(o){this.loggingService.catch("Error in DocService getDefaultMetadata:",o);return}}getBaseMetadata(t,i){try{let o,s;i?.element?o=this.getAdditionalDocumentIdFromElement(i.element)||void 0:i?.clientDocumentId&&(o=i.clientDocumentId),o&&(s=this.generateDocumentId(o));let a=this.getMetadataFromType(t,i),c=this.getDefaultMetadata({clientDocumentId:o,documentId:s}),l=a||c||{};return l.sdkVersion=jr(),l}catch(o){return this.loggingService.catch("Error in DocService getBaseMetadata:",o),{}}}getServerId({documentId:t,organizationId:i}){try{return t&&(t=this.generateDocumentId(t)),i&&(i=this.generateOrganizationId(i)),{documentId:t,organizationId:i}}catch(o){return this.loggingService.catch("Error in DocService getServerId:",o),null}}fetchDocuments(t){return I(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 o=[];if(!t?.organizationId)return this.loggingService.catch("Error in fetchDocuments: organizationId is required"),[];if(t?.folderId){let a=wo(t?.folderId);o.push(Ji("metadata.veltFolderId","==",a))}return t?.documentIds?.length&&!t?.allDocuments&&o.push(Ji("metadata.documentId","in",t?.documentIds?.map(a=>this.generateDocumentId(a)).slice(0,30))),yield this.commonDbService?.queryData({feature:"allDocuments",properties:{firestoreQuery:o,apiKey:this.apiKey??"",organizationId:this.generateOrganizationId(t?.organizationId)??this.documentPaths$.value?.organizationId,documentId:this.documentPaths$.value?.documentId}})}catch(i){return this.loggingService.catch("Error in DocService fetchDocuments:",i),[]}})}fetchLocations(t){return I(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 o=[];if(!t?.organizationId)return this.commonDbService?.shouldUseFirestore()&&this.loggingService.catch("Error in fetchLocations: organizationId is required"),[];if(t?.folderId){let a=wo(t?.folderId);o.push(Ji("metadata.veltFolderId","==",a))}return t?.documentIds?.length&&!t?.allDocuments&&o.push(Ji("metadata.documentId","in",t?.documentIds?.map(a=>this.generateDocumentId(a)).slice(0,30))),yield this.commonDbService?.queryData({feature:"allLocations",properties:{firestoreQuery:o,apiKey:this.apiKey??"",organizationId:this.generateOrganizationId(t?.organizationId)??this.documentPaths$.value?.organizationId,documentId:this.documentPaths$.value?.documentId}})}catch(i){return this.loggingService.catch("Error in DocService fetchLocations:",i),[]}})}updateDocuments(t){return I(this,null,function*(){try{if(typeof t=="object"&&(t=JSON.parse(JSON.stringify(t??{}))),!this.authService.getUser())return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),[];let{organizationId:o,documents:s,folderId:a}=t;if(!o&&(o=this.documentPaths$.value?.clientOrganizationId,!o))return this.loggingService.catch("Error in updateDocuments: organizationId is required"),[];let c=Ts(o);if(!s||s.length===0)return this.loggingService.catch("Error in updateDocuments: documents is required"),[];let l=[],u=this.documentMetadata$.value??{};for(let d of s)if(d?.documentId){d.organizationId=c,d.clientOrganizationId=o,d.clientDocumentId=d.documentId;let f=da(d.documentId);d.documentId=f,d.apiKey=this.configService.getApiKey()??void 0,(a||this.documentPaths$.value?.folderId)&&(d.folderId=a||this.documentPaths$.value?.folderId,d.veltFolderId=wo(a||this.documentPaths$.value?.folderId||""));let g=()=>{if(a&&this.documentPaths$.value?.folderId&&a!==this.documentPaths$.value?.folderId)return;let _=u?.[f];_?u[f]=x(x({},_),d):u[f]=d},p=yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:f,organizationId:c,field:"metadata"}});if(p?.errorCode&&(p={}),p&&p.apiKey&&p.folderId&&a&&p.folderId!=d.folderId){this.loggingService.catch(`Error in updateDocuments: document ${d.clientDocumentId} already exists with different folderId: ${p.folderId}`);continue}if(p&&p.apiKey&&!p.folderId&&d.folderId){this.loggingService.catch(`Error in updateDocuments: document ${d.clientDocumentId} already exists, move this document to folder with REST API`);continue}g(),d&&this.commonDbService&&this.userPermissionService?.hasEditAccess({documentId:d?.documentId??""})&&l.push(this.commonDbService.updateData({feature:"documentMetadata",data:JSON.parse(JSON.stringify(d)),properties:{organizationId:c,documentId:f}}))}yield Promise.all(l),this.setAllDocumentMetadata(u)}catch(i){return this.loggingService.catch("Error in DocService updateDocuments:",i),[]}})}updateLocations(t){return I(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:o,locations:s,documentIds:a}=t;if((!a||a.length===0)&&(a=this.documentIds$.value.map(d=>d.clientDocumentId)??[],a.length===0))return this.loggingService.catch("Error in updateLocations: documentId is required"),[];if(!o&&(o=this.documentPaths$.value?.clientOrganizationId,!o))return this.loggingService.catch("Error in updateLocations: organizationId is required"),[];if(!s||s.length===0)return this.loggingService.catch("Error in updateLocations: locations is required"),[];let c=a.map(d=>da(d)),l=[],u=this.locationMetadata$.value;u||(u={}),c.forEach(d=>{s.forEach(f=>{let g=this.location$.value;if(f?.id===g?.location?.id&&this.location$.next({locationId:g?.locationId,location:f}),f?.id){delete f?.metadata;let p=CC(f.id),_=u?.[d],T=_?.[f.id];u&&(_||(u[d]={}),T||(u[d][f.id]={}),u[d][f.id]=le(x({},T),{location:f})),f&&this.commonDbService&&l.push(this.commonDbService.updateData({feature:"locationMetadata",data:JSON.parse(JSON.stringify({location:f})),properties:{organizationId:Ts(o),documentId:d,id:p}}))}})}),yield Promise.all(l),Object.keys(u||{}).length>0&&this.locationMetadata$.next(u)}catch(i){return this.loggingService.catch("Error in DocService updateLocations:",i),[]}})}fetchFolders(t){return I(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 o=[];if(!t?.organizationId)return this.loggingService.catch("Error in fetchFolders: organizationId is required"),{data:[],parentFolders:[]};let s=[],a=this.generateOrganizationId(t?.organizationId);if(t?.folderId){let c=wo(t?.folderId);o=yield this.commonDbService?.getData({feature:"folder",properties:{folderId:c,apiKey:this.apiKey??"",organizationId:a,documentId:this.documentPaths$.value?.documentId}}),o&&(o=[o]),s=yield this.commonDbService?.queryData({feature:"allFolders",properties:{firestoreQuery:[Ji("metadata.veltParentFolderId","==",c)],folderId:c,apiKey:this.apiKey??"",organizationId:a,documentId:this.documentPaths$.value?.documentId}})}else o=yield this.commonDbService?.queryData({feature:"allFolders",properties:{apiKey:this.apiKey??"",organizationId:a,documentId:this.documentPaths$.value?.documentId}});return{data:o,parentFolders:s}}catch(i){return this.loggingService.catch("Error in DocService getFoldersRequest:",i),{data:[],parentFolders:[]}}})}getDocumentIam$(){return this.authService.getUser$().pipe(mt(t=>t?this.documentPaths$.pipe(mt(i=>i?.documentIam?this.commonDbService?.dbListener({feature:"documentIam",properties:{documentId:i.documentId,organizationId:i.organizationId,isCollection:!1}}).pipe(fe(o=>o?.data?.docIamConfig??o?.data),it((o,s)=>JSON.stringify(o??{})===JSON.stringify(s??{}))):ue(null))):ue(null)))}getDocumentAccessType(t){try{return t&&t.features&&t.features.all?t.features.all.restricted?wt.RESTRICTED:wt.PUBLIC:t&&t.documentAccessType?t.documentAccessType:wt.PUBLIC}catch(i){return this.loggingService.catch("Error in DocService getDocumentAccessType:",i),wt.PUBLIC}}changeDocumentAccessType(t){return I(this,null,function*(){try{let i=this.documentPaths$.value;if(i){let o=yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:i?.documentId??"",organizationId:i?.organizationId??"",field:"docIamConfig"}});if(o?.errorCode)return;switch(delete o.documentAccessType,o.features||(o.features={}),o.features.all||(o.features.all={}),t){case wt.PUBLIC:o.features.all.restricted=!1;break;case wt.RESTRICTED:o.features.all.restricted=!0,o.features.all.guestMode=!1;break;default:break}this.commonDbService?.updateData({feature:"documentAccessType",data:JSON.parse(JSON.stringify(o)),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(t){return this.loggingService.catch("Error in DocService getUserIdForAnalytics:",t),""}}setUIState(t){try{this.uiState.next(x(x({},this.uiState.value),t))}catch(i){this.loggingService.catch("Error in DocService setUIState:",i)}}getUIState$(){return this.uiState.asObservable()}};e.\u0275fac=function(i){return new(i||e)(w(Lt),w(Cr),w(Wy),w(Ev),w(Rr),w(_e),w(zo),w(qo),w(ec),w(It),w(dr),w(li))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let n=e;return n})();var zt=(()=>{let e=class e{constructor(t,i,o,s,a){this.analyticsService=t,this.authService=i,this.coreActionsService=o,this.docService=s,this.loggingService=a,this.resolveOrganizationUsers=new Y(!0),this.resolveFolderUsers=new Y(!0),this.resolveDocumentUsers=new Y(!0),this.unresolvedUsers=new Y([]),this.resolveTimeout=60*1e3,this.resolveAttempts=new Map,this.subscriptions=new gt,this.userDataProvider$=new Y(null),this.anonymousUserDataProvider$=new Y(null),this.userIdByEmailCache={},this.userById$=new Y({}),this.customContactUserById$=new Y({}),this.userByIdCalled$=new Y({}),this.pendingResolutions=new Set,this.getUserById=c=>{try{let l=this.userById$.value?.[c],u=this.customContactUserById$.value?.[c];return u?l?x(x({},l),u):u:l}catch(l){this.loggingService.catch("Error in UsersService getUserById:",l);return}};try{this.docService.setUsersService(this),this.analyticsService.setUserService(this),this.authService.setUsersService(this),this.docService.getDocumentPaths$().pipe(Ct(c=>!!c),mt(()=>this.getUnresolvedUsers$().pipe(Ct(c=>c.length>0),Au(300),Nt(20),mt(c=>{let l=this.docService.getOrganizationConfig()?.organizationId;return this.commonDbService?this.commonDbService?.dbListener({feature:"allOrganizationUsers",properties:{organizationId:l,isCollection:!0,useQuery:!0,firestoreQuery:[MM(Ji("user.userId","in",c.slice(0,20)))]}}).pipe(fe(u=>u?.data),Ks(u=>{if(u&&typeof u=="object"){delete u.undefined,delete u.null;let d=Object.values(u??{});this.setUserByIds(d.map(g=>g.user));let f=c.filter(g=>!d.some(p=>p.user.userId===g));f.length!==c.length&&this.setUnresolvedUsers(f)}})):ue([])})))).subscribe()}catch(c){this.loggingService.catch("Error in UsersService constructor:",c)}}setCommonDbService(t){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setCommonDbService","color: green;"),this.commonDbService=t}catch(i){this.loggingService.catch("Error in UsersService setCommonDbService:",i)}}setContactService(t){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setContactService","color: green;"),this.contactService=t}catch(i){this.loggingService.catch("Error in UsersService setContactService:",i)}}ngOnDestroy(){try{this.subscriptions.unsubscribe(),this.pendingResolutions.clear(),this.resolveAttempts.clear()}catch(t){this.loggingService.catch("Error in UsersService ngOnDestroy:",t)}}isResolverForFeatureDisabled(t){let i=this.userDataProvider$.getValue();try{switch(t){case"allOrganizationUsers":return i?!this.resolveOrganizationUsers.value:!0;case"allFolderUsers":return i?!this.resolveFolderUsers.value:!0;case"allDocumentUsers":return i?!this.resolveDocumentUsers.value:!0;default:return!1}}catch(o){return this.loggingService.catch("Error in UsersService isResolverForFeatureDisabled:",o),!1}}resolveUsers(u){return I(this,arguments,function*({userIds:t,forceResolve:i,feature:o,organizationId:s,skipUserCheck:a=!1,uniqueId:c,moduleName:l}){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: resolveUsers","color: green;");let d=!1;if(o&&(d=this.isResolverForFeatureDisabled(o)),d)return{};{let f={},g=[],p={};if(t?.forEach(_=>{let T=this.getUserById(_);T?f[_]=T:this.userByIdCalled$.getValue()[_]?i&&g.push(_):(g.push(_),this.userByIdCalled$.next(le(x({},this.userByIdCalled$.getValue()),{[_]:!0})))}),g.length>0){let _=c||J();this.coreActionsService.triggerAction($.USER_RESOLVER,{event:L.Events.Resolver.USER_RESOLUTION_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:_,moduleName:l,methodName:xn.RESOLVE_USERS,source:"internal",payload:{userIds:g,organizationId:s,feature:o,forceResolve:i,skipUserCheck:a,externalUserDataProviderAvailable:this.externalUserDataProviderAvailable()}});let T={};try{let D,b=new Promise((G,M)=>{D=setTimeout(()=>{M(new Error("User resolution timeout"))},this.userDataProvider$.getValue()?.config?.resolveTimeout||this.userDataProvider$.getValue()?.resolveTimeout||this.resolveTimeout)});T=yield Promise.race([this.getUsersFromDB({userIds:g,organizationId:s,skipUserCheck:a}).finally(()=>{clearTimeout(D)}),b]),this.analyticsService.trackEvent(L.Events.Resolver.USER_RESOLVER_GET,{sourceMethod:"resolveUsers",source:"sdk",userIds:g}),this.coreActionsService.triggerAction($.USER_RESOLVER,{event:L.Events.Resolver.USER_RESOLUTION_RESULT,timestamp:new Date().getTime(),uniqueId:_,methodName:xn.RESOLVE_USERS,moduleName:l,source:"internal",payload:{result:T,userIds:g,externalUserDataProviderAvailable:this.externalUserDataProviderAvailable()}})}catch(D){this.loggingService.catch("Error in UsersService resolveUsers getUsers:",D,{userIds:g}),this.coreActionsService.triggerAction($.USER_RESOLVER,{event:L.Events.Resolver.USER_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:_,methodName:xn.RESOLVE_USERS,moduleName:l,source:"internal",payload:{error:D,userIds:g,externalUserDataProviderAvailable:this.externalUserDataProviderAvailable()}})}finally{g?.forEach(D=>{if(!T[D]){let b=new Set([...this.getUnresolvedUsers(),D]);this.unresolvedUsers.next(Array.from(b)),T[D]={userId:D,name:`User ${D}`}}})}Object.entries(T).forEach(([D,b])=>{b&&(f[D]=T?.[D],p[D]=T?.[D])})}return Object.keys(p).length>0&&(this.authService.setOptionalPropertiesToUsers(Object.values(p)),this.mergeUsersIntoStore(Object.values(p)),Object.keys(p).forEach(_=>{let T=this.getUserById(_);T&&(f[_]=T)})),f}}catch(d){this.loggingService.catch("Error in UsersService resolveUsers:",d);let f=c||J();return this.coreActionsService.triggerAction($.USER_RESOLVER,{event:L.Events.Resolver.USER_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:f,methodName:xn.RESOLVE_USERS,moduleName:l,source:"internal",payload:{error:d,userIds:t,externalUserDataProviderAvailable:this.externalUserDataProviderAvailable()}}),{}}})}getUnresolvedUsers$(){return this.unresolvedUsers.asObservable()}getUnresolvedUsers(){this.loggingService.log("%c[WB] Calling UsersService FUNCTION: getUnresolvedUsers","color: green;");try{return JSON.parse(JSON.stringify(this.unresolvedUsers.getValue()))}catch(t){return this.loggingService.catch("Error in UsersService getUnresolvedUsers:",t),[]}}setUnresolvedUsers(t){this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setUnresolvedUsers","color: green;");try{if(Array.isArray(t)){let i=JSON.parse(JSON.stringify(t));this.unresolvedUsers.next(i)}}catch(i){this.loggingService.catch("Error in UsersService setUnresolvedUsers:",i)}}getUsersFromDB(s){return I(this,arguments,function*({userIds:t,organizationId:i,skipUserCheck:o=!1}){this.loggingService.log("%c[WB] Calling UsersService FUNCTION: getUsersFromDB","color: green;");try{let a=this.userDataProvider$.getValue();if(a){if(a.config?.getConfig?.url){if(i||(i=this.docService.getOrganizationConfig()?.organizationId),!i)return this.loggingService.catch("Error in getUsersFromDB: organizationId is required when using getConfig"),{};let d={organizationId:i,userIds:t},f=yield Ht(a.config.getConfig.url,a.config.getConfig.headers,d,!0,a.config.getConfig.credentials);return f.statusCode!==200?(this.loggingService.catch(`Error in getUsersFromDB: config-based request failed with statusCode ${f.statusCode}. Message: ${f.message||"Unknown error"}`),{}):f.data??{}}let u=yield a.get(t);if(u&&typeof u=="object"&&"success"in u&&"statusCode"in u&&typeof u.success=="boolean"&&typeof u.statusCode=="number"){let d=u;return d.statusCode===200&&d.data?d.data:(this.loggingService.catch(`Error in getUsersFromDB: provider returned error response with statusCode ${d.statusCode}`),{})}return u}if(i||(i=this.docService.getOrganizationConfig()?.organizationId),!i)return{};let c=(yield this.getUsersFromDBWithBatching({userIds:t,organizationId:i,skipUserCheck:o}))??[];this.contactService?.setResolvedUsers(c.flat());let l={};return c.forEach(u=>{u.forEach(d=>{d?.user?.userId&&(l[d.user.userId]=d.user)})}),l}catch(a){return this.loggingService.catch("Error in UsersService getUsersFromDB:",a),{}}})}getUsersFromDBWithBatching(s){return I(this,arguments,function*({userIds:t,organizationId:i,skipUserCheck:o=!1}){try{if(!t?.length)return[];let a=[];for(let u=0;u<t.length;u+=30)a.push(t.slice(u,u+30));let c=a.map((u,d)=>I(this,null,function*(){try{return(yield this.commonDbService?.queryData({feature:"allOrganizationUsers",properties:{organizationId:i,useCollectionGroup:!1,isCollection:!0,firestoreQuery:[Ji("user.userId","in",u)],skipUserCheck:o}}))||[]}catch(f){return this.loggingService.catch(`Error in batch ${d+1}:`,f),[]}}));return yield Promise.all(c)}catch(a){return this.loggingService.catch("Error in getUsersFromDBWithBatching:",a),[]}})}getTemporaryUsersFromDBWithBatching(s){return I(this,arguments,function*({userIds:t,organizationId:i,resourceIds:o}){try{if(!t?.length||!o?.length)return[];let a=[];for(let _=0;_<t.length;_+=30)a.push(t.slice(_,_+30));let c=[];for(let _=0;_<o.length;_+=30)c.push(o.slice(_,_+30));let l=[],u=0,d=(_,T)=>I(this,null,function*(){try{return((yield this.commonDbService?.queryData({feature:"allPermissionsUsers",properties:{organizationId:i,useCollectionGroup:!1,isCollection:!0,firestoreQuery:[MM(Ji("userId","in",_),Ji("veltResourceId","in",T))]}}))??[])||[]}catch(D){return this.loggingService.catch(`Error in batch ${u+1}:`,D),[]}});for(let _ of a)for(let T of c)l.push(d(_,T)),u++;return(yield Promise.all(l)).flat().filter((_,T,D)=>T===D.findIndex(b=>b.userId===_.userId&&b.resourceId===_.resourceId))}catch(a){return this.loggingService.catch("Error in getTemporaryUsersFromDBWithBatching:",a),[]}})}getResolveOrganizationUsers$(){return this.resolveOrganizationUsers.asObservable()}getResolveFolderUsers$(){return this.resolveFolderUsers.asObservable()}getResolveDocumentUsers$(){return this.resolveDocumentUsers.asObservable()}getUserById$(){try{return this.loggingService.log("%c[WB] Calling UsersService FUNCTION: getUserById$","color: green;"),Zr([this.userById$,this.customContactUserById$]).pipe(fe(([t,i])=>this.applyContactOverlay(t,i)),it(Ft))}catch(t){return this.loggingService.catch("Error in UsersService getUserById$:",t),ue({})}}applyContactOverlay(t,i){let o=x({},t??{});return Object.entries(i??{}).forEach(([s,a])=>{o[s]=x(x({},o[s]??{}),a)}),o}setUserByIds(t){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setUserByIds","color: green;"),this.mergeUsersIntoStore(t)}catch(i){this.loggingService.catch("Error in UsersService setUserByIds:",i)}}setContactListUsers(t){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setContactListUsers","color: green;");let i={};(t??[]).forEach(o=>{let s=o?.userId;s&&(i[s]=JSON.parse(JSON.stringify(o)))}),this.customContactUserById$.next(i)}catch(i){this.loggingService.catch("Error in UsersService setContactListUsers:",i)}}getContactListUser(t){try{return this.customContactUserById$.value?.[t]}catch(i){this.loggingService.catch("Error in UsersService getContactListUser:",i);return}}mergeUsersIntoStore(t){try{let i=JSON.parse(JSON.stringify(this.userById$.getValue()??{}));(t??[]).forEach(o=>{let s=o?.userId;s&&(i[s]=x(x({},i?.[s]??{}),o))}),this.userById$.next(i)}catch(i){this.loggingService.catch("Error in UsersService mergeUsersIntoStore:",i)}}setUserDataProvider(t){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setUserDataProvider","color: green;");let i=t.config?.getConfig?.url,o="get"in t&&typeof t.get=="function";if(!i&&!o){this.loggingService.catch("DataProviders.user is invalid. The get method is missing or is not a function (and no getConfig provided).");return}this.userDataProvider$.next(t),t.config?.resolveUsersConfig?.organization===!1?this.resolveOrganizationUsers.next(!1):this.resolveOrganizationUsers.next(!0),t.config?.resolveUsersConfig?.folder===!1?this.resolveFolderUsers.next(!1):this.resolveFolderUsers.next(!0),t.config?.resolveUsersConfig?.document===!1?this.resolveDocumentUsers.next(!1):this.resolveDocumentUsers.next(!0)}catch(i){this.loggingService.catch("Error in UsersService setUserDataProvider:",i)}}setAnonymousUserDataProvider(t){try{if(this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setAnonymousUserDataProvider","color: green;"),!("resolveUserIdsByEmail"in t)||typeof t.resolveUserIdsByEmail!="function"){this.loggingService.catch("setAnonymousUserDataProvider is invalid. The resolveUserIdsByEmail method is missing or is not a function.");return}this.anonymousUserDataProvider$.next(t)}catch(i){this.loggingService.catch("Error in UsersService setAnonymousUserDataProvider:",i)}}resolveUserIdsByEmail(o){return I(this,arguments,function*({emails:t,uniqueId:i}){try{if(this.loggingService.log("%c[WB] Calling UsersService FUNCTION: resolveUserIdsByEmail","color: green;"),!t?.length)return{};let s=this.anonymousUserDataProvider$.getValue();if(!s||typeof s.resolveUserIdsByEmail!="function")return{};let a=[...new Set(t.filter(M=>!!M))];if(a.length===0)return{};let c={},l=[];if(a.forEach(M=>{let U=this.userIdByEmailCache[M];U?c[M]=U:l.push(M)}),l.length===0)return c;let u=this.docService.getOrganizationConfig()?.clientOrganizationId||"",d=this.docService.getDocumentPaths()?.clientDocumentId||"",f=this.docService.getDocumentPaths()?.folderId||"",g={organizationId:u,documentId:d,folderId:f,emails:l},p=i||J();this.coreActionsService.triggerAction($.USER_RESOLVER,{event:L.Events.Resolver.EMAIL_USER_ID_RESOLUTION_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:p,methodName:xn.RESOLVE_USER_IDS_BY_EMAIL,source:"internal",payload:{emails:l,organizationId:u,documentId:d,folderId:f}});let _=s.config?.resolveTimeout||this.resolveTimeout,T,D=new Promise((M,U)=>{T=setTimeout(()=>{U(new Error("resolveUserIdsByEmail timeout"))},_)}),b=s.config?.getRetryConfig||{retryCount:0,retryDelay:0},G=I(this,null,function*(){try{let M=yield kt(()=>s.resolveUserIdsByEmail(g),"resolveUserIdsByEmail",b);return M?.statusCode===200&&M?.data?M.data:(this.loggingService.catch(`Error in resolveUserIdsByEmail: provider returned statusCode ${M?.statusCode}. Message: ${M?.message||"Unknown error"}`),{})}finally{clearTimeout(T)}});try{let M=yield Promise.race([G,D]);return Object.entries(M).forEach(([U,k])=>{k&&(this.userIdByEmailCache[U]=k,c[U]=k,this.externalUserDataProviderAvailable()||this.docService.addUserInfoToOrganization({organizationId:this.docService.getOrganizationConfig()?.clientOrganizationId??"",user:{userId:k,name:U,email:U},currentUserId:this.authService.getUser()?.userId??""}).catch(S=>{this.loggingService.catch("Error in UsersService resolveUserIdsByEmail addUserInfoToOrganization:",S)}))}),this.coreActionsService.triggerAction($.USER_RESOLVER,{event:L.Events.Resolver.EMAIL_USER_ID_RESOLUTION_RESULT,timestamp:new Date().getTime(),uniqueId:p,methodName:xn.RESOLVE_USER_IDS_BY_EMAIL,source:"internal",payload:{result:M,emails:l}}),c}catch(M){return this.loggingService.catch("Error in UsersService resolveUserIdsByEmail (timeout/race):",M),this.coreActionsService.triggerAction($.USER_RESOLVER,{event:L.Events.Resolver.EMAIL_USER_ID_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:p,methodName:xn.RESOLVE_USER_IDS_BY_EMAIL,source:"internal",payload:{error:M,emails:l}}),c}}catch(s){return this.loggingService.catch("Error in UsersService resolveUserIdsByEmail:",s),{}}})}externalUserDataProviderAvailable(){try{return this.loggingService.log("%c[WB] Calling UsersService FUNCTION: externalUserDataProviderAvailable","color: green;"),!!this.commonDbService?.shouldUseFirestore()&&!!this.userDataProvider$.getValue()}catch(t){return this.loggingService.catch("Error in UsersService externalUserDataProviderAvailable:",t),!1}}userDataProviderAvailable(){try{return this.loggingService.log("%c[WB] Calling UsersService FUNCTION: userDataProviderAvailable","color: green;"),!!this.commonDbService?.shouldUseFirestore()}catch(t){return this.loggingService.catch("Error in UsersService userDataProviderAvailable:",t),!1}}};e.\u0275fac=function(i){return new(i||e)(w(Lt),w(Cr),w(It),w(zh),w(_e))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let n=e;return n})();var tc=class{static getFirestoreProdDbName(e,r){return r?.databaseURL?.includes("snippyly-plugin.firebaseio.com")||r?.databaseURL?.includes("snippyly-plugin-staging.firebaseio.com")?"sfdb":r?.storeDbId??(this.isTestingDb(r?.databaseURL??"")?"sdktest":`apikey${e.toLowerCase()}`)}static isTestingDb(e){try{return e.includes("-test")}catch(r){return H.error("Error in isTestingDb:",r),!1}}};var Ky=(()=>{let e=class e{constructor(t,i,o,s,a,c,l,u){this.loggingService=t,this.usersService=i,this.authService=o,this.functions=s,this.configService=a,this.commentAnnotationsResolverService=c,this.attachmentResolverService=l,this.coreActionsService=u,this.notificationActionTypeMap={[Ie.NEWLY_ADDED]:Qt.COMMENT_ANNOTATION_ADD,[Ie.ADDED]:Qt.COMMENT_ADD,[Ie.UPDATED]:Qt.COMMENT_UPDATE,[Ie.DELETED]:Qt.COMMENT_DELETE},this.additionalEventTypeMap={[Ie.STATUS_CHANGED]:Xn.STATUS_CHANGE,[Ie.PRIORITY_CHANGED]:Xn.PRIORITY_CHANGE,[Ie.ASSIGNED]:Xn.ASSIGN,[Ie.ACCESS_MODE_CHANGED]:Xn.ACCESS_MODE_CHANGE,[Ie.CUSTOM_LIST_CHANGED]:Xn.CUSTOM_LIST_CHANGE,[Ie.APPROVED]:Xn.APPROVE,[Ie.ACCEPTED]:Xn.ACCEPT,[Ie.REJECTED]:Xn.REJECT,[Ie.SUGGESTION_ACCEPTED]:Xn.SUGGESTION_ACCEPT,[Ie.SUGGESTION_REJECTED]:Xn.SUGGESTION_REJECT,[Ie.REACTION_ADDED]:Xn.REACTION_ADD,[Ie.REACTION_DELETED]:Xn.REACTION_DELETE,[Ie.SUBSCRIBED]:Xn.SUBSCRIBE,[Ie.UNSUBSCRIBED]:Xn.UNSUBSCRIBE}}setNotificationService(t){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: setNotificationService","color: green;"),this.notificationService=t}catch(i){this.loggingService.catch("Error in CommentUtilsService setNotificationService: ",i)}}setUserPermissionService(t){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: setUserPermissionService","color: green;"),this.userPermissionService=t}catch(i){this.loggingService.catch("Error in CommentUtilsService setUserPermissionService: ",i)}}getUserIdsToResolveFromComments(t){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: getUserIdsToResolveFromComments","color: green;");let i=new Set;for(let o of t){if(o?.from?.userId&&i.add(o?.from?.userId),o?.comments)for(let s of o?.comments){if(s?.from?.userId&&i.add(s?.from?.userId),s?.to)for(let a of s?.to)a?.userId&&i.add(a?.userId);if(s?.taggedUserContacts)for(let a of s?.taggedUserContacts)a?.userId&&i.add(a?.userId)}if(o?.assignedTo?.userId&&i.add(o?.assignedTo?.userId),o?.resolvedByUserId&&i.add(o?.resolvedByUserId),o?.suggestion?.resolvedBy?.userId&&i.add(o?.suggestion?.resolvedBy?.userId),o?.subscribedUsers)for(let s of Object.values(o?.subscribedUsers))s.user.userId&&i.add(s.user.userId);if(o?.unsubscribedUsers)for(let s of Object.values(o?.unsubscribedUsers))s.user.userId&&i.add(s.user.userId)}return Array.from(i)}catch(i){return this.loggingService.catch("Error in CommentUtilsService getUserIdsToResolveFromComments:",i),[]}}mergeCommentWithUser(t){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: mergeCommentWithUser","color: green;"),t?.from?.userId){let i=this.usersService.getUserById(t?.from?.userId);i&&(t.from=i)}if(t?.suggestion?.resolvedBy?.userId){let i=this.usersService.getUserById(t?.suggestion?.resolvedBy?.userId);i&&(t.suggestion.resolvedBy=i)}if(t?.comments)for(let i of t?.comments){if(i?.from?.userId){let s=this.usersService.getUserById(i?.from?.userId);s&&(i.from=s)}i?.to&&(i.to=i?.to?.map(s=>{if(s?.userId){let a=this.usersService.getUserById(s?.userId);if(a)return x(x({},s),a)}return s})),i?.taggedUserContacts&&(i.taggedUserContacts=i?.taggedUserContacts?.map(s=>{if(s?.contact){let a=this.usersService.getUserById(s?.contact?.userId);a&&(s.contact=a,(a?.name||a?.email)&&(s.text=`@${a?.name||a?.email}`))}return s}));let o=i?.taggedUserContacts?.filter((s,a,c)=>c.findIndex(l=>l.text===s.text)===a)||[];o.sort((s,a)=>(a.text?.length||0)-(s.text?.length||0)),o.forEach(s=>{if(s?.text){let a=new RegExp(rl(`{{${s.userId}}}`),"g");i.commentText?.includes(`@User ${s.userId}`)&&(a=new RegExp(rl(`@User ${s.userId}`),"g")),i.commentText=i.commentText?.replaceAll(a,s.text),i.commentHtml=i.commentHtml?.replaceAll(a,s.text)}})}if(t?.assignedTo?.userId){let i=this.usersService.getUserById(t?.assignedTo?.userId);i&&(t.assignedTo=i)}if(t?.resolvedByUserId){let i=this.usersService.getUserById(t?.resolvedByUserId);i&&(t.resolvedByUser=i)}if(t?.subscribedUsers)for(let i of Object.values(t?.subscribedUsers)){let o=this.usersService.getUserById(i.user.userId);o&&t?.subscribedUsers?.id?.user&&(t.subscribedUsers.id.user=o)}if(t?.unsubscribedUsers)for(let i of Object.values(t?.unsubscribedUsers)){let o=this.usersService.getUserById(i.user.userId);o&&t?.unsubscribedUsers?.id?.user&&(t.unsubscribedUsers.id.user=o)}return t}catch(i){return this.loggingService.catch("Error in CommentUtilsService mergeCommentWithUser:",i),t}}formatCommentData(t){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: formatCommentData","color: green;"),t?.comments?.forEach(i=>{i?.commentText&&i?.commentText?.length>0&&(i.isCommentTextAvailable=!0)}),t?.viewedBy&&delete t.viewedBy,t?.unread!==void 0&&delete t.unread,t?.resolvedByUser!==void 0&&delete t.resolvedByUser,t?.comments&&t.comments.forEach(i=>{i?.reactionAnnotations&&delete i.reactionAnnotations}),this.usersService.userDataProviderAvailable()){if(t?.from?.userId&&(t.from={userId:t.from.userId}),t?.assignedTo?.userId&&(t.assignedTo={userId:t.assignedTo.userId}),t?.subscribedUsers)for(let i of Object.keys(t?.subscribedUsers))t.subscribedUsers[i].user={userId:t?.subscribedUsers[i].user.userId};if(t?.unsubscribedUsers)for(let i of Object.keys(t?.unsubscribedUsers))t.unsubscribedUsers[i].user={userId:t?.unsubscribedUsers[i].user.userId};t?.suggestion?.resolvedBy?.userId&&(t.suggestion.resolvedBy={userId:t.suggestion.resolvedBy.userId})}return t?.comments&&(t.comments=t?.comments?.map(i=>this.formatCommentThreadData(i))),t}catch(i){return this.loggingService.catch("Error in CommentUtilsService formatCommentData:",i),t}}mergeStrippedDataWithCommentAnnotations(t){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: mergeStrippedDataWithCommentAnnotations","color: green;"),!this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())return t;let i=this.commentAnnotationsResolverService.getAnnotationById(t?.annotationId),o=this.attachmentResolverService.attachmentDataProviderAvailable(),s=this.commentAnnotationsResolverService.getFieldsToRemove();return i&&(t?.comments?.forEach(a=>{let c=i?.comments?.[a?.commentId];if(c){a.commentHtml=c?.commentHtml,a.commentText=c?.commentText;let l=c?.attachments;o&&l&&a.attachments?.forEach(u=>{let d=u?.attachmentId;l?.[d]&&(u.name=l?.[d]?.name,u.url=l?.[d]?.url)})}}),i?.targetTextRange?.text&&t?.targetTextRange&&(t.targetTextRange.text=i?.targetTextRange?.text),s?.length>0&&s.forEach(a=>{i?.[a]&&(t[a]=i[a])})),t}catch(i){return this.loggingService.catch("Error in CommentUtilsService mergeStrippedDataWithCommentAnnotations:",i),t}}mergeLocationWithCommentAnnotations(t,i){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: mergeLocationWithCommentAnnotations","color: green;");let o=t?.location?.id,s=t?.metadata?.documentId;if(!o||!s)return t;let a=i?.[s]?.[o];return a&&(t.location=a?.location),t}catch(o){return this.loggingService.catch("Error in CommentUtilsService mergeLocationWithCommentAnnotations:",o),t}}isCommentsDataChanged(t,i){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: isCommentsDataChanged","color: green;");let o=this.commentAnnotationsResolverService.getCommentAnnotationById(i);return o?!ki(t,o):!0}catch(o){return this.loggingService.catch("Error in CommentUtilsService isCommentsDataChanged:",o),!0}}stripCommentsFromAnnotationData({comment:t}){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: stripCommentsFromAnnotationData","color: green;");let i=this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable();if(!i)return t;let o=this.attachmentResolverService.attachmentDataProviderAvailable(),s=new LT;if(Object.assign(s,t),s.isCommentResolverUsed=i,o){let a=s.attachments?.map(c=>(c.isAttachmentResolverUsed=!0,delete c?.name,delete c?.url,c));s.attachments=a}return delete s?.commentHtml,delete s?.commentText,s}catch(i){return this.loggingService.catch("Error in CommentUtilsService stripCommentsFromAnnotationData:",i),t}}resolveTaggedUserEmails(t){return I(this,null,function*(){try{let i=new Set;if(t.comments?.forEach(o=>{o.taggedUserContacts?.forEach(s=>{s?.contact?.email&&!s?.userId&&i.add(s.contact.email)}),o.to?.forEach(s=>{s?.email&&!s?.userId&&i.add(s.email)})}),i.size>0){let o=J();this.coreActionsService.triggerAction($.USER_RESOLVER,{event:L.Events.Resolver.EMAIL_USER_ID_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:o,methodName:xn.RESOLVE_USER_IDS_BY_EMAIL,source:"internal",payload:{emails:Array.from(i)}});let s=yield this.usersService.resolveUserIdsByEmail({emails:Array.from(i),uniqueId:o});Object.keys(s).length>0&&t.comments?.forEach(a=>{a.taggedUserContacts?.forEach(c=>{if(c?.contact?.email&&!c?.userId){let l=s[c.contact.email];if(l){let u=c.text;if(u){let d=rl(u),f=new RegExp(d,"g");a.commentText&&(a.commentText=a.commentText.replace(f,`{{${l}}}`)),a.commentHtml&&(a.commentHtml=a.commentHtml.replace(f,`{{${l}}}`))}c.userId=l,c.contact.userId=l,delete c.contact?.email,delete c.contact?.visibility,c.text=""}}}),a.to=a.to?.map(c=>{if(c?.email&&!c?.userId){let l=s[c.email];if(l)return delete c?.email,delete c?.visibility,le(x({},c),{userId:l})}return c})})}return t}catch(i){return this.loggingService.catch("Error in CommentUtilsService resolveTaggedUserEmails:",i),t}})}stripCommentAnnotationData(s){return I(this,arguments,function*({data:t,actionType:i,commentId:o}){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: stripCommentAnnotationData","color: green;"),t=yield this.resolveTaggedUserEmails(t),!this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())return{originalData:t,strippedData:null};let a=this.attachmentResolverService.attachmentDataProviderAvailable(),c=this.commentAnnotationsResolverService.getFieldsToRemove(),l=this.commentAnnotationsResolverService.getAdditionalFields(),u,d;i&&(u=this.notificationActionTypeMap?.[i],d=this.additionalEventTypeMap?.[i]);let f=this.commentAnnotationsResolverService.getAdditionalSaveEvents(),g=Array.isArray(f)?f:[],p={},_=null,T=!1;if(t&&t.annotationId){let M=t.annotationId;if(p[M]=x(x(x(x({annotationId:M,metadata:Cn(t.metadata??{}),comments:{}},t?.from&&{from:t?.from}),t?.assignedTo&&{assignedTo:t?.assignedTo}),t?.resolvedByUserId&&{resolvedByUserId:t?.resolvedByUserId}),t?.targetTextRange?.text&&{targetTextRange:{text:t?.targetTextRange?.text}}),delete t?.targetTextRange?.text,c?.length>0&&c.forEach(k=>{t?.[k]&&(p[M][k]=t[k],delete t[k])}),l?.length)for(let k of l)t?.[k]!==void 0&&(p[M][k]=JSON.parse(JSON.stringify(t[k])));t.comments?.forEach(k=>{if(k.commentId){let S;a&&(S={},k.attachments?.forEach(A=>{S[A.attachmentId]={attachmentId:A.attachmentId,name:A.name,url:A.url}})),p[M].comments[k.commentId]=x(x(x(x(x(x({commentId:k.commentId},k?.commentHtml&&{commentHtml:k?.commentHtml}),k?.commentText&&{commentText:k?.commentText}),S&&{attachments:S}),k?.from&&{from:k?.from}),k?.to&&{to:k?.to}),k?.taggedUserContacts&&{taggedUserContacts:k?.taggedUserContacts})}}),T=this.isCommentsDataChanged(p[M],M);let U=new bT;Object.assign(U,t),c?.length>0&&c.forEach(k=>{k in t||delete U[k]}),U.comments=t.comments?.map(k=>this.stripCommentsFromAnnotationData({comment:k}))||[],_=U}let D=_?.comments?.find(M=>M.commentId===o);D?.isDraft&&(u=_?.comments?.length&&_?.comments?.length>0?Qt.COMMENT_ADD:Qt.COMMENT_ANNOTATION_ADD);let b=!!i&&!!this.notificationActionTypeMap?.[i],G=!!d&&!!_&&!b&&!D?.isDraft&&g.includes(d);return G&&(u=d),{strippedData:T&&(i&&this.notificationActionTypeMap?.[i]||D?.isDraft)||G?p:null,originalData:_,eventType:u}}catch(a){return this.loggingService.catch("Error in CommentAnnotationsResolverService stripCommentAnnotationData:",a),{strippedData:null,originalData:null}}})}formatCommentThreadData(t){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: formatCommentThreadData","color: green;"),this.usersService.userDataProviderAvailable()){t?.from?.userId&&(t.from={userId:t.from.userId}),t?.to&&(t.to=t?.to?.map(o=>o?.userId?{userId:o.userId}:o)),t?.taggedUserContacts&&(t.taggedUserContacts=t?.taggedUserContacts?.map(o=>o?.contact?.userId?le(x({},o),{contact:{userId:o.contact.userId}}):o));let i=t?.taggedUserContacts?.filter((o,s,a)=>a.findIndex(c=>c.text===o.text)===s)||[];i.sort((o,s)=>(s.text?.length||0)-(o.text?.length||0)),i.forEach(o=>{if(o?.text&&o?.contact?.userId){let s=new RegExp(rl(o.text),"g");t.commentText=t.commentText?.replaceAll(s,a=>`{{${o.userId}}}`),t.commentHtml=t.commentHtml?.replaceAll(s,a=>`{{${o.userId}}}`)}}),i.forEach(o=>{o?.text&&o?.contact?.userId&&(o.text="")})}return t}catch(i){return this.loggingService.catch("Error in CommentUtilsService formatCommentThreadData:",i),t}}getDeniedForYouUsers(i){return I(this,arguments,function*({extraData:t}){try{let o=Object.values(t?.annotationData?.subscribedUsers||{}).map(a=>a.user.userId)??[],s=[];if(this.userPermissionService?.isPermissionProviderAvailable()&&o.length){let a=t?.metadata?.clientDocumentId,c=t?.annotationData?.context?.access&&this.userPermissionService?.getIsContextEnabled()?t?.annotationData?.context?.access:null,l=[];o.forEach(f=>{if(l.push({userId:f,resource:{id:a,type:di.DOCUMENT,source:Un.SET_NOTIFICATIONS,organizationId:t?.metadata?.clientOrganizationId??"",context:c?{access:c}:void 0}}),c){let g=JSON.stringify(c);l.push({userId:f,resource:{id:g,type:di.CONTEXT,source:Un.SET_NOTIFICATIONS,organizationId:t?.metadata?.clientOrganizationId??"",context:{access:c}}})}});let u=J();this.coreActionsService.triggerAction($.PERMISSION_PROVIDER,{event:L.Events.PermissionProvider.RESOURCE_ACCESS_REQUEST_FORMED,methodName:Un.SET_NOTIFICATIONS,uniqueId:u,timestamp:new Date().getTime(),source:"internal",payload:{requests:l}});let d=yield this.userPermissionService?.onResourceAccessRequired({requests:l,uniqueId:u,methodName:Un.SET_NOTIFICATIONS});d?.success&&d?.data?.length&&d.data.forEach(f=>{f.hasAccess||s.push(f.userId)})}return s}catch(o){return this.loggingService.catch("Error in CommentUtilsService getDeniedForYouUsers:",o),[]}})}handleCommentEncryption(c){return I(this,arguments,function*({data:t,firestorePath:i,extraData:o,eventType:s,metadata:a}){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: handleCommentEncryption","color: green;");let l=$T(this.authService.getFirebaseConfig()?.firebaseOptions),u=Dr(this.functions,Ir({url:st.cloudFunction?.[l]?.setEncryptedData,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:1200*1e3});if(o){o=this.notificationService?.processNotificationData(o),o.annotationData=t;let _=o?.targetAnnotationData?.commentId;if(_){let T=t?.comments?.find(D=>D?.commentId===_);T&&(o.targetAnnotationData=T)}try{let T=yield this.stripCommentAnnotationData({data:o.annotationData,actionType:o?.actionType??Ie.NEWLY_ADDED});T?.originalData&&(o.annotationData=this.formatCommentData(T.originalData)),o?.targetAnnotationData&&(o.targetAnnotationData=this.formatCommentThreadData(this.stripCommentsFromAnnotationData({comment:o.targetAnnotationData})))}catch(T){this.loggingService.warn("Error in CommentUtilsService handleCommentEncryption:",T)}}let d=tc.getFirestoreProdDbName(this.configService.getApiKey()??"",this.authService.getFirebaseConfig()?.firebaseOptions),f=yield this.getDeniedForYouUsers({extraData:o}),g={path:i??"",data:t??{},dbId:d??"",notificationData:o||void 0,notificationURL:st.firebaseNotificationsDatabaseURL,feature:"comment",eventType:s??"PATCH",sdkVersion:jr(),deniedForYouUsers:f,isPermissionProviderUsed:this.userPermissionService?.isPermissionProviderAvailable(),isCommentResolverUsed:this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable(),isSettingsConfigByOrganization:this.notificationService?.getSettingsConfigByOrganization(),isCrossOrganizationEnabled:this.notificationService?.getCrossOrganizationConfig()?.enabled,metadata:a},p=yield il(g,this.authService.getUser()?.userId??"");yield u({veltData:p})}catch(l){this.loggingService.catch("Error in CommentUtilsService handleCommentEncryption:",l)}})}};e.\u0275fac=function(i){return new(i||e)(w(_e),w(zt),w(Cr),w(dr),w(Rr),w(zo),w(Wh),w(It))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let n=e;return n})();var Yy=(()=>{let e=class e{constructor(t,i,o){this.coreActionsService=t,this.loggingService=i,this.analyticsService=o,this.resolveTimeout=60*1e3,this.retrySaveConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.retryGetConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.activityDataProvider$=new Y(null),this.activityById$=new Y({}),this.fieldsToRemove=[],this.getActivityById=s=>{try{return this.activityDataProviderAvailable()?this.activityById$.value?.[s]:void 0}catch(a){this.loggingService.catch("Error in ActivityResolverService getActivityById:",a);return}};try{this.loggingService.log("ActivityResolverService initialized"),this.activityDataProvider$.subscribe(s=>{s&&(s.config?.resolveTimeout&&(this.resolveTimeout=s.config.resolveTimeout),s.config?.saveRetryConfig&&(this.retrySaveConfig=s.config.saveRetryConfig),s.config?.getRetryConfig&&(this.retryGetConfig=s.config.getRetryConfig),s.config?.fieldsToRemove&&(this.fieldsToRemove=s.config.fieldsToRemove))})}catch(s){this.loggingService.catch("Error in ActivityResolverService constructor:",s)}}getProvider(){try{let t=this.activityDataProvider$.getValue();return t||void 0}catch(t){this.loggingService.catch("Error in ActivityResolverService getProvider:",t);return}}ngOnDestroy(){try{this.activityById$.next({})}catch(t){this.loggingService.catch("Error in ActivityResolverService ngOnDestroy:",t)}}resolveActivities(s){return I(this,arguments,function*({request:t,uniqueId:i,moduleName:o}){try{if(this.loggingService.log("%c[WB] Calling ActivityResolverService FUNCTION: resolveActivities","color: green;"),!this.activityDataProviderAvailable())return{};let a,c=!1,l=!1,u=()=>{a&&(clearTimeout(a),a=void 0,l=!0)};return new Promise((d,f)=>{a=setTimeout(()=>{if(!l){c=!0,u();let b=i||J();this.coreActionsService.triggerAction($.ACTIVITY_RESOLVER,{event:L.Events.Resolver.ACTIVITY_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:b,methodName:lr.RESOLVE_ACTIVITIES,moduleName:o,source:"internal",payload:{error:new Error("Activity resolution timeout"),request:t}}),f(new Error("Activity resolution timeout"))}},this.activityDataProvider$.value?.config?.resolveTimeout||this.resolveTimeout);let g=this.getProvider();if(!g)return u(),d({});let p={},_=[...new Set(t.activityIds||[])],T=le(x({},t),{activityIds:_});I(this,null,function*(){try{if(_.length>0||t.documentIds?.length){let b=i||J();this.coreActionsService.triggerAction($.ACTIVITY_RESOLVER,{event:L.Events.Resolver.ACTIVITY_RESOLUTION_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:b,methodName:lr.RESOLVE_ACTIVITIES,moduleName:o,source:"internal",payload:{request:T}});let G=kt(()=>g?.config?.getConfig?.url?Ht(g.config.getConfig.url,g.config.getConfig.headers,T,!0,g.config.getConfig.credentials):g?.get?.(T)||Promise.resolve(void 0),"resolveActivities",this.retryGetConfig).then(M=>c?{}:(u(),M&&M.statusCode!==200?(this.coreActionsService.triggerAction($.ACTIVITY_RESOLVER,{event:L.Events.Resolver.ACTIVITY_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:b,methodName:lr.RESOLVE_ACTIVITIES,moduleName:o,source:"internal",payload:{result:M,request:T}}),this.loggingService.catch(M?.message??"Error in ActivityResolverService resolveActivities:"),{}):M?.data)).catch(M=>{throw u(),M});try{p=(yield G)||{},this.analyticsService.trackEvent(L.Events.Resolver.ACTIVITY_RESOLVER_GET,{sourceMethod:"resolveActivities",source:"sdk",activityIds:_});let M={};Object.entries(p).forEach(([U,k])=>{let S=this.activityById$.value?.[U];S?S&&JSON.stringify(S)!==JSON.stringify(k)&&(M[U]=k):M[U]=k}),Object.keys(M).length>0&&this.activityById$.next(x(x({},this.activityById$.getValue()),M)),this.coreActionsService.triggerAction($.ACTIVITY_RESOLVER,{event:L.Events.Resolver.ACTIVITY_RESOLUTION_RESULT,timestamp:new Date().getTime(),uniqueId:b,methodName:lr.RESOLVE_ACTIVITIES,moduleName:o,source:"internal",payload:{result:M,request:T}}),d(M)}catch(M){let U=i||J();this.coreActionsService.triggerAction($.ACTIVITY_RESOLVER,{event:L.Events.Resolver.ACTIVITY_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:U,methodName:lr.RESOLVE_ACTIVITIES,moduleName:o,source:"internal",payload:{error:M,request:T}}),c||f(M),d(p)}}else u(),d({})}catch(b){u();let G=i||J();this.coreActionsService.triggerAction($.ACTIVITY_RESOLVER,{event:L.Events.Resolver.ACTIVITY_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:G,methodName:lr.RESOLVE_ACTIVITIES,moduleName:o,source:"internal",payload:{error:b,request:T}}),f(b)}})})}catch(a){this.loggingService.catch("Error in ActivityResolverService resolveActivities:",a);let c=i||J();return this.coreActionsService.triggerAction($.ACTIVITY_RESOLVER,{event:L.Events.Resolver.ACTIVITY_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:c,methodName:lr.RESOLVE_ACTIVITIES,moduleName:o,source:"internal",payload:{error:a,request:t}}),{}}})}saveActivity(t,i){return I(this,null,function*(){try{this.loggingService.log("%c[WB] Calling ActivityResolverService FUNCTION: saveActivity","color: green;");let o=this.getProvider();if(!this.activityDataProviderAvailable())throw new Error("Activity save data provider not available");let s=i||J();this.coreActionsService.triggerAction($.ACTIVITY_RESOLVER,{event:L.Events.Resolver.ACTIVITY_SAVE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:s,methodName:lr.SAVE_ACTIVITY,source:"internal",payload:{request:t}});let a=JSON.parse(JSON.stringify(this.activityById$.getValue()));this.activityById$._value=x(x({},a),t.activity);let c=yield kt(()=>{if(o?.config?.saveConfig?.url){let l={activity:t.activity,event:t.event,metadata:Object.values(t.activity??{})?.[0]?.metadata};return Ht(o.config.saveConfig.url,o.config.saveConfig.headers,l,!1,o.config.saveConfig.credentials)}return o?.save?.({activity:t.activity,event:t.event,metadata:Object.values(t.activity??{})?.[0]?.metadata})||Promise.resolve(void 0)},"saveActivity",this.retrySaveConfig);return c&&c.statusCode!==200?(this.retrySaveConfig.revertOnFailure&&(this.activityById$._value=a),this.loggingService.catch(c?.message??"Error in ActivityResolverService saveActivity:"),this.coreActionsService.triggerAction($.ACTIVITY_RESOLVER,{event:L.Events.Resolver.ACTIVITY_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:s,methodName:lr.SAVE_ACTIVITY,source:"internal",payload:{error:c,request:t}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(L.Events.Resolver.ACTIVITY_RESOLVER_SAVE,{sourceMethod:"saveActivity",source:"sdk",activityIds:Object.keys(t.activity),event:t.event}),this.coreActionsService.triggerAction($.ACTIVITY_RESOLVER,{event:L.Events.Resolver.ACTIVITY_SAVE_RESULT,timestamp:new Date().getTime(),uniqueId:s,methodName:lr.SAVE_ACTIVITY,source:"internal",payload:{result:{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0},request:t}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0})}catch(o){this.loggingService.warn("Error in ActivityResolverService saveActivity:",o);let s=i||J();return this.coreActionsService.triggerAction($.ACTIVITY_RESOLVER,{event:L.Events.Resolver.ACTIVITY_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:s,methodName:lr.SAVE_ACTIVITY,source:"internal",payload:{error:o,request:t}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!1}}})}getActivitiesById$(){try{return this.activityDataProviderAvailable()?(this.loggingService.log("%c[WB] Calling ActivityResolverService FUNCTION: getActivitiesById$","color: green;"),this.activityById$.asObservable()):ue(void 0)}catch(t){return this.loggingService.catch("Error in ActivityResolverService getActivitiesById$:",t),ue(void 0)}}getFieldsToRemove(){try{return this.fieldsToRemove}catch(t){return this.loggingService.catch("Error in ActivityResolverService getFieldsToRemove:",t),this.fieldsToRemove}}setActivityDataProvider(t){try{if(t){this.loggingService.log("Setting activity data provider");let i=t.config,o=[{method:"get",configKey:"getConfig"},{method:"save",configKey:"saveConfig"}],s=[];if(o.forEach(({method:a,configKey:c})=>{let l=i?.[c]?.url,u=a in t&&typeof t[a]=="function";!l&&!u&&s.push(a)}),s.length>0){let a=`DataProviders.activity is invalid. The following methods are missing or are not functions (and no corresponding config provided): ${s.join(", ")}.`;this.loggingService.catch(a);return}else this.activityDataProvider$.next(t)}}catch(i){this.loggingService.catch("Error in ActivityResolverService setActivityDataProvider:",i)}}activityDataProviderAvailable(){try{return!!this.activityDataProvider$.getValue()}catch(t){return this.loggingService.catch("Error in ActivityResolverService activityDataProviderAvailable:",t),!1}}};e.\u0275fac=function(i){return new(i||e)(w(It),w(_e),w(Lt))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let n=e;return n})();var Qy=(()=>{let e=class e{constructor(t,i,o,s,a,c){this.loggingService=t,this.usersService=i,this.authService=o,this.functions=s,this.configService=a,this.reactionAnnotationsResolverService=c}getUserIdsToResolveFromReactions(t){try{let i=new Set;for(let o of t)if(o?.from?.userId&&i.add(o?.from?.userId),o?.reactions?.length)for(let s of o?.reactions)s?.from?.userId&&i.add(s?.from?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in ReactionUtilsService getUserIdsToResolveFromRecorders:",i),[]}}handleReactionEncryption(s){return I(this,arguments,function*({data:t,firestorePath:i,eventType:o}){try{let a=$T(this.authService.getFirebaseConfig()?.firebaseOptions),c=Dr(this.functions,Ir({url:st.cloudFunction?.[a]?.setEncryptedData,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:1200*1e3}),l=tc.getFirestoreProdDbName(this.configService.getApiKey()??"",this.authService.getFirebaseConfig()?.firebaseOptions),u=this.authService.getUser()?.userId??"",d={path:i??"",data:t??{},dbId:l??"",feature:"reaction",eventType:o??"PATCH",sdkVersion:jr()},f=yield il(d,u);yield c({veltData:f})}catch(a){this.loggingService.catch("Error in handleReactionEncryption:",a)}})}mergeReactionWithUser(t){try{if(this.usersService.userDataProviderAvailable()){if(t?.from?.userId){let i=this.usersService.getUserById(t?.from?.userId);i&&(t.from=i)}if(t?.reactions?.length){for(let i of t?.reactions)if(i?.from?.userId){let o=this.usersService.getUserById(i?.from?.userId);o&&(i.from=o)}}}return t}catch(i){return this.loggingService.catch("Error in ReactionUtilsService mergeReactionWithUser:",i),t}}formatReactionData(t){try{return this.usersService.userDataProviderAvailable()&&t?.from?.userId&&(t.from={userId:t.from.userId}),t.reactions=t?.reactions?.map(i=>(this.usersService.userDataProviderAvailable()&&i?.from?.userId&&(i.from={userId:i.from.userId}),i)),t}catch(i){return this.loggingService.catch("Error in ReactionUtilsService formatReactionData:",i),t}}isReactionDataChanged(t,i){try{this.loggingService.log("%c[WB] Calling ReactionUtilsService FUNCTION: isReactionDataChanged","color: green;");let o=this.reactionAnnotationsResolverService.getReactionAnnotationById(i);return o?!ki(t,o):!0}catch(o){return this.loggingService.catch("Error in ReactionUtilsService isReactionDataChanged:",o),!0}}stripReactionAnnotationData(t){try{if(this.loggingService.log("%c[WB] Calling ReactionUtilsService FUNCTION: stripReactionAnnotationData","color: green;"),!this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable())return{originalData:t,strippedData:null};let i={};if(t&&t.annotationId){let o=t.annotationId;if(i[o]=x({annotationId:o,metadata:Cn(t.metadata??{}),icon:t.icon},t?.from&&{from:t?.from}),!this.isReactionDataChanged(i[o],o))return{strippedData:null,originalData:t};delete t?.icon,t.isReactionResolverUsed=!0}return{strippedData:i,originalData:t}}catch(i){return this.loggingService.catch("Error in ReactionUtilsService stripReactionAnnotationData:",i),{strippedData:null,originalData:null}}}mergeStrippedDataWithReactionAnnotations(t){try{if(this.loggingService.log("%c[WB] Calling ReactionUtilsService FUNCTION: mergeStrippedDataWithReactionAnnotations","color: green;"),!this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable())return t;let i=this.reactionAnnotationsResolverService.getReactionAnnotationById(t?.annotationId);return i&&i.icon&&(t.icon=i.icon),t}catch(i){return this.loggingService.catch("Error in ReactionUtilsService mergeStrippedDataWithReactionAnnotations:",i),t}}};e.\u0275fac=function(i){return new(i||e)(w(_e),w(zt),w(Cr),w(dr),w(Rr),w(qo))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let n=e;return n})();var Xy=(()=>{let e=class e{constructor(t,i,o,s,a,c,l,u,d){this.loggingService=t,this.usersService=i,this.commentUtilsService=o,this.reactionUtilsService=s,this.commentAnnotationsResolverService=a,this.reactionAnnotationsResolverService=c,this.recorderAnnotationsResolverService=l,this.activityResolverService=u,this.serviceBook=d}getActivityDisplayMessage(t){try{switch(t.featureType){case"comment":return this.getCommentDisplayMessage(t);case"recorder":return this.getRecorderDisplayMessage(t);case"reaction":return this.getReactionDisplayMessage(t);case"crdt":return this.getCrdtDisplayMessage(t);case"custom":return t.displayMessageTemplate&&t.displayMessageTemplateData?this.resolveTemplate(t.displayMessageTemplate,t.displayMessageTemplateData):"";default:return""}}catch(i){return this.loggingService.catch("Error in ActivityUtilsService getActivityDisplayMessage:",i),""}}resolveTemplate(t,i){try{return t.replace(/\{\{([\w.]+)\}\}/g,(o,s)=>{let a=s.split(".").reduce((c,l)=>{if(c!=null&&typeof c=="object")return c[l]},i);return a!=null?String(a):""})}catch(o){return this.loggingService.catch("Error in ActivityUtilsService resolveTemplate:",o),t}}buildActivityDataFromExtraData(t){try{let{feature:i,extraData:o}=t;if(!o?.actionType)return null;switch(i){case"comment":return this.buildCommentActivityData({commentAnnotation:o.annotationData,targetComment:o.targetAnnotationData,actionType:o.actionType,otherFields:o});case"recorder":return this.buildRecorderActivityData(o);case"reaction":return this.buildReactionActivityData(o);default:return null}}catch(i){return this.loggingService.catch("Error in ActivityUtilsService buildActivityDataFromExtraData:",i),null}}stripActivityPII(t){return I(this,null,function*(){try{let i=JSON.parse(JSON.stringify(t));if(delete i.displayMessage,!this.usersService.userDataProviderAvailable())return{strippedActivity:i};i.actionUser?.userId&&(i.actionUser={userId:i.actionUser.userId}),i.changes&&this.stripUsersFromChanges(i.changes),i.displayMessageTemplateData&&this.stripUsersFromTemplateData(i.displayMessageTemplateData);let o=this.extractCommentChangesForResolver(i),s=this.extractFeatureEntityDataForResolver(i);yield this.stripFeatureSpecificPII(i);let a=this.extractActivityResolverData(i);return o&&(a?a.changes=x(x({},a.changes),o.changes):a=o),s&&(a?(s.entityData!==void 0&&(a.entityData=s.entityData),s.entityTargetData!==void 0&&(a.entityTargetData=s.entityTargetData)):a=s),a&&(i.isActivityResolverUsed=!0),{strippedActivity:i,activityResolverData:a}}catch(i){return this.loggingService.catch("Error in ActivityUtilsService stripActivityPII:",i),{strippedActivity:t}}})}mergeActivityWithUser(t){try{if(!this.usersService.userDataProviderAvailable())return t;if(t=JSON.parse(JSON.stringify(t)),t.actionUser?.userId){let i=this.usersService.getUserById(t.actionUser.userId);i&&(t.actionUser=i)}return t.changes&&this.rehydrateUsersInChanges(t.changes),t.displayMessageTemplateData&&this.rehydrateUsersInTemplateData(t.displayMessageTemplateData),this.rehydrateFeatureSpecificUserData(t),t}catch(i){return this.loggingService.catch("Error in ActivityUtilsService mergeActivityWithUser:",i),t}}mergeActivityWithFeatureData(t){try{switch(t.featureType){case"comment":return this.mergeActivityWithCommentAnnotationData(t);case"reaction":return this.mergeActivityWithReactionData(t);case"recorder":return this.mergeActivityWithRecorderData(t);default:return t}}catch(i){return this.loggingService.catch("Error in ActivityUtilsService mergeActivityWithFeatureData:",i),t}}getUserIdsToResolveFromActivities(t){try{let i=new Set;for(let o of t){if(o.actionUser?.userId&&i.add(o.actionUser.userId),o.changes)for(let s of Object.values(o.changes))s&&(this.extractUserIdFromValue(s.from,i),this.extractUserIdFromValue(s.to,i));if(o.displayMessageTemplateData)for(let s of Object.values(o.displayMessageTemplateData))this.extractUserIdFromValue(s,i);this.extractFeatureSpecificUserIds(o,i)}return Array.from(i)}catch(i){return this.loggingService.catch("Error in ActivityUtilsService getUserIdsToResolveFromActivities:",i),[]}}getEntityIdsToResolveFromActivities(t,i){try{let o=new Set;for(let s of t)if(!(i&&s.featureType!==i))switch(s.featureType){case"comment":case"reaction":case"recorder":s.targetEntityId&&o.add(s.targetEntityId);break}return Array.from(o)}catch(o){return this.loggingService.catch("Error in ActivityUtilsService getEntityIdsToResolveFromActivities:",o),[]}}stripFeatureSpecificPII(t){return I(this,null,function*(){try{switch(t.featureType){case"comment":yield this.stripCommentPII(t);break;case"reaction":this.stripReactionPII(t);break;case"recorder":this.stripRecorderPII(t);break}}catch(i){this.loggingService.catch("Error in ActivityUtilsService stripFeatureSpecificPII:",i)}})}extractActivityResolverData(t){try{if(!this.activityResolverService.activityDataProviderAvailable())return;let i={id:t.id},o=!1;if(t.featureType==="custom"){let s=this.activityResolverService.getFieldsToRemove();for(let a of s)a in t&&t[a]!==void 0&&(i[a]=t[a],delete t[a],o=!0)}return t.metadata&&(i.metadata=Cn(t.metadata)),o?i:void 0}catch(i){this.loggingService.catch("Error in ActivityUtilsService extractActivityResolverData:",i);return}}extractCommentChangesForResolver(t){try{return!this.activityResolverService.activityDataProviderAvailable()||t.featureType!=="comment"||!t.changes?.commentText?void 0:{id:t.id,changes:{commentText:t.changes.commentText},metadata:t.metadata?Cn(t.metadata):void 0}}catch(i){this.loggingService.catch("Error in ActivityUtilsService extractCommentChangesForResolver:",i);return}}extractFeatureEntityDataForResolver(t){try{if(!this.activityResolverService.activityDataProviderAvailable()||!t.entityData)return;let i=t.featureType==="recorder"&&this.recorderAnnotationsResolverService.recorderAnnotationDataProviderAvailable(),o=t.featureType==="reaction"&&this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable();if(!i&&!o)return;let s={id:t.id,metadata:t.metadata?Cn(t.metadata):void 0},a=JSON.parse(JSON.stringify(t.entityData));if(i){let c=this.serviceBook.get(ci)?.stripRecorderAnnotationData({data:a});if(c?.strippedData){let l=Object.keys(c.strippedData)[0];l&&(s.entityData=c.strippedData[l])}}if(o){let c=this.reactionUtilsService.stripReactionAnnotationData(a);if(c?.strippedData){let l=Object.keys(c.strippedData)[0];l&&(s.entityData=c.strippedData[l])}}return s.entityData?s:void 0}catch(i){this.loggingService.catch("Error in ActivityUtilsService extractFeatureEntityDataForResolver:",i);return}}mergeActivityWithResolverData(t){try{if(!this.activityResolverService.activityDataProviderAvailable())return t;let i=this.activityResolverService.getActivityById(t.id);if(!i)return t;i.changes&&(t.changes||(t.changes={}),Object.assign(t.changes,i.changes)),i.entityData!==void 0&&(t.entityData=i.entityData),i.entityTargetData!==void 0&&(t.entityTargetData=i.entityTargetData),i.displayMessageTemplateData&&(t.displayMessageTemplateData||(t.displayMessageTemplateData={}),Object.assign(t.displayMessageTemplateData,i.displayMessageTemplateData));let o=new Set(["id","metadata","changes","entityData","entityTargetData","displayMessageTemplateData"]);for(let[s,a]of Object.entries(i))!o.has(s)&&a!==void 0&&(t[s]=a);return t}catch(i){return this.loggingService.catch("Error in ActivityUtilsService mergeActivityWithResolverData:",i),t}}rehydrateFeatureSpecificUserData(t){try{switch(t.featureType){case"comment":this.rehydrateCommentUserData(t);break;case"reaction":this.rehydrateReactionUserData(t);break;case"recorder":this.rehydrateRecorderUserData(t);break}}catch(i){this.loggingService.catch("Error in ActivityUtilsService rehydrateFeatureSpecificUserData:",i)}}getCommentDisplayMessage(t){try{let i=t.actionUser?.name??"Someone";switch(t.actionType){case xe.ANNOTATION_ADD:return`${i} added a comment`;case xe.COMMENT_ADD:return`${i} replied to a comment`;case xe.COMMENT_UPDATE:return`${i} edited a comment`;case xe.COMMENT_DELETE:return`${i} deleted a comment`;case xe.ANNOTATION_DELETE:return`${i} deleted a comment thread`;case xe.STATUS_CHANGE:{let o=t.changes?.status,s=o?.from?.name,a=o?.to?.name;return s&&a?`${i} changed status from ${s} to ${a}`:`${i} changed the status`}case xe.PRIORITY_CHANGE:{let o=t.changes?.priority,s=o?.to;if(!s)return`${i} removed the priority`;let a=typeof s=="object"?s?.name:String(s),c=o?.from,l=c&&typeof c=="object"?c?.name:c?String(c):null;return l&&a?`${i} changed priority from ${l} to ${a}`:`${i} changed priority to ${a}`}case xe.ASSIGN:{let s=t.changes?.assignedTo?.to;return s&&typeof s=="object"&&s.name?`${i} assigned to ${s.name}`:`${i} assigned the comment`}case xe.ACCESS_MODE_CHANGE:{let s=t.changes?.accessMode?.to;return s?`${i} changed access to ${s}`:`${i} changed the access mode`}case xe.CUSTOM_LIST_CHANGE:return`${i} changed the custom list`;case xe.APPROVE:return`${i} approved the comment`;case xe.ACCEPT:case xe.SUGGESTION_ACCEPT:return`${i} accepted a suggestion`;case xe.REJECT:case xe.SUGGESTION_REJECT:return`${i} rejected a suggestion`;case xe.REACTION_ADD:return`${i} reacted to a comment`;case xe.REACTION_DELETE:return`${i} removed a reaction`;case xe.SUBSCRIBE:return`${i} subscribed to the thread`;case xe.UNSUBSCRIBE:return`${i} unsubscribed from the thread`;default:return""}}catch(i){return this.loggingService.catch("Error in ActivityUtilsService getCommentDisplayMessage:",i),""}}getRecorderDisplayMessage(t){try{let i=t.actionUser?.name??"Someone";switch(t.actionType){case vg.RECORDING_ADD:return`${i} added a recording`;case vg.RECORDING_DELETE:return`${i} deleted a recording`;default:return""}}catch(i){return this.loggingService.catch("Error in ActivityUtilsService getRecorderDisplayMessage:",i),""}}getReactionDisplayMessage(t){try{let i=t.actionUser?.name??"Someone";switch(t.actionType){case yg.REACTION_ADD:return`${i} added a reaction`;case yg.REACTION_DELETE:return`${i} removed a reaction`;default:return""}}catch(i){return this.loggingService.catch("Error in ActivityUtilsService getReactionDisplayMessage:",i),""}}getCrdtDisplayMessage(t){try{let i=t.actionUser?.name??"Someone",s=t.entityData?.editCount??0,a=t.targetEntityId??"unknown";return`${i} made ${s} edit${s!==1?"s":""} to editor ${a}`}catch(i){return this.loggingService.catch("Error in ActivityUtilsService getCrdtDisplayMessage:",i),""}}stripCommentPII(t){return I(this,null,function*(){try{let i=yield this.commentUtilsService.stripCommentAnnotationData({data:t.entityData,actionType:t.eventType??Ie.NEWLY_ADDED});i?.originalData&&(t.entityData=this.commentUtilsService.formatCommentData(i.originalData)),t.entityTargetData&&(t.entityTargetData=this.commentUtilsService.formatCommentThreadData(this.commentUtilsService.stripCommentsFromAnnotationData({comment:t.entityTargetData}))),this.activityResolverService.activityDataProviderAvailable()&&t.changes?.commentText&&delete t.changes.commentText}catch(i){this.loggingService.catch("Error in ActivityUtilsService stripCommentPII:",i)}})}rehydrateCommentUserData(t){try{t.entityData&&this.commentUtilsService.mergeCommentWithUser(t.entityData),t.entityTargetData&&(this.rehydrateUserInObject(t.entityTargetData,"from"),this.rehydrateUsersInArray(t.entityTargetData,"to"),this.rehydrateUsersInArray(t.entityTargetData,"taggedUserContacts"))}catch(i){this.loggingService.catch("Error in ActivityUtilsService rehydrateCommentUserData:",i)}}stripReactionPII(t){try{if(!t.entityData)return;this.activityResolverService.activityDataProviderAvailable()&&this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable()&&this.reactionUtilsService.stripReactionAnnotationData(t.entityData),t.entityData=this.reactionUtilsService.formatReactionData(t.entityData)}catch(i){this.loggingService.catch("Error in ActivityUtilsService stripReactionPII:",i)}}rehydrateReactionUserData(t){try{if(!t.entityData)return;this.reactionUtilsService.mergeReactionWithUser(t.entityData)}catch(i){this.loggingService.catch("Error in ActivityUtilsService rehydrateReactionUserData:",i)}}stripRecorderPII(t){try{if(!t.entityData)return;if(this.activityResolverService.activityDataProviderAvailable()&&this.recorderAnnotationsResolverService.recorderAnnotationDataProviderAvailable()){this.serviceBook.get(ci)?.stripRecorderAnnotationData({data:t.entityData});return}let i=t.entityData;if(this.usersService.userDataProviderAvailable()){i.from&&typeof i.from=="object"&&"userId"in i.from&&(i.from={userId:i.from.userId});let o=i.transcription;o?.from&&typeof o.from=="object"&&"userId"in o.from&&(o.from={userId:o.from.userId})}}catch(i){this.loggingService.catch("Error in ActivityUtilsService stripRecorderPII:",i)}}rehydrateRecorderUserData(t){try{if(!t.entityData)return;this.serviceBook.get(ci)?.mergeRecorderWithUser(t.entityData)}catch(i){this.loggingService.catch("Error in ActivityUtilsService rehydrateRecorderUserData:",i)}}mergeActivityWithCommentAnnotationData(t){try{if(!this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())return t;let i=this.commentAnnotationsResolverService.getAnnotationById(t.targetEntityId);if(!i)return t;let o=t.entityData?.comments;if(Array.isArray(o))for(let s of o){let a=s?.commentId;if(a==null)continue;let c=i.comments?.[String(a)];c&&(c.commentText&&(s.commentText=c.commentText),c.commentHtml&&(s.commentHtml=c.commentHtml))}if(t.targetSubEntityId&&t.entityTargetData){let s=i.comments?.[t.targetSubEntityId];if(s){let a=t.entityTargetData;s.commentText&&(a.commentText=s.commentText),s.commentHtml&&(a.commentHtml=s.commentHtml)}}return t}catch(i){return this.loggingService.catch("Error in ActivityUtilsService mergeActivityWithCommentAnnotationData:",i),t}}mergeActivityWithReactionData(t){try{return!this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable()||!t.targetEntityId||!t.entityData||this.reactionUtilsService.mergeStrippedDataWithReactionAnnotations(t.entityData),t}catch(i){return this.loggingService.catch("Error in ActivityUtilsService mergeActivityWithReactionData:",i),t}}mergeActivityWithRecorderData(t){try{return!this.recorderAnnotationsResolverService.recorderAnnotationDataProviderAvailable()||!t.targetEntityId||!t.entityData||this.serviceBook.get(ci)?.mergeStrippedDataWithRecorderAnnotation(t.entityData),t}catch(i){return this.loggingService.catch("Error in ActivityUtilsService mergeActivityWithRecorderData:",i),t}}buildCommentActivityData(t){try{let{commentAnnotation:i,targetComment:o,actionType:s,otherFields:a}=t,c=i,l=o,u=s===Ie.DELETED&&a?.isAnnotationDelete?xe.ANNOTATION_DELETE:this.mapCommentStatusToActionType(s);if(!u)return null;let d=c?.annotationId;if(!d)return null;let f=l?.commentId,g=this.buildCommentChanges(s,l,a);return{featureType:"comment",actionType:u,targetEntityId:d,eventType:s,targetSubEntityId:f??null,changes:Object.keys(g).length>0?g:void 0,entityData:i,entityTargetData:o??void 0}}catch(i){return this.loggingService.catch("Error in ActivityUtilsService buildCommentActivityData:",i),null}}mapCommentStatusToActionType(t){try{switch(t){case Ie.NEWLY_ADDED:return xe.ANNOTATION_ADD;case Ie.ADDED:return xe.COMMENT_ADD;case Ie.UPDATED:return xe.COMMENT_UPDATE;case Ie.DELETED:return xe.COMMENT_DELETE;case Ie.STATUS_CHANGED:return xe.STATUS_CHANGE;case Ie.PRIORITY_CHANGED:return xe.PRIORITY_CHANGE;case Ie.ASSIGNED:return xe.ASSIGN;case Ie.ACCESS_MODE_CHANGED:return xe.ACCESS_MODE_CHANGE;case Ie.CUSTOM_LIST_CHANGED:return xe.CUSTOM_LIST_CHANGE;case Ie.APPROVED:return xe.APPROVE;case Ie.ACCEPTED:return xe.ACCEPT;case Ie.REJECTED:return xe.REJECT;case Ie.SUGGESTION_ACCEPTED:return xe.SUGGESTION_ACCEPT;case Ie.SUGGESTION_REJECTED:return xe.SUGGESTION_REJECT;case Ie.REACTION_ADDED:return xe.REACTION_ADD;case Ie.REACTION_DELETED:return xe.REACTION_DELETE;case Ie.SUBSCRIBED:return xe.SUBSCRIBE;case Ie.UNSUBSCRIBED:return xe.UNSUBSCRIBE;default:return null}}catch(i){return this.loggingService.catch("Error in ActivityUtilsService mapCommentStatusToActionType:",i),null}}buildRecorderActivityData(t){try{let i=t.annotationData,o=t.actionType,s=this.mapRecorderStatusToActionType(o);if(!s)return null;let a=i?.annotationId;return a?{featureType:"recorder",actionType:s,targetEntityId:a,entityData:i}:null}catch(i){return this.loggingService.catch("Error in ActivityUtilsService buildRecorderActivityData:",i),null}}mapRecorderStatusToActionType(t){try{switch(t){case _T.ADDED:return vg.RECORDING_ADD;case _T.DELETED:return vg.RECORDING_DELETE;default:return null}}catch(i){return this.loggingService.catch("Error in ActivityUtilsService mapRecorderStatusToActionType:",i),null}}buildReactionActivityData(t){try{let i=t.annotationData,o=t.actionType,s=this.mapReactionActionType(o);if(!s)return null;let a=i?.annotationId;return a?{featureType:"reaction",actionType:s,targetEntityId:a,entityData:i}:null}catch(i){return this.loggingService.catch("Error in ActivityUtilsService buildReactionActivityData:",i),null}}mapReactionActionType(t){try{switch(t){case"add":return yg.REACTION_ADD;case"delete":return yg.REACTION_DELETE;default:return null}}catch(i){return this.loggingService.catch("Error in ActivityUtilsService mapReactionActionType:",i),null}}buildCommentChanges(t,i,o){try{let s={};switch(t){case Ie.NEWLY_ADDED:case Ie.ADDED:s.commentText={from:null,to:i?.commentText??null};break;case Ie.UPDATED:s.commentText={from:o?.oldCommentText??null,to:i?.commentText??null};break;case Ie.DELETED:s.commentText={from:i?.commentText??null,to:null};break;case Ie.STATUS_CHANGED:s.status={from:o?.oldStatus??null,to:o?.newStatus??null};break;case Ie.PRIORITY_CHANGED:s.priority={from:o?.oldPriority??null,to:o?.newPriority??null};break;case Ie.ASSIGNED:{s.assignedTo={from:o?.oldAssignedTo??null,to:o?.newAssignedTo??null};break}case Ie.ACCESS_MODE_CHANGED:s.accessMode={from:o?.oldAccessMode??null,to:o?.newAccessMode??null};break;case Ie.CUSTOM_LIST_CHANGED:s.customList={from:o?.oldCustomList??null,to:o?.newCustomList??null};break}return s}catch(s){return this.loggingService.catch("Error in ActivityUtilsService buildCommentChanges:",s),{}}}extractFeatureSpecificUserIds(t,i){try{switch(t.featureType){case"comment":this.extractCommentActivityUserIds(t,i);break;case"reaction":this.extractReactionActivityUserIds(t,i);break;case"recorder":this.extractRecorderActivityUserIds(t,i);break}}catch(o){this.loggingService.catch("Error in ActivityUtilsService extractFeatureSpecificUserIds:",o)}}extractCommentActivityUserIds(t,i){try{if(t.entityData){let o=this.commentUtilsService.getUserIdsToResolveFromComments([t.entityData]);for(let s of o)i.add(s)}if(t.entityTargetData){let o=t.entityTargetData;if(this.extractUserIdFromValue(o.from,i),Array.isArray(o.to))for(let s of o.to)this.extractUserIdFromValue(s,i);if(Array.isArray(o.taggedUserContacts))for(let s of o.taggedUserContacts)this.extractUserIdFromValue(s,i)}}catch(o){this.loggingService.catch("Error in ActivityUtilsService extractCommentActivityUserIds:",o)}}extractReactionActivityUserIds(t,i){try{if(!t.entityData)return;let o=this.reactionUtilsService.getUserIdsToResolveFromReactions([t.entityData]);for(let s of o)i.add(s)}catch(o){this.loggingService.catch("Error in ActivityUtilsService extractReactionActivityUserIds:",o)}}extractRecorderActivityUserIds(t,i){try{if(!t.entityData)return;let o=this.serviceBook.get(ci)?.getUserIdsToResolveFromRecorders([t.entityData])??[];for(let s of o)i.add(s)}catch(o){this.loggingService.catch("Error in ActivityUtilsService extractRecorderActivityUserIds:",o)}}stripUsersFromChanges(t){try{for(let i of Object.keys(t)){let o=t[i];o&&(o.from=this.stripUserIfPresent(o.from),o.to=this.stripUserIfPresent(o.to))}}catch(i){this.loggingService.catch("Error in ActivityUtilsService stripUsersFromChanges:",i)}}stripUserIfPresent(t){try{return t&&typeof t=="object"&&"userId"in t?{userId:t.userId}:t}catch(i){return this.loggingService.catch("Error in ActivityUtilsService stripUserIfPresent:",i),t}}stripUsersFromTemplateData(t){try{for(let i of Object.keys(t)){let o=t[i];o&&typeof o=="object"&&"userId"in o&&(t[i]={userId:o.userId})}}catch(i){this.loggingService.catch("Error in ActivityUtilsService stripUsersFromTemplateData:",i)}}rehydrateUsersInChanges(t){try{for(let i of Object.values(t))i&&(i.from=this.rehydrateIfUser(i.from),i.to=this.rehydrateIfUser(i.to))}catch(i){this.loggingService.catch("Error in ActivityUtilsService rehydrateUsersInChanges:",i)}}rehydrateIfUser(t){try{if(t&&typeof t=="object"&&"userId"in t){let i=t.userId;return this.usersService.getUserById(i)??t}return t}catch(i){return this.loggingService.catch("Error in ActivityUtilsService rehydrateIfUser:",i),t}}rehydrateUsersInTemplateData(t){try{for(let i of Object.keys(t))t[i]=this.rehydrateIfUser(t[i])}catch(i){this.loggingService.catch("Error in ActivityUtilsService rehydrateUsersInTemplateData:",i)}}rehydrateUserInObject(t,i){try{let o=t[i];if(o&&typeof o=="object"&&"userId"in o){let s=o.userId,a=this.usersService.getUserById(s);a&&(t[i]=a)}}catch(o){this.loggingService.catch("Error in ActivityUtilsService rehydrateUserInObject:",o)}}rehydrateUsersInArray(t,i){try{let o=t[i];Array.isArray(o)&&(t[i]=o.map(s=>this.rehydrateIfUser(s)))}catch(o){this.loggingService.catch("Error in ActivityUtilsService rehydrateUsersInArray:",o)}}extractUserIdFromValue(t,i){try{if(t&&typeof t=="object"&&"userId"in t){let o=t.userId;typeof o=="string"&&i.add(o)}}catch(o){this.loggingService.catch("Error in ActivityUtilsService extractUserIdFromValue:",o)}}};e.\u0275fac=function(i){return new(i||e)(w(_e),w(zt),w(Ky),w(Qy),w(zo),w(qo),w(ec),w(Yy),w(li))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let n=e;return n})();var Jy=class{constructor({apiKey:e,documentId:r,organizationId:t,folderId:i,veltFolderId:o,clientDocumentId:s,clientOrganizationId:a}){this.paths={},this.apiKey=e,this.documentId=r,this.organizationId=t,this.folderId=i,this.veltFolderId=o,this.clientDocumentId=s,this.clientOrganizationId=a,s&&(this.documentId=da(s)),a&&(this.organizationId=Ts(a)),i&&(this.folderId=i,this.veltFolderId=wo(i)),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 e=`${this.apiKey}`;this.organizationId&&(e=`${e}/${v.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${this.paths.organizationId}`),this.documentId&&(this.paths.docs=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/`,this.paths.folder=`${e}/${v.FIREBASE_PARTIAL_PATH_FOLDERS}/`,this.paths.presence=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_PRESENCE}/`,this.paths.cursor=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_CURSOR}/`,this.paths.comment=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_COMMENT}/`,this.paths.multiThread=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_MULTI_THREAD}/`,this.paths.tag=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_TAG}/`,this.paths.area=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_AREA}/`,this.paths.arrow=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_ARROW}/`,this.paths.selection=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_SELECTION}/`,this.paths.audioHuddle=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_AUDIO_HUDDLE}/`,this.paths.huddle=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_HUDDLE}/`,this.paths.recorder=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_RECORDER}/`,this.paths.flock=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_FOLLOW_ALONG}/`,this.paths.syncVideoPlayer=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_SYNC_VIDEO_PLAYER}/`,this.paths.liveState=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_LIVE_STATE}/`,this.paths.liveStateSingleEditorMode=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_LIVE_STATE}/default/singleEditorMode`,this.paths.reaction=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_REACTION}/`,this.paths.crdt=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_CRDT}/`,this.paths.views=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_VIEWS}/`,this.paths.notifications=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_NOTIFICATIONS}/`,this.paths.metadata=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_METADATA}/`,this.paths.users=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_USERS}/`,this.paths.documentIam=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_IAM}/`,this.paths.userConfig=`${e}/${v.FIREBASE_PARTIAL_PATH_USERS}`),this.paths.customerMetadata=`${e}/${v.FIREBASE_PARTIAL_PATH_CUSTOMER_METADATA}/`,this.paths.groupContacts=`${e}/${v.FIREBASE_PARTIAL_PATH_CONTACTS}/${v.FIREBASE_PARTIAL_PATH_GROUPS}/`,this.paths.globalContacts=`${e}/${v.FIREBASE_PARTIAL_PATH_CONTACTS}/${v.FIREBASE_PARTIAL_PATH_GLOBAL}/`,this.paths.logins=`${e}/${v.FIREBASE_PARTIAL_PATH_CONTACTS}/${v.FIREBASE_PARTIAL_PATH_LOGINS}/`,this.paths.userFeedback=`${e}/${v.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${v.FIREBASE_PARTIAL_PATH_FEEDBACK}/`,this.paths.userReportBugs=`${e}/${v.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${v.FIREBASE_PARTIAL_PATH_BUGS}/`,this.paths.userContactUs=`${e}/${v.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${v.FIREBASE_PARTIAL_PATH_CONTACT_US}/`,this.organizationId&&(this.paths.organizationMetadata=`${e}/${v.FIREBASE_PARTIAL_PATH_ORGANIZATION_METADATA}/`,this.paths.organizationIam=`${e}/${v.FIREBASE_PARTIAL_PATH_IAM}/`,this.paths.organizationGroups=`${e}/${v.FIREBASE_PARTIAL_PATH_ORGANIZATION_GROUPS}/`,this.paths.organizationNotifications=`${e}/${v.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/`,this.documentId&&(this.paths.organizationNotificationsWithDocumentId=`${e}/${v.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/`,this.paths.heartbeatByDocument=`${e}/${v.FIREBASE_PARTIAL_PATH_HEARTBEAT_BY_DOCUMENT}/${this.documentId}/`),this.paths.organizationNotificationsLastNotificationTimestamp=`${e}/${v.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${v.FIREBASE_PARTIAL_PATH_LAST_NOTIFICATION_TIMESTAMP}/${v.FIREBASE_PARTIAL_PATH_DOCS}/`,this.paths.organizationNotificationsUsers=`${e}/${v.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${v.FIREBASE_PARTIAL_PATH_USERS}/`,this.paths.heartbeat=`${e}/${v.FIREBASE_PARTIAL_PATH_HEARTBEAT}/`),this.paths.workspaceIam=`${this.apiKey}/${v.FIREBASE_PARTIAL_PATH_IAM}/`}}catch{}}get folder(){return this.paths.folder?this.paths.folder:this.throwError("Folder path is not available.")}get userConfig(){return this.paths.userConfig?this.paths.userConfig:this.throwError("User config path is not available.")}get workspaceIam(){return this.paths.workspaceIam?this.paths.workspaceIam:this.throwError("Workspace IAM path is not available.")}get docs(){return this.paths.docs?this.paths.docs:this.throwError("Docs path is not available.")}get presence(){return this.paths.presence?this.paths.presence:this.throwError("Presence path is not available.")}get cursor(){return this.paths.cursor?this.paths.cursor:this.throwError("Cursor path is not available.")}get area(){return this.paths.area?this.paths.area:this.throwError("Area path is not available.")}get arrow(){return this.paths.arrow?this.paths.arrow:this.throwError("Arrow path is not available.")}get comment(){return this.paths.comment?this.paths.comment:this.throwError("Comment path is not available.")}get multiThread(){return this.paths.multiThread?this.paths.multiThread:this.throwError("Multi thread path is not available.")}get tag(){return this.paths.tag?this.paths.tag:this.throwError("Tag path is not available.")}get selection(){return this.paths.selection?this.paths.selection:this.throwError("Selection path is not available.")}get audioHuddle(){return this.paths.audioHuddle?this.paths.audioHuddle:this.throwError("Audio huddle path is not available.")}get huddle(){return this.paths.huddle?this.paths.huddle:this.throwError("Huddle path is not available.")}get recorder(){return this.paths.recorder?this.paths.recorder:this.throwError("Recorder path is not available.")}get flock(){return this.paths.flock?this.paths.flock:this.throwError("Flock path is not available.")}get syncVideoPlayer(){return this.paths.syncVideoPlayer?this.paths.syncVideoPlayer:this.throwError("Sync video player path is not available.")}get liveState(){return this.paths.liveState?this.paths.liveState:this.throwError("Live state path is not available.")}get liveStateSingleEditorMode(){return this.paths.liveStateSingleEditorMode?this.paths.liveStateSingleEditorMode:this.throwError("Live state single editor mode path is not available.")}get reaction(){return this.paths.reaction?this.paths.reaction:this.throwError("Reaction path is not available.")}get crdt(){return this.paths.crdt?this.paths.crdt:this.throwError("CRDT path is not available.")}get views(){return this.paths.views?this.paths.views:this.throwError("Views path is not available.")}get notifications(){return this.paths.notifications?this.paths.notifications:this.throwError("Notifications path is not available.")}get metadata(){return this.paths.metadata?this.paths.metadata:this.throwError("Metadata path is not available.")}get users(){return this.paths.users?this.paths.users:this.throwError("Users path is not available.")}get documentIam(){return this.paths.documentIam?this.paths.documentIam:this.throwError("Document IAM path is not available.")}get organizationMetadata(){return this.paths.organizationMetadata?this.paths.organizationMetadata:this.throwError("Organization metadata path is not available.")}get organizationIam(){return this.paths.organizationIam?this.paths.organizationIam:this.throwError("Organization IAM path is not available.")}get customerMetadata(){return this.paths.customerMetadata?this.paths.customerMetadata:this.throwError("Customer metadata path is not available.")}get groupContacts(){return this.paths.groupContacts?this.paths.groupContacts:this.throwError("Group contacts path is not available.")}get globalContacts(){return this.paths.globalContacts?this.paths.globalContacts:this.throwError("Global contacts path is not available.")}get logins(){return this.paths.logins?this.paths.logins:this.throwError("Logins path is not available.")}get userFeedback(){return this.paths.userFeedback?this.paths.userFeedback:this.throwError("User feedback path is not available.")}get userReportBugs(){return this.paths.userReportBugs?this.paths.userReportBugs:this.throwError("User report bugs path is not available.")}get userContactUs(){return this.paths.userContactUs?this.paths.userContactUs:this.throwError("User contact us path is not available.")}get organizationGroups(){return this.paths.organizationGroups?this.paths.organizationGroups:this.throwError("Organization groups path is not available.")}get heartbeat(){return this.paths.heartbeat?this.paths.heartbeat:this.throwError("Heartbeat path is not available.")}get heartbeatByDocument(){return this.paths.heartbeatByDocument?this.paths.heartbeatByDocument:this.throwError("Heartbeat by document 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(e){throw{type:"DocumentPaths",message:e,metadata:{apiKey:this.apiKey,documentId:this.documentId,organizationId:this.organizationId}}}};var zz=(()=>{let e=class e{constructor(t,i,o){this.coreActionsService=t,this.loggingService=i,this.usersService=o}getUserIdsToResolveFromLiveStateCustom(t){try{let i=new Set;return t?.updatedBy&&i.add(t?.updatedBy?.userId),Array.from(i)}catch(i){return this.loggingService.catch("Error in LiveStateUtilsService getUserIdsToResolveFromLiveStateCustom:",i),[]}}mergeLiveStateCustomWithUser(t){try{if(t?.updatedBy?.userId){let i=this.usersService.getUserById(t?.updatedBy?.userId);i&&(t.updatedBy=i)}return t}catch(i){return this.loggingService.catch("Error in LiveStateUtilsService mergeLiveStateCustomWithUser:",i),t}}formatLiveStateCustomData(t){try{return this.usersService.userDataProviderAvailable()&&t?.updatedBy&&(t.updatedBy={userId:t.updatedBy.userId}),t}catch(i){return this.loggingService.catch("Error in LiveStateUtilsService formatLiveStateCustomData:",i),t}}getUserIdsToResolveFromLiveStateCustoms(t){try{let i=new Set;for(let o of t)o?.updatedBy?.userId&&i.add(o?.updatedBy?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in LiveStateUtilsService getUserIdsToResolveFromLiveStateCustoms:",i),[]}}getUserIdsToResolveFromLiveStates(t){try{let i=new Set;return t?.default?.singleEditorMode?.editor?.userId&&i.add(t?.default?.singleEditorMode?.editor?.userId),Array.from(i)}catch(i){return this.loggingService.catch("Error in LiveStateUtilsService getUserIdsToResolveFromLiveStates:",i),[]}}getUserIdsToResolveFromLiveStateSingleEditorMode(t){try{let i=new Set;return t?.editor?.userId&&i.add(t?.editor?.userId),t?.requestEditorAccess?.user?.userId&&i.add(t?.requestEditorAccess?.user?.userId),Array.from(i)}catch(i){return this.loggingService.catch("Error in LiveStateUtilsService getUserIdsToResolveFromLiveStateSingleEditorMode:",i),[]}}mergeLiveStateWithUser(t){try{if(t?.default?.singleEditorMode?.editor?.userId){let i=this.usersService.getUserById(t?.default?.singleEditorMode?.editor?.userId);i&&(t.default.singleEditorMode.editor=i)}if(t?.default?.singleEditorMode?.requestEditorAccess?.user?.userId){let i=this.usersService.getUserById(t?.default?.singleEditorMode?.requestEditorAccess?.user?.userId);i&&(t.default.singleEditorMode.requestEditorAccess.user=i)}return t}catch(i){return this.loggingService.catch("Error in LiveStateUtilsService mergeLiveStateWithUser:",i),t}}mergeSingleEditorLiveStateDataWithUser(t){try{if(t?.editor?.userId){let i=this.usersService.getUserById(t?.editor?.userId);i&&(t.editor=i)}if(t?.requestEditorAccess?.user?.userId){let i=this.usersService.getUserById(t?.requestEditorAccess?.user?.userId);i&&(t.requestEditorAccess.user=i)}return t}catch(i){return this.loggingService.catch("Error in LiveStateUtilsService mergeSingleEditorLiveStateDataWithUser:",i),t}}resolveAndMergeSingleEditorLiveStateDataWithUser(t){return I(this,null,function*(){try{let i=this.getUserIdsToResolveFromLiveStates({default:{singleEditorMode:t}});if(i.length){let o=J(),s=tl.GET_SINGLE_EDITOR_USERS;return this.coreActionsService.triggerAction($.USER_RESOLVER,{event:L.Events.Resolver.USER_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:o,methodName:xn.RESOLVE_AND_MERGE_SINGLE_EDITOR_LIVE_STATE_DATA_WITH_USER,moduleName:s,source:"internal",payload:{userIds:i}}),yield this.usersService.resolveUsers({userIds:i,uniqueId:o,moduleName:s}),this.mergeSingleEditorLiveStateDataWithUser(t)}return t}catch(i){return this.loggingService.catch("Error in LiveStateUtilsService resolveAndMergeSingleEditorLiveStateDataWithUser:",i),t}})}formatLiveStateSingleEditorModeData(t){try{return this.usersService.userDataProviderAvailable()&&(t?.editor?.userId&&(t.editor={userId:t.editor.userId}),t?.requestEditorAccess?.user?.userId&&(t.requestEditorAccess.user={userId:t.requestEditorAccess.user.userId})),t}catch(i){return this.loggingService.catch("Error in LiveStateUtilsService formatLiveStateSingleEditorModeData:",i),t}}mergeLiveStateCustomsWithUsers(t){try{for(let i of t)if(i?.updatedBy?.userId){let o=this.usersService.getUserById(i?.updatedBy?.userId);o&&(i.updatedBy=o)}return t}catch(i){return this.loggingService.catch("Error in mergeLiveStateCustomsWithUsers:",i),t}}};e.\u0275fac=function(i){return new(i||e)(w(It),w(_e),w(zt))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let n=e;return n})();var Zy=(()=>{let e=class e{constructor(t,i,o){this.coreActionsService=t,this.loggingService=i,this.analyticsService=o,this.resolveTimeout=60*1e3,this.retryDeleteConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.retryGetConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.notificationDataProvider$=new Y(null),this.notificationById$=new Y({}),this.inFlightRequests=new Map,this.getNotificationById=s=>{try{return this.notificationDataProviderAvailable()?this.notificationById$.value?.[s]:void 0}catch(a){this.loggingService.catch("Error in NotificationResolverService getNotificationById:",a);return}};try{this.loggingService.log("NotificationResolverService initialized"),this.notificationDataProvider$.subscribe(s=>{s&&(s.config?.resolveTimeout&&(this.resolveTimeout=s.config.resolveTimeout),s.config?.deleteRetryConfig&&(this.retryDeleteConfig=s.config.deleteRetryConfig),s.config?.getRetryConfig&&(this.retryGetConfig=s.config.getRetryConfig))})}catch(s){this.loggingService.catch("Error in NotificationResolverService constructor:",s)}}getProvider(){try{let t=this.notificationDataProvider$.getValue();return t||void 0}catch(t){this.loggingService.catch("Error in NotificationResolverService getProvider:",t);return}}ngOnDestroy(){try{this.notificationById$.next({})}catch(t){this.loggingService.catch("Error in NotificationResolverService ngOnDestroy:",t)}}resolveNotifications(s){return I(this,arguments,function*({request:t,uniqueId:i,moduleName:o}){try{if(this.loggingService.log("%c[WB] Calling NotificationResolverService FUNCTION: resolveNotifications","color: green;"),!this.notificationDataProviderAvailable())return{};let a,c=!1,l=!1,u=()=>{a&&(clearTimeout(a),a=void 0,l=!0)};return new Promise((d,f)=>{a=setTimeout(()=>{if(!l){c=!0,u();let k=i||J();this.coreActionsService.triggerAction($.NOTIFICATION_RESOLVER,{event:L.Events.Resolver.NOTIFICATION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:k,methodName:Fn.RESOLVE_NOTIFICATIONS,moduleName:o,source:"internal",payload:{error:new Error("Notification resolution timeout"),request:t}}),f(new Error("Notification resolution timeout"))}},this.notificationDataProvider$.value?.config?.resolveTimeout||this.resolveTimeout);let g=this.getProvider();if(!g)return u(),d({});let p={},_=this.notificationById$.getValue()||{},T=[...new Set(t.notificationIds||[])],D=[],b=[],G=[];for(let k of T)_[k]||(this.inFlightRequests.has(k)?(D.push(this.inFlightRequests.get(k)),b.push(k)):G.push(k));let M=le(x({},t),{notificationIds:G});I(this,null,function*(){try{if(D.length>0&&(yield Promise.allSettled(D)),G.length>0){let k=i||J();this.coreActionsService.triggerAction($.NOTIFICATION_RESOLVER,{event:L.Events.Resolver.NOTIFICATION_RESOLUTION_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:k,methodName:Fn.RESOLVE_NOTIFICATIONS,moduleName:o,source:"internal",payload:{request:M}});let S,A=new Promise(O=>{S=O});for(let O of G)this.inFlightRequests.set(O,A.then(P=>P?.[O]));let C=kt(()=>g?.config?.getConfig?.url?Ht(g.config.getConfig.url,g.config.getConfig.headers,M,!0,g.config.getConfig.credentials):g?.get?.(M)||Promise.resolve(void 0),"getNotifications",this.retryGetConfig).then(O=>c?{}:(u(),O&&O.statusCode!==200?(this.coreActionsService.triggerAction($.NOTIFICATION_RESOLVER,{event:L.Events.Resolver.NOTIFICATION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:k,methodName:Fn.RESOLVE_NOTIFICATIONS,moduleName:o,source:"internal",payload:{result:O,request:M}}),this.loggingService.catch(O?.message??"Error in NotificationResolverService resolveNotifications:"),{}):O?.data)).catch(O=>{throw u(),O});try{p=(yield C)||{},S(p);for(let P of G)this.inFlightRequests.delete(P);this.analyticsService.trackEvent(L.Events.Resolver.NOTIFICATION_RESOLVER_GET,{sourceMethod:"resolveNotifications",source:"sdk",notificationIds:G});let O={};Object.entries(p).forEach(([P,F])=>{let N=this.notificationById$.value?.[P];N?N&&JSON.stringify(N)!==JSON.stringify(F)&&(O[P]=F):O[P]=F}),Object.keys(O).length>0&&this.notificationById$.next(x(x({},this.notificationById$.getValue()),O)),this.coreActionsService.triggerAction($.NOTIFICATION_RESOLVER,{event:L.Events.Resolver.NOTIFICATION_RESOLUTION_RESULT,timestamp:new Date().getTime(),uniqueId:k,methodName:Fn.RESOLVE_NOTIFICATIONS,moduleName:o,source:"internal",payload:{result:O,request:M}}),d(O)}catch(O){S({});for(let F of G)this.inFlightRequests.delete(F);let P=i||J();this.coreActionsService.triggerAction($.NOTIFICATION_RESOLVER,{event:L.Events.Resolver.NOTIFICATION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:P,methodName:Fn.RESOLVE_NOTIFICATIONS,moduleName:o,source:"internal",payload:{error:O,request:M}}),c||f(O),d(p)}}else u(),d({})}catch(k){u();let S=i||J();this.coreActionsService.triggerAction($.NOTIFICATION_RESOLVER,{event:L.Events.Resolver.NOTIFICATION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:S,methodName:Fn.RESOLVE_NOTIFICATIONS,moduleName:o,source:"internal",payload:{error:k,request:M}}),f(k)}})})}catch(a){this.loggingService.catch("Error in NotificationResolverService resolveNotifications:",a);let c=i||J();return this.coreActionsService.triggerAction($.NOTIFICATION_RESOLVER,{event:L.Events.Resolver.NOTIFICATION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:c,methodName:Fn.RESOLVE_NOTIFICATIONS,moduleName:o,source:"internal",payload:{error:a,request:t}}),{}}})}deleteNotification(t,i,o){return I(this,null,function*(){try{this.loggingService.log("%c[WB] Calling NotificationResolverService FUNCTION: deleteNotification","color: green;");let s=this.getProvider();if(!this.notificationDataProviderAvailable())throw new Error("Notification delete data provider not available");let a=o||J();this.coreActionsService.triggerAction($.NOTIFICATION_RESOLVER,{event:L.Events.Resolver.NOTIFICATION_DELETE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:a,methodName:Fn.DELETE_NOTIFICATION,source:"internal",payload:{notificationId:t,organizationId:i}});let c=this.notificationById$.getValue(),l=x({},c);delete l?.[t],this.notificationById$._value=l;let u={notificationId:t,organizationId:i},d=yield kt(()=>s?.config?.deleteConfig?.url?Ht(s.config.deleteConfig.url,s.config.deleteConfig.headers,u,!1,s.config.deleteConfig.credentials):s?.delete?.(u)||Promise.resolve(void 0),"deleteNotification",this.retryDeleteConfig);return d&&d.statusCode!==200?(this.retryDeleteConfig.revertOnFailure&&(this.notificationById$._value=c),this.loggingService.catch(d?.message??"Error in NotificationResolverService deleteNotification:"),this.coreActionsService.triggerAction($.NOTIFICATION_RESOLVER,{event:L.Events.Resolver.NOTIFICATION_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:a,methodName:Fn.DELETE_NOTIFICATION,source:"internal",payload:{error:d,notificationId:t,organizationId:i}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(L.Events.Resolver.NOTIFICATION_RESOLVER_DELETE,{sourceMethod:"deleteNotification",source:"sdk",notificationId:t}),this.coreActionsService.triggerAction($.NOTIFICATION_RESOLVER,{event:L.Events.Resolver.NOTIFICATION_DELETE_RESULT,timestamp:new Date().getTime(),uniqueId:a,methodName:Fn.DELETE_NOTIFICATION,source:"internal",payload:{result:{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0},notificationId:t,organizationId:i}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0})}catch(s){this.loggingService.warn("Error in NotificationResolverService deleteNotification:",s);let a=o||J();return this.coreActionsService.triggerAction($.NOTIFICATION_RESOLVER,{event:L.Events.Resolver.NOTIFICATION_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:a,methodName:Fn.DELETE_NOTIFICATION,source:"internal",payload:{error:s,notificationId:t,organizationId:i}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0}}})}getNotificationsById$(){try{return this.notificationDataProviderAvailable()?(this.loggingService.log("%c[WB] Calling NotificationResolverService FUNCTION: getNotificationsById$","color: green;"),this.notificationById$.asObservable()):ue(void 0)}catch(t){return this.loggingService.catch("Error in NotificationResolverService getNotificationsById$:",t),ue(void 0)}}setNotificationDataProvider(t){try{if(t){this.loggingService.log("Setting notification data provider");let i=t.config,o=[{method:"get",configKey:"getConfig"},{method:"delete",configKey:"deleteConfig"}],s=[];if(o.forEach(({method:a,configKey:c})=>{let l=i?.[c]?.url,u=a in t&&typeof t[a]=="function";!l&&!u&&s.push(a)}),s.length>0){let a=`DataProviders.notification is invalid. The following methods are missing or are not functions (and no corresponding config provided): ${s.join(", ")}.`;this.loggingService.catch(a);return}else this.notificationDataProvider$.next(t)}}catch(i){this.loggingService.catch("Error in NotificationResolverService setNotificationDataProvider:",i)}}notificationDataProviderAvailable(){try{return!!this.notificationDataProvider$.getValue()}catch(t){return this.loggingService.catch("Error in NotificationResolverService notificationDataProviderAvailable:",t),!1}}};e.\u0275fac=function(i){return new(i||e)(w(It),w(_e),w(Lt))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let n=e;return n})();var Np=class{constructor({apiKey:e,documentId:r,organizationId:t,clientDocumentId:i,clientOrganizationId:o,folderId:s,veltFolderId:a}){this.paths={},this.apiKey=e,this.documentId=r,this.organizationId=t,this.veltFolderId=a,i&&(this.documentId=da(i)),o&&(this.organizationId=Ts(o)),s&&(this.folderId=s,this.veltFolderId=wo(s)),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 e=`apiKey/${this.apiKey}`;this.paths.activities=`${e}/${v.FIREBASE_PARTIAL_PATH_ACTIVITIES}`,this.paths.userNotificationIndex=`${e}/${v.FIREBASE_PARTIAL_PATH_USER_NOTIFICATION_INDEX}`,this.organizationId&&(e=`${e}/${v.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${this.paths.organizationId}`,this.paths.organization=e,this.paths.folder=`${e}/${v.FIREBASE_PARTIAL_PATH_FOLDERS}`,this.paths.organizationUsers=`${e}/${v.FIREBASE_PARTIAL_PATH_ORGANIZATION_USERS}`,this.paths.users=`${e}/${v.FIREBASE_PARTIAL_PATH_CENTRAL_USERS}`,this.paths.notificationDocs=`${e}/${v.FIREBASE_PARTIAL_PATH_NOTIFICATION_DOCS}`,this.paths.notificationUsers=`${e}/${v.FIREBASE_PARTIAL_PATH_NOTIFICATION_USERS}`,this.paths.organizationGroups=`${e}/${v.FIREBASE_PARTIAL_PATH_GROUPS}`,this.paths.lastNotificationTimestamp=`${e}/${v.FIREBASE_PARTIAL_PATH_LAST_NOTIFICATION_TIMESTAMP}`,this.paths.lastActivityTimestamp=`${e}/${v.FIREBASE_PARTIAL_PATH_LAST_ACTIVITY_TIMESTAMP}`,this.paths.userConfig=`${e}/${v.FIREBASE_PARTIAL_PATH_USERS}`,this.paths.permissionsUsers=`${e}/${v.FIREBASE_PARTIAL_PATH_PERMISSIONS_USERS}`),this.veltFolderId&&(this.paths.folderUsers=`${e}/${v.FIREBASE_PARTIAL_PATH_FOLDERS}/${this.veltFolderId}/${v.FIREBASE_PARTIAL_PATH_FOLDER_USERS}`),this.documentId&&(this.paths.document=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}`,this.paths.comment=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_COMMENT}`,this.paths.location=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_LOCATION}`,this.paths.multiThread=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_MULTI_THREAD}`,this.paths.area=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_AREA}`,this.paths.recorder=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_RECORDER}`,this.paths.reaction=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_REACTION}`,this.paths.crdt=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_CRDT}`,this.paths.notificationViews=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_NOTIFICATION_VIEWS}`,this.paths.documentViews=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_DOCUMENT_VIEWS}`,this.paths.locationViews=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_LOCATION_VIEWS}`,this.paths.documentUsers=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_DOCUMENT_USERS}`,this.paths.docNotification=`${this.paths.notificationDocs}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_DOC_NOTIFICATION}`)}}catch{}}get userNotificationIndex(){return this.paths.userNotificationIndex}get permissionsUsers(){return this.paths.permissionsUsers?this.paths.permissionsUsers:this.throwError("PermissionsUsers path is not available.")}get users(){return this.paths.users?this.paths.users:this.throwError("Users path is not available.")}get userConfig(){return this.paths.userConfig?this.paths.userConfig:this.throwError("UserConfig path is not available.")}get folder(){return this.paths.folder?this.paths.folder:this.throwError("Folder path is not available.")}get lastNotificationTimestamp(){return this.paths.lastNotificationTimestamp?this.paths.lastNotificationTimestamp:this.throwError("LastNotificationTimestamp path is not available.")}get organizationGroups(){return this.paths.organizationGroups?this.paths.organizationGroups:this.throwError("organizationGroups path is not available.")}get docNotification(){return this.paths.docNotification?this.paths.docNotification:this.throwError("DocNotification path is not available.")}get organization(){return this.paths.organization?this.paths.organization:this.throwError("Organization path is not available.")}get document(){return this.paths.document?this.paths.document:this.throwError("Document path is not available.")}get location(){return this.paths.location?this.paths.location:this.throwError("Location path is not available.")}get area(){return this.paths.area?this.paths.area:this.throwError("Area path is not available.")}get comment(){return this.paths.comment?this.paths.comment:this.throwError("Comment path is not available.")}get documentViews(){return this.paths.documentViews?this.paths.documentViews:this.throwError("DocumentViews path is not available.")}get locationViews(){return this.paths.locationViews?this.paths.locationViews:this.throwError("LocationViews path is not available.")}get notificationViews(){return this.paths.notificationViews?this.paths.notificationViews:this.throwError("NotificationViews path is not available.")}get documentUsers(){return this.paths.documentUsers?this.paths.documentUsers:this.throwError("DocumentUsers path is not available.")}get folderUsers(){return this.paths.folderUsers?this.paths.folderUsers:this.throwError("FolderUsers path is not available.")}get organizationUsers(){return this.paths.organizationUsers?this.paths.organizationUsers:this.throwError("OrganizationUsers path is not available.")}get notificationDocs(){return this.paths.notificationDocs?this.paths.notificationDocs:this.throwError("NotificationDocs path is not available.")}get notificationUsers(){return this.paths.notificationUsers?this.paths.notificationUsers:this.throwError("NotificationUsers path is not available.")}get multiThread(){return this.paths.multiThread?this.paths.multiThread:this.throwError("Multi thread path is not available.")}get recorder(){return this.paths.recorder?this.paths.recorder:this.throwError("Recorder path is not available.")}get reaction(){return this.paths.reaction?this.paths.reaction:this.throwError("Reaction path is not available.")}get crdt(){return this.paths.crdt?this.paths.crdt:this.throwError("CRDT path is not available.")}get activities(){return this.paths.activities?this.paths.activities:this.throwError("Activities path is not available.")}get lastActivityTimestamp(){return this.paths.lastActivityTimestamp?this.paths.lastActivityTimestamp:this.throwError("LastActivityTimestamp path is not available.")}throwError(e){throw{type:"DocumentPaths",message:e,metadata:{apiKey:this.apiKey,documentId:this.documentId,organizationId:this.organizationId}}}};var Kz=(()=>{let e=class e{constructor(t,i){this.loggingService=t,this.usersService=i}getUserIdsToResolveFromAreaAnnotations(t){try{this.loggingService.log("%c[WB] Calling AreaUtilsService FUNCTION: getUserIdsToResolveFromAreaAnnotations","color: green;");let i=new Set;for(let o of t)o?.from?.userId&&i.add(o?.from?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in AreaUtilsService getUserIdsToResolveFromAreaAnnotations:",i),[]}}mergeAreaWithUser(t){try{if(this.loggingService.log("%c[WB] Calling AreaUtilsService FUNCTION: mergeAreaWithUser","color: green;"),t?.from?.userId){let i=this.usersService.getUserById(t?.from?.userId);i&&(t.from=i)}return t}catch(i){return this.loggingService.catch("Error in AreaUtilsService mergeAreaWithUser:",i),t}}formatAreaData(t){try{return this.loggingService.log("%c[WB] Calling AreaUtilsService FUNCTION: formatAreaData","color: green;"),this.usersService.userDataProviderAvailable()&&t?.from?.userId&&(t.from={userId:t.from.userId}),t}catch(i){return this.loggingService.catch("Error in AreaUtilsService formatAreaData:",i),t}}};e.\u0275fac=function(i){return new(i||e)(w(_e),w(zt))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let n=e;return n})();var Yz=(()=>{let e=class e{constructor(t,i){this.loggingService=t,this.usersService=i}getUserIdsToResolveFromUserIamData(t){try{this.loggingService.log("%c[WB] Calling ContactUtilsService FUNCTION: getUserIdsToResolveFromUserIamData","color: green;");let i=new Set;if(t?.length)for(let o of t)o?.user?.userId&&i.add(o?.user?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in ContactUtilsService getUserIdsToResolveFromUserIamData: ",i),[]}}mergeUserIamWithUser(t){try{if(this.loggingService.log("%c[WB] Calling ContactUtilsService FUNCTION: mergeUserIamWithUser","color: green;"),t?.user?.userId){let i=this.usersService.getUserById(t?.user?.userId);if(i){let o=i;t?.user&&typeof t.user=="object"&&(o=x(x({},o),t.user));let s=this.usersService.getContactListUser(t.user.userId);s&&(o=x(x({},o),s)),t=le(x({},t),{user:o})}}return t}catch(i){return this.loggingService.catch("Error in ContactUtilsService mergeUserIamWithUser: ",i),t}}};e.\u0275fac=function(i){return new(i||e)(w(_e),w(zt))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let n=e;return n})();var Qz=(()=>{let e=class e{constructor(t,i){this.loggingService=t,this.usersService=i}getUserIdsToResolveFromMultiThreads(t){try{let i=new Set;for(let o of t)o?.from?.userId&&i.add(o?.from?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in MultiThreadUtilsService getUserIdsToResolveFromMultiThreads:",i),[]}}mergeMultiThreadWithUser(t){try{if(t?.from?.userId){let i=this.usersService.getUserById(t?.from?.userId);i&&(t.from=i)}return t}catch(i){return this.loggingService.catch("Error in MultiThreadUtilsService mergeMultiThreadWithUser:",i),t}}formatMultiThreadData(t){try{return this.usersService.userDataProviderAvailable()&&(t?.from?.userId&&(t.from={userId:t.from.userId}),t?.commentAnnotationsMap&&(t.commentAnnotationsMap=null)),t}catch(i){return this.loggingService.catch("Error in MultiThreadUtilsService formatMultiThreadData:",i),t}}};e.\u0275fac=function(i){return new(i||e)(w(_e),w(zt))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let n=e;return n})();var Xz=(()=>{let e=class e{constructor(t,i){this.loggingService=t,this.usersService=i}getUserIdsToResolveFromSelections(t){try{let i=new Set;for(let o of t)o?.user?.userId&&i.add(o.user.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in SelectionUtilsService getUserIdsToResolveFromSelections:",i),[]}}mergeSelectionWithUser(t){try{if(t?.user?.userId){let i=this.usersService.getUserById(t?.user?.userId);i&&(t.user=i)}return t}catch(i){return this.loggingService.catch("Error in SelectionUtilsService mergeSelectionWithUser:",i),t}}formatSelectionData(t){try{return this.usersService.userDataProviderAvailable()&&t?.user?.userId&&(t.user={userId:t.user.userId}),t}catch(i){return this.loggingService.catch("Error in SelectionUtilsService formatSelectionData:",i),t}}};e.\u0275fac=function(i){return new(i||e)(w(_e),w(zt))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let n=e;return n})();var Jz=(()=>{let e=class e{constructor(t,i){this.loggingService=t,this.usersService=i}getUserIdsToResolveFromTags(t){try{let i=new Set;for(let o of t)if(o?.from?.userId&&i.add(o.from.userId),o?.to?.length)for(let s of o.to)s?.userId&&i.add(s.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in TagUtilsService getUserIdsToResolveFromTags:",i),[]}}mergeTagWithUser(t){try{if(t?.from?.userId){let i=this.usersService.getUserById(t?.from?.userId);i&&(t.from=i)}return t?.to?.length&&(t.to=t.to.map(i=>{if(i?.userId){let o=this.usersService.getUserById(i?.userId);o&&(i=o)}return i})),t}catch(i){return this.loggingService.catch("Error in TagUtilsService mergeTagWithUser:",i),t}}formatTagData(t){try{return this.usersService.userDataProviderAvailable()&&(t?.from?.userId&&(t.from={userId:t.from.userId}),t?.to?.length&&(t.to=t.to.map(i=>(i?.userId&&(i={userId:i.userId}),i)))),t}catch(i){return this.loggingService.catch("Error in TagUtilsService formatTagData:",i),t}}};e.\u0275fac=function(i){return new(i||e)(w(_e),w(zt))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let n=e;return n})();var Zz=(()=>{let e=class e{constructor(t,i,o,s,a,c,l,u,d,f,g,p,_,T,D,b,G,M,U,k){this.activityUtilsService=t,this.areaUtilsService=i,this.commentUtilsService=o,this.contactUtilsService=s,this.coreActionsService=a,this.liveStateUtilsService=c,this.loggingService=l,this.multiThreadUtilsService=u,this.reactionUtilsService=d,this.selectionUtilsService=f,this.tagUtilsService=g,this.usersService=p,this.docService=_,this.commentAnnotationsResolverService=T,this.reactionAnnotationsResolverService=D,this.recorderAnnotationsResolverService=b,this.notificationResolverService=G,this.activityResolverService=M,this.serviceBook=U,this.attachmentResolverService=k}getErrorForGetRequests({feature:t,error:i}){try{switch(t){case"apiKeyMetadata":case"organizationMetadata":case"documentMetadata":case"folderMetadata":return(i?.message??"")?.includes("Missing or insufficient permissions.")?{errorCode:"PERMISSION_DENIED"}:null;default:return null}}catch(o){return this.loggingService.catch("Error in CommonDbUtilsService getErrorForGetRequests:",o),null}}getFirestorePath({feature:t,properties:i,documentPaths:o,apiKey:s}){try{if(!s)return;if(t==="userNotificationIndex"){if(!i?.id)return;let d=new Np({apiKey:s});return d?.userNotificationIndex?`${d.userNotificationIndex}/${i.id}`:void 0}let{documentId:a,organizationId:c,folderId:l}=i;if(!c&&(c=o?.organizationId,!c))return;let u=new Np({apiKey:s,documentId:a?`${a}`:"",organizationId:c?`${c}`:"",veltFolderId:l?`${l}`:void 0});switch(t){case"userConfig":return i?.userId&&u?.userConfig?`${u?.userConfig}/${i?.userId}${i?.documentId?`/${v.FIREBASE_PARTIAL_PATH_DOCUMENT_CONFIGURATIONS}/${i?.documentId}`:""}`:void 0;case"allPermissionsUsers":return u?.permissionsUsers?`${u?.permissionsUsers}`:void 0;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"crdt":return i?.documentId&&u?.crdt&&i?.id?`${u?.crdt}/${i?.id}`: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"activity":return i?.id&&u?.activities?`${u?.activities}/${i?.id}`:void 0;case"allActivities":return u?.activities?`${u?.activities}`:void 0;case"allLastActivityTimestamp":return u?.lastActivityTimestamp?`${u?.lastActivityTimestamp}`:void 0;case"lastActivityTimestamp":return i?.id&&u?.lastActivityTimestamp?`${u?.lastActivityTimestamp}/${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"recorderTrackEvent":return i?.documentId&&i?.id&&u?.recorder?`${u?.recorder}/${i?.id}/trackRecorderEvent`:void 0;case"documentAccessType":return i?.documentId&&u?.document?`${u?.document}/${i?.documentId}`:void 0;case"apiKeyMetadata":return s?`apiKey/${s}`: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 u?.users?`${u?.users}`:void 0;case"allFolderUsers":return u?.users?`${u?.users}`:void 0;case"allOrganizationGroups":return u?.organizationGroups?`${u?.organizationGroups}`:void 0;case"allOrganizationUsers":return u?.users?`${u?.users}`:void 0;case"notificationViewsTimestamp":return 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}/${v.FIREBASE_PARTIAL_PATH_USER_NOTIFICATION}/${i?.id}`:void 0;case"allUserNotifications":return i?.userId&&u?.notificationUsers?`${u?.notificationUsers}/${i?.userId}/${v.FIREBASE_PARTIAL_PATH_USER_NOTIFICATION}`:void 0;default:throw new Error(`Unknown feature: ${t}`)}}catch(a){this.loggingService.catch("Error in CommonDbUtilsService getFirestorePath:",a);return}}getFirestoreCollectionGroupPath(t){try{switch(t){case"allComments":return v.FIREBASE_PARTIAL_PATH_COMMENT;case"allDocuments":return v.FIREBASE_PARTIAL_PATH_DOCS;case"allLocations":return v.FIREBASE_PARTIAL_PATH_LOCATION;case"allMultiThreads":return v.FIREBASE_PARTIAL_PATH_MULTI_THREAD;case"allAreas":return v.FIREBASE_PARTIAL_PATH_AREA;case"allReactions":return v.FIREBASE_PARTIAL_PATH_REACTION;case"allRecorders":return v.FIREBASE_PARTIAL_PATH_RECORDER;case"allDocumentViews":return v.FIREBASE_PARTIAL_PATH_DOCUMENT_VIEWS;case"allLocationViews":return v.FIREBASE_PARTIAL_PATH_LOCATION_VIEWS;case"allDocumentUsers":return v.FIREBASE_PARTIAL_PATH_DOCUMENT_USERS;case"allFolderUsers":return v.FIREBASE_PARTIAL_PATH_FOLDER_USERS;default:throw new Error(`Unknown feature: ${t}`)}}catch(i){this.loggingService.catch("Error in CommonDbUtilsService getFirestoreCollectionGroupPath:",i);return}}getDocumentPath({feature:t,properties:i,defaultDocumentPaths:o,apiKey:s,useFirestore:a}){try{if(!s)return;let{documentId:c,organizationId:l}=i;l||(l=o?.organizationId);let u=new Jy({apiKey:s,documentId:c?`${c}`:"",organizationId:l?`${l}`:""});switch(t){case"userConfig":return i?.userId&&i?.documentId&&u?.userConfig?`${u?.userConfig}/${i?.userId}/${v.FIREBASE_PARTIAL_PATH_DOCUMENT_CONFIGURATIONS}/${i?.documentId}`:void 0;case"allComments":return!a&&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"liveStateAutoSyncState":return i?.documentId&&u?.liveState?`${u?.liveState}default/autoSyncState`: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!a&&i?.documentId&&i?.id&&u?.comment?`${u?.comment}${i?.id}`:void 0;case"allMultiThreads":return!a&&i?.documentId&&u?.multiThread?`${u?.multiThread}`:void 0;case"crdt":return!a&&i?.documentId&&u?.crdt?`${u?.crdt}`:void 0;case"crdtData":return i?.documentId&&u?.crdt&&i?.id?`${u?.crdt}/${i?.id}/data`:void 0;case"crdtSyncState":return i?.documentId&&u?.crdt&&i?.id?`${u?.crdt}/${i?.id}/sync/state`:void 0;case"crdtSyncPresence":return i?.documentId&&i.userId&&u?.crdt&&i?.id?`${u?.crdt}/${i?.id}/sync/presence/${i.userId}`:void 0;case"allCrdtSyncPresence":return i?.documentId&&u?.crdt&&i?.id?`${u?.crdt}/${i?.id}/sync/presence`:void 0;case"crdtPresence":return i?.documentId&&i.userId&&u?.crdt&&i?.id?`${u?.crdt}/${i?.id}/presence/${i.userId}`:void 0;case"allCrdtPresence":return i?.documentId&&u?.crdt&&i?.id?`${u?.crdt}/${i?.id}/presence`:void 0;case"crdtVersion":return i?.documentId&&u?.crdt&&i?.id&&i?.versionId?`${u?.crdt}/${i?.id}/versions/${i?.versionId}`:void 0;case"crdtVersions":return i?.documentId&&u?.crdt&&i?.id?`${u?.crdt}/${i?.id}/versions`:void 0;case"crdtMessages":return i?.documentId&&u?.crdt&&i?.id?`${u?.crdt}/${i?.id}/messages`:void 0;case"crdtMessage":return i?.documentId&&u?.crdt&&i?.id&&i?.messageId?`${u?.crdt}/${i?.id}/messages/${i?.messageId}`:void 0;case"crdtSnapshot":return i?.documentId&&u?.crdt&&i?.id?`${u?.crdt}/${i?.id}/snapshot`:void 0;case"multiThread":return!a&&i?.documentId&&i?.id&&u?.multiThread?`${u?.multiThread}${i?.id}`:void 0;case"allLastNotificationTimestamp":return!a&&u?.organizationNotificationsLastNotificationTimestamp?`${u?.organizationNotificationsLastNotificationTimestamp}`:void 0;case"lastNotificationTimestamp":return!a&&i?.id&&u?.organizationNotificationsLastNotificationTimestamp?`${u?.organizationNotificationsLastNotificationTimestamp}${i?.id}`:void 0;case"documentIam":return!a&&i?.documentId&&u?.documentIam?`${u?.documentIam}`:void 0;case"allDocuments":return!a&&u?.docs&&i?.documentId?`${u?.docs}/${i?.documentId}/${v.FIREBASE_PARTIAL_PATH_METADATA}`:void 0;case"allAreas":return!a&&i?.documentId&&u?.area?`${u?.area}`:void 0;case"area":return!a&&i?.id&&u?.area?`${u?.area}${i?.id}`:void 0;case"folder":return!a&&i?.folderId&&u?.folder?`${u?.folder}${i?.folderId}`:void 0;case"documentUserAccess":return!a&&i?.id&&u?.documentIam?`${u?.documentIam}users/${i?.id}`:void 0;case"documentUser":return!a&&i?.documentId&&i?.id&&u?.documentIam?`${u?.documentIam}users/${i?.id}`:void 0;case"allDocumentUsers":return!a&&i?.documentId&&u?.documentIam?`${u?.documentIam}users/`:void 0;case"allOrganizationGroups":return!a&&u?.organizationGroups?`${u?.organizationGroups}`:void 0;case"allOrganizationUsers":return!a&&u?.organizationIam?`${u?.organizationIam}users/`:void 0;case"reaction":return!a&&i?.id&&u?.reaction?`${u?.reaction}${i?.id}`:void 0;case"allReactions":return!a&&i?.documentId&&u?.reaction?`${u?.reaction}`:void 0;case"recorder":return!a&&i?.documentId&&i?.id&&u?.recorder?`${u?.recorder}${i?.id}`:void 0;case"allRecorders":return!a&&i?.documentId&&u?.recorder?`${u?.recorder}`:void 0;case"organizationMetadata":return!a&&u?.organizationMetadata?`${u?.organizationMetadata}`:void 0;case"heartbeat":return i?.id&&u?.heartbeat?`${u?.heartbeat}${i?.id}`:void 0;case"allHeartbeats":return u?.heartbeat?`${u?.heartbeat}`:void 0;case"heartbeatByDocument":return i?.id&&u?.heartbeatByDocument?`${u?.heartbeatByDocument}${i?.id}`:void 0;case"allHeartbeatsByDocument":return u?.heartbeatByDocument?`${u?.heartbeatByDocument}`:void 0;case"documentAccessType":return!a&&u?.documentIam?`${u?.documentIam}`:void 0;case"documentMetadata":return!a&&i?.documentId&&u?.metadata?`${u?.metadata}`:void 0;case"allDocumentViews":return!a&&i?.documentId&&u?.views?`${u?.views}documentViews/`:void 0;case"documentViews":return!a&&i?.documentId&&i?.id&&u?.views?`${u?.views}documentViews/${i?.id}`:void 0;case"allLocationViews":return!a&&i?.documentId&&u?.views?`${u?.views}locationViews/`:void 0;case"notificationViewsTimestamp":return!a&&i?.id&&i?.user&&u?.views?`${u?.views}notification/${i?.id}/views/${i?.user}`:void 0;case"documentUsersViews":return!a&&i?.id&&i?.user&&i?.date&&u?.views?`${u?.views}documentViews/${i?.id}/users/${i?.user}/${i?.date}`:void 0;case"documentMetadataViews":return!a&&i?.id&&u?.views?`${u?.views}documentViews/${i?.id}/metadata`:void 0;case"documentDayViews":return!a&&i?.id&&i?.date&&i?.user&&u?.views?`${u?.views}documentViews/${i?.id}/day/${i?.date}/${i?.user}`:void 0;case"locationViews":return!a&&i?.id&&u?.views?`${u?.views}locationViews/${i?.id}/location`:void 0;case"location":return!a&&i?.id&&u?.views?`${u?.views}locationViews/${i?.id}`:void 0;case"locationUsersViews":return!a&&i?.id&&i?.user&&i?.date&&u?.views?`${u?.views}locationViews/${i?.id}/users/${i?.user}/${i?.date}`:void 0;case"locationMetadataViews":return!a&&i?.id&&u?.views?`${u?.views}locationViews/${i?.id}/metadata`:void 0;case"locationDayViews":return!a&&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;case"allPermissionsUsers":return;default:throw new Error(`Unknown feature: ${t}`)}}catch(c){this.loggingService.catch("Error in CommonDbUtilsService getDocumentPath:",c);return}}resolveAnnotations(o){return I(this,arguments,function*({data:t,feature:i}){try{if(t&&t?.length>0)switch(i){case"allComments":{if(this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable()){let s=J(),a=Td.GET_COMMENT_ANNOTATIONS;this.coreActionsService.triggerAction($.COMMENT_RESOLVER,{event:L.Events.Resolver.COMMENT_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:s,methodName:Et.RESOLVE_COMMENT_ANNOTATIONS,moduleName:a,source:"internal",payload:{commentAnnotationIds:t,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""}}),this.commentAnnotationsResolverService.resolveCommentAnnotations({request:{commentAnnotationIds:t,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""},uniqueId:s,moduleName:a})}break}case"allReactions":{if(this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable()){let s=J(),a=Id.GET_REACTION_ANNOTATIONS;this.coreActionsService.triggerAction($.REACTION_RESOLVER,{event:L.Events.Resolver.REACTION_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:s,methodName:_t.RESOLVE_REACTION_ANNOTATIONS,moduleName:a,source:"internal",payload:{reactionAnnotationIds:t,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""}}),this.reactionAnnotationsResolverService.resolveReactionAnnotations({request:{reactionAnnotationIds:t,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""},uniqueId:s,moduleName:a})}break}case"allRecorders":{if(this.recorderAnnotationsResolverService.recorderAnnotationDataProviderAvailable()){let s=J(),a=vd.GET_RECORDER_ANNOTATIONS;this.coreActionsService.triggerAction($.RECORDER_RESOLVER,{event:L.Events.Resolver.RECORDER_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:s,methodName:Tt.RESOLVE_RECORDER_ANNOTATIONS,moduleName:a,source:"internal",payload:{recorderAnnotationIds:t,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""}}),this.recorderAnnotationsResolverService.resolveRecorderAnnotations({request:{recorderAnnotationIds:t,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""},uniqueId:s,moduleName:a})}break}default:break}}catch(s){this.loggingService.catch(`Error in CommonDbUtilsService resolveAnnotations: ${i}`,s)}})}formatResponse(g){return I(this,arguments,function*({feature:t,data:i,organizationId:o,shouldAwait:s=!1,forceResolve:a=!1,shouldCommentAnnotationsResolverAwait:c=!1,shouldNotificationResolverAwait:l=!1,shouldActivityResolverAwait:u=!1,shouldReactionResolverAwait:d=!1,shouldRecorderResolverAwait:f=!1}){try{let p=o??this.docService.getDocumentPaths()?.clientOrganizationId??this.docService.getOrganizationConfig()?.clientOrganizationId??"";if(this.usersService.userDataProviderAvailable()){let _=[];switch(t){case"allAreas":{i&&typeof i=="object"&&!Array.isArray(i)&&(_=this.areaUtilsService.getUserIdsToResolveFromAreaAnnotations(Object.values(i)));break}case"allArrows":{i&&typeof i=="object"&&!Array.isArray(i)&&(_=this.serviceBook.get(IT)?.getUserIdsToResolveFromArrowAnnotations(Object.values(i))??[]);break}case"allCursors":{i&&typeof i=="object"&&!Array.isArray(i)&&(_=this.serviceBook.get(vT)?.getUserIdsToResolveFromCursorUsers(Object.values(i))??[]);break}case"allComments":{i&&typeof i=="object"&&!Array.isArray(i)&&(_=this.commentUtilsService.getUserIdsToResolveFromComments(Object.values(i)));break}case"allDocumentUsers":{i&&typeof i=="object"&&!Array.isArray(i)&&(_=this.contactUtilsService.getUserIdsToResolveFromUserIamData(Object.values(i)));break}case"allFolderUsers":{i&&typeof i=="object"&&!Array.isArray(i)&&(_=this.contactUtilsService.getUserIdsToResolveFromUserIamData(Object.values(i)));break}case"allOrganizationUsers":{i&&typeof i=="object"&&!Array.isArray(i)&&(_=this.contactUtilsService.getUserIdsToResolveFromUserIamData(Object.values(i)));break}case"allMultiThreads":{i&&typeof i=="object"&&!Array.isArray(i)&&(_=this.multiThreadUtilsService.getUserIdsToResolveFromMultiThreads(Object.values(i)));break}case"allDocNotifications":{i&&typeof i=="object"&&(_=this.serviceBook.get(xi)?.getUserIdsToResolveFromNotifications(Array.isArray(i)?i:Object.values(i))??[]);break}case"allUserNotifications":{i&&typeof i=="object"&&!Array.isArray(i)&&(_=this.serviceBook.get(xi)?.getUserIdsToResolveFromNotifications(Object.values(i))??[]);break}case"allPresence":{i&&typeof i=="object"&&!Array.isArray(i)&&(_=this.serviceBook.get(yT)?.getUserIdsToResolveFromPresenceUsers(Object.values(i))??[]);break}case"allRecorders":{i&&typeof i=="object"&&!Array.isArray(i)&&(_=this.serviceBook.get(ci)?.getUserIdsToResolveFromRecorders(Object.values(i))??[]);break}case"allReactions":{i&&typeof i=="object"&&!Array.isArray(i)&&(_=this.reactionUtilsService.getUserIdsToResolveFromReactions(Object.values(i)));break}case"allTags":{i&&typeof i=="object"&&!Array.isArray(i)&&(_=this.tagUtilsService.getUserIdsToResolveFromTags(Object.values(i)));break}case"allHuddleAttendees":{i&&typeof i=="object"&&!Array.isArray(i)&&(_=this.serviceBook.get(ST)?.getUserIdsToResolveFromHuddleAttendees(Object.values(i))??[]);break}case"liveStateCustom":{i&&typeof i=="object"&&!Array.isArray(i)&&(_=this.liveStateUtilsService.getUserIdsToResolveFromLiveStateCustom(i));break}case"allLiveStateCustoms":{i&&typeof i=="object"&&!Array.isArray(i)&&(_=this.liveStateUtilsService.getUserIdsToResolveFromLiveStateCustoms(Object.values(i)));break}case"allLiveStates":{i&&typeof i=="object"&&(_=this.liveStateUtilsService.getUserIdsToResolveFromLiveStates(i));break}case"liveStateSingleEditorMode":{i&&typeof i=="object"&&!Array.isArray(i)&&(_=this.liveStateUtilsService.getUserIdsToResolveFromLiveStateSingleEditorMode(i));break}case"allSelections":{i&&typeof i=="object"&&!Array.isArray(i)&&(_=this.selectionUtilsService.getUserIdsToResolveFromSelections(Object.values(i)));break}case"allActivities":{i&&typeof i=="object"&&(_=this.activityUtilsService.getUserIdsToResolveFromActivities(Array.isArray(i)?i:Object.values(i)));break}default:_=[]}if(_?.length){let T=J(),D=tl.GET_USERS;this.coreActionsService.triggerAction($.USER_RESOLVER,{event:L.Events.Resolver.USER_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:T,methodName:xn.FORMAT_RESPONSE,source:"internal",moduleName:D,payload:{userIds:_,feature:t,forceResolve:a}}),s?yield this.usersService.resolveUsers({userIds:_,forceResolve:a,feature:t,organizationId:o,uniqueId:T,moduleName:D}):this.usersService.resolveUsers({userIds:_,forceResolve:a,feature:t,organizationId:o,uniqueId:T,moduleName:D})}}if(this.notificationResolverService.notificationDataProviderAvailable()){let _=[];switch(t){case"allDocNotifications":case"allUserNotifications":{i&&typeof i=="object"&&(_=this.serviceBook.get(xi)?.getCustomNotificationIdsToResolve(i)??[],_=_.filter(D=>!this.notificationResolverService.getNotificationById(D)));break}default:_=[]}if(_?.length){let T=J(),D=yC.GET_NOTIFICATIONS;this.coreActionsService.triggerAction($.NOTIFICATION_RESOLVER,{event:L.Events.Resolver.NOTIFICATION_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:T,methodName:Fn.FORMAT_RESPONSE,moduleName:D,source:"internal",payload:{notificationIds:_,organizationId:p,shouldNotificationResolverAwait:l}}),l?yield this.notificationResolverService.resolveNotifications({request:{notificationIds:_,organizationId:p},uniqueId:T,moduleName:D}):this.notificationResolverService.resolveNotifications({request:{notificationIds:_,organizationId:p},uniqueId:T,moduleName:D})}}if(this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable()){let _=[];switch(t){case"allDocNotifications":{if(i&&typeof i=="object"){let D=this.serviceBook.get(xi)?.getTargetAnnotationIdsFromNotifications(i)??[];_=[..._,...D],_=_.filter(b=>!this.commentAnnotationsResolverService.getCommentAnnotationById(b))}break}case"allUserNotifications":{if(i&&typeof i=="object"&&!Array.isArray(i)){let D=this.serviceBook.get(xi)?.getTargetAnnotationIdsFromNotifications(i)??[];_=[..._,...D],_=_.filter(b=>!this.commentAnnotationsResolverService.getCommentAnnotationById(b))}break}case"allActivities":{if(i&&typeof i=="object"){let T=Array.isArray(i)?i:Object.values(i),D=this.activityUtilsService.getEntityIdsToResolveFromActivities(T,"comment");_=[..._,...D],_=_.filter(b=>!this.commentAnnotationsResolverService.getCommentAnnotationById(b))}break}default:_=[]}if(_?.length){let T=J(),D=Td.GET_NOTIFICATIONS;this.coreActionsService.triggerAction($.COMMENT_RESOLVER,{event:L.Events.Resolver.COMMENT_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:T,methodName:Et.FORMAT_RESPONSE,moduleName:D,source:"internal",payload:{commentAnnotationIds:_,organizationId:p,shouldCommentAnnotationsResolverAwait:c}}),c?yield this.commentAnnotationsResolverService.resolveCommentAnnotations({request:{commentAnnotationIds:_,organizationId:p},uniqueId:T,moduleName:D}):this.commentAnnotationsResolverService.resolveCommentAnnotations({request:{commentAnnotationIds:_,organizationId:p},uniqueId:T,moduleName:D})}}if(t==="allActivities"&&i&&typeof i=="object"){let _=Array.isArray(i)?i:Object.values(i),T=this.docService.getDocumentPaths()?.clientOrganizationId??"";if(this.activityResolverService.activityDataProviderAvailable()){let D=[];for(let b of _)b?.id&&!this.activityResolverService.getActivityById(b.id)&&D.push(b.id);if(D.length){let b=J(),G=SC.GET_ACTIVITIES;this.coreActionsService.triggerAction($.ACTIVITY_RESOLVER,{event:L.Events.Resolver.ACTIVITY_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:b,methodName:lr.FORMAT_RESPONSE,moduleName:G,source:"internal",payload:{activityIds:D,organizationId:T,shouldActivityResolverAwait:u}}),u?yield this.activityResolverService.resolveActivities({request:{activityIds:D,organizationId:T},uniqueId:b,moduleName:G}):this.activityResolverService.resolveActivities({request:{activityIds:D,organizationId:T},uniqueId:b,moduleName:G})}}if(this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable()){let D=this.activityUtilsService.getEntityIdsToResolveFromActivities(_,"reaction");if(D=D.filter(b=>!this.reactionAnnotationsResolverService.getAnnotationById(b)),D.length){let b=J(),G=Id.GET_REACTION_ANNOTATIONS;this.coreActionsService.triggerAction($.REACTION_RESOLVER,{event:L.Events.Resolver.REACTION_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:b,methodName:_t.RESOLVE_REACTION_ANNOTATIONS,moduleName:G,source:"internal",payload:{reactionAnnotationIds:D,organizationId:T,shouldReactionResolverAwait:d}}),d?yield this.reactionAnnotationsResolverService.resolveReactionAnnotations({request:{reactionAnnotationIds:D,organizationId:T},uniqueId:b,moduleName:G}):this.reactionAnnotationsResolverService.resolveReactionAnnotations({request:{reactionAnnotationIds:D,organizationId:T},uniqueId:b,moduleName:G})}}if(this.recorderAnnotationsResolverService.recorderAnnotationDataProviderAvailable()){let D=this.activityUtilsService.getEntityIdsToResolveFromActivities(_,"recorder");if(D=D.filter(b=>!this.recorderAnnotationsResolverService.getAnnotationById(b)),D.length){let b=J(),G=vd.GET_RECORDER_ANNOTATIONS;this.coreActionsService.triggerAction($.RECORDER_RESOLVER,{event:L.Events.Resolver.RECORDER_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:b,methodName:Tt.RESOLVE_RECORDER_ANNOTATIONS,moduleName:G,source:"internal",payload:{recorderAnnotationIds:D,organizationId:T,shouldRecorderResolverAwait:f}}),f?yield this.recorderAnnotationsResolverService.resolveRecorderAnnotations({request:{recorderAnnotationIds:D,organizationId:T},uniqueId:b,moduleName:G}):this.recorderAnnotationsResolverService.resolveRecorderAnnotations({request:{recorderAnnotationIds:D,organizationId:T},uniqueId:b,moduleName:G})}}}return i}catch(p){return this.loggingService.catch("Error in CommonDbUtilsService formatResponse:",p),i}})}mergeCommentAnnotationsWithData({data:t,feature:i}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeCommentAnnotationsWithData","color: green;"),this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())switch(i){case"allComments":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((o,[s,a])=>(o[s]=this.commentUtilsService.mergeStrippedDataWithCommentAnnotations(a),o),{}):t;case"allDocNotifications":case"allUserNotifications":if(t&&typeof t=="object"&&!Array.isArray(t)){let o=this.serviceBook.get(xi);return Object.entries(t).reduce((s,[a,c])=>(s[a]=o?o.mergeStrippedDataWithNotification(c):c,s),{})}else return t;case"allActivities":return this.mergeActivitiesWithFeatureData(t);default:return t}return t}catch(o){return this.loggingService.catch("Error in CommonDbUtilsService mergeCommentAnnotationsWithData:",o),t}}mergeActivityResolverWithData({data:t,feature:i}){try{return this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeActivityResolverWithData","color: green;"),this.activityResolverService.activityDataProviderAvailable()&&i==="allActivities"&&Array.isArray(t)?t.map(o=>this.activityUtilsService.mergeActivityWithResolverData(o)):t}catch(o){return this.loggingService.catch("Error in CommonDbUtilsService mergeActivityResolverWithData:",o),t}}mergeNotificationsWithResolvedData({data:t,feature:i}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeNotificationsWithResolvedData","color: green;"),this.notificationResolverService.notificationDataProviderAvailable())switch(i){case"allDocNotifications":case"allUserNotifications":{let o=this.serviceBook.get(xi);return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((s,[a,c])=>(s[a]=o?o.mergeResolvedNotificationData(c):c,s),{}):Array.isArray(t)?t.map(s=>o?o.mergeResolvedNotificationData(s):s):t}default:return t}return t}catch(o){return this.loggingService.catch("Error in CommonDbUtilsService mergeNotificationsWithResolvedData:",o),t}}mergeNotificationsWithResolvedData$({data:t,feature:i}){try{return this.notificationResolverService.getNotificationsById$().pipe(fe(()=>{let o=this.mergeNotificationsWithResolvedData({data:t?.data??{},feature:i}),s=this.mergeUsersWithData({feature:i,data:o??{}});return typeof s=="object"?{data:JSON.parse(JSON.stringify(s)),operation:t?.operation??null}:{data:s,operation:t?.operation??null}}),it(Ft))}catch(o){return this.loggingService.catch("Error in mergeNotificationsWithResolvedData$:",o),ue(t)}}mergeReactionAnnotationsWithData({data:t,feature:i}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeReactionAnnotationsWithData","color: green;"),this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable())switch(i){case"allReactions":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((o,[s,a])=>(o[s]=this.reactionUtilsService.mergeStrippedDataWithReactionAnnotations(a),o),{}):t;case"allActivities":return this.mergeActivitiesWithFeatureData(t);default:return t}return t}catch(o){return this.loggingService.catch("Error in CommonDbUtilsService mergeReactionAnnotationsWithData:",o),t}}mergeRecorderAnnotationsWithData({data:t,feature:i}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeRecorderAnnotationsWithData","color: green;"),this.recorderAnnotationsResolverService.recorderAnnotationDataProviderAvailable())switch(i){case"allRecorders":if(t&&typeof t=="object"&&!Array.isArray(t)){let o=this.serviceBook.get(ci);return Object.entries(t).reduce((s,[a,c])=>(s[a]=o?o.mergeStrippedDataWithRecorderAnnotation(c):c,s),{})}else return t;case"allActivities":return this.mergeActivitiesWithFeatureData(t);default:return t}return t}catch(o){return this.loggingService.catch("Error in CommonDbUtilsService mergeRecorderAnnotationsWithData:",o),t}}mergeActivitiesWithFeatureData(t){return Array.isArray(t)?t.map(i=>this.activityUtilsService.mergeActivityWithFeatureData(i)):t}mergeLocationMetadataWithData({data:t,feature:i,locationMetadata:o}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeLocationMetadataWithData","color: green;"),o&&typeof o=="object"&&!Array.isArray(o))switch(i){case"allComments":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((s,[a,c])=>(s[a]=this.commentUtilsService.mergeLocationWithCommentAnnotations(c,o),s),{}):t;case"allDocNotifications":case"allUserNotifications":if(t&&typeof t=="object"&&!Array.isArray(t)){let s=this.serviceBook.get(xi);return Object.entries(t).reduce((a,[c,l])=>(a[c]=s?s.mergeLocationWithNotification(l,o):l,a),{})}else return t;default:return t}return t}catch(s){return this.loggingService.catch("Error in CommonDbUtilsService mergeLocationMetadataWithData:",s),t}}mergeUsersWithData({feature:t,data:i}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeUsersWithData","color: green;"),this.usersService.userDataProviderAvailable())switch(t){case"allAreas":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((o,[s,a])=>(o[s]=this.areaUtilsService.mergeAreaWithUser(a),o),{}):i;case"allArrows":if(i&&typeof i=="object"&&!Array.isArray(i)){let o=this.serviceBook.get(IT);return Object.entries(i).reduce((s,[a,c])=>(s[a]=o?o.mergeArrowWithUser(c):c,s),{})}else return i;case"allCursors":if(i&&typeof i=="object"&&!Array.isArray(i)){let o=this.serviceBook.get(vT);return Object.entries(i).reduce((s,[a,c])=>(s[a]=o?o.mergeCursorUserWithUser(c):c,s),{})}else return i;case"allComments":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((o,[s,a])=>(o[s]=this.commentUtilsService.mergeCommentWithUser(a),o),{}):i;case"allDocumentUsers":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((o,[s,a])=>(o[s]=this.contactUtilsService.mergeUserIamWithUser(a),o),{}):i;case"allFolderUsers":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((o,[s,a])=>(o[s]=this.contactUtilsService.mergeUserIamWithUser(a),o),{}):i;case"allOrganizationUsers":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((o,[s,a])=>(o[s]=this.contactUtilsService.mergeUserIamWithUser(a),o),{}):i;case"allMultiThreads":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((o,[s,a])=>(o[s]=this.multiThreadUtilsService.mergeMultiThreadWithUser(a),o),{}):i;case"allDocNotifications":if(i&&typeof i=="object"){let o=this.serviceBook.get(xi);return i?.map(s=>o?o.mergeNotificationWithUser(s):s)}else return i;case"allUserNotifications":if(i&&typeof i=="object"&&!Array.isArray(i)){let o=this.serviceBook.get(xi);return Object.entries(i).reduce((s,[a,c])=>(s[a]=o?o.mergeNotificationWithUser(c):c,s),{})}else return i;case"allPresence":if(i&&typeof i=="object"&&!Array.isArray(i)){let o=this.serviceBook.get(yT);return Object.entries(i).reduce((s,[a,c])=>(s[a]=o?o.mergePresenceUserWithUser(c):c,s),{})}else return i;case"allRecorders":if(i&&typeof i=="object"&&!Array.isArray(i)){let o=this.serviceBook.get(ci);return Object.entries(i).reduce((s,[a,c])=>(s[a]=o?o.mergeRecorderWithUser(c):c,s),{})}else return i;case"allReactions":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((o,[s,a])=>(o[s]=this.reactionUtilsService.mergeReactionWithUser(a),o),{}):i;case"allTags":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((o,[s,a])=>(o[s]=this.tagUtilsService.mergeTagWithUser(a),o),{}):i;case"allHuddleAttendees":if(i&&typeof i=="object"&&!Array.isArray(i)){let o=this.serviceBook.get(ST);return Object.entries(i).reduce((s,[a,c])=>(s[a]=o?.mergeHuddleAttendeeWithUser(c)??c,s),{})}else return 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((o,[s,a])=>(o[s]=this.liveStateUtilsService.mergeLiveStateCustomWithUser(a),o),{}):i;case"allLiveStates":return i&&typeof i=="object"?this.liveStateUtilsService.mergeLiveStateWithUser(i):i;case"liveStateSingleEditorMode":return i&&typeof i=="object"&&!Array.isArray(i)?this.liveStateUtilsService.mergeSingleEditorLiveStateDataWithUser(i):i;case"allSelections":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((o,[s,a])=>(o[s]=this.selectionUtilsService.mergeSelectionWithUser(a),o),{}):i;case"allActivities":return Array.isArray(i)?i.map(o=>this.activityUtilsService.mergeActivityWithUser(o)):i;default:return i}return i}catch(o){return this.loggingService.catch("Error in CommonDbUtilsService mergeUsersWithData:",o),i}}mergeCommentAnnotationsWithData$({data:t,feature:i}){try{return this.commentAnnotationsResolverService.getCommentAnnotationsById$().pipe(fe(()=>{let o=this.mergeCommentAnnotationsWithData({data:t?.data??{},feature:i}),s=this.mergeUsersWithData({feature:i,data:o??{}});return typeof s=="object"?{data:JSON.parse(JSON.stringify(s)),operation:t?.operation??null}:{data:s,operation:t?.operation??null}}),it(Ft))}catch(o){return this.loggingService.catch("Error in mergeCommentAnnotationsWithData:",o),ue(t)}}mergeReactionAnnotationsWithData$({data:t,feature:i}){try{return this.reactionAnnotationsResolverService.getReactionAnnotationsById$().pipe(fe(()=>{let o=this.mergeReactionAnnotationsWithData({data:t?.data??{},feature:i}),s=this.mergeUsersWithData({feature:i,data:o??{}});return typeof s=="object"?{data:JSON.parse(JSON.stringify(s)),operation:t?.operation??null}:{data:s,operation:t?.operation??null}}),it(Ft))}catch(o){return this.loggingService.catch("Error in mergeReactionAnnotationsWithData:",o),ue(t)}}mergeRecorderAnnotationsWithData$({data:t,feature:i}){try{return this.recorderAnnotationsResolverService.getRecorderAnnotationsById$().pipe(fe(()=>{let o=this.mergeRecorderAnnotationsWithData({data:t?.data??{},feature:i}),s=this.mergeUsersWithData({feature:i,data:o??{}});return typeof s=="object"?{data:JSON.parse(JSON.stringify(s)),operation:t?.operation??null}:{data:s,operation:t?.operation??null}}),it(Ft))}catch(o){return this.loggingService.catch("Error in mergeRecorderAnnotationsWithData:",o),ue(t)}}mergeUsersWithData$({feature:t,data:i}){try{return this.usersService.getUserById$().pipe(fe(()=>{let o=this.mergeUsersWithData({feature:t,data:i?.data??{}});return typeof o=="object"?{data:JSON.parse(JSON.stringify(o)),operation:i?.operation??null}:{data:o,operation:i?.operation??null}}),it(Ft))}catch(o){return this.loggingService.catch(`Error in mergeUsersWithData for ${t}:`,o),ue(i)}}mergeLocationMetadataWithData$({data:t,feature:i}){try{return this.docService.getLocationMetadata$().pipe(fe(o=>{let s=this.mergeLocationMetadataWithData({data:t?.data??{},feature:i,locationMetadata:o});return typeof s=="object"?{data:JSON.parse(JSON.stringify(s)),operation:t?.operation??null}:{data:s,operation:t?.operation??null}}),it(Ft))}catch(o){return this.loggingService.catch(`Error in mergeLocationMetadataWithData for ${i}:`,o),ue(t)}}handleDataStripping(a){return I(this,arguments,function*({feature:t,data:i,actionType:o,commentId:s}){try{switch(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: handleDataStripping","color: green;"),t){case"comment":{let c=yield this.commentUtilsService.stripCommentAnnotationData({data:i,actionType:o,commentId:s});return this.filterOriginalDataForVeltDb({feature:t,result:c,providerAvailable:this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable()})}case"reaction":{let c=this.reactionUtilsService.stripReactionAnnotationData(i);return this.filterOriginalDataForVeltDb({feature:t,result:c,providerAvailable:this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable()})}case"recorder":{let c=this.serviceBook.get(ci)?.stripRecorderAnnotationData({data:i,actionType:o})??{originalData:i,strippedData:null};return this.filterOriginalDataForVeltDb({feature:t,result:c,providerAvailable:this.recorderAnnotationsResolverService.recorderAnnotationDataProviderAvailable()})}default:return{originalData:i,strippedData:null}}}catch(c){return this.loggingService.catch("Error in CommonDbUtilsService handleDataStripping:",c),{originalData:i,strippedData:null}}})}filterOriginalDataForVeltDb({feature:t,result:i,providerAvailable:o}){try{return!o||!i||i.originalData===null||i.originalData===void 0?i:le(x({},i),{originalData:this.applyVeltDbFieldFilter(t,i.originalData)})}catch(s){return this.loggingService.catch("Error in CommonDbUtilsService filterOriginalDataForVeltDb:",s),i}}applyVeltDbFieldFilter(t,i){switch(t){case"comment":return WV(i,{stripAttachmentFiles:this.attachmentResolverService.attachmentDataProviderAvailable()});case"reaction":return zV(i);case"recorder":return qV(i);default:return i}}formatData({feature:t,data:i,properties:o,offset:s,isRealtimeDb:a}){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()+s;switch(t){case"documentAccessType":return delete i?.users,{docIamConfig:i};case"organizationMetadata":case"documentMetadata":return a?i:{metadata:i};case"documentCommentMetadata":return i;case"cursor":{let l=this.serviceBook.get(vT);return l?l.formatCursorUserData(i):i}case"comment":return this.commentUtilsService.formatCommentData(i);case"area":return this.areaUtilsService.formatAreaData(i);case"arrow":{let l=this.serviceBook.get(IT);return l?l.formatArrowData(i):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.serviceBook.get(ci)?.formatRecorderData(i,c)??i;case"notificationViewsTimestamp":return{views:{[o.user??""]:i}};case"documentUsersViews":return a?i:{users:{[o.user??""]:{[o.date??""]:i}}};case"documentDayViews":return a?i:{day:{[o.date??""]:{[o.user??""]:i}}};case"documentMetadataViews":return a?i:{metadata:i};case"huddleMessage":return this.serviceBook.get(ST)?.formatHuddleMessageData(i)??i;case"locationMetadataViews":return a?i:{metadata:i};case"locationUsersViews":return a?i:{users:{[o.user??""]:{[o.date??""]:i}}};case"locationDayViews":return a?i:{day:{[o.date??""]:{[o.user??""]:i}}};case"locationViews":return a?i:{location:i};case"docNotificationViews":return a?i:{views:i.views};case"userNotificationViews":return a?i:{views:i.views};case"presence":{let l=this.serviceBook.get(yT);return l?l.formatPresenceUserData(i):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(a){return I(this,arguments,function*({feature:t,data:i,subscriber:o,operation:s=null}){try{let c=yield this.modifyData({feature:t,data:i});o.next({data:c,operation:s})}catch(c){this.loggingService.catch("Error in CommonDbUtilsService modifyAndSetData:",c)}})}isDataAlreadyProcessedInLocalCache({feature:t,change:i,cache:o}){try{if(t==="allReactions"||t==="allComments"){if(i.type==="removed")return!Object.keys(o??{}).includes(i.doc.id);if(o?.[i.doc.id]){let s=i.doc.data(),a=o?.[i.doc.id];return s?.lastUpdated===a?.lastUpdated}}return!1}catch(s){return this.loggingService.catch("Error in CommonDbUtilsService isDataAlreadyProcessedInLocalCache:",s),!1}}modifyData(o){return I(this,arguments,function*({feature:t,data:i}){try{return yield this.formatResponse({feature:t,data:i})}catch(s){return this.loggingService.catch("Error in CommonDbUtilsService modifyData:",s),i}})}addMetadata(t,i){try{return t&&typeof t=="object"&&!Array.isArray(t)?le(x({},t),{metadata:t?.metadata??{documentId:i?.documentId,organizationId:i?.organizationId,apiKey:i?.apiKey}}):t}catch(o){return this.loggingService.catch("Error in CommonDbUtilsService addMetadata:",o),t}}setDataInLocal(l){return I(this,arguments,function*({feature:t,data:i,observablesCache:o,eventType:s,id:a,operation:c=null}){try{let d={comment:"allComments",reaction:"allReactions"}[t];if(!d)return null;let f=i?.metadata?.documentId,g=i?.metadata?.veltFolderId;return Object.keys(o).filter(p=>p.includes(d)&&(!f||p.includes(f)||g&&p.includes(g))).forEach(p=>{let _=o[p]?.subject?.getValue()??{};s==="DELETE"?a&&_?.data?.[a]&&(delete _?.data?.[a],o[p]?.subject&&o[p].subject.next({data:_?.data,operation:c})):o[p]?.subject?.next({data:le(x({},_?.data),{[i?.annotationId]:i}),operation:c})}),null}catch(u){return this.loggingService.catch("Error in CommonDbUtilsService setDataInLocal:",u),null}})}handleCommentEncryption(c){return I(this,arguments,function*({data:t,firestorePath:i,extraData:o,eventType:s,metadata:a}){try{return yield this.commentUtilsService.handleCommentEncryption({data:t,firestorePath:i,extraData:o,eventType:s,metadata:a})}catch(l){return this.loggingService.catch("Error in CommonDbUtilsService handleCommentEncryption:",l),t}})}handleReactionEncryption(s){return I(this,arguments,function*({data:t,firestorePath:i,eventType:o}){try{return yield this.reactionUtilsService.handleReactionEncryption({data:t,firestorePath:i,eventType:o})}catch(a){return this.loggingService.catch("Error in CommonDbUtilsService handleReactionEncryption:",a),t}})}rtdbDefaultTransactionCallback(t,i){try{let o=x({},t||{});return Object.entries(i).forEach(([s,a])=>{a==null?delete o[s]:o[s]=a}),o}catch(o){return this.loggingService.catch("Error in CommonDbUtilsService rtdbDefaultTransactionCallback:",o),t}}};e.\u0275fac=function(i){return new(i||e)(w(Xy),w(Kz),w(Ky),w(Yz),w(It),w(zz),w(_e),w(Qz),w(Qy),w(Xz),w(Jz),w(zt),w(zh),w(zo),w(qo),w(ec),w(Zy),w(Yy),w(li),w(Wh))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let n=e;return n})();var e3=(()=>{let e=class e{constructor(t,i,o){this.configService=t,this.authService=i,this.loggingService=o,this.firestore$=new Y(null);try{Zr([this.authService.getFirebaseConfig$(),this.configService.getApiKey$(),this.configService.getFirestorePersistentCacheEnabled$()]).pipe(Ct(([s,a])=>!!s&&!!a),Nt(1)).subscribe(([s,a,c])=>{if(s&&a&&s?.firebaseOptions?.storeDbId){try{let d=sessionStorage?.getItem("veltFirestoreLogLevel")||st?.firebaseLogLevel||"silent";YL(d)}catch(d){this.loggingService.catch("Error in FirestoreService setLogLevel: ",d)}let l=tc.getFirestoreProdDbName(a,s.firebaseOptions),u=this.configService.getProxyConfig();if(u?.v2DbHost){let d={host:u.v2DbHost,ssl:!0};u.forceLongPolling?d.experimentalForceLongPolling=!0:d.experimentalAutoDetectLongPolling=!0,c&&(d.localCache=bM({tabManager:LM()}));try{this.firestore$.next(Gy(Sr(),d,l))}catch(f){this.loggingService.catch("Firestore proxy: initializeFirestore failed, falling back to existing instance. Proxy settings may not be applied: ",f),this.firestore$.next($h(l))}}else if(c)try{let d=Sr(),f=Gy(d,{localCache:bM({tabManager:LM()})},l);this.firestore$.next(f)}catch{this.firestore$.next($h(l))}else this.firestore$.next($h(l))}},s=>{})}catch{}}getFirestore(){return this.firestore$.asObservable()}getFirestoreValue(){return this.firestore$.value}generateFirestoreDocumentId(){try{let t=this.getFirestoreValue()||$h("DocumentIdDb");if(t){let i=Dp(t,"generateDocumentId");return Hh(i).id}return}catch(t){this.loggingService.catch("Error in FirestoreService generateFirestoreDocumentId: ",t);return}}};e.\u0275fac=function(i){return new(i||e)(w(Rr),w(Cr),w(_e))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let n=e;return n})();var jke=(()=>{let e=class e{constructor(t,i,o,s,a,c,l,u,d,f,g,p,_,T,D){this.activityUtilsService=t,this.authService=i,this.commonDbUtilsService=o,this.coreActionsService=s,this.loggingService=a,this.firestoreService=c,this.databaseService=l,this.configService=u,this.docService=d,this.usersService=f,this.commentAnnotationsResolverService=g,this.reactionAnnotationsResolverService=p,this.recorderAnnotationsResolverService=_,this.notificationResolverService=T,this.serviceBook=D,this.offset=0,this.db=null,this.firestore=null,this.subscriptions=[],this.offsetListener=null,this.observablesCache={},this.firestoreSubscriptions={},this.rtdbSubscriptions={},this.loggingService.log("%c[WB] Creating CLASS: CommonDbService","color: blue;"),this.serviceBook.observe(CT).subscribe(b=>{this.activityService=b??void 0}),this.docService.setCommonDbService(this),this.authService.setCommonDbService(this),this.usersService.setCommonDbService(this),this.subscriptions.push(this.databaseService.getDb().subscribe(b=>{if(b){this.db=b;let G=wa(b,".info/serverTimeOffset");this.offsetListener=gv(G,M=>{let U=M.val();this.offset=U})}})),this.subscriptions.push(this.firestoreService.getFirestore().subscribe(b=>{b&&(this.firestore=b)}))}unsubscribeFromObservables(){try{Object.values(this.firestoreSubscriptions??{}).forEach(t=>{t?.unsubscribe()}),Object.values(this.rtdbSubscriptions??{}).forEach(t=>{t?.unsubscribe()}),Object.entries(this.observablesCache??{}).forEach(([t,i])=>{i?.subject?.complete(),i?.subject?.unsubscribe()}),this.observablesCache={},this.firestoreSubscriptions={},this.rtdbSubscriptions={}}catch(t){this.loggingService.catch("Error in unsubscribeFromObservables:",t)}}ngOnDestroy(){this.subscriptions.forEach(t=>t.unsubscribe()),this.offsetListener&&this.offsetListener(),this.unsubscribeFromObservables()}setupOnDisconnect(t,i){return I(this,null,function*(){try{if(this.db){let o=wa(this.db,t);return M2(o).update(i)}return Promise.resolve()}catch(o){return this.loggingService.catch("Error in setupOnDisconnect:",o),Promise.resolve()}})}getOffset(){return this.offset}getServerTimestamp(){return new Date().getTime()+this.getOffset()}subscribeToServices(t){Zr([this.databaseService.getDb(),this.firestoreService.getFirestore()]).pipe(Ct(([i,o])=>!!i),Nt(1),Ks(([i,o])=>{t({db:i,firestore:o})})).subscribe({error:i=>{this.loggingService.catch("Error in CommonDbService subscription: ",i)}})}performDatabaseOperation(t,i,o,s,a,c){return I(this,null,function*(){try{if(!i){this.loggingService.warn(`%c[WB] No properties found for ${t}`,"color: red;");return}return this.subscribeToServices(d=>I(this,[d],function*({db:l,firestore:u}){let f;i?.skipFirestore||(f=this.commonDbUtilsService.getFirestorePath({feature:t,properties:i,documentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey()}));let g=this.commonDbUtilsService.getDocumentPath({feature:t,properties:i,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey(),useFirestore:this.shouldUseFirestore()});if(!l){this.loggingService.warn(`%c[WB] No database or firestore found for ${t}`,"color: red;");return}try{let p,_;try{g&&(p=wa(l,`${g}`))}catch{this.loggingService.catch("Error in dbRef")}try{f?.includes("/organizations")&&u&&f&&(_=Hh(u,`${f}`))}catch{this.loggingService.catch("Error in docRef")}if(!this.authService.getUser())return;yield o({dbRef:p,firestoreRef:_,data:s,firestorePath:f}),c&&c({firestoreAvailable:!!u})}catch(p){this.loggingService.catch(`Error in ${t} operation: `,p),a&&a(p)}}))}catch(l){this.loggingService.catch("Error in performDatabaseOperation:",l)}})}setData(l){return I(this,arguments,function*({feature:t,data:i,properties:o,callback:s,errorCallback:a,extraData:c}){try{return this.loggingService.log(`%c[WB] Calling FUNCTION: setData for ${t}`,"color: green;"),this.shouldUseFirestore()&&i?.metadata&&!i?.metadata?.apiKey?void 0:(this.commonDbUtilsService.setDataInLocal({feature:t,data:i,observablesCache:this.observablesCache,operation:null}),this.createActivityFromExtraData(t,c),this.performDatabaseOperation(t,o,u=>I(this,null,function*(){if(u.dbRef){let d=this.commonDbUtilsService.formatData({feature:t,data:u.data,properties:o,offset:this.getOffset(),isRealtimeDb:!0});o?.rtdbTransaction?yield Iw(u.dbRef,()=>JSON.parse(JSON.stringify(d))):yield vw(u.dbRef,JSON.parse(JSON.stringify(d)))}try{if(u.firestoreRef&&u.data&&!o?.skipFirestore){let d=this.commonDbUtilsService.formatData({feature:t,data:u.data,properties:o,offset:this.getOffset()});typeof d=="object"&&(d=JSON.parse(JSON.stringify(d)));let{strippedData:f,originalData:g,eventType:p}=yield this.commonDbUtilsService.handleDataStripping({feature:t,data:d,actionType:c?.actionType,commentId:c?.targetAnnotationData?.commentId??o?.targetCommentId});if(t==="comment"){let _=null,T=J();this.coreActionsService.triggerAction($.COMMENT_RESOLVER,{event:L.Events.Resolver.COMMENT_SAVE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:T,methodName:Et.SET_DATA,source:"internal",payload:{strippedData:f,originalData:g,eventType:p,commentId:c?.targetAnnotationData?.commentId}}),f&&(_=yield this.commentAnnotationsResolverService.saveCommentAnnotation({commentAnnotation:f,eventType:p,commentId:c?.targetAnnotationData?.commentId},T)),g&&(_?.isSuccess||_===null)&&(yield this.commonDbUtilsService.handleCommentEncryption({data:g,firestorePath:u.firestorePath??"",extraData:c,metadata:o?.metadata}))}else if(t==="reaction"){let _=null,T=J();this.coreActionsService.triggerAction($.REACTION_RESOLVER,{event:L.Events.Resolver.REACTION_SAVE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:T,methodName:_t.SET_DATA,source:"internal",payload:{strippedData:f,originalData:g}}),f&&(_=yield this.reactionAnnotationsResolverService.saveReactionAnnotation(f,T)),g&&(_?.isSuccess||_===null)&&(yield this.commonDbUtilsService.handleReactionEncryption({data:g,firestorePath:u.firestorePath??""}))}else if(t==="recorder"){let _=null,T=J();this.coreActionsService.triggerAction($.RECORDER_RESOLVER,{event:L.Events.Resolver.RECORDER_SAVE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:T,methodName:Tt.SET_DATA,source:"internal",payload:{strippedData:f,originalData:g}}),f&&(_=yield this.recorderAnnotationsResolverService.saveRecorderAnnotation({recorderAnnotation:f,eventType:p},T)),g&&(_?.isSuccess||_===null)&&this.firestore&&(yield kM(this.firestore,D=>I(this,null,function*(){D.set(u.firestoreRef,JSON.parse(JSON.stringify(g)))})))}else yield UM(u.firestoreRef,d)}}catch(d){this.authService.getUser()&&this.loggingService.catch(`Error in setData for ${t}`,d)}}),i,a,s))}catch(u){this.loggingService.catch(`Error in setData for ${t}`,u)}})}updateData(l){return I(this,arguments,function*({feature:t,data:i,properties:o,callback:s,errorCallback:a,extraData:c}){try{return this.loggingService.log(`%c[WB] Calling FUNCTION: updateData for ${t}`,"color: green;"),this.shouldUseFirestore()&&i?.metadata&&!i?.metadata?.apiKey?void 0:(this.commonDbUtilsService.setDataInLocal({feature:t,data:i,observablesCache:this.observablesCache,operation:null}),this.createActivityFromExtraData(t,c),this.performDatabaseOperation(t,o,u=>I(this,null,function*(){if(u.dbRef&&!o?.skipRtdb){let d=this.commonDbUtilsService.formatData({feature:t,data:u.data,properties:o,offset:this.getOffset(),isRealtimeDb:!0});o?.rtdbTransaction?yield Iw(u.dbRef,f=>{let g;return o?.rtdbTransactionCallback?g=o.rtdbTransactionCallback(f,d):g=this.commonDbUtilsService.rtdbDefaultTransactionCallback(f,d),JSON.parse(JSON.stringify(g))}):yield F2(u.dbRef,JSON.parse(JSON.stringify(d)))}try{if(u.firestoreRef&&u.data&&!o?.skipFirestore){let d=this.commonDbUtilsService.formatData({feature:t,data:u.data,properties:o,offset:this.getOffset()});typeof d=="object"&&(d=JSON.parse(JSON.stringify(d)));let{strippedData:f,originalData:g,eventType:p}=yield this.commonDbUtilsService.handleDataStripping({feature:t,data:d,actionType:c?.actionType,commentId:c?.targetAnnotationData?.commentId});if(t==="comment"){let _=null,T=J();this.coreActionsService.triggerAction($.COMMENT_RESOLVER,{event:L.Events.Resolver.COMMENT_SAVE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:T,methodName:Et.UPDATE_DATA,source:"internal",payload:{strippedData:f,originalData:g,eventType:p,commentId:c?.targetAnnotationData?.commentId}}),f&&(_=yield this.commentAnnotationsResolverService.saveCommentAnnotation({commentAnnotation:f,eventType:p,commentId:c?.targetAnnotationData?.commentId},T)),g&&(_?.isSuccess||_===null)&&(yield this.commonDbUtilsService.handleCommentEncryption({data:g,firestorePath:u.firestorePath??"",extraData:c,metadata:o?.metadata}))}else if(t==="reaction"){let _=null,T=J();this.coreActionsService.triggerAction($.REACTION_RESOLVER,{event:L.Events.Resolver.REACTION_SAVE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:T,methodName:_t.UPDATE_DATA,source:"internal",payload:{strippedData:f,originalData:g}}),f&&(_=yield this.reactionAnnotationsResolverService.saveReactionAnnotation(f,T)),g&&(_?.isSuccess||_===null)&&(yield this.commonDbUtilsService.handleReactionEncryption({data:g,firestorePath:u.firestorePath??""}))}else if(t==="recorder"){let _=null,T=J();this.coreActionsService.triggerAction($.RECORDER_RESOLVER,{event:L.Events.Resolver.RECORDER_SAVE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:T,methodName:Tt.UPDATE_DATA,source:"internal",payload:{strippedData:f,originalData:g}}),f&&(_=yield this.recorderAnnotationsResolverService.saveRecorderAnnotation({recorderAnnotation:f,eventType:p},T)),g&&(_?.isSuccess||_===null)&&this.firestore&&(yield kM(this.firestore,D=>I(this,null,function*(){D.set(u.firestoreRef,JSON.parse(JSON.stringify(g)))})))}else yield UM(u.firestoreRef,d,{merge:!0})}}catch(d){this.authService.getUser()&&this.loggingService.catch(`Error in updateDoc for ${t}`,d)}}),i,a,s))}catch(u){this.loggingService.catch(`Error in updateData for ${t}`,u)}})}createActivityFromExtraData(t,i){try{if(!i?.actionType||!this.activityService)return;let o=this.activityUtilsService.buildActivityDataFromExtraData({feature:t,extraData:i});o&&this.activityService.createActivity(o)}catch(o){this.loggingService.catch("Error in CommonDbService createActivityFromExtraData:",o)}}deleteData(c){return I(this,arguments,function*({feature:t,properties:i,callback:o,errorCallback:s,extraData:a}){try{return this.loggingService.log(`%c[WB] Calling FUNCTION: deleteData for ${t}`,"color: green;"),this.commonDbUtilsService.setDataInLocal({feature:t,observablesCache:this.observablesCache,eventType:"DELETE",id:i?.id,operation:{type:"removed",ids:[i?.id]}}),this.createActivityFromExtraData(t,a),this.performDatabaseOperation(t,i,l=>I(this,null,function*(){l.dbRef&&(yield x2(l.dbRef));try{if(l.firestoreRef&&!i?.skipFirestore)if(t==="comment"){let u=null,d=J();this.coreActionsService.triggerAction($.COMMENT_RESOLVER,{event:L.Events.Resolver.COMMENT_DELETE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:d,methodName:Et.DELETE_DATA,source:"internal",payload:{commentAnnotationId:i?.id??"",metadata:i?.metadata}}),u=yield this.commentAnnotationsResolverService.deleteCommentAnnotation(i?.id??"",i?.metadata,d),(u?.isSuccess||u===null)&&(yield this.commonDbUtilsService.handleCommentEncryption({firestorePath:l.firestorePath??"",eventType:"DELETE",metadata:i?.metadata}))}else if(t==="reaction"){let u=null,d=J();this.coreActionsService.triggerAction($.REACTION_RESOLVER,{event:L.Events.Resolver.REACTION_DELETE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:d,methodName:_t.DELETE_DATA,source:"internal",payload:{reactionAnnotationId:i?.id??"",metadata:i?.metadata}}),u=yield this.reactionAnnotationsResolverService.deleteReactionAnnotation(i?.id??"",i?.metadata,d),(u?.isSuccess||u===null)&&(yield this.commonDbUtilsService.handleReactionEncryption({firestorePath:l.firestorePath??"",eventType:"DELETE"}))}else if(t==="recorder"){let u=null,d=J();this.coreActionsService.triggerAction($.RECORDER_RESOLVER,{event:L.Events.Resolver.RECORDER_DELETE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:d,methodName:Tt.DELETE_DATA,source:"internal",payload:{recorderAnnotationId:i?.id??"",metadata:i?.metadata}}),u=yield this.recorderAnnotationsResolverService.deleteRecorderAnnotation(i?.id??"",i?.metadata,d),(u?.isSuccess||u===null)&&(yield Hy(l.firestoreRef))}else if(t==="userNotification"){let u=null,d=J();this.coreActionsService.triggerAction($.NOTIFICATION_RESOLVER,{event:L.Events.Resolver.NOTIFICATION_DELETE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:d,methodName:Fn.DELETE_DATA,source:"internal",payload:{notificationId:i?.id??"",organizationId:i?.organizationId??""}}),u=yield this.notificationResolverService.deleteNotification(String(i?.id??""),this.docService.getDocumentPaths()?.clientOrganizationId??"",d),(u?.isSuccess||u===null)&&(yield Hy(l.firestoreRef))}else yield Hy(l.firestoreRef)}catch(u){this.authService.getUser()&&this.loggingService.catch(`Error in deleteData for ${t}`,u)}}),void 0,s,o)}catch(l){this.loggingService.catch(`Error in deleteData for ${t}`,l)}})}shouldUseFirestore(){try{return this.authService.getAdvancedQueriesEnabled()}catch(t){return this.loggingService.catch("Error in shouldUseFirestore:",t),!1}}generateDocumentId(){try{let t=this.firestoreService.generateFirestoreDocumentId();return t||(t=J()),t||"noDocumentId"}catch(t){return this.loggingService.catch("Error in generateFirestoreDocumentId:",t),J()||"noDocumentId"}}queryData(o){return I(this,arguments,function*({feature:t,properties:i}){try{let s=this.shouldUseFirestore();return!t||!i?(this.loggingService.warn("[WB] Missing required parameters in queryData"),[]):s?yield this.handleFirestoreQuery(t,i):yield this.handleRtdbQuery(t,i)}catch(s){return this.loggingService.catch(`Error in queryData for ${t}`,s),[]}})}handleFirestoreQuery(t,i){return I(this,null,function*(){try{if(!this.firestore)return this.loggingService.warn("[WB] Firestore not initialized"),[];let o=i?.useCollectionGroup?this.commonDbUtilsService.getFirestoreCollectionGroupPath(t):this.commonDbUtilsService.getFirestorePath({feature:t,properties:i,documentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey()});if(!o)return this.loggingService.warn(`[WB] No firestore path found for ${t}`),[];try{let s=Dp(this.firestore,o);i?.useCollectionGroup&&(s=PM(this.firestore,o));let a=i?.firestoreQuery??[],c=FM(s,...a);if(!this.authService.getUser()&&!i?.skipUserCheck)return[];if(i?.getCount)try{let l=yield Uz(c).catch(u=>(this.authService.getUser()&&this.loggingService.catch(`Error in getCountFromServer for ${t}`,u),null));return l?l.data().count:0}catch(l){return this.authService.getUser()&&this.loggingService.catch(`Error in getCountFromServer for ${t}`,l),0}else try{let l=yield Bz(c).catch(d=>(this.authService.getUser()&&this.loggingService.catch(`Error in getDocs for ${t}`,d),null));if(!l)return[];let u=l.docs.map(d=>d.data());try{return yield this.commonDbUtilsService.modifyData({feature:t,data:u})}catch(d){return this.loggingService.catch(`Error in modifyData for ${t}`,d),u}}catch(l){return this.authService.getUser()&&this.loggingService.catch(`Error in getDocs for ${t}`,l),[]}}catch(s){return this.loggingService.catch(`Error in Firestore query for ${t}:`,s),[]}}catch(o){return this.loggingService.catch(`Error in Firestore query for ${t}:`,o),[]}})}handleRtdbQuery(t,i){return I(this,null,function*(){if(!this.db)return this.loggingService.warn("[WB] Realtime Database not initialized"),[];let o=this.commonDbUtilsService.getDocumentPath({feature:t,properties:i,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey()});if(!o)return this.loggingService.warn(`[WB] No database path found for ${t}`),[];try{let s=wa(this.db,o),a=i?.rtdbQuery??[],c=Tw(s,...a);if(!this.authService.getUser()&&!i?.skipUserCheck)return[];let l=yield Ew(c).catch(d=>(this.authService.getUser()&&this.loggingService.catch(`Error in get for ${t}`,d),null));if(!l)return[];let u=l.val();return u?i?.skipObjectValues?u:Object.values(u??{}):[]}catch(s){return this.loggingService.catch(`Error in RTDB query for ${t}:`,s),[]}})}getData(o){return I(this,arguments,function*({feature:t,properties:i}){try{let s=this.shouldUseFirestore();if(i?.skipFirestore&&(s=!1),!t||!i)return this.loggingService.warn("[WB] Missing required parameters in getData"),{};if(s&&this.firestore){let a=this.commonDbUtilsService.getFirestorePath({feature:t,properties:i,documentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey()});if(!a)return this.loggingService.warn(`[WB] No firestore path found for ${t}`),{};try{if(!this.authService.getUser())return this.loggingService.catch("User not set. [source: getData]",void 0,void 0,!0),{};let c=yield Vz(Hh(this.firestore,a)).catch(u=>(this.authService.getUser()&&!i?.suppressError&&this.loggingService.catch(`Error in getDoc for ${t}`,u),this.commonDbUtilsService.getErrorForGetRequests({feature:t,error:u})));if(c){if(c?.errorCode)return c}else return this.loggingService.warn(`[WB] No document found at ${a}`),{};let l=c.data();return i?.field?l?.[i.field]??{}:l??{}}catch(c){return this.loggingService.catch(`Error fetching Firestore data for ${t}:`,c),{}}}if(this.db){let a=this.commonDbUtilsService.getDocumentPath({feature:t,properties:i,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey()});if(!a)return this.loggingService.warn(`[WB] No database path found for ${t}`),{};try{if(!this.authService.getUser())return{};let c=yield Ew(wa(this.db,a)).catch(u=>(this.authService.getUser()&&this.loggingService.catch(`Error in get for ${t}`,u),this.commonDbUtilsService.getErrorForGetRequests({feature:t,error:u})));if(c){if(c?.errorCode)return c}else return this.loggingService.warn(`[WB] No data found at ${a}`),{};let l=c.val();return i?.field?l?.[i.field]??{}:l??{}}catch(c){return this.loggingService.catch(`Error fetching RTDB data for ${t}:`,c),{}}}return this.loggingService.warn("[WB] No database connection available"),{}}catch(s){return this.loggingService.catch("Unexpected error in getData:",s),{}}})}dbListener({feature:t,properties:i}){let o=this.shouldUseFirestore();i?.skipFirestore&&(o=!1);let s=`${t}-${JSON.stringify(i)}`;return Zr([this.databaseService.getDb(),this.firestoreService.getFirestore(),this.authService.getUser$().pipe(Ct(a=>!!a))]).pipe(Ct(([a,c])=>a?o&&!c?(this.loggingService.warn(`[WB] Firestore requested but not available for ${t}`),!1):!0:(this.loggingService.warn(`[WB] No database found for ${t}`),!1)),mt(([a,c])=>{try{if(o&&c){if(!!!this.observablesCache[s]){this.observablesCache[s]={subject:new Y({}),count:0};let d=this.handleFirestoreListener(t,i,c).subscribe(f=>{this.observablesCache[s]?.subject?.next(f)},f=>this.observablesCache[s]?.subject?.error(f));this.firestoreSubscriptions[s]=d}return new ge(u=>{let d=this.observablesCache[s]?.subject?.subscribe(f=>u.next(f),f=>u.error(f),()=>u.complete());return this.observablesCache[s].count+=1,()=>{d?.unsubscribe(),this.observablesCache[s]&&(this.observablesCache[s].count-=1,this.observablesCache[s].count<=0&&(this.firestoreSubscriptions[s]?.unsubscribe(),delete this.firestoreSubscriptions[s],this.observablesCache[s]?.subject?.complete(),delete this.observablesCache[s]))}})}else if(a){if(!!!this.observablesCache[s]){this.observablesCache[s]={subject:new Y({}),count:0};let d=this.handleRealtimeDbListener(t,i,a).subscribe(f=>{this.observablesCache[s]?.subject?.next(f)},f=>this.observablesCache[s]?.subject?.error(f));this.rtdbSubscriptions[s]=d}return new ge(u=>{let d=this.observablesCache[s]?.subject?.subscribe(f=>u.next(f),f=>u.error(f),()=>u.complete());return this.observablesCache[s].count+=1,()=>{d?.unsubscribe(),this.observablesCache[s]&&(this.observablesCache[s].count-=1,this.observablesCache[s].count<=0&&(this.rtdbSubscriptions[s]?.unsubscribe(),delete this.rtdbSubscriptions?.[s],this.observablesCache[s]?.subject?.complete(),delete this.observablesCache?.[s]))}})}return ue({})}catch(l){return this.loggingService.catch(`Error setting up listener for ${t}:`,l),ue({})}}),Sc(()=>{this.loggingService.log(`[WB] Cleaning up listener for ${t} and key ${s}`)}))}handleFirestoreListener(t,i,o){let s=i?.useCollectionGroup?this.commonDbUtilsService.getFirestoreCollectionGroupPath(t):this.commonDbUtilsService.getFirestorePath({feature:t,properties:i,documentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey()}),a=`${t}-${JSON.stringify(i)}`;return s?new ge(c=>{let l=i.isCollection?this.setupCollectionListener(o,s,t,c,i):this.setupDocumentListener(o,s,t,c,i);return()=>{c.complete(),c.unsubscribe(),l(),this.observablesCache[a]?.subject?.complete(),this.observablesCache[a]?.subject?.unsubscribe(),delete this.observablesCache[a]}}).pipe(mt(c=>this.commonDbUtilsService.mergeUsersWithData$({feature:t,data:c})),mt(c=>["allComments","allUserNotifications"].includes(t)?this.commonDbUtilsService.mergeCommentAnnotationsWithData$({data:c,feature:t}):ue(c)),mt(c=>["allReactions"].includes(t)?this.commonDbUtilsService.mergeReactionAnnotationsWithData$({data:c,feature:t}):ue(c)),mt(c=>["allRecorders"].includes(t)?this.commonDbUtilsService.mergeRecorderAnnotationsWithData$({data:c,feature:t}):ue(c)),it(Ft)):(this.loggingService.warn(`[WB] No firestore path found for ${t} and key ${a}`),ue({}))}setupCollectionListener(t,i,o,s,a){let c=`${o}-${JSON.stringify(a)}`,l=Dp(t,i);if(a?.useCollectionGroup&&(l=PM(t,i)),a?.useQuery&&a?.firestoreQuery){let f=a?.firestoreQuery??[];l=FM(l,...f)}let u=!0,d=[];return o==="allComments"&&this.loggingService.logContext("[CONTEXT] setupCollectionListener called with path:",i,"feature:",o,"properties:",JSON.stringify(a??"nil")),xM(l,f=>{try{let g=JSON.parse(JSON.stringify(this.observablesCache[c]?.subject?.getValue()?.data??{})),p=null,_=!1;f?.docChanges()?.length?f.docChanges().forEach(T=>{["allComments","allReactions","allRecorders"].includes(o)&&!u&&T.type!=="removed"&&d.push(T.doc.id),this.commonDbUtilsService.isDataAlreadyProcessedInLocalCache({feature:o,change:T,cache:this.observablesCache[c]?.subject?.getValue()?.data??{}})||(_=!0,Object.assign(g,this.handleCollectionChange(T,g)),T.type==="removed"&&(p||(p={type:T.type,ids:[]}),p.ids.push(T.doc.id)))}):_=!0,_&&(["allComments","allReactions","allRecorders"].includes(o)&&d?.length&&(this.commonDbUtilsService.resolveAnnotations({data:d,feature:o}),d=[]),this.commonDbUtilsService.modifyAndSetData({feature:o,data:g,subscriber:s,operation:p})),u=!1}catch(g){this.loggingService.logContext(`[ERROR] Firestore listener error for feature ${o}:`,g),this.loggingService.logContext(`[ERROR] Firestore listener error for properties ${JSON.stringify(a??"nil")}:`),this.loggingService.logContext(`[ERROR] Firestore listener error for user ${JSON.stringify(this.authService.getUser()??"nil")}:`),this.handleListenerError(g,o,s)}},f=>{this.loggingService.logContext(`[ERROR] Firestore listener error for feature ${o}:`,f),this.loggingService.logContext(`[ERROR] Firestore listener error for properties ${JSON.stringify(a??"nil")}:`),this.loggingService.logContext(`[ERROR] Firestore listener error for user ${JSON.stringify(this.authService.getUser()??"nil")}:`),this.handleListenerError(f,o,s)})}handleCollectionChange(t,i){switch(t.type){case"added":case"modified":i[t.doc.id]=t.doc.data();break;case"removed":delete i?.[t.doc.id];break}return i}setupDocumentListener(t,i,o,s,a){let c=Hh(t,i);return xM(c,l=>{try{let u=l.data()||{};a?.field&&(u=u?.[a?.field]??{}),this.commonDbUtilsService.modifyAndSetData({feature:o,data:u,subscriber:s,operation:null})}catch(u){this.handleListenerError(u,o,s)}},l=>this.handleListenerError(l,o,s))}handleListenerError(t,i,o){this.loggingService.catch(`Firestore listener error for ${i}:`,t)}handleRealtimeDbListener(t,i,o){let s=this.commonDbUtilsService.getDocumentPath({feature:t,properties:i,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey()});if(!s)return this.loggingService.warn(`[WB] No database path found for ${t}`),ue({});let a=wa(o,s);if(i?.useQuery&&i?.rtdbQuery){let c=i?.rtdbQuery??[];a=Tw(a,...c)}return this.objectValFromChildEvents(a,t).pipe(ts(c=>(this.loggingService.catch(`RTDB listener error for ${t}:`,c),ue({}))),fe(c=>(c===null&&(c={}),c&&typeof c=="object"?Object.entries(c??{}).reduce((u,[d,f])=>(u[d]=this.commonDbUtilsService.addMetadata(f,i),u),{}):this.commonDbUtilsService.addMetadata(c,i))),mt(c=>this.commonDbUtilsService.modifyData({feature:t,data:c})),mt(c=>this.usersService.getUserById$().pipe(fe(()=>({data:this.commonDbUtilsService.mergeUsersWithData({feature:t,data:c}),operation:null})))))}pushData(s){return I(this,arguments,function*({feature:t,properties:i,data:o}){try{return this.loggingService.log(`%c[WB] Calling FUNCTION: pushData for ${t}`,"color: green;"),this.performDatabaseOperation(t,i,a=>I(this,null,function*(){if(a.dbRef){let c=P2(a.dbRef);yield vw(c,JSON.parse(JSON.stringify(a.data)))}}),o)}catch(a){this.loggingService.catch(`Error in pushData for ${t}`,a)}})}streamChildAdded({feature:t,properties:i,afterTs:o}){try{return this.loggingService.log(`%c[WB] Calling FUNCTION: streamChildAdded for ${t}`,"color: green;"),new ge(s=>{let a=null,c=!1,l=({db:u})=>{if(!u||c||!this.authService.getUser())return;let d=this.commonDbUtilsService.getDocumentPath({feature:t,properties:i,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey(),useFirestore:!1});if(!d)return;let g=wa(u,d),p=!1,_=b=>{try{let G=b.val();if(p){if(o!=null&&G?.timestamp!=null&&G.timestamp<=o)return;s.next(G)}}catch(G){this.loggingService.catch(`streamChildAdded onChildAdded callback error for ${t}:`,G)}},T=b=>{try{this.loggingService.catch(`streamChildAdded error for ${t}:`,b),s.error(b)}catch(G){this.loggingService.catch(`streamChildAdded onError handler error for ${t}:`,G)}};_w(g,_,T);let D=gv(g,()=>{p=!0},T,{onlyOnce:!0});a=()=>{try{D&&typeof D=="function"&&D(),Am(g,"child_added",_)}catch(b){this.loggingService.catch(`streamChildAdded cleanup error for ${t}:`,b)}}};return this.subscribeToServices(l),()=>{c=!0,a&&a()}})}catch(s){return this.loggingService.catch(`Error in streamChildAdded for ${t}`,s),ue(null)}}objectValFromChildEvents(t,i){return new ge(o=>{let s={},a=!1,c=null,l=T=>{try{this.loggingService.catch(`Realtime DB listener error for ${i}:`,T),o.error(T)}catch{}},u=T=>{try{if(!ki(T,c)){let D=JSON.parse(JSON.stringify(T));c=D,o.next(D)}}catch{}},d=T=>{try{T.key&&(s[T.key]=T.val(),a&&u(x({},s)))}catch{}},f=T=>{try{T.key&&(s[T.key]=T.val(),a&&u(x({},s)))}catch{}},g=T=>{try{T.key&&(delete s[T.key],a&&u(x({},s)))}catch{}},p=T=>{try{if(!a){let D=s&&typeof s=="object"?JSON.parse(JSON.stringify(s)):{};c=D,o.next(D),a=!0}}catch{}};_w(t,d,l),b2(t,f,l),L2(t,g,l);let _=gv(t,p,l,{onlyOnce:!0});return()=>{try{_&&typeof _=="function"&&_(),Am(t,"child_added",d),Am(t,"child_changed",f),Am(t,"child_removed",g)}catch{}}})}};e.\u0275fac=function(i){return new(i||e)(w(Xy),w(Cr),w(Zz),w(It),w(_e),w(e3),w(Wy),w(Rr),w(zh),w(zt),w(zo),w(qo),w(ec),w(Zy),w(li))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let n=e;return n})();export{x as a,le as b,dS as c,pse as d,Ese as e,_se as f,I as g,gt as h,ge as i,RS as j,Ot as k,Y as l,Ac as m,l6 as n,u6 as o,Ic as p,xr as q,ue as r,d6 as s,h6 as t,Q3 as u,fe as v,Zr as w,GS as x,f6 as y,ho as z,I6 as A,Ci as B,H3 as C,Pu as D,Ct as E,P3 as F,ts as G,yS as H,Au as I,Nt as J,DS as K,it as L,Du as M,dE as N,NS as O,W3 as P,OS as Q,z3 as R,Ru as S,mt as T,qs as U,q3 as V,Ks as W,K3 as X,J3 as Y,oe as Z,ME as _,K as $,is as aa,Z as ba,w as ca,ne as da,pr as ea,Kn as fa,fo as ga,w0 as ha,b0 as ia,$0 as ja,j0 as ka,St as la,Dn as ma,cr as na,Fr as oa,To as pa,jc as qa,ei as ra,J6 as sa,pn as ta,VD as ua,E4 as va,sa as wa,g_ as xa,w_ as ya,D4 as za,iq as Aa,oq as Ba,sq as Ca,aq as Da,cq as Ea,Dq as Fa,cs as Ga,Le as Ha,Mq as Ia,y8 as Ja,S8 as Ka,yo as La,Yf as Ma,ds as Na,j_ as Oa,ut as Pa,M8 as Qa,Do as Ra,Kc as Sa,Tk as Ta,I5 as Ua,aa as Va,Ro as Wa,Xf as Xa,Dk as Ya,w5 as Za,Nk as _a,Ok as $a,z_ as ab,ca as bb,xk as cb,Fk as db,k5 as eb,V5 as fb,B5 as gb,G5 as hb,$5 as ib,j5 as jb,H5 as kb,kk as lb,AR as mb,DR as nb,Uk as ob,RR as pb,CR as qb,Vk as rb,NR as sb,OR as tb,Gk as ub,Q5 as vb,$k as wb,Hk as xb,Wk as yb,t9 as zb,r9 as Ab,i9 as Bb,s9 as Cb,a9 as Db,c9 as Eb,l9 as Fb,u9 as Gb,d9 as Hb,h9 as Ib,Xk as Jb,Jk as Kb,D9 as Lb,C9 as Mb,k9 as Nb,aU as Ob,wR as Pb,cU as Qb,lU as Rb,uU as Sb,G9 as Tb,dU as Ub,fU as Vb,$9 as Wb,j9 as Xb,H9 as Yb,W9 as Zb,Q9 as _b,X9 as $b,J9 as ac,Z9 as bc,eK as cc,tK as dc,nK as ec,rK as fc,iK as gc,oK as hc,sK as ic,aK as jc,lK as kc,dK as lc,hK as mc,fK as nc,gK as oc,mK as pc,_K as qc,rg as rc,ig as sc,xR as tc,qve as uc,Kve as vc,Yve as wc,KK as xc,qR as yc,Qve as zc,Xve as Ac,Jve as Bc,Co as Cc,HU as Dc,fY as Ec,a1 as Fc,gY as Gc,eC as Hc,mY as Ic,pY as Jc,EY as Kc,_Y as Lc,IY as Mc,yY as Nc,AY as Oc,tC as Pc,uC as Qc,GY as Rc,HY as Sc,O1 as Tc,g7 as Uc,m7 as Vc,pC as Wc,G1 as Xc,IC as Yc,Nd as Zc,Hr as _c,ha as $c,KT as ad,sl as bd,vr as cd,Ge as dd,_n as ed,ur as fd,Po as gd,yr as hd,pa as id,Sr as jd,Qe as kd,IX as ld,pbe as md,Ebe as nd,_be as od,Bi as pd,Ea as qd,vs as rd,Gi as sd,pe as td,$i as ud,ys as vd,Fbe as wd,kbe as xd,Ube as yd,Ta as zd,jJ as Ad,WJ as Bd,iZ as Cd,hl as Dd,fl as Ed,IMe as Fd,bd as Gd,EI as Hd,vMe as Id,g2 as Jd,dv as Kd,GPe as Ld,$Pe as Md,jPe as Nd,HPe as Od,WPe as Pd,zPe as Qd,qPe as Rd,M2 as Sd,gv as Td,KPe as Ud,P2 as Vd,wa as Wd,x2 as Xd,Iw as Yd,vw as Zd,YPe as _d,F2 as $d,dr as ae,VMe as be,BMe as ce,GMe as de,Dr as ee,H1 as fe,U7 as ge,Sg as he,st as ie,L as je,Ie as ke,Qt as le,pAe as me,EAe as ne,_Ae as oe,TAe as pe,$ as qe,IAe as re,vAe as se,yAe as te,SAe as ue,_7 as ve,T7 as we,I7 as xe,v7 as ye,_T as ze,y7 as Ae,S7 as Be,A7 as Ce,EC as De,D7 as Ee,$r as Fe,TT as Ge,R7 as He,md as Ie,wt as Je,C7 as Ke,Tg as Le,N7 as Me,O7 as Ne,w7 as Oe,b7 as Pe,L7 as Qe,M7 as Re,P7 as Se,v as Te,U1 as Ue,tDe as Ve,_d as We,H as Xe,oDe as Ye,sDe as Ze,ui as _e,bt as $e,W1 as af,z1 as bf,xDe as cf,FDe as df,bT as ef,vC as ff,LT as gf,xn as hf,tl as if,No as jf,Y1 as kf,Q1 as lf,X1 as mf,_s as nf,V7 as of,Un as pf,di as qf,J1 as rf,Z1 as sf,eV as tf,tV as uf,nV as vf,rV as wf,iV as xf,oV as yf,sV as zf,aV as Af,cV as Bf,B7 as Cf,G7 as Df,lV as Ef,AC as Ff,uV as Gf,dV as Hf,fV as If,$7 as Jf,Oo as Kf,j7 as Lf,H7 as Mf,vOe as Nf,OV as Of,Tr as Pf,Fi as Qf,da as Rf,Ts as Sf,wo as Tf,LOe as Uf,MOe as Vf,POe as Wf,xOe as Xf,FOe as Yf,kOe as Zf,UOe as _f,bV as $f,J as ag,VOe as bg,LV as cg,Sd as dg,SV as eg,AV as fg,z7 as gg,q7 as hg,il as ig,NC as jg,BOe as kg,bo as lg,GOe as mg,Rg as ng,ki as og,$Oe as pg,OC as qg,rl as rg,Q7 as sg,VT as tg,jOe as ug,HOe as vg,PV as wg,Cg as xg,X7 as yg,J7 as zg,Z7 as Ag,eQ as Bg,tQ as Cg,jr as Dg,WOe as Eg,RC as Fg,zOe as Gg,rQ as Hg,qOe as Ig,KOe as Jg,FV as Kg,YOe as Lg,QOe as Mg,XOe as Ng,JOe as Og,ZOe as Pg,ewe as Qg,twe as Rg,UT as Sg,nwe as Tg,rwe as Ug,iwe as Vg,owe as Wg,swe as Xg,awe as Yg,cwe as Zg,lwe as _g,uwe as $g,dwe as ah,hwe as bh,fwe as ch,gwe as dh,mwe as eh,pwe as fh,Ewe as gh,_we as hh,Twe as ih,Iwe as jh,vwe as kh,ywe as lh,Swe as mh,Awe as nh,Dwe as oh,Rwe as ph,aQ as qh,Cwe as rh,Nwe as sh,Owe as th,RV as uh,wwe as vh,bwe as wh,Ft as xh,Cn as yh,Lwe as zh,kt as Ah,Ht as Bh,Mwe as Ch,$V as Dh,Ad as Eh,bC as Fh,Ir as Gh,Pwe as Hh,CV as Ih,IT as Jh,NAe as Kh,OAe as Lh,xi as Mh,wAe as Nh,vT as Oh,bAe as Ph,LAe as Qh,yT as Rh,MAe as Sh,ST as Th,PAe as Uh,AT as Vh,xAe as Wh,ci as Xh,FAe as Yh,pd as Zh,kAe as _h,UAe as $h,VAe as ai,BAe as bi,GAe as ci,$Ae as di,jAe as ei,DT as fi,HAe as gi,WAe as hi,RT as ii,CT as ji,P1 as ki,x1 as li,F1 as mi,li as ni,Lt as oi,_e as pi,Rr as qi,U2 as ri,It as si,pv as ti,Ev as ui,Cr as vi,MM as wi,Lxe as xi,Mxe as yi,Pxe as zi,xxe as Ai,Ji as Bi,Wy as Ci,zo as Di,qo as Ei,Wh as Fi,ec as Gi,zh as Hi,zt as Ii,Ky as Ji,Yy as Ki,Xy as Li,Jy as Mi,zz as Ni,Zy as Oi,Zz as Pi,jke as Qi};
|
|
167
|
+
`+n.stack),e}function _H(n){return(function(r,t){if(typeof r!="object"||r===null)return!1;let i=r;for(let o of t)if(o in i&&typeof i[o]=="function")return!0;return!1})(n,["next","error","complete"])}var Xi=class extends Zl{constructor(e,r,t,i){super(e,r,t,i),this.type="firestore",this._queue=new Ay,this._persistenceKey=i?.name||"[DEFAULT]"}_terminate(){return I(this,null,function*(){if(this._firestoreClient){let e=this._firestoreClient.terminate();this._queue=new Ay(e),this._firestoreClient=void 0,yield e}})}};function Gy(n,e,r){r||(r=Xm);let t=Po(n,"firestore");if(t.isInitialized(r)){let i=t.getImmediate({identifier:r}),o=t.getOptions(r);if(Vi(o,e))return i;throw new Q(j.FAILED_PRECONDITION,"initializeFirestore() has already been called with different options. To avoid this error, call initializeFirestore() with the same options as when it was originally called, or call getFirestore() to return the already initialized instance.")}if(e.cacheSizeBytes!==void 0&&e.localCache!==void 0)throw new Q(j.INVALID_ARGUMENT,"cache and cacheSizeBytes cannot be specified at the same time as cacheSizeBytes willbe deprecated. Instead, specify the cache size in the cache object");if(e.cacheSizeBytes!==void 0&&e.cacheSizeBytes!==-1&&e.cacheSizeBytes<xW)throw new Q(j.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");return e.host&&Hr(e.host)&&ha(e.host),t.initialize({options:e,instanceIdentifier:r})}function $h(n,e){let r=typeof n=="object"?n:Sr(),t=typeof n=="string"?n:e||Xm,i=Po(r,"firestore").getImmediate({identifier:t});if(!i._initialized){let o=Nd("firestore");o&&az(i,...o)}return i}function jh(n){if(n._terminated)throw new Q(j.FAILED_PRECONDITION,"The client has already been terminated.");return n._firestoreClient||Joe(n),n._firestoreClient}function Joe(n){var e,r,t;let i=n._freezeSettings(),o=(function(a,c,l,u){return new rb(a,c,l,u.host,u.ssl,u.experimentalForceLongPolling,u.experimentalAutoDetectLongPolling,oz(u.experimentalLongPollingOptions),u.useFetchStreams,u.isUsingEmulator)})(n._databaseId,((e=n._app)===null||e===void 0?void 0:e.options.appId)||"",n._persistenceKey,i);n._componentsProvider||!((r=i.localCache)===null||r===void 0)&&r._offlineComponentProvider&&(!((t=i.localCache)===null||t===void 0)&&t._onlineComponentProvider)&&(n._componentsProvider={_offline:i.localCache._offlineComponentProvider,_online:i.localCache._onlineComponentProvider}),n._firestoreClient=new LL(n._authCredentials,n._appCheckCredentials,n._queue,o,n._componentsProvider&&(function(a){let c=a?._online.build();return{_offline:a?._offline.build(c),_online:c}})(n._componentsProvider))}var ML=class{constructor(e="count",r){this._internalFieldPath=r,this.type="AggregateField",this.aggregateType=e}},PL=class{constructor(e,r,t){this._userDataWriter=r,this._data=t,this.type="AggregateQuerySnapshot",this.query=e}data(){return this._userDataWriter.convertObjectMap(this._data)}};var Os=class n{constructor(e){this._byteString=e}static fromBase64String(e){try{return new n(un.fromBase64String(e))}catch(r){throw new Q(j.INVALID_ARGUMENT,"Failed to construct data from Base64 string: "+r)}}static fromUint8Array(e){return new n(un.fromUint8Array(e))}toBase64(){return this._byteString.toBase64()}toUint8Array(){return this._byteString.toUint8Array()}toString(){return"Bytes(base64: "+this.toBase64()+")"}isEqual(e){return this._byteString.isEqual(e._byteString)}toJSON(){return{type:n._jsonSchemaVersion,bytes:this.toBase64()}}static fromJSON(e){if(Ep(e,n._jsonSchema))return n.fromBase64String(e.bytes)}};Os._jsonSchemaVersion="firestore/bytes/1.0",Os._jsonSchema={type:ln("string",Os._jsonSchemaVersion),bytes:ln("string")};var xh=class{constructor(...e){for(let r=0;r<e.length;++r)if(e[r].length===0)throw new Q(j.INVALID_ARGUMENT,"Invalid field name at argument $(i + 1). Field names must not be empty.");this._internalPath=new Tn(e)}isEqual(e){return this._internalPath.isEqual(e._internalPath)}};var gp=class{constructor(e){this._methodName=e}};var Va=class n{constructor(e,r){if(!isFinite(e)||e<-90||e>90)throw new Q(j.INVALID_ARGUMENT,"Latitude must be a number between -90 and 90, but was: "+e);if(!isFinite(r)||r<-180||r>180)throw new Q(j.INVALID_ARGUMENT,"Longitude must be a number between -180 and 180, but was: "+r);this._lat=e,this._long=r}get latitude(){return this._lat}get longitude(){return this._long}isEqual(e){return this._lat===e._lat&&this._long===e._long}_compareTo(e){return Re(this._lat,e._lat)||Re(this._long,e._long)}toJSON(){return{latitude:this._lat,longitude:this._long,type:n._jsonSchemaVersion}}static fromJSON(e){if(Ep(e,n._jsonSchema))return new n(e.latitude,e.longitude)}};Va._jsonSchemaVersion="firestore/geoPoint/1.0",Va._jsonSchema={type:ln("string",Va._jsonSchemaVersion),latitude:ln("number"),longitude:ln("number")};var Ba=class n{constructor(e){this._values=(e||[]).map(r=>r)}toArray(){return this._values.map(e=>e)}isEqual(e){return(function(t,i){if(t.length!==i.length)return!1;for(let o=0;o<t.length;++o)if(t[o]!==i[o])return!1;return!0})(this._values,e._values)}toJSON(){return{type:n._jsonSchemaVersion,vectorValues:this._values}}static fromJSON(e){if(Ep(e,n._jsonSchema)){if(Array.isArray(e.vectorValues)&&e.vectorValues.every(r=>typeof r=="number"))return new n(e.vectorValues);throw new Q(j.INVALID_ARGUMENT,"Expected 'vectorValues' field to be a number array")}}};Ba._jsonSchemaVersion="firestore/vectorValue/1.0",Ba._jsonSchema={type:ln("string",Ba._jsonSchemaVersion),vectorValues:ln("object")};var Zoe=/^__.*__$/,xL=class{constructor(e,r,t){this.data=e,this.fieldMask=r,this.fieldTransforms=t}toMutation(e,r){return this.fieldMask!==null?new Yi(e,this.data,this.fieldMask,r,this.fieldTransforms):new qa(e,this.data,r,this.fieldTransforms)}},Dy=class{constructor(e,r,t){this.data=e,this.fieldMask=r,this.fieldTransforms=t}toMutation(e,r){return new Yi(e,this.data,this.fieldMask,r,this.fieldTransforms)}};function dz(n){switch(n){case 0:case 2:case 1:return!0;case 3:case 4:return!1;default:throw ae(40011,{Ec:n})}}var FL=class n{constructor(e,r,t,i,o,s){this.settings=e,this.databaseId=r,this.serializer=t,this.ignoreUndefinedProperties=i,o===void 0&&this.Ac(),this.fieldTransforms=o||[],this.fieldMask=s||[]}get path(){return this.settings.path}get Ec(){return this.settings.Ec}Rc(e){return new n(Object.assign(Object.assign({},this.settings),e),this.databaseId,this.serializer,this.ignoreUndefinedProperties,this.fieldTransforms,this.fieldMask)}Vc(e){var r;let t=(r=this.path)===null||r===void 0?void 0:r.child(e),i=this.Rc({path:t,mc:!1});return i.fc(e),i}gc(e){var r;let t=(r=this.path)===null||r===void 0?void 0:r.child(e),i=this.Rc({path:t,mc:!1});return i.Ac(),i}yc(e){return this.Rc({path:void 0,mc:!0})}wc(e){return Cy(e,this.settings.methodName,this.settings.Sc||!1,this.path,this.settings.bc)}contains(e){return this.fieldMask.find(r=>e.isPrefixOf(r))!==void 0||this.fieldTransforms.find(r=>e.isPrefixOf(r.field))!==void 0}Ac(){if(this.path)for(let e=0;e<this.path.length;e++)this.fc(this.path.get(e))}fc(e){if(e.length===0)throw this.wc("Document fields must not be empty");if(dz(this.Ec)&&Zoe.test(e))throw this.wc('Document fields cannot begin and end with "__"')}},kL=class{constructor(e,r,t){this.databaseId=e,this.ignoreUndefinedProperties=r,this.serializer=t||ky(e)}Dc(e,r,t,i=!1){return new FL({Ec:e,methodName:r,bc:t,path:Tn.emptyPath(),mc:!1,Sc:i},this.databaseId,this.serializer,this.ignoreUndefinedProperties)}};function $y(n){let e=n._freezeSettings(),r=ky(n._databaseId);return new kL(n._databaseId,!!e.ignoreUndefinedProperties,r)}function hz(n,e,r,t,i,o={}){let s=n.Dc(o.merge||o.mergeFields?2:0,e,r,i);OM("Data must be an object, but it was:",s,t);let a=gz(t,s),c,l;if(o.merge)c=new Yr(s.fieldMask),l=s.fieldTransforms;else if(o.mergeFields){let u=[];for(let d of o.mergeFields){let f=UL(e,d,r);if(!s.contains(f))throw new Q(j.INVALID_ARGUMENT,`Field '${f}' is specified in your field mask but missing from your input data.`);pz(u,f)||u.push(f)}c=new Yr(u),l=s.fieldTransforms.filter(d=>c.covers(d.field))}else c=null,l=s.fieldTransforms;return new xL(new nr(a),c,l)}var Ry=class n extends gp{_toFieldTransform(e){if(e.Ec!==2)throw e.Ec===1?e.wc(`${this._methodName}() can only appear at the top level of your update data`):e.wc(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`);return e.fieldMask.push(e.path),null}isEqual(e){return e instanceof n}};function ese(n,e,r,t){let i=n.Dc(1,e,r);OM("Data must be an object, but it was:",i,t);let o=[],s=nr.empty();Ja(t,(c,l)=>{let u=wM(e,c,r);l=Ge(l);let d=i.gc(u);if(l instanceof Ry)o.push(u);else{let f=Ap(l,d);f!=null&&(o.push(u),s.set(u,f))}});let a=new Yr(o);return new Dy(s,a,i.fieldTransforms)}function tse(n,e,r,t,i,o){let s=n.Dc(1,e,r),a=[UL(e,t,r)],c=[i];if(o.length%2!=0)throw new Q(j.INVALID_ARGUMENT,`Function ${e}() needs to be called with an even number of arguments that alternate between field names and values.`);for(let f=0;f<o.length;f+=2)a.push(UL(e,o[f])),c.push(o[f+1]);let l=[],u=nr.empty();for(let f=a.length-1;f>=0;--f)if(!pz(l,a[f])){let g=a[f],p=c[f];p=Ge(p);let _=s.gc(g);if(p instanceof Ry)l.push(g);else{let T=Ap(p,_);T!=null&&(l.push(g),u.set(g,T))}}let d=new Yr(l);return new Dy(u,d,s.fieldTransforms)}function fz(n,e,r,t=!1){return Ap(r,n.Dc(t?4:3,e))}function Ap(n,e){if(mz(n=Ge(n)))return OM("Unsupported field value:",e,n),gz(n,e);if(n instanceof gp)return(function(t,i){if(!dz(i.Ec))throw i.wc(`${t._methodName}() can only be used with update() and set()`);if(!i.path)throw i.wc(`${t._methodName}() is not currently supported inside arrays`);let o=t._toFieldTransform(i);o&&i.fieldTransforms.push(o)})(n,e),null;if(n===void 0&&e.ignoreUndefinedProperties)return null;if(e.path&&e.fieldMask.push(e.path),n instanceof Array){if(e.settings.mc&&e.Ec!==4)throw e.wc("Nested arrays are not supported");return(function(t,i){let o=[],s=0;for(let a of t){let c=Ap(a,i.yc(s));c==null&&(c={nullValue:"NULL_VALUE"}),o.push(c),s++}return{arrayValue:{values:o}}})(n,e)}return(function(t,i){if((t=Ge(t))===null)return{nullValue:"NULL_VALUE"};if(typeof t=="number")return Bie(i.serializer,t);if(typeof t=="boolean")return{booleanValue:t};if(typeof t=="string")return{stringValue:t};if(t instanceof Date){let o=Pt.fromDate(t);return{timestampValue:Nh(i.serializer,o)}}if(t instanceof Pt){let o=new Pt(t.seconds,1e3*Math.floor(t.nanoseconds/1e3));return{timestampValue:Nh(i.serializer,o)}}if(t instanceof Va)return{geoPointValue:{latitude:t.latitude,longitude:t.longitude}};if(t instanceof Os)return{bytesValue:EW(i.serializer,t._byteString)};if(t instanceof vn){let o=i.databaseId,s=t.firestore._databaseId;if(!s.isEqual(o))throw i.wc(`Document reference is for database ${s.projectId}/${s.database} but should be for database ${o.projectId}/${o.database}`);return{referenceValue:uM(t.firestore._databaseId||i.databaseId,t._key.path)}}if(t instanceof Ba)return(function(s,a){return{mapValue:{fields:{[iM]:{stringValue:oM},[Sh]:{arrayValue:{values:s.toArray().map(l=>{if(typeof l!="number")throw a.wc("VectorValues must only contain numeric values.");return lM(a.serializer,l)})}}}}}})(t,i);throw i.wc(`Unsupported field value: ${Oy(t)}`)})(n,e)}function gz(n,e){let r={};return BH(n)?e.path&&e.path.length>0&&e.fieldMask.push(e.path):Ja(n,(t,i)=>{let o=Ap(i,e.Vc(t));o!=null&&(r[t]=o)}),{mapValue:{fields:r}}}function mz(n){return!(typeof n!="object"||n===null||n instanceof Array||n instanceof Date||n instanceof Pt||n instanceof Va||n instanceof Os||n instanceof vn||n instanceof gp||n instanceof Ba)}function OM(n,e,r){if(!mz(r)||!AH(r)){let t=Oy(r);throw t==="an object"?e.wc(n+" a custom object"):e.wc(n+" "+t)}}function UL(n,e,r){if((e=Ge(e))instanceof xh)return e._internalPath;if(typeof e=="string")return wM(n,e);throw Cy("Field path arguments must be of type string or ",n,!1,void 0,r)}var nse=new RegExp("[~\\*/\\[\\]]");function wM(n,e,r){if(e.search(nse)>=0)throw Cy(`Invalid field path (${e}). Paths must not contain '~', '*', '/', '[', or ']'`,n,!1,void 0,r);try{return new xh(...e.split("."))._internalPath}catch{throw Cy(`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`,n,!1,void 0,r)}}function Cy(n,e,r,t,i){let o=t&&!t.isEmpty(),s=i!==void 0,a=`Function ${e}() called with invalid data`;r&&(a+=" (via `toFirestore()`)"),a+=". ";let c="";return(o||s)&&(c+=" (found",o&&(c+=` in field ${t}`),s&&(c+=` in document ${i}`),c+=")"),new Q(j.INVALID_ARGUMENT,a+n+c)}function pz(n,e){return n.some(r=>r.isEqual(e))}var eu=class{constructor(e,r,t,i,o){this._firestore=e,this._userDataWriter=r,this._key=t,this._document=i,this._converter=o}get id(){return this._key.path.lastSegment()}get ref(){return new vn(this._firestore,this._converter,this._key)}exists(){return this._document!==null}data(){if(this._document){if(this._converter){let e=new VL(this._firestore,this._userDataWriter,this._key,this._document,null);return this._converter.fromFirestore(e)}return this._userDataWriter.convertValue(this._document.data.value)}}get(e){if(this._document){let r=this._document.data.field(jy("DocumentSnapshot.get",e));if(r!==null)return this._userDataWriter.convertValue(r)}}},VL=class extends eu{data(){return super.data()}};function jy(n,e){return typeof e=="string"?wM(n,e):e instanceof xh?e._internalPath:e._delegate._internalPath}function Ez(n){if(n.limitType==="L"&&n.explicitOrderBy.length===0)throw new Q(j.UNIMPLEMENTED,"limitToLast() queries require specifying at least one orderBy() clause")}var mp=class{},Fh=class extends mp{};function _z(n,e,...r){let t=[];e instanceof mp&&t.push(e),t=t.concat(r),(function(o){let s=o.filter(c=>c instanceof kh).length,a=o.filter(c=>c instanceof pp).length;if(s>1||s>0&&a>0)throw new Q(j.INVALID_ARGUMENT,"InvalidQuery. When using composite filters, you cannot use more than one filter at the top level. Consider nesting the multiple filters within an `and(...)` statement. For example: change `query(query, where(...), or(...))` to `query(query, and(where(...), or(...)))`.")})(t);for(let i of t)n=i._apply(n);return n}var pp=class n extends Fh{constructor(e,r,t){super(),this._field=e,this._op=r,this._value=t,this.type="where"}static _create(e,r,t){return new n(e,r,t)}_apply(e){let r=this._parse(e);return Dz(e._query,r),new Qi(e.firestore,e.converter,pb(e._query,r))}_parse(e){let r=$y(e.firestore);return(function(o,s,a,c,l,u,d){let f;if(l.isKeyField()){if(u==="array-contains"||u==="array-contains-any")throw new Q(j.INVALID_ARGUMENT,`Invalid Query. You can't perform '${u}' queries on documentId().`);if(u==="in"||u==="not-in"){IH(d,u);let p=[];for(let _ of d)p.push(TH(c,o,_));f={arrayValue:{values:p}}}else f=TH(c,o,d)}else u!=="in"&&u!=="not-in"&&u!=="array-contains-any"||IH(d,u),f=fz(a,s,d,u==="in"||u==="not-in");return $e.create(l,u,f)})(e._query,"where",r,e.firestore._databaseId,this._field,this._op,this._value)}};function Tz(n,e,r){let t=e,i=jy("where",n);return pp._create(i,t,r)}var kh=class n extends mp{constructor(e,r){super(),this.type=e,this._queryConstraints=r}static _create(e,r){return new n(e,r)}_parse(e){let r=this._queryConstraints.map(t=>t._parse(e)).filter(t=>t.getFilters().length>0);return r.length===1?r[0]:nt.create(r,this._getOperator())}_apply(e){let r=this._parse(e);return r.getFilters().length===0?e:((function(i,o){let s=i,a=o.getFlattenedFilters();for(let c of a)Dz(s,c),s=pb(s,c)})(e._query,r),new Qi(e.firestore,e.converter,pb(e._query,r)))}_getQueryConstraints(){return this._queryConstraints}_getOperator(){return this.type==="and"?"and":"or"}};function Iz(...n){return n.forEach(e=>Rz("or",e)),kh._create("or",n)}function vz(...n){return n.forEach(e=>Rz("and",e)),kh._create("and",n)}var BL=class n extends Fh{constructor(e,r){super(),this._field=e,this._direction=r,this.type="orderBy"}static _create(e,r){return new n(e,r)}_apply(e){let r=(function(i,o,s){if(i.startAt!==null)throw new Q(j.INVALID_ARGUMENT,"Invalid query. You must not call startAt() or startAfter() before calling orderBy().");if(i.endAt!==null)throw new Q(j.INVALID_ARGUMENT,"Invalid query. You must not call endAt() or endBefore() before calling orderBy().");return new Wl(o,s)})(e._query,this._field,this._direction);return new Qi(e.firestore,e.converter,(function(i,o){let s=i.explicitOrderBy.concat([o]);return new Wo(i.path,i.collectionGroup,s,i.filters.slice(),i.limit,i.limitType,i.startAt,i.endAt)})(e._query,r))}};function yz(n,e="asc"){let r=e,t=jy("orderBy",n);return BL._create(t,r)}var GL=class n extends Fh{constructor(e,r,t){super(),this.type=e,this._limit=r,this._limitType=t}static _create(e,r,t){return new n(e,r,t)}_apply(e){return new Qi(e.firestore,e.converter,qv(e._query,this._limit,this._limitType))}};function Sz(n){return nie("limit",n),GL._create("limit",n,"F")}var $L=class n extends Fh{constructor(e,r,t){super(),this.type=e,this._docOrFields=r,this._inclusive=t}static _create(e,r,t){return new n(e,r,t)}_apply(e){let r=rse(e,this.type,this._docOrFields,this._inclusive);return new Qi(e.firestore,e.converter,(function(i,o){return new Wo(i.path,i.collectionGroup,i.explicitOrderBy.slice(),i.filters.slice(),i.limit,i.limitType,o,i.endAt)})(e._query,r))}};function Az(...n){return $L._create("startAfter",n,!1)}function rse(n,e,r,t){if(r[0]=Ge(r[0]),r[0]instanceof eu)return(function(o,s,a,c,l){if(!c)throw new Q(j.NOT_FOUND,`Can't use a DocumentSnapshot that doesn't exist for ${a}().`);let u=[];for(let d of dh(o))if(d.field.isKeyField())u.push(Hl(s,c.key));else{let f=c.data.field(d.field);if(My(f))throw new Q(j.INVALID_ARGUMENT,'Invalid query. You are trying to start or end a query using a document for which the field "'+d.field+'" is an uncommitted server timestamp. (Since the value of this field is unknown, you cannot start/end a query with it.)');if(f===null){let g=d.field.canonicalString();throw new Q(j.INVALID_ARGUMENT,`Invalid query. You are trying to start or end a query using a document for which the field '${g}' (used as the orderBy) does not exist.`)}u.push(f)}return new Ho(u,l)})(n._query,n.firestore._databaseId,e,r[0]._document,t);{let i=$y(n.firestore);return(function(s,a,c,l,u,d){let f=s.explicitOrderBy;if(u.length>f.length)throw new Q(j.INVALID_ARGUMENT,`Too many arguments provided to ${l}(). The number of arguments must be less than or equal to the number of orderBy() clauses`);let g=[];for(let p=0;p<u.length;p++){let _=u[p];if(f[p].field.isKeyField()){if(typeof _!="string")throw new Q(j.INVALID_ARGUMENT,`Invalid query. Expected a string for document ID in ${l}(), but got a ${typeof _}`);if(!aM(s)&&_.indexOf("/")!==-1)throw new Q(j.INVALID_ARGUMENT,`Invalid query. When querying a collection and ordering by documentId(), the value passed to ${l}() must be a plain document ID, but '${_}' contains a slash.`);let T=s.path.child(We.fromString(_));if(!ie.isDocumentKey(T))throw new Q(j.INVALID_ARGUMENT,`Invalid query. When querying a collection group and ordering by documentId(), the value passed to ${l}() must result in a valid document path, but '${T}' is not because it contains an odd number of segments.`);let D=new ie(T);g.push(Hl(a,D))}else{let T=fz(c,l,_);g.push(T)}}return new Ho(g,d)})(n._query,n.firestore._databaseId,i,e,r,t)}}function TH(n,e,r){if(typeof(r=Ge(r))=="string"){if(r==="")throw new Q(j.INVALID_ARGUMENT,"Invalid query. When querying with documentId(), you must provide a valid document ID, but it was an empty string.");if(!aM(e)&&r.indexOf("/")!==-1)throw new Q(j.INVALID_ARGUMENT,`Invalid query. When querying a collection by documentId(), you must provide a plain document ID, but '${r}' contains a '/' character.`);let t=e.path.child(We.fromString(r));if(!ie.isDocumentKey(t))throw new Q(j.INVALID_ARGUMENT,`Invalid query. When querying a collection group by documentId(), the value provided must result in a valid document path, but '${t}' is not because it has an odd number of segments (${t.length}).`);return Hl(n,new ie(t))}if(r instanceof vn)return Hl(n,r._key);throw new Q(j.INVALID_ARGUMENT,`Invalid query. When querying with documentId(), you must provide a valid string or a DocumentReference, but it was: ${Oy(r)}.`)}function IH(n,e){if(!Array.isArray(n)||n.length===0)throw new Q(j.INVALID_ARGUMENT,`Invalid Query. A non-empty array is required for '${e.toString()}' filters.`)}function Dz(n,e){let r=(function(i,o){for(let s of i)for(let a of s.getFlattenedFilters())if(o.indexOf(a.op)>=0)return a.op;return null})(n.filters,(function(i){switch(i){case"!=":return["!=","not-in"];case"array-contains-any":case"in":return["not-in"];case"not-in":return["array-contains-any","in","not-in","!="];default:return[]}})(e.op));if(r!==null)throw r===e.op?new Q(j.INVALID_ARGUMENT,`Invalid query. You cannot use more than one '${e.op.toString()}' filter.`):new Q(j.INVALID_ARGUMENT,`Invalid query. You cannot use '${e.op.toString()}' filters with '${r.toString()}' filters.`)}function Rz(n,e){if(!(e instanceof pp||e instanceof kh))throw new Q(j.INVALID_ARGUMENT,`Function ${n}() requires AppliableConstraints created with a call to 'where(...)', 'or(...)', or 'and(...)'.`)}var Ny=class{convertValue(e,r="none"){switch(ja(e)){case 0:return null;case 1:return e.booleanValue;case 2:return Mt(e.integerValue||e.doubleValue);case 3:return this.convertTimestamp(e.timestampValue);case 4:return this.convertServerTimestamp(e,r);case 5:return e.stringValue;case 6:return this.convertBytes(Ls(e.bytesValue));case 7:return this.convertReference(e.referenceValue);case 8:return this.convertGeoPoint(e.geoPointValue);case 9:return this.convertArray(e.arrayValue,r);case 11:return this.convertObject(e.mapValue,r);case 10:return this.convertVectorValue(e.mapValue);default:throw ae(62114,{value:e})}}convertObject(e,r){return this.convertObjectMap(e.fields,r)}convertObjectMap(e,r="none"){let t={};return Ja(e,(i,o)=>{t[i]=this.convertValue(o,r)}),t}convertVectorValue(e){var r,t,i;let o=(i=(t=(r=e.fields)===null||r===void 0?void 0:r[Sh].arrayValue)===null||t===void 0?void 0:t.values)===null||i===void 0?void 0:i.map(s=>Mt(s.doubleValue));return new Ba(o)}convertGeoPoint(e){return new Va(Mt(e.latitude),Mt(e.longitude))}convertArray(e,r){return(e.values||[]).map(t=>this.convertValue(t,r))}convertServerTimestamp(e,r){switch(r){case"previous":let t=Py(e);return t==null?null:this.convertValue(t,r);case"estimate":return this.convertTimestamp(Qm(e));default:return null}}convertTimestamp(e){let r=bs(e);return new Pt(r.seconds,r.nanos)}convertDocumentKey(e,r){let t=We.fromString(e);he(RW(t),9688,{name:e});let i=new yh(t.get(1),t.get(3)),o=new ie(t.popFirst(5));return i.isEqual(r)||Xt(`Document ${o} contains a document reference within a different database (${i.projectId}/${i.database}) which is not supported. It will be treated as a reference in the current database (${r.projectId}/${r.database}) instead.`),o}};function Cz(n,e,r){let t;return t=n?r&&(r.merge||r.mergeFields)?n.toFirestore(e,r):n.toFirestore(e):e,t}var jL=class extends Ny{constructor(e){super(),this.firestore=e}convertBytes(e){return new Os(e)}convertReference(e){let r=this.convertDocumentKey(e,this.firestore._databaseId);return new vn(this.firestore,null,r)}};function ise(){return new ML("count")}var ka=class{constructor(e,r){this.hasPendingWrites=e,this.fromCache=r}isEqual(e){return this.hasPendingWrites===e.hasPendingWrites&&this.fromCache===e.fromCache}},Ga=class n extends eu{constructor(e,r,t,i,o,s){super(e,r,t,i,s),this._firestore=e,this._firestoreImpl=e,this.metadata=o}exists(){return super.exists()}data(e={}){if(this._document){if(this._converter){let r=new fh(this._firestore,this._userDataWriter,this._key,this._document,this.metadata,null);return this._converter.fromFirestore(r,e)}return this._userDataWriter.convertValue(this._document.data.value,e.serverTimestamps)}}get(e,r={}){if(this._document){let t=this._document.data.field(jy("DocumentSnapshot.get",e));if(t!==null)return this._userDataWriter.convertValue(t,r.serverTimestamps)}}toJSON(){if(this.metadata.hasPendingWrites)throw new Q(j.FAILED_PRECONDITION,"DocumentSnapshot.toJSON() attempted to serialize a document with pending writes. Await waitForPendingWrites() before invoking toJSON().");let e=this._document,r={};return r.type=n._jsonSchemaVersion,r.bundle="",r.bundleSource="DocumentSnapshot",r.bundleName=this._key.toString(),!e||!e.isValidDocument()||!e.isFoundDocument()?r:(this._userDataWriter.convertObjectMap(e.data.value.mapValue.fields,"previous"),r.bundle=(this._firestore,this.ref.path,"NOT SUPPORTED"),r)}};Ga._jsonSchemaVersion="firestore/documentSnapshot/1.0",Ga._jsonSchema={type:ln("string",Ga._jsonSchemaVersion),bundleSource:ln("string","DocumentSnapshot"),bundleName:ln("string"),bundle:ln("string")};var fh=class extends Ga{data(e={}){return super.data(e)}},jl=class n{constructor(e,r,t,i){this._firestore=e,this._userDataWriter=r,this._snapshot=i,this.metadata=new ka(i.hasPendingWrites,i.fromCache),this.query=t}get docs(){let e=[];return this.forEach(r=>e.push(r)),e}get size(){return this._snapshot.docs.size}get empty(){return this.size===0}forEach(e,r){this._snapshot.docs.forEach(t=>{e.call(r,new fh(this._firestore,this._userDataWriter,t.key,t,new ka(this._snapshot.mutatedKeys.has(t.key),this._snapshot.fromCache),this.query.converter))})}docChanges(e={}){let r=!!e.includeMetadataChanges;if(r&&this._snapshot.excludesMetadataChanges)throw new Q(j.INVALID_ARGUMENT,"To include metadata changes with your document changes, you must also pass { includeMetadataChanges:true } to onSnapshot().");return this._cachedChanges&&this._cachedChangesIncludeMetadataChanges===r||(this._cachedChanges=(function(i,o){if(i._snapshot.oldDocs.isEmpty()){let s=0;return i._snapshot.docChanges.map(a=>{let c=new fh(i._firestore,i._userDataWriter,a.doc.key,a.doc,new ka(i._snapshot.mutatedKeys.has(a.doc.key),i._snapshot.fromCache),i.query.converter);return a.doc,{type:"added",doc:c,oldIndex:-1,newIndex:s++}})}{let s=i._snapshot.oldDocs;return i._snapshot.docChanges.filter(a=>o||a.type!==3).map(a=>{let c=new fh(i._firestore,i._userDataWriter,a.doc.key,a.doc,new ka(i._snapshot.mutatedKeys.has(a.doc.key),i._snapshot.fromCache),i.query.converter),l=-1,u=-1;return a.type!==0&&(l=s.indexOf(a.doc.key),s=s.delete(a.doc.key)),a.type!==1&&(s=s.add(a.doc),u=s.indexOf(a.doc.key)),{type:ose(a.type),doc:c,oldIndex:l,newIndex:u}})}})(this,r),this._cachedChangesIncludeMetadataChanges=r),this._cachedChanges}toJSON(){if(this.metadata.hasPendingWrites)throw new Q(j.FAILED_PRECONDITION,"QuerySnapshot.toJSON() attempted to serialize a document with pending writes. Await waitForPendingWrites() before invoking toJSON().");let e={};e.type=n._jsonSchemaVersion,e.bundleSource="QuerySnapshot",e.bundleName=jm.newId(),this._firestore._databaseId.database,this._firestore._databaseId.projectId;let r=[],t=[],i=[];return this.docs.forEach(o=>{o._document!==null&&(r.push(o._document),t.push(this._userDataWriter.convertObjectMap(o._document.data.value.mapValue.fields,"previous")),i.push(o.ref.path))}),e.bundle=(this._firestore,this.query._query,e.bundleName,"NOT SUPPORTED"),e}};function ose(n){switch(n){case 0:return"added";case 2:case 3:return"modified";case 1:return"removed";default:return ae(61501,{type:n})}}function Nz(n){n=wr(n,vn);let e=wr(n.firestore,Xi);return Yoe(jh(e),n._key).then(r=>Pz(e,n,r))}jl._jsonSchemaVersion="firestore/querySnapshot/1.0",jl._jsonSchema={type:ln("string",jl._jsonSchemaVersion),bundleSource:ln("string","QuerySnapshot"),bundleName:ln("string"),bundle:ln("string")};var tu=class extends Ny{constructor(e){super(),this.firestore=e}convertBytes(e){return new Os(e)}convertReference(e){let r=this.convertDocumentKey(e,this.firestore._databaseId);return new vn(this.firestore,null,r)}};function Oz(n){n=wr(n,Qi);let e=wr(n.firestore,Xi),r=jh(e),t=new tu(e);return Ez(n._query),Qoe(r,n._query).then(i=>new jl(e,t,n,i))}function wz(n,e,r){n=wr(n,vn);let t=wr(n.firestore,Xi),i=Cz(n.converter,e,r);return Mz(t,[hz($y(t),"setDoc",n._key,i,n.converter!==null,r).toMutation(n._key,Gn.none())])}function bz(n){return Mz(wr(n.firestore,Xi),[new Yl(n._key,Gn.none())])}function Lz(n,...e){var r,t,i;n=Ge(n);let o={includeMetadataChanges:!1,source:"default"},s=0;typeof e[s]!="object"||_H(e[s])||(o=e[s++]);let a={includeMetadataChanges:o.includeMetadataChanges,source:o.source};if(_H(e[s])){let d=e[s];e[s]=(r=d.next)===null||r===void 0?void 0:r.bind(d),e[s+1]=(t=d.error)===null||t===void 0?void 0:t.bind(d),e[s+2]=(i=d.complete)===null||i===void 0?void 0:i.bind(d)}let c,l,u;if(n instanceof vn)l=wr(n.firestore,Xi),u=vp(n._key.path),c={next:d=>{e[s]&&e[s](Pz(l,n,d))},error:e[s+1],complete:e[s+2]};else{let d=wr(n,Qi);l=wr(d.firestore,Xi),u=d._query;let f=new tu(l);c={next:g=>{e[s]&&e[s](new jl(l,f,d,g))},error:e[s+1],complete:e[s+2]},Ez(n._query)}return(function(f,g,p,_){let T=new fp(_),D=new hp(g,T,p);return f.asyncQueue.enqueueAndForget(()=>I(null,null,function*(){return _M(yield yy(f),D)})),()=>{T.Ou(),f.asyncQueue.enqueueAndForget(()=>I(null,null,function*(){return TM(yield yy(f),D)}))}})(jh(l),u,a,c)}function Mz(n,e){return(function(t,i){let o=new Or;return t.asyncQueue.enqueueAndForget(()=>I(null,null,function*(){return Moe(yield Koe(t),i,o)})),o.promise})(jh(n),e)}function Pz(n,e,r){let t=r.docs.get(e._key),i=new tu(n);return new Ga(n,i,e._key,t,new ka(r.hasPendingWrites,r.fromCache),e.converter)}function xz(n){return Fz(n,{count:ise()})}function Fz(n,e){let r=wr(n.firestore,Xi),t=jh(r),i=Oie(e,(o,s)=>new Ib(s,o.aggregateType,o._internalFieldPath));return Xoe(t,n._query,i).then(o=>(function(a,c,l){let u=new tu(a);return new PL(c,u,l)})(r,n,o))}var HL=class{constructor(e){let r;this.kind="persistent",e?.tabManager?(e.tabManager._initialize(e),r=e.tabManager):(r=sse(void 0),r._initialize(e)),this._onlineComponentProvider=r._onlineComponentProvider,this._offlineComponentProvider=r._offlineComponentProvider}toJSON(){return{kind:this.kind}}};function bM(n){return new HL(n)}var WL=class{constructor(e){this.forceOwnership=e,this.kind="persistentSingleTab"}toJSON(){return{kind:this.kind}}_initialize(e){this._onlineComponentProvider=CM.provider,this._offlineComponentProvider={build:r=>new vy(r,e?.cacheSizeBytes,this.forceOwnership)}}},zL=class{constructor(){this.kind="PersistentMultipleTab"}toJSON(){return{kind:this.kind}}_initialize(e){this._onlineComponentProvider=CM.provider,this._offlineComponentProvider={build:r=>new OL(r,e?.cacheSizeBytes)}}};function sse(n){return new WL(n?.forceOwnership)}function LM(){return new zL}var ase={maxAttempts:5};function Pm(n,e){if((n=Ge(n)).firestore!==e)throw new Q(j.INVALID_ARGUMENT,"Provided document reference is from a different Firestore instance.");return n}var qL=class{constructor(e,r){this._firestore=e,this._transaction=r,this._dataReader=$y(e)}get(e){let r=Pm(e,this._firestore),t=new jL(this._firestore);return this._transaction.lookup([r._key]).then(i=>{if(!i||i.length!==1)return ae(24041);let o=i[0];if(o.isFoundDocument())return new eu(this._firestore,t,o.key,o,r.converter);if(o.isNoDocument())return new eu(this._firestore,t,r._key,null,r.converter);throw ae(18433,{doc:o})})}set(e,r,t){let i=Pm(e,this._firestore),o=Cz(i.converter,r,t),s=hz(this._dataReader,"Transaction.set",i._key,o,i.converter!==null,t);return this._transaction.set(i._key,s),this}update(e,r,t,...i){let o=Pm(e,this._firestore),s;return s=typeof(r=Ge(r))=="string"||r instanceof xh?tse(this._dataReader,"Transaction.update",o._key,r,t,i):ese(this._dataReader,"Transaction.update",o._key,r),this._transaction.update(o._key,s),this}delete(e){let r=Pm(e,this._firestore);return this._transaction.delete(r._key),this}};var KL=class extends qL{constructor(e,r){super(e,r),this._firestore=e}get(e){let r=Pm(e,this._firestore),t=new tu(this._firestore);return super.get(e).then(i=>new Ga(this._firestore,t,r._key,i._document,new ka(!1,!1),r.converter))}};function kz(n,e,r){n=wr(n,Xi);let t=Object.assign(Object.assign({},ase),r);return(function(o){if(o.maxAttempts<1)throw new Q(j.INVALID_ARGUMENT,"Max attempts must be at least 1")})(t),(function(o,s,a){let c=new Or;return o.asyncQueue.enqueueAndForget(()=>I(null,null,function*(){let l=yield iz(o);new bL(o.asyncQueue,l,a,s,c).zu()})),c.promise})(jh(n),i=>e(new KL(n,i)),t)}(function(e,r=!0){(function(i){Uh=i})(pa),ur(new _n("firestore",(t,{instanceIdentifier:i,options:o})=>{let s=t.getProvider("app").getImmediate(),a=new Xi(new Hw(t.getProvider("auth-internal")),new qw(s,t.getProvider("app-check-internal")),(function(l,u){if(!Object.prototype.hasOwnProperty.apply(l.options,["projectId"]))throw new Q(j.INVALID_ARGUMENT,'"projectId" not provided in firebase.initializeApp.');return new yh(l.options.projectId,u)})(s,i),s);return o=Object.assign({useFetchStreams:r},o),a._setSettings(o),a},"PUBLIC").setMultipleInstances(!0)),Qe(oj,sj,e),Qe(oj,sj,"esm2017")})();var MM=pe(vz,!0,2);var Dp=pe(cz,!0,2),PM=pe(lz,!0,2);var Hy=pe(bz,!0,2);var Hh=pe(uz,!0,2);var Uz=pe(xz,!0),Vz=pe(Nz,!0);var Bz=pe(Oz,!0);var Lxe=pe(Sz,!0,2);var xM=pe(Lz,!0);var Mxe=pe(Iz,!0,2),Pxe=pe(yz,!0,2),FM=pe(_z,!0,2);var kM=pe(kz,!0),UM=pe(wz,!0,2);var xxe=pe(Az,!0,2);var Ji=pe(Tz,!0,2);var Wy=(()=>{let e=class e{constructor(t,i,o){this.authService=t,this.configService=i,this.loggingService=o,this.db$=new Y(null);try{this.authService.getFirebaseConfig$().subscribe(s=>{if(s){let a=this.configService.getProxyConfig(),c=s.firebaseOptions.databaseURL;a?.v1DbHost&&c&&(c=OV(c,a.v1DbHost),a?.forceLongPolling&&hw());let l=dv(void 0,c);a?.v1DbHost&&c&&this.lockDatabaseHost(l),this.db$.next(l)}},s=>{this.loggingService.catch("Error in DatabaseService constructor: ",s)})}catch(s){this.loggingService.catch("Error in DatabaseService constructor:",s)}}getDb(){return this.db$.asObservable()}getDbValue(){return this.db$.getValue()}lockDatabaseHost(t){try{let o=t?._repo?.repoInfo_;if(o){let s=o.host;Object.defineProperty(o,"host",{get:()=>s,set:()=>{},configurable:!0}),o.internalHost=s}}catch(i){this.loggingService.catch("Error in DatabaseService lockDatabaseHost: ",i)}}};e.\u0275fac=function(i){return new(i||e)(w(Cr),w(Rr),w(_e))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let n=e;return n})();var zo=(()=>{let e=class e{constructor(t,i,o){this.coreActionsService=t,this.loggingService=i,this.analyticsService=o,this.resolveTimeout=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 Y(null),this.commentAnnotationById$=new Y({}),this.fieldsToRemove=[],this.additionalFields=[],this.additionalSaveEvents=[],this.getCommentAnnotationById=s=>{try{return this.commentAnnotationDataProviderAvailable()?this.commentAnnotationById$.value?.[s]:void 0}catch(a){this.loggingService.catch("Error in CommentAnnotationsResolverService getCommentAnnotationById:",a);return}};try{this.loggingService.log("CommentAnnotationsResolverService initialized"),this.commentAnnotationDataProvider$.subscribe(s=>{s&&(s.config?.resolveTimeout&&(this.resolveTimeout=s.config.resolveTimeout),s.config?.saveRetryConfig&&(this.retrySaveConfig=s.config.saveRetryConfig),s.config?.deleteRetryConfig&&(this.retryDeleteConfig=s.config.deleteRetryConfig),s.config?.getRetryConfig&&(this.retryGetConfig=s.config.getRetryConfig),s.config?.fieldsToRemove&&(this.fieldsToRemove=s.config.fieldsToRemove),s.config?.additionalFields&&(this.additionalFields=s.config.additionalFields||[]),this.additionalSaveEvents=(s.config?.additionalSaveEvents||[]).map(a=>a?.event).filter(a=>!!a))})}catch(s){this.loggingService.catch("Error in CommentAnnotationsResolverService constructor:",s)}}getProvider(){try{let t=this.commentAnnotationDataProvider$.getValue();return t||void 0}catch(t){this.loggingService.catch("Error in CommentAnnotationsResolverService getProvider:",t);return}}ngOnDestroy(){try{this.commentAnnotationById$.next({})}catch(t){this.loggingService.catch("Error in CommentAnnotationsResolverService ngOnDestroy:",t)}}resolveCommentAnnotations(s){return I(this,arguments,function*({request:t,uniqueId:i,moduleName:o}){try{if(this.loggingService.log("%c[WB] Calling CommentAnnotationsResolverService FUNCTION: resolveCommentAnnotations","color: green;"),!this.commentAnnotationDataProviderAvailable())return{};let a,c=!1,l=!1,u=()=>{a&&(clearTimeout(a),a=void 0,l=!0)};return new Promise((d,f)=>{a=setTimeout(()=>{if(!l){c=!0,u();let b=i||J();this.coreActionsService.triggerAction($.COMMENT_RESOLVER,{event:L.Events.Resolver.COMMENT_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:b,methodName:Et.RESOLVE_COMMENT_ANNOTATIONS,moduleName:o,source:"internal",payload:{error:new Error("Comment annotation resolution timeout"),request:t}}),f(new Error("Comment annotation resolution timeout"))}},this.commentAnnotationDataProvider$.value?.config?.resolveTimeout||this.resolveTimeout);let g=this.getProvider();if(!g)return u(),d({});let p={},_=[...new Set(t.commentAnnotationIds||[])],T=le(x({},t),{commentAnnotationIds:_});I(this,null,function*(){try{if(_.length>0||t.documentIds?.length||t.folderId){let b=i||J();this.coreActionsService.triggerAction($.COMMENT_RESOLVER,{event:L.Events.Resolver.COMMENT_RESOLUTION_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:b,methodName:Et.RESOLVE_COMMENT_ANNOTATIONS,moduleName:o,source:"internal",payload:{request:T}});let G=kt(()=>g?.config?.getConfig?.url?Ht(g.config.getConfig.url,g.config.getConfig.headers,T,!0,g.config.getConfig.credentials):g?.get?.(T)||Promise.resolve(void 0),"getCommentAnnotations",this.retryGetConfig).then(M=>c?{}:(u(),M&&M.statusCode!==200?(this.coreActionsService.triggerAction($.COMMENT_RESOLVER,{event:L.Events.Resolver.COMMENT_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:b,methodName:Et.RESOLVE_COMMENT_ANNOTATIONS,moduleName:o,source:"internal",payload:{result:M,request:T}}),this.loggingService.catch(M?.message??"Error in CommentAnnotationsResolverService resolveCommentAnnotations:"),{}):M?.data)).catch(M=>{throw u(),M});try{p=(yield G)||{},this.analyticsService.trackEvent(L.Events.Resolver.COMMENT_RESOLVER_GET,{sourceMethod:"resolveCommentAnnotations",source:"sdk",commentAnnotationIds:_});let M={};Object.entries(p).forEach(([U,k])=>{let S=this.commentAnnotationById$.value?.[U];S?S&&JSON.stringify(S)!==JSON.stringify(k)&&(M[U]=k):M[U]=k}),Object.keys(M).length>0&&this.commentAnnotationById$.next(x(x({},this.commentAnnotationById$.getValue()),M)),this.coreActionsService.triggerAction($.COMMENT_RESOLVER,{event:L.Events.Resolver.COMMENT_RESOLUTION_RESULT,timestamp:new Date().getTime(),uniqueId:b,methodName:Et.RESOLVE_COMMENT_ANNOTATIONS,moduleName:o,source:"internal",payload:{result:M,request:T}}),d(M)}catch(M){let U=i||J();this.coreActionsService.triggerAction($.COMMENT_RESOLVER,{event:L.Events.Resolver.COMMENT_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:U,methodName:Et.RESOLVE_COMMENT_ANNOTATIONS,moduleName:o,source:"internal",payload:{error:M,request:T}}),c||f(M),d(p)}}else u(),d({})}catch(b){u();let G=i||J();this.coreActionsService.triggerAction($.COMMENT_RESOLVER,{event:L.Events.Resolver.COMMENT_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:G,methodName:Et.RESOLVE_COMMENT_ANNOTATIONS,moduleName:o,source:"internal",payload:{error:b,request:T}}),f(b)}})})}catch(a){this.loggingService.catch("Error in CommentAnnotationsResolverService resolveCommentAnnotations:",a);let c=i||J();return this.coreActionsService.triggerAction($.COMMENT_RESOLVER,{event:L.Events.Resolver.COMMENT_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:c,methodName:Et.RESOLVE_COMMENT_ANNOTATIONS,moduleName:o,source:"internal",payload:{error:a,request:t}}),{}}})}saveCommentAnnotation(t,i){return I(this,null,function*(){try{this.loggingService.log("%c[WB] Calling CommentAnnotationsResolverService FUNCTION: saveCommentAnnotation","color: green;");let o=this.getProvider();if(!this.commentAnnotationDataProviderAvailable())throw new Error("Comment annotation save data provider not available");let s=i||J();this.coreActionsService.triggerAction($.COMMENT_RESOLVER,{event:L.Events.Resolver.COMMENT_SAVE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:s,methodName:Et.SAVE_COMMENT_ANNOTATION,source:"internal",payload:{request:t}});let a=JSON.parse(JSON.stringify(this.commentAnnotationById$.getValue()));this.commentAnnotationById$._value=x(x({},a),t.commentAnnotation);let c=this.getTargetComment(t.commentAnnotation,t.commentId),l=yield kt(()=>{if(o?.config?.saveConfig?.url){let u={commentAnnotation:t.commentAnnotation,event:t.eventType,commentId:t.commentId,targetComment:c,metadata:Object.values(t.commentAnnotation??{})?.[0]?.metadata};return Ht(o.config.saveConfig.url,o.config.saveConfig.headers,u,!1,o.config.saveConfig.credentials)}return o?.save?.({commentAnnotation:t.commentAnnotation,event:t.eventType,commentId:t.commentId,targetComment:c,metadata:Object.values(t.commentAnnotation??{})?.[0]?.metadata})||Promise.resolve(void 0)},"saveCommentAnnotation",this.retrySaveConfig);return l&&l.statusCode!==200?(this.retrySaveConfig.revertOnFailure&&(this.commentAnnotationById$._value=a),this.loggingService.catch(l?.message??"Error in CommentAnnotationsResolverService saveCommentAnnotation:"),this.coreActionsService.triggerAction($.COMMENT_RESOLVER,{event:L.Events.Resolver.COMMENT_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:s,methodName:Et.SAVE_COMMENT_ANNOTATION,source:"internal",payload:{error:l,request:t}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(L.Events.Resolver.COMMENT_RESOLVER_SAVE,{sourceMethod:"saveCommentAnnotation",source:"sdk",commentAnnotationIds:Object.keys(t.commentAnnotation),eventType:t.eventType,commentId:t.commentId}),this.coreActionsService.triggerAction($.COMMENT_RESOLVER,{event:L.Events.Resolver.COMMENT_SAVE_RESULT,timestamp:new Date().getTime(),uniqueId:s,methodName:Et.SAVE_COMMENT_ANNOTATION,source:"internal",payload:{result:{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0},request:t}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0})}catch(o){this.loggingService.warn("Error in CommentAnnotationsResolverService saveCommentAnnotation:",o);let s=i||J();return this.coreActionsService.triggerAction($.COMMENT_RESOLVER,{event:L.Events.Resolver.COMMENT_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:s,methodName:Et.SAVE_COMMENT_ANNOTATION,source:"internal",payload:{error:o,request:t}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0}}})}getTargetComment(t,i){if(!(!i||!t))for(let o of Object.values(t)){let s=o?.comments?.[i];if(s)return s}}deleteCommentAnnotation(t,i,o){return I(this,null,function*(){try{this.loggingService.log("%c[WB] Calling CommentAnnotationsResolverService FUNCTION: deleteCommentAnnotation","color: green;");let s=this.getProvider();if(!this.commentAnnotationDataProviderAvailable())throw new Error("Comment annotation delete data provider not available");let a=this.commentAnnotationById$.getValue(),l=a?.[t]?.metadata??(i?Cn(i):void 0),u=l?x({apiKey:l.apiKey??null,documentId:l.documentId??null,organizationId:l.organizationId??null},l.folderId&&{folderId:l.folderId}):void 0,d=o||J();this.coreActionsService.triggerAction($.COMMENT_RESOLVER,{event:L.Events.Resolver.COMMENT_DELETE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:d,methodName:Et.DELETE_COMMENT_ANNOTATION,source:"internal",payload:{commentAnnotationId:t.toString(),metadata:u}});let f=x({},a);delete f?.[t],this.commentAnnotationById$._value=f;let g=yield kt(()=>{if(s?.config?.deleteConfig?.url){let p={commentAnnotationId:t.toString(),metadata:u,event:Qt.COMMENT_ANNOTATION_DELETE};return Ht(s.config.deleteConfig.url,s.config.deleteConfig.headers,p,!1,s.config.deleteConfig.credentials)}return s?.delete?.({commentAnnotationId:t.toString(),metadata:u,event:Qt.COMMENT_ANNOTATION_DELETE})||Promise.resolve(void 0)},"deleteCommentAnnotation",this.retryDeleteConfig);return g&&g.statusCode!==200?(this.retryDeleteConfig.revertOnFailure&&(this.commentAnnotationById$._value=a),this.loggingService.catch(g?.message??"Error in CommentAnnotationsResolverService deleteCommentAnnotation:"),this.coreActionsService.triggerAction($.COMMENT_RESOLVER,{event:L.Events.Resolver.COMMENT_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:d,methodName:Et.DELETE_COMMENT_ANNOTATION,source:"internal",payload:{error:g,commentAnnotationId:t.toString(),metadata:u}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(L.Events.Resolver.COMMENT_RESOLVER_DELETE,{sourceMethod:"deleteCommentAnnotation",source:"sdk",commentAnnotationId:t.toString()}),this.coreActionsService.triggerAction($.COMMENT_RESOLVER,{event:L.Events.Resolver.COMMENT_DELETE_RESULT,timestamp:new Date().getTime(),uniqueId:d,methodName:Et.DELETE_COMMENT_ANNOTATION,source:"internal",payload:{result:{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0},commentAnnotationId:t.toString(),metadata:u}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0})}catch(s){this.loggingService.warn("Error in CommentAnnotationsResolverService deleteCommentAnnotation:",s);let a=o||J(),c=i?Cn(i):void 0;return this.coreActionsService.triggerAction($.COMMENT_RESOLVER,{event:L.Events.Resolver.COMMENT_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:a,methodName:Et.DELETE_COMMENT_ANNOTATION,source:"internal",payload:{error:s,commentAnnotationId:t.toString(),metadata:c}}),{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()):ue(void 0)}catch(t){return this.loggingService.catch("Error in CommentAnnotationsResolverService getCommentAnnotationsById$:",t),ue(void 0)}}getAnnotationById(t){try{return this.commentAnnotationDataProviderAvailable()?this.commentAnnotationById$.getValue()?.[t]:void 0}catch(i){this.loggingService.catch("Error in CommentAnnotationsResolverService getAnnotationById:",i);return}}getFieldsToRemove(){try{return this.fieldsToRemove}catch(t){return this.loggingService.catch("Error in CommentAnnotationsResolverService getFieldsToRemove:",t),this.fieldsToRemove}}getAdditionalFields(){try{return this.additionalFields}catch(t){return this.loggingService.catch("Error in CommentAnnotationsResolverService getAdditionalFields:",t),this.additionalFields}}getAdditionalSaveEvents(){try{return this.additionalSaveEvents}catch(t){return this.loggingService.catch("Error in CommentAnnotationsResolverService getAdditionalSaveEvents:",t),this.additionalSaveEvents}}setCommentAnnotationDataProvider(t){try{if(t){this.loggingService.log("Setting comment annotation data provider");let i=t.config,o=[{method:"get",configKey:"getConfig"},{method:"save",configKey:"saveConfig"},{method:"delete",configKey:"deleteConfig"}],s=[];if(o.forEach(({method:a,configKey:c})=>{let l=i?.[c]?.url,u=a in t&&typeof t[a]=="function";!l&&!u&&s.push(a)}),s.length>0){let a=`DataProviders.comment is invalid. The following methods are missing or are not functions (and no corresponding config provided): ${s.join(", ")}.`;this.loggingService.catch(a);return}else this.commentAnnotationDataProvider$.next(t)}}catch(i){this.loggingService.catch("Error in CommentAnnotationsResolverService setCommentAnnotationDataProvider:",i)}}commentAnnotationDataProviderAvailable(){try{return!!this.commentAnnotationDataProvider$.getValue()}catch(t){return this.loggingService.catch("Error in CommentAnnotationsResolverService commentAnnotationDataProviderAvailable:",t),!1}}};e.\u0275fac=function(i){return new(i||e)(w(It),w(_e),w(Lt))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let n=e;return n})();var qo=(()=>{let e=class e{constructor(t,i,o){this.coreActionsService=t,this.loggingService=i,this.analyticsService=o,this.resolveTimeout=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 Y(null),this.reactionAnnotationById$=new Y({}),this.fieldsToRemove=[],this.getReactionAnnotationById=s=>{try{return this.reactionAnnotationDataProviderAvailable()?this.reactionAnnotationById$.value?.[s]:void 0}catch(a){this.loggingService.catch("Error in ReactionAnnotationsResolverService getReactionAnnotationById:",a);return}};try{this.loggingService.log("ReactionAnnotationsResolverService initialized"),this.reactionAnnotationDataProvider$.subscribe(s=>{s&&(s.config?.resolveTimeout&&(this.resolveTimeout=s.config.resolveTimeout),s.config?.saveRetryConfig&&(this.retrySaveConfig=s.config.saveRetryConfig),s.config?.deleteRetryConfig&&(this.retryDeleteConfig=s.config.deleteRetryConfig),s.config?.getRetryConfig&&(this.retryGetConfig=s.config.getRetryConfig),s.config?.fieldsToRemove&&(this.fieldsToRemove=s.config.fieldsToRemove||[]))})}catch(s){this.loggingService.catch("Error in ReactionAnnotationsResolverService constructor:",s)}}getProvider(){try{let t=this.reactionAnnotationDataProvider$.getValue();return t||void 0}catch(t){this.loggingService.catch("Error in ReactionAnnotationsResolverService getProvider:",t);return}}ngOnDestroy(){try{this.reactionAnnotationById$.next({})}catch(t){this.loggingService.catch("Error in ReactionAnnotationsResolverService ngOnDestroy:",t)}}getFieldsToRemove(){try{return this.fieldsToRemove}catch(t){return this.loggingService.catch("Error in ReactionAnnotationsResolverService getFieldsToRemove:",t),this.fieldsToRemove}}resolveReactionAnnotations(s){return I(this,arguments,function*({request:t,uniqueId:i,moduleName:o}){try{if(this.loggingService.log("%c[WB] Calling ReactionAnnotationsResolverService FUNCTION: resolveReactionAnnotations","color: green;"),!this.reactionAnnotationDataProviderAvailable())return{};let a,c=!1,l=!1,u=()=>{a&&(clearTimeout(a),a=void 0,l=!0)};return new Promise((d,f)=>{a=setTimeout(()=>{if(!l){c=!0,u();let b=i||J();this.coreActionsService.triggerAction($.REACTION_RESOLVER,{event:L.Events.Resolver.REACTION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:b,methodName:_t.RESOLVE_REACTION_ANNOTATIONS,moduleName:o,source:"internal",payload:{error:new Error("Reaction annotation resolution timeout"),request:t}}),f(new Error("Reaction annotation resolution timeout"))}},this.reactionAnnotationDataProvider$.value?.config?.resolveTimeout||this.resolveTimeout);let g=this.getProvider();if(!g)return u(),d({});let p={},_=[...new Set(t.reactionAnnotationIds||[])],T=le(x({},t),{reactionAnnotationIds:_});I(this,null,function*(){try{if(_.length>0||t.documentIds?.length||t.folderId){let b=i||J();this.coreActionsService.triggerAction($.REACTION_RESOLVER,{event:L.Events.Resolver.REACTION_RESOLUTION_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:b,methodName:_t.RESOLVE_REACTION_ANNOTATIONS,moduleName:o,source:"internal",payload:{request:T}});let G=kt(()=>g?.config?.getConfig?.url?Ht(g.config.getConfig.url,g.config.getConfig.headers,T,!0,g.config.getConfig.credentials):g?.get?.(T)||Promise.resolve(void 0),"getReactionAnnotations",this.retryGetConfig).then(M=>c?{}:(u(),M&&M.statusCode!==200?(this.coreActionsService.triggerAction($.REACTION_RESOLVER,{event:L.Events.Resolver.REACTION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:b,methodName:_t.RESOLVE_REACTION_ANNOTATIONS,moduleName:o,source:"internal",payload:{result:M,request:T}}),this.loggingService.catch(M?.message??"Error in ReactionAnnotationsResolverService resolveReactionAnnotations:"),{}):M?.data)).catch(M=>{throw u(),M});try{p=(yield G)||{},this.analyticsService.trackEvent(L.Events.Resolver.REACTION_RESOLVER_GET,{sourceMethod:"resolveReactionAnnotations",source:"sdk",reactionAnnotationIds:_});let M={};Object.entries(p).forEach(([U,k])=>{let S=this.reactionAnnotationById$.value?.[U];S?S&&JSON.stringify(S)!==JSON.stringify(k)&&(M[U]=k):M[U]=k}),Object.keys(M).length>0&&this.reactionAnnotationById$.next(x(x({},this.reactionAnnotationById$.getValue()),M)),this.coreActionsService.triggerAction($.REACTION_RESOLVER,{event:L.Events.Resolver.REACTION_RESOLUTION_RESULT,timestamp:new Date().getTime(),uniqueId:b,methodName:_t.RESOLVE_REACTION_ANNOTATIONS,moduleName:o,source:"internal",payload:{result:M,request:T}}),d(M)}catch(M){let U=i||J();this.coreActionsService.triggerAction($.REACTION_RESOLVER,{event:L.Events.Resolver.REACTION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:U,methodName:_t.RESOLVE_REACTION_ANNOTATIONS,moduleName:o,source:"internal",payload:{error:M,request:T}}),c||f(M),d(p)}}else u(),d({})}catch(b){u();let G=i||J();this.coreActionsService.triggerAction($.REACTION_RESOLVER,{event:L.Events.Resolver.REACTION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:G,methodName:_t.RESOLVE_REACTION_ANNOTATIONS,moduleName:o,source:"internal",payload:{error:b,request:T}}),f(b)}})})}catch(a){this.loggingService.catch("Error in ReactionAnnotationsResolverService resolveReactionAnnotations:",a);let c=i||J();return this.coreActionsService.triggerAction($.REACTION_RESOLVER,{event:L.Events.Resolver.REACTION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:c,methodName:_t.RESOLVE_REACTION_ANNOTATIONS,moduleName:o,source:"internal",payload:{error:a,request:t}}),{}}})}saveReactionAnnotation(t,i){return I(this,null,function*(){try{this.loggingService.log("%c[WB] Calling ReactionAnnotationsResolverService FUNCTION: saveReactionAnnotation","color: green;");let o=this.getProvider();if(!this.reactionAnnotationDataProviderAvailable())throw new Error("Reaction annotation save data provider not available");let s=i||J();this.coreActionsService.triggerAction($.REACTION_RESOLVER,{event:L.Events.Resolver.REACTION_SAVE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:s,methodName:_t.SAVE_REACTION_ANNOTATION,source:"internal",payload:{request:t}});let a=JSON.parse(JSON.stringify(this.reactionAnnotationById$.getValue()));this.reactionAnnotationById$._value=x(x({},a),t);let c={reactionAnnotation:t,event:Qt.REACTION_ADD,metadata:Object.values(t??{})?.[0]?.metadata},l=yield kt(()=>o?.config?.saveConfig?.url?Ht(o.config.saveConfig.url,o.config.saveConfig.headers,c,!1,o.config.saveConfig.credentials):o?.save?.(c)||Promise.resolve(void 0),"saveReactionAnnotation",this.retrySaveConfig);return l&&l.statusCode!==200?(this.retrySaveConfig.revertOnFailure&&(this.reactionAnnotationById$._value=a),this.loggingService.catch(l?.message??"Error in ReactionAnnotationsResolverService saveReactionAnnotation:"),this.coreActionsService.triggerAction($.REACTION_RESOLVER,{event:L.Events.Resolver.REACTION_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:s,methodName:_t.SAVE_REACTION_ANNOTATION,source:"internal",payload:{error:l,request:t}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(L.Events.Resolver.REACTION_RESOLVER_SAVE,{sourceMethod:"saveReactionAnnotation",source:"sdk",reactionAnnotationIds:Object.keys(t),eventType:c.event}),this.coreActionsService.triggerAction($.REACTION_RESOLVER,{event:L.Events.Resolver.REACTION_SAVE_RESULT,timestamp:new Date().getTime(),uniqueId:s,methodName:_t.SAVE_REACTION_ANNOTATION,source:"internal",payload:{result:{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0},request:t}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0})}catch(o){this.loggingService.warn("Error in ReactionAnnotationsResolverService saveReactionAnnotation:",o);let s=i||J();return this.coreActionsService.triggerAction($.REACTION_RESOLVER,{event:L.Events.Resolver.REACTION_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:s,methodName:_t.SAVE_REACTION_ANNOTATION,source:"internal",payload:{error:o,request:t}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0}}})}deleteReactionAnnotation(t,i,o){return I(this,null,function*(){try{this.loggingService.log("%c[WB] Calling ReactionAnnotationsResolverService FUNCTION: deleteReactionAnnotation","color: green;");let s=this.getProvider();if(!this.reactionAnnotationDataProviderAvailable())throw new Error("Reaction annotation delete data provider not available");let a=JSON.parse(JSON.stringify(this.reactionAnnotationById$.getValue())),c=i??a?.[t]?.metadata,l=c?Cn(c):void 0,u=l?x({apiKey:l.apiKey??null,documentId:l.documentId??null,organizationId:l.organizationId??null},l.folderId&&{folderId:l.folderId}):void 0,d=o||J();this.coreActionsService.triggerAction($.REACTION_RESOLVER,{event:L.Events.Resolver.REACTION_DELETE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:d,methodName:_t.DELETE_REACTION_ANNOTATION,source:"internal",payload:{reactionAnnotationId:t.toString(),metadata:u}});let f=x({},a);delete f?.[t],this.reactionAnnotationById$._value=f;let g=yield kt(()=>{if(s?.config?.deleteConfig?.url){let p={reactionAnnotationId:t.toString(),metadata:u,event:Qt.REACTION_DELETE};return Ht(s.config.deleteConfig.url,s.config.deleteConfig.headers,p,!1,s.config.deleteConfig.credentials)}return s?.delete?.({reactionAnnotationId:t.toString(),metadata:u,event:Qt.REACTION_DELETE})||Promise.resolve(void 0)},"deleteReactionAnnotation",this.retryDeleteConfig);return g&&g.statusCode!==200?(this.retryDeleteConfig.revertOnFailure&&(this.reactionAnnotationById$._value=a),this.loggingService.catch(g?.message??"Error in ReactionAnnotationsResolverService deleteReactionAnnotation:"),this.coreActionsService.triggerAction($.REACTION_RESOLVER,{event:L.Events.Resolver.REACTION_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:d,methodName:_t.DELETE_REACTION_ANNOTATION,source:"internal",payload:{error:g,reactionAnnotationId:t.toString(),metadata:u}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(L.Events.Resolver.REACTION_RESOLVER_DELETE,{sourceMethod:"deleteReactionAnnotation",source:"sdk",reactionAnnotationId:t.toString()}),this.coreActionsService.triggerAction($.REACTION_RESOLVER,{event:L.Events.Resolver.REACTION_DELETE_RESULT,timestamp:new Date().getTime(),uniqueId:d,methodName:_t.DELETE_REACTION_ANNOTATION,source:"internal",payload:{result:{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0},reactionAnnotationId:t.toString(),metadata:u}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0})}catch(s){this.loggingService.warn("Error in ReactionAnnotationsResolverService deleteReactionAnnotation:",s);let a=o||J(),c=i?Cn(i):void 0;return this.coreActionsService.triggerAction($.REACTION_RESOLVER,{event:L.Events.Resolver.REACTION_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:a,methodName:_t.DELETE_REACTION_ANNOTATION,source:"internal",payload:{error:s,reactionAnnotationId:t.toString(),metadata:c}}),{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()):ue(void 0)}catch(t){return this.loggingService.catch("Error in ReactionAnnotationsResolverService getReactionAnnotationsById$:",t),ue(void 0)}}getAnnotationById(t){try{return this.reactionAnnotationDataProviderAvailable()?this.reactionAnnotationById$.getValue()?.[t]:void 0}catch(i){this.loggingService.catch("Error in ReactionAnnotationsResolverService getAnnotationById:",i);return}}setReactionAnnotationDataProvider(t){try{if(t){this.loggingService.log("Setting reaction annotation data provider");let i=t.config,o=[{method:"get",configKey:"getConfig"},{method:"save",configKey:"saveConfig"},{method:"delete",configKey:"deleteConfig"}],s=[];if(o.forEach(({method:a,configKey:c})=>{let l=i?.[c]?.url,u=a in t&&typeof t[a]=="function";!l&&!u&&s.push(a)}),s.length>0){let a=`DataProviders.reaction is invalid. The following methods are missing or are not functions (and no corresponding config provided): ${s.join(", ")}.`;this.loggingService.catch(a);return}else this.reactionAnnotationDataProvider$.next(t)}}catch(i){this.loggingService.catch("Error in ReactionAnnotationsResolverService setReactionAnnotationDataProvider:",i)}}reactionAnnotationDataProviderAvailable(){try{return!!this.reactionAnnotationDataProvider$.getValue()}catch(t){return this.loggingService.catch("Error in ReactionAnnotationsResolverService reactionAnnotationDataProviderAvailable:",t),!1}}};e.\u0275fac=function(i){return new(i||e)(w(It),w(_e),w(Lt))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let n=e;return n})();var Wh=(()=>{let e=class e{constructor(t,i,o){this.coreActionsService=t,this.loggingService=i,this.analyticsService=o,this.providers=new Map,this.retrySaveConfigs=new Map,this.retryDeleteConfigs=new Map,this.defaultRetryConfig={retryCount:0,retryDelay:0,revertOnFailure:!1};try{this.loggingService.log("AttachmentResolverService initialized")}catch(s){this.loggingService.catch("Error in AttachmentResolverService constructor:",s)}}getProvider(t){try{let i=t||"default";return this.providers.get(i)||void 0}catch(i){this.loggingService.catch("Error in AttachmentResolverService getProvider:",i);return}}getRetrySaveConfig(t){let i=t||"default";return this.retrySaveConfigs.get(i)||this.defaultRetryConfig}getRetryDeleteConfig(t){let i=t||"default";return this.retryDeleteConfigs.get(i)||this.defaultRetryConfig}makeAttachmentConfigBasedRequest(t,i,o,s,a){return I(this,null,function*(){try{let c=typeof i=="function"?yield i():i||{},l=new FormData;l.append("file",o);let u={attachment:{attachmentId:s.attachment.attachmentId,name:s.attachment.name,mimeType:s.attachment.mimeType},metadata:s.metadata,event:s.event};l.append("request",JSON.stringify(u));let d={};Object.entries(c).forEach(([p,_])=>{p.toLowerCase()!=="content-type"&&(d[p]=_)});let f=yield fetch(t,x({method:"POST",headers:d,body:l},a?{credentials:a}:{}));return f.ok?{data:(yield f.json())?.data??{},success:!0,statusCode:200}:(H.catch(`Error in makeAttachmentConfigBasedRequest: ${f.status} ${f.statusText}`),{data:{},success:!1,statusCode:f.status})}catch(c){return H.catch("Error in makeAttachmentConfigBasedRequest:",c),{data:{},success:!1,statusCode:500}}})}saveAttachment(t,i,o){return I(this,null,function*(){try{this.loggingService.log("%c[WB] Calling AttachmentResolverService FUNCTION: saveAttachment","color: green;");let s=this.getProvider(o);if(!this.attachmentDataProviderAvailable(o))throw new Error("Attachment save data provider not available");let a=this.getRetrySaveConfig(o),c=i||J();this.coreActionsService.triggerAction($.ATTACHMENT_RESOLVER,{event:L.Events.Resolver.ATTACHMENT_SAVE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:c,methodName:No.SAVE_ATTACHMENT,source:"internal",payload:{request:t}});let l=yield kt(()=>I(this,null,function*(){if(s?.config?.saveConfig?.url){let u=t.attachment,{file:d}=u,f=dS(u,["file"]);return this.makeAttachmentConfigBasedRequest(s.config.saveConfig.url,s.config.saveConfig.headers,d,{attachment:f,event:t.eventType,metadata:t.attachment.metadata},s.config.saveConfig.credentials)}return s?.save?.({attachment:t.attachment,event:t.eventType,metadata:t.attachment.metadata})||Promise.resolve(void 0)}),"saveAttachment",a);if(l?.statusCode!==200){this.loggingService.catch(l?.message??"Error in AttachmentResolverService saveAttachment:"),this.coreActionsService.triggerAction($.ATTACHMENT_RESOLVER,{event:L.Events.Resolver.ATTACHMENT_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:c,methodName:No.SAVE_ATTACHMENT,source:"internal",payload:{error:l,request:t}});return}return this.analyticsService.trackEvent(L.Events.Resolver.ATTACHMENT_RESOLVER_SAVE,{sourceMethod:"saveAttachment",source:"sdk",attachmentId:t.attachment.attachmentId,eventType:t.eventType}),this.coreActionsService.triggerAction($.ATTACHMENT_RESOLVER,{event:L.Events.Resolver.ATTACHMENT_SAVE_RESULT,timestamp:new Date().getTime(),uniqueId:c,methodName:No.SAVE_ATTACHMENT,source:"internal",payload:{result:l,request:t}}),l}catch(s){this.loggingService.warn("Error in AttachmentResolverService saveAttachment:",s);let a=i||J();this.coreActionsService.triggerAction($.ATTACHMENT_RESOLVER,{event:L.Events.Resolver.ATTACHMENT_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:a,methodName:No.SAVE_ATTACHMENT,source:"internal",payload:{error:s,request:t}});return}})}deleteAttachment(a,c,l){return I(this,arguments,function*({attachmentId:t,metadata:i},o,s){try{this.loggingService.log("%c[WB] Calling AttachmentResolverService FUNCTION: deleteAttachment","color: green;");let u=this.getProvider(s);if(!this.attachmentDataProviderAvailable(s))throw new Error("Attachment delete data provider not available");let d=i?x({apiKey:i.apiKey??null,documentId:i.documentId??null,organizationId:i.organizationId??null},i.folderId&&{folderId:i.folderId}):void 0,f=this.getRetryDeleteConfig(s),g=o||J();this.coreActionsService.triggerAction($.ATTACHMENT_RESOLVER,{event:L.Events.Resolver.ATTACHMENT_DELETE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:g,methodName:No.DELETE_ATTACHMENT,source:"internal",payload:{attachmentId:t,metadata:d}});let p=yield kt(()=>{if(u?.config?.deleteConfig?.url){let _={attachmentId:t,metadata:d,event:Qt.ATTACHMENT_DELETE};return Ht(u.config.deleteConfig.url,u.config.deleteConfig.headers,_,!1,u.config.deleteConfig.credentials)}return u?.delete?.({attachmentId:t,metadata:d,event:Qt.ATTACHMENT_DELETE})||Promise.resolve(void 0)},"deleteAttachment",f);return p?.statusCode!==200?(this.loggingService.catch(p?.message??"Error in AttachmentResolverService deleteAttachment:"),this.coreActionsService.triggerAction($.ATTACHMENT_RESOLVER,{event:L.Events.Resolver.ATTACHMENT_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:g,methodName:No.DELETE_ATTACHMENT,source:"internal",payload:{error:p,attachmentId:t,metadata:d}}),{revertOnFailure:f.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(L.Events.Resolver.ATTACHMENT_RESOLVER_DELETE,{sourceMethod:"deleteAttachment",source:"sdk",attachmentId:t}),this.coreActionsService.triggerAction($.ATTACHMENT_RESOLVER,{event:L.Events.Resolver.ATTACHMENT_DELETE_RESULT,timestamp:new Date().getTime(),uniqueId:g,methodName:No.DELETE_ATTACHMENT,source:"internal",payload:{result:{revertOnFailure:f.revertOnFailure,isSuccess:!0},attachmentId:t,metadata:d}}),{revertOnFailure:f.revertOnFailure,isSuccess:!0})}catch(u){this.loggingService.warn("Error in AttachmentResolverService deleteAttachment:",u);let d=this.getRetryDeleteConfig(s),f=o||J(),g=i?x({apiKey:i.apiKey??null,documentId:i.documentId??null,organizationId:i.organizationId??null},i.folderId&&{folderId:i.folderId}):void 0;return this.coreActionsService.triggerAction($.ATTACHMENT_RESOLVER,{event:L.Events.Resolver.ATTACHMENT_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:f,methodName:No.DELETE_ATTACHMENT,source:"internal",payload:{error:u,attachmentId:t,metadata:g}}),{revertOnFailure:d.revertOnFailure,isSuccess:!0}}})}setAttachmentDataProvider(t,i="default"){try{if(t){this.loggingService.log(`Setting attachment data provider for scope: ${i}`);let o=t.config,s=[{method:"save",configKey:"saveConfig"},{method:"delete",configKey:"deleteConfig"}],a=[];if(s.forEach(({method:c,configKey:l})=>{let u=o?.[l]?.url,d=c in t&&typeof t[c]=="function";!u&&!d&&a.push(c)}),a.length>0){let c=`DataProviders.attachment is invalid. The following methods are missing or are not functions (and no corresponding config provided): ${a.join(", ")}.`;this.loggingService.catch(c);return}else this.providers.set(i,t),t.config?.saveRetryConfig&&this.retrySaveConfigs.set(i,t.config.saveRetryConfig),t.config?.deleteRetryConfig&&this.retryDeleteConfigs.set(i,t.config.deleteRetryConfig)}}catch(o){this.loggingService.catch("Error in AttachmentResolverService setAttachmentDataProvider:",o)}}attachmentDataProviderAvailable(t){try{let i=t||"default";return this.providers.has(i)}catch(i){return this.loggingService.catch("Error in AttachmentResolverService attachmentDataProviderAvailable:",i),!1}}};e.\u0275fac=function(i){return new(i||e)(w(It),w(_e),w(Lt))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let n=e;return n})();var ec=(()=>{let e=class e{constructor(t,i,o,s){this.coreActionsService=t,this.loggingService=i,this.analyticsService=o,this.attachmentResolverService=s,this.resolveTimeout=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.recorderAnnotationDataProvider$=new Y(null),this.recorderAnnotationById$=new Y({}),this.additionalFields=[],this.fieldsToRemove=[],this.uploadChunks=!1,this.getRecorderAnnotationById=a=>{try{return this.recorderAnnotationDataProviderAvailable()?this.recorderAnnotationById$.value?.[a]:void 0}catch(c){this.loggingService.catch("Error in RecorderAnnotationsResolverService getRecorderAnnotationById:",c);return}};try{this.loggingService.log("RecorderAnnotationsResolverService initialized"),this.recorderAnnotationDataProvider$.subscribe(a=>{a&&(a.config?.resolveTimeout&&(this.resolveTimeout=a.config.resolveTimeout),a.config?.saveRetryConfig&&(this.retrySaveConfig=a.config.saveRetryConfig),a.config?.deleteRetryConfig&&(this.retryDeleteConfig=a.config.deleteRetryConfig),a.config?.getRetryConfig&&(this.retryGetConfig=a.config.getRetryConfig),a.config?.additionalFields&&(this.additionalFields=a.config.additionalFields||[]),a.config?.fieldsToRemove&&(this.fieldsToRemove=a.config.fieldsToRemove||[]),this.uploadChunks=a.uploadChunks??!1)})}catch(a){this.loggingService.catch("Error in RecorderAnnotationsResolverService constructor:",a)}}getProvider(){try{let t=this.recorderAnnotationDataProvider$.getValue();return t||void 0}catch(t){this.loggingService.catch("Error in RecorderAnnotationsResolverService getProvider:",t);return}}ngOnDestroy(){try{this.recorderAnnotationById$.next({})}catch(t){this.loggingService.catch("Error in RecorderAnnotationsResolverService ngOnDestroy:",t)}}resolveRecorderAnnotations(s){return I(this,arguments,function*({request:t,uniqueId:i,moduleName:o}){try{if(this.loggingService.log("%c[WB] Calling RecorderAnnotationsResolverService FUNCTION: resolveRecorderAnnotations","color: green;"),!this.recorderAnnotationDataProviderAvailable())return{};let a,c=!1,l=!1,u=()=>{a&&(clearTimeout(a),a=void 0,l=!0)};return new Promise((d,f)=>{a=setTimeout(()=>{if(!l){c=!0,u();let b=i||J();this.coreActionsService.triggerAction($.RECORDER_RESOLVER,{event:L.Events.Resolver.RECORDER_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:b,methodName:Tt.RESOLVE_RECORDER_ANNOTATIONS,moduleName:o,source:"internal",payload:{error:new Error("Recorder annotation resolution timeout"),request:t}}),f(new Error("Recorder annotation resolution timeout"))}},this.recorderAnnotationDataProvider$.value?.config?.resolveTimeout||this.resolveTimeout);let g=this.getProvider();if(!g)return u(),d({});let p={},_=[...new Set(t.recorderAnnotationIds||[])],T=le(x({},t),{recorderAnnotationIds:_});I(this,null,function*(){try{if(_.length>0||t.documentIds?.length){let b=i||J();this.coreActionsService.triggerAction($.RECORDER_RESOLVER,{event:L.Events.Resolver.RECORDER_RESOLUTION_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:b,methodName:Tt.RESOLVE_RECORDER_ANNOTATIONS,moduleName:o,source:"internal",payload:{request:T}});let G=kt(()=>g?.config?.getConfig?.url?Ht(g.config.getConfig.url,g.config.getConfig.headers,T,!0,g.config.getConfig.credentials):g?.get?.(T)||Promise.resolve(void 0),"getRecorderAnnotations",this.retryGetConfig).then(M=>c?{}:(u(),M&&M.statusCode!==200?(this.coreActionsService.triggerAction($.RECORDER_RESOLVER,{event:L.Events.Resolver.RECORDER_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:b,methodName:Tt.RESOLVE_RECORDER_ANNOTATIONS,moduleName:o,source:"internal",payload:{result:M,request:T}}),this.loggingService.catch(M?.message??"Error in RecorderAnnotationsResolverService resolveRecorderAnnotations:"),{}):M?.data)).catch(M=>{throw u(),M});try{p=(yield G)||{},this.analyticsService.trackEvent(L.Events.Resolver.RECORDER_RESOLVER_GET,{sourceMethod:"resolveRecorderAnnotations",source:"sdk",recorderAnnotationIds:_});let M={};Object.entries(p).forEach(([U,k])=>{let S=this.recorderAnnotationById$.value?.[U];S?S&&JSON.stringify(S)!==JSON.stringify(k)&&(M[U]=k):M[U]=k}),Object.keys(M).length>0&&this.recorderAnnotationById$.next(x(x({},this.recorderAnnotationById$.getValue()),M)),this.coreActionsService.triggerAction($.RECORDER_RESOLVER,{event:L.Events.Resolver.RECORDER_RESOLUTION_RESULT,timestamp:new Date().getTime(),uniqueId:b,methodName:Tt.RESOLVE_RECORDER_ANNOTATIONS,moduleName:o,source:"internal",payload:{result:M,request:T}}),d(M)}catch(M){let U=i||J();this.coreActionsService.triggerAction($.RECORDER_RESOLVER,{event:L.Events.Resolver.RECORDER_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:U,methodName:Tt.RESOLVE_RECORDER_ANNOTATIONS,moduleName:o,source:"internal",payload:{error:M,request:T}}),c||f(M),d(p)}}else u(),d({})}catch(b){u();let G=i||J();this.coreActionsService.triggerAction($.RECORDER_RESOLVER,{event:L.Events.Resolver.RECORDER_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:G,methodName:Tt.RESOLVE_RECORDER_ANNOTATIONS,moduleName:o,source:"internal",payload:{error:b,request:T}}),f(b)}})})}catch(a){this.loggingService.catch("Error in RecorderAnnotationsResolverService resolveRecorderAnnotations:",a);let c=i||J();return this.coreActionsService.triggerAction($.RECORDER_RESOLVER,{event:L.Events.Resolver.RECORDER_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:c,methodName:Tt.RESOLVE_RECORDER_ANNOTATIONS,moduleName:o,source:"internal",payload:{error:a,request:t}}),{}}})}saveRecorderAnnotation(t,i){return I(this,null,function*(){try{this.loggingService.log("%c[WB] Calling RecorderAnnotationsResolverService FUNCTION: saveRecorderAnnotation","color: green;");let o=this.getProvider();if(!this.recorderAnnotationDataProviderAvailable())throw new Error("Recorder annotation save data provider not available");let s=i||J();this.coreActionsService.triggerAction($.RECORDER_RESOLVER,{event:L.Events.Resolver.RECORDER_SAVE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:s,methodName:Tt.SAVE_RECORDER_ANNOTATION,source:"internal",payload:{request:t}});let a=JSON.parse(JSON.stringify(this.recorderAnnotationById$.getValue()));this.recorderAnnotationById$._value=x(x({},a),t.recorderAnnotation);let c=yield kt(()=>{if(o?.config?.saveConfig?.url){let l={recorderAnnotation:t.recorderAnnotation,event:t.eventType,metadata:Object.values(t.recorderAnnotation??{})?.[0]?.metadata};return Ht(o.config.saveConfig.url,o.config.saveConfig.headers,l,!1,o.config.saveConfig.credentials)}return o?.save?.({recorderAnnotation:t.recorderAnnotation,event:t.eventType,metadata:Object.values(t.recorderAnnotation??{})?.[0]?.metadata})||Promise.resolve(void 0)},"saveRecorderAnnotation",this.retrySaveConfig);return c&&c.statusCode!==200?(this.retrySaveConfig.revertOnFailure&&(this.recorderAnnotationById$._value=a),this.loggingService.catch(c?.message??"Error in RecorderAnnotationsResolverService saveRecorderAnnotation:"),this.coreActionsService.triggerAction($.RECORDER_RESOLVER,{event:L.Events.Resolver.RECORDER_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:s,methodName:Tt.SAVE_RECORDER_ANNOTATION,source:"internal",payload:{error:c,request:t}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(L.Events.Resolver.RECORDER_RESOLVER_SAVE,{sourceMethod:"saveRecorderAnnotation",source:"sdk",recorderAnnotationIds:Object.keys(t.recorderAnnotation),eventType:t.eventType}),this.coreActionsService.triggerAction($.RECORDER_RESOLVER,{event:L.Events.Resolver.RECORDER_SAVE_RESULT,timestamp:new Date().getTime(),uniqueId:s,methodName:Tt.SAVE_RECORDER_ANNOTATION,source:"internal",payload:{result:{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0},request:t}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0})}catch(o){this.loggingService.warn("Error in RecorderAnnotationsResolverService saveRecorderAnnotation:",o);let s=i||J();return this.coreActionsService.triggerAction($.RECORDER_RESOLVER,{event:L.Events.Resolver.RECORDER_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:s,methodName:Tt.SAVE_RECORDER_ANNOTATION,source:"internal",payload:{error:o,request:t}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0}}})}deleteRecorderAnnotation(t,i,o){return I(this,null,function*(){try{this.loggingService.log("%c[WB] Calling RecorderAnnotationsResolverService FUNCTION: deleteRecorderAnnotation","color: green;");let s=this.getProvider();if(!this.recorderAnnotationDataProviderAvailable())throw new Error("Recorder annotation delete data provider not available");let a=this.recorderAnnotationById$.getValue(),l=a?.[t]?.metadata??(i?Cn(i):void 0),u=l?x({apiKey:l.apiKey??null,documentId:l.documentId??null,organizationId:l.organizationId??null},l.folderId&&{folderId:l.folderId}):void 0,d=o||J();this.coreActionsService.triggerAction($.RECORDER_RESOLVER,{event:L.Events.Resolver.RECORDER_DELETE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:d,methodName:Tt.DELETE_RECORDER_ANNOTATION,source:"internal",payload:{recorderAnnotationId:t.toString(),metadata:u}});let f=x({},a);delete f?.[t],this.recorderAnnotationById$._value=f;let g=yield kt(()=>{if(s?.config?.deleteConfig?.url){let p={recorderAnnotationId:t.toString(),metadata:u,event:Qt.RECORDER_ANNOTATION_DELETE};return Ht(s.config.deleteConfig.url,s.config.deleteConfig.headers,p,!1,s.config.deleteConfig.credentials)}return s?.delete?.({recorderAnnotationId:t.toString(),metadata:u,event:Qt.RECORDER_ANNOTATION_DELETE})||Promise.resolve(void 0)},"deleteRecorderAnnotation",this.retryDeleteConfig);return g&&g.statusCode!==200?(this.retryDeleteConfig.revertOnFailure&&(this.recorderAnnotationById$._value=a),this.loggingService.catch(g?.message??"Error in RecorderAnnotationsResolverService deleteRecorderAnnotation:"),this.coreActionsService.triggerAction($.RECORDER_RESOLVER,{event:L.Events.Resolver.RECORDER_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:d,methodName:Tt.DELETE_RECORDER_ANNOTATION,source:"internal",payload:{error:g,recorderAnnotationId:t.toString(),metadata:u}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(L.Events.Resolver.RECORDER_RESOLVER_DELETE,{sourceMethod:"deleteRecorderAnnotation",source:"sdk",recorderAnnotationId:t.toString()}),this.coreActionsService.triggerAction($.RECORDER_RESOLVER,{event:L.Events.Resolver.RECORDER_DELETE_RESULT,timestamp:new Date().getTime(),uniqueId:d,methodName:Tt.DELETE_RECORDER_ANNOTATION,source:"internal",payload:{result:{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0},recorderAnnotationId:t.toString(),metadata:u}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0})}catch(s){this.loggingService.warn("Error in RecorderAnnotationsResolverService deleteRecorderAnnotation:",s);let a=o||J(),c=i?Cn(i):void 0;return this.coreActionsService.triggerAction($.RECORDER_RESOLVER,{event:L.Events.Resolver.RECORDER_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:a,methodName:Tt.DELETE_RECORDER_ANNOTATION,source:"internal",payload:{error:s,recorderAnnotationId:t.toString(),metadata:c}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0}}})}getRecorderAnnotationsById$(){try{return this.recorderAnnotationDataProviderAvailable()?(this.loggingService.log("%c[WB] Calling RecorderAnnotationsResolverService FUNCTION: getRecorderAnnotationsById$","color: green;"),this.recorderAnnotationById$.asObservable()):ue(void 0)}catch(t){return this.loggingService.catch("Error in RecorderAnnotationsResolverService getRecorderAnnotationsById$:",t),ue(void 0)}}getAnnotationById(t){try{return this.recorderAnnotationDataProviderAvailable()?this.recorderAnnotationById$.getValue()?.[t]:void 0}catch(i){this.loggingService.catch("Error in RecorderAnnotationsResolverService getAnnotationById:",i);return}}getAdditionalFields(){try{return this.additionalFields}catch(t){return this.loggingService.catch("Error in RecorderAnnotationsResolverService getAdditionalFields:",t),this.additionalFields}}getFieldsToRemove(){try{return this.fieldsToRemove}catch(t){return this.loggingService.catch("Error in RecorderAnnotationsResolverService getFieldsToRemove:",t),this.fieldsToRemove}}shouldUploadChunks(){return this.uploadChunks}shouldUploadFullRecording(){return this.recorderAnnotationDataProviderAvailable()&&!this.uploadChunks}setRecorderAnnotationDataProvider(t){try{if(t){this.loggingService.log("Setting recorder annotation data provider");let i=t.config,o=[{method:"get",configKey:"getConfig"},{method:"save",configKey:"saveConfig"},{method:"delete",configKey:"deleteConfig"}],s=[];if(o.forEach(({method:a,configKey:c})=>{let l=i?.[c]?.url,u=a in t&&typeof t[a]=="function";!l&&!u&&s.push(a)}),s.length>0){let a=`DataProviders.recorder is invalid. The following methods are missing or are not functions (and no corresponding config provided): ${s.join(", ")}.`;this.loggingService.catch(a);return}else t.storage&&this.attachmentResolverService.setAttachmentDataProvider(t.storage,"recorder"),this.attachmentResolverService.attachmentDataProviderAvailable("recorder")||this.loggingService.catch("Recording resolver is configured without storage resolver. Recording files (chunks, thumbnails) will be stored on Velt's infrastructure. Configure storage resolver for full self-hosting.",void 0,void 0,!0),this.recorderAnnotationDataProvider$.next(t)}}catch(i){this.loggingService.catch("Error in RecorderAnnotationsResolverService setRecorderAnnotationDataProvider:",i)}}recorderAnnotationDataProviderAvailable(){try{return!!this.recorderAnnotationDataProvider$.getValue()}catch(t){return this.loggingService.catch("Error in RecorderAnnotationsResolverService recorderAnnotationDataProviderAvailable:",t),!1}}};e.\u0275fac=function(i){return new(i||e)(w(It),w(_e),w(Lt),w(Wh))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let n=e;return n})();var qy=class{};var zh=(()=>{let e=class e{constructor(t,i,o,s,a,c,l,u,d,f,g,p){this.analyticsService=t,this.authService=i,this.databaseService=o,this.domService=s,this.configService=a,this.loggingService=c,this.commentResolverService=l,this.reactionResolverService=u,this.recorderResolverService=d,this.coreActionsService=f,this.functions=g,this.serviceBook=p,this.documentPaths$=new Y(null),this.docContext$=new Y(null),this.documentIds$=new Y([]),this.organizationConfig$=new Y(null),this.firestorePaths$=new Y(null),this.location$=new Y(null),this.excludedLocationIds$=new Y([]),this.organizationMetadata$=new Y(null),this.documentMetadata$=new Y(null),this.locationMetadata$=new Y(null),this.customerMetadata$=new Y(null),this.currentDocumentId=null,this.isCustomDocId=!1,this.locations$=new Y({}),this.preDocumentIdChangeFunctions=new Map,this.draftDocuments=[],this.clientDocumentMetadataMap={},this.uiState=new Y({}),this.lastSetDocumentIdExecutionTime=0,this.lastSetDocumentIdCallTime=0,this.setDocumentIdSubject=new Ot,this.DEBOUNCE_TIME=5e3,this.currentDebounceTime=this.DEBOUNCE_TIME,this.MAX_QUEUE_SIZE=100,this.queueSize=0,this.isDocumentIdInDebounceQueue=!1,this.currentValidationToken=null,this.pendingDocumentIds=[],this.pendingOptions={},this.draftLocationMap={locations:[],options:void 0};try{this.loggingService.log("%c[WB] Creating CLASS: DocService","color: blue;"),this.domService.setDocService(this),this.authService.setDocService(this),this.serviceBook.observe(pd).subscribe(_=>{this.commentService=_??void 0}),B1(()=>this.documentPaths$.value?.clientDocumentId),this.setDocumentIdSubject.pipe(SS(()=>Ci(this.currentDebounceTime))).subscribe({next:_=>I(this,null,function*(){try{yield this.setDocumentIdImpl(_.documentId,_.clientOrganizationId,_.options),this.lastSetDocumentIdExecutionTime=Date.now(),this.isDocumentIdInDebounceQueue=!1,this.draftLocationMap.locations.length&&(yield this.setLocations({locations:this.draftLocationMap.locations,options:this.draftLocationMap.options,source:"internal"})),this.draftLocationMap={locations:[],options:void 0}}finally{this.queueSize--}}),error:_=>{this.loggingService.catch("Error in setDocumentId subscription:",_),this.queueSize--}}),this.databaseService.getDb().pipe(Ct(_=>!!_),Nt(1)).subscribe(_=>{_&&(this.db=_)}),this.configService.getApiKey$().subscribe(_=>{if(this.apiKey=_,this.apiKey){if(!this.isCustomDocId){let T=HT(window.location.href);this.currentUrl=T}this.analyticsService.updateDefaultProperties({apiKey:_})}}),this.authService.getUser$().subscribe(_=>I(this,null,function*(){if(_&&(this.analyticsService.updateDefaultProperties({organizationId:_?.organizationId,clientOrganizationId:_?.clientOrganizationId}),this.draftDocuments?.length?(yield this.setDocuments({documents:this.draftDocuments,options:this.draftOptions??void 0,source:"internal"}),this.draftDocuments=[],this.draftOptions=void 0,this.draftLocationMap.locations.length&&(yield this.setLocations({locations:this.draftLocationMap.locations,options:this.draftLocationMap.options,source:"internal"}).then(()=>this.draftLocationMap={locations:[],options:void 0}))):this.documentPaths$?.value&&_?.organizationId&&this.documentPaths$.value?.organizationId!==_?.organizationId&&(yield this.setDocuments({documents:this.documentIds$.value.length?this.documentIds$.value.map(T=>({id:T.clientDocumentId})):[{id:this.documentPaths$.value?.clientDocumentId}],options:void 0,source:"internal"})),setTimeout(()=>{this.documentPaths$.value||this.loggingService.catch("Error in DocService constructor:","Please set document id to continue.")},1e4),_?.organizationId&&_?.clientOrganizationId)){let T={organizationId:_?.organizationId,clientOrganizationId:_?.clientOrganizationId};this.getOrganizationConfig()||this.setOrganizationConfig({organizationId:_?.organizationId,clientOrganizationId:_?.clientOrganizationId}),yield this.updateOrganizationMetadata(T)}})),this.documentPaths$.subscribe(_=>{let T={documentId:_?.documentId,clientDocumentId:_?.clientDocumentId,folderId:_?.folderId,allDocuments:_?.allDocuments,veltFolderId:_?.veltFolderId};_?.organizationId&&(T.organizationId=_.organizationId,T.clientOrganizationId=_.clientOrganizationId),this.analyticsService.updateDefaultProperties(T),this.domService.resetSelectedAnnotationsMap()}),this.location$.subscribe(_=>{this.analyticsService.updateDefaultProperties({clientLocation:_?.location,locationId:_?.locationId})}),this.organizationMetadata$.subscribe(_=>{this.authService.setUserOrganization(_?.[this.documentPaths$.value?.organizationId])}),this.documentPaths$.pipe(Ct(_=>!!_),Nt(1)).subscribe(()=>{try{this.subscribeToCustomerMetadata()}catch(_){this.loggingService.catch("Error in DocService subscribeToCustomerMetadata:",_)}},_=>{this.loggingService.catch("Error in DocService subscribeToCustomerMetadata:",_)}),this.loggingService.log("%c[WB] Creating CLASS: DocService 2","color: blue;"),this.onWindowPopstate(),this.onWindowClick()}catch(_){this.loggingService.catch("Error in DocService constructor:",_)}}getOptionsFromDocumentPaths(){try{return this.documentPaths$.value?{organizationId:this.documentPaths$.value?.clientOrganizationId,folderId:this.documentPaths$.value?.folderId,allDocuments:this.documentPaths$.value?.allDocuments,locationId:this.documentPaths$.value?.locationId,optimisticPermissions:this.documentPaths$.value?.optimisticPermissions}:null}catch(t){return this.loggingService.catch("Error in getOptionsFromDocumentPaths:",t),null}}clearCacheOnUserCascade(){this.loggingService.log("%c[WB] Calling FUNCTION: clearCacheOnUserCascade in DocService","color: green;");try{this.setOrganizationConfig(null),this.organizationMetadata$.next(null),this.customerMetadata$.next(null),this.customerMetadataSubscription?.unsubscribe(),this.documentPaths$.value&&(this.draftOptions=this.getOptionsFromDocumentPaths(),this.draftDocuments=this.documentIds$.value.map(t=>({id:t.clientDocumentId})),this.draftLocationMap={locations:[this.location$.value?.location??null,...Object.values(this.locations$.value||{}).map(t=>t.location)].filter(t=>t!==null),options:{rootLocationId:this.location$.value?.location?.id}},this.currentDocumentId=null,this.documentPaths$.next(null),this.firestorePaths$.next(null)),this.unsetDocuments({source:"internal"})}catch(t){this.loggingService.catch("Error in DocService clearCacheOnUserCascade: ",t)}}setUsersService(t){try{this.usersService=t}catch(i){this.loggingService.catch("Error in setUsersService:",i)}}setCommonDbService(t){try{this.commonDbService=t}catch(i){this.loggingService.catch("Error in setCommonDbService:",i)}}setUserPermissionService(t){try{this.userPermissionService=t}catch(i){this.loggingService.catch("Error in setUserPermissionService:",i)}}setCommentService(t){try{this.commentService=t}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 t=HT(location.href);this.currentUrl!==t&&(this.currentUrl=t,!this.isCustomDocId&&this.apiKey&&this.loggingService.log("current url in doc service",this.currentUrl))},t=>{this.loggingService.catch("Error in DocService onWindowPopstate subscription: ",t)})}catch(t){this.loggingService.catch("Error in onWindowPopstate: ",t)}}onWindowClick(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowClick","color: green;");try{this.domService.onWindowClick$().subscribe(()=>{let t=HT(location.href);this.currentUrl!==t&&(this.currentUrl=t,this.isCustomDocId||this.loggingService.log("current url in doc service",this.currentUrl))},t=>{this.loggingService.catch("Error in DocService onWindowClick subscription: ",t)})}catch(t){this.loggingService.catch("Error in onWindowClick: ",t)}}setDocument(a){return I(this,arguments,function*({documentId:t,documentMetadata:i,options:o,source:s="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocument","color: green;"),s==="internal"&&this.analyticsService.trackEvent(L.Events.Core.SET_DOCUMENTS_TRIGGERED,{payload:{id:t,documentMetadata:i,methodName:"setDocument",source:s}}),this.coreActionsService.triggerAction($.INIT_UPDATE,{event:L.Events.Core.SET_DOCUMENTS_TRIGGERED,methodName:kn.SET_DOCUMENTS,source:s,payload:{documentId:t,documentMetadata:i,options:o}}),yield this.setDocumentsImpl({documents:[{id:t,metadata:i}],options:x({organizationId:i?.organizationId},o??{}),source:s})}catch(c){this.loggingService.catch("Error in DocService setDocument:",c)}})}shouldSetDocumentsAgain(t,i={}){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: shouldSetDocumentsAgain","color: green;"),this.pendingDocumentIds.length>0&&t.length===this.pendingDocumentIds.length&&t.every(d=>this.pendingDocumentIds.includes(d.id))&&ki(i,this.pendingOptions))return!1;let o=this.documentPaths$.value?.clientDocumentId,s=i?.rootDocumentId??t[0]?.id,a=this.documentIds$.value.map(u=>u.clientDocumentId),c=jT(this.getOptionsFromDocumentPaths()??{})??{};return!t.every(u=>a.includes(u.id))||!ki(c,i)||o!==s}catch(o){return this.loggingService.catch("Error in DocService shouldSetDocumentsAgain:",o),!0}}getDocumentIdsFromDocuments({documents:t,setClientDocumentMetadataMap:i=!1}){try{let o=[];return t.forEach(s=>{let a=s.id,c=`${Tr(a)}`;i&&s?.metadata&&typeof s.metadata=="object"&&(this.clientDocumentMetadataMap[a]=s.metadata),o.push({documentId:c,clientDocumentId:a})}),o}catch(o){return this.loggingService.catch("Error in DocService getDocumentIdsFromDocuments:",o),[]}}setDocuments(a){return I(this,arguments,function*({documents:t,options:i,source:o="internal",skipPermissionValidation:s=!1}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocuments","color: green;"),o==="internal"&&this.analyticsService.trackEvent(L.Events.Core.SET_DOCUMENTS_TRIGGERED,{payload:{documents:t,options:i,methodName:"setDocuments",source:o}}),this.coreActionsService.triggerAction($.INIT_UPDATE,{event:L.Events.Core.SET_DOCUMENTS_TRIGGERED,methodName:kn.SET_DOCUMENTS,source:o,payload:{documents:t,options:i}}),yield this.setDocumentsImpl({documents:t,options:i??{},source:o,skipPermissionValidation:s})}catch(c){this.loggingService.catch("Error in DocService setDocuments:",c)}})}setRootDocument(o){return I(this,arguments,function*({document:t,source:i="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setRootDocument","color: green;"),this.coreActionsService.triggerAction($.INIT_UPDATE,{event:L.Events.Core.SET_ROOT_DOCUMENT_TRIGGERED,methodName:kn.SET_ROOT_DOCUMENT,source:i,payload:{document:t}});let s=this.getOptionsFromDocumentPaths()??{},a=this.documentIds$.value.map(c=>c.clientDocumentId);if(!a.includes(t.id)){let c=[...a.map(u=>({id:u})),{id:t.id}],l=this.getDocumentIdsFromDocuments({documents:c,setClientDocumentMetadataMap:!0});this.documentIds$.next(l)}yield this.setDocumentIdImpl(t.id,this.documentPaths$.value?.clientOrganizationId,s)}catch(s){this.loggingService.catch("Error in DocService setRootDocument:",s)}})}setDocContext(t){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocContext","color: green;");let i=JSON.parse(JSON.stringify(t??null));this.docContext$.next(i)}catch(i){this.loggingService.catch("Error in setDocContext: ",i)}}getDocContext(){return this.docContext$.getValue()}getDocContext$(){return this.docContext$.asObservable().pipe(it(Ft))}getProcessedDocContext(){return GV(this.getDocContext())}filterRelevantDocuments(s){return I(this,arguments,function*({options:t,documentIds:i,skipPermissionValidation:o=!1}){try{let a=this.authService.getUser();return!a||!this.commonDbService?.shouldUseFirestore()||(i=yield this.fetchDocumentsFromFolder(t,i,a),yield this.handlePermissionProvider(t,i,a),i=yield this.filterDocumentsByPermissions(t,i,a,o),i=i.slice(0,50)),i}catch(a){return this.loggingService.catch("Error in DocService filterRelevantDocuments:",a),i}})}fetchDocumentsFromFolder(t,i,o){return I(this,null,function*(){if(!t?.folderId||!t?.allDocuments)return i;try{let s=Dr(this.functions,Ir({url:st?.cloudFunction?.sdkProxy,apiProxyDomain:this.configService?.getApiProxyDomain()}));(yield Ad({methodName:"getDocuments",data:{type:"getDocuments",metadata:{organizationId:t?.organizationId??o?.clientOrganizationId,folderId:t?.folderId}},getSdkProxy:s,userId:o?.userId??""}))?.data?.forEach(c=>{i.find(l=>l.clientDocumentId===c.id)||i.push({documentId:da(c.id),clientDocumentId:c.id})})}catch(s){this.loggingService.warn("Error in DocService fetchDocumentsFromFolder:",s)}return i})}buildPermissionRequests(t,i,o){try{let s=[];return t.organizationId&&t.organizationId!==o.clientOrganizationId&&s.push({userId:o.userId,resource:{id:t.organizationId,type:di.ORGANIZATION,source:Un.SET_DOCUMENTS,organizationId:t.organizationId,context:t?.context}}),t.folderId&&s.push({userId:o.userId,resource:{id:t.folderId,type:di.FOLDER,source:Un.SET_DOCUMENTS,organizationId:t?.organizationId??o?.clientOrganizationId??"",context:t?.context}}),i&&i.forEach(a=>{s.push({userId:o.userId,resource:x({id:a.clientDocumentId,type:di.DOCUMENT,source:Un.SET_DOCUMENTS,organizationId:t?.organizationId??o?.clientOrganizationId??"",context:t?.context},t?.folderId&&{parentFolderId:t.folderId})})}),t?.context&&this.userPermissionService?.getIsContextEnabled()&&$V({input:t?.context}).forEach(c=>{let l=JSON.stringify(c.access);s.push({userId:o.userId,resource:{id:l,type:di.CONTEXT,source:Un.SET_DOCUMENTS,organizationId:t?.organizationId??o?.clientOrganizationId??"",context:c}})}),s}catch(s){return this.loggingService.catch("Error in buildPermissionRequests:",s),[]}}processAccessibleContexts(t,i){try{if(!t?.success||!t?.data?.length||!this.userPermissionService?.getIsContextEnabled())return;let o=t.data.filter(s=>s.type===di.CONTEXT&&s.hasAccess).map(s=>s.resourceId);if(this.loggingService.logContext("[CONTEXT] processAccessibleContexts called with accessibleContextIds:",JSON.parse(JSON.stringify(o??"nil"))),o?.length){let s=i.filter(c=>o.includes(c.resource.id)).map(c=>c.resource.context).filter(c=>!!c),a=jV({input:s});this.loggingService.logContext("[CONTEXT] processAccessibleContexts called with accessibleContext:",JSON.parse(JSON.stringify(a??"nil"))),a?.access&&(this.loggingService.logContext("[CONTEXT] setting accessibleContext in docContext:",JSON.parse(JSON.stringify(a??"nil"))),this.setDocContext(a))}}catch(o){this.loggingService.catch("Error in processAccessibleContexts:",o)}}handlePermissionProvider(t,i,o){return I(this,null,function*(){if(this.userPermissionService?.isPermissionProviderAvailable())try{this.loggingService.logContext("[CONTEXT] handlePermissionProvider called with options:",JSON.parse(JSON.stringify(t??"nil")),"documentIds:",JSON.parse(JSON.stringify(i??"nil")),"user:",JSON.parse(JSON.stringify(o??"nil")));let s=this.buildPermissionRequests(t,i,o),a=J();this.coreActionsService.triggerAction($.PERMISSION_PROVIDER,{event:L.Events.PermissionProvider.RESOURCE_ACCESS_REQUEST_FORMED,methodName:Un.SET_DOCUMENTS,uniqueId:a,timestamp:new Date().getTime(),source:"internal",payload:{requests:s}}),this.userPermissionService?.cancelPendingRevokes(s);let c=yield this.userPermissionService?.onResourceAccessRequired({requests:s,uniqueId:a,methodName:Un.SET_DOCUMENTS,fromCache:!1});this.loggingService.logContext("[CONTEXT] handlePermissionProvider called with res:",JSON.parse(JSON.stringify(c??"nil")),"requests:",JSON.parse(JSON.stringify(s??"nil"))),this.processAccessibleContexts(c,s)}catch(s){this.loggingService.catch("Error in handlePermissionProvider:",s)}})}filterDocumentsByPermissions(t,i,o,s=!1){return I(this,null,function*(){if(s)return i;if(this.loggingService.logContext("[CONTEXT] filterDocumentsByPermissions called with options:",JSON.parse(JSON.stringify(t??"nil")),"documentIds:",JSON.parse(JSON.stringify(i??"nil")),"user:",JSON.parse(JSON.stringify(o??"nil"))),!(t?.optimisticPermissions!==!1))return yield this.validateAndFilterPermissions(t,i,o);let c=this.currentValidationToken,l=[...i];return c&&this.validatePermissionsInBackground(t,i,o,c),l})}validateAndFilterPermissions(t,i,o){return I(this,null,function*(){try{let s=t?.organizationId??o?.clientOrganizationId,a=yield this.userPermissionService?.getUserPermissions({organizationId:s,documentIds:i.map(u=>u.clientDocumentId),folderIds:t?.folderId?[t?.folderId]:[]});if(!a)return i;this.userPermissionService?.setCurrentUserPermissions(a),s&&a?.[o.userId]?.organization?.[s]?.errorCode===Oo.PERMISSION_DENIED&&this.loggingService.catch(`User does not have access to organization: ${s}`,void 0,void 0,!0),t?.folderId&&a?.[o.userId]?.folders?.[t?.folderId]?.errorCode===Oo.PERMISSION_DENIED&&this.loggingService.catch(`User does not have access to folder: ${t?.folderId}`,void 0,void 0,!0);let c=new Set;Object.entries(a?.[o.userId]?.documents??{}).forEach(([u,d])=>{d?.errorCode===Oo.PERMISSION_DENIED&&c.add(u)}),c.size>0&&(this.loggingService.catch(`User does not have access to documents: ${[...c].join(", ")}`,void 0,void 0,!0),this.coreActionsService.triggerAction($.ERROR,{event:L.Events.Core.SDK_ERROR,sourceMethod:"validateAndFilterPermissions",message:"Access denied to documents in strict validation mode",documentIds:[...c],userId:o.userId,timestamp:new Date().getTime()}));let l=i.filter(u=>!c.has(u.clientDocumentId));return l.length===0&&i.length>0&&this.loggingService.catch("Error in validateAndFilterPermissions: All documents provided are denied"),l}catch(s){return this.loggingService.catch("Error in validateAndFilterPermissions:",s),i}})}validatePermissionsInBackground(t,i,o,s){let a=t?.organizationId??o?.clientOrganizationId;this.userPermissionService?.getUserPermissions({organizationId:a,documentIds:i.map(c=>c.clientDocumentId),folderIds:t?.folderId?[t?.folderId]:[]}).then(c=>{if(this.currentValidationToken===s&&c){this.userPermissionService?.setCurrentUserPermissions(c);let l=[];Object.entries(c?.[o.userId]?.documents??{}).forEach(([u,d])=>{d?.errorCode===Oo.PERMISSION_DENIED&&l.push(u)}),a&&c?.[o.userId]?.organization?.[a]?.errorCode===Oo.PERMISSION_DENIED&&this.loggingService.catch(`User does not have access to organization: ${a}`,void 0,void 0,!0),t?.folderId&&c?.[o.userId]?.folders?.[t?.folderId]?.errorCode===Oo.PERMISSION_DENIED&&this.loggingService.catch(`User does not have access to folder: ${t?.folderId}`,void 0,void 0,!0),l.length>0&&(this.loggingService.catch(`User does not have access to documents: ${l.join(", ")}`,void 0,void 0,!0),this.handleDeniedDocumentAccess(l,o,s))}}).catch(c=>{this.loggingService.catch("Error in background permission validation:",c)})}handleDeniedDocumentAccess(t,i,o){try{if(this.currentValidationToken!==o)return;let s=this.documentPaths$.value;this.coreActionsService.triggerAction($.ERROR,{event:L.Events.Core.SDK_ERROR,sourceMethod:"handleDeniedDocumentAccess",message:"Access denied to document after optimistic load",documentIds:t,userId:i.userId,timestamp:new Date().getTime()});let a=this.documentIds$.value||[],c=a.filter(l=>!t.includes(l.clientDocumentId));c.length!==a.length&&(c.length>0?this.setDocuments({documents:c.map(l=>({id:l.clientDocumentId})),options:{organizationId:s?.clientOrganizationId},source:"internal",skipPermissionValidation:!0}):(this.loggingService.catch("Error in DocService handleDeniedDocumentAccess: Documents provided are all denied"),this.coreActionsService.triggerAction($.ERROR,{event:L.Events.Core.SDK_ERROR,sourceMethod:"handleDeniedDocumentAccess",message:"All documents provided are denied",documentIds:t,userId:i.userId,timestamp:new Date().getTime()}),this.unsetDocuments({source:"internal"})))}catch(s){this.loggingService.catch("Error in handleDeniedDocumentAccess:",s)}}addUserInfoToOrganization(a){return I(this,arguments,function*({organizationId:t,user:i,notificationsConfig:o,currentUserId:s}){try{let c=Dr(this.functions,Ir({url:st?.cloudFunction?.sdkProxy,apiProxyDomain:this.configService?.getApiProxyDomain()}));yield Ad({data:x({type:"addUserInfoToOrganization",metadata:{organizationId:t},user:this.usersService?.externalUserDataProviderAvailable()?{userId:i?.userId}:i},o&&{notificationsConfig:o}),getSdkProxy:c,userId:s??i?.userId??""})}catch(c){this.loggingService.warn("Error in DocService addUserInfoToOrganization:",c)}})}setDocumentsImpl(a){return I(this,arguments,function*({documents:t,options:i,source:o,skipPermissionValidation:s=!1}){try{if(this.loggingService.logContext("[CONTEXT] setDocumentsImpl called with documents:",JSON.parse(JSON.stringify(t??"nil")),"options:",JSON.parse(JSON.stringify(i??"nil"))),!this.shouldSetDocumentsAgain(t,jT(i))){o==="external"&&this.loggingService.catch("setDocuments called with previous request");return}let c=J();this.currentValidationToken=c;let l=this.getDocumentIdsFromDocuments({documents:t,setClientDocumentMetadataMap:!0});if(l?.length===0){this.loggingService.warn("Minimum one document must be set in setDocuments");return}let u=this.authService.getUser();if(!u){this.draftDocuments=t,this.draftOptions=i;return}this.pendingDocumentIds=t.map(f=>f.id),this.pendingOptions=jT(i)??{},this.documentPaths$.value?.organizationId&&i?.organizationId&&this.documentPaths$.value?.clientOrganizationId!==i?.organizationId?this.authService.resetServicesCache():this.unsetDocuments({source:"internal",unsetDocumentPaths:!1});let d=i?.organizationId??u?.clientOrganizationId;if(d&&this.addUserInfoToOrganization({organizationId:d,user:u}),l=yield this.filterRelevantDocuments({options:i,documentIds:l,skipPermissionValidation:s}),this.documentIds$.next(l),l?.length){let f=l[0]?.clientDocumentId;i?.rootDocumentId&&l.find(g=>g.clientDocumentId===i?.rootDocumentId)&&(f=i?.rootDocumentId),yield this.debounceSetDocuments({documentId:f,clientOrganizationId:i?.organizationId,options:i})}this.pendingDocumentIds=[],this.pendingOptions={};return}catch(c){this.pendingDocumentIds=[],this.pendingOptions={},this.loggingService.catch("Error in DocService setDocumentsImpl:",c)}})}setDocumentId(s){return I(this,arguments,function*({documentId:t,clientOrganizationId:i,source:o="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocumentId","color: green;"),o==="internal"&&this.analyticsService.trackEvent(L.Events.Core.SET_DOCUMENTS_TRIGGERED,{payload:{id:t,clientOrganizationId:i,methodName:"setDocumentId",source:o}}),this.coreActionsService.triggerAction($.INIT_UPDATE,{event:L.Events.Core.SET_DOCUMENTS_TRIGGERED,methodName:kn.SET_DOCUMENT_ID,source:o,payload:{documentId:t,clientOrganizationId:i}}),yield this.setDocumentsImpl({documents:[{id:t}],options:{organizationId:i},source:o})}catch(a){this.loggingService.catch("Error in setDocumentId:",a);return}})}debounceSetDocuments(s){return I(this,arguments,function*({documentId:t,clientOrganizationId:i,options:o}){try{this.loggingService.log("%c[WB] Calling FUNCTION: debounceSetDocuments","color: green;");let a=o?.debounceTime??this.DEBOUNCE_TIME;this.currentDebounceTime=a;let c=Date.now(),l=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||l>a&&u>a){yield this.setDocumentIdImpl(t,i,o),this.lastSetDocumentIdExecutionTime=c;return}this.documentPaths$.next(null),this.isDocumentIdInDebounceQueue=!0,this.draftLocationMap={locations:[],options:void 0},this.queueSize++,this.setDocumentIdSubject.next({documentId:t,clientOrganizationId:i,options:o??void 0});return}catch(a){this.loggingService.catch("Error in debounceSetDocuments:",a)}})}setDocumentIdImpl(t,i,o){return I(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: setDocumentIdImpl","color: green;");try{let s=this.authService.getUser();if(!s)return;this.currentDocumentId&&this.documentPaths$.value&&(yield this.callPreDocumentIdChangeFunctions(this.documentPaths$.value));let a=this.currentDocumentId;if(this.apiKey){let c=`${Tr(t)}`,l=o?.folderId,u=o?.folderId?wo(o?.folderId):void 0,d=o?.locationId,f=o?.allDocuments,g=o?.optimisticPermissions,p=s?.organizationId?i?Fi(i):s?.organizationId:void 0,_=J(),T=Td.SET_DOCUMENTS;this.coreActionsService.triggerAction($.COMMENT_RESOLVER,{event:L.Events.Resolver.COMMENT_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:_,methodName:Et.INIT_DOCUMENTS,moduleName:T,source:"internal",payload:{documentIds:this.documentIds$.value.map(U=>U.clientDocumentId),organizationId:i??s?.clientOrganizationId??""}});let D=J(),b=Id.SET_DOCUMENTS;this.coreActionsService.triggerAction($.REACTION_RESOLVER,{event:L.Events.Resolver.REACTION_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:D,moduleName:b,methodName:_t.INIT_DOCUMENTS,source:"internal",payload:{documentIds:this.documentIds$.value.map(U=>U.clientDocumentId),organizationId:i??s?.clientOrganizationId??""}});let G=J(),M=vd.GET_RECORDER_ANNOTATIONS;if(this.coreActionsService.triggerAction($.RECORDER_RESOLVER,{event:L.Events.Resolver.RECORDER_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:G,moduleName:M,methodName:Tt.RESOLVE_RECORDER_ANNOTATIONS,source:"internal",payload:{documentIds:this.documentIds$.value.map(U=>U.clientDocumentId),organizationId:i??s?.clientOrganizationId??""}}),yield Promise.allSettled([this.commentResolverService.resolveCommentAnnotations({request:{documentIds:this.documentIds$.value.map(U=>U.clientDocumentId),organizationId:i??s?.clientOrganizationId??""},uniqueId:_,moduleName:T}),this.reactionResolverService.resolveReactionAnnotations({request:{documentIds:this.documentIds$.value.map(U=>U.clientDocumentId),organizationId:i??s?.clientOrganizationId??""},uniqueId:D,moduleName:b}),this.recorderResolverService.resolveRecorderAnnotations({request:{documentIds:this.documentIds$.value.map(U=>U.clientDocumentId),organizationId:i??s?.clientOrganizationId??""},uniqueId:G,moduleName:M})]),this.currentDocumentId!==c||this.documentPaths$.value?.organizationId!==p){this.loggingService.log("setting new docid"),this.currentDocumentId=c;let U=new xT,k=new qy;U.clientDocumentId=t,k.clientDocumentId=t,U.folderId=l,k.folderId=l,U.locationId=d,k.locationId=d,U.allDocuments=f,U.optimisticPermissions=g,k.allDocuments=f,k.optimisticPermissions=g,U.veltFolderId=u,k.veltFolderId=u,U.documentId=c,k.documentId=c,p&&(U.organizationId=p,U.clientOrganizationId=i??s?.clientOrganizationId,k.organizationId=p,k.clientOrganizationId=i??s?.clientOrganizationId);let S=`${this.apiKey}`,A=`apiKey/${this.apiKey}`;p&&(S=`${S}/${v.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${U.organizationId}`,A=`${A}/${v.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${U.organizationId}`),k.organization=`apiKey/${this.apiKey}/${v.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}`,k.document=`${A}/${v.FIREBASE_PARTIAL_PATH_DOCS}`,U.presence=`${S}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_PRESENCE}/`,U.cursor=`${S}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_CURSOR}/`,U.comment=`${S}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_COMMENT}/`,k.comment=`${A}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_COMMENT}`,U.multiThread=`${S}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_MULTI_THREAD}/`,k.multiThread=`${A}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_MULTI_THREAD}`,U.tag=`${S}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_TAG}/`,U.area=`${S}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_AREA}/`,k.area=`${A}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_AREA}`,U.arrow=`${S}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_ARROW}/`,U.selection=`${S}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_SELECTION}/`,U.audioHuddle=`${S}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_AUDIO_HUDDLE}/`,U.huddle=`${S}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_HUDDLE}/`,U.recorder=`${S}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_RECORDER}/`,k.recorder=`${A}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_RECORDER}`,U.flock=`${S}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_FOLLOW_ALONG}/`,U.syncVideoPlayer=`${S}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_SYNC_VIDEO_PLAYER}/`,U.liveState=`${S}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_LIVE_STATE}/`,U.liveStateSingleEditorMode=`${S}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_LIVE_STATE}/default/singleEditorMode`,U.reaction=`${S}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_REACTION}/`,k.reaction=`${A}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_REACTION}`,U.crdt=`${S}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_CRDT}/`,k.crdt=`${A}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_CRDT}`,U.customerMetadata=`${this.apiKey}/${v.FIREBASE_PARTIAL_PATH_CUSTOMER_METADATA}/`,U.views=`${S}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_VIEWS}/`,k.notificationViews=`${A}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_NOTIFICATION_VIEWS}`,k.documentViews=`${A}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_DOCUMENT_VIEWS}`,k.locationViews=`${A}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_LOCATION_VIEWS}`,U.notifications=`${S}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_NOTIFICATIONS}/`,U.metadata=`${S}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_METADATA}/`,U.users=`${S}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_USERS}/`,U.documentIam=`${S}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_IAM}/`,U.workspaceIam=`${this.apiKey}/${v.FIREBASE_PARTIAL_PATH_IAM}/`,U.groupContacts=`${S}/${v.FIREBASE_PARTIAL_PATH_CONTACTS}/${v.FIREBASE_PARTIAL_PATH_GROUPS}/`,U.globalContacts=`${S}/${v.FIREBASE_PARTIAL_PATH_CONTACTS}/${v.FIREBASE_PARTIAL_PATH_GLOBAL}/`,U.logins=`${S}/${v.FIREBASE_PARTIAL_PATH_CONTACTS}/${v.FIREBASE_PARTIAL_PATH_LOGINS}/`,U.userFeedback=`${S}/${v.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${v.FIREBASE_PARTIAL_PATH_FEEDBACK}/`,U.userReportBugs=`${S}/${v.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${v.FIREBASE_PARTIAL_PATH_BUGS}/`,U.userContactUs=`${S}/${v.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${v.FIREBASE_PARTIAL_PATH_CONTACT_US}/`,p&&(U.organizationMetadata=`${S}/${v.FIREBASE_PARTIAL_PATH_ORGANIZATION_METADATA}/`,U.organizationIam=`${S}/${v.FIREBASE_PARTIAL_PATH_IAM}/`,U.organizationGroups=`${S}/${v.FIREBASE_PARTIAL_PATH_ORGANIZATION_GROUPS}/`,U.organizationNotifications=`${S}/${v.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/`,c&&(U.organizationNotificationsWithDocumentId=`${S}/${v.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/`,U.heartbeatByDocument=`${S}/${v.FIREBASE_PARTIAL_PATH_HEARTBEAT_BY_DOCUMENT}/${c}/`),U.organizationNotificationsLastNotificationTimestamp=`${S}/${v.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${v.FIREBASE_PARTIAL_PATH_LAST_NOTIFICATION_TIMESTAMP}/${v.FIREBASE_PARTIAL_PATH_DOCS}/`,U.organizationNotificationsUsers=`${S}/${v.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${v.FIREBASE_PARTIAL_PATH_USERS}/`,U.heartbeat=`${S}/${v.FIREBASE_PARTIAL_PATH_HEARTBEAT}/`),k.organizationUsers=`${A}/${v.FIREBASE_PARTIAL_PATH_ORGANIZATION_USERS}`,k.users=`${A}/${v.FIREBASE_PARTIAL_PATH_CENTRAL_USERS}`,k.documentUsers=`${A}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_DOCUMENT_USERS}`,k.notificationDocs=`${A}/${v.FIREBASE_PARTIAL_PATH_NOTIFICATION_DOCS}`,k.notificationUsers=`${A}/${v.FIREBASE_PARTIAL_PATH_NOTIFICATION_USERS}`,this.documentPaths$.next(U),this.firestorePaths$.next(k),U?.clientOrganizationId&&U?.organizationId&&!(U?.clientOrganizationId===this.getOrganizationConfig()?.clientOrganizationId&&U?.organizationId===this.getOrganizationConfig()?.organizationId)&&this.setOrganizationConfig({organizationId:U?.organizationId,clientOrganizationId:U?.clientOrganizationId}),Promise.allSettled([this.updateFolderMetadata(),this.updateDocumentMetadata(),this.fetchLocationMetadata(),this.updateOrganizationMetadata()]),a&&this.location$.value&&this.removeLocation({}),this.coreActionsService.triggerAction($.INIT_UPDATE,{event:L.Events.Doc.SET_DOCUMENTS_SUCCESS,payload:{documentId:c,clientDocumentId:t}}),this.analyticsService.trackEvent(L.Events.Doc.SET_DOCUMENTS_SUCCESS,{documentId:c,clientDocumentId:t},!0,this.getUserIdForAnalytics())}}else this.loggingService.catch("Error in setDocumentIdImpl: API key is not provided.")}catch(s){this.loggingService.catch("Error in setDocumentIdImpl: ",s)}})}unsetDocumentId({source:t,unsetDocumentPaths:i}){this.loggingService.log("%c[WB] Calling FUNCTION: unsetDocumentId","color: green;");try{t==="internal"&&this.analyticsService.trackEvent(L.Events.Core.UNSET_DOCUMENTS_TRIGGERED,{payload:{methodName:"unsetDocumentId",source:t}}),this.coreActionsService.triggerAction($.INIT_UPDATE,{event:L.Events.Doc.UNSET_DOCUMENTS_TRIGGERED,methodName:kn.UNSET_DOCUMENT_ID,source:t}),this.unsetDocumentImpl({source:t,unsetDocumentPaths:i})}catch(o){this.loggingService.catch("Error in unsetDocumentId: ",o)}}unsetDocumentImpl({source:t,unsetDocumentPaths:i}){this.loggingService.log("%c[WB] Calling FUNCTION: unsetDocumentImpl","color: green;");try{let o=JSON.parse(JSON.stringify(this.documentIds$.value??[])),s=JSON.parse(JSON.stringify(this.documentPaths$.value?.folderId??"")),a=this.getDocContext();this.currentDocumentId&&this.documentPaths$.value&&this.callPreDocumentIdChangeFunctions(this.documentPaths$.value),i&&(this.documentPaths$.next(null),this.firestorePaths$.next(null)),this.currentDocumentId=null,this.location$.next(null),this.excludedLocationIds$.next([]),this.documentMetadata$.next(null),this.locationMetadata$.next(null),this.locations$.next({}),this.documentIds$.next([]),this.setDocContext(null),this.userPermissionService?.revokeAccessOnDocumentUnset({documentIds:o,folderId:s,context:a}),this.coreActionsService.triggerAction($.INIT_UPDATE,{event:L.Events.Doc.UNSET_DOCUMENTS_SUCCESS,source:t}),this.analyticsService.trackEvent(L.Events.Doc.UNSET_DOCUMENTS_SUCCESS,{documentId:this.currentDocumentId,documentMetadata:this.documentMetadata$.value?.[this.currentDocumentId??""],message:t==="external"?"User unset document id":"System unset document id",source:t},!0,this.getUserIdForAnalytics())}catch(o){this.loggingService.catch("Error in unsetDocumentImpl: ",o)}}unsetDocuments({source:t,unsetDocumentPaths:i=!0}){this.loggingService.log("%c[WB] Calling FUNCTION: unsetDocuments","color: green;");try{t==="internal"&&this.analyticsService.trackEvent(L.Events.Core.UNSET_DOCUMENTS_TRIGGERED,{payload:{methodName:"unsetDocuments",source:t}}),this.coreActionsService.triggerAction($.INIT_UPDATE,{event:L.Events.Doc.UNSET_DOCUMENTS_TRIGGERED,source:t,methodName:kn.UNSET_DOCUMENTS}),this.unsetDocumentImpl({source:t,unsetDocumentPaths:i})}catch(o){this.loggingService.catch("Error in unsetDocuments: ",o)}}addPreDocumentIdChangeFunction(t,i){try{this.loggingService.log("%c[WB] Calling FUNCTION: addPreDocumentIdChangeFunction","color: green;"),this.preDocumentIdChangeFunctions.set(t,i)}catch(o){this.loggingService.catch("Error in addPreDocumentIdChangeFunction: ",o)}}callPreDocumentIdChangeFunctions(t){return I(this,null,function*(){try{this.loggingService.log("%c[WB] Calling FUNCTION: callPreDocumentIdChangeFunctions","color: green;");for(let[i,o]of this.preDocumentIdChangeFunctions)try{yield o(t)}catch(s){this.loggingService.catch("Error in callPreDocumentIdChangeFunctions: ",s)}}catch(i){this.loggingService.catch("Error in callPreDocumentIdChangeFunctions: ",i)}})}fetchOrganizationMetadata(t){return I(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: fetchOrganizationMetadata","color: green;");try{if(!t&&this.getOrganizationConfig()&&(t=this.getOrganizationConfig()),this.db&&t?.organizationId){let i=t?.organizationId,o=t?.clientOrganizationId,s=this.authService.getUser()?.userId??"",a=yield this.userPermissionService?.getUserPermissionsFromCacheOrFetch({organizationId:o});if(s&&a?.[s]?.organization?.[o]?.errorCode===Oo.PERMISSION_DENIED)return;yield this.commonDbService?.getData({feature:"organizationMetadata",properties:{apiKey:this.apiKey??"",organizationId:i,field:"metadata"}}).then(c=>{c&&!c?.errorCode&&this.organizationMetadata$.next(le(x({},this.organizationMetadata$.value),{[i]:c}))}).catch(c=>{this.loggingService.catch("Error in fetchOrganizationMetadata: ",c)})}}catch(i){this.loggingService.catch("Error in fetchOrganizationMetadata: ",i)}})}fetchDocumentMetadata(t){return I(this,null,function*(){try{if(this.db&&this.authService.getUser()){let i=this.documentPaths$.value,o=this.documentMetadata$.value;if(t=t.filter(s=>!o?.[s.documentId]),t?.some(s=>!s?.documentId||!s?.clientDocumentId)||!i)return;if(this.commonDbService?.shouldUseFirestore()){let s=i?.folderId,a=[],c={organizationId:i?.clientOrganizationId,folderId:s},l=[],u=20;for(let f=0;f<t.length;f+=u)l.push(t.slice(f,f+u));l.forEach(f=>{let g=JSON.parse(JSON.stringify(c));g.documentIds=f.map(p=>p.clientDocumentId),a.push(this.fetchDocuments(g))});let d={};a.length>0&&(yield Promise.all(a).then(f=>{f?.forEach(g=>{g?.forEach(p=>{p?.metadata?.documentId&&(d[p.metadata.documentId]=p.metadata)})}),this.setAllDocumentMetadata(x(x({},this.documentMetadata$.value),d))}).catch(f=>{this.loggingService.catch("Error in fetchDocumentMetadata: ",f)}))}else o?.[i?.documentId??t?.[0]?.documentId]||this.commonDbService?.queryData({feature:"allDocuments",properties:{apiKey:this.apiKey??"",organizationId:i?.organizationId,documentId:i?.documentId??t?.[0]?.documentId,skipObjectValues:!0}}).then(s=>{s?.documentId&&this.setDocumentMetadata(s.documentId,s)}).catch(s=>{this.loggingService.catch("Error in fetchDocumentMetadata: ",s)})}}catch(i){this.loggingService.catch("Error in fetchDocumentMetadata: ",i)}})}fetchLocationMetadata(){return I(this,null,function*(){try{if(this.db&&this.authService.getUser()){let t=this.documentPaths$.value,i=this.documentIds$.value,o=t?.folderId,s=t?.allDocuments,a=[],c={organizationId:t?.clientOrganizationId,folderId:o,allDocuments:s},l=[],u=20;for(let f=0;f<i.length;f+=u)l.push(i.slice(f,f+u));l.forEach(f=>{let g=JSON.parse(JSON.stringify(c));g.documentIds=f.map(p=>p.clientDocumentId),a.push(this.fetchLocations(g))});let d=this.locationMetadata$.value??{};a.length>0&&Promise.all(a).then(f=>{f?.forEach(g=>{g?.forEach(p=>{p?.metadata?.documentId&&(d[p.metadata.documentId]=le(x({},d?.[p.metadata.documentId]??{}),{[p.location.id]:p}))})}),Object.keys(d||{}).length>0&&this.locationMetadata$.next(d)}).catch(f=>{this.loggingService.catch("Error in fetchLocationMetadata: ",f)})}}catch(t){this.loggingService.catch("Error in fetchLocationMetadata: ",t)}})}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(ts(i=>ue(null))).subscribe(i=>{this.customerMetadata$.next(i?.data)}))}catch(t){this.loggingService.catch("Error in subscribeToCustomerMetadata: ",t)}}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(fe(t=>t?.slice()))}getDocumentIds(){return this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentIds","color: green;"),this.documentIds$.value?.slice()}getLocationMetadata$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getLocationMetadata$","color: green;"),this.locationMetadata$.asObservable().pipe()}getDocumentPaths$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentPaths$","color: green;"),this.documentPaths$.asObservable()}getFirestorePaths$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getFirestorePaths$","color: green;"),this.firestorePaths$.asObservable()}getDocumentPaths(){return this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentPaths","color: green;"),this.documentPaths$.value}generateDocumentId(t){try{return`${Tr(t)}`}catch(i){return this.loggingService.catch("Error in generateDocumentId: ",i),""}}generateOrganizationId(t){try{return`${Fi(t)}`}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(o){return I(this,arguments,function*({location:t,source:i="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setLocation","color: green;"),i==="internal"&&this.analyticsService.trackEvent(L.Events.Core.SET_LOCATIONS_TRIGGERED,{payload:{locations:[t],options:void 0,methodName:"setLocation",source:i}}),this.coreActionsService.triggerAction($.INIT_UPDATE,{event:L.Events.Core.SET_LOCATIONS_TRIGGERED,source:i,methodName:kn.SET_LOCATION,payload:{locations:[t],options:void 0}}),this.setLocationsImpl({locations:[t]})}catch(s){this.loggingService.catch("Error in setLocation: ",s)}})}setLocations(s){return I(this,arguments,function*({locations:t,options:i,source:o="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setLocations","color: green;"),o==="internal"&&this.analyticsService.trackEvent(L.Events.Core.SET_LOCATIONS_TRIGGERED,{payload:{locations:t,options:i,methodName:"setLocations",source:o}}),this.coreActionsService.triggerAction($.INIT_UPDATE,{event:L.Events.Core.SET_LOCATIONS_TRIGGERED,methodName:kn.SET_LOCATIONS,source:o,payload:{locations:t,options:i}}),this.setLocationsImpl({locations:t,options:i})}catch(a){this.loggingService.catch("Error in setLocations: ",a)}})}getValidLocations(t){try{let i=[];return t&&Array.isArray(t)&&t.forEach(o=>{if(o&&typeof o=="object"){let s=!0;o?.version&&(!o?.version?.id||!o?.version?.name)&&(this.loggingService.catch(`Error in setting location for locationId: ${o?.id}, If you're setting version then add id and name fields to version object.`),s=!1),s&&i.push(o)}}),i}catch(i){this.loggingService.catch("Error in getValidLocations: ",i)}return t}setRootLocation(o){return I(this,arguments,function*({location:t,source:i="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setRootLocation","color: green;"),i==="internal"&&this.analyticsService.trackEvent(L.Events.Core.SET_ROOT_LOCATION_TRIGGERED,{payload:{location:t,methodName:"setRootLocation",source:i}}),this.coreActionsService.triggerAction($.INIT_UPDATE,{event:L.Events.Core.SET_ROOT_LOCATION_TRIGGERED,methodName:kn.SET_ROOT_LOCATION,source:i,payload:{location:t}});let s=Object.values(this.locations$.value).map(a=>a.location).filter(a=>String(a.id)!==String(t.id));this.setLocationsImpl({locations:[t,...s],options:{rootLocationId:t.id}})}catch(s){this.loggingService.catch("Error in DocService setRootLocation:",s)}})}setLocationsImpl({locations:t,options:i}){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: setLocationsImpl","color: green;"),t.length===0)return;if(!this.authService.getUser()){!i?.appendLocation&&t.length>0&&(this.draftLocationMap.options=le(x(x({},this.draftLocationMap.options??{}),i??{}),{rootLocationId:t[0].id})),this.draftLocationMap.locations=[...this.draftLocationMap.locations,...t],this.draftLocationMap.options=x(x({},this.draftLocationMap.options),i);return}let s=this.getValidLocations(t),a=[],c=[];this.location$.value?.location.id&&c.push(this.location$.value?.location.id),c=[...c,...Object.values(this.locations$.value).map(d=>d.location.id)].filter(d=>d!==void 0);let l;if(i?.rootLocationId&&i?.rootLocationId!==this.location$.value?.location.id&&(l=s.find(d=>d.id===i?.rootLocationId),!l)){this.loggingService.catch(`Error in setting locations, rootLocationId: ${i?.rootLocationId} not found in locations.`);return}if(i?.appendLocation){if(l){let d=Sd(l),f=Tr(JSON.stringify(d));d.id&&a.push({locationId:f,location:d}),this.location$.next({locationId:f,location:d})}}else{l||(l=s[0]);let d=Sd(l),f=Tr(JSON.stringify(d));d.id&&a.push({locationId:f,location:d}),this.location$.next({locationId:f,location:d})}let u=[];return s.slice(i?.appendLocation?0:1).forEach(d=>{if(d.id!==this.location$.value?.location.id){let f=x({},d),g=this.locations$.value;d?.id&&Object.keys(g).forEach(D=>{let b=g[D];b.location?.id===d.id&&(f=x(x({},b.location),d),delete g?.[D])});let p=this.genarateLocationId(f),_={locationId:p,location:f};f.id&&a.push({locationId:p,location:f}),u.push(_);let T=le(x({},g),{[p]:_});this.locations$.next(T)}}),this.updateDocumentLocationMetadata(a),this.coreActionsService.triggerAction($.INIT_UPDATE,{event:L.Events.Doc.SET_LOCATIONS_SUCCESS,methodName:kn.SET_LOCATIONS,payload:{locations:s,options:i}}),this.analyticsService.trackEvent(L.Events.Doc.SET_LOCATIONS_SUCCESS,{locations:s,options:i},!0,this.getUserIdForAnalytics()),u}catch(o){this.loggingService.catch("Error in setLocationImpl: ",o);return}}addLocation({location:t,source:i="internal"}){try{return this.loggingService.log("%c[WB] Calling FUNCTION: addLocation","color: green;"),i==="internal"&&this.analyticsService.trackEvent(L.Events.Core.SET_LOCATIONS_TRIGGERED,{payload:{locations:[t],options:{appendLocation:!0},methodName:"addLocation",source:i}}),this.coreActionsService.triggerAction($.INIT_UPDATE,{event:L.Events.Core.SET_LOCATIONS_TRIGGERED,methodName:kn.ADD_LOCATION,source:i,payload:{locations:[t],options:{appendLocation:!0}}}),this.setLocationsImpl({locations:[t],options:{appendLocation:!0}})}catch(o){this.loggingService.catch("Error in DocService addLocation:",o);return}}removeLocation({location:t,source:i="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: removeLocation","color: green;"),i==="internal"&&this.analyticsService.trackEvent(L.Events.Core.REMOVE_LOCATIONS_TRIGGERED,{payload:{locations:[t],methodName:"removeLocation",source:i}}),this.coreActionsService.triggerAction($.INIT_UPDATE,{event:L.Events.Core.REMOVE_LOCATIONS_TRIGGERED,source:i,methodName:kn.REMOVE_LOCATION,payload:{locations:[t]}}),t&&this.removeLocationsImpl([t],i)}catch(o){this.loggingService.catch("Error in removeLocation: ",o)}}removeLocations({locations:t,source:i="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: removeLocations","color: green;"),i==="internal"&&this.analyticsService.trackEvent(L.Events.Core.REMOVE_LOCATIONS_TRIGGERED,{payload:{locations:t,methodName:"removeLocations",source:i}}),this.coreActionsService.triggerAction($.INIT_UPDATE,{event:L.Events.Core.REMOVE_LOCATIONS_TRIGGERED,methodName:kn.REMOVE_LOCATIONS,source:i,payload:{locations:t}}),this.removeLocationsImpl(t,i)}catch(o){this.loggingService.catch("Error in removeLocations: ",o)}}removeLocationsImpl(t,i="internal"){try{this.loggingService.log("%c[WB] Calling FUNCTION: removeLocations","color: green;"),i==="internal"&&this.analyticsService.trackEvent(L.Events.Core.REMOVE_LOCATIONS_TRIGGERED,{payload:{locations:t},methodName:"removeLocations",message:"System removed locations",source:i},!0,this.getUserIdForAnalytics()),t?t.forEach(o=>{let s=this.genarateLocationId(o);this.getLocation()?.locationId===s&&(this.location$.next(null),i!=="internal"&&(this.draftLocationMap.locations=this.draftLocationMap.locations.filter(a=>a.id!==o.id))),this.removeCustomLocation(o)}):(this.location$.next(null),this.locations$.next({}),i!=="internal"&&(this.draftLocationMap.options=void 0,this.draftLocationMap.locations=[])),this.analyticsService.trackEvent(L.Events.Doc.REMOVE_LOCATIONS_SUCCESS,{payload:{locations:t},source:i},!0,this.getUserIdForAnalytics())}catch(o){this.loggingService.catch("Error in removeLocation: ",o)}}unsetLocationIds(t,i="internal"){try{this.loggingService.log("%c[WB] Calling FUNCTION: unsetLocationIds","color: green;"),this.coreActionsService.triggerAction($.INIT_UPDATE,{event:L.Events.Core.UNSET_LOCATIONS_TRIGGERED,methodName:kn.UNSET_LOCATION_IDS,source:i,payload:{locationIds:t}}),i==="internal"&&this.analyticsService.trackEvent(L.Events.Core.UNSET_LOCATIONS_TRIGGERED,{payload:{locationIds:t},methodName:"unsetLocationIds",message:"System unset location ids",source:i},!0,this.getUserIdForAnalytics()),t?.length?t.forEach(o=>{this.getLocation()?.location.id===o&&(this.location$.next(null),i!=="internal"&&(this.draftLocationMap.locations=this.draftLocationMap.locations.filter(s=>s.id!==o))),this.removeCustomLocationId(o)}):(this.location$.next(null),this.locations$.next({}),i!=="internal"&&(this.draftLocationMap.options=void 0,this.draftLocationMap.locations=[])),this.coreActionsService.triggerAction($.INIT_UPDATE,{event:L.Events.Doc.REMOVE_LOCATIONS_SUCCESS,methodName:kn.REMOVE_LOCATIONS_SUCCESS,source:i,payload:{locationIds:t}}),this.analyticsService.trackEvent(L.Events.Doc.REMOVE_LOCATIONS_SUCCESS,{payload:{locationIds:t},source:i},!0,this.getUserIdForAnalytics())}catch(o){this.loggingService.catch("Error in unsetLocationIds: ",o)}}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(t){try{this.excludedLocationIds$.next([...t])}catch(i){this.loggingService.catch("Error in excludeLocationIds: ",i)}}getExcludedLocationIds$(){try{return this.excludedLocationIds$.asObservable()}catch(t){return this.loggingService.catch("Error in getExcludedLocationIds$: ",t),ue([])}}updateOrganizationMetadata(t){return I(this,null,function*(){try{!t&&this.getOrganizationConfig()&&(t=this.getOrganizationConfig());let i=t?.organizationId,o=t?.clientOrganizationId,s=this.documentPaths$.value;if(this.db&&i&&s?.documentId){if(this.organizationMetadata$.value?.[i])return;let c=new kT;c.apiKey=this.configService?.getApiKey()??"",c.organizationId=i,c.clientOrganizationId=o;let l=this.authService.getUser()?.userId??"",u=o?yield this.userPermissionService?.getUserPermissionsFromCacheOrFetch({organizationId:o}):null;!!(l&&o&&u?.[l]?.organization?.[o]?.errorCode===Oo.PERMISSION_DENIED)?this.loggingService.log(`%c[WB] updateOrganizationMetadata skipped \u2014 user does not have access to organization: ${o}`,"color: orange;"):this.userPermissionService?.hasEditAccess({organizationId:i})&&(yield this.commonDbService?.updateData({feature:"organizationMetadata",data:JSON.parse(JSON.stringify(c)),properties:{organizationId:i,documentId:s?.documentId??""}})),yield this.fetchOrganizationMetadata(t)}}catch(i){this.loggingService.catch("Error in updateOrganizationMetadata: ",i)}})}updateFolderMetadata(){return I(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: updateFolderMetadata","color: green;"),this.db&&this.authService.getUser()&&this.documentPaths$.value?.folderId){let t=this.documentPaths$.value;if(!t?.veltFolderId||!t?.organizationId)return;if(!(yield this.commonDbService?.getData({feature:"folderMetadata",properties:{organizationId:t?.organizationId??"",folderId:t?.veltFolderId??""}}))?.metadata){let o={folderId:this.documentPaths$.value?.folderId,clientOrganizationId:t?.clientOrganizationId,parentFolderId:"root"};if(this.userPermissionService?.hasEditAccess({folderId:this.documentPaths$.value?.veltFolderId??""})){let s=Dr(this.functions,Ir({url:st?.cloudFunction?.sdkProxy,apiProxyDomain:this.configService?.getApiProxyDomain()}));yield Ad({methodName:"createFolder",data:{type:"createFolder",metadata:o},getSdkProxy:s,userId:this.authService.getUser()?.userId??""})}}}}catch(t){this.loggingService.catch("Error in updateFolderMetadata: ",t)}})}updateDocumentMetadata(){return I(this,null,function*(){try{if(this.db&&this.authService.getUser()){let t=this.documentPaths$.value;if(t){let i=this.getDocumentIds();i.find(s=>s.documentId===t.documentId)||i.push({documentId:t.documentId??"",clientDocumentId:t.clientDocumentId??""});let o=i.map(s=>I(this,null,function*(){let a=new PT;this.clientDocumentMetadataMap?.[s.clientDocumentId]&&(a=x(x({},this.clientDocumentMetadataMap[s.clientDocumentId]),a)),a.apiKey=this.configService?.getApiKey()??"",a.documentId=s.documentId,a.clientDocumentId=s.clientDocumentId,a.organizationId=t.organizationId,a.clientOrganizationId=t.clientOrganizationId,a.pageInfo=Cg(s.clientDocumentId);let c=t?.folderId,l=t?.veltFolderId;a?.pageInfo?.deviceInfo&&delete a?.pageInfo?.deviceInfo;let u=!0,d=this.documentMetadata$.value?.[s.documentId];if(c&&l){let f=this.getDocumentMetadata(s?.documentId??"")??(yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:s?.documentId??"",organizationId:t?.organizationId??"",field:"metadata"}}));f?.clientDocumentId&&!f?.errorCode?f?.folderId&&(f?.folderId!==c||f?.veltFolderId!==l)?(this.loggingService.catch(`Folder id mismatch for document ${s?.clientDocumentId??""}`),u=!1):f?.folderId===c?(c&&(a.folderId=c),l&&(a.veltFolderId=l)):(this.loggingService.catch(`Document ${s?.clientDocumentId??""} is not in the folder ${c??""}`),u=!1):(c&&(a.folderId=c),l&&(a.veltFolderId=l))}if(d){let f={};Object.entries(a).forEach(([g,p])=>{f[g]=p}),ki(f,d)&&(u=!1)}u&&this.userPermissionService?.hasEditAccess({documentId:s?.documentId??"",folderId:t?.allDocuments&&t?.veltFolderId?t?.veltFolderId:void 0})&&(yield this.commonDbService?.updateData({feature:"documentMetadata",data:JSON.parse(JSON.stringify(a)),properties:{organizationId:t?.organizationId??"",documentId:s?.documentId??""}}))}));yield Promise.allSettled(o),yield this.fetchDocumentMetadata(i)}}}catch(t){this.loggingService.catch("Error in updateDocumentMetadata: ",t)}})}updateDocumentLocationMetadata(t){return I(this,null,function*(){try{if(this.db&&this.authService.getUser()){let i=this.documentPaths$.value;if(i){let o=this.getDocumentIds();o.find(s=>s.documentId===i.documentId)||o.push({documentId:i.documentId??"",clientDocumentId:i.clientDocumentId??""});for(let s of o){let a=yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:s?.documentId??"",organizationId:i?.organizationId??"",field:"metadata"}});a?.errorCode&&(a={});let c=[];for(let l of t){let u=new FT;u.locationId=l?.locationId,u.veltLocationId=CC(l?.location?.id??""),u.location=l?.location,u.pageInfo=Cg(s?.clientDocumentId),u?.pageInfo?.deviceInfo&&delete u?.pageInfo?.deviceInfo;let d=le(x({},a),{[v.FIREBASE_PARTIAL_PATH_LOCATIONS]:le(x({},a[v.FIREBASE_PARTIAL_PATH_LOCATIONS]??{}),{[l?.locationId]:u})});this.commonDbService?.shouldUseFirestore()||c.push(this.commonDbService?.updateData({feature:"documentMetadata",data:JSON.parse(JSON.stringify(d)),properties:{documentId:s?.documentId??"",organizationId:i?.organizationId??""}}));let f=this.locationMetadata$.value;if(f||(f={}),l?.location?.id){let g=f?.[s.documentId],p=g?.[l?.location?.id??""];f&&(g||(f[s.documentId]={}),p||(f[s.documentId][l?.location?.id??""]={}),f[s.documentId][l?.location?.id??""]=le(x({},p),{location:l?.location})),Object.keys(f||{}).length>0&&this.locationMetadata$.next(f)}}yield Promise.allSettled(c)}}}}catch(i){this.loggingService.catch("Error in updateDocumentLocationMetadata: ",i)}})}genarateLocationId(t){try{return t&&typeof t=="object"?Tr(JSON.stringify(Sd(t))):0}catch(i){return this.loggingService.catch("Error in genarateLocationId: ",i),0}}removeCustomLocation(t,i="internal"){try{let o=this.genarateLocationId(t),s=this.locations$.value;s[o]&&(delete s[o],this.locations$.next(x({},s)),i!=="internal"&&this.isDocumentIdInDebounceQueue&&(this.draftLocationMap.locations=this.draftLocationMap.locations.filter(a=>a.id!==t.id)))}catch(o){this.loggingService.catch("Error in DocService removeLocation:",o)}}removeCustomLocationId(t,i="internal"){try{this.loggingService.log("%c[WB] Calling FUNCTION: removeCustomLocationId","color: green;");let o=this.locations$.value;Object.entries(o).forEach(([s,a])=>{a.location.id===t&&(delete o[s],this.locations$.next(x({},o)),i!=="internal"&&this.isDocumentIdInDebounceQueue&&(this.draftLocationMap.locations=this.draftLocationMap.locations.filter(c=>c.id!==t)))})}catch(o){this.loggingService.catch("Error in DocService removeCustomLocationId:",o)}}getLocationByClientLocationId(t){try{let i=this.getLocation()?.location;if(i?.id===t)return i;{let o=this.getLocations();Object.keys(o).forEach(s=>{let a=o[s];a.location?.id===t&&(i=a.location)})}return i}catch(i){this.loggingService.catch("Error in DocService getLocationByClientLocationId:",i);return}}removeLocationIfNotInDom(){try{let t=this.locations$.value,i=document.querySelectorAll(`[${v.ATTRIBUTES.VELT_LOCATION}]`),o=[];i.forEach(s=>{let a=s.getAttribute(v.ATTRIBUTES.VELT_LOCATION);if(a){let c=JSON.parse(a),l=this.genarateLocationId(c);o.push(l)}}),Object.keys(t).forEach(s=>{let a=t[s];o.includes(a.locationId)||delete t[s]}),this.locations$.next(x({},t))}catch(t){this.loggingService.catch("Error in DocService removeLocationIfNotInDom:",t)}}getLocations$(){try{return this.locations$.asObservable()}catch(t){return this.loggingService.catch("Error in DocService getLocations$:",t),ue({})}}getLocations(){try{return this.locations$.value}catch(t){return this.loggingService.catch("Error in DocService getLocations:",t),{}}}getLocationFromElement(t){try{this.loggingService.log("%c[WB] Calling FUNCTION: getLocationFromElement","color: green;");let i=null;if(t?.getAttribute(v.ATTRIBUTES.VELT_LOCATION)?i=t:i=t.closest(`[${v.ATTRIBUTES.VELT_LOCATION}]`),i){let o=i?.getAttribute(v.ATTRIBUTES.VELT_LOCATION);if(o){let s=JSON.parse(o);return{locationId:this.genarateLocationId(s),location:s}}}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 t={};return document.querySelectorAll(`[${v.ATTRIBUTES.VELT_LOCATION}], [${v.ATTRIBUTES.VELT_LOCATION_ID}]`).forEach(o=>{if(o.getAttribute(v.ATTRIBUTES.VELT_LOCATION)){let s=this.getLocationFromElement(o);s?.locationId&&(t[s.locationId]={element:o,location:s})}else if(o.getAttribute(v.ATTRIBUTES.VELT_LOCATION_ID)){let s=o.getAttribute(v.ATTRIBUTES.VELT_LOCATION_ID);if(s){let a=this.getLocationByClientLocationId(s);a?.locationId&&(t[a.locationId]={element:o,location:a});let c={id:s},l=this.genarateLocationId(c);t[s]={element:o,location:{locationId:l,location:c}}}}}),t}catch(t){return this.loggingService.catch("Error in DocService getElementMapWithLocation:",t),{}}}getAdditionLocationFromElement(t){try{this.loggingService.log("%c[WB] Calling FUNCTION: getAdditionLocationFromElement","color: green;");let i;if(i=t?.closest(`[${v.ATTRIBUTES.VELT_LOCATION}], [${v.ATTRIBUTES.VELT_LOCATION_ID}]`),i){if(i?.getAttribute(v.ATTRIBUTES.VELT_LOCATION)){let o=i?.getAttribute(v.ATTRIBUTES.VELT_LOCATION);if(o)return JSON.parse(o)}else if(i?.getAttribute(v.ATTRIBUTES.VELT_LOCATION_ID)){let o=i?.getAttribute(v.ATTRIBUTES.VELT_LOCATION_ID);if(o)return{id:o}}}return null}catch(i){return this.loggingService.catch("Error in DocService getAdditionLocationFromElement:",i),null}}getAdditionalDocumentIdFromElement(t){try{return t?.closest(`[${v.ATTRIBUTES.VELT_DOCUMENT_ID}]`)?.getAttribute(v.ATTRIBUTES.VELT_DOCUMENT_ID)||null}catch(i){return this.loggingService.catch("Error in DocService getAdditionalDocumentIdFromElement:",i),null}}getDocumentMetadata(t){try{return t?this.documentMetadata$.value?.[t]||null:this.documentMetadata$.value?.[this.documentPaths$.value?.documentId??""]||null}catch(i){return this.loggingService.catch("Error in DocService getDocumentMetadata:",i),null}}getAllDocumentMetadata$(t){return this.getAllDocumentMetadataMap$().pipe(fe(i=>i?.[t??this.documentPaths$.value?.documentId??""]||null),it(Ft))}getAllDocumentMetadata(){try{return Object.values(this.documentMetadata$.value||{})}catch(t){return this.loggingService.catch("Error in DocService getAllDocumentMetadata:",t),[]}}getAllDocumentMetadataMap$(){return this.documentMetadata$.asObservable().pipe(fe(t=>t||{}),it(Ft))}getAllDocumentMetadataMap(){try{return this.documentMetadata$.value||{}}catch(t){return this.loggingService.catch("Error in DocService getAllDocumentMetadata:",t),{}}}getDocumentMetadataOfAvailableDocuments(){try{this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentMetadataOfAvailableDocuments","color: green;");let t=this.documentMetadata$.value||{},i={},o=this.documentPaths$.value?.veltFolderId,s=this.documentPaths$.value?.allDocuments;if(o&&s)Object.values(t).forEach(a=>{a?.documentId&&a?.veltFolderId===o&&(i[a.documentId]=a)});else{let a=this.documentIds$.value;if(a?.length)a.forEach(c=>{let l=t?.[c.documentId];l&&(i[c.documentId]=l)});else if(this.documentPaths$.value?.documentId){let c=t?.[this.documentPaths$.value?.documentId];c&&(i[this.documentPaths$.value?.documentId]=c)}}return Object.values(i)}catch(t){return this.loggingService.catch("Error in DocService getDocumentMetadataOfAvailableDocuments:",t),[]}}getDocumentMetadata$(t){return this.documentMetadata$.asObservable().pipe(fe(i=>i?.[t??this.documentPaths$.value?.documentId??""]||null),it(Ft))}setDocumentMetadata(t,i){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocumentMetadata","color: green;");let o=JSON.parse(JSON.stringify(this.documentMetadata$.value??{}));o[t]=i,this.documentMetadata$.next(o)}catch(o){this.loggingService.catch("Error in DocService setDocumentMetadata:",o)}}setAllDocumentMetadata(t){try{this.loggingService.log("%c[WB] Calling FUNCTION: setAllDocumentMetadata","color: green;"),this.documentMetadata$.next(t)}catch(i){this.loggingService.catch("Error in DocService setAllDocumentMetadata:",i)}}getOrganizationMetadata(t){return this.organizationMetadata$.value?.[t]||null}getOrganizationMetadata$(t){return this.organizationMetadata$.asObservable().pipe(fe(i=>i?.[t]||null))}getOrganizationMetadataMap$(){return this.organizationMetadata$.asObservable().pipe(fe(t=>t||{}),it(Ft))}getCustomerMetadata(){return this.customerMetadata$.value}getCustomerMetadata$(){return this.customerMetadata$.asObservable()}getOrganizationConfig$(){return this.organizationConfig$.asObservable().pipe(it(Ft))}getOrganizationConfig(){return this.organizationConfig$.value}setOrganizationConfig(t){try{this.loggingService.log("%c[WB] Calling FUNCTION: setOrganizationConfig","color: green;");let i=JSON.parse(JSON.stringify(t));this.organizationConfig$.next(i)}catch(i){return this.loggingService.catch("Error in DocService setOrganizationConfig:",i),!1}return!0}getMetadataFromType(t,i){try{switch(t){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(o){this.loggingService.catch("Error in DocService getMetadataFromType:",o);return}}getDefaultMetadata({clientDocumentId:t,documentId:i}){try{let o=this.documentPaths$.value;if(!o)return;let s=t||o.clientDocumentId,a=i||o.documentId,c=this.getDocumentMetadata(a);if(!c)return;let l=c?.folderId,u=c?.veltFolderId;return x(x({apiKey:this.configService.getApiKey()??void 0,clientDocumentId:s,clientOrganizationId:o.clientOrganizationId,documentId:a,organizationId:o.organizationId},l?{folderId:l}:{}),u?{veltFolderId:u}:{})}catch(o){this.loggingService.catch("Error in DocService getDefaultMetadata:",o);return}}getBaseMetadata(t,i){try{let o,s;i?.element?o=this.getAdditionalDocumentIdFromElement(i.element)||void 0:i?.clientDocumentId&&(o=i.clientDocumentId),o&&(s=this.generateDocumentId(o));let a=this.getMetadataFromType(t,i),c=this.getDefaultMetadata({clientDocumentId:o,documentId:s}),l=a||c||{};return l.sdkVersion=jr(),l}catch(o){return this.loggingService.catch("Error in DocService getBaseMetadata:",o),{}}}getServerId({documentId:t,organizationId:i}){try{return t&&(t=this.generateDocumentId(t)),i&&(i=this.generateOrganizationId(i)),{documentId:t,organizationId:i}}catch(o){return this.loggingService.catch("Error in DocService getServerId:",o),null}}fetchDocuments(t){return I(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 o=[];if(!t?.organizationId)return this.loggingService.catch("Error in fetchDocuments: organizationId is required"),[];if(t?.folderId){let a=wo(t?.folderId);o.push(Ji("metadata.veltFolderId","==",a))}return t?.documentIds?.length&&!t?.allDocuments&&o.push(Ji("metadata.documentId","in",t?.documentIds?.map(a=>this.generateDocumentId(a)).slice(0,30))),yield this.commonDbService?.queryData({feature:"allDocuments",properties:{firestoreQuery:o,apiKey:this.apiKey??"",organizationId:this.generateOrganizationId(t?.organizationId)??this.documentPaths$.value?.organizationId,documentId:this.documentPaths$.value?.documentId}})}catch(i){return this.loggingService.catch("Error in DocService fetchDocuments:",i),[]}})}fetchLocations(t){return I(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 o=[];if(!t?.organizationId)return this.commonDbService?.shouldUseFirestore()&&this.loggingService.catch("Error in fetchLocations: organizationId is required"),[];if(t?.folderId){let a=wo(t?.folderId);o.push(Ji("metadata.veltFolderId","==",a))}return t?.documentIds?.length&&!t?.allDocuments&&o.push(Ji("metadata.documentId","in",t?.documentIds?.map(a=>this.generateDocumentId(a)).slice(0,30))),yield this.commonDbService?.queryData({feature:"allLocations",properties:{firestoreQuery:o,apiKey:this.apiKey??"",organizationId:this.generateOrganizationId(t?.organizationId)??this.documentPaths$.value?.organizationId,documentId:this.documentPaths$.value?.documentId}})}catch(i){return this.loggingService.catch("Error in DocService fetchLocations:",i),[]}})}updateDocuments(t){return I(this,null,function*(){try{if(typeof t=="object"&&(t=JSON.parse(JSON.stringify(t??{}))),!this.authService.getUser())return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),[];let{organizationId:o,documents:s,folderId:a}=t;if(!o&&(o=this.documentPaths$.value?.clientOrganizationId,!o))return this.loggingService.catch("Error in updateDocuments: organizationId is required"),[];let c=Ts(o);if(!s||s.length===0)return this.loggingService.catch("Error in updateDocuments: documents is required"),[];let l=[],u=this.documentMetadata$.value??{};for(let d of s)if(d?.documentId){d.organizationId=c,d.clientOrganizationId=o,d.clientDocumentId=d.documentId;let f=da(d.documentId);d.documentId=f,d.apiKey=this.configService.getApiKey()??void 0,(a||this.documentPaths$.value?.folderId)&&(d.folderId=a||this.documentPaths$.value?.folderId,d.veltFolderId=wo(a||this.documentPaths$.value?.folderId||""));let g=()=>{if(a&&this.documentPaths$.value?.folderId&&a!==this.documentPaths$.value?.folderId)return;let _=u?.[f];_?u[f]=x(x({},_),d):u[f]=d},p=yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:f,organizationId:c,field:"metadata"}});if(p?.errorCode&&(p={}),p&&p.apiKey&&p.folderId&&a&&p.folderId!=d.folderId){this.loggingService.catch(`Error in updateDocuments: document ${d.clientDocumentId} already exists with different folderId: ${p.folderId}`);continue}if(p&&p.apiKey&&!p.folderId&&d.folderId){this.loggingService.catch(`Error in updateDocuments: document ${d.clientDocumentId} already exists, move this document to folder with REST API`);continue}g(),d&&this.commonDbService&&this.userPermissionService?.hasEditAccess({documentId:d?.documentId??""})&&l.push(this.commonDbService.updateData({feature:"documentMetadata",data:JSON.parse(JSON.stringify(d)),properties:{organizationId:c,documentId:f}}))}yield Promise.all(l),this.setAllDocumentMetadata(u)}catch(i){return this.loggingService.catch("Error in DocService updateDocuments:",i),[]}})}updateLocations(t){return I(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:o,locations:s,documentIds:a}=t;if((!a||a.length===0)&&(a=this.documentIds$.value.map(d=>d.clientDocumentId)??[],a.length===0))return this.loggingService.catch("Error in updateLocations: documentId is required"),[];if(!o&&(o=this.documentPaths$.value?.clientOrganizationId,!o))return this.loggingService.catch("Error in updateLocations: organizationId is required"),[];if(!s||s.length===0)return this.loggingService.catch("Error in updateLocations: locations is required"),[];let c=a.map(d=>da(d)),l=[],u=this.locationMetadata$.value;u||(u={}),c.forEach(d=>{s.forEach(f=>{let g=this.location$.value;if(f?.id===g?.location?.id&&this.location$.next({locationId:g?.locationId,location:f}),f?.id){delete f?.metadata;let p=CC(f.id),_=u?.[d],T=_?.[f.id];u&&(_||(u[d]={}),T||(u[d][f.id]={}),u[d][f.id]=le(x({},T),{location:f})),f&&this.commonDbService&&l.push(this.commonDbService.updateData({feature:"locationMetadata",data:JSON.parse(JSON.stringify({location:f})),properties:{organizationId:Ts(o),documentId:d,id:p}}))}})}),yield Promise.all(l),Object.keys(u||{}).length>0&&this.locationMetadata$.next(u)}catch(i){return this.loggingService.catch("Error in DocService updateLocations:",i),[]}})}fetchFolders(t){return I(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 o=[];if(!t?.organizationId)return this.loggingService.catch("Error in fetchFolders: organizationId is required"),{data:[],parentFolders:[]};let s=[],a=this.generateOrganizationId(t?.organizationId);if(t?.folderId){let c=wo(t?.folderId);o=yield this.commonDbService?.getData({feature:"folder",properties:{folderId:c,apiKey:this.apiKey??"",organizationId:a,documentId:this.documentPaths$.value?.documentId}}),o&&(o=[o]),s=yield this.commonDbService?.queryData({feature:"allFolders",properties:{firestoreQuery:[Ji("metadata.veltParentFolderId","==",c)],folderId:c,apiKey:this.apiKey??"",organizationId:a,documentId:this.documentPaths$.value?.documentId}})}else o=yield this.commonDbService?.queryData({feature:"allFolders",properties:{apiKey:this.apiKey??"",organizationId:a,documentId:this.documentPaths$.value?.documentId}});return{data:o,parentFolders:s}}catch(i){return this.loggingService.catch("Error in DocService getFoldersRequest:",i),{data:[],parentFolders:[]}}})}getDocumentIam$(){return this.authService.getUser$().pipe(mt(t=>t?this.documentPaths$.pipe(mt(i=>i?.documentIam?this.commonDbService?.dbListener({feature:"documentIam",properties:{documentId:i.documentId,organizationId:i.organizationId,isCollection:!1}}).pipe(fe(o=>o?.data?.docIamConfig??o?.data),it((o,s)=>JSON.stringify(o??{})===JSON.stringify(s??{}))):ue(null))):ue(null)))}getDocumentAccessType(t){try{return t&&t.features&&t.features.all?t.features.all.restricted?wt.RESTRICTED:wt.PUBLIC:t&&t.documentAccessType?t.documentAccessType:wt.PUBLIC}catch(i){return this.loggingService.catch("Error in DocService getDocumentAccessType:",i),wt.PUBLIC}}changeDocumentAccessType(t){return I(this,null,function*(){try{let i=this.documentPaths$.value;if(i){let o=yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:i?.documentId??"",organizationId:i?.organizationId??"",field:"docIamConfig"}});if(o?.errorCode)return;switch(delete o.documentAccessType,o.features||(o.features={}),o.features.all||(o.features.all={}),t){case wt.PUBLIC:o.features.all.restricted=!1;break;case wt.RESTRICTED:o.features.all.restricted=!0,o.features.all.guestMode=!1;break;default:break}this.commonDbService?.updateData({feature:"documentAccessType",data:JSON.parse(JSON.stringify(o)),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(t){return this.loggingService.catch("Error in DocService getUserIdForAnalytics:",t),""}}setUIState(t){try{this.uiState.next(x(x({},this.uiState.value),t))}catch(i){this.loggingService.catch("Error in DocService setUIState:",i)}}getUIState$(){return this.uiState.asObservable()}};e.\u0275fac=function(i){return new(i||e)(w(Lt),w(Cr),w(Wy),w(Ev),w(Rr),w(_e),w(zo),w(qo),w(ec),w(It),w(dr),w(li))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let n=e;return n})();var zt=(()=>{let e=class e{constructor(t,i,o,s,a){this.analyticsService=t,this.authService=i,this.coreActionsService=o,this.docService=s,this.loggingService=a,this.resolveOrganizationUsers=new Y(!0),this.resolveFolderUsers=new Y(!0),this.resolveDocumentUsers=new Y(!0),this.unresolvedUsers=new Y([]),this.resolveTimeout=60*1e3,this.resolveAttempts=new Map,this.subscriptions=new gt,this.userDataProvider$=new Y(null),this.anonymousUserDataProvider$=new Y(null),this.userIdByEmailCache={},this.userById$=new Y({}),this.customContactUserById$=new Y({}),this.userByIdCalled$=new Y({}),this.pendingResolutions=new Set,this.getUserById=c=>{try{let l=this.userById$.value?.[c],u=this.customContactUserById$.value?.[c];return u?l?x(x({},l),u):u:l}catch(l){this.loggingService.catch("Error in UsersService getUserById:",l);return}};try{this.docService.setUsersService(this),this.analyticsService.setUserService(this),this.authService.setUsersService(this),this.docService.getDocumentPaths$().pipe(Ct(c=>!!c),mt(()=>this.getUnresolvedUsers$().pipe(Ct(c=>c.length>0),Au(300),Nt(20),mt(c=>{let l=this.docService.getOrganizationConfig()?.organizationId;return this.commonDbService?this.commonDbService?.dbListener({feature:"allOrganizationUsers",properties:{organizationId:l,isCollection:!0,useQuery:!0,firestoreQuery:[MM(Ji("user.userId","in",c.slice(0,20)))]}}).pipe(fe(u=>u?.data),Ks(u=>{if(u&&typeof u=="object"){delete u.undefined,delete u.null;let d=Object.values(u??{});this.setUserByIds(d.map(g=>g.user));let f=c.filter(g=>!d.some(p=>p.user.userId===g));f.length!==c.length&&this.setUnresolvedUsers(f)}})):ue([])})))).subscribe()}catch(c){this.loggingService.catch("Error in UsersService constructor:",c)}}setCommonDbService(t){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setCommonDbService","color: green;"),this.commonDbService=t}catch(i){this.loggingService.catch("Error in UsersService setCommonDbService:",i)}}setContactService(t){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setContactService","color: green;"),this.contactService=t}catch(i){this.loggingService.catch("Error in UsersService setContactService:",i)}}ngOnDestroy(){try{this.subscriptions.unsubscribe(),this.pendingResolutions.clear(),this.resolveAttempts.clear()}catch(t){this.loggingService.catch("Error in UsersService ngOnDestroy:",t)}}isResolverForFeatureDisabled(t){let i=this.userDataProvider$.getValue();try{switch(t){case"allOrganizationUsers":return i?!this.resolveOrganizationUsers.value:!0;case"allFolderUsers":return i?!this.resolveFolderUsers.value:!0;case"allDocumentUsers":return i?!this.resolveDocumentUsers.value:!0;default:return!1}}catch(o){return this.loggingService.catch("Error in UsersService isResolverForFeatureDisabled:",o),!1}}resolveUsers(u){return I(this,arguments,function*({userIds:t,forceResolve:i,feature:o,organizationId:s,skipUserCheck:a=!1,uniqueId:c,moduleName:l}){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: resolveUsers","color: green;");let d=!1;if(o&&(d=this.isResolverForFeatureDisabled(o)),d)return{};{let f={},g=[],p={};if(t?.forEach(_=>{let T=this.getUserById(_);T?f[_]=T:this.userByIdCalled$.getValue()[_]?i&&g.push(_):(g.push(_),this.userByIdCalled$.next(le(x({},this.userByIdCalled$.getValue()),{[_]:!0})))}),g.length>0){let _=c||J();this.coreActionsService.triggerAction($.USER_RESOLVER,{event:L.Events.Resolver.USER_RESOLUTION_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:_,moduleName:l,methodName:xn.RESOLVE_USERS,source:"internal",payload:{userIds:g,organizationId:s,feature:o,forceResolve:i,skipUserCheck:a,externalUserDataProviderAvailable:this.externalUserDataProviderAvailable()}});let T={};try{let D,b=new Promise((G,M)=>{D=setTimeout(()=>{M(new Error("User resolution timeout"))},this.userDataProvider$.getValue()?.config?.resolveTimeout||this.userDataProvider$.getValue()?.resolveTimeout||this.resolveTimeout)});T=yield Promise.race([this.getUsersFromDB({userIds:g,organizationId:s,skipUserCheck:a}).finally(()=>{clearTimeout(D)}),b]),this.analyticsService.trackEvent(L.Events.Resolver.USER_RESOLVER_GET,{sourceMethod:"resolveUsers",source:"sdk",userIds:g}),this.coreActionsService.triggerAction($.USER_RESOLVER,{event:L.Events.Resolver.USER_RESOLUTION_RESULT,timestamp:new Date().getTime(),uniqueId:_,methodName:xn.RESOLVE_USERS,moduleName:l,source:"internal",payload:{result:T,userIds:g,externalUserDataProviderAvailable:this.externalUserDataProviderAvailable()}})}catch(D){this.loggingService.catch("Error in UsersService resolveUsers getUsers:",D,{userIds:g}),this.coreActionsService.triggerAction($.USER_RESOLVER,{event:L.Events.Resolver.USER_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:_,methodName:xn.RESOLVE_USERS,moduleName:l,source:"internal",payload:{error:D,userIds:g,externalUserDataProviderAvailable:this.externalUserDataProviderAvailable()}})}finally{g?.forEach(D=>{if(!T[D]){let b=new Set([...this.getUnresolvedUsers(),D]);this.unresolvedUsers.next(Array.from(b)),T[D]={userId:D,name:`User ${D}`}}})}Object.entries(T).forEach(([D,b])=>{b&&(f[D]=T?.[D],p[D]=T?.[D])})}return Object.keys(p).length>0&&(this.authService.setOptionalPropertiesToUsers(Object.values(p)),this.mergeUsersIntoStore(Object.values(p)),Object.keys(p).forEach(_=>{let T=this.getUserById(_);T&&(f[_]=T)})),f}}catch(d){this.loggingService.catch("Error in UsersService resolveUsers:",d);let f=c||J();return this.coreActionsService.triggerAction($.USER_RESOLVER,{event:L.Events.Resolver.USER_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:f,methodName:xn.RESOLVE_USERS,moduleName:l,source:"internal",payload:{error:d,userIds:t,externalUserDataProviderAvailable:this.externalUserDataProviderAvailable()}}),{}}})}getUnresolvedUsers$(){return this.unresolvedUsers.asObservable()}getUnresolvedUsers(){this.loggingService.log("%c[WB] Calling UsersService FUNCTION: getUnresolvedUsers","color: green;");try{return JSON.parse(JSON.stringify(this.unresolvedUsers.getValue()))}catch(t){return this.loggingService.catch("Error in UsersService getUnresolvedUsers:",t),[]}}setUnresolvedUsers(t){this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setUnresolvedUsers","color: green;");try{if(Array.isArray(t)){let i=JSON.parse(JSON.stringify(t));this.unresolvedUsers.next(i)}}catch(i){this.loggingService.catch("Error in UsersService setUnresolvedUsers:",i)}}getUsersFromDB(s){return I(this,arguments,function*({userIds:t,organizationId:i,skipUserCheck:o=!1}){this.loggingService.log("%c[WB] Calling UsersService FUNCTION: getUsersFromDB","color: green;");try{let a=this.userDataProvider$.getValue();if(a){if(a.config?.getConfig?.url){if(i||(i=this.docService.getOrganizationConfig()?.organizationId),!i)return this.loggingService.catch("Error in getUsersFromDB: organizationId is required when using getConfig"),{};let d={organizationId:i,userIds:t},f=yield Ht(a.config.getConfig.url,a.config.getConfig.headers,d,!0,a.config.getConfig.credentials);return f.statusCode!==200?(this.loggingService.catch(`Error in getUsersFromDB: config-based request failed with statusCode ${f.statusCode}. Message: ${f.message||"Unknown error"}`),{}):f.data??{}}let u=yield a.get(t);if(u&&typeof u=="object"&&"success"in u&&"statusCode"in u&&typeof u.success=="boolean"&&typeof u.statusCode=="number"){let d=u;return d.statusCode===200&&d.data?d.data:(this.loggingService.catch(`Error in getUsersFromDB: provider returned error response with statusCode ${d.statusCode}`),{})}return u}if(i||(i=this.docService.getOrganizationConfig()?.organizationId),!i)return{};let c=(yield this.getUsersFromDBWithBatching({userIds:t,organizationId:i,skipUserCheck:o}))??[];this.contactService?.setResolvedUsers(c.flat());let l={};return c.forEach(u=>{u.forEach(d=>{d?.user?.userId&&(l[d.user.userId]=d.user)})}),l}catch(a){return this.loggingService.catch("Error in UsersService getUsersFromDB:",a),{}}})}getUsersFromDBWithBatching(s){return I(this,arguments,function*({userIds:t,organizationId:i,skipUserCheck:o=!1}){try{if(!t?.length)return[];let a=[];for(let u=0;u<t.length;u+=30)a.push(t.slice(u,u+30));let c=a.map((u,d)=>I(this,null,function*(){try{return(yield this.commonDbService?.queryData({feature:"allOrganizationUsers",properties:{organizationId:i,useCollectionGroup:!1,isCollection:!0,firestoreQuery:[Ji("user.userId","in",u)],skipUserCheck:o}}))||[]}catch(f){return this.loggingService.catch(`Error in batch ${d+1}:`,f),[]}}));return yield Promise.all(c)}catch(a){return this.loggingService.catch("Error in getUsersFromDBWithBatching:",a),[]}})}getTemporaryUsersFromDBWithBatching(s){return I(this,arguments,function*({userIds:t,organizationId:i,resourceIds:o}){try{if(!t?.length||!o?.length)return[];let a=[];for(let _=0;_<t.length;_+=30)a.push(t.slice(_,_+30));let c=[];for(let _=0;_<o.length;_+=30)c.push(o.slice(_,_+30));let l=[],u=0,d=(_,T)=>I(this,null,function*(){try{return((yield this.commonDbService?.queryData({feature:"allPermissionsUsers",properties:{organizationId:i,useCollectionGroup:!1,isCollection:!0,firestoreQuery:[MM(Ji("userId","in",_),Ji("veltResourceId","in",T))]}}))??[])||[]}catch(D){return this.loggingService.catch(`Error in batch ${u+1}:`,D),[]}});for(let _ of a)for(let T of c)l.push(d(_,T)),u++;return(yield Promise.all(l)).flat().filter((_,T,D)=>T===D.findIndex(b=>b.userId===_.userId&&b.resourceId===_.resourceId))}catch(a){return this.loggingService.catch("Error in getTemporaryUsersFromDBWithBatching:",a),[]}})}getResolveOrganizationUsers$(){return this.resolveOrganizationUsers.asObservable()}getResolveFolderUsers$(){return this.resolveFolderUsers.asObservable()}getResolveDocumentUsers$(){return this.resolveDocumentUsers.asObservable()}getUserById$(){try{return this.loggingService.log("%c[WB] Calling UsersService FUNCTION: getUserById$","color: green;"),Zr([this.userById$,this.customContactUserById$]).pipe(fe(([t,i])=>this.applyContactOverlay(t,i)),it(Ft))}catch(t){return this.loggingService.catch("Error in UsersService getUserById$:",t),ue({})}}applyContactOverlay(t,i){let o=x({},t??{});return Object.entries(i??{}).forEach(([s,a])=>{o[s]=x(x({},o[s]??{}),a)}),o}setUserByIds(t){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setUserByIds","color: green;"),this.mergeUsersIntoStore(t)}catch(i){this.loggingService.catch("Error in UsersService setUserByIds:",i)}}setContactListUsers(t){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setContactListUsers","color: green;");let i={};(t??[]).forEach(o=>{let s=o?.userId;s&&(i[s]=JSON.parse(JSON.stringify(o)))}),this.customContactUserById$.next(i)}catch(i){this.loggingService.catch("Error in UsersService setContactListUsers:",i)}}getContactListUser(t){try{return this.customContactUserById$.value?.[t]}catch(i){this.loggingService.catch("Error in UsersService getContactListUser:",i);return}}mergeUsersIntoStore(t){try{let i=JSON.parse(JSON.stringify(this.userById$.getValue()??{}));(t??[]).forEach(o=>{let s=o?.userId;s&&(i[s]=x(x({},i?.[s]??{}),o))}),this.userById$.next(i)}catch(i){this.loggingService.catch("Error in UsersService mergeUsersIntoStore:",i)}}setUserDataProvider(t){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setUserDataProvider","color: green;");let i=t.config?.getConfig?.url,o="get"in t&&typeof t.get=="function";if(!i&&!o){this.loggingService.catch("DataProviders.user is invalid. The get method is missing or is not a function (and no getConfig provided).");return}this.userDataProvider$.next(t),t.config?.resolveUsersConfig?.organization===!1?this.resolveOrganizationUsers.next(!1):this.resolveOrganizationUsers.next(!0),t.config?.resolveUsersConfig?.folder===!1?this.resolveFolderUsers.next(!1):this.resolveFolderUsers.next(!0),t.config?.resolveUsersConfig?.document===!1?this.resolveDocumentUsers.next(!1):this.resolveDocumentUsers.next(!0)}catch(i){this.loggingService.catch("Error in UsersService setUserDataProvider:",i)}}setAnonymousUserDataProvider(t){try{if(this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setAnonymousUserDataProvider","color: green;"),!("resolveUserIdsByEmail"in t)||typeof t.resolveUserIdsByEmail!="function"){this.loggingService.catch("setAnonymousUserDataProvider is invalid. The resolveUserIdsByEmail method is missing or is not a function.");return}this.anonymousUserDataProvider$.next(t)}catch(i){this.loggingService.catch("Error in UsersService setAnonymousUserDataProvider:",i)}}resolveUserIdsByEmail(o){return I(this,arguments,function*({emails:t,uniqueId:i}){try{if(this.loggingService.log("%c[WB] Calling UsersService FUNCTION: resolveUserIdsByEmail","color: green;"),!t?.length)return{};let s=this.anonymousUserDataProvider$.getValue();if(!s||typeof s.resolveUserIdsByEmail!="function")return{};let a=[...new Set(t.filter(M=>!!M))];if(a.length===0)return{};let c={},l=[];if(a.forEach(M=>{let U=this.userIdByEmailCache[M];U?c[M]=U:l.push(M)}),l.length===0)return c;let u=this.docService.getOrganizationConfig()?.clientOrganizationId||"",d=this.docService.getDocumentPaths()?.clientDocumentId||"",f=this.docService.getDocumentPaths()?.folderId||"",g={organizationId:u,documentId:d,folderId:f,emails:l},p=i||J();this.coreActionsService.triggerAction($.USER_RESOLVER,{event:L.Events.Resolver.EMAIL_USER_ID_RESOLUTION_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:p,methodName:xn.RESOLVE_USER_IDS_BY_EMAIL,source:"internal",payload:{emails:l,organizationId:u,documentId:d,folderId:f}});let _=s.config?.resolveTimeout||this.resolveTimeout,T,D=new Promise((M,U)=>{T=setTimeout(()=>{U(new Error("resolveUserIdsByEmail timeout"))},_)}),b=s.config?.getRetryConfig||{retryCount:0,retryDelay:0},G=I(this,null,function*(){try{let M=yield kt(()=>s.resolveUserIdsByEmail(g),"resolveUserIdsByEmail",b);return M?.statusCode===200&&M?.data?M.data:(this.loggingService.catch(`Error in resolveUserIdsByEmail: provider returned statusCode ${M?.statusCode}. Message: ${M?.message||"Unknown error"}`),{})}finally{clearTimeout(T)}});try{let M=yield Promise.race([G,D]);return Object.entries(M).forEach(([U,k])=>{k&&(this.userIdByEmailCache[U]=k,c[U]=k,this.externalUserDataProviderAvailable()||this.docService.addUserInfoToOrganization({organizationId:this.docService.getOrganizationConfig()?.clientOrganizationId??"",user:{userId:k,name:U,email:U},currentUserId:this.authService.getUser()?.userId??""}).catch(S=>{this.loggingService.catch("Error in UsersService resolveUserIdsByEmail addUserInfoToOrganization:",S)}))}),this.coreActionsService.triggerAction($.USER_RESOLVER,{event:L.Events.Resolver.EMAIL_USER_ID_RESOLUTION_RESULT,timestamp:new Date().getTime(),uniqueId:p,methodName:xn.RESOLVE_USER_IDS_BY_EMAIL,source:"internal",payload:{result:M,emails:l}}),c}catch(M){return this.loggingService.catch("Error in UsersService resolveUserIdsByEmail (timeout/race):",M),this.coreActionsService.triggerAction($.USER_RESOLVER,{event:L.Events.Resolver.EMAIL_USER_ID_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:p,methodName:xn.RESOLVE_USER_IDS_BY_EMAIL,source:"internal",payload:{error:M,emails:l}}),c}}catch(s){return this.loggingService.catch("Error in UsersService resolveUserIdsByEmail:",s),{}}})}externalUserDataProviderAvailable(){try{return this.loggingService.log("%c[WB] Calling UsersService FUNCTION: externalUserDataProviderAvailable","color: green;"),!!this.commonDbService?.shouldUseFirestore()&&!!this.userDataProvider$.getValue()}catch(t){return this.loggingService.catch("Error in UsersService externalUserDataProviderAvailable:",t),!1}}userDataProviderAvailable(){try{return this.loggingService.log("%c[WB] Calling UsersService FUNCTION: userDataProviderAvailable","color: green;"),!!this.commonDbService?.shouldUseFirestore()}catch(t){return this.loggingService.catch("Error in UsersService userDataProviderAvailable:",t),!1}}};e.\u0275fac=function(i){return new(i||e)(w(Lt),w(Cr),w(It),w(zh),w(_e))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let n=e;return n})();var tc=class{static getFirestoreProdDbName(e,r){return r?.databaseURL?.includes("snippyly-plugin.firebaseio.com")||r?.databaseURL?.includes("snippyly-plugin-staging.firebaseio.com")?"sfdb":r?.storeDbId??(this.isTestingDb(r?.databaseURL??"")?"sdktest":`apikey${e.toLowerCase()}`)}static isTestingDb(e){try{return e.includes("-test")}catch(r){return H.error("Error in isTestingDb:",r),!1}}};var Ky=(()=>{let e=class e{constructor(t,i,o,s,a,c,l,u){this.loggingService=t,this.usersService=i,this.authService=o,this.functions=s,this.configService=a,this.commentAnnotationsResolverService=c,this.attachmentResolverService=l,this.coreActionsService=u,this.notificationActionTypeMap={[Ie.NEWLY_ADDED]:Qt.COMMENT_ANNOTATION_ADD,[Ie.ADDED]:Qt.COMMENT_ADD,[Ie.UPDATED]:Qt.COMMENT_UPDATE,[Ie.DELETED]:Qt.COMMENT_DELETE},this.additionalEventTypeMap={[Ie.STATUS_CHANGED]:Xn.STATUS_CHANGE,[Ie.PRIORITY_CHANGED]:Xn.PRIORITY_CHANGE,[Ie.ASSIGNED]:Xn.ASSIGN,[Ie.ACCESS_MODE_CHANGED]:Xn.ACCESS_MODE_CHANGE,[Ie.CUSTOM_LIST_CHANGED]:Xn.CUSTOM_LIST_CHANGE,[Ie.APPROVED]:Xn.APPROVE,[Ie.ACCEPTED]:Xn.ACCEPT,[Ie.REJECTED]:Xn.REJECT,[Ie.SUGGESTION_ACCEPTED]:Xn.SUGGESTION_ACCEPT,[Ie.SUGGESTION_REJECTED]:Xn.SUGGESTION_REJECT,[Ie.REACTION_ADDED]:Xn.REACTION_ADD,[Ie.REACTION_DELETED]:Xn.REACTION_DELETE,[Ie.SUBSCRIBED]:Xn.SUBSCRIBE,[Ie.UNSUBSCRIBED]:Xn.UNSUBSCRIBE}}setNotificationService(t){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: setNotificationService","color: green;"),this.notificationService=t}catch(i){this.loggingService.catch("Error in CommentUtilsService setNotificationService: ",i)}}setUserPermissionService(t){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: setUserPermissionService","color: green;"),this.userPermissionService=t}catch(i){this.loggingService.catch("Error in CommentUtilsService setUserPermissionService: ",i)}}getUserIdsToResolveFromComments(t){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: getUserIdsToResolveFromComments","color: green;");let i=new Set;for(let o of t){if(o?.from?.userId&&i.add(o?.from?.userId),o?.comments)for(let s of o?.comments){if(s?.from?.userId&&i.add(s?.from?.userId),s?.to)for(let a of s?.to)a?.userId&&i.add(a?.userId);if(s?.taggedUserContacts)for(let a of s?.taggedUserContacts)a?.userId&&i.add(a?.userId)}if(o?.assignedTo?.userId&&i.add(o?.assignedTo?.userId),o?.resolvedByUserId&&i.add(o?.resolvedByUserId),o?.suggestion?.resolvedBy?.userId&&i.add(o?.suggestion?.resolvedBy?.userId),o?.subscribedUsers)for(let s of Object.values(o?.subscribedUsers))s.user.userId&&i.add(s.user.userId);if(o?.unsubscribedUsers)for(let s of Object.values(o?.unsubscribedUsers))s.user.userId&&i.add(s.user.userId)}return Array.from(i)}catch(i){return this.loggingService.catch("Error in CommentUtilsService getUserIdsToResolveFromComments:",i),[]}}mergeCommentWithUser(t){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: mergeCommentWithUser","color: green;"),t?.from?.userId){let i=this.usersService.getUserById(t?.from?.userId);i&&(t.from=i)}if(t?.suggestion?.resolvedBy?.userId){let i=this.usersService.getUserById(t?.suggestion?.resolvedBy?.userId);i&&(t.suggestion.resolvedBy=i)}if(t?.comments)for(let i of t?.comments){if(i?.from?.userId){let s=this.usersService.getUserById(i?.from?.userId);s&&(i.from=s)}i?.to&&(i.to=i?.to?.map(s=>{if(s?.userId){let a=this.usersService.getUserById(s?.userId);if(a)return x(x({},s),a)}return s})),i?.taggedUserContacts&&(i.taggedUserContacts=i?.taggedUserContacts?.map(s=>{if(s?.contact){let a=this.usersService.getUserById(s?.contact?.userId);a&&(s.contact=a,(a?.name||a?.email)&&(s.text=`@${a?.name||a?.email}`))}return s}));let o=i?.taggedUserContacts?.filter((s,a,c)=>c.findIndex(l=>l.text===s.text)===a)||[];o.sort((s,a)=>(a.text?.length||0)-(s.text?.length||0)),o.forEach(s=>{if(s?.text){let a=new RegExp(rl(`{{${s.userId}}}`),"g");i.commentText?.includes(`@User ${s.userId}`)&&(a=new RegExp(rl(`@User ${s.userId}`),"g")),i.commentText=i.commentText?.replaceAll(a,s.text),i.commentHtml=i.commentHtml?.replaceAll(a,s.text)}})}if(t?.assignedTo?.userId){let i=this.usersService.getUserById(t?.assignedTo?.userId);i&&(t.assignedTo=i)}if(t?.resolvedByUserId){let i=this.usersService.getUserById(t?.resolvedByUserId);i&&(t.resolvedByUser=i)}if(t?.subscribedUsers)for(let i of Object.values(t?.subscribedUsers)){let o=this.usersService.getUserById(i.user.userId);o&&t?.subscribedUsers?.id?.user&&(t.subscribedUsers.id.user=o)}if(t?.unsubscribedUsers)for(let i of Object.values(t?.unsubscribedUsers)){let o=this.usersService.getUserById(i.user.userId);o&&t?.unsubscribedUsers?.id?.user&&(t.unsubscribedUsers.id.user=o)}return t}catch(i){return this.loggingService.catch("Error in CommentUtilsService mergeCommentWithUser:",i),t}}formatCommentData(t){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: formatCommentData","color: green;"),t?.comments?.forEach(i=>{i?.commentText&&i?.commentText?.length>0&&(i.isCommentTextAvailable=!0)}),t?.viewedBy&&delete t.viewedBy,t?.unread!==void 0&&delete t.unread,t?.resolvedByUser!==void 0&&delete t.resolvedByUser,t?.comments&&t.comments.forEach(i=>{i?.reactionAnnotations&&delete i.reactionAnnotations}),this.usersService.userDataProviderAvailable()){if(t?.from?.userId&&(t.from={userId:t.from.userId}),t?.assignedTo?.userId&&(t.assignedTo={userId:t.assignedTo.userId}),t?.subscribedUsers)for(let i of Object.keys(t?.subscribedUsers))t.subscribedUsers[i].user={userId:t?.subscribedUsers[i].user.userId};if(t?.unsubscribedUsers)for(let i of Object.keys(t?.unsubscribedUsers))t.unsubscribedUsers[i].user={userId:t?.unsubscribedUsers[i].user.userId};t?.suggestion?.resolvedBy?.userId&&(t.suggestion.resolvedBy={userId:t.suggestion.resolvedBy.userId})}return t?.comments&&(t.comments=t?.comments?.map(i=>this.formatCommentThreadData(i))),t}catch(i){return this.loggingService.catch("Error in CommentUtilsService formatCommentData:",i),t}}mergeStrippedDataWithCommentAnnotations(t){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: mergeStrippedDataWithCommentAnnotations","color: green;"),!this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())return t;let i=this.commentAnnotationsResolverService.getAnnotationById(t?.annotationId),o=this.attachmentResolverService.attachmentDataProviderAvailable(),s=this.commentAnnotationsResolverService.getFieldsToRemove();return i&&(t?.comments?.forEach(a=>{let c=i?.comments?.[a?.commentId];if(c){a.commentHtml=c?.commentHtml,a.commentText=c?.commentText;let l=c?.attachments;o&&l&&a.attachments?.forEach(u=>{let d=u?.attachmentId;l?.[d]&&(u.name=l?.[d]?.name,u.url=l?.[d]?.url)})}}),i?.targetTextRange?.text&&t?.targetTextRange&&(t.targetTextRange.text=i?.targetTextRange?.text),s?.length>0&&s.forEach(a=>{i?.[a]&&(t[a]=i[a])})),t}catch(i){return this.loggingService.catch("Error in CommentUtilsService mergeStrippedDataWithCommentAnnotations:",i),t}}mergeLocationWithCommentAnnotations(t,i){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: mergeLocationWithCommentAnnotations","color: green;");let o=t?.location?.id,s=t?.metadata?.documentId;if(!o||!s)return t;let a=i?.[s]?.[o];return a&&(t.location=a?.location),t}catch(o){return this.loggingService.catch("Error in CommentUtilsService mergeLocationWithCommentAnnotations:",o),t}}isCommentsDataChanged(t,i){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: isCommentsDataChanged","color: green;");let o=this.commentAnnotationsResolverService.getCommentAnnotationById(i);return o?!ki(t,o):!0}catch(o){return this.loggingService.catch("Error in CommentUtilsService isCommentsDataChanged:",o),!0}}stripCommentsFromAnnotationData({comment:t}){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: stripCommentsFromAnnotationData","color: green;");let i=this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable();if(!i)return t;let o=this.attachmentResolverService.attachmentDataProviderAvailable(),s=new LT;if(Object.assign(s,t),s.isCommentResolverUsed=i,o){let a=s.attachments?.map(c=>(c.isAttachmentResolverUsed=!0,delete c?.name,delete c?.url,c));s.attachments=a}return delete s?.commentHtml,delete s?.commentText,s}catch(i){return this.loggingService.catch("Error in CommentUtilsService stripCommentsFromAnnotationData:",i),t}}resolveTaggedUserEmails(t){return I(this,null,function*(){try{let i=new Set;if(t.comments?.forEach(o=>{o.taggedUserContacts?.forEach(s=>{s?.contact?.email&&!s?.userId&&i.add(s.contact.email)}),o.to?.forEach(s=>{s?.email&&!s?.userId&&i.add(s.email)})}),i.size>0){let o=J();this.coreActionsService.triggerAction($.USER_RESOLVER,{event:L.Events.Resolver.EMAIL_USER_ID_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:o,methodName:xn.RESOLVE_USER_IDS_BY_EMAIL,source:"internal",payload:{emails:Array.from(i)}});let s=yield this.usersService.resolveUserIdsByEmail({emails:Array.from(i),uniqueId:o});Object.keys(s).length>0&&t.comments?.forEach(a=>{a.taggedUserContacts?.forEach(c=>{if(c?.contact?.email&&!c?.userId){let l=s[c.contact.email];if(l){let u=c.text;if(u){let d=rl(u),f=new RegExp(d,"g");a.commentText&&(a.commentText=a.commentText.replace(f,`{{${l}}}`)),a.commentHtml&&(a.commentHtml=a.commentHtml.replace(f,`{{${l}}}`))}c.userId=l,c.contact.userId=l,delete c.contact?.email,delete c.contact?.visibility,c.text=""}}}),a.to=a.to?.map(c=>{if(c?.email&&!c?.userId){let l=s[c.email];if(l)return delete c?.email,delete c?.visibility,le(x({},c),{userId:l})}return c})})}return t}catch(i){return this.loggingService.catch("Error in CommentUtilsService resolveTaggedUserEmails:",i),t}})}stripCommentAnnotationData(s){return I(this,arguments,function*({data:t,actionType:i,commentId:o}){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: stripCommentAnnotationData","color: green;"),t=yield this.resolveTaggedUserEmails(t),!this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())return{originalData:t,strippedData:null};let a=this.attachmentResolverService.attachmentDataProviderAvailable(),c=this.commentAnnotationsResolverService.getFieldsToRemove(),l=this.commentAnnotationsResolverService.getAdditionalFields(),u,d;i&&(u=this.notificationActionTypeMap?.[i],d=this.additionalEventTypeMap?.[i]);let f=this.commentAnnotationsResolverService.getAdditionalSaveEvents(),g=Array.isArray(f)?f:[],p={},_=null,T=!1;if(t&&t.annotationId){let M=t.annotationId;if(p[M]=x(x(x(x({annotationId:M,metadata:Cn(t.metadata??{}),comments:{}},t?.from&&{from:t?.from}),t?.assignedTo&&{assignedTo:t?.assignedTo}),t?.resolvedByUserId&&{resolvedByUserId:t?.resolvedByUserId}),t?.targetTextRange?.text&&{targetTextRange:{text:t?.targetTextRange?.text}}),delete t?.targetTextRange?.text,c?.length>0&&c.forEach(k=>{t?.[k]&&(p[M][k]=t[k],delete t[k])}),l?.length)for(let k of l)t?.[k]!==void 0&&(p[M][k]=JSON.parse(JSON.stringify(t[k])));t.comments?.forEach(k=>{if(k.commentId){let S;a&&(S={},k.attachments?.forEach(A=>{S[A.attachmentId]={attachmentId:A.attachmentId,name:A.name,url:A.url}})),p[M].comments[k.commentId]=x(x(x(x(x(x({commentId:k.commentId},k?.commentHtml&&{commentHtml:k?.commentHtml}),k?.commentText&&{commentText:k?.commentText}),S&&{attachments:S}),k?.from&&{from:k?.from}),k?.to&&{to:k?.to}),k?.taggedUserContacts&&{taggedUserContacts:k?.taggedUserContacts})}}),T=this.isCommentsDataChanged(p[M],M);let U=new bT;Object.assign(U,t),c?.length>0&&c.forEach(k=>{k in t||delete U[k]}),U.comments=t.comments?.map(k=>this.stripCommentsFromAnnotationData({comment:k}))||[],_=U}let D=_?.comments?.find(M=>M.commentId===o);D?.isDraft&&(u=_?.comments?.length&&_?.comments?.length>0?Qt.COMMENT_ADD:Qt.COMMENT_ANNOTATION_ADD);let b=!!i&&!!this.notificationActionTypeMap?.[i],G=!!d&&!!_&&!b&&!D?.isDraft&&g.includes(d);return G&&(u=d),{strippedData:T&&(i&&this.notificationActionTypeMap?.[i]||D?.isDraft)||G?p:null,originalData:_,eventType:u}}catch(a){return this.loggingService.catch("Error in CommentAnnotationsResolverService stripCommentAnnotationData:",a),{strippedData:null,originalData:null}}})}formatCommentThreadData(t){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: formatCommentThreadData","color: green;"),this.usersService.userDataProviderAvailable()){t?.from?.userId&&(t.from={userId:t.from.userId}),t?.to&&(t.to=t?.to?.map(o=>o?.userId?{userId:o.userId}:o)),t?.taggedUserContacts&&(t.taggedUserContacts=t?.taggedUserContacts?.map(o=>o?.contact?.userId?le(x({},o),{contact:{userId:o.contact.userId}}):o));let i=t?.taggedUserContacts?.filter((o,s,a)=>a.findIndex(c=>c.text===o.text)===s)||[];i.sort((o,s)=>(s.text?.length||0)-(o.text?.length||0)),i.forEach(o=>{if(o?.text&&o?.contact?.userId){let s=new RegExp(rl(o.text),"g");t.commentText=t.commentText?.replaceAll(s,a=>`{{${o.userId}}}`),t.commentHtml=t.commentHtml?.replaceAll(s,a=>`{{${o.userId}}}`)}}),i.forEach(o=>{o?.text&&o?.contact?.userId&&(o.text="")})}return t}catch(i){return this.loggingService.catch("Error in CommentUtilsService formatCommentThreadData:",i),t}}getDeniedForYouUsers(i){return I(this,arguments,function*({extraData:t}){try{let o=Object.values(t?.annotationData?.subscribedUsers||{}).map(a=>a.user.userId)??[],s=[];if(this.userPermissionService?.isPermissionProviderAvailable()&&o.length){let a=t?.metadata?.clientDocumentId,c=t?.annotationData?.context?.access&&this.userPermissionService?.getIsContextEnabled()?t?.annotationData?.context?.access:null,l=[];o.forEach(f=>{if(l.push({userId:f,resource:{id:a,type:di.DOCUMENT,source:Un.SET_NOTIFICATIONS,organizationId:t?.metadata?.clientOrganizationId??"",context:c?{access:c}:void 0}}),c){let g=JSON.stringify(c);l.push({userId:f,resource:{id:g,type:di.CONTEXT,source:Un.SET_NOTIFICATIONS,organizationId:t?.metadata?.clientOrganizationId??"",context:{access:c}}})}});let u=J();this.coreActionsService.triggerAction($.PERMISSION_PROVIDER,{event:L.Events.PermissionProvider.RESOURCE_ACCESS_REQUEST_FORMED,methodName:Un.SET_NOTIFICATIONS,uniqueId:u,timestamp:new Date().getTime(),source:"internal",payload:{requests:l}});let d=yield this.userPermissionService?.onResourceAccessRequired({requests:l,uniqueId:u,methodName:Un.SET_NOTIFICATIONS});d?.success&&d?.data?.length&&d.data.forEach(f=>{f.hasAccess||s.push(f.userId)})}return s}catch(o){return this.loggingService.catch("Error in CommentUtilsService getDeniedForYouUsers:",o),[]}})}handleCommentEncryption(c){return I(this,arguments,function*({data:t,firestorePath:i,extraData:o,eventType:s,metadata:a}){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: handleCommentEncryption","color: green;");let l=$T(this.authService.getFirebaseConfig()?.firebaseOptions),u=Dr(this.functions,Ir({url:st.cloudFunction?.[l]?.setEncryptedData,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:1200*1e3});if(o){o=this.notificationService?.processNotificationData(o),o.annotationData=t;let _=o?.targetAnnotationData?.commentId;if(_){let T=t?.comments?.find(D=>D?.commentId===_);T&&(o.targetAnnotationData=T)}try{let T=yield this.stripCommentAnnotationData({data:o.annotationData,actionType:o?.actionType??Ie.NEWLY_ADDED});T?.originalData&&(o.annotationData=this.formatCommentData(T.originalData)),o?.targetAnnotationData&&(o.targetAnnotationData=this.formatCommentThreadData(this.stripCommentsFromAnnotationData({comment:o.targetAnnotationData})))}catch(T){this.loggingService.warn("Error in CommentUtilsService handleCommentEncryption:",T)}}let d=tc.getFirestoreProdDbName(this.configService.getApiKey()??"",this.authService.getFirebaseConfig()?.firebaseOptions),f=yield this.getDeniedForYouUsers({extraData:o}),g={path:i??"",data:t??{},dbId:d??"",notificationData:o||void 0,notificationURL:st.firebaseNotificationsDatabaseURL,feature:"comment",eventType:s??"PATCH",sdkVersion:jr(),deniedForYouUsers:f,isPermissionProviderUsed:this.userPermissionService?.isPermissionProviderAvailable(),isCommentResolverUsed:this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable(),isSettingsConfigByOrganization:this.notificationService?.getSettingsConfigByOrganization(),isCrossOrganizationEnabled:this.notificationService?.getCrossOrganizationConfig()?.enabled,metadata:a},p=yield il(g,this.authService.getUser()?.userId??"");yield u({veltData:p})}catch(l){this.loggingService.catch("Error in CommentUtilsService handleCommentEncryption:",l)}})}};e.\u0275fac=function(i){return new(i||e)(w(_e),w(zt),w(Cr),w(dr),w(Rr),w(zo),w(Wh),w(It))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let n=e;return n})();var Yy=(()=>{let e=class e{constructor(t,i,o){this.coreActionsService=t,this.loggingService=i,this.analyticsService=o,this.resolveTimeout=60*1e3,this.retrySaveConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.retryGetConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.activityDataProvider$=new Y(null),this.activityById$=new Y({}),this.fieldsToRemove=[],this.getActivityById=s=>{try{return this.activityDataProviderAvailable()?this.activityById$.value?.[s]:void 0}catch(a){this.loggingService.catch("Error in ActivityResolverService getActivityById:",a);return}};try{this.loggingService.log("ActivityResolverService initialized"),this.activityDataProvider$.subscribe(s=>{s&&(s.config?.resolveTimeout&&(this.resolveTimeout=s.config.resolveTimeout),s.config?.saveRetryConfig&&(this.retrySaveConfig=s.config.saveRetryConfig),s.config?.getRetryConfig&&(this.retryGetConfig=s.config.getRetryConfig),s.config?.fieldsToRemove&&(this.fieldsToRemove=s.config.fieldsToRemove))})}catch(s){this.loggingService.catch("Error in ActivityResolverService constructor:",s)}}getProvider(){try{let t=this.activityDataProvider$.getValue();return t||void 0}catch(t){this.loggingService.catch("Error in ActivityResolverService getProvider:",t);return}}ngOnDestroy(){try{this.activityById$.next({})}catch(t){this.loggingService.catch("Error in ActivityResolverService ngOnDestroy:",t)}}resolveActivities(s){return I(this,arguments,function*({request:t,uniqueId:i,moduleName:o}){try{if(this.loggingService.log("%c[WB] Calling ActivityResolverService FUNCTION: resolveActivities","color: green;"),!this.activityDataProviderAvailable())return{};let a,c=!1,l=!1,u=()=>{a&&(clearTimeout(a),a=void 0,l=!0)};return new Promise((d,f)=>{a=setTimeout(()=>{if(!l){c=!0,u();let b=i||J();this.coreActionsService.triggerAction($.ACTIVITY_RESOLVER,{event:L.Events.Resolver.ACTIVITY_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:b,methodName:lr.RESOLVE_ACTIVITIES,moduleName:o,source:"internal",payload:{error:new Error("Activity resolution timeout"),request:t}}),f(new Error("Activity resolution timeout"))}},this.activityDataProvider$.value?.config?.resolveTimeout||this.resolveTimeout);let g=this.getProvider();if(!g)return u(),d({});let p={},_=[...new Set(t.activityIds||[])],T=le(x({},t),{activityIds:_});I(this,null,function*(){try{if(_.length>0||t.documentIds?.length){let b=i||J();this.coreActionsService.triggerAction($.ACTIVITY_RESOLVER,{event:L.Events.Resolver.ACTIVITY_RESOLUTION_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:b,methodName:lr.RESOLVE_ACTIVITIES,moduleName:o,source:"internal",payload:{request:T}});let G=kt(()=>g?.config?.getConfig?.url?Ht(g.config.getConfig.url,g.config.getConfig.headers,T,!0,g.config.getConfig.credentials):g?.get?.(T)||Promise.resolve(void 0),"resolveActivities",this.retryGetConfig).then(M=>c?{}:(u(),M&&M.statusCode!==200?(this.coreActionsService.triggerAction($.ACTIVITY_RESOLVER,{event:L.Events.Resolver.ACTIVITY_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:b,methodName:lr.RESOLVE_ACTIVITIES,moduleName:o,source:"internal",payload:{result:M,request:T}}),this.loggingService.catch(M?.message??"Error in ActivityResolverService resolveActivities:"),{}):M?.data)).catch(M=>{throw u(),M});try{p=(yield G)||{},this.analyticsService.trackEvent(L.Events.Resolver.ACTIVITY_RESOLVER_GET,{sourceMethod:"resolveActivities",source:"sdk",activityIds:_});let M={};Object.entries(p).forEach(([U,k])=>{let S=this.activityById$.value?.[U];S?S&&JSON.stringify(S)!==JSON.stringify(k)&&(M[U]=k):M[U]=k}),Object.keys(M).length>0&&this.activityById$.next(x(x({},this.activityById$.getValue()),M)),this.coreActionsService.triggerAction($.ACTIVITY_RESOLVER,{event:L.Events.Resolver.ACTIVITY_RESOLUTION_RESULT,timestamp:new Date().getTime(),uniqueId:b,methodName:lr.RESOLVE_ACTIVITIES,moduleName:o,source:"internal",payload:{result:M,request:T}}),d(M)}catch(M){let U=i||J();this.coreActionsService.triggerAction($.ACTIVITY_RESOLVER,{event:L.Events.Resolver.ACTIVITY_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:U,methodName:lr.RESOLVE_ACTIVITIES,moduleName:o,source:"internal",payload:{error:M,request:T}}),c||f(M),d(p)}}else u(),d({})}catch(b){u();let G=i||J();this.coreActionsService.triggerAction($.ACTIVITY_RESOLVER,{event:L.Events.Resolver.ACTIVITY_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:G,methodName:lr.RESOLVE_ACTIVITIES,moduleName:o,source:"internal",payload:{error:b,request:T}}),f(b)}})})}catch(a){this.loggingService.catch("Error in ActivityResolverService resolveActivities:",a);let c=i||J();return this.coreActionsService.triggerAction($.ACTIVITY_RESOLVER,{event:L.Events.Resolver.ACTIVITY_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:c,methodName:lr.RESOLVE_ACTIVITIES,moduleName:o,source:"internal",payload:{error:a,request:t}}),{}}})}saveActivity(t,i){return I(this,null,function*(){try{this.loggingService.log("%c[WB] Calling ActivityResolverService FUNCTION: saveActivity","color: green;");let o=this.getProvider();if(!this.activityDataProviderAvailable())throw new Error("Activity save data provider not available");let s=i||J();this.coreActionsService.triggerAction($.ACTIVITY_RESOLVER,{event:L.Events.Resolver.ACTIVITY_SAVE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:s,methodName:lr.SAVE_ACTIVITY,source:"internal",payload:{request:t}});let a=JSON.parse(JSON.stringify(this.activityById$.getValue()));this.activityById$._value=x(x({},a),t.activity);let c=yield kt(()=>{if(o?.config?.saveConfig?.url){let l={activity:t.activity,event:t.event,metadata:Object.values(t.activity??{})?.[0]?.metadata};return Ht(o.config.saveConfig.url,o.config.saveConfig.headers,l,!1,o.config.saveConfig.credentials)}return o?.save?.({activity:t.activity,event:t.event,metadata:Object.values(t.activity??{})?.[0]?.metadata})||Promise.resolve(void 0)},"saveActivity",this.retrySaveConfig);return c&&c.statusCode!==200?(this.retrySaveConfig.revertOnFailure&&(this.activityById$._value=a),this.loggingService.catch(c?.message??"Error in ActivityResolverService saveActivity:"),this.coreActionsService.triggerAction($.ACTIVITY_RESOLVER,{event:L.Events.Resolver.ACTIVITY_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:s,methodName:lr.SAVE_ACTIVITY,source:"internal",payload:{error:c,request:t}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(L.Events.Resolver.ACTIVITY_RESOLVER_SAVE,{sourceMethod:"saveActivity",source:"sdk",activityIds:Object.keys(t.activity),event:t.event}),this.coreActionsService.triggerAction($.ACTIVITY_RESOLVER,{event:L.Events.Resolver.ACTIVITY_SAVE_RESULT,timestamp:new Date().getTime(),uniqueId:s,methodName:lr.SAVE_ACTIVITY,source:"internal",payload:{result:{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0},request:t}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0})}catch(o){this.loggingService.warn("Error in ActivityResolverService saveActivity:",o);let s=i||J();return this.coreActionsService.triggerAction($.ACTIVITY_RESOLVER,{event:L.Events.Resolver.ACTIVITY_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:s,methodName:lr.SAVE_ACTIVITY,source:"internal",payload:{error:o,request:t}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!1}}})}getActivitiesById$(){try{return this.activityDataProviderAvailable()?(this.loggingService.log("%c[WB] Calling ActivityResolverService FUNCTION: getActivitiesById$","color: green;"),this.activityById$.asObservable()):ue(void 0)}catch(t){return this.loggingService.catch("Error in ActivityResolverService getActivitiesById$:",t),ue(void 0)}}getFieldsToRemove(){try{return this.fieldsToRemove}catch(t){return this.loggingService.catch("Error in ActivityResolverService getFieldsToRemove:",t),this.fieldsToRemove}}setActivityDataProvider(t){try{if(t){this.loggingService.log("Setting activity data provider");let i=t.config,o=[{method:"get",configKey:"getConfig"},{method:"save",configKey:"saveConfig"}],s=[];if(o.forEach(({method:a,configKey:c})=>{let l=i?.[c]?.url,u=a in t&&typeof t[a]=="function";!l&&!u&&s.push(a)}),s.length>0){let a=`DataProviders.activity is invalid. The following methods are missing or are not functions (and no corresponding config provided): ${s.join(", ")}.`;this.loggingService.catch(a);return}else this.activityDataProvider$.next(t)}}catch(i){this.loggingService.catch("Error in ActivityResolverService setActivityDataProvider:",i)}}activityDataProviderAvailable(){try{return!!this.activityDataProvider$.getValue()}catch(t){return this.loggingService.catch("Error in ActivityResolverService activityDataProviderAvailable:",t),!1}}};e.\u0275fac=function(i){return new(i||e)(w(It),w(_e),w(Lt))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let n=e;return n})();var Qy=(()=>{let e=class e{constructor(t,i,o,s,a,c){this.loggingService=t,this.usersService=i,this.authService=o,this.functions=s,this.configService=a,this.reactionAnnotationsResolverService=c}getUserIdsToResolveFromReactions(t){try{let i=new Set;for(let o of t)if(o?.from?.userId&&i.add(o?.from?.userId),o?.reactions?.length)for(let s of o?.reactions)s?.from?.userId&&i.add(s?.from?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in ReactionUtilsService getUserIdsToResolveFromRecorders:",i),[]}}handleReactionEncryption(s){return I(this,arguments,function*({data:t,firestorePath:i,eventType:o}){try{let a=$T(this.authService.getFirebaseConfig()?.firebaseOptions),c=Dr(this.functions,Ir({url:st.cloudFunction?.[a]?.setEncryptedData,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:1200*1e3}),l=tc.getFirestoreProdDbName(this.configService.getApiKey()??"",this.authService.getFirebaseConfig()?.firebaseOptions),u=this.authService.getUser()?.userId??"",d={path:i??"",data:t??{},dbId:l??"",feature:"reaction",eventType:o??"PATCH",sdkVersion:jr()},f=yield il(d,u);yield c({veltData:f})}catch(a){this.loggingService.catch("Error in handleReactionEncryption:",a)}})}mergeReactionWithUser(t){try{if(this.usersService.userDataProviderAvailable()){if(t?.from?.userId){let i=this.usersService.getUserById(t?.from?.userId);i&&(t.from=i)}if(t?.reactions?.length){for(let i of t?.reactions)if(i?.from?.userId){let o=this.usersService.getUserById(i?.from?.userId);o&&(i.from=o)}}}return t}catch(i){return this.loggingService.catch("Error in ReactionUtilsService mergeReactionWithUser:",i),t}}formatReactionData(t){try{return this.usersService.userDataProviderAvailable()&&t?.from?.userId&&(t.from={userId:t.from.userId}),t.reactions=t?.reactions?.map(i=>(this.usersService.userDataProviderAvailable()&&i?.from?.userId&&(i.from={userId:i.from.userId}),i)),t}catch(i){return this.loggingService.catch("Error in ReactionUtilsService formatReactionData:",i),t}}isReactionDataChanged(t,i){try{this.loggingService.log("%c[WB] Calling ReactionUtilsService FUNCTION: isReactionDataChanged","color: green;");let o=this.reactionAnnotationsResolverService.getReactionAnnotationById(i);return o?!ki(t,o):!0}catch(o){return this.loggingService.catch("Error in ReactionUtilsService isReactionDataChanged:",o),!0}}stripReactionAnnotationData(t){try{if(this.loggingService.log("%c[WB] Calling ReactionUtilsService FUNCTION: stripReactionAnnotationData","color: green;"),!this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable())return{originalData:t,strippedData:null};let i={},o=this.reactionAnnotationsResolverService.getFieldsToRemove();if(t&&t.annotationId){let s=t.annotationId;if(i[s]=x({annotationId:s,metadata:Cn(t.metadata??{}),icon:t.icon},t?.from&&{from:t?.from}),o?.length>0)for(let c of o)t?.[c]!==void 0&&(i[s][c]=t[c],delete t[c]);if(!this.isReactionDataChanged(i[s],s))return{strippedData:null,originalData:t};delete t?.icon,t.isReactionResolverUsed=!0}return{strippedData:i,originalData:t}}catch(i){return this.loggingService.catch("Error in ReactionUtilsService stripReactionAnnotationData:",i),{strippedData:null,originalData:null}}}mergeStrippedDataWithReactionAnnotations(t){try{if(this.loggingService.log("%c[WB] Calling ReactionUtilsService FUNCTION: mergeStrippedDataWithReactionAnnotations","color: green;"),!this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable())return t;let i=this.reactionAnnotationsResolverService.getReactionAnnotationById(t?.annotationId);if(i){i.icon&&(t.icon=i.icon);let o=this.reactionAnnotationsResolverService.getFieldsToRemove();if(o?.length>0)for(let s of o)i?.[s]!==void 0&&(t[s]=i[s])}return t}catch(i){return this.loggingService.catch("Error in ReactionUtilsService mergeStrippedDataWithReactionAnnotations:",i),t}}};e.\u0275fac=function(i){return new(i||e)(w(_e),w(zt),w(Cr),w(dr),w(Rr),w(qo))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let n=e;return n})();var Xy=(()=>{let e=class e{constructor(t,i,o,s,a,c,l,u,d){this.loggingService=t,this.usersService=i,this.commentUtilsService=o,this.reactionUtilsService=s,this.commentAnnotationsResolverService=a,this.reactionAnnotationsResolverService=c,this.recorderAnnotationsResolverService=l,this.activityResolverService=u,this.serviceBook=d}getActivityDisplayMessage(t){try{switch(t.featureType){case"comment":return this.getCommentDisplayMessage(t);case"recorder":return this.getRecorderDisplayMessage(t);case"reaction":return this.getReactionDisplayMessage(t);case"crdt":return this.getCrdtDisplayMessage(t);case"custom":return t.displayMessageTemplate&&t.displayMessageTemplateData?this.resolveTemplate(t.displayMessageTemplate,t.displayMessageTemplateData):"";default:return""}}catch(i){return this.loggingService.catch("Error in ActivityUtilsService getActivityDisplayMessage:",i),""}}resolveTemplate(t,i){try{return t.replace(/\{\{([\w.]+)\}\}/g,(o,s)=>{let a=s.split(".").reduce((c,l)=>{if(c!=null&&typeof c=="object")return c[l]},i);return a!=null?String(a):""})}catch(o){return this.loggingService.catch("Error in ActivityUtilsService resolveTemplate:",o),t}}buildActivityDataFromExtraData(t){try{let{feature:i,extraData:o}=t;if(!o?.actionType)return null;switch(i){case"comment":return this.buildCommentActivityData({commentAnnotation:o.annotationData,targetComment:o.targetAnnotationData,actionType:o.actionType,otherFields:o});case"recorder":return this.buildRecorderActivityData(o);case"reaction":return this.buildReactionActivityData(o);default:return null}}catch(i){return this.loggingService.catch("Error in ActivityUtilsService buildActivityDataFromExtraData:",i),null}}stripActivityPII(t){return I(this,null,function*(){try{let i=JSON.parse(JSON.stringify(t));if(delete i.displayMessage,!this.usersService.userDataProviderAvailable())return{strippedActivity:i};i.actionUser?.userId&&(i.actionUser={userId:i.actionUser.userId}),i.changes&&this.stripUsersFromChanges(i.changes),i.displayMessageTemplateData&&this.stripUsersFromTemplateData(i.displayMessageTemplateData);let o=this.extractCommentChangesForResolver(i),s=this.extractFeatureEntityDataForResolver(i);yield this.stripFeatureSpecificPII(i);let a=this.extractActivityResolverData(i);return o&&(a?a.changes=x(x({},a.changes),o.changes):a=o),s&&(a?(s.entityData!==void 0&&(a.entityData=s.entityData),s.entityTargetData!==void 0&&(a.entityTargetData=s.entityTargetData)):a=s),a&&(i.isActivityResolverUsed=!0),{strippedActivity:i,activityResolverData:a}}catch(i){return this.loggingService.catch("Error in ActivityUtilsService stripActivityPII:",i),{strippedActivity:t}}})}mergeActivityWithUser(t){try{if(!this.usersService.userDataProviderAvailable())return t;if(t=JSON.parse(JSON.stringify(t)),t.actionUser?.userId){let i=this.usersService.getUserById(t.actionUser.userId);i&&(t.actionUser=i)}return t.changes&&this.rehydrateUsersInChanges(t.changes),t.displayMessageTemplateData&&this.rehydrateUsersInTemplateData(t.displayMessageTemplateData),this.rehydrateFeatureSpecificUserData(t),t}catch(i){return this.loggingService.catch("Error in ActivityUtilsService mergeActivityWithUser:",i),t}}mergeActivityWithFeatureData(t){try{switch(t.featureType){case"comment":return this.mergeActivityWithCommentAnnotationData(t);case"reaction":return this.mergeActivityWithReactionData(t);case"recorder":return this.mergeActivityWithRecorderData(t);default:return t}}catch(i){return this.loggingService.catch("Error in ActivityUtilsService mergeActivityWithFeatureData:",i),t}}getUserIdsToResolveFromActivities(t){try{let i=new Set;for(let o of t){if(o.actionUser?.userId&&i.add(o.actionUser.userId),o.changes)for(let s of Object.values(o.changes))s&&(this.extractUserIdFromValue(s.from,i),this.extractUserIdFromValue(s.to,i));if(o.displayMessageTemplateData)for(let s of Object.values(o.displayMessageTemplateData))this.extractUserIdFromValue(s,i);this.extractFeatureSpecificUserIds(o,i)}return Array.from(i)}catch(i){return this.loggingService.catch("Error in ActivityUtilsService getUserIdsToResolveFromActivities:",i),[]}}getEntityIdsToResolveFromActivities(t,i){try{let o=new Set;for(let s of t)if(!(i&&s.featureType!==i))switch(s.featureType){case"comment":case"reaction":case"recorder":s.targetEntityId&&o.add(s.targetEntityId);break}return Array.from(o)}catch(o){return this.loggingService.catch("Error in ActivityUtilsService getEntityIdsToResolveFromActivities:",o),[]}}stripFeatureSpecificPII(t){return I(this,null,function*(){try{switch(t.featureType){case"comment":yield this.stripCommentPII(t);break;case"reaction":this.stripReactionPII(t);break;case"recorder":this.stripRecorderPII(t);break}}catch(i){this.loggingService.catch("Error in ActivityUtilsService stripFeatureSpecificPII:",i)}})}extractActivityResolverData(t){try{if(!this.activityResolverService.activityDataProviderAvailable())return;let i={id:t.id},o=!1,s=this.activityResolverService.getFieldsToRemove();for(let a of s)a in t&&t[a]!==void 0&&(i[a]=t[a],delete t[a],o=!0);return t.metadata&&(i.metadata=Cn(t.metadata)),o?i:void 0}catch(i){this.loggingService.catch("Error in ActivityUtilsService extractActivityResolverData:",i);return}}extractCommentChangesForResolver(t){try{return!this.activityResolverService.activityDataProviderAvailable()||t.featureType!=="comment"||!t.changes?.commentText?void 0:{id:t.id,changes:{commentText:t.changes.commentText},metadata:t.metadata?Cn(t.metadata):void 0}}catch(i){this.loggingService.catch("Error in ActivityUtilsService extractCommentChangesForResolver:",i);return}}extractFeatureEntityDataForResolver(t){try{if(!this.activityResolverService.activityDataProviderAvailable()||!t.entityData)return;let i=t.featureType==="recorder"&&this.recorderAnnotationsResolverService.recorderAnnotationDataProviderAvailable(),o=t.featureType==="reaction"&&this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable();if(!i&&!o)return;let s={id:t.id,metadata:t.metadata?Cn(t.metadata):void 0},a=JSON.parse(JSON.stringify(t.entityData));if(i){let c=this.serviceBook.get(ci)?.stripRecorderAnnotationData({data:a});if(c?.strippedData){let l=Object.keys(c.strippedData)[0];l&&(s.entityData=c.strippedData[l])}}if(o){let c=this.reactionUtilsService.stripReactionAnnotationData(a);if(c?.strippedData){let l=Object.keys(c.strippedData)[0];l&&(s.entityData=c.strippedData[l])}}return s.entityData?s:void 0}catch(i){this.loggingService.catch("Error in ActivityUtilsService extractFeatureEntityDataForResolver:",i);return}}mergeActivityWithResolverData(t){try{if(!this.activityResolverService.activityDataProviderAvailable())return t;let i=this.activityResolverService.getActivityById(t.id);if(!i)return t;i.changes&&(t.changes||(t.changes={}),Object.assign(t.changes,i.changes)),i.entityData!==void 0&&(t.entityData=i.entityData),i.entityTargetData!==void 0&&(t.entityTargetData=i.entityTargetData),i.displayMessageTemplateData&&(t.displayMessageTemplateData||(t.displayMessageTemplateData={}),Object.assign(t.displayMessageTemplateData,i.displayMessageTemplateData));let o=new Set(["id","metadata","changes","entityData","entityTargetData","displayMessageTemplateData"]);for(let[s,a]of Object.entries(i))!o.has(s)&&a!==void 0&&(t[s]=a);return t}catch(i){return this.loggingService.catch("Error in ActivityUtilsService mergeActivityWithResolverData:",i),t}}rehydrateFeatureSpecificUserData(t){try{switch(t.featureType){case"comment":this.rehydrateCommentUserData(t);break;case"reaction":this.rehydrateReactionUserData(t);break;case"recorder":this.rehydrateRecorderUserData(t);break}}catch(i){this.loggingService.catch("Error in ActivityUtilsService rehydrateFeatureSpecificUserData:",i)}}getCommentDisplayMessage(t){try{let i=t.actionUser?.name??"Someone";switch(t.actionType){case xe.ANNOTATION_ADD:return`${i} added a comment`;case xe.COMMENT_ADD:return`${i} replied to a comment`;case xe.COMMENT_UPDATE:return`${i} edited a comment`;case xe.COMMENT_DELETE:return`${i} deleted a comment`;case xe.ANNOTATION_DELETE:return`${i} deleted a comment thread`;case xe.STATUS_CHANGE:{let o=t.changes?.status,s=o?.from?.name,a=o?.to?.name;return s&&a?`${i} changed status from ${s} to ${a}`:`${i} changed the status`}case xe.PRIORITY_CHANGE:{let o=t.changes?.priority,s=o?.to;if(!s)return`${i} removed the priority`;let a=typeof s=="object"?s?.name:String(s),c=o?.from,l=c&&typeof c=="object"?c?.name:c?String(c):null;return l&&a?`${i} changed priority from ${l} to ${a}`:`${i} changed priority to ${a}`}case xe.ASSIGN:{let s=t.changes?.assignedTo?.to;return s&&typeof s=="object"&&s.name?`${i} assigned to ${s.name}`:`${i} assigned the comment`}case xe.ACCESS_MODE_CHANGE:{let s=t.changes?.accessMode?.to;return s?`${i} changed access to ${s}`:`${i} changed the access mode`}case xe.CUSTOM_LIST_CHANGE:return`${i} changed the custom list`;case xe.APPROVE:return`${i} approved the comment`;case xe.ACCEPT:case xe.SUGGESTION_ACCEPT:return`${i} accepted a suggestion`;case xe.REJECT:case xe.SUGGESTION_REJECT:return`${i} rejected a suggestion`;case xe.REACTION_ADD:return`${i} reacted to a comment`;case xe.REACTION_DELETE:return`${i} removed a reaction`;case xe.SUBSCRIBE:return`${i} subscribed to the thread`;case xe.UNSUBSCRIBE:return`${i} unsubscribed from the thread`;default:return""}}catch(i){return this.loggingService.catch("Error in ActivityUtilsService getCommentDisplayMessage:",i),""}}getRecorderDisplayMessage(t){try{let i=t.actionUser?.name??"Someone";switch(t.actionType){case vg.RECORDING_ADD:return`${i} added a recording`;case vg.RECORDING_DELETE:return`${i} deleted a recording`;default:return""}}catch(i){return this.loggingService.catch("Error in ActivityUtilsService getRecorderDisplayMessage:",i),""}}getReactionDisplayMessage(t){try{let i=t.actionUser?.name??"Someone";switch(t.actionType){case yg.REACTION_ADD:return`${i} added a reaction`;case yg.REACTION_DELETE:return`${i} removed a reaction`;default:return""}}catch(i){return this.loggingService.catch("Error in ActivityUtilsService getReactionDisplayMessage:",i),""}}getCrdtDisplayMessage(t){try{let i=t.actionUser?.name??"Someone",s=t.entityData?.editCount??0,a=t.targetEntityId??"unknown";return`${i} made ${s} edit${s!==1?"s":""} to editor ${a}`}catch(i){return this.loggingService.catch("Error in ActivityUtilsService getCrdtDisplayMessage:",i),""}}stripCommentPII(t){return I(this,null,function*(){try{let i=yield this.commentUtilsService.stripCommentAnnotationData({data:t.entityData,actionType:t.eventType??Ie.NEWLY_ADDED});i?.originalData&&(t.entityData=this.commentUtilsService.formatCommentData(i.originalData)),t.entityTargetData&&(t.entityTargetData=this.commentUtilsService.formatCommentThreadData(this.commentUtilsService.stripCommentsFromAnnotationData({comment:t.entityTargetData}))),this.activityResolverService.activityDataProviderAvailable()&&t.changes?.commentText&&delete t.changes.commentText}catch(i){this.loggingService.catch("Error in ActivityUtilsService stripCommentPII:",i)}})}rehydrateCommentUserData(t){try{t.entityData&&this.commentUtilsService.mergeCommentWithUser(t.entityData),t.entityTargetData&&(this.rehydrateUserInObject(t.entityTargetData,"from"),this.rehydrateUsersInArray(t.entityTargetData,"to"),this.rehydrateUsersInArray(t.entityTargetData,"taggedUserContacts"))}catch(i){this.loggingService.catch("Error in ActivityUtilsService rehydrateCommentUserData:",i)}}stripReactionPII(t){try{if(!t.entityData)return;this.activityResolverService.activityDataProviderAvailable()&&this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable()&&this.reactionUtilsService.stripReactionAnnotationData(t.entityData),t.entityData=this.reactionUtilsService.formatReactionData(t.entityData)}catch(i){this.loggingService.catch("Error in ActivityUtilsService stripReactionPII:",i)}}rehydrateReactionUserData(t){try{if(!t.entityData)return;this.reactionUtilsService.mergeReactionWithUser(t.entityData)}catch(i){this.loggingService.catch("Error in ActivityUtilsService rehydrateReactionUserData:",i)}}stripRecorderPII(t){try{if(!t.entityData)return;if(this.activityResolverService.activityDataProviderAvailable()&&this.recorderAnnotationsResolverService.recorderAnnotationDataProviderAvailable()){this.serviceBook.get(ci)?.stripRecorderAnnotationData({data:t.entityData});return}let i=t.entityData;if(this.usersService.userDataProviderAvailable()){i.from&&typeof i.from=="object"&&"userId"in i.from&&(i.from={userId:i.from.userId});let o=i.transcription;o?.from&&typeof o.from=="object"&&"userId"in o.from&&(o.from={userId:o.from.userId})}}catch(i){this.loggingService.catch("Error in ActivityUtilsService stripRecorderPII:",i)}}rehydrateRecorderUserData(t){try{if(!t.entityData)return;this.serviceBook.get(ci)?.mergeRecorderWithUser(t.entityData)}catch(i){this.loggingService.catch("Error in ActivityUtilsService rehydrateRecorderUserData:",i)}}mergeActivityWithCommentAnnotationData(t){try{if(!this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())return t;let i=this.commentAnnotationsResolverService.getAnnotationById(t.targetEntityId);if(!i)return t;let o=t.entityData?.comments;if(Array.isArray(o))for(let s of o){let a=s?.commentId;if(a==null)continue;let c=i.comments?.[String(a)];c&&(c.commentText&&(s.commentText=c.commentText),c.commentHtml&&(s.commentHtml=c.commentHtml))}if(t.targetSubEntityId&&t.entityTargetData){let s=i.comments?.[t.targetSubEntityId];if(s){let a=t.entityTargetData;s.commentText&&(a.commentText=s.commentText),s.commentHtml&&(a.commentHtml=s.commentHtml)}}return t}catch(i){return this.loggingService.catch("Error in ActivityUtilsService mergeActivityWithCommentAnnotationData:",i),t}}mergeActivityWithReactionData(t){try{return!this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable()||!t.targetEntityId||!t.entityData||this.reactionUtilsService.mergeStrippedDataWithReactionAnnotations(t.entityData),t}catch(i){return this.loggingService.catch("Error in ActivityUtilsService mergeActivityWithReactionData:",i),t}}mergeActivityWithRecorderData(t){try{return!this.recorderAnnotationsResolverService.recorderAnnotationDataProviderAvailable()||!t.targetEntityId||!t.entityData||this.serviceBook.get(ci)?.mergeStrippedDataWithRecorderAnnotation(t.entityData),t}catch(i){return this.loggingService.catch("Error in ActivityUtilsService mergeActivityWithRecorderData:",i),t}}buildCommentActivityData(t){try{let{commentAnnotation:i,targetComment:o,actionType:s,otherFields:a}=t,c=i,l=o,u=s===Ie.DELETED&&a?.isAnnotationDelete?xe.ANNOTATION_DELETE:this.mapCommentStatusToActionType(s);if(!u)return null;let d=c?.annotationId;if(!d)return null;let f=l?.commentId,g=this.buildCommentChanges(s,l,a);return{featureType:"comment",actionType:u,targetEntityId:d,eventType:s,targetSubEntityId:f??null,changes:Object.keys(g).length>0?g:void 0,entityData:i,entityTargetData:o??void 0}}catch(i){return this.loggingService.catch("Error in ActivityUtilsService buildCommentActivityData:",i),null}}mapCommentStatusToActionType(t){try{switch(t){case Ie.NEWLY_ADDED:return xe.ANNOTATION_ADD;case Ie.ADDED:return xe.COMMENT_ADD;case Ie.UPDATED:return xe.COMMENT_UPDATE;case Ie.DELETED:return xe.COMMENT_DELETE;case Ie.STATUS_CHANGED:return xe.STATUS_CHANGE;case Ie.PRIORITY_CHANGED:return xe.PRIORITY_CHANGE;case Ie.ASSIGNED:return xe.ASSIGN;case Ie.ACCESS_MODE_CHANGED:return xe.ACCESS_MODE_CHANGE;case Ie.CUSTOM_LIST_CHANGED:return xe.CUSTOM_LIST_CHANGE;case Ie.APPROVED:return xe.APPROVE;case Ie.ACCEPTED:return xe.ACCEPT;case Ie.REJECTED:return xe.REJECT;case Ie.SUGGESTION_ACCEPTED:return xe.SUGGESTION_ACCEPT;case Ie.SUGGESTION_REJECTED:return xe.SUGGESTION_REJECT;case Ie.REACTION_ADDED:return xe.REACTION_ADD;case Ie.REACTION_DELETED:return xe.REACTION_DELETE;case Ie.SUBSCRIBED:return xe.SUBSCRIBE;case Ie.UNSUBSCRIBED:return xe.UNSUBSCRIBE;default:return null}}catch(i){return this.loggingService.catch("Error in ActivityUtilsService mapCommentStatusToActionType:",i),null}}buildRecorderActivityData(t){try{let i=t.annotationData,o=t.actionType,s=this.mapRecorderStatusToActionType(o);if(!s)return null;let a=i?.annotationId;return a?{featureType:"recorder",actionType:s,targetEntityId:a,entityData:i}:null}catch(i){return this.loggingService.catch("Error in ActivityUtilsService buildRecorderActivityData:",i),null}}mapRecorderStatusToActionType(t){try{switch(t){case _T.ADDED:return vg.RECORDING_ADD;case _T.DELETED:return vg.RECORDING_DELETE;default:return null}}catch(i){return this.loggingService.catch("Error in ActivityUtilsService mapRecorderStatusToActionType:",i),null}}buildReactionActivityData(t){try{let i=t.annotationData,o=t.actionType,s=this.mapReactionActionType(o);if(!s)return null;let a=i?.annotationId;return a?{featureType:"reaction",actionType:s,targetEntityId:a,entityData:i}:null}catch(i){return this.loggingService.catch("Error in ActivityUtilsService buildReactionActivityData:",i),null}}mapReactionActionType(t){try{switch(t){case"add":return yg.REACTION_ADD;case"delete":return yg.REACTION_DELETE;default:return null}}catch(i){return this.loggingService.catch("Error in ActivityUtilsService mapReactionActionType:",i),null}}buildCommentChanges(t,i,o){try{let s={};switch(t){case Ie.NEWLY_ADDED:case Ie.ADDED:s.commentText={from:null,to:i?.commentText??null};break;case Ie.UPDATED:s.commentText={from:o?.oldCommentText??null,to:i?.commentText??null};break;case Ie.DELETED:s.commentText={from:i?.commentText??null,to:null};break;case Ie.STATUS_CHANGED:s.status={from:o?.oldStatus??null,to:o?.newStatus??null};break;case Ie.PRIORITY_CHANGED:s.priority={from:o?.oldPriority??null,to:o?.newPriority??null};break;case Ie.ASSIGNED:{s.assignedTo={from:o?.oldAssignedTo??null,to:o?.newAssignedTo??null};break}case Ie.ACCESS_MODE_CHANGED:s.accessMode={from:o?.oldAccessMode??null,to:o?.newAccessMode??null};break;case Ie.CUSTOM_LIST_CHANGED:s.customList={from:o?.oldCustomList??null,to:o?.newCustomList??null};break}return s}catch(s){return this.loggingService.catch("Error in ActivityUtilsService buildCommentChanges:",s),{}}}extractFeatureSpecificUserIds(t,i){try{switch(t.featureType){case"comment":this.extractCommentActivityUserIds(t,i);break;case"reaction":this.extractReactionActivityUserIds(t,i);break;case"recorder":this.extractRecorderActivityUserIds(t,i);break}}catch(o){this.loggingService.catch("Error in ActivityUtilsService extractFeatureSpecificUserIds:",o)}}extractCommentActivityUserIds(t,i){try{if(t.entityData){let o=this.commentUtilsService.getUserIdsToResolveFromComments([t.entityData]);for(let s of o)i.add(s)}if(t.entityTargetData){let o=t.entityTargetData;if(this.extractUserIdFromValue(o.from,i),Array.isArray(o.to))for(let s of o.to)this.extractUserIdFromValue(s,i);if(Array.isArray(o.taggedUserContacts))for(let s of o.taggedUserContacts)this.extractUserIdFromValue(s,i)}}catch(o){this.loggingService.catch("Error in ActivityUtilsService extractCommentActivityUserIds:",o)}}extractReactionActivityUserIds(t,i){try{if(!t.entityData)return;let o=this.reactionUtilsService.getUserIdsToResolveFromReactions([t.entityData]);for(let s of o)i.add(s)}catch(o){this.loggingService.catch("Error in ActivityUtilsService extractReactionActivityUserIds:",o)}}extractRecorderActivityUserIds(t,i){try{if(!t.entityData)return;let o=this.serviceBook.get(ci)?.getUserIdsToResolveFromRecorders([t.entityData])??[];for(let s of o)i.add(s)}catch(o){this.loggingService.catch("Error in ActivityUtilsService extractRecorderActivityUserIds:",o)}}stripUsersFromChanges(t){try{for(let i of Object.keys(t)){let o=t[i];o&&(o.from=this.stripUserIfPresent(o.from),o.to=this.stripUserIfPresent(o.to))}}catch(i){this.loggingService.catch("Error in ActivityUtilsService stripUsersFromChanges:",i)}}stripUserIfPresent(t){try{return t&&typeof t=="object"&&"userId"in t?{userId:t.userId}:t}catch(i){return this.loggingService.catch("Error in ActivityUtilsService stripUserIfPresent:",i),t}}stripUsersFromTemplateData(t){try{for(let i of Object.keys(t)){let o=t[i];o&&typeof o=="object"&&"userId"in o&&(t[i]={userId:o.userId})}}catch(i){this.loggingService.catch("Error in ActivityUtilsService stripUsersFromTemplateData:",i)}}rehydrateUsersInChanges(t){try{for(let i of Object.values(t))i&&(i.from=this.rehydrateIfUser(i.from),i.to=this.rehydrateIfUser(i.to))}catch(i){this.loggingService.catch("Error in ActivityUtilsService rehydrateUsersInChanges:",i)}}rehydrateIfUser(t){try{if(t&&typeof t=="object"&&"userId"in t){let i=t.userId;return this.usersService.getUserById(i)??t}return t}catch(i){return this.loggingService.catch("Error in ActivityUtilsService rehydrateIfUser:",i),t}}rehydrateUsersInTemplateData(t){try{for(let i of Object.keys(t))t[i]=this.rehydrateIfUser(t[i])}catch(i){this.loggingService.catch("Error in ActivityUtilsService rehydrateUsersInTemplateData:",i)}}rehydrateUserInObject(t,i){try{let o=t[i];if(o&&typeof o=="object"&&"userId"in o){let s=o.userId,a=this.usersService.getUserById(s);a&&(t[i]=a)}}catch(o){this.loggingService.catch("Error in ActivityUtilsService rehydrateUserInObject:",o)}}rehydrateUsersInArray(t,i){try{let o=t[i];Array.isArray(o)&&(t[i]=o.map(s=>this.rehydrateIfUser(s)))}catch(o){this.loggingService.catch("Error in ActivityUtilsService rehydrateUsersInArray:",o)}}extractUserIdFromValue(t,i){try{if(t&&typeof t=="object"&&"userId"in t){let o=t.userId;typeof o=="string"&&i.add(o)}}catch(o){this.loggingService.catch("Error in ActivityUtilsService extractUserIdFromValue:",o)}}};e.\u0275fac=function(i){return new(i||e)(w(_e),w(zt),w(Ky),w(Qy),w(zo),w(qo),w(ec),w(Yy),w(li))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let n=e;return n})();var Jy=class{constructor({apiKey:e,documentId:r,organizationId:t,folderId:i,veltFolderId:o,clientDocumentId:s,clientOrganizationId:a}){this.paths={},this.apiKey=e,this.documentId=r,this.organizationId=t,this.folderId=i,this.veltFolderId=o,this.clientDocumentId=s,this.clientOrganizationId=a,s&&(this.documentId=da(s)),a&&(this.organizationId=Ts(a)),i&&(this.folderId=i,this.veltFolderId=wo(i)),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 e=`${this.apiKey}`;this.organizationId&&(e=`${e}/${v.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${this.paths.organizationId}`),this.documentId&&(this.paths.docs=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/`,this.paths.folder=`${e}/${v.FIREBASE_PARTIAL_PATH_FOLDERS}/`,this.paths.presence=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_PRESENCE}/`,this.paths.cursor=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_CURSOR}/`,this.paths.comment=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_COMMENT}/`,this.paths.multiThread=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_MULTI_THREAD}/`,this.paths.tag=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_TAG}/`,this.paths.area=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_AREA}/`,this.paths.arrow=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_ARROW}/`,this.paths.selection=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_SELECTION}/`,this.paths.audioHuddle=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_AUDIO_HUDDLE}/`,this.paths.huddle=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_HUDDLE}/`,this.paths.recorder=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_RECORDER}/`,this.paths.flock=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_FOLLOW_ALONG}/`,this.paths.syncVideoPlayer=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_SYNC_VIDEO_PLAYER}/`,this.paths.liveState=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_LIVE_STATE}/`,this.paths.liveStateSingleEditorMode=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_LIVE_STATE}/default/singleEditorMode`,this.paths.reaction=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_REACTION}/`,this.paths.crdt=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_CRDT}/`,this.paths.views=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_VIEWS}/`,this.paths.notifications=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_NOTIFICATIONS}/`,this.paths.metadata=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_METADATA}/`,this.paths.users=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_USERS}/`,this.paths.documentIam=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_IAM}/`,this.paths.userConfig=`${e}/${v.FIREBASE_PARTIAL_PATH_USERS}`),this.paths.customerMetadata=`${e}/${v.FIREBASE_PARTIAL_PATH_CUSTOMER_METADATA}/`,this.paths.groupContacts=`${e}/${v.FIREBASE_PARTIAL_PATH_CONTACTS}/${v.FIREBASE_PARTIAL_PATH_GROUPS}/`,this.paths.globalContacts=`${e}/${v.FIREBASE_PARTIAL_PATH_CONTACTS}/${v.FIREBASE_PARTIAL_PATH_GLOBAL}/`,this.paths.logins=`${e}/${v.FIREBASE_PARTIAL_PATH_CONTACTS}/${v.FIREBASE_PARTIAL_PATH_LOGINS}/`,this.paths.userFeedback=`${e}/${v.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${v.FIREBASE_PARTIAL_PATH_FEEDBACK}/`,this.paths.userReportBugs=`${e}/${v.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${v.FIREBASE_PARTIAL_PATH_BUGS}/`,this.paths.userContactUs=`${e}/${v.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${v.FIREBASE_PARTIAL_PATH_CONTACT_US}/`,this.organizationId&&(this.paths.organizationMetadata=`${e}/${v.FIREBASE_PARTIAL_PATH_ORGANIZATION_METADATA}/`,this.paths.organizationIam=`${e}/${v.FIREBASE_PARTIAL_PATH_IAM}/`,this.paths.organizationGroups=`${e}/${v.FIREBASE_PARTIAL_PATH_ORGANIZATION_GROUPS}/`,this.paths.organizationNotifications=`${e}/${v.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/`,this.documentId&&(this.paths.organizationNotificationsWithDocumentId=`${e}/${v.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/`,this.paths.heartbeatByDocument=`${e}/${v.FIREBASE_PARTIAL_PATH_HEARTBEAT_BY_DOCUMENT}/${this.documentId}/`),this.paths.organizationNotificationsLastNotificationTimestamp=`${e}/${v.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${v.FIREBASE_PARTIAL_PATH_LAST_NOTIFICATION_TIMESTAMP}/${v.FIREBASE_PARTIAL_PATH_DOCS}/`,this.paths.organizationNotificationsUsers=`${e}/${v.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${v.FIREBASE_PARTIAL_PATH_USERS}/`,this.paths.heartbeat=`${e}/${v.FIREBASE_PARTIAL_PATH_HEARTBEAT}/`),this.paths.workspaceIam=`${this.apiKey}/${v.FIREBASE_PARTIAL_PATH_IAM}/`}}catch{}}get folder(){return this.paths.folder?this.paths.folder:this.throwError("Folder path is not available.")}get userConfig(){return this.paths.userConfig?this.paths.userConfig:this.throwError("User config path is not available.")}get workspaceIam(){return this.paths.workspaceIam?this.paths.workspaceIam:this.throwError("Workspace IAM path is not available.")}get docs(){return this.paths.docs?this.paths.docs:this.throwError("Docs path is not available.")}get presence(){return this.paths.presence?this.paths.presence:this.throwError("Presence path is not available.")}get cursor(){return this.paths.cursor?this.paths.cursor:this.throwError("Cursor path is not available.")}get area(){return this.paths.area?this.paths.area:this.throwError("Area path is not available.")}get arrow(){return this.paths.arrow?this.paths.arrow:this.throwError("Arrow path is not available.")}get comment(){return this.paths.comment?this.paths.comment:this.throwError("Comment path is not available.")}get multiThread(){return this.paths.multiThread?this.paths.multiThread:this.throwError("Multi thread path is not available.")}get tag(){return this.paths.tag?this.paths.tag:this.throwError("Tag path is not available.")}get selection(){return this.paths.selection?this.paths.selection:this.throwError("Selection path is not available.")}get audioHuddle(){return this.paths.audioHuddle?this.paths.audioHuddle:this.throwError("Audio huddle path is not available.")}get huddle(){return this.paths.huddle?this.paths.huddle:this.throwError("Huddle path is not available.")}get recorder(){return this.paths.recorder?this.paths.recorder:this.throwError("Recorder path is not available.")}get flock(){return this.paths.flock?this.paths.flock:this.throwError("Flock path is not available.")}get syncVideoPlayer(){return this.paths.syncVideoPlayer?this.paths.syncVideoPlayer:this.throwError("Sync video player path is not available.")}get liveState(){return this.paths.liveState?this.paths.liveState:this.throwError("Live state path is not available.")}get liveStateSingleEditorMode(){return this.paths.liveStateSingleEditorMode?this.paths.liveStateSingleEditorMode:this.throwError("Live state single editor mode path is not available.")}get reaction(){return this.paths.reaction?this.paths.reaction:this.throwError("Reaction path is not available.")}get crdt(){return this.paths.crdt?this.paths.crdt:this.throwError("CRDT path is not available.")}get views(){return this.paths.views?this.paths.views:this.throwError("Views path is not available.")}get notifications(){return this.paths.notifications?this.paths.notifications:this.throwError("Notifications path is not available.")}get metadata(){return this.paths.metadata?this.paths.metadata:this.throwError("Metadata path is not available.")}get users(){return this.paths.users?this.paths.users:this.throwError("Users path is not available.")}get documentIam(){return this.paths.documentIam?this.paths.documentIam:this.throwError("Document IAM path is not available.")}get organizationMetadata(){return this.paths.organizationMetadata?this.paths.organizationMetadata:this.throwError("Organization metadata path is not available.")}get organizationIam(){return this.paths.organizationIam?this.paths.organizationIam:this.throwError("Organization IAM path is not available.")}get customerMetadata(){return this.paths.customerMetadata?this.paths.customerMetadata:this.throwError("Customer metadata path is not available.")}get groupContacts(){return this.paths.groupContacts?this.paths.groupContacts:this.throwError("Group contacts path is not available.")}get globalContacts(){return this.paths.globalContacts?this.paths.globalContacts:this.throwError("Global contacts path is not available.")}get logins(){return this.paths.logins?this.paths.logins:this.throwError("Logins path is not available.")}get userFeedback(){return this.paths.userFeedback?this.paths.userFeedback:this.throwError("User feedback path is not available.")}get userReportBugs(){return this.paths.userReportBugs?this.paths.userReportBugs:this.throwError("User report bugs path is not available.")}get userContactUs(){return this.paths.userContactUs?this.paths.userContactUs:this.throwError("User contact us path is not available.")}get organizationGroups(){return this.paths.organizationGroups?this.paths.organizationGroups:this.throwError("Organization groups path is not available.")}get heartbeat(){return this.paths.heartbeat?this.paths.heartbeat:this.throwError("Heartbeat path is not available.")}get heartbeatByDocument(){return this.paths.heartbeatByDocument?this.paths.heartbeatByDocument:this.throwError("Heartbeat by document 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(e){throw{type:"DocumentPaths",message:e,metadata:{apiKey:this.apiKey,documentId:this.documentId,organizationId:this.organizationId}}}};var zz=(()=>{let e=class e{constructor(t,i,o){this.coreActionsService=t,this.loggingService=i,this.usersService=o}getUserIdsToResolveFromLiveStateCustom(t){try{let i=new Set;return t?.updatedBy&&i.add(t?.updatedBy?.userId),Array.from(i)}catch(i){return this.loggingService.catch("Error in LiveStateUtilsService getUserIdsToResolveFromLiveStateCustom:",i),[]}}mergeLiveStateCustomWithUser(t){try{if(t?.updatedBy?.userId){let i=this.usersService.getUserById(t?.updatedBy?.userId);i&&(t.updatedBy=i)}return t}catch(i){return this.loggingService.catch("Error in LiveStateUtilsService mergeLiveStateCustomWithUser:",i),t}}formatLiveStateCustomData(t){try{return this.usersService.userDataProviderAvailable()&&t?.updatedBy&&(t.updatedBy={userId:t.updatedBy.userId}),t}catch(i){return this.loggingService.catch("Error in LiveStateUtilsService formatLiveStateCustomData:",i),t}}getUserIdsToResolveFromLiveStateCustoms(t){try{let i=new Set;for(let o of t)o?.updatedBy?.userId&&i.add(o?.updatedBy?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in LiveStateUtilsService getUserIdsToResolveFromLiveStateCustoms:",i),[]}}getUserIdsToResolveFromLiveStates(t){try{let i=new Set;return t?.default?.singleEditorMode?.editor?.userId&&i.add(t?.default?.singleEditorMode?.editor?.userId),Array.from(i)}catch(i){return this.loggingService.catch("Error in LiveStateUtilsService getUserIdsToResolveFromLiveStates:",i),[]}}getUserIdsToResolveFromLiveStateSingleEditorMode(t){try{let i=new Set;return t?.editor?.userId&&i.add(t?.editor?.userId),t?.requestEditorAccess?.user?.userId&&i.add(t?.requestEditorAccess?.user?.userId),Array.from(i)}catch(i){return this.loggingService.catch("Error in LiveStateUtilsService getUserIdsToResolveFromLiveStateSingleEditorMode:",i),[]}}mergeLiveStateWithUser(t){try{if(t?.default?.singleEditorMode?.editor?.userId){let i=this.usersService.getUserById(t?.default?.singleEditorMode?.editor?.userId);i&&(t.default.singleEditorMode.editor=i)}if(t?.default?.singleEditorMode?.requestEditorAccess?.user?.userId){let i=this.usersService.getUserById(t?.default?.singleEditorMode?.requestEditorAccess?.user?.userId);i&&(t.default.singleEditorMode.requestEditorAccess.user=i)}return t}catch(i){return this.loggingService.catch("Error in LiveStateUtilsService mergeLiveStateWithUser:",i),t}}mergeSingleEditorLiveStateDataWithUser(t){try{if(t?.editor?.userId){let i=this.usersService.getUserById(t?.editor?.userId);i&&(t.editor=i)}if(t?.requestEditorAccess?.user?.userId){let i=this.usersService.getUserById(t?.requestEditorAccess?.user?.userId);i&&(t.requestEditorAccess.user=i)}return t}catch(i){return this.loggingService.catch("Error in LiveStateUtilsService mergeSingleEditorLiveStateDataWithUser:",i),t}}resolveAndMergeSingleEditorLiveStateDataWithUser(t){return I(this,null,function*(){try{let i=this.getUserIdsToResolveFromLiveStates({default:{singleEditorMode:t}});if(i.length){let o=J(),s=tl.GET_SINGLE_EDITOR_USERS;return this.coreActionsService.triggerAction($.USER_RESOLVER,{event:L.Events.Resolver.USER_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:o,methodName:xn.RESOLVE_AND_MERGE_SINGLE_EDITOR_LIVE_STATE_DATA_WITH_USER,moduleName:s,source:"internal",payload:{userIds:i}}),yield this.usersService.resolveUsers({userIds:i,uniqueId:o,moduleName:s}),this.mergeSingleEditorLiveStateDataWithUser(t)}return t}catch(i){return this.loggingService.catch("Error in LiveStateUtilsService resolveAndMergeSingleEditorLiveStateDataWithUser:",i),t}})}formatLiveStateSingleEditorModeData(t){try{return this.usersService.userDataProviderAvailable()&&(t?.editor?.userId&&(t.editor={userId:t.editor.userId}),t?.requestEditorAccess?.user?.userId&&(t.requestEditorAccess.user={userId:t.requestEditorAccess.user.userId})),t}catch(i){return this.loggingService.catch("Error in LiveStateUtilsService formatLiveStateSingleEditorModeData:",i),t}}mergeLiveStateCustomsWithUsers(t){try{for(let i of t)if(i?.updatedBy?.userId){let o=this.usersService.getUserById(i?.updatedBy?.userId);o&&(i.updatedBy=o)}return t}catch(i){return this.loggingService.catch("Error in mergeLiveStateCustomsWithUsers:",i),t}}};e.\u0275fac=function(i){return new(i||e)(w(It),w(_e),w(zt))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let n=e;return n})();var Zy=(()=>{let e=class e{constructor(t,i,o){this.coreActionsService=t,this.loggingService=i,this.analyticsService=o,this.resolveTimeout=60*1e3,this.retryDeleteConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.retryGetConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.notificationDataProvider$=new Y(null),this.notificationById$=new Y({}),this.inFlightRequests=new Map,this.getNotificationById=s=>{try{return this.notificationDataProviderAvailable()?this.notificationById$.value?.[s]:void 0}catch(a){this.loggingService.catch("Error in NotificationResolverService getNotificationById:",a);return}};try{this.loggingService.log("NotificationResolverService initialized"),this.notificationDataProvider$.subscribe(s=>{s&&(s.config?.resolveTimeout&&(this.resolveTimeout=s.config.resolveTimeout),s.config?.deleteRetryConfig&&(this.retryDeleteConfig=s.config.deleteRetryConfig),s.config?.getRetryConfig&&(this.retryGetConfig=s.config.getRetryConfig))})}catch(s){this.loggingService.catch("Error in NotificationResolverService constructor:",s)}}getProvider(){try{let t=this.notificationDataProvider$.getValue();return t||void 0}catch(t){this.loggingService.catch("Error in NotificationResolverService getProvider:",t);return}}ngOnDestroy(){try{this.notificationById$.next({})}catch(t){this.loggingService.catch("Error in NotificationResolverService ngOnDestroy:",t)}}resolveNotifications(s){return I(this,arguments,function*({request:t,uniqueId:i,moduleName:o}){try{if(this.loggingService.log("%c[WB] Calling NotificationResolverService FUNCTION: resolveNotifications","color: green;"),!this.notificationDataProviderAvailable())return{};let a,c=!1,l=!1,u=()=>{a&&(clearTimeout(a),a=void 0,l=!0)};return new Promise((d,f)=>{a=setTimeout(()=>{if(!l){c=!0,u();let k=i||J();this.coreActionsService.triggerAction($.NOTIFICATION_RESOLVER,{event:L.Events.Resolver.NOTIFICATION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:k,methodName:Fn.RESOLVE_NOTIFICATIONS,moduleName:o,source:"internal",payload:{error:new Error("Notification resolution timeout"),request:t}}),f(new Error("Notification resolution timeout"))}},this.notificationDataProvider$.value?.config?.resolveTimeout||this.resolveTimeout);let g=this.getProvider();if(!g)return u(),d({});let p={},_=this.notificationById$.getValue()||{},T=[...new Set(t.notificationIds||[])],D=[],b=[],G=[];for(let k of T)_[k]||(this.inFlightRequests.has(k)?(D.push(this.inFlightRequests.get(k)),b.push(k)):G.push(k));let M=le(x({},t),{notificationIds:G});I(this,null,function*(){try{if(D.length>0&&(yield Promise.allSettled(D)),G.length>0){let k=i||J();this.coreActionsService.triggerAction($.NOTIFICATION_RESOLVER,{event:L.Events.Resolver.NOTIFICATION_RESOLUTION_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:k,methodName:Fn.RESOLVE_NOTIFICATIONS,moduleName:o,source:"internal",payload:{request:M}});let S,A=new Promise(O=>{S=O});for(let O of G)this.inFlightRequests.set(O,A.then(P=>P?.[O]));let C=kt(()=>g?.config?.getConfig?.url?Ht(g.config.getConfig.url,g.config.getConfig.headers,M,!0,g.config.getConfig.credentials):g?.get?.(M)||Promise.resolve(void 0),"getNotifications",this.retryGetConfig).then(O=>c?{}:(u(),O&&O.statusCode!==200?(this.coreActionsService.triggerAction($.NOTIFICATION_RESOLVER,{event:L.Events.Resolver.NOTIFICATION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:k,methodName:Fn.RESOLVE_NOTIFICATIONS,moduleName:o,source:"internal",payload:{result:O,request:M}}),this.loggingService.catch(O?.message??"Error in NotificationResolverService resolveNotifications:"),{}):O?.data)).catch(O=>{throw u(),O});try{p=(yield C)||{},S(p);for(let P of G)this.inFlightRequests.delete(P);this.analyticsService.trackEvent(L.Events.Resolver.NOTIFICATION_RESOLVER_GET,{sourceMethod:"resolveNotifications",source:"sdk",notificationIds:G});let O={};Object.entries(p).forEach(([P,F])=>{let N=this.notificationById$.value?.[P];N?N&&JSON.stringify(N)!==JSON.stringify(F)&&(O[P]=F):O[P]=F}),Object.keys(O).length>0&&this.notificationById$.next(x(x({},this.notificationById$.getValue()),O)),this.coreActionsService.triggerAction($.NOTIFICATION_RESOLVER,{event:L.Events.Resolver.NOTIFICATION_RESOLUTION_RESULT,timestamp:new Date().getTime(),uniqueId:k,methodName:Fn.RESOLVE_NOTIFICATIONS,moduleName:o,source:"internal",payload:{result:O,request:M}}),d(O)}catch(O){S({});for(let F of G)this.inFlightRequests.delete(F);let P=i||J();this.coreActionsService.triggerAction($.NOTIFICATION_RESOLVER,{event:L.Events.Resolver.NOTIFICATION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:P,methodName:Fn.RESOLVE_NOTIFICATIONS,moduleName:o,source:"internal",payload:{error:O,request:M}}),c||f(O),d(p)}}else u(),d({})}catch(k){u();let S=i||J();this.coreActionsService.triggerAction($.NOTIFICATION_RESOLVER,{event:L.Events.Resolver.NOTIFICATION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:S,methodName:Fn.RESOLVE_NOTIFICATIONS,moduleName:o,source:"internal",payload:{error:k,request:M}}),f(k)}})})}catch(a){this.loggingService.catch("Error in NotificationResolverService resolveNotifications:",a);let c=i||J();return this.coreActionsService.triggerAction($.NOTIFICATION_RESOLVER,{event:L.Events.Resolver.NOTIFICATION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:c,methodName:Fn.RESOLVE_NOTIFICATIONS,moduleName:o,source:"internal",payload:{error:a,request:t}}),{}}})}deleteNotification(t,i,o){return I(this,null,function*(){try{this.loggingService.log("%c[WB] Calling NotificationResolverService FUNCTION: deleteNotification","color: green;");let s=this.getProvider();if(!this.notificationDataProviderAvailable())throw new Error("Notification delete data provider not available");let a=o||J();this.coreActionsService.triggerAction($.NOTIFICATION_RESOLVER,{event:L.Events.Resolver.NOTIFICATION_DELETE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:a,methodName:Fn.DELETE_NOTIFICATION,source:"internal",payload:{notificationId:t,organizationId:i}});let c=this.notificationById$.getValue(),l=x({},c);delete l?.[t],this.notificationById$._value=l;let u={notificationId:t,organizationId:i},d=yield kt(()=>s?.config?.deleteConfig?.url?Ht(s.config.deleteConfig.url,s.config.deleteConfig.headers,u,!1,s.config.deleteConfig.credentials):s?.delete?.(u)||Promise.resolve(void 0),"deleteNotification",this.retryDeleteConfig);return d&&d.statusCode!==200?(this.retryDeleteConfig.revertOnFailure&&(this.notificationById$._value=c),this.loggingService.catch(d?.message??"Error in NotificationResolverService deleteNotification:"),this.coreActionsService.triggerAction($.NOTIFICATION_RESOLVER,{event:L.Events.Resolver.NOTIFICATION_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:a,methodName:Fn.DELETE_NOTIFICATION,source:"internal",payload:{error:d,notificationId:t,organizationId:i}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(L.Events.Resolver.NOTIFICATION_RESOLVER_DELETE,{sourceMethod:"deleteNotification",source:"sdk",notificationId:t}),this.coreActionsService.triggerAction($.NOTIFICATION_RESOLVER,{event:L.Events.Resolver.NOTIFICATION_DELETE_RESULT,timestamp:new Date().getTime(),uniqueId:a,methodName:Fn.DELETE_NOTIFICATION,source:"internal",payload:{result:{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0},notificationId:t,organizationId:i}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0})}catch(s){this.loggingService.warn("Error in NotificationResolverService deleteNotification:",s);let a=o||J();return this.coreActionsService.triggerAction($.NOTIFICATION_RESOLVER,{event:L.Events.Resolver.NOTIFICATION_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:a,methodName:Fn.DELETE_NOTIFICATION,source:"internal",payload:{error:s,notificationId:t,organizationId:i}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0}}})}getNotificationsById$(){try{return this.notificationDataProviderAvailable()?(this.loggingService.log("%c[WB] Calling NotificationResolverService FUNCTION: getNotificationsById$","color: green;"),this.notificationById$.asObservable()):ue(void 0)}catch(t){return this.loggingService.catch("Error in NotificationResolverService getNotificationsById$:",t),ue(void 0)}}setNotificationDataProvider(t){try{if(t){this.loggingService.log("Setting notification data provider");let i=t.config,o=[{method:"get",configKey:"getConfig"},{method:"delete",configKey:"deleteConfig"}],s=[];if(o.forEach(({method:a,configKey:c})=>{let l=i?.[c]?.url,u=a in t&&typeof t[a]=="function";!l&&!u&&s.push(a)}),s.length>0){let a=`DataProviders.notification is invalid. The following methods are missing or are not functions (and no corresponding config provided): ${s.join(", ")}.`;this.loggingService.catch(a);return}else this.notificationDataProvider$.next(t)}}catch(i){this.loggingService.catch("Error in NotificationResolverService setNotificationDataProvider:",i)}}notificationDataProviderAvailable(){try{return!!this.notificationDataProvider$.getValue()}catch(t){return this.loggingService.catch("Error in NotificationResolverService notificationDataProviderAvailable:",t),!1}}};e.\u0275fac=function(i){return new(i||e)(w(It),w(_e),w(Lt))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let n=e;return n})();var Np=class{constructor({apiKey:e,documentId:r,organizationId:t,clientDocumentId:i,clientOrganizationId:o,folderId:s,veltFolderId:a}){this.paths={},this.apiKey=e,this.documentId=r,this.organizationId=t,this.veltFolderId=a,i&&(this.documentId=da(i)),o&&(this.organizationId=Ts(o)),s&&(this.folderId=s,this.veltFolderId=wo(s)),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 e=`apiKey/${this.apiKey}`;this.paths.activities=`${e}/${v.FIREBASE_PARTIAL_PATH_ACTIVITIES}`,this.paths.userNotificationIndex=`${e}/${v.FIREBASE_PARTIAL_PATH_USER_NOTIFICATION_INDEX}`,this.organizationId&&(e=`${e}/${v.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${this.paths.organizationId}`,this.paths.organization=e,this.paths.folder=`${e}/${v.FIREBASE_PARTIAL_PATH_FOLDERS}`,this.paths.organizationUsers=`${e}/${v.FIREBASE_PARTIAL_PATH_ORGANIZATION_USERS}`,this.paths.users=`${e}/${v.FIREBASE_PARTIAL_PATH_CENTRAL_USERS}`,this.paths.notificationDocs=`${e}/${v.FIREBASE_PARTIAL_PATH_NOTIFICATION_DOCS}`,this.paths.notificationUsers=`${e}/${v.FIREBASE_PARTIAL_PATH_NOTIFICATION_USERS}`,this.paths.organizationGroups=`${e}/${v.FIREBASE_PARTIAL_PATH_GROUPS}`,this.paths.lastNotificationTimestamp=`${e}/${v.FIREBASE_PARTIAL_PATH_LAST_NOTIFICATION_TIMESTAMP}`,this.paths.lastActivityTimestamp=`${e}/${v.FIREBASE_PARTIAL_PATH_LAST_ACTIVITY_TIMESTAMP}`,this.paths.userConfig=`${e}/${v.FIREBASE_PARTIAL_PATH_USERS}`,this.paths.permissionsUsers=`${e}/${v.FIREBASE_PARTIAL_PATH_PERMISSIONS_USERS}`),this.veltFolderId&&(this.paths.folderUsers=`${e}/${v.FIREBASE_PARTIAL_PATH_FOLDERS}/${this.veltFolderId}/${v.FIREBASE_PARTIAL_PATH_FOLDER_USERS}`),this.documentId&&(this.paths.document=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}`,this.paths.comment=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_COMMENT}`,this.paths.location=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_LOCATION}`,this.paths.multiThread=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_MULTI_THREAD}`,this.paths.area=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_AREA}`,this.paths.recorder=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_RECORDER}`,this.paths.reaction=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_REACTION}`,this.paths.crdt=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_CRDT}`,this.paths.notificationViews=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_NOTIFICATION_VIEWS}`,this.paths.documentViews=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_DOCUMENT_VIEWS}`,this.paths.locationViews=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_LOCATION_VIEWS}`,this.paths.documentUsers=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_DOCUMENT_USERS}`,this.paths.docNotification=`${this.paths.notificationDocs}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_DOC_NOTIFICATION}`)}}catch{}}get userNotificationIndex(){return this.paths.userNotificationIndex}get permissionsUsers(){return this.paths.permissionsUsers?this.paths.permissionsUsers:this.throwError("PermissionsUsers path is not available.")}get users(){return this.paths.users?this.paths.users:this.throwError("Users path is not available.")}get userConfig(){return this.paths.userConfig?this.paths.userConfig:this.throwError("UserConfig path is not available.")}get folder(){return this.paths.folder?this.paths.folder:this.throwError("Folder path is not available.")}get lastNotificationTimestamp(){return this.paths.lastNotificationTimestamp?this.paths.lastNotificationTimestamp:this.throwError("LastNotificationTimestamp path is not available.")}get organizationGroups(){return this.paths.organizationGroups?this.paths.organizationGroups:this.throwError("organizationGroups path is not available.")}get docNotification(){return this.paths.docNotification?this.paths.docNotification:this.throwError("DocNotification path is not available.")}get organization(){return this.paths.organization?this.paths.organization:this.throwError("Organization path is not available.")}get document(){return this.paths.document?this.paths.document:this.throwError("Document path is not available.")}get location(){return this.paths.location?this.paths.location:this.throwError("Location path is not available.")}get area(){return this.paths.area?this.paths.area:this.throwError("Area path is not available.")}get comment(){return this.paths.comment?this.paths.comment:this.throwError("Comment path is not available.")}get documentViews(){return this.paths.documentViews?this.paths.documentViews:this.throwError("DocumentViews path is not available.")}get locationViews(){return this.paths.locationViews?this.paths.locationViews:this.throwError("LocationViews path is not available.")}get notificationViews(){return this.paths.notificationViews?this.paths.notificationViews:this.throwError("NotificationViews path is not available.")}get documentUsers(){return this.paths.documentUsers?this.paths.documentUsers:this.throwError("DocumentUsers path is not available.")}get folderUsers(){return this.paths.folderUsers?this.paths.folderUsers:this.throwError("FolderUsers path is not available.")}get organizationUsers(){return this.paths.organizationUsers?this.paths.organizationUsers:this.throwError("OrganizationUsers path is not available.")}get notificationDocs(){return this.paths.notificationDocs?this.paths.notificationDocs:this.throwError("NotificationDocs path is not available.")}get notificationUsers(){return this.paths.notificationUsers?this.paths.notificationUsers:this.throwError("NotificationUsers path is not available.")}get multiThread(){return this.paths.multiThread?this.paths.multiThread:this.throwError("Multi thread path is not available.")}get recorder(){return this.paths.recorder?this.paths.recorder:this.throwError("Recorder path is not available.")}get reaction(){return this.paths.reaction?this.paths.reaction:this.throwError("Reaction path is not available.")}get crdt(){return this.paths.crdt?this.paths.crdt:this.throwError("CRDT path is not available.")}get activities(){return this.paths.activities?this.paths.activities:this.throwError("Activities path is not available.")}get lastActivityTimestamp(){return this.paths.lastActivityTimestamp?this.paths.lastActivityTimestamp:this.throwError("LastActivityTimestamp path is not available.")}throwError(e){throw{type:"DocumentPaths",message:e,metadata:{apiKey:this.apiKey,documentId:this.documentId,organizationId:this.organizationId}}}};var Kz=(()=>{let e=class e{constructor(t,i){this.loggingService=t,this.usersService=i}getUserIdsToResolveFromAreaAnnotations(t){try{this.loggingService.log("%c[WB] Calling AreaUtilsService FUNCTION: getUserIdsToResolveFromAreaAnnotations","color: green;");let i=new Set;for(let o of t)o?.from?.userId&&i.add(o?.from?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in AreaUtilsService getUserIdsToResolveFromAreaAnnotations:",i),[]}}mergeAreaWithUser(t){try{if(this.loggingService.log("%c[WB] Calling AreaUtilsService FUNCTION: mergeAreaWithUser","color: green;"),t?.from?.userId){let i=this.usersService.getUserById(t?.from?.userId);i&&(t.from=i)}return t}catch(i){return this.loggingService.catch("Error in AreaUtilsService mergeAreaWithUser:",i),t}}formatAreaData(t){try{return this.loggingService.log("%c[WB] Calling AreaUtilsService FUNCTION: formatAreaData","color: green;"),this.usersService.userDataProviderAvailable()&&t?.from?.userId&&(t.from={userId:t.from.userId}),t}catch(i){return this.loggingService.catch("Error in AreaUtilsService formatAreaData:",i),t}}};e.\u0275fac=function(i){return new(i||e)(w(_e),w(zt))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let n=e;return n})();var Yz=(()=>{let e=class e{constructor(t,i){this.loggingService=t,this.usersService=i}getUserIdsToResolveFromUserIamData(t){try{this.loggingService.log("%c[WB] Calling ContactUtilsService FUNCTION: getUserIdsToResolveFromUserIamData","color: green;");let i=new Set;if(t?.length)for(let o of t)o?.user?.userId&&i.add(o?.user?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in ContactUtilsService getUserIdsToResolveFromUserIamData: ",i),[]}}mergeUserIamWithUser(t){try{if(this.loggingService.log("%c[WB] Calling ContactUtilsService FUNCTION: mergeUserIamWithUser","color: green;"),t?.user?.userId){let i=this.usersService.getUserById(t?.user?.userId);if(i){let o=i;t?.user&&typeof t.user=="object"&&(o=x(x({},o),t.user));let s=this.usersService.getContactListUser(t.user.userId);s&&(o=x(x({},o),s)),t=le(x({},t),{user:o})}}return t}catch(i){return this.loggingService.catch("Error in ContactUtilsService mergeUserIamWithUser: ",i),t}}};e.\u0275fac=function(i){return new(i||e)(w(_e),w(zt))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let n=e;return n})();var Qz=(()=>{let e=class e{constructor(t,i){this.loggingService=t,this.usersService=i}getUserIdsToResolveFromMultiThreads(t){try{let i=new Set;for(let o of t)o?.from?.userId&&i.add(o?.from?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in MultiThreadUtilsService getUserIdsToResolveFromMultiThreads:",i),[]}}mergeMultiThreadWithUser(t){try{if(t?.from?.userId){let i=this.usersService.getUserById(t?.from?.userId);i&&(t.from=i)}return t}catch(i){return this.loggingService.catch("Error in MultiThreadUtilsService mergeMultiThreadWithUser:",i),t}}formatMultiThreadData(t){try{return this.usersService.userDataProviderAvailable()&&(t?.from?.userId&&(t.from={userId:t.from.userId}),t?.commentAnnotationsMap&&(t.commentAnnotationsMap=null)),t}catch(i){return this.loggingService.catch("Error in MultiThreadUtilsService formatMultiThreadData:",i),t}}};e.\u0275fac=function(i){return new(i||e)(w(_e),w(zt))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let n=e;return n})();var Xz=(()=>{let e=class e{constructor(t,i){this.loggingService=t,this.usersService=i}getUserIdsToResolveFromSelections(t){try{let i=new Set;for(let o of t)o?.user?.userId&&i.add(o.user.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in SelectionUtilsService getUserIdsToResolveFromSelections:",i),[]}}mergeSelectionWithUser(t){try{if(t?.user?.userId){let i=this.usersService.getUserById(t?.user?.userId);i&&(t.user=i)}return t}catch(i){return this.loggingService.catch("Error in SelectionUtilsService mergeSelectionWithUser:",i),t}}formatSelectionData(t){try{return this.usersService.userDataProviderAvailable()&&t?.user?.userId&&(t.user={userId:t.user.userId}),t}catch(i){return this.loggingService.catch("Error in SelectionUtilsService formatSelectionData:",i),t}}};e.\u0275fac=function(i){return new(i||e)(w(_e),w(zt))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let n=e;return n})();var Jz=(()=>{let e=class e{constructor(t,i){this.loggingService=t,this.usersService=i}getUserIdsToResolveFromTags(t){try{let i=new Set;for(let o of t)if(o?.from?.userId&&i.add(o.from.userId),o?.to?.length)for(let s of o.to)s?.userId&&i.add(s.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in TagUtilsService getUserIdsToResolveFromTags:",i),[]}}mergeTagWithUser(t){try{if(t?.from?.userId){let i=this.usersService.getUserById(t?.from?.userId);i&&(t.from=i)}return t?.to?.length&&(t.to=t.to.map(i=>{if(i?.userId){let o=this.usersService.getUserById(i?.userId);o&&(i=o)}return i})),t}catch(i){return this.loggingService.catch("Error in TagUtilsService mergeTagWithUser:",i),t}}formatTagData(t){try{return this.usersService.userDataProviderAvailable()&&(t?.from?.userId&&(t.from={userId:t.from.userId}),t?.to?.length&&(t.to=t.to.map(i=>(i?.userId&&(i={userId:i.userId}),i)))),t}catch(i){return this.loggingService.catch("Error in TagUtilsService formatTagData:",i),t}}};e.\u0275fac=function(i){return new(i||e)(w(_e),w(zt))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let n=e;return n})();var Zz=(()=>{let e=class e{constructor(t,i,o,s,a,c,l,u,d,f,g,p,_,T,D,b,G,M,U,k){this.activityUtilsService=t,this.areaUtilsService=i,this.commentUtilsService=o,this.contactUtilsService=s,this.coreActionsService=a,this.liveStateUtilsService=c,this.loggingService=l,this.multiThreadUtilsService=u,this.reactionUtilsService=d,this.selectionUtilsService=f,this.tagUtilsService=g,this.usersService=p,this.docService=_,this.commentAnnotationsResolverService=T,this.reactionAnnotationsResolverService=D,this.recorderAnnotationsResolverService=b,this.notificationResolverService=G,this.activityResolverService=M,this.serviceBook=U,this.attachmentResolverService=k}getErrorForGetRequests({feature:t,error:i}){try{switch(t){case"apiKeyMetadata":case"organizationMetadata":case"documentMetadata":case"folderMetadata":return(i?.message??"")?.includes("Missing or insufficient permissions.")?{errorCode:"PERMISSION_DENIED"}:null;default:return null}}catch(o){return this.loggingService.catch("Error in CommonDbUtilsService getErrorForGetRequests:",o),null}}getFirestorePath({feature:t,properties:i,documentPaths:o,apiKey:s}){try{if(!s)return;if(t==="userNotificationIndex"){if(!i?.id)return;let d=new Np({apiKey:s});return d?.userNotificationIndex?`${d.userNotificationIndex}/${i.id}`:void 0}let{documentId:a,organizationId:c,folderId:l}=i;if(!c&&(c=o?.organizationId,!c))return;let u=new Np({apiKey:s,documentId:a?`${a}`:"",organizationId:c?`${c}`:"",veltFolderId:l?`${l}`:void 0});switch(t){case"userConfig":return i?.userId&&u?.userConfig?`${u?.userConfig}/${i?.userId}${i?.documentId?`/${v.FIREBASE_PARTIAL_PATH_DOCUMENT_CONFIGURATIONS}/${i?.documentId}`:""}`:void 0;case"allPermissionsUsers":return u?.permissionsUsers?`${u?.permissionsUsers}`:void 0;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"crdt":return i?.documentId&&u?.crdt&&i?.id?`${u?.crdt}/${i?.id}`: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"activity":return i?.id&&u?.activities?`${u?.activities}/${i?.id}`:void 0;case"allActivities":return u?.activities?`${u?.activities}`:void 0;case"allLastActivityTimestamp":return u?.lastActivityTimestamp?`${u?.lastActivityTimestamp}`:void 0;case"lastActivityTimestamp":return i?.id&&u?.lastActivityTimestamp?`${u?.lastActivityTimestamp}/${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"recorderTrackEvent":return i?.documentId&&i?.id&&u?.recorder?`${u?.recorder}/${i?.id}/trackRecorderEvent`:void 0;case"documentAccessType":return i?.documentId&&u?.document?`${u?.document}/${i?.documentId}`:void 0;case"apiKeyMetadata":return s?`apiKey/${s}`: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 u?.users?`${u?.users}`:void 0;case"allFolderUsers":return u?.users?`${u?.users}`:void 0;case"allOrganizationGroups":return u?.organizationGroups?`${u?.organizationGroups}`:void 0;case"allOrganizationUsers":return u?.users?`${u?.users}`:void 0;case"notificationViewsTimestamp":return 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}/${v.FIREBASE_PARTIAL_PATH_USER_NOTIFICATION}/${i?.id}`:void 0;case"allUserNotifications":return i?.userId&&u?.notificationUsers?`${u?.notificationUsers}/${i?.userId}/${v.FIREBASE_PARTIAL_PATH_USER_NOTIFICATION}`:void 0;default:throw new Error(`Unknown feature: ${t}`)}}catch(a){this.loggingService.catch("Error in CommonDbUtilsService getFirestorePath:",a);return}}getFirestoreCollectionGroupPath(t){try{switch(t){case"allComments":return v.FIREBASE_PARTIAL_PATH_COMMENT;case"allDocuments":return v.FIREBASE_PARTIAL_PATH_DOCS;case"allLocations":return v.FIREBASE_PARTIAL_PATH_LOCATION;case"allMultiThreads":return v.FIREBASE_PARTIAL_PATH_MULTI_THREAD;case"allAreas":return v.FIREBASE_PARTIAL_PATH_AREA;case"allReactions":return v.FIREBASE_PARTIAL_PATH_REACTION;case"allRecorders":return v.FIREBASE_PARTIAL_PATH_RECORDER;case"allDocumentViews":return v.FIREBASE_PARTIAL_PATH_DOCUMENT_VIEWS;case"allLocationViews":return v.FIREBASE_PARTIAL_PATH_LOCATION_VIEWS;case"allDocumentUsers":return v.FIREBASE_PARTIAL_PATH_DOCUMENT_USERS;case"allFolderUsers":return v.FIREBASE_PARTIAL_PATH_FOLDER_USERS;default:throw new Error(`Unknown feature: ${t}`)}}catch(i){this.loggingService.catch("Error in CommonDbUtilsService getFirestoreCollectionGroupPath:",i);return}}getDocumentPath({feature:t,properties:i,defaultDocumentPaths:o,apiKey:s,useFirestore:a}){try{if(!s)return;let{documentId:c,organizationId:l}=i;l||(l=o?.organizationId);let u=new Jy({apiKey:s,documentId:c?`${c}`:"",organizationId:l?`${l}`:""});switch(t){case"userConfig":return i?.userId&&i?.documentId&&u?.userConfig?`${u?.userConfig}/${i?.userId}/${v.FIREBASE_PARTIAL_PATH_DOCUMENT_CONFIGURATIONS}/${i?.documentId}`:void 0;case"allComments":return!a&&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"liveStateAutoSyncState":return i?.documentId&&u?.liveState?`${u?.liveState}default/autoSyncState`: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!a&&i?.documentId&&i?.id&&u?.comment?`${u?.comment}${i?.id}`:void 0;case"allMultiThreads":return!a&&i?.documentId&&u?.multiThread?`${u?.multiThread}`:void 0;case"crdt":return!a&&i?.documentId&&u?.crdt?`${u?.crdt}`:void 0;case"crdtData":return i?.documentId&&u?.crdt&&i?.id?`${u?.crdt}/${i?.id}/data`:void 0;case"crdtSyncState":return i?.documentId&&u?.crdt&&i?.id?`${u?.crdt}/${i?.id}/sync/state`:void 0;case"crdtSyncPresence":return i?.documentId&&i.userId&&u?.crdt&&i?.id?`${u?.crdt}/${i?.id}/sync/presence/${i.userId}`:void 0;case"allCrdtSyncPresence":return i?.documentId&&u?.crdt&&i?.id?`${u?.crdt}/${i?.id}/sync/presence`:void 0;case"crdtPresence":return i?.documentId&&i.userId&&u?.crdt&&i?.id?`${u?.crdt}/${i?.id}/presence/${i.userId}`:void 0;case"allCrdtPresence":return i?.documentId&&u?.crdt&&i?.id?`${u?.crdt}/${i?.id}/presence`:void 0;case"crdtVersion":return i?.documentId&&u?.crdt&&i?.id&&i?.versionId?`${u?.crdt}/${i?.id}/versions/${i?.versionId}`:void 0;case"crdtVersions":return i?.documentId&&u?.crdt&&i?.id?`${u?.crdt}/${i?.id}/versions`:void 0;case"crdtMessages":return i?.documentId&&u?.crdt&&i?.id?`${u?.crdt}/${i?.id}/messages`:void 0;case"crdtMessage":return i?.documentId&&u?.crdt&&i?.id&&i?.messageId?`${u?.crdt}/${i?.id}/messages/${i?.messageId}`:void 0;case"crdtSnapshot":return i?.documentId&&u?.crdt&&i?.id?`${u?.crdt}/${i?.id}/snapshot`:void 0;case"multiThread":return!a&&i?.documentId&&i?.id&&u?.multiThread?`${u?.multiThread}${i?.id}`:void 0;case"allLastNotificationTimestamp":return!a&&u?.organizationNotificationsLastNotificationTimestamp?`${u?.organizationNotificationsLastNotificationTimestamp}`:void 0;case"lastNotificationTimestamp":return!a&&i?.id&&u?.organizationNotificationsLastNotificationTimestamp?`${u?.organizationNotificationsLastNotificationTimestamp}${i?.id}`:void 0;case"documentIam":return!a&&i?.documentId&&u?.documentIam?`${u?.documentIam}`:void 0;case"allDocuments":return!a&&u?.docs&&i?.documentId?`${u?.docs}/${i?.documentId}/${v.FIREBASE_PARTIAL_PATH_METADATA}`:void 0;case"allAreas":return!a&&i?.documentId&&u?.area?`${u?.area}`:void 0;case"area":return!a&&i?.id&&u?.area?`${u?.area}${i?.id}`:void 0;case"folder":return!a&&i?.folderId&&u?.folder?`${u?.folder}${i?.folderId}`:void 0;case"documentUserAccess":return!a&&i?.id&&u?.documentIam?`${u?.documentIam}users/${i?.id}`:void 0;case"documentUser":return!a&&i?.documentId&&i?.id&&u?.documentIam?`${u?.documentIam}users/${i?.id}`:void 0;case"allDocumentUsers":return!a&&i?.documentId&&u?.documentIam?`${u?.documentIam}users/`:void 0;case"allOrganizationGroups":return!a&&u?.organizationGroups?`${u?.organizationGroups}`:void 0;case"allOrganizationUsers":return!a&&u?.organizationIam?`${u?.organizationIam}users/`:void 0;case"reaction":return!a&&i?.id&&u?.reaction?`${u?.reaction}${i?.id}`:void 0;case"allReactions":return!a&&i?.documentId&&u?.reaction?`${u?.reaction}`:void 0;case"recorder":return!a&&i?.documentId&&i?.id&&u?.recorder?`${u?.recorder}${i?.id}`:void 0;case"allRecorders":return!a&&i?.documentId&&u?.recorder?`${u?.recorder}`:void 0;case"organizationMetadata":return!a&&u?.organizationMetadata?`${u?.organizationMetadata}`:void 0;case"heartbeat":return i?.id&&u?.heartbeat?`${u?.heartbeat}${i?.id}`:void 0;case"allHeartbeats":return u?.heartbeat?`${u?.heartbeat}`:void 0;case"heartbeatByDocument":return i?.id&&u?.heartbeatByDocument?`${u?.heartbeatByDocument}${i?.id}`:void 0;case"allHeartbeatsByDocument":return u?.heartbeatByDocument?`${u?.heartbeatByDocument}`:void 0;case"documentAccessType":return!a&&u?.documentIam?`${u?.documentIam}`:void 0;case"documentMetadata":return!a&&i?.documentId&&u?.metadata?`${u?.metadata}`:void 0;case"allDocumentViews":return!a&&i?.documentId&&u?.views?`${u?.views}documentViews/`:void 0;case"documentViews":return!a&&i?.documentId&&i?.id&&u?.views?`${u?.views}documentViews/${i?.id}`:void 0;case"allLocationViews":return!a&&i?.documentId&&u?.views?`${u?.views}locationViews/`:void 0;case"notificationViewsTimestamp":return!a&&i?.id&&i?.user&&u?.views?`${u?.views}notification/${i?.id}/views/${i?.user}`:void 0;case"documentUsersViews":return!a&&i?.id&&i?.user&&i?.date&&u?.views?`${u?.views}documentViews/${i?.id}/users/${i?.user}/${i?.date}`:void 0;case"documentMetadataViews":return!a&&i?.id&&u?.views?`${u?.views}documentViews/${i?.id}/metadata`:void 0;case"documentDayViews":return!a&&i?.id&&i?.date&&i?.user&&u?.views?`${u?.views}documentViews/${i?.id}/day/${i?.date}/${i?.user}`:void 0;case"locationViews":return!a&&i?.id&&u?.views?`${u?.views}locationViews/${i?.id}/location`:void 0;case"location":return!a&&i?.id&&u?.views?`${u?.views}locationViews/${i?.id}`:void 0;case"locationUsersViews":return!a&&i?.id&&i?.user&&i?.date&&u?.views?`${u?.views}locationViews/${i?.id}/users/${i?.user}/${i?.date}`:void 0;case"locationMetadataViews":return!a&&i?.id&&u?.views?`${u?.views}locationViews/${i?.id}/metadata`:void 0;case"locationDayViews":return!a&&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;case"allPermissionsUsers":return;default:throw new Error(`Unknown feature: ${t}`)}}catch(c){this.loggingService.catch("Error in CommonDbUtilsService getDocumentPath:",c);return}}resolveAnnotations(o){return I(this,arguments,function*({data:t,feature:i}){try{if(t&&t?.length>0)switch(i){case"allComments":{if(this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable()){let s=J(),a=Td.GET_COMMENT_ANNOTATIONS;this.coreActionsService.triggerAction($.COMMENT_RESOLVER,{event:L.Events.Resolver.COMMENT_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:s,methodName:Et.RESOLVE_COMMENT_ANNOTATIONS,moduleName:a,source:"internal",payload:{commentAnnotationIds:t,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""}}),this.commentAnnotationsResolverService.resolveCommentAnnotations({request:{commentAnnotationIds:t,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""},uniqueId:s,moduleName:a})}break}case"allReactions":{if(this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable()){let s=J(),a=Id.GET_REACTION_ANNOTATIONS;this.coreActionsService.triggerAction($.REACTION_RESOLVER,{event:L.Events.Resolver.REACTION_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:s,methodName:_t.RESOLVE_REACTION_ANNOTATIONS,moduleName:a,source:"internal",payload:{reactionAnnotationIds:t,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""}}),this.reactionAnnotationsResolverService.resolveReactionAnnotations({request:{reactionAnnotationIds:t,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""},uniqueId:s,moduleName:a})}break}case"allRecorders":{if(this.recorderAnnotationsResolverService.recorderAnnotationDataProviderAvailable()){let s=J(),a=vd.GET_RECORDER_ANNOTATIONS;this.coreActionsService.triggerAction($.RECORDER_RESOLVER,{event:L.Events.Resolver.RECORDER_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:s,methodName:Tt.RESOLVE_RECORDER_ANNOTATIONS,moduleName:a,source:"internal",payload:{recorderAnnotationIds:t,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""}}),this.recorderAnnotationsResolverService.resolveRecorderAnnotations({request:{recorderAnnotationIds:t,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""},uniqueId:s,moduleName:a})}break}default:break}}catch(s){this.loggingService.catch(`Error in CommonDbUtilsService resolveAnnotations: ${i}`,s)}})}formatResponse(g){return I(this,arguments,function*({feature:t,data:i,organizationId:o,shouldAwait:s=!1,forceResolve:a=!1,shouldCommentAnnotationsResolverAwait:c=!1,shouldNotificationResolverAwait:l=!1,shouldActivityResolverAwait:u=!1,shouldReactionResolverAwait:d=!1,shouldRecorderResolverAwait:f=!1}){try{let p=o??this.docService.getDocumentPaths()?.clientOrganizationId??this.docService.getOrganizationConfig()?.clientOrganizationId??"";if(this.usersService.userDataProviderAvailable()){let _=[];switch(t){case"allAreas":{i&&typeof i=="object"&&!Array.isArray(i)&&(_=this.areaUtilsService.getUserIdsToResolveFromAreaAnnotations(Object.values(i)));break}case"allArrows":{i&&typeof i=="object"&&!Array.isArray(i)&&(_=this.serviceBook.get(IT)?.getUserIdsToResolveFromArrowAnnotations(Object.values(i))??[]);break}case"allCursors":{i&&typeof i=="object"&&!Array.isArray(i)&&(_=this.serviceBook.get(vT)?.getUserIdsToResolveFromCursorUsers(Object.values(i))??[]);break}case"allComments":{i&&typeof i=="object"&&!Array.isArray(i)&&(_=this.commentUtilsService.getUserIdsToResolveFromComments(Object.values(i)));break}case"allDocumentUsers":{i&&typeof i=="object"&&!Array.isArray(i)&&(_=this.contactUtilsService.getUserIdsToResolveFromUserIamData(Object.values(i)));break}case"allFolderUsers":{i&&typeof i=="object"&&!Array.isArray(i)&&(_=this.contactUtilsService.getUserIdsToResolveFromUserIamData(Object.values(i)));break}case"allOrganizationUsers":{i&&typeof i=="object"&&!Array.isArray(i)&&(_=this.contactUtilsService.getUserIdsToResolveFromUserIamData(Object.values(i)));break}case"allMultiThreads":{i&&typeof i=="object"&&!Array.isArray(i)&&(_=this.multiThreadUtilsService.getUserIdsToResolveFromMultiThreads(Object.values(i)));break}case"allDocNotifications":{i&&typeof i=="object"&&(_=this.serviceBook.get(xi)?.getUserIdsToResolveFromNotifications(Array.isArray(i)?i:Object.values(i))??[]);break}case"allUserNotifications":{i&&typeof i=="object"&&!Array.isArray(i)&&(_=this.serviceBook.get(xi)?.getUserIdsToResolveFromNotifications(Object.values(i))??[]);break}case"allPresence":{i&&typeof i=="object"&&!Array.isArray(i)&&(_=this.serviceBook.get(yT)?.getUserIdsToResolveFromPresenceUsers(Object.values(i))??[]);break}case"allRecorders":{i&&typeof i=="object"&&!Array.isArray(i)&&(_=this.serviceBook.get(ci)?.getUserIdsToResolveFromRecorders(Object.values(i))??[]);break}case"allReactions":{i&&typeof i=="object"&&!Array.isArray(i)&&(_=this.reactionUtilsService.getUserIdsToResolveFromReactions(Object.values(i)));break}case"allTags":{i&&typeof i=="object"&&!Array.isArray(i)&&(_=this.tagUtilsService.getUserIdsToResolveFromTags(Object.values(i)));break}case"allHuddleAttendees":{i&&typeof i=="object"&&!Array.isArray(i)&&(_=this.serviceBook.get(ST)?.getUserIdsToResolveFromHuddleAttendees(Object.values(i))??[]);break}case"liveStateCustom":{i&&typeof i=="object"&&!Array.isArray(i)&&(_=this.liveStateUtilsService.getUserIdsToResolveFromLiveStateCustom(i));break}case"allLiveStateCustoms":{i&&typeof i=="object"&&!Array.isArray(i)&&(_=this.liveStateUtilsService.getUserIdsToResolveFromLiveStateCustoms(Object.values(i)));break}case"allLiveStates":{i&&typeof i=="object"&&(_=this.liveStateUtilsService.getUserIdsToResolveFromLiveStates(i));break}case"liveStateSingleEditorMode":{i&&typeof i=="object"&&!Array.isArray(i)&&(_=this.liveStateUtilsService.getUserIdsToResolveFromLiveStateSingleEditorMode(i));break}case"allSelections":{i&&typeof i=="object"&&!Array.isArray(i)&&(_=this.selectionUtilsService.getUserIdsToResolveFromSelections(Object.values(i)));break}case"allActivities":{i&&typeof i=="object"&&(_=this.activityUtilsService.getUserIdsToResolveFromActivities(Array.isArray(i)?i:Object.values(i)));break}default:_=[]}if(_?.length){let T=J(),D=tl.GET_USERS;this.coreActionsService.triggerAction($.USER_RESOLVER,{event:L.Events.Resolver.USER_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:T,methodName:xn.FORMAT_RESPONSE,source:"internal",moduleName:D,payload:{userIds:_,feature:t,forceResolve:a}}),s?yield this.usersService.resolveUsers({userIds:_,forceResolve:a,feature:t,organizationId:o,uniqueId:T,moduleName:D}):this.usersService.resolveUsers({userIds:_,forceResolve:a,feature:t,organizationId:o,uniqueId:T,moduleName:D})}}if(this.notificationResolverService.notificationDataProviderAvailable()){let _=[];switch(t){case"allDocNotifications":case"allUserNotifications":{i&&typeof i=="object"&&(_=this.serviceBook.get(xi)?.getCustomNotificationIdsToResolve(i)??[],_=_.filter(D=>!this.notificationResolverService.getNotificationById(D)));break}default:_=[]}if(_?.length){let T=J(),D=yC.GET_NOTIFICATIONS;this.coreActionsService.triggerAction($.NOTIFICATION_RESOLVER,{event:L.Events.Resolver.NOTIFICATION_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:T,methodName:Fn.FORMAT_RESPONSE,moduleName:D,source:"internal",payload:{notificationIds:_,organizationId:p,shouldNotificationResolverAwait:l}}),l?yield this.notificationResolverService.resolveNotifications({request:{notificationIds:_,organizationId:p},uniqueId:T,moduleName:D}):this.notificationResolverService.resolveNotifications({request:{notificationIds:_,organizationId:p},uniqueId:T,moduleName:D})}}if(this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable()){let _=[];switch(t){case"allDocNotifications":{if(i&&typeof i=="object"){let D=this.serviceBook.get(xi)?.getTargetAnnotationIdsFromNotifications(i)??[];_=[..._,...D],_=_.filter(b=>!this.commentAnnotationsResolverService.getCommentAnnotationById(b))}break}case"allUserNotifications":{if(i&&typeof i=="object"&&!Array.isArray(i)){let D=this.serviceBook.get(xi)?.getTargetAnnotationIdsFromNotifications(i)??[];_=[..._,...D],_=_.filter(b=>!this.commentAnnotationsResolverService.getCommentAnnotationById(b))}break}case"allActivities":{if(i&&typeof i=="object"){let T=Array.isArray(i)?i:Object.values(i),D=this.activityUtilsService.getEntityIdsToResolveFromActivities(T,"comment");_=[..._,...D],_=_.filter(b=>!this.commentAnnotationsResolverService.getCommentAnnotationById(b))}break}default:_=[]}if(_?.length){let T=J(),D=Td.GET_NOTIFICATIONS;this.coreActionsService.triggerAction($.COMMENT_RESOLVER,{event:L.Events.Resolver.COMMENT_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:T,methodName:Et.FORMAT_RESPONSE,moduleName:D,source:"internal",payload:{commentAnnotationIds:_,organizationId:p,shouldCommentAnnotationsResolverAwait:c}}),c?yield this.commentAnnotationsResolverService.resolveCommentAnnotations({request:{commentAnnotationIds:_,organizationId:p},uniqueId:T,moduleName:D}):this.commentAnnotationsResolverService.resolveCommentAnnotations({request:{commentAnnotationIds:_,organizationId:p},uniqueId:T,moduleName:D})}}if(t==="allActivities"&&i&&typeof i=="object"){let _=Array.isArray(i)?i:Object.values(i),T=this.docService.getDocumentPaths()?.clientOrganizationId??"";if(this.activityResolverService.activityDataProviderAvailable()){let D=[];for(let b of _)b?.id&&!this.activityResolverService.getActivityById(b.id)&&D.push(b.id);if(D.length){let b=J(),G=SC.GET_ACTIVITIES;this.coreActionsService.triggerAction($.ACTIVITY_RESOLVER,{event:L.Events.Resolver.ACTIVITY_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:b,methodName:lr.FORMAT_RESPONSE,moduleName:G,source:"internal",payload:{activityIds:D,organizationId:T,shouldActivityResolverAwait:u}}),u?yield this.activityResolverService.resolveActivities({request:{activityIds:D,organizationId:T},uniqueId:b,moduleName:G}):this.activityResolverService.resolveActivities({request:{activityIds:D,organizationId:T},uniqueId:b,moduleName:G})}}if(this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable()){let D=this.activityUtilsService.getEntityIdsToResolveFromActivities(_,"reaction");if(D=D.filter(b=>!this.reactionAnnotationsResolverService.getAnnotationById(b)),D.length){let b=J(),G=Id.GET_REACTION_ANNOTATIONS;this.coreActionsService.triggerAction($.REACTION_RESOLVER,{event:L.Events.Resolver.REACTION_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:b,methodName:_t.RESOLVE_REACTION_ANNOTATIONS,moduleName:G,source:"internal",payload:{reactionAnnotationIds:D,organizationId:T,shouldReactionResolverAwait:d}}),d?yield this.reactionAnnotationsResolverService.resolveReactionAnnotations({request:{reactionAnnotationIds:D,organizationId:T},uniqueId:b,moduleName:G}):this.reactionAnnotationsResolverService.resolveReactionAnnotations({request:{reactionAnnotationIds:D,organizationId:T},uniqueId:b,moduleName:G})}}if(this.recorderAnnotationsResolverService.recorderAnnotationDataProviderAvailable()){let D=this.activityUtilsService.getEntityIdsToResolveFromActivities(_,"recorder");if(D=D.filter(b=>!this.recorderAnnotationsResolverService.getAnnotationById(b)),D.length){let b=J(),G=vd.GET_RECORDER_ANNOTATIONS;this.coreActionsService.triggerAction($.RECORDER_RESOLVER,{event:L.Events.Resolver.RECORDER_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:b,methodName:Tt.RESOLVE_RECORDER_ANNOTATIONS,moduleName:G,source:"internal",payload:{recorderAnnotationIds:D,organizationId:T,shouldRecorderResolverAwait:f}}),f?yield this.recorderAnnotationsResolverService.resolveRecorderAnnotations({request:{recorderAnnotationIds:D,organizationId:T},uniqueId:b,moduleName:G}):this.recorderAnnotationsResolverService.resolveRecorderAnnotations({request:{recorderAnnotationIds:D,organizationId:T},uniqueId:b,moduleName:G})}}}return i}catch(p){return this.loggingService.catch("Error in CommonDbUtilsService formatResponse:",p),i}})}mergeCommentAnnotationsWithData({data:t,feature:i}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeCommentAnnotationsWithData","color: green;"),this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())switch(i){case"allComments":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((o,[s,a])=>(o[s]=this.commentUtilsService.mergeStrippedDataWithCommentAnnotations(a),o),{}):t;case"allDocNotifications":case"allUserNotifications":if(t&&typeof t=="object"&&!Array.isArray(t)){let o=this.serviceBook.get(xi);return Object.entries(t).reduce((s,[a,c])=>(s[a]=o?o.mergeStrippedDataWithNotification(c):c,s),{})}else return t;case"allActivities":return this.mergeActivitiesWithFeatureData(t);default:return t}return t}catch(o){return this.loggingService.catch("Error in CommonDbUtilsService mergeCommentAnnotationsWithData:",o),t}}mergeActivityResolverWithData({data:t,feature:i}){try{return this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeActivityResolverWithData","color: green;"),this.activityResolverService.activityDataProviderAvailable()&&i==="allActivities"&&Array.isArray(t)?t.map(o=>this.activityUtilsService.mergeActivityWithResolverData(o)):t}catch(o){return this.loggingService.catch("Error in CommonDbUtilsService mergeActivityResolverWithData:",o),t}}mergeNotificationsWithResolvedData({data:t,feature:i}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeNotificationsWithResolvedData","color: green;"),this.notificationResolverService.notificationDataProviderAvailable())switch(i){case"allDocNotifications":case"allUserNotifications":{let o=this.serviceBook.get(xi);return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((s,[a,c])=>(s[a]=o?o.mergeResolvedNotificationData(c):c,s),{}):Array.isArray(t)?t.map(s=>o?o.mergeResolvedNotificationData(s):s):t}default:return t}return t}catch(o){return this.loggingService.catch("Error in CommonDbUtilsService mergeNotificationsWithResolvedData:",o),t}}mergeNotificationsWithResolvedData$({data:t,feature:i}){try{return this.notificationResolverService.getNotificationsById$().pipe(fe(()=>{let o=this.mergeNotificationsWithResolvedData({data:t?.data??{},feature:i}),s=this.mergeUsersWithData({feature:i,data:o??{}});return typeof s=="object"?{data:JSON.parse(JSON.stringify(s)),operation:t?.operation??null}:{data:s,operation:t?.operation??null}}),it(Ft))}catch(o){return this.loggingService.catch("Error in mergeNotificationsWithResolvedData$:",o),ue(t)}}mergeReactionAnnotationsWithData({data:t,feature:i}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeReactionAnnotationsWithData","color: green;"),this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable())switch(i){case"allReactions":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((o,[s,a])=>(o[s]=this.reactionUtilsService.mergeStrippedDataWithReactionAnnotations(a),o),{}):t;case"allActivities":return this.mergeActivitiesWithFeatureData(t);default:return t}return t}catch(o){return this.loggingService.catch("Error in CommonDbUtilsService mergeReactionAnnotationsWithData:",o),t}}mergeRecorderAnnotationsWithData({data:t,feature:i}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeRecorderAnnotationsWithData","color: green;"),this.recorderAnnotationsResolverService.recorderAnnotationDataProviderAvailable())switch(i){case"allRecorders":if(t&&typeof t=="object"&&!Array.isArray(t)){let o=this.serviceBook.get(ci);return Object.entries(t).reduce((s,[a,c])=>(s[a]=o?o.mergeStrippedDataWithRecorderAnnotation(c):c,s),{})}else return t;case"allActivities":return this.mergeActivitiesWithFeatureData(t);default:return t}return t}catch(o){return this.loggingService.catch("Error in CommonDbUtilsService mergeRecorderAnnotationsWithData:",o),t}}mergeActivitiesWithFeatureData(t){return Array.isArray(t)?t.map(i=>this.activityUtilsService.mergeActivityWithFeatureData(i)):t}mergeLocationMetadataWithData({data:t,feature:i,locationMetadata:o}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeLocationMetadataWithData","color: green;"),o&&typeof o=="object"&&!Array.isArray(o))switch(i){case"allComments":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((s,[a,c])=>(s[a]=this.commentUtilsService.mergeLocationWithCommentAnnotations(c,o),s),{}):t;case"allDocNotifications":case"allUserNotifications":if(t&&typeof t=="object"&&!Array.isArray(t)){let s=this.serviceBook.get(xi);return Object.entries(t).reduce((a,[c,l])=>(a[c]=s?s.mergeLocationWithNotification(l,o):l,a),{})}else return t;default:return t}return t}catch(s){return this.loggingService.catch("Error in CommonDbUtilsService mergeLocationMetadataWithData:",s),t}}mergeUsersWithData({feature:t,data:i}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeUsersWithData","color: green;"),this.usersService.userDataProviderAvailable())switch(t){case"allAreas":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((o,[s,a])=>(o[s]=this.areaUtilsService.mergeAreaWithUser(a),o),{}):i;case"allArrows":if(i&&typeof i=="object"&&!Array.isArray(i)){let o=this.serviceBook.get(IT);return Object.entries(i).reduce((s,[a,c])=>(s[a]=o?o.mergeArrowWithUser(c):c,s),{})}else return i;case"allCursors":if(i&&typeof i=="object"&&!Array.isArray(i)){let o=this.serviceBook.get(vT);return Object.entries(i).reduce((s,[a,c])=>(s[a]=o?o.mergeCursorUserWithUser(c):c,s),{})}else return i;case"allComments":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((o,[s,a])=>(o[s]=this.commentUtilsService.mergeCommentWithUser(a),o),{}):i;case"allDocumentUsers":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((o,[s,a])=>(o[s]=this.contactUtilsService.mergeUserIamWithUser(a),o),{}):i;case"allFolderUsers":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((o,[s,a])=>(o[s]=this.contactUtilsService.mergeUserIamWithUser(a),o),{}):i;case"allOrganizationUsers":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((o,[s,a])=>(o[s]=this.contactUtilsService.mergeUserIamWithUser(a),o),{}):i;case"allMultiThreads":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((o,[s,a])=>(o[s]=this.multiThreadUtilsService.mergeMultiThreadWithUser(a),o),{}):i;case"allDocNotifications":if(i&&typeof i=="object"){let o=this.serviceBook.get(xi);return i?.map(s=>o?o.mergeNotificationWithUser(s):s)}else return i;case"allUserNotifications":if(i&&typeof i=="object"&&!Array.isArray(i)){let o=this.serviceBook.get(xi);return Object.entries(i).reduce((s,[a,c])=>(s[a]=o?o.mergeNotificationWithUser(c):c,s),{})}else return i;case"allPresence":if(i&&typeof i=="object"&&!Array.isArray(i)){let o=this.serviceBook.get(yT);return Object.entries(i).reduce((s,[a,c])=>(s[a]=o?o.mergePresenceUserWithUser(c):c,s),{})}else return i;case"allRecorders":if(i&&typeof i=="object"&&!Array.isArray(i)){let o=this.serviceBook.get(ci);return Object.entries(i).reduce((s,[a,c])=>(s[a]=o?o.mergeRecorderWithUser(c):c,s),{})}else return i;case"allReactions":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((o,[s,a])=>(o[s]=this.reactionUtilsService.mergeReactionWithUser(a),o),{}):i;case"allTags":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((o,[s,a])=>(o[s]=this.tagUtilsService.mergeTagWithUser(a),o),{}):i;case"allHuddleAttendees":if(i&&typeof i=="object"&&!Array.isArray(i)){let o=this.serviceBook.get(ST);return Object.entries(i).reduce((s,[a,c])=>(s[a]=o?.mergeHuddleAttendeeWithUser(c)??c,s),{})}else return 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((o,[s,a])=>(o[s]=this.liveStateUtilsService.mergeLiveStateCustomWithUser(a),o),{}):i;case"allLiveStates":return i&&typeof i=="object"?this.liveStateUtilsService.mergeLiveStateWithUser(i):i;case"liveStateSingleEditorMode":return i&&typeof i=="object"&&!Array.isArray(i)?this.liveStateUtilsService.mergeSingleEditorLiveStateDataWithUser(i):i;case"allSelections":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((o,[s,a])=>(o[s]=this.selectionUtilsService.mergeSelectionWithUser(a),o),{}):i;case"allActivities":return Array.isArray(i)?i.map(o=>this.activityUtilsService.mergeActivityWithUser(o)):i;default:return i}return i}catch(o){return this.loggingService.catch("Error in CommonDbUtilsService mergeUsersWithData:",o),i}}mergeCommentAnnotationsWithData$({data:t,feature:i}){try{return this.commentAnnotationsResolverService.getCommentAnnotationsById$().pipe(fe(()=>{let o=this.mergeCommentAnnotationsWithData({data:t?.data??{},feature:i}),s=this.mergeUsersWithData({feature:i,data:o??{}});return typeof s=="object"?{data:JSON.parse(JSON.stringify(s)),operation:t?.operation??null}:{data:s,operation:t?.operation??null}}),it(Ft))}catch(o){return this.loggingService.catch("Error in mergeCommentAnnotationsWithData:",o),ue(t)}}mergeReactionAnnotationsWithData$({data:t,feature:i}){try{return this.reactionAnnotationsResolverService.getReactionAnnotationsById$().pipe(fe(()=>{let o=this.mergeReactionAnnotationsWithData({data:t?.data??{},feature:i}),s=this.mergeUsersWithData({feature:i,data:o??{}});return typeof s=="object"?{data:JSON.parse(JSON.stringify(s)),operation:t?.operation??null}:{data:s,operation:t?.operation??null}}),it(Ft))}catch(o){return this.loggingService.catch("Error in mergeReactionAnnotationsWithData:",o),ue(t)}}mergeRecorderAnnotationsWithData$({data:t,feature:i}){try{return this.recorderAnnotationsResolverService.getRecorderAnnotationsById$().pipe(fe(()=>{let o=this.mergeRecorderAnnotationsWithData({data:t?.data??{},feature:i}),s=this.mergeUsersWithData({feature:i,data:o??{}});return typeof s=="object"?{data:JSON.parse(JSON.stringify(s)),operation:t?.operation??null}:{data:s,operation:t?.operation??null}}),it(Ft))}catch(o){return this.loggingService.catch("Error in mergeRecorderAnnotationsWithData:",o),ue(t)}}mergeUsersWithData$({feature:t,data:i}){try{return this.usersService.getUserById$().pipe(fe(()=>{let o=this.mergeUsersWithData({feature:t,data:i?.data??{}});return typeof o=="object"?{data:JSON.parse(JSON.stringify(o)),operation:i?.operation??null}:{data:o,operation:i?.operation??null}}),it(Ft))}catch(o){return this.loggingService.catch(`Error in mergeUsersWithData for ${t}:`,o),ue(i)}}mergeLocationMetadataWithData$({data:t,feature:i}){try{return this.docService.getLocationMetadata$().pipe(fe(o=>{let s=this.mergeLocationMetadataWithData({data:t?.data??{},feature:i,locationMetadata:o});return typeof s=="object"?{data:JSON.parse(JSON.stringify(s)),operation:t?.operation??null}:{data:s,operation:t?.operation??null}}),it(Ft))}catch(o){return this.loggingService.catch(`Error in mergeLocationMetadataWithData for ${i}:`,o),ue(t)}}handleDataStripping(a){return I(this,arguments,function*({feature:t,data:i,actionType:o,commentId:s}){try{switch(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: handleDataStripping","color: green;"),t){case"comment":{let c=yield this.commentUtilsService.stripCommentAnnotationData({data:i,actionType:o,commentId:s});return this.filterOriginalDataForVeltDb({feature:t,result:c,providerAvailable:this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable()})}case"reaction":{let c=this.reactionUtilsService.stripReactionAnnotationData(i);return this.filterOriginalDataForVeltDb({feature:t,result:c,providerAvailable:this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable()})}case"recorder":{let c=this.serviceBook.get(ci)?.stripRecorderAnnotationData({data:i,actionType:o})??{originalData:i,strippedData:null};return this.filterOriginalDataForVeltDb({feature:t,result:c,providerAvailable:this.recorderAnnotationsResolverService.recorderAnnotationDataProviderAvailable()})}default:return{originalData:i,strippedData:null}}}catch(c){return this.loggingService.catch("Error in CommonDbUtilsService handleDataStripping:",c),{originalData:i,strippedData:null}}})}filterOriginalDataForVeltDb({feature:t,result:i,providerAvailable:o}){try{return!o||!i||i.originalData===null||i.originalData===void 0?i:le(x({},i),{originalData:this.applyVeltDbFieldFilter(t,i.originalData)})}catch(s){return this.loggingService.catch("Error in CommonDbUtilsService filterOriginalDataForVeltDb:",s),i}}applyVeltDbFieldFilter(t,i){switch(t){case"comment":return WV(i,{stripAttachmentFiles:this.attachmentResolverService.attachmentDataProviderAvailable()});case"reaction":return zV(i);case"recorder":return qV(i);default:return i}}formatData({feature:t,data:i,properties:o,offset:s,isRealtimeDb:a}){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()+s;switch(t){case"documentAccessType":return delete i?.users,{docIamConfig:i};case"organizationMetadata":case"documentMetadata":return a?i:{metadata:i};case"documentCommentMetadata":return i;case"cursor":{let l=this.serviceBook.get(vT);return l?l.formatCursorUserData(i):i}case"comment":return this.commentUtilsService.formatCommentData(i);case"area":return this.areaUtilsService.formatAreaData(i);case"arrow":{let l=this.serviceBook.get(IT);return l?l.formatArrowData(i):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.serviceBook.get(ci)?.formatRecorderData(i,c)??i;case"notificationViewsTimestamp":return{views:{[o.user??""]:i}};case"documentUsersViews":return a?i:{users:{[o.user??""]:{[o.date??""]:i}}};case"documentDayViews":return a?i:{day:{[o.date??""]:{[o.user??""]:i}}};case"documentMetadataViews":return a?i:{metadata:i};case"huddleMessage":return this.serviceBook.get(ST)?.formatHuddleMessageData(i)??i;case"locationMetadataViews":return a?i:{metadata:i};case"locationUsersViews":return a?i:{users:{[o.user??""]:{[o.date??""]:i}}};case"locationDayViews":return a?i:{day:{[o.date??""]:{[o.user??""]:i}}};case"locationViews":return a?i:{location:i};case"docNotificationViews":return a?i:{views:i.views};case"userNotificationViews":return a?i:{views:i.views};case"presence":{let l=this.serviceBook.get(yT);return l?l.formatPresenceUserData(i):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(a){return I(this,arguments,function*({feature:t,data:i,subscriber:o,operation:s=null}){try{let c=yield this.modifyData({feature:t,data:i});o.next({data:c,operation:s})}catch(c){this.loggingService.catch("Error in CommonDbUtilsService modifyAndSetData:",c)}})}isDataAlreadyProcessedInLocalCache({feature:t,change:i,cache:o}){try{if(t==="allReactions"||t==="allComments"){if(i.type==="removed")return!Object.keys(o??{}).includes(i.doc.id);if(o?.[i.doc.id]){let s=i.doc.data(),a=o?.[i.doc.id];return s?.lastUpdated===a?.lastUpdated}}return!1}catch(s){return this.loggingService.catch("Error in CommonDbUtilsService isDataAlreadyProcessedInLocalCache:",s),!1}}modifyData(o){return I(this,arguments,function*({feature:t,data:i}){try{return yield this.formatResponse({feature:t,data:i})}catch(s){return this.loggingService.catch("Error in CommonDbUtilsService modifyData:",s),i}})}addMetadata(t,i){try{return t&&typeof t=="object"&&!Array.isArray(t)?le(x({},t),{metadata:t?.metadata??{documentId:i?.documentId,organizationId:i?.organizationId,apiKey:i?.apiKey}}):t}catch(o){return this.loggingService.catch("Error in CommonDbUtilsService addMetadata:",o),t}}setDataInLocal(l){return I(this,arguments,function*({feature:t,data:i,observablesCache:o,eventType:s,id:a,operation:c=null}){try{let d={comment:"allComments",reaction:"allReactions"}[t];if(!d)return null;let f=i?.metadata?.documentId,g=i?.metadata?.veltFolderId;return Object.keys(o).filter(p=>p.includes(d)&&(!f||p.includes(f)||g&&p.includes(g))).forEach(p=>{let _=o[p]?.subject?.getValue()??{};s==="DELETE"?a&&_?.data?.[a]&&(delete _?.data?.[a],o[p]?.subject&&o[p].subject.next({data:_?.data,operation:c})):o[p]?.subject?.next({data:le(x({},_?.data),{[i?.annotationId]:i}),operation:c})}),null}catch(u){return this.loggingService.catch("Error in CommonDbUtilsService setDataInLocal:",u),null}})}handleCommentEncryption(c){return I(this,arguments,function*({data:t,firestorePath:i,extraData:o,eventType:s,metadata:a}){try{return yield this.commentUtilsService.handleCommentEncryption({data:t,firestorePath:i,extraData:o,eventType:s,metadata:a})}catch(l){return this.loggingService.catch("Error in CommonDbUtilsService handleCommentEncryption:",l),t}})}handleReactionEncryption(s){return I(this,arguments,function*({data:t,firestorePath:i,eventType:o}){try{return yield this.reactionUtilsService.handleReactionEncryption({data:t,firestorePath:i,eventType:o})}catch(a){return this.loggingService.catch("Error in CommonDbUtilsService handleReactionEncryption:",a),t}})}rtdbDefaultTransactionCallback(t,i){try{let o=x({},t||{});return Object.entries(i).forEach(([s,a])=>{a==null?delete o[s]:o[s]=a}),o}catch(o){return this.loggingService.catch("Error in CommonDbUtilsService rtdbDefaultTransactionCallback:",o),t}}};e.\u0275fac=function(i){return new(i||e)(w(Xy),w(Kz),w(Ky),w(Yz),w(It),w(zz),w(_e),w(Qz),w(Qy),w(Xz),w(Jz),w(zt),w(zh),w(zo),w(qo),w(ec),w(Zy),w(Yy),w(li),w(Wh))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let n=e;return n})();var e3=(()=>{let e=class e{constructor(t,i,o){this.configService=t,this.authService=i,this.loggingService=o,this.firestore$=new Y(null);try{Zr([this.authService.getFirebaseConfig$(),this.configService.getApiKey$(),this.configService.getFirestorePersistentCacheEnabled$()]).pipe(Ct(([s,a])=>!!s&&!!a),Nt(1)).subscribe(([s,a,c])=>{if(s&&a&&s?.firebaseOptions?.storeDbId){try{let d=sessionStorage?.getItem("veltFirestoreLogLevel")||st?.firebaseLogLevel||"silent";YL(d)}catch(d){this.loggingService.catch("Error in FirestoreService setLogLevel: ",d)}let l=tc.getFirestoreProdDbName(a,s.firebaseOptions),u=this.configService.getProxyConfig();if(u?.v2DbHost){let d={host:u.v2DbHost,ssl:!0};u.forceLongPolling?d.experimentalForceLongPolling=!0:d.experimentalAutoDetectLongPolling=!0,c&&(d.localCache=bM({tabManager:LM()}));try{this.firestore$.next(Gy(Sr(),d,l))}catch(f){this.loggingService.catch("Firestore proxy: initializeFirestore failed, falling back to existing instance. Proxy settings may not be applied: ",f),this.firestore$.next($h(l))}}else if(c)try{let d=Sr(),f=Gy(d,{localCache:bM({tabManager:LM()})},l);this.firestore$.next(f)}catch{this.firestore$.next($h(l))}else this.firestore$.next($h(l))}},s=>{})}catch{}}getFirestore(){return this.firestore$.asObservable()}getFirestoreValue(){return this.firestore$.value}generateFirestoreDocumentId(){try{let t=this.getFirestoreValue()||$h("DocumentIdDb");if(t){let i=Dp(t,"generateDocumentId");return Hh(i).id}return}catch(t){this.loggingService.catch("Error in FirestoreService generateFirestoreDocumentId: ",t);return}}};e.\u0275fac=function(i){return new(i||e)(w(Rr),w(Cr),w(_e))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let n=e;return n})();var jke=(()=>{let e=class e{constructor(t,i,o,s,a,c,l,u,d,f,g,p,_,T,D){this.activityUtilsService=t,this.authService=i,this.commonDbUtilsService=o,this.coreActionsService=s,this.loggingService=a,this.firestoreService=c,this.databaseService=l,this.configService=u,this.docService=d,this.usersService=f,this.commentAnnotationsResolverService=g,this.reactionAnnotationsResolverService=p,this.recorderAnnotationsResolverService=_,this.notificationResolverService=T,this.serviceBook=D,this.offset=0,this.db=null,this.firestore=null,this.subscriptions=[],this.offsetListener=null,this.observablesCache={},this.firestoreSubscriptions={},this.rtdbSubscriptions={},this.loggingService.log("%c[WB] Creating CLASS: CommonDbService","color: blue;"),this.serviceBook.observe(CT).subscribe(b=>{this.activityService=b??void 0}),this.docService.setCommonDbService(this),this.authService.setCommonDbService(this),this.usersService.setCommonDbService(this),this.subscriptions.push(this.databaseService.getDb().subscribe(b=>{if(b){this.db=b;let G=wa(b,".info/serverTimeOffset");this.offsetListener=gv(G,M=>{let U=M.val();this.offset=U})}})),this.subscriptions.push(this.firestoreService.getFirestore().subscribe(b=>{b&&(this.firestore=b)}))}unsubscribeFromObservables(){try{Object.values(this.firestoreSubscriptions??{}).forEach(t=>{t?.unsubscribe()}),Object.values(this.rtdbSubscriptions??{}).forEach(t=>{t?.unsubscribe()}),Object.entries(this.observablesCache??{}).forEach(([t,i])=>{i?.subject?.complete(),i?.subject?.unsubscribe()}),this.observablesCache={},this.firestoreSubscriptions={},this.rtdbSubscriptions={}}catch(t){this.loggingService.catch("Error in unsubscribeFromObservables:",t)}}ngOnDestroy(){this.subscriptions.forEach(t=>t.unsubscribe()),this.offsetListener&&this.offsetListener(),this.unsubscribeFromObservables()}setupOnDisconnect(t,i){return I(this,null,function*(){try{if(this.db){let o=wa(this.db,t);return M2(o).update(i)}return Promise.resolve()}catch(o){return this.loggingService.catch("Error in setupOnDisconnect:",o),Promise.resolve()}})}getOffset(){return this.offset}getServerTimestamp(){return new Date().getTime()+this.getOffset()}subscribeToServices(t){Zr([this.databaseService.getDb(),this.firestoreService.getFirestore()]).pipe(Ct(([i,o])=>!!i),Nt(1),Ks(([i,o])=>{t({db:i,firestore:o})})).subscribe({error:i=>{this.loggingService.catch("Error in CommonDbService subscription: ",i)}})}performDatabaseOperation(t,i,o,s,a,c){return I(this,null,function*(){try{if(!i){this.loggingService.warn(`%c[WB] No properties found for ${t}`,"color: red;");return}return this.subscribeToServices(d=>I(this,[d],function*({db:l,firestore:u}){let f;i?.skipFirestore||(f=this.commonDbUtilsService.getFirestorePath({feature:t,properties:i,documentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey()}));let g=this.commonDbUtilsService.getDocumentPath({feature:t,properties:i,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey(),useFirestore:this.shouldUseFirestore()});if(!l){this.loggingService.warn(`%c[WB] No database or firestore found for ${t}`,"color: red;");return}try{let p,_;try{g&&(p=wa(l,`${g}`))}catch{this.loggingService.catch("Error in dbRef")}try{f?.includes("/organizations")&&u&&f&&(_=Hh(u,`${f}`))}catch{this.loggingService.catch("Error in docRef")}if(!this.authService.getUser())return;yield o({dbRef:p,firestoreRef:_,data:s,firestorePath:f}),c&&c({firestoreAvailable:!!u})}catch(p){this.loggingService.catch(`Error in ${t} operation: `,p),a&&a(p)}}))}catch(l){this.loggingService.catch("Error in performDatabaseOperation:",l)}})}setData(l){return I(this,arguments,function*({feature:t,data:i,properties:o,callback:s,errorCallback:a,extraData:c}){try{return this.loggingService.log(`%c[WB] Calling FUNCTION: setData for ${t}`,"color: green;"),this.shouldUseFirestore()&&i?.metadata&&!i?.metadata?.apiKey?void 0:(this.commonDbUtilsService.setDataInLocal({feature:t,data:i,observablesCache:this.observablesCache,operation:null}),this.createActivityFromExtraData(t,c),this.performDatabaseOperation(t,o,u=>I(this,null,function*(){if(u.dbRef){let d=this.commonDbUtilsService.formatData({feature:t,data:u.data,properties:o,offset:this.getOffset(),isRealtimeDb:!0});o?.rtdbTransaction?yield Iw(u.dbRef,()=>JSON.parse(JSON.stringify(d))):yield vw(u.dbRef,JSON.parse(JSON.stringify(d)))}try{if(u.firestoreRef&&u.data&&!o?.skipFirestore){let d=this.commonDbUtilsService.formatData({feature:t,data:u.data,properties:o,offset:this.getOffset()});typeof d=="object"&&(d=JSON.parse(JSON.stringify(d)));let{strippedData:f,originalData:g,eventType:p}=yield this.commonDbUtilsService.handleDataStripping({feature:t,data:d,actionType:c?.actionType,commentId:c?.targetAnnotationData?.commentId??o?.targetCommentId});if(t==="comment"){let _=null,T=J();this.coreActionsService.triggerAction($.COMMENT_RESOLVER,{event:L.Events.Resolver.COMMENT_SAVE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:T,methodName:Et.SET_DATA,source:"internal",payload:{strippedData:f,originalData:g,eventType:p,commentId:c?.targetAnnotationData?.commentId}}),f&&(_=yield this.commentAnnotationsResolverService.saveCommentAnnotation({commentAnnotation:f,eventType:p,commentId:c?.targetAnnotationData?.commentId},T)),g&&(_?.isSuccess||_===null)&&(yield this.commonDbUtilsService.handleCommentEncryption({data:g,firestorePath:u.firestorePath??"",extraData:c,metadata:o?.metadata}))}else if(t==="reaction"){let _=null,T=J();this.coreActionsService.triggerAction($.REACTION_RESOLVER,{event:L.Events.Resolver.REACTION_SAVE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:T,methodName:_t.SET_DATA,source:"internal",payload:{strippedData:f,originalData:g}}),f&&(_=yield this.reactionAnnotationsResolverService.saveReactionAnnotation(f,T)),g&&(_?.isSuccess||_===null)&&(yield this.commonDbUtilsService.handleReactionEncryption({data:g,firestorePath:u.firestorePath??""}))}else if(t==="recorder"){let _=null,T=J();this.coreActionsService.triggerAction($.RECORDER_RESOLVER,{event:L.Events.Resolver.RECORDER_SAVE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:T,methodName:Tt.SET_DATA,source:"internal",payload:{strippedData:f,originalData:g}}),f&&(_=yield this.recorderAnnotationsResolverService.saveRecorderAnnotation({recorderAnnotation:f,eventType:p},T)),g&&(_?.isSuccess||_===null)&&this.firestore&&(yield kM(this.firestore,D=>I(this,null,function*(){D.set(u.firestoreRef,JSON.parse(JSON.stringify(g)))})))}else yield UM(u.firestoreRef,d)}}catch(d){this.authService.getUser()&&this.loggingService.catch(`Error in setData for ${t}`,d)}}),i,a,s))}catch(u){this.loggingService.catch(`Error in setData for ${t}`,u)}})}updateData(l){return I(this,arguments,function*({feature:t,data:i,properties:o,callback:s,errorCallback:a,extraData:c}){try{return this.loggingService.log(`%c[WB] Calling FUNCTION: updateData for ${t}`,"color: green;"),this.shouldUseFirestore()&&i?.metadata&&!i?.metadata?.apiKey?void 0:(this.commonDbUtilsService.setDataInLocal({feature:t,data:i,observablesCache:this.observablesCache,operation:null}),this.createActivityFromExtraData(t,c),this.performDatabaseOperation(t,o,u=>I(this,null,function*(){if(u.dbRef&&!o?.skipRtdb){let d=this.commonDbUtilsService.formatData({feature:t,data:u.data,properties:o,offset:this.getOffset(),isRealtimeDb:!0});o?.rtdbTransaction?yield Iw(u.dbRef,f=>{let g;return o?.rtdbTransactionCallback?g=o.rtdbTransactionCallback(f,d):g=this.commonDbUtilsService.rtdbDefaultTransactionCallback(f,d),JSON.parse(JSON.stringify(g))}):yield F2(u.dbRef,JSON.parse(JSON.stringify(d)))}try{if(u.firestoreRef&&u.data&&!o?.skipFirestore){let d=this.commonDbUtilsService.formatData({feature:t,data:u.data,properties:o,offset:this.getOffset()});typeof d=="object"&&(d=JSON.parse(JSON.stringify(d)));let{strippedData:f,originalData:g,eventType:p}=yield this.commonDbUtilsService.handleDataStripping({feature:t,data:d,actionType:c?.actionType,commentId:c?.targetAnnotationData?.commentId});if(t==="comment"){let _=null,T=J();this.coreActionsService.triggerAction($.COMMENT_RESOLVER,{event:L.Events.Resolver.COMMENT_SAVE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:T,methodName:Et.UPDATE_DATA,source:"internal",payload:{strippedData:f,originalData:g,eventType:p,commentId:c?.targetAnnotationData?.commentId}}),f&&(_=yield this.commentAnnotationsResolverService.saveCommentAnnotation({commentAnnotation:f,eventType:p,commentId:c?.targetAnnotationData?.commentId},T)),g&&(_?.isSuccess||_===null)&&(yield this.commonDbUtilsService.handleCommentEncryption({data:g,firestorePath:u.firestorePath??"",extraData:c,metadata:o?.metadata}))}else if(t==="reaction"){let _=null,T=J();this.coreActionsService.triggerAction($.REACTION_RESOLVER,{event:L.Events.Resolver.REACTION_SAVE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:T,methodName:_t.UPDATE_DATA,source:"internal",payload:{strippedData:f,originalData:g}}),f&&(_=yield this.reactionAnnotationsResolverService.saveReactionAnnotation(f,T)),g&&(_?.isSuccess||_===null)&&(yield this.commonDbUtilsService.handleReactionEncryption({data:g,firestorePath:u.firestorePath??""}))}else if(t==="recorder"){let _=null,T=J();this.coreActionsService.triggerAction($.RECORDER_RESOLVER,{event:L.Events.Resolver.RECORDER_SAVE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:T,methodName:Tt.UPDATE_DATA,source:"internal",payload:{strippedData:f,originalData:g}}),f&&(_=yield this.recorderAnnotationsResolverService.saveRecorderAnnotation({recorderAnnotation:f,eventType:p},T)),g&&(_?.isSuccess||_===null)&&this.firestore&&(yield kM(this.firestore,D=>I(this,null,function*(){D.set(u.firestoreRef,JSON.parse(JSON.stringify(g)))})))}else yield UM(u.firestoreRef,d,{merge:!0})}}catch(d){this.authService.getUser()&&this.loggingService.catch(`Error in updateDoc for ${t}`,d)}}),i,a,s))}catch(u){this.loggingService.catch(`Error in updateData for ${t}`,u)}})}createActivityFromExtraData(t,i){try{if(!i?.actionType||!this.activityService)return;let o=this.activityUtilsService.buildActivityDataFromExtraData({feature:t,extraData:i});o&&this.activityService.createActivity(o)}catch(o){this.loggingService.catch("Error in CommonDbService createActivityFromExtraData:",o)}}deleteData(c){return I(this,arguments,function*({feature:t,properties:i,callback:o,errorCallback:s,extraData:a}){try{return this.loggingService.log(`%c[WB] Calling FUNCTION: deleteData for ${t}`,"color: green;"),this.commonDbUtilsService.setDataInLocal({feature:t,observablesCache:this.observablesCache,eventType:"DELETE",id:i?.id,operation:{type:"removed",ids:[i?.id]}}),this.createActivityFromExtraData(t,a),this.performDatabaseOperation(t,i,l=>I(this,null,function*(){l.dbRef&&(yield x2(l.dbRef));try{if(l.firestoreRef&&!i?.skipFirestore)if(t==="comment"){let u=null,d=J();this.coreActionsService.triggerAction($.COMMENT_RESOLVER,{event:L.Events.Resolver.COMMENT_DELETE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:d,methodName:Et.DELETE_DATA,source:"internal",payload:{commentAnnotationId:i?.id??"",metadata:i?.metadata}}),u=yield this.commentAnnotationsResolverService.deleteCommentAnnotation(i?.id??"",i?.metadata,d),(u?.isSuccess||u===null)&&(yield this.commonDbUtilsService.handleCommentEncryption({firestorePath:l.firestorePath??"",eventType:"DELETE",metadata:i?.metadata}))}else if(t==="reaction"){let u=null,d=J();this.coreActionsService.triggerAction($.REACTION_RESOLVER,{event:L.Events.Resolver.REACTION_DELETE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:d,methodName:_t.DELETE_DATA,source:"internal",payload:{reactionAnnotationId:i?.id??"",metadata:i?.metadata}}),u=yield this.reactionAnnotationsResolverService.deleteReactionAnnotation(i?.id??"",i?.metadata,d),(u?.isSuccess||u===null)&&(yield this.commonDbUtilsService.handleReactionEncryption({firestorePath:l.firestorePath??"",eventType:"DELETE"}))}else if(t==="recorder"){let u=null,d=J();this.coreActionsService.triggerAction($.RECORDER_RESOLVER,{event:L.Events.Resolver.RECORDER_DELETE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:d,methodName:Tt.DELETE_DATA,source:"internal",payload:{recorderAnnotationId:i?.id??"",metadata:i?.metadata}}),u=yield this.recorderAnnotationsResolverService.deleteRecorderAnnotation(i?.id??"",i?.metadata,d),(u?.isSuccess||u===null)&&(yield Hy(l.firestoreRef))}else if(t==="userNotification"){let u=null,d=J();this.coreActionsService.triggerAction($.NOTIFICATION_RESOLVER,{event:L.Events.Resolver.NOTIFICATION_DELETE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:d,methodName:Fn.DELETE_DATA,source:"internal",payload:{notificationId:i?.id??"",organizationId:i?.organizationId??""}}),u=yield this.notificationResolverService.deleteNotification(String(i?.id??""),this.docService.getDocumentPaths()?.clientOrganizationId??"",d),(u?.isSuccess||u===null)&&(yield Hy(l.firestoreRef))}else yield Hy(l.firestoreRef)}catch(u){this.authService.getUser()&&this.loggingService.catch(`Error in deleteData for ${t}`,u)}}),void 0,s,o)}catch(l){this.loggingService.catch(`Error in deleteData for ${t}`,l)}})}shouldUseFirestore(){try{return this.authService.getAdvancedQueriesEnabled()}catch(t){return this.loggingService.catch("Error in shouldUseFirestore:",t),!1}}generateDocumentId(){try{let t=this.firestoreService.generateFirestoreDocumentId();return t||(t=J()),t||"noDocumentId"}catch(t){return this.loggingService.catch("Error in generateFirestoreDocumentId:",t),J()||"noDocumentId"}}queryData(o){return I(this,arguments,function*({feature:t,properties:i}){try{let s=this.shouldUseFirestore();return!t||!i?(this.loggingService.warn("[WB] Missing required parameters in queryData"),[]):s?yield this.handleFirestoreQuery(t,i):yield this.handleRtdbQuery(t,i)}catch(s){return this.loggingService.catch(`Error in queryData for ${t}`,s),[]}})}handleFirestoreQuery(t,i){return I(this,null,function*(){try{if(!this.firestore)return this.loggingService.warn("[WB] Firestore not initialized"),[];let o=i?.useCollectionGroup?this.commonDbUtilsService.getFirestoreCollectionGroupPath(t):this.commonDbUtilsService.getFirestorePath({feature:t,properties:i,documentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey()});if(!o)return this.loggingService.warn(`[WB] No firestore path found for ${t}`),[];try{let s=Dp(this.firestore,o);i?.useCollectionGroup&&(s=PM(this.firestore,o));let a=i?.firestoreQuery??[],c=FM(s,...a);if(!this.authService.getUser()&&!i?.skipUserCheck)return[];if(i?.getCount)try{let l=yield Uz(c).catch(u=>(this.authService.getUser()&&this.loggingService.catch(`Error in getCountFromServer for ${t}`,u),null));return l?l.data().count:0}catch(l){return this.authService.getUser()&&this.loggingService.catch(`Error in getCountFromServer for ${t}`,l),0}else try{let l=yield Bz(c).catch(d=>(this.authService.getUser()&&this.loggingService.catch(`Error in getDocs for ${t}`,d),null));if(!l)return[];let u=l.docs.map(d=>d.data());try{return yield this.commonDbUtilsService.modifyData({feature:t,data:u})}catch(d){return this.loggingService.catch(`Error in modifyData for ${t}`,d),u}}catch(l){return this.authService.getUser()&&this.loggingService.catch(`Error in getDocs for ${t}`,l),[]}}catch(s){return this.loggingService.catch(`Error in Firestore query for ${t}:`,s),[]}}catch(o){return this.loggingService.catch(`Error in Firestore query for ${t}:`,o),[]}})}handleRtdbQuery(t,i){return I(this,null,function*(){if(!this.db)return this.loggingService.warn("[WB] Realtime Database not initialized"),[];let o=this.commonDbUtilsService.getDocumentPath({feature:t,properties:i,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey()});if(!o)return this.loggingService.warn(`[WB] No database path found for ${t}`),[];try{let s=wa(this.db,o),a=i?.rtdbQuery??[],c=Tw(s,...a);if(!this.authService.getUser()&&!i?.skipUserCheck)return[];let l=yield Ew(c).catch(d=>(this.authService.getUser()&&this.loggingService.catch(`Error in get for ${t}`,d),null));if(!l)return[];let u=l.val();return u?i?.skipObjectValues?u:Object.values(u??{}):[]}catch(s){return this.loggingService.catch(`Error in RTDB query for ${t}:`,s),[]}})}getData(o){return I(this,arguments,function*({feature:t,properties:i}){try{let s=this.shouldUseFirestore();if(i?.skipFirestore&&(s=!1),!t||!i)return this.loggingService.warn("[WB] Missing required parameters in getData"),{};if(s&&this.firestore){let a=this.commonDbUtilsService.getFirestorePath({feature:t,properties:i,documentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey()});if(!a)return this.loggingService.warn(`[WB] No firestore path found for ${t}`),{};try{if(!this.authService.getUser())return this.loggingService.catch("User not set. [source: getData]",void 0,void 0,!0),{};let c=yield Vz(Hh(this.firestore,a)).catch(u=>(this.authService.getUser()&&!i?.suppressError&&this.loggingService.catch(`Error in getDoc for ${t}`,u),this.commonDbUtilsService.getErrorForGetRequests({feature:t,error:u})));if(c){if(c?.errorCode)return c}else return this.loggingService.warn(`[WB] No document found at ${a}`),{};let l=c.data();return i?.field?l?.[i.field]??{}:l??{}}catch(c){return this.loggingService.catch(`Error fetching Firestore data for ${t}:`,c),{}}}if(this.db){let a=this.commonDbUtilsService.getDocumentPath({feature:t,properties:i,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey()});if(!a)return this.loggingService.warn(`[WB] No database path found for ${t}`),{};try{if(!this.authService.getUser())return{};let c=yield Ew(wa(this.db,a)).catch(u=>(this.authService.getUser()&&this.loggingService.catch(`Error in get for ${t}`,u),this.commonDbUtilsService.getErrorForGetRequests({feature:t,error:u})));if(c){if(c?.errorCode)return c}else return this.loggingService.warn(`[WB] No data found at ${a}`),{};let l=c.val();return i?.field?l?.[i.field]??{}:l??{}}catch(c){return this.loggingService.catch(`Error fetching RTDB data for ${t}:`,c),{}}}return this.loggingService.warn("[WB] No database connection available"),{}}catch(s){return this.loggingService.catch("Unexpected error in getData:",s),{}}})}dbListener({feature:t,properties:i}){let o=this.shouldUseFirestore();i?.skipFirestore&&(o=!1);let s=`${t}-${JSON.stringify(i)}`;return Zr([this.databaseService.getDb(),this.firestoreService.getFirestore(),this.authService.getUser$().pipe(Ct(a=>!!a))]).pipe(Ct(([a,c])=>a?o&&!c?(this.loggingService.warn(`[WB] Firestore requested but not available for ${t}`),!1):!0:(this.loggingService.warn(`[WB] No database found for ${t}`),!1)),mt(([a,c])=>{try{if(o&&c){if(!!!this.observablesCache[s]){this.observablesCache[s]={subject:new Y({}),count:0};let d=this.handleFirestoreListener(t,i,c).subscribe(f=>{this.observablesCache[s]?.subject?.next(f)},f=>this.observablesCache[s]?.subject?.error(f));this.firestoreSubscriptions[s]=d}return new ge(u=>{let d=this.observablesCache[s]?.subject?.subscribe(f=>u.next(f),f=>u.error(f),()=>u.complete());return this.observablesCache[s].count+=1,()=>{d?.unsubscribe(),this.observablesCache[s]&&(this.observablesCache[s].count-=1,this.observablesCache[s].count<=0&&(this.firestoreSubscriptions[s]?.unsubscribe(),delete this.firestoreSubscriptions[s],this.observablesCache[s]?.subject?.complete(),delete this.observablesCache[s]))}})}else if(a){if(!!!this.observablesCache[s]){this.observablesCache[s]={subject:new Y({}),count:0};let d=this.handleRealtimeDbListener(t,i,a).subscribe(f=>{this.observablesCache[s]?.subject?.next(f)},f=>this.observablesCache[s]?.subject?.error(f));this.rtdbSubscriptions[s]=d}return new ge(u=>{let d=this.observablesCache[s]?.subject?.subscribe(f=>u.next(f),f=>u.error(f),()=>u.complete());return this.observablesCache[s].count+=1,()=>{d?.unsubscribe(),this.observablesCache[s]&&(this.observablesCache[s].count-=1,this.observablesCache[s].count<=0&&(this.rtdbSubscriptions[s]?.unsubscribe(),delete this.rtdbSubscriptions?.[s],this.observablesCache[s]?.subject?.complete(),delete this.observablesCache?.[s]))}})}return ue({})}catch(l){return this.loggingService.catch(`Error setting up listener for ${t}:`,l),ue({})}}),Sc(()=>{this.loggingService.log(`[WB] Cleaning up listener for ${t} and key ${s}`)}))}handleFirestoreListener(t,i,o){let s=i?.useCollectionGroup?this.commonDbUtilsService.getFirestoreCollectionGroupPath(t):this.commonDbUtilsService.getFirestorePath({feature:t,properties:i,documentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey()}),a=`${t}-${JSON.stringify(i)}`;return s?new ge(c=>{let l=i.isCollection?this.setupCollectionListener(o,s,t,c,i):this.setupDocumentListener(o,s,t,c,i);return()=>{c.complete(),c.unsubscribe(),l(),this.observablesCache[a]?.subject?.complete(),this.observablesCache[a]?.subject?.unsubscribe(),delete this.observablesCache[a]}}).pipe(mt(c=>this.commonDbUtilsService.mergeUsersWithData$({feature:t,data:c})),mt(c=>["allComments","allUserNotifications"].includes(t)?this.commonDbUtilsService.mergeCommentAnnotationsWithData$({data:c,feature:t}):ue(c)),mt(c=>["allReactions"].includes(t)?this.commonDbUtilsService.mergeReactionAnnotationsWithData$({data:c,feature:t}):ue(c)),mt(c=>["allRecorders"].includes(t)?this.commonDbUtilsService.mergeRecorderAnnotationsWithData$({data:c,feature:t}):ue(c)),it(Ft)):(this.loggingService.warn(`[WB] No firestore path found for ${t} and key ${a}`),ue({}))}setupCollectionListener(t,i,o,s,a){let c=`${o}-${JSON.stringify(a)}`,l=Dp(t,i);if(a?.useCollectionGroup&&(l=PM(t,i)),a?.useQuery&&a?.firestoreQuery){let f=a?.firestoreQuery??[];l=FM(l,...f)}let u=!0,d=[];return o==="allComments"&&this.loggingService.logContext("[CONTEXT] setupCollectionListener called with path:",i,"feature:",o,"properties:",JSON.stringify(a??"nil")),xM(l,f=>{try{let g=JSON.parse(JSON.stringify(this.observablesCache[c]?.subject?.getValue()?.data??{})),p=null,_=!1;f?.docChanges()?.length?f.docChanges().forEach(T=>{["allComments","allReactions","allRecorders"].includes(o)&&!u&&T.type!=="removed"&&d.push(T.doc.id),this.commonDbUtilsService.isDataAlreadyProcessedInLocalCache({feature:o,change:T,cache:this.observablesCache[c]?.subject?.getValue()?.data??{}})||(_=!0,Object.assign(g,this.handleCollectionChange(T,g)),T.type==="removed"&&(p||(p={type:T.type,ids:[]}),p.ids.push(T.doc.id)))}):_=!0,_&&(["allComments","allReactions","allRecorders"].includes(o)&&d?.length&&(this.commonDbUtilsService.resolveAnnotations({data:d,feature:o}),d=[]),this.commonDbUtilsService.modifyAndSetData({feature:o,data:g,subscriber:s,operation:p})),u=!1}catch(g){this.loggingService.logContext(`[ERROR] Firestore listener error for feature ${o}:`,g),this.loggingService.logContext(`[ERROR] Firestore listener error for properties ${JSON.stringify(a??"nil")}:`),this.loggingService.logContext(`[ERROR] Firestore listener error for user ${JSON.stringify(this.authService.getUser()??"nil")}:`),this.handleListenerError(g,o,s)}},f=>{this.loggingService.logContext(`[ERROR] Firestore listener error for feature ${o}:`,f),this.loggingService.logContext(`[ERROR] Firestore listener error for properties ${JSON.stringify(a??"nil")}:`),this.loggingService.logContext(`[ERROR] Firestore listener error for user ${JSON.stringify(this.authService.getUser()??"nil")}:`),this.handleListenerError(f,o,s)})}handleCollectionChange(t,i){switch(t.type){case"added":case"modified":i[t.doc.id]=t.doc.data();break;case"removed":delete i?.[t.doc.id];break}return i}setupDocumentListener(t,i,o,s,a){let c=Hh(t,i);return xM(c,l=>{try{let u=l.data()||{};a?.field&&(u=u?.[a?.field]??{}),this.commonDbUtilsService.modifyAndSetData({feature:o,data:u,subscriber:s,operation:null})}catch(u){this.handleListenerError(u,o,s)}},l=>this.handleListenerError(l,o,s))}handleListenerError(t,i,o){this.loggingService.catch(`Firestore listener error for ${i}:`,t)}handleRealtimeDbListener(t,i,o){let s=this.commonDbUtilsService.getDocumentPath({feature:t,properties:i,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey()});if(!s)return this.loggingService.warn(`[WB] No database path found for ${t}`),ue({});let a=wa(o,s);if(i?.useQuery&&i?.rtdbQuery){let c=i?.rtdbQuery??[];a=Tw(a,...c)}return this.objectValFromChildEvents(a,t).pipe(ts(c=>(this.loggingService.catch(`RTDB listener error for ${t}:`,c),ue({}))),fe(c=>(c===null&&(c={}),c&&typeof c=="object"?Object.entries(c??{}).reduce((u,[d,f])=>(u[d]=this.commonDbUtilsService.addMetadata(f,i),u),{}):this.commonDbUtilsService.addMetadata(c,i))),mt(c=>this.commonDbUtilsService.modifyData({feature:t,data:c})),mt(c=>this.usersService.getUserById$().pipe(fe(()=>({data:this.commonDbUtilsService.mergeUsersWithData({feature:t,data:c}),operation:null})))))}pushData(s){return I(this,arguments,function*({feature:t,properties:i,data:o}){try{return this.loggingService.log(`%c[WB] Calling FUNCTION: pushData for ${t}`,"color: green;"),this.performDatabaseOperation(t,i,a=>I(this,null,function*(){if(a.dbRef){let c=P2(a.dbRef);yield vw(c,JSON.parse(JSON.stringify(a.data)))}}),o)}catch(a){this.loggingService.catch(`Error in pushData for ${t}`,a)}})}streamChildAdded({feature:t,properties:i,afterTs:o}){try{return this.loggingService.log(`%c[WB] Calling FUNCTION: streamChildAdded for ${t}`,"color: green;"),new ge(s=>{let a=null,c=!1,l=({db:u})=>{if(!u||c||!this.authService.getUser())return;let d=this.commonDbUtilsService.getDocumentPath({feature:t,properties:i,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey(),useFirestore:!1});if(!d)return;let g=wa(u,d),p=!1,_=b=>{try{let G=b.val();if(p){if(o!=null&&G?.timestamp!=null&&G.timestamp<=o)return;s.next(G)}}catch(G){this.loggingService.catch(`streamChildAdded onChildAdded callback error for ${t}:`,G)}},T=b=>{try{this.loggingService.catch(`streamChildAdded error for ${t}:`,b),s.error(b)}catch(G){this.loggingService.catch(`streamChildAdded onError handler error for ${t}:`,G)}};_w(g,_,T);let D=gv(g,()=>{p=!0},T,{onlyOnce:!0});a=()=>{try{D&&typeof D=="function"&&D(),Am(g,"child_added",_)}catch(b){this.loggingService.catch(`streamChildAdded cleanup error for ${t}:`,b)}}};return this.subscribeToServices(l),()=>{c=!0,a&&a()}})}catch(s){return this.loggingService.catch(`Error in streamChildAdded for ${t}`,s),ue(null)}}objectValFromChildEvents(t,i){return new ge(o=>{let s={},a=!1,c=null,l=T=>{try{this.loggingService.catch(`Realtime DB listener error for ${i}:`,T),o.error(T)}catch{}},u=T=>{try{if(!ki(T,c)){let D=JSON.parse(JSON.stringify(T));c=D,o.next(D)}}catch{}},d=T=>{try{T.key&&(s[T.key]=T.val(),a&&u(x({},s)))}catch{}},f=T=>{try{T.key&&(s[T.key]=T.val(),a&&u(x({},s)))}catch{}},g=T=>{try{T.key&&(delete s[T.key],a&&u(x({},s)))}catch{}},p=T=>{try{if(!a){let D=s&&typeof s=="object"?JSON.parse(JSON.stringify(s)):{};c=D,o.next(D),a=!0}}catch{}};_w(t,d,l),b2(t,f,l),L2(t,g,l);let _=gv(t,p,l,{onlyOnce:!0});return()=>{try{_&&typeof _=="function"&&_(),Am(t,"child_added",d),Am(t,"child_changed",f),Am(t,"child_removed",g)}catch{}}})}};e.\u0275fac=function(i){return new(i||e)(w(Xy),w(Cr),w(Zz),w(It),w(_e),w(e3),w(Wy),w(Rr),w(zh),w(zt),w(zo),w(qo),w(ec),w(Zy),w(li))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let n=e;return n})();export{x as a,le as b,dS as c,pse as d,Ese as e,_se as f,I as g,gt as h,ge as i,RS as j,Ot as k,Y as l,Ac as m,l6 as n,u6 as o,Ic as p,xr as q,ue as r,d6 as s,h6 as t,Q3 as u,fe as v,Zr as w,GS as x,f6 as y,ho as z,I6 as A,Ci as B,H3 as C,Pu as D,Ct as E,P3 as F,ts as G,yS as H,Au as I,Nt as J,DS as K,it as L,Du as M,dE as N,NS as O,W3 as P,OS as Q,z3 as R,Ru as S,mt as T,qs as U,q3 as V,Ks as W,K3 as X,J3 as Y,oe as Z,ME as _,K as $,is as aa,Z as ba,w as ca,ne as da,pr as ea,Kn as fa,fo as ga,w0 as ha,b0 as ia,$0 as ja,j0 as ka,St as la,Dn as ma,cr as na,Fr as oa,To as pa,jc as qa,ei as ra,J6 as sa,pn as ta,VD as ua,E4 as va,sa as wa,g_ as xa,w_ as ya,D4 as za,iq as Aa,oq as Ba,sq as Ca,aq as Da,cq as Ea,Dq as Fa,cs as Ga,Le as Ha,Mq as Ia,y8 as Ja,S8 as Ka,yo as La,Yf as Ma,ds as Na,j_ as Oa,ut as Pa,M8 as Qa,Do as Ra,Kc as Sa,Tk as Ta,I5 as Ua,aa as Va,Ro as Wa,Xf as Xa,Dk as Ya,w5 as Za,Nk as _a,Ok as $a,z_ as ab,ca as bb,xk as cb,Fk as db,k5 as eb,V5 as fb,B5 as gb,G5 as hb,$5 as ib,j5 as jb,H5 as kb,kk as lb,AR as mb,DR as nb,Uk as ob,RR as pb,CR as qb,Vk as rb,NR as sb,OR as tb,Gk as ub,Q5 as vb,$k as wb,Hk as xb,Wk as yb,t9 as zb,r9 as Ab,i9 as Bb,s9 as Cb,a9 as Db,c9 as Eb,l9 as Fb,u9 as Gb,d9 as Hb,h9 as Ib,Xk as Jb,Jk as Kb,D9 as Lb,C9 as Mb,k9 as Nb,aU as Ob,wR as Pb,cU as Qb,lU as Rb,uU as Sb,G9 as Tb,dU as Ub,fU as Vb,$9 as Wb,j9 as Xb,H9 as Yb,W9 as Zb,Q9 as _b,X9 as $b,J9 as ac,Z9 as bc,eK as cc,tK as dc,nK as ec,rK as fc,iK as gc,oK as hc,sK as ic,aK as jc,lK as kc,dK as lc,hK as mc,fK as nc,gK as oc,mK as pc,_K as qc,rg as rc,ig as sc,xR as tc,qve as uc,Kve as vc,Yve as wc,KK as xc,qR as yc,Qve as zc,Xve as Ac,Jve as Bc,Co as Cc,HU as Dc,fY as Ec,a1 as Fc,gY as Gc,eC as Hc,mY as Ic,pY as Jc,EY as Kc,_Y as Lc,IY as Mc,yY as Nc,AY as Oc,tC as Pc,uC as Qc,GY as Rc,HY as Sc,O1 as Tc,g7 as Uc,m7 as Vc,pC as Wc,G1 as Xc,IC as Yc,Nd as Zc,Hr as _c,ha as $c,KT as ad,sl as bd,vr as cd,Ge as dd,_n as ed,ur as fd,Po as gd,yr as hd,pa as id,Sr as jd,Qe as kd,IX as ld,pbe as md,Ebe as nd,_be as od,Bi as pd,Ea as qd,vs as rd,Gi as sd,pe as td,$i as ud,ys as vd,Fbe as wd,kbe as xd,Ube as yd,Ta as zd,jJ as Ad,WJ as Bd,iZ as Cd,hl as Dd,fl as Ed,IMe as Fd,bd as Gd,EI as Hd,vMe as Id,g2 as Jd,dv as Kd,GPe as Ld,$Pe as Md,jPe as Nd,HPe as Od,WPe as Pd,zPe as Qd,qPe as Rd,M2 as Sd,gv as Td,KPe as Ud,P2 as Vd,wa as Wd,x2 as Xd,Iw as Yd,vw as Zd,YPe as _d,F2 as $d,dr as ae,VMe as be,BMe as ce,GMe as de,Dr as ee,H1 as fe,U7 as ge,Sg as he,st as ie,L as je,Ie as ke,Qt as le,pAe as me,EAe as ne,_Ae as oe,TAe as pe,$ as qe,IAe as re,vAe as se,yAe as te,SAe as ue,_7 as ve,T7 as we,I7 as xe,v7 as ye,_T as ze,y7 as Ae,S7 as Be,A7 as Ce,EC as De,D7 as Ee,$r as Fe,TT as Ge,R7 as He,md as Ie,wt as Je,C7 as Ke,Tg as Le,N7 as Me,O7 as Ne,w7 as Oe,b7 as Pe,L7 as Qe,M7 as Re,P7 as Se,v as Te,U1 as Ue,tDe as Ve,_d as We,H as Xe,oDe as Ye,sDe as Ze,ui as _e,bt as $e,W1 as af,z1 as bf,xDe as cf,FDe as df,bT as ef,vC as ff,LT as gf,xn as hf,tl as if,No as jf,Y1 as kf,Q1 as lf,X1 as mf,_s as nf,V7 as of,Un as pf,di as qf,J1 as rf,Z1 as sf,eV as tf,tV as uf,nV as vf,rV as wf,iV as xf,oV as yf,sV as zf,aV as Af,cV as Bf,B7 as Cf,G7 as Df,lV as Ef,AC as Ff,uV as Gf,dV as Hf,fV as If,$7 as Jf,Oo as Kf,j7 as Lf,H7 as Mf,vOe as Nf,OV as Of,Tr as Pf,Fi as Qf,da as Rf,Ts as Sf,wo as Tf,LOe as Uf,MOe as Vf,POe as Wf,xOe as Xf,FOe as Yf,kOe as Zf,UOe as _f,bV as $f,J as ag,VOe as bg,LV as cg,Sd as dg,SV as eg,AV as fg,z7 as gg,q7 as hg,il as ig,NC as jg,BOe as kg,bo as lg,GOe as mg,Rg as ng,ki as og,$Oe as pg,OC as qg,rl as rg,Q7 as sg,VT as tg,jOe as ug,HOe as vg,PV as wg,Cg as xg,X7 as yg,J7 as zg,Z7 as Ag,eQ as Bg,tQ as Cg,jr as Dg,WOe as Eg,RC as Fg,zOe as Gg,rQ as Hg,qOe as Ig,KOe as Jg,FV as Kg,YOe as Lg,QOe as Mg,XOe as Ng,JOe as Og,ZOe as Pg,ewe as Qg,twe as Rg,UT as Sg,nwe as Tg,rwe as Ug,iwe as Vg,owe as Wg,swe as Xg,awe as Yg,cwe as Zg,lwe as _g,uwe as $g,dwe as ah,hwe as bh,fwe as ch,gwe as dh,mwe as eh,pwe as fh,Ewe as gh,_we as hh,Twe as ih,Iwe as jh,vwe as kh,ywe as lh,Swe as mh,Awe as nh,Dwe as oh,Rwe as ph,aQ as qh,Cwe as rh,Nwe as sh,Owe as th,RV as uh,wwe as vh,bwe as wh,Ft as xh,Cn as yh,Lwe as zh,kt as Ah,Ht as Bh,Mwe as Ch,$V as Dh,Ad as Eh,bC as Fh,Ir as Gh,Pwe as Hh,CV as Ih,IT as Jh,NAe as Kh,OAe as Lh,xi as Mh,wAe as Nh,vT as Oh,bAe as Ph,LAe as Qh,yT as Rh,MAe as Sh,ST as Th,PAe as Uh,AT as Vh,xAe as Wh,ci as Xh,FAe as Yh,pd as Zh,kAe as _h,UAe as $h,VAe as ai,BAe as bi,GAe as ci,$Ae as di,jAe as ei,DT as fi,HAe as gi,WAe as hi,RT as ii,CT as ji,P1 as ki,x1 as li,F1 as mi,li as ni,Lt as oi,_e as pi,Rr as qi,U2 as ri,It as si,pv as ti,Ev as ui,Cr as vi,MM as wi,Lxe as xi,Mxe as yi,Pxe as zi,xxe as Ai,Ji as Bi,Wy as Ci,zo as Di,qo as Ei,Wh as Fi,ec as Gi,zh as Hi,zt as Ii,Ky as Ji,Yy as Ki,Xy as Li,Jy as Mi,zz as Ni,Zy as Oi,Zz as Pi,jke as Qi};
|