@veltdev/sdk-dev 6.0.16-beta.1 → 6.0.17-beta.1

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.
Files changed (65) hide show
  1. package/app/models/element/comment-element.model.d.ts +25 -0
  2. package/app/utils/constants.d.ts +7 -0
  3. package/{chunk-L5SOVVIR.js → chunk-2BXOD5Z7.js} +1 -1
  4. package/{chunk-CSN6ATAA.js → chunk-44HAZKIE.js} +1 -1
  5. package/{chunk-HALPIS6O.js → chunk-5H4ODM5U.js} +1 -1
  6. package/chunk-5ZUX3AU3.js +1 -0
  7. package/{chunk-KBXVJ2AO.js → chunk-6P3LPEPY.js} +1 -1
  8. package/chunk-A52PJCIA.js +1 -0
  9. package/{chunk-TJT3IIS7.js → chunk-AWSU4IMS.js} +1 -1
  10. package/chunk-B3U3OLF6.js +1 -0
  11. package/{chunk-O3CLK76M.js → chunk-BB2UXAYE.js} +1 -1
  12. package/chunk-BTNNHMUJ.js +1 -0
  13. package/{chunk-PHGOP6XJ.js → chunk-CYAQOX2W.js} +1 -1
  14. package/{chunk-LUXKOQSC.js → chunk-D24LAR5L.js} +1 -1
  15. package/{chunk-TAOBMSMM.js → chunk-DFQFM4NV.js} +1 -1
  16. package/chunk-EPQLN2EE.js +1 -0
  17. package/{chunk-H57PY57T.js → chunk-F5REFWTQ.js} +1 -1
  18. package/{chunk-HRU6STNE.js → chunk-FEA5HRMI.js} +1 -1
  19. package/{chunk-ZSCDUVYV.js → chunk-FFTR7QJM.js} +1 -1
  20. package/{chunk-U4L2FEIW.js → chunk-FPEVLQAP.js} +1 -1
  21. package/{chunk-FS6KTSNQ.js → chunk-HEFEC6O6.js} +1 -1
  22. package/{chunk-2XFRSBAE.js → chunk-IUD3QEEM.js} +1 -1
  23. package/{chunk-NM32S6ZH.js → chunk-KHL24R7O.js} +1 -1
  24. package/{chunk-LTKCIADR.js → chunk-LEIUFK3K.js} +1 -1
  25. package/{chunk-SC3WVEMZ.js → chunk-MVVXZ2D6.js} +1 -1
  26. package/{chunk-C7NBAS5V.js → chunk-ND3RYLBW.js} +1 -1
  27. package/{chunk-FWPOKU7S.js → chunk-NSGBIR4C.js} +2 -2
  28. package/{chunk-CEZ7IT67.js → chunk-OLHFUO6O.js} +1 -1
  29. package/{chunk-XCOVQJPR.js → chunk-QZ5UHEP2.js} +1 -1
  30. package/{chunk-OBDK4TJR.js → chunk-RGBU7P5H.js} +1 -1
  31. package/{chunk-DEQNXKWW.js → chunk-SKNIB72F.js} +1 -1
  32. package/chunk-SMANT45B.js +1 -0
  33. package/chunk-TAGMM5ED.js +174 -0
  34. package/{chunk-3MNQES2P.js → chunk-UCURXRPI.js} +1 -1
  35. package/{chunk-OCCE2UTF.js → chunk-VECW5ME3.js} +1 -1
  36. package/{chunk-6HNU2FG2.js → chunk-XZD6KKXD.js} +1 -1
  37. package/{chunk-YNFDUIYD.js → chunk-ZPO5AK7X.js} +1 -1
  38. package/package.json +1 -1
  39. package/velt-activity-log.js +1 -1
  40. package/velt-area.js +1 -1
  41. package/velt-arrow.js +2 -2
  42. package/velt-comment.js +6 -6
  43. package/velt-crdt.js +1 -1
  44. package/velt-cursor.js +2 -2
  45. package/velt-huddle.js +1 -1
  46. package/velt-live-state-sync.js +1 -1
  47. package/velt-notification.js +1 -1
  48. package/velt-portable.js +1 -1
  49. package/velt-presence.js +1 -1
  50. package/velt-reaction.js +1 -1
  51. package/velt-recorder.js +1 -1
  52. package/velt-rewriter.js +3 -3
  53. package/velt-selection.js +1 -1
  54. package/velt-tag.js +1 -1
  55. package/velt-user-invite.js +1 -1
  56. package/velt-user-request.js +1 -1
  57. package/velt-video-player.js +1 -1
  58. package/velt-views.js +2 -2
  59. package/velt.js +3 -3
  60. package/chunk-FUR2EFO6.js +0 -1
  61. package/chunk-GUHU4CU5.js +0 -1
  62. package/chunk-H6ZQEQFJ.js +0 -1
  63. package/chunk-I6ELSCG4.js +0 -1
  64. package/chunk-RV7ZJ7J2.js +0 -174
  65. package/chunk-VOMZ73T5.js +0 -1
@@ -1391,6 +1391,21 @@ export declare class CommentElement {
1391
1391
  */
1392
1392
  public disableDraftConfirmation: () => void;
1393
1393
 
1394
+ /**
1395
+ * To enable id-scoped anchoring for comment pins. When a pin's saved xpath is rooted at an
1396
+ * element id, that id is authoritative: the pin is placed only inside that element (on its
1397
+ * saved child path, else on the nearest element under the id that still exists), and is not
1398
+ * shown where the id is absent. New pins also skip framework-generated ids (React `useId`,
1399
+ * Radix) when choosing the id to root at. Applies to existing pins. Defaults to disabled.
1400
+ */
1401
+ public enableIdScopedAnchoring: () => void;
1402
+
1403
+ /**
1404
+ * To disable id-scoped anchoring. Pins resolve through the default anchor resolution,
1405
+ * which is the default behaviour.
1406
+ */
1407
+ public disableIdScopedAnchoring: () => void;
1408
+
1394
1409
  /**
1395
1410
  * To enable filter comments on dom
1396
1411
  */
@@ -2780,6 +2795,16 @@ export declare class CommentElement {
2780
2795
  */
2781
2796
  private _disableDraftConfirmation;
2782
2797
 
2798
+ /**
2799
+ * To enable id-scoped anchoring for comment pins
2800
+ */
2801
+ private _enableIdScopedAnchoring;
2802
+
2803
+ /**
2804
+ * To disable id-scoped anchoring for comment pins
2805
+ */
2806
+ private _disableIdScopedAnchoring;
2807
+
2783
2808
  /**
2784
2809
  * To enable filter comments on dom
2785
2810
  */
@@ -18,6 +18,12 @@ export declare class Constants {
18
18
  * (catchError → of([]) → every row on the page silently vanishes).
19
19
  */
20
20
  static FIRESTORE_MAX_DISJUNCTIONS: number;
21
+ /**
22
+ * Firestore's cap on the values of one `in` / `array-contains-any` filter. Hosted queries slice or
23
+ * batch their id lists to it, and the Tier B gateway ops that replace those queries apply the SAME
24
+ * cap client-side so both tiers ask for the same rows (Group 9: one name, not nine literals).
25
+ */
26
+ static readonly FIRESTORE_IN_QUERY_LIMIT = 30;
21
27
  static DEFAULT_VELT_CONTEXT: string;
22
28
  static VISIBILITY_SELF_PREFIX: string;
23
29
  static VISIBILITY_ORG_PREFIX: string;
@@ -641,6 +647,7 @@ export declare class Constants {
641
647
  VELT_COMMENT_VIEWS_MIGRATED: string;
642
648
  VELT_AUTH_PROXY_HOST: string;
643
649
  VELT_PORTABLE_SESSION: string;
650
+ VELT_PORTABLE_SIGNED_OUT: string;
644
651
  };
645
652
  static NON_NESTABLE_ELEMENTS: {
646
653
  [tag: string]: boolean;
@@ -1 +1 @@
1
- import{h as V}from"./chunk-FS6KTSNQ.js";import{Ga as x,Ha as L,Ja as D,M as C,R as v,S as I}from"./chunk-2XFRSBAE.js";import{Bi as y,Ri as E,Ti as U,Wa as m,_a as d,a as s,b as h,fa as o,sa as f,xc as u,ya as S,zc as p}from"./chunk-RV7ZJ7J2.js";var A=(()=>{let r=class r extends D{set parentLocalUIState(t){try{t&&(this.localUIStateSignal=t,this.isLocalUIStateOwner=!1,this._localUIStateFromExplicitInput=!0)}catch{}}get elementRef(){try{return this.hostElementRef}catch{return null}}getServiceComponentConfigSignal(){}constructor(){let t=o(S),e=o(L),i=o(p),a=o(E).get(y),g=o(x),l=o(U);super(t,e,i,a??void 0,void 0,g,l),this.defaultCondition=u(!0,{transform:n=>{try{return typeof n=="string"?n==="true"||n==="":n}catch{return!0}}}),this.isLocalUIStateOwner=!1,this._localUIStateFromExplicitInput=!1,this.veltContextHost=new V({getHost:()=>this.hostElementRef?.nativeElement,ownerRef:this,getEntity:()=>this.getPublishedVeltEntity(),getLocalUIState:()=>this.isLocalUIStateOwner?this.localUIStateSignal:void 0,onContextChanged:()=>{this.adoptInheritedLocalUIState(),this.rebindServiceConfigFromPlacement(),this.onVeltContextChanged()},markForCheck:()=>this.cd?.markForCheck()}),this.isLocalUIStateRoot=!1,this.selfConnectedConfig=!1,this.ownsConfigSignal=!0;try{this.hostElementRef=t,this.themeService=e,this.dynamicDataService=g,this.loggingService=l,this.cd=i,this.commentService=a??void 0,this.initializeLocalUIState()}catch(n){this.loggingService=this.loggingService||l,this.loggingService?.catch?.("Error in V2PrimitiveThemedBase constructor:",n)}}initializeLocalUIState(){this.localUIStateSignal=f(this.getDefaultLocalUIState()),this.isLocalUIStateOwner=!0}getConditionalClassesContext(){return{componentConfigSignal:this.componentConfigSignal}}ngOnInit(){try{this.adoptInheritedLocalUIState(),this.connectToServiceSignalIfStandalone(),this.dynamicDataService.applyConditionalClasses(this.hostElementRef?.nativeElement,this.getConditionalClassesContext()),this.setupA11yAttributes(),this.isLocalUIStateOwner&&this.setupDarkModeSync(),this.finalizeVeltContext()}catch(t){this.loggingService.catch("Error in V2PrimitiveThemedBase ngOnInit:",t)}}adoptInheritedLocalUIState(){try{v({host:this.hostElementRef?.nativeElement,current:this.localUIStateSignal,isOwner:this.isLocalUIStateOwner,fromExplicitInput:this._localUIStateFromExplicitInput,isRoot:this.isLocalUIStateRoot,adopt:t=>{this.localUIStateSignal=t,this.isLocalUIStateOwner=!1}})}catch(t){this.loggingService.catch("Error in V2PrimitiveThemedBase adoptInheritedLocalUIState:",t)}}rebindServiceConfigFromPlacement(){try{if(!this.selfConnectedConfig)return;let t=this.getServiceComponentConfigSignal();if(!t||t===this.componentConfigSignal)return;let e=this.componentConfigSignal,i=this.ownsConfigSignal;if(this.componentConfigSignal=t,this.ownsConfigSignal=!1,i)try{e?.update(a=>s({},a))}catch{}this.cd?.markForCheck()}catch(t){this.loggingService.catch("Error in V2PrimitiveThemedBase rebindServiceConfigFromPlacement:",t)}}finalizeVeltContext(){this.veltContextHost.finalize()}getPublishedVeltEntity(){}getInheritedVeltEntity(){try{return I(this.hostElementRef?.nativeElement)}catch{return}}refreshVeltContextFromPlacement(){this.veltContextHost.refreshFromPlacement()}onVeltContextChanged(){}getInheritedVeltContextData(){try{return C(this.hostElementRef?.nativeElement)?.payload?.contextData||{}}catch{return{}}}connectToServiceSignalIfStandalone(){try{let t=this.componentConfigSignal();if(!t||!t?.uiState){this.selfConnectedConfig=!0;let e=this.getServiceComponentConfigSignal();e&&(this.componentConfigSignal=e,this.ownsConfigSignal=!1)}}catch(t){this.loggingService.catch("Error connecting to service signal:",t)}}ngOnDestroy(){try{this.darkModeConfigSyncSubscription&&this.darkModeConfigSyncSubscription.unsubscribe(),this.veltContextHost.destroy(),super.ngOnDestroy()}catch(t){this.loggingService.catch("Error in V2PrimitiveThemedBase ngOnDestroy:",t)}}setupA11yAttributes(){}setupDarkModeSync(){try{this.darkModeConfigSyncSubscription=this.onDarkModeChange().subscribe(t=>{try{if(this.componentConfigSignal&&typeof this.componentConfigSignal=="function"){let e=this.componentConfigSignal();e&&e.uiState&&e.uiState.darkMode!==t&&this.componentConfigSignal.update(i=>h(s({},i),{uiState:h(s({},i.uiState),{darkMode:t})}))}}catch(e){this.loggingService.catch("Error in darkMode sync subscription:",e)}})}catch(t){this.loggingService.catch("Error in V2PrimitiveThemedBase setupDarkModeSync:",t)}}};r.\u0275fac=function(e){return new(e||r)},r.\u0275cmp=m({type:r,selectors:[["app-v2-primitive-themed-base"]],inputs:{defaultCondition:[1,"defaultCondition"],parentLocalUIState:"parentLocalUIState"},standalone:!1,features:[d],decls:0,vars:0,template:function(e,i){},encapsulation:2});let c=r;return c})();export{A as a};
1
+ import{h as V}from"./chunk-HEFEC6O6.js";import{Ga as x,Ha as L,Ja as D,M as C,R as v,S as I}from"./chunk-IUD3QEEM.js";import{Hi as y,Wa as m,Xi as E,Zi as U,_a as d,a as s,b as h,fa as o,sa as f,xc as u,ya as S,zc as p}from"./chunk-TAGMM5ED.js";var A=(()=>{let r=class r extends D{set parentLocalUIState(t){try{t&&(this.localUIStateSignal=t,this.isLocalUIStateOwner=!1,this._localUIStateFromExplicitInput=!0)}catch{}}get elementRef(){try{return this.hostElementRef}catch{return null}}getServiceComponentConfigSignal(){}constructor(){let t=o(S),e=o(L),i=o(p),a=o(E).get(y),g=o(x),l=o(U);super(t,e,i,a??void 0,void 0,g,l),this.defaultCondition=u(!0,{transform:n=>{try{return typeof n=="string"?n==="true"||n==="":n}catch{return!0}}}),this.isLocalUIStateOwner=!1,this._localUIStateFromExplicitInput=!1,this.veltContextHost=new V({getHost:()=>this.hostElementRef?.nativeElement,ownerRef:this,getEntity:()=>this.getPublishedVeltEntity(),getLocalUIState:()=>this.isLocalUIStateOwner?this.localUIStateSignal:void 0,onContextChanged:()=>{this.adoptInheritedLocalUIState(),this.rebindServiceConfigFromPlacement(),this.onVeltContextChanged()},markForCheck:()=>this.cd?.markForCheck()}),this.isLocalUIStateRoot=!1,this.selfConnectedConfig=!1,this.ownsConfigSignal=!0;try{this.hostElementRef=t,this.themeService=e,this.dynamicDataService=g,this.loggingService=l,this.cd=i,this.commentService=a??void 0,this.initializeLocalUIState()}catch(n){this.loggingService=this.loggingService||l,this.loggingService?.catch?.("Error in V2PrimitiveThemedBase constructor:",n)}}initializeLocalUIState(){this.localUIStateSignal=f(this.getDefaultLocalUIState()),this.isLocalUIStateOwner=!0}getConditionalClassesContext(){return{componentConfigSignal:this.componentConfigSignal}}ngOnInit(){try{this.adoptInheritedLocalUIState(),this.connectToServiceSignalIfStandalone(),this.dynamicDataService.applyConditionalClasses(this.hostElementRef?.nativeElement,this.getConditionalClassesContext()),this.setupA11yAttributes(),this.isLocalUIStateOwner&&this.setupDarkModeSync(),this.finalizeVeltContext()}catch(t){this.loggingService.catch("Error in V2PrimitiveThemedBase ngOnInit:",t)}}adoptInheritedLocalUIState(){try{v({host:this.hostElementRef?.nativeElement,current:this.localUIStateSignal,isOwner:this.isLocalUIStateOwner,fromExplicitInput:this._localUIStateFromExplicitInput,isRoot:this.isLocalUIStateRoot,adopt:t=>{this.localUIStateSignal=t,this.isLocalUIStateOwner=!1}})}catch(t){this.loggingService.catch("Error in V2PrimitiveThemedBase adoptInheritedLocalUIState:",t)}}rebindServiceConfigFromPlacement(){try{if(!this.selfConnectedConfig)return;let t=this.getServiceComponentConfigSignal();if(!t||t===this.componentConfigSignal)return;let e=this.componentConfigSignal,i=this.ownsConfigSignal;if(this.componentConfigSignal=t,this.ownsConfigSignal=!1,i)try{e?.update(a=>s({},a))}catch{}this.cd?.markForCheck()}catch(t){this.loggingService.catch("Error in V2PrimitiveThemedBase rebindServiceConfigFromPlacement:",t)}}finalizeVeltContext(){this.veltContextHost.finalize()}getPublishedVeltEntity(){}getInheritedVeltEntity(){try{return I(this.hostElementRef?.nativeElement)}catch{return}}refreshVeltContextFromPlacement(){this.veltContextHost.refreshFromPlacement()}onVeltContextChanged(){}getInheritedVeltContextData(){try{return C(this.hostElementRef?.nativeElement)?.payload?.contextData||{}}catch{return{}}}connectToServiceSignalIfStandalone(){try{let t=this.componentConfigSignal();if(!t||!t?.uiState){this.selfConnectedConfig=!0;let e=this.getServiceComponentConfigSignal();e&&(this.componentConfigSignal=e,this.ownsConfigSignal=!1)}}catch(t){this.loggingService.catch("Error connecting to service signal:",t)}}ngOnDestroy(){try{this.darkModeConfigSyncSubscription&&this.darkModeConfigSyncSubscription.unsubscribe(),this.veltContextHost.destroy(),super.ngOnDestroy()}catch(t){this.loggingService.catch("Error in V2PrimitiveThemedBase ngOnDestroy:",t)}}setupA11yAttributes(){}setupDarkModeSync(){try{this.darkModeConfigSyncSubscription=this.onDarkModeChange().subscribe(t=>{try{if(this.componentConfigSignal&&typeof this.componentConfigSignal=="function"){let e=this.componentConfigSignal();e&&e.uiState&&e.uiState.darkMode!==t&&this.componentConfigSignal.update(i=>h(s({},i),{uiState:h(s({},i.uiState),{darkMode:t})}))}}catch(e){this.loggingService.catch("Error in darkMode sync subscription:",e)}})}catch(t){this.loggingService.catch("Error in V2PrimitiveThemedBase setupDarkModeSync:",t)}}};r.\u0275fac=function(e){return new(e||r)},r.\u0275cmp=m({type:r,selectors:[["app-v2-primitive-themed-base"]],inputs:{defaultCondition:[1,"defaultCondition"],parentLocalUIState:"parentLocalUIState"},standalone:!1,features:[d],decls:0,vars:0,template:function(e,i){},encapsulation:2});let c=r;return c})();export{A as a};
@@ -1 +1 @@
1
- import{Ra as c,Za as o,wj as s}from"./chunk-RV7ZJ7J2.js";var n=(()=>{let r=class r{constructor(t){this.domService=t}transform(t){try{return this.domService.sanitizeHtml(t)}catch{return t}}};r.\u0275fac=function(i){return new(i||r)(c(s,16))},r.\u0275pipe=o({name:"sanitizeHtml",type:r,pure:!0});let e=r;return e})();export{n as a};
1
+ import{Fj as s,Ra as c,Za as o}from"./chunk-TAGMM5ED.js";var n=(()=>{let r=class r{constructor(t){this.domService=t}transform(t){try{return this.domService.sanitizeHtml(t)}catch{return t}}};r.\u0275fac=function(i){return new(i||r)(c(s,16))},r.\u0275pipe=o({name:"sanitizeHtml",type:r,pure:!0});let e=r;return e})();export{n as a};
@@ -1 +1 @@
1
- import{a as N}from"./chunk-YNFDUIYD.js";import{e as K,t as W}from"./chunk-I6ELSCG4.js";import{E as P,G as x,He as m,J as C,K as f,Kg as T,Oa as j,Pg as k,Ti as g,ba as v,db as X,ea as a,jj as G,l as p,mj as B,na as M,r as A,rg as $,uh as V,vh as L,w as D,wh as H,wj as J,xh as z,xj as b,yh as R,z as y,zh as F}from"./chunk-RV7ZJ7J2.js";var h=(function(l){return l.CLICK="click",l.HOVER="hover",l.SCROLL="scroll",l.NAVIGATE="navigate",l})(h||{}),u=class{constructor(){this.type=h.HOVER,this.data=null,this.pageInfo=k(),this.timestamp=Date.now()}},U=class{constructor(n,w){this.targetXpath=n,this.xpath=w}};var E=class{constructor(){this.sessionId=null,this.isLeader=!1,this.lastProcessedActionTimestamp=null}};var S=class{constructor(n){this.snippylyId=n,this.joinTimestamp=Date.now()}};var I=class{constructor(n,w,e){this.followers=[],this.actionStack=[],this.id=$(),this.leaderId=n,this.leaderName=w,this.followers.push(new S(e))}};var Q=(()=>{let n=class n{constructor(e,t,r,i,o,s){this.databaseService=e,this.docService=t,this.loggingService=r,this.authService=i,this.commonDbService=o,this.realtimeAdapter=s,this.currentUser$=new p(null),this.currentSession$=new p(null);try{this.databaseService.getDb().pipe(P(c=>!!c),f(1)).subscribe(c=>{c&&(this.db=c)},c=>{this.loggingService.catch("Error in FlockSessionService getDb subscription: ",c)}),this.authService.getUser$().subscribe(c=>{c&&c.userSnippylyId&&(this.user=c)})}catch(c){this.loggingService.catch("Error in FlockSessionService constructor: ",c)}}startCurrentFlockUserSubscription(e){try{this.currentUserSub?.unsubscribe(),e&&e.userSnippylyId&&(this.user=e,this.subscribeToCurrentFlockUser(e?.userSnippylyId))}catch(t){this.loggingService.catch("Error in FlockSessionService startCurrentFlockUserSubscription: ",t)}}stopCurrentFlockUserSubscription(){try{this.currentUserSub?.unsubscribe()}catch(e){this.loggingService.catch("Error in FlockSessionService stopCurrentFlockUserSubscription: ",e)}}provisionFlockSession(e,t,r){try{let i=this.docService.getDocumentPaths();i&&this.db&&this.commonDbService.dbListener({feature:"flockUser",properties:{documentId:i?.documentId,organizationId:i?.organizationId,id:e,skipFirestore:!0}}).pipe(f(1)).subscribe(o=>{o?.data&&o?.data?.sessionId?this.subscribeToCurrentSession(o?.data?.sessionId,r):this.createFlockSession(e,t,r)})}catch(i){this.loggingService.catch("Error in FlockSessionService provisionFlockSession: ",i)}return null}swapLeader(e,t,r){try{if(this.updateRemoteFlockUser(e,{isLeader:!1}),this.updateRemoteFlockUser(t,{isLeader:!0}),this.currentSession){this.currentSession.leaderId=t,this.currentSession.leaderName=r,this.currentSession.followers.push(new S(e));let i=this.currentSession.followers.findIndex(o=>o.snippylyId===t);i>-1&&this.currentSession.followers.splice(i,1),this.updateSession(this.currentSession.id,this.currentSession)}}catch(i){this.loggingService.catch("Error in FlockSessionService swapLeader: ",i)}}createFlockSession(e,t,r){try{let i=new I(e,t,r);return this.updateRemoteFlockUser(e,{snippylyId:e,sessionId:i.id,isLeader:!0}),this.updateSession(i.id,i),this.subscribeToCurrentSession(i.id),i.id}catch(i){this.loggingService.catch("Error in FlockSessionService createFlockSession: ",i)}return null}removeFollowerFromCurrentSession(e){try{if(this.currentSession){this.updateRemoteFlockUser(e,{sessionId:null,lastProcessedActionTimestamp:null});let t=this.currentSession.followers.findIndex(r=>r.snippylyId===e);if(t>-1){if(this.currentSession.followers.splice(t,1),this.currentSession.followers.length===0){this.deleteSession(this.currentSession.id);return}this.updateSession(this.currentSession.id,this.currentSession),this.user&&this.user.userSnippylyId&&this.user.userSnippylyId===e&&(this.sessionSub?.unsubscribe(),this.currentSession=void 0,this.currentSession$?.next(null))}}}catch(t){this.loggingService.catch("Error in FlockSessionService removeFollowerFromSession: ",t)}}updateRemoteFlockUser(e,t={}){try{if(!e)return;let r=this.docService.getDocumentPaths();for(let i in t)t.hasOwnProperty(i)&&t[i]===void 0&&delete t[i];r&&this.db&&this.commonDbService.updateData({feature:"flockUser",properties:{documentId:r?.documentId??"",organizationId:r?.organizationId??"",id:e,skipFirestore:!0},data:JSON.parse(JSON.stringify(t))})}catch(r){this.loggingService.catch("Error in FlockSessionService updateRemoteFlockUser: ",r)}}subscribeToCurrentSession(e,t=void 0){try{let r=this.docService.getDocumentPaths();r&&this.db&&(this.sessionSub&&this.sessionSub.unsubscribe(),this.sessionSub=this.commonDbService.dbListener({feature:"flockSession",properties:{documentId:r?.documentId,organizationId:r?.organizationId,id:e,skipFirestore:!0}}).subscribe(i=>{i?.data&&typeof i?.data=="object"&&Object.keys(i?.data)?.length>0?(this.currentSession=i?.data,t!==void 0&&this.currentSession?.followers.findIndex(o=>o.snippylyId===t)===-1&&(this.currentSession.followers.push(new S(t)),this.updateSession(this.currentSession.id,this.currentSession)),this.currentSession$.next(this.currentSession??null)):(this.currentSession=void 0,this.currentSession$.next(null))}))}catch(r){this.loggingService.catch("Error in FlockSessionService subscribeToCurrentSession: ",r)}}subscribeToCurrentFlockUser(e){try{let t=this.docService.getDocumentPaths();t&&this.db&&(this.currentUserSub&&this.currentUserSub.unsubscribe(),this.currentUserSub=this.commonDbService.dbListener({feature:"flockUser",properties:{documentId:t?.documentId,organizationId:t?.organizationId,id:e,skipFirestore:!0}}).pipe(x(r=>(this.loggingService.catch("Error in FlockSessionService subscribeToCurrentFlockUser: ",r),A(null)))).subscribe(r=>{r?.data&&typeof r?.data=="object"&&Object.keys(r?.data)?.length>0&&(this.currentUser$.next(r?.data),r?.data?.sessionId&&this.subscribeToCurrentSession(r?.data?.sessionId))},r=>{this.loggingService.catch("Error in FlockSessionService subscribeToCurrentFlockUser subscription: ",r)}))}catch(t){this.loggingService.catch("Error in FlockSessionService subscribeToCurrentFlockUser: ",t)}}updateSession(e,t={}){try{if(!e)return;let r=this.docService.getDocumentPaths();for(let i in t)t.hasOwnProperty(i)&&t[i]===void 0&&delete t[i];r&&this.db&&this.commonDbService.updateData({feature:"flockSession",properties:{documentId:r?.documentId??"",organizationId:r?.organizationId??"",id:e,skipFirestore:!0},data:JSON.parse(JSON.stringify(t))})}catch(r){this.loggingService.catch("Error in FlockSessionService updateSession: ",r)}}deleteSession(e){try{let t=this.docService.getDocumentPaths();t&&this.db&&(this.commonDbService.deleteData({feature:"flockSession",properties:{documentId:t?.documentId??"",organizationId:t?.organizationId??"",id:e,skipFirestore:!0}}),this.currentSession&&e===this.currentSession.id&&(this.updateRemoteFlockUser(this.currentSession.leaderId,{sessionId:null,isLeader:!1,lastProcessedActionTimestamp:null}),this.currentSession.followers.forEach(r=>{this.updateRemoteFlockUser(r.snippylyId,{sessionId:null,lastProcessedActionTimestamp:null})}),this.currentSession=void 0,this.currentSession$.next(null),this.sessionSub?.unsubscribe()))}catch(t){this.loggingService.catch("Error in FlockSessionService deleteSession: ",t)}}addActionToStack(e,t){try{t=t&&JSON.parse(JSON.stringify(t));let r=this.docService.getDocumentPaths();if(r&&this.db&&e){let i=this.realtimeAdapter.rtdbRef(this.db,`${r.flock}/sessions/${e}/actionStack`);this.realtimeAdapter.rtdbRunTransaction("flockSession",i,o=>o?(o.unshift(t),o.slice(0,5)):[t]),t.type===h.NAVIGATE&&this.updateSession(e,{pageInfo:t.pageInfo})}}catch(r){this.loggingService.catch("Error in FlockSessionService addActionToStack: ",r)}}};n.\u0275fac=function(t){return new(t||n)(a(G),a(K),a(g),a(b),a(W),a(B))},n.\u0275prov=v({token:n,factory:n.\u0275fac,providedIn:"root"});let l=n;return l})();var Z=(()=>{let n=class n{constructor(e,t,r,i){this.componentFactoryResolver=e,this.applicationRef=t,this.injector=r,this.loggingService=i,this.darkMode=!1}createFollowOverlay(e,t){try{let i=this.componentFactoryResolver.resolveComponentFactory(N).create(this.injector);i.instance.setLeaderName(e),i.instance.closeOverlayEvent.pipe(f(1)).subscribe(()=>{this.removeOverlay(),t()}),this.applicationRef.attachView(i.hostView),this.overlayRef=i,this.overlayRef.instance.darkMode=this.darkMode;let o=this.overlayRef.location.nativeElement;o.id="snippyly-follow-overlay",o.setAttribute(m.ATTRIBUTES.VELT_IGNORE,""),document.body.appendChild(o)}catch(r){this.loggingService.catch("Error in FlockOverlayService createFollowOverlay: ",r)}}createLeaderOverlay(e){let r=this.componentFactoryResolver.resolveComponentFactory(N).create(this.injector);r.instance.setType("leading"),r.instance.closeOverlayEvent.pipe(f(1)).subscribe(()=>{this.removeOverlay(),e()}),this.applicationRef.attachView(r.hostView),this.overlayRef=r,this.overlayRef.instance.darkMode=this.darkMode;let i=this.overlayRef.location.nativeElement;i.id="snippyly-follow-overlay",i.setAttribute(m.ATTRIBUTES.VELT_IGNORE,""),document.body.appendChild(i)}changeLeaderName(e){this.overlayRef&&this.overlayRef.instance.setLeaderName(e)}getLeaderName(){return this.overlayRef?this.overlayRef.instance.getLeaderName():null}removeOverlay(){if(this.overlayRef){let e=this.overlayRef.location.nativeElement;this.applicationRef.detachView(this.overlayRef.hostView),this.overlayRef.destroy(),e.shadowRoot&&e.shadowRoot.removeChild(e.shadowRoot.childNodes[0]),e.remove(),this.overlayRef=void 0}}setDarkMode(e){try{this.darkMode=e,this.overlayRef&&(this.overlayRef.instance.darkMode=e)}catch(t){this.loggingService.catch("Error in FlockOverlayService setDarkMode: ",t)}}};n.\u0275fac=function(t){return new(t||n)(a(j),a(X),a(M),a(g))},n.\u0275prov=v({token:n,factory:n.\u0275fac,providedIn:"root"});let l=n;return l})();var Ce=(()=>{let n=class n{constructor(e,t,r,i,o){this.authService=e,this.domService=t,this.loggingService=r,this.flockSessionService=i,this.flockOverlayService=o,this.flockLeader$=new p({userId:"",name:""}),this.flockMode$=new p(!1),this.currentFlockUser=null,this.localScrollData=[],this.domSubscriptions=[],this.followOverlayCreated=!1,this.leaderOverlayCreated=!1,this.windowFocused=!0,this.tabFocused=!0,this.useHistoryAPI=!0,this.disableDefaultNavigation=!1;try{this.flockLeader$.subscribe(s=>{let{userId:c,name:d}=s,O=c;if(this.provisionFollowUser(),O&&this.currentFlockUser&&this.currentFlockUser.snippylyId)if(this.currentFlockUser.sessionId){if(this.currentFlockUser.snippylyId&&this.currentFlockUser.isLeader){this.flockSessionService.swapLeader(this.currentFlockUser.snippylyId,O,d);return}this.removeCurrentUserFromSession()}else this.flockSessionService.provisionFlockSession(O,d,this.currentFlockUser.snippylyId)},s=>{this.loggingService.catch("Error in FlockService flockLeader$ subscription: ",s)}),this.flockSessionService.currentSession$.subscribe(s=>{if(s!==null){if(this.currentFlockUser&&(this.currentFlockUser.sessionId===null||this.currentFlockUser.sessionId===void 0)&&this.currentFlockUser.snippylyId&&(this.currentFlockUser.sessionId=s.id,this.flockSessionService.updateRemoteFlockUser(this.currentFlockUser.snippylyId,this.currentFlockUser)),this.currentFlockUser&&!this.currentFlockUser.isLeader&&!this.followOverlayCreated&&(this.leaderOverlayCreated&&(this.flockOverlayService.removeOverlay(),this.leaderOverlayCreated=!1),this.followOverlayCreated=!0,this.flockOverlayService.createFollowOverlay(s.leaderName,()=>{this.removeCurrentUserFromSession(),this.followOverlayCreated=!1})),this.currentFlockUser&&this.currentFlockUser.isLeader&&!this.leaderOverlayCreated&&(this.followOverlayCreated&&(this.flockOverlayService.removeOverlay(),this.followOverlayCreated=!1),this.leaderOverlayCreated=!0,this.flockOverlayService.createLeaderOverlay(()=>{this.removeCurrentUserFromSession(),this.leaderOverlayCreated=!1})),this.currentFlockUser&&!this.currentFlockUser.isLeader&&s.actionStack){let c=s.actionStack[0];c&&this.currentFlockUser.lastProcessedActionTimestamp!==c.timestamp&&this.processAction(c)}if(this.currentFlockUser&&!this.currentFlockUser.isLeader&&this.followOverlayCreated&&this.flockOverlayService.getLeaderName()!==null&&s.leaderName!==this.flockOverlayService.getLeaderName()&&this.flockOverlayService.changeLeaderName(s.leaderName),this.currentFlockUser&&this.currentFlockUser.isLeader){let c=k();if(s.pageInfo){if(c&&c.url!==s.pageInfo.url){let d=new u;d.type=h.NAVIGATE,this.flockSessionService.addActionToStack(s.id,d)}}else{this.flockSessionService.updateSession(s.id,{pageInfo:c});let d=new u;d.type=h.NAVIGATE,this.flockSessionService.addActionToStack(s.id,d)}}}else this.currentFlockUser&&this.leaderOverlayCreated&&(this.flockOverlayService.removeOverlay(),this.leaderOverlayCreated=!1),this.currentFlockUser&&this.followOverlayCreated&&(this.flockOverlayService.removeOverlay(),this.followOverlayCreated=!1)}),this.flockSessionService.currentUser$.subscribe(s=>{if(s!==null&&(this.currentFlockUser&&this.currentFlockUser.isLeader!==s.isLeader&&(this.domSubscriptions.forEach(c=>c.unsubscribe()),this.domSubscriptions=[]),this.currentFlockUser=s,s.sessionId&&this.domSubscriptions.length===0))if(s.isLeader){if(!this.tabFocused||!this.windowFocused)return;this.subscribeToLeaderDOMEvents()}else this.subscribeToFollowerDOMEvents()}),D([this.authService.getUser$(),this.getFlockMode$()]).subscribe(([s,c])=>{s&&s.userSnippylyId&&c?this.flockSessionService.startCurrentFlockUserSubscription(s):this.flockSessionService.stopCurrentFlockUserSubscription()})}catch(s){this.loggingService.catch("Error in FlockService constructor: ",s)}}provisionFollowUser(){try{if(this.currentFlockUser===null){let e=this.authService.getUser();e&&e.userSnippylyId&&(this.currentFlockUser=new E,this.currentFlockUser.snippylyId=e.userSnippylyId)}}catch(e){this.loggingService.catch("Error in FlockService provisionFollowUser: ",e)}}startFollowingUser(e,t){try{if(this.provisionFollowUser(),e&&this.currentFlockUser&&this.currentFlockUser.snippylyId){if(this.currentFlockUser.sessionId){if(this.currentFlockUser.snippylyId&&this.currentFlockUser.isLeader){this.flockSessionService.swapLeader(this.currentFlockUser.snippylyId,e,t);return}this.removeCurrentUserFromSession()}this.flockSessionService.provisionFlockSession(e,t,this.currentFlockUser.snippylyId)}}catch(r){this.loggingService.catch("Error in FlockService startFollowingUser: ",r)}}stopFollowingUser(){try{this.removeCurrentUserFromSession()}catch(e){this.loggingService.catch("Error in FlockService stopFollowingUser: ",e)}}subscribeToUrlChanges(){try{if(this.useHistoryAPI){let e=window.history.pushState,t=window.history.replaceState;window.history.pushState=(...r)=>{e.apply(window.history,r),this.onUrlChange()},window.history.replaceState=(...r)=>{t.apply(window.history,r),this.onUrlChange()},this.domSubscriptions.push({unsubscribe:()=>{window.history.pushState=e,window.history.replaceState=t}}),this.domSubscriptions.push(y(window,"popstate").subscribe(()=>{this.onUrlChange()}))}}catch(e){this.loggingService.catch("Error in FlockService subscribeToUrlChanges: ",e)}}onUrlChange(){try{if(this.currentFlockUser&&this.currentFlockUser.sessionId&&this.currentFlockUser.isLeader){let e=new u;e.type=h.NAVIGATE,this.flockSessionService.addActionToStack(this.currentFlockUser.sessionId,e)}}catch(e){this.loggingService.catch("Error in FlockService onUrlChange: ",e)}}processAction(e){try{switch(e.type){case h.CLICK:this.clickUserElement(e.data);break;case h.HOVER:this.scrollToHoveredElement(e.data);break;case h.SCROLL:this.scrollToFollowedUser(e.data);break;case h.NAVIGATE:this.checkMatchingUrl(e.pageInfo);break}this.currentFlockUser&&this.currentFlockUser.snippylyId&&this.flockSessionService.updateRemoteFlockUser(this.currentFlockUser.snippylyId,{lastProcessedActionTimestamp:e.timestamp})}catch(t){this.loggingService.catch("Error in FlockService processAction: ",t)}}subscribeToLeaderDOMEvents(){try{this.domSubscriptions.length>0&&(this.domSubscriptions.forEach(e=>e.unsubscribe()),this.domSubscriptions=[]),this.domSubscriptions.push(y(window,"mouseover").pipe(C(500)).subscribe(e=>{let t=e?.target;if(t){let r=window.getComputedStyle(t);if(r.position==="fixed"||r.position==="sticky"||t.hasAttribute(m.ATTRIBUTES.VELT_IGNORE))return;t=L(t,{x:e.clientX,y:e.clientY}),this.updateHoveredElement(t)}})),this.domSubscriptions.push(this.domService.onWindowClick$().subscribe(e=>{let t=e?.target;if(t){if(t.hasAttribute(m.ATTRIBUTES.VELT_IGNORE))return;this.updateClickedElement(t)}})),this.subscribeToUrlChanges(),this.subscribeToScrollables()}catch(e){this.loggingService.catch("Error in FlockService subscribeToLeaderDOMEvents: ",e)}}subscribeToFollowerDOMEvents(){}updateClickedElement(e){try{if(this.currentFlockUser&&this.currentFlockUser.sessionId){let t=this.domService.getXPath(e),r=T(e),i=this.domService.getXPath(r),o={id:Math.random().toString(36).substring(2),xpath:t,parentXpath:i},s=new u;s.type=h.CLICK,s.data=o,this.flockSessionService.addActionToStack(this.currentFlockUser.sessionId,s)}}catch(t){this.loggingService.catch("Error in FlockService updateClickedElement: ",t)}}updateHoveredElement(e){try{if(this.currentFlockUser&&this.currentFlockUser.sessionId){let t=this.domService.getXPath(e),r=T(e),i=this.domService.getXPath(r),o={id:Math.random().toString(36).substring(2),xpath:t,parentXpath:i},s=new u;s.type=h.HOVER,s.data=o,this.flockSessionService.addActionToStack(this.currentFlockUser.sessionId,s)}}catch(t){this.loggingService.catch("Error in FlockService updateHoveredElement: ",t)}}subscribeToScrollables(){try{let e=V();e.push(document),e?.forEach(t=>{this.domSubscriptions.push(y(t,"scroll").pipe(C(100)).subscribe(r=>{this.currentFlockUser&&this.currentFlockUser.sessionId&&this.currentFlockUser.isLeader&&this.updateScrollPositionOfElement(t)}))})}catch(e){this.loggingService.catch("Error in FlockService getScrollableElements: ",e)}}updateScrollPositionOfElement(e){try{if(this.currentFlockUser&&this.currentFlockUser.sessionId){let t=new U("","");if(e===document){let o=z();if(o){let s=L(o);s&&(t.targetXpath=this.domService.getXPath(s))}t.xpath=""}else{let o=H(e);t.targetXpath=this.domService.getXPath(o),t.xpath=this.domService.getXPath(e)}let r=!1,i=!1;if(this.localScrollData.forEach((o,s)=>{o.xpath===o.xpath&&(t.targetXpath!==o.targetXpath&&(r=!0),this.localScrollData[s]=Object.assign(o,t),i=!0)}),i||this.localScrollData.push(t),r||!i){let o=new u;o.type=h.SCROLL,o.data=t,this.flockSessionService.addActionToStack(this.currentFlockUser.sessionId,o)}}}catch(t){this.loggingService.catch("Error in FlockService calculateScrollPositionOfAnElement: ",t)}}enableFlockMode(e){try{if(this.flockMode$.next(!0),e){let{useHistoryAPI:t,onNavigate:r,disableDefaultNavigation:i,darkMode:o}=e;t!==void 0&&(this.useHistoryAPI=t),r!==void 0&&typeof r=="function"&&(this.onNavigate=r),i!==void 0&&(this.disableDefaultNavigation=i),this.flockOverlayService.setDarkMode(o)}}catch(t){this.loggingService.catch("Error in FlockService enableFlockMode: ",t)}}disableFlockMode(){try{this.flockMode$.next(!1),this.onNavigateEmitter=void 0,this.useHistoryAPI=!0,this.onNavigate=void 0}catch(e){this.loggingService.catch("Error in FlockService disableFlockMode: ",e)}}setDisableFlockNavigation(e){try{this.disableDefaultNavigation=e}catch(t){this.loggingService.catch("Error in FlockService setDisableFlockNavigation: ",t)}}getFlockMode$(){return this.flockMode$.asObservable()}getFlockMode(){return this.flockMode$.value}setNavigateEmitter(e){try{this.onNavigateEmitter=e}catch(t){this.loggingService.catch("Error in FlockService setNavigateEmitter: ",t)}}setTabFocused(e){try{if(this.tabFocused=e,!this.currentFlockUser)return;this.currentFlockUser.isLeader&&this.currentFlockUser.sessionId&&(this.tabFocused&&this.domSubscriptions.length===0?this.subscribeToLeaderDOMEvents():!this.tabFocused&&this.domSubscriptions.length>0&&(this.domSubscriptions.forEach(r=>{r.unsubscribe()}),this.domSubscriptions=[]))}catch(t){this.loggingService.catch("Error in FlockService setTabFocused: ",t)}}setWindowFocused(e){try{if(this.windowFocused=e,!this.currentFlockUser)return;this.currentFlockUser.isLeader&&this.currentFlockUser.sessionId&&(this.windowFocused&&this.domSubscriptions.length===0?this.subscribeToLeaderDOMEvents():!this.windowFocused&&this.domSubscriptions.length>0&&(this.domSubscriptions.forEach(r=>{r.unsubscribe()}),this.domSubscriptions=[]))}catch(t){this.loggingService.catch("Error in FlockService setWindowFocused: ",t)}}setFlockLeader(e,t){try{this.flockLeader$.next({userId:e,name:t})}catch(r){this.loggingService.catch("Error in FlockService setFlockLeader: ",r)}}isInSession(){try{return!!(this.currentFlockUser&&this.currentFlockUser.sessionId)}catch(e){this.loggingService.catch("Error in FlockService isFollowing: ",e)}return!1}removeCurrentUserFromSession(){try{this.domSubscriptions.forEach(e=>e.unsubscribe()),this.domSubscriptions=[],this.currentFlockUser&&(this.currentFlockUser.isLeader?this.currentFlockUser.sessionId&&this.flockSessionService.deleteSession(this.currentFlockUser.sessionId):this.currentFlockUser.snippylyId&&this.flockSessionService.removeFollowerFromCurrentSession(this.currentFlockUser.snippylyId))}catch(e){this.loggingService.catch("Error in FlockService removeCurrentUserFromSession: ",e)}}checkMatchingUrl(e){try{let r=k()?.url,i=e.url;if(r!==i&&i!==void 0){let{url:o,path:s,baseUrl:c}=e;if(this.onNavigate!==void 0&&typeof this.onNavigate=="function"){this.onNavigate({url:o,path:s,baseUrl:c});return}if(this.onNavigateEmitter&&this.onNavigateEmitter.emit({url:o,path:s,baseUrl:c}),this.disableDefaultNavigation)return;window.location.href=i}}catch(t){this.loggingService.catch("Error in FlockService checkMatchingUrl: ",t)}}scrollToFollowedUser(e){try{if(e.xpath===""){let t=this.domService.getElementFromXPath(e.targetXpath);t&&F(t)}else{let t=this.domService.getElementFromXPath(e.xpath),r=this.domService.getElementFromXPath(e.targetXpath);t&&r&&(F(t),R(t,r))}}catch(t){this.loggingService.catch("Error in FlockService scrollToFollowedUser: ",t)}}clickUserElement(e){try{let t=this.domService.getElementFromXPath(e.xpath);t&&this.lastClickedElement?.id!==e.id&&(t?.click(),this.lastClickedElement=e)}catch(t){this.loggingService.catch("Error in FlockService clickUserElement: ",t)}}scrollToHoveredElement(e){try{let t=this.domService.getElementFromXPath(e.xpath);if(t&&e.parentXpath)if(e.parentXpath==="/html")F(t);else{let r=this.domService.getElementFromXPath(e.parentXpath);r&&R(r,t,!0)}}catch(t){this.loggingService.catch("Error in FlockService clickUserElement: ",t)}}};n.\u0275fac=function(t){return new(t||n)(a(b),a(J),a(g),a(Q),a(Z))},n.\u0275prov=v({token:n,factory:n.\u0275fac,providedIn:"root"});let l=n;return l})();export{Ce as a};
1
+ import{a as N}from"./chunk-ZPO5AK7X.js";import{v as K,w as W}from"./chunk-EPQLN2EE.js";import{Ah as V,Bh as L,Ch as H,Dh as z,E as P,Eh as R,Fh as F,Fj as J,G as x,Gj as b,He as m,J as C,K as f,Kg as T,Oa as j,Pg as k,Zi as g,ba as v,db as X,ea as a,l as p,na as M,r as A,rg as $,rj as G,uj as B,w as D,z as y}from"./chunk-TAGMM5ED.js";var h=(function(l){return l.CLICK="click",l.HOVER="hover",l.SCROLL="scroll",l.NAVIGATE="navigate",l})(h||{}),u=class{constructor(){this.type=h.HOVER,this.data=null,this.pageInfo=k(),this.timestamp=Date.now()}},U=class{constructor(n,w){this.targetXpath=n,this.xpath=w}};var E=class{constructor(){this.sessionId=null,this.isLeader=!1,this.lastProcessedActionTimestamp=null}};var S=class{constructor(n){this.snippylyId=n,this.joinTimestamp=Date.now()}};var I=class{constructor(n,w,e){this.followers=[],this.actionStack=[],this.id=$(),this.leaderId=n,this.leaderName=w,this.followers.push(new S(e))}};var Q=(()=>{let n=class n{constructor(e,t,r,i,o,s){this.databaseService=e,this.docService=t,this.loggingService=r,this.authService=i,this.commonDbService=o,this.realtimeAdapter=s,this.currentUser$=new p(null),this.currentSession$=new p(null);try{this.databaseService.getDb().pipe(P(c=>!!c),f(1)).subscribe(c=>{c&&(this.db=c)},c=>{this.loggingService.catch("Error in FlockSessionService getDb subscription: ",c)}),this.authService.getUser$().subscribe(c=>{c&&c.userSnippylyId&&(this.user=c)})}catch(c){this.loggingService.catch("Error in FlockSessionService constructor: ",c)}}startCurrentFlockUserSubscription(e){try{this.currentUserSub?.unsubscribe(),e&&e.userSnippylyId&&(this.user=e,this.subscribeToCurrentFlockUser(e?.userSnippylyId))}catch(t){this.loggingService.catch("Error in FlockSessionService startCurrentFlockUserSubscription: ",t)}}stopCurrentFlockUserSubscription(){try{this.currentUserSub?.unsubscribe()}catch(e){this.loggingService.catch("Error in FlockSessionService stopCurrentFlockUserSubscription: ",e)}}provisionFlockSession(e,t,r){try{let i=this.docService.getDocumentPaths();i&&this.db&&this.commonDbService.dbListener({feature:"flockUser",properties:{documentId:i?.documentId,organizationId:i?.organizationId,id:e,skipFirestore:!0}}).pipe(f(1)).subscribe(o=>{o?.data&&o?.data?.sessionId?this.subscribeToCurrentSession(o?.data?.sessionId,r):this.createFlockSession(e,t,r)})}catch(i){this.loggingService.catch("Error in FlockSessionService provisionFlockSession: ",i)}return null}swapLeader(e,t,r){try{if(this.updateRemoteFlockUser(e,{isLeader:!1}),this.updateRemoteFlockUser(t,{isLeader:!0}),this.currentSession){this.currentSession.leaderId=t,this.currentSession.leaderName=r,this.currentSession.followers.push(new S(e));let i=this.currentSession.followers.findIndex(o=>o.snippylyId===t);i>-1&&this.currentSession.followers.splice(i,1),this.updateSession(this.currentSession.id,this.currentSession)}}catch(i){this.loggingService.catch("Error in FlockSessionService swapLeader: ",i)}}createFlockSession(e,t,r){try{let i=new I(e,t,r);return this.updateRemoteFlockUser(e,{snippylyId:e,sessionId:i.id,isLeader:!0}),this.updateSession(i.id,i),this.subscribeToCurrentSession(i.id),i.id}catch(i){this.loggingService.catch("Error in FlockSessionService createFlockSession: ",i)}return null}removeFollowerFromCurrentSession(e){try{if(this.currentSession){this.updateRemoteFlockUser(e,{sessionId:null,lastProcessedActionTimestamp:null});let t=this.currentSession.followers.findIndex(r=>r.snippylyId===e);if(t>-1){if(this.currentSession.followers.splice(t,1),this.currentSession.followers.length===0){this.deleteSession(this.currentSession.id);return}this.updateSession(this.currentSession.id,this.currentSession),this.user&&this.user.userSnippylyId&&this.user.userSnippylyId===e&&(this.sessionSub?.unsubscribe(),this.currentSession=void 0,this.currentSession$?.next(null))}}}catch(t){this.loggingService.catch("Error in FlockSessionService removeFollowerFromSession: ",t)}}updateRemoteFlockUser(e,t={}){try{if(!e)return;let r=this.docService.getDocumentPaths();for(let i in t)t.hasOwnProperty(i)&&t[i]===void 0&&delete t[i];r&&this.db&&this.commonDbService.updateData({feature:"flockUser",properties:{documentId:r?.documentId??"",organizationId:r?.organizationId??"",id:e,skipFirestore:!0},data:JSON.parse(JSON.stringify(t))})}catch(r){this.loggingService.catch("Error in FlockSessionService updateRemoteFlockUser: ",r)}}subscribeToCurrentSession(e,t=void 0){try{let r=this.docService.getDocumentPaths();r&&this.db&&(this.sessionSub&&this.sessionSub.unsubscribe(),this.sessionSub=this.commonDbService.dbListener({feature:"flockSession",properties:{documentId:r?.documentId,organizationId:r?.organizationId,id:e,skipFirestore:!0}}).subscribe(i=>{i?.data&&typeof i?.data=="object"&&Object.keys(i?.data)?.length>0?(this.currentSession=i?.data,t!==void 0&&this.currentSession?.followers.findIndex(o=>o.snippylyId===t)===-1&&(this.currentSession.followers.push(new S(t)),this.updateSession(this.currentSession.id,this.currentSession)),this.currentSession$.next(this.currentSession??null)):(this.currentSession=void 0,this.currentSession$.next(null))}))}catch(r){this.loggingService.catch("Error in FlockSessionService subscribeToCurrentSession: ",r)}}subscribeToCurrentFlockUser(e){try{let t=this.docService.getDocumentPaths();t&&this.db&&(this.currentUserSub&&this.currentUserSub.unsubscribe(),this.currentUserSub=this.commonDbService.dbListener({feature:"flockUser",properties:{documentId:t?.documentId,organizationId:t?.organizationId,id:e,skipFirestore:!0}}).pipe(x(r=>(this.loggingService.catch("Error in FlockSessionService subscribeToCurrentFlockUser: ",r),A(null)))).subscribe(r=>{r?.data&&typeof r?.data=="object"&&Object.keys(r?.data)?.length>0&&(this.currentUser$.next(r?.data),r?.data?.sessionId&&this.subscribeToCurrentSession(r?.data?.sessionId))},r=>{this.loggingService.catch("Error in FlockSessionService subscribeToCurrentFlockUser subscription: ",r)}))}catch(t){this.loggingService.catch("Error in FlockSessionService subscribeToCurrentFlockUser: ",t)}}updateSession(e,t={}){try{if(!e)return;let r=this.docService.getDocumentPaths();for(let i in t)t.hasOwnProperty(i)&&t[i]===void 0&&delete t[i];r&&this.db&&this.commonDbService.updateData({feature:"flockSession",properties:{documentId:r?.documentId??"",organizationId:r?.organizationId??"",id:e,skipFirestore:!0},data:JSON.parse(JSON.stringify(t))})}catch(r){this.loggingService.catch("Error in FlockSessionService updateSession: ",r)}}deleteSession(e){try{let t=this.docService.getDocumentPaths();t&&this.db&&(this.commonDbService.deleteData({feature:"flockSession",properties:{documentId:t?.documentId??"",organizationId:t?.organizationId??"",id:e,skipFirestore:!0}}),this.currentSession&&e===this.currentSession.id&&(this.updateRemoteFlockUser(this.currentSession.leaderId,{sessionId:null,isLeader:!1,lastProcessedActionTimestamp:null}),this.currentSession.followers.forEach(r=>{this.updateRemoteFlockUser(r.snippylyId,{sessionId:null,lastProcessedActionTimestamp:null})}),this.currentSession=void 0,this.currentSession$.next(null),this.sessionSub?.unsubscribe()))}catch(t){this.loggingService.catch("Error in FlockSessionService deleteSession: ",t)}}addActionToStack(e,t){try{t=t&&JSON.parse(JSON.stringify(t));let r=this.docService.getDocumentPaths();if(r&&this.db&&e){let i=this.realtimeAdapter.rtdbRef(this.db,`${r.flock}/sessions/${e}/actionStack`);this.realtimeAdapter.rtdbRunTransaction("flockSession",i,o=>o?(o.unshift(t),o.slice(0,5)):[t]),t.type===h.NAVIGATE&&this.updateSession(e,{pageInfo:t.pageInfo})}}catch(r){this.loggingService.catch("Error in FlockSessionService addActionToStack: ",r)}}};n.\u0275fac=function(t){return new(t||n)(a(G),a(W),a(g),a(b),a(K),a(B))},n.\u0275prov=v({token:n,factory:n.\u0275fac,providedIn:"root"});let l=n;return l})();var Z=(()=>{let n=class n{constructor(e,t,r,i){this.componentFactoryResolver=e,this.applicationRef=t,this.injector=r,this.loggingService=i,this.darkMode=!1}createFollowOverlay(e,t){try{let i=this.componentFactoryResolver.resolveComponentFactory(N).create(this.injector);i.instance.setLeaderName(e),i.instance.closeOverlayEvent.pipe(f(1)).subscribe(()=>{this.removeOverlay(),t()}),this.applicationRef.attachView(i.hostView),this.overlayRef=i,this.overlayRef.instance.darkMode=this.darkMode;let o=this.overlayRef.location.nativeElement;o.id="snippyly-follow-overlay",o.setAttribute(m.ATTRIBUTES.VELT_IGNORE,""),document.body.appendChild(o)}catch(r){this.loggingService.catch("Error in FlockOverlayService createFollowOverlay: ",r)}}createLeaderOverlay(e){let r=this.componentFactoryResolver.resolveComponentFactory(N).create(this.injector);r.instance.setType("leading"),r.instance.closeOverlayEvent.pipe(f(1)).subscribe(()=>{this.removeOverlay(),e()}),this.applicationRef.attachView(r.hostView),this.overlayRef=r,this.overlayRef.instance.darkMode=this.darkMode;let i=this.overlayRef.location.nativeElement;i.id="snippyly-follow-overlay",i.setAttribute(m.ATTRIBUTES.VELT_IGNORE,""),document.body.appendChild(i)}changeLeaderName(e){this.overlayRef&&this.overlayRef.instance.setLeaderName(e)}getLeaderName(){return this.overlayRef?this.overlayRef.instance.getLeaderName():null}removeOverlay(){if(this.overlayRef){let e=this.overlayRef.location.nativeElement;this.applicationRef.detachView(this.overlayRef.hostView),this.overlayRef.destroy(),e.shadowRoot&&e.shadowRoot.removeChild(e.shadowRoot.childNodes[0]),e.remove(),this.overlayRef=void 0}}setDarkMode(e){try{this.darkMode=e,this.overlayRef&&(this.overlayRef.instance.darkMode=e)}catch(t){this.loggingService.catch("Error in FlockOverlayService setDarkMode: ",t)}}};n.\u0275fac=function(t){return new(t||n)(a(j),a(X),a(M),a(g))},n.\u0275prov=v({token:n,factory:n.\u0275fac,providedIn:"root"});let l=n;return l})();var Ce=(()=>{let n=class n{constructor(e,t,r,i,o){this.authService=e,this.domService=t,this.loggingService=r,this.flockSessionService=i,this.flockOverlayService=o,this.flockLeader$=new p({userId:"",name:""}),this.flockMode$=new p(!1),this.currentFlockUser=null,this.localScrollData=[],this.domSubscriptions=[],this.followOverlayCreated=!1,this.leaderOverlayCreated=!1,this.windowFocused=!0,this.tabFocused=!0,this.useHistoryAPI=!0,this.disableDefaultNavigation=!1;try{this.flockLeader$.subscribe(s=>{let{userId:c,name:d}=s,O=c;if(this.provisionFollowUser(),O&&this.currentFlockUser&&this.currentFlockUser.snippylyId)if(this.currentFlockUser.sessionId){if(this.currentFlockUser.snippylyId&&this.currentFlockUser.isLeader){this.flockSessionService.swapLeader(this.currentFlockUser.snippylyId,O,d);return}this.removeCurrentUserFromSession()}else this.flockSessionService.provisionFlockSession(O,d,this.currentFlockUser.snippylyId)},s=>{this.loggingService.catch("Error in FlockService flockLeader$ subscription: ",s)}),this.flockSessionService.currentSession$.subscribe(s=>{if(s!==null){if(this.currentFlockUser&&(this.currentFlockUser.sessionId===null||this.currentFlockUser.sessionId===void 0)&&this.currentFlockUser.snippylyId&&(this.currentFlockUser.sessionId=s.id,this.flockSessionService.updateRemoteFlockUser(this.currentFlockUser.snippylyId,this.currentFlockUser)),this.currentFlockUser&&!this.currentFlockUser.isLeader&&!this.followOverlayCreated&&(this.leaderOverlayCreated&&(this.flockOverlayService.removeOverlay(),this.leaderOverlayCreated=!1),this.followOverlayCreated=!0,this.flockOverlayService.createFollowOverlay(s.leaderName,()=>{this.removeCurrentUserFromSession(),this.followOverlayCreated=!1})),this.currentFlockUser&&this.currentFlockUser.isLeader&&!this.leaderOverlayCreated&&(this.followOverlayCreated&&(this.flockOverlayService.removeOverlay(),this.followOverlayCreated=!1),this.leaderOverlayCreated=!0,this.flockOverlayService.createLeaderOverlay(()=>{this.removeCurrentUserFromSession(),this.leaderOverlayCreated=!1})),this.currentFlockUser&&!this.currentFlockUser.isLeader&&s.actionStack){let c=s.actionStack[0];c&&this.currentFlockUser.lastProcessedActionTimestamp!==c.timestamp&&this.processAction(c)}if(this.currentFlockUser&&!this.currentFlockUser.isLeader&&this.followOverlayCreated&&this.flockOverlayService.getLeaderName()!==null&&s.leaderName!==this.flockOverlayService.getLeaderName()&&this.flockOverlayService.changeLeaderName(s.leaderName),this.currentFlockUser&&this.currentFlockUser.isLeader){let c=k();if(s.pageInfo){if(c&&c.url!==s.pageInfo.url){let d=new u;d.type=h.NAVIGATE,this.flockSessionService.addActionToStack(s.id,d)}}else{this.flockSessionService.updateSession(s.id,{pageInfo:c});let d=new u;d.type=h.NAVIGATE,this.flockSessionService.addActionToStack(s.id,d)}}}else this.currentFlockUser&&this.leaderOverlayCreated&&(this.flockOverlayService.removeOverlay(),this.leaderOverlayCreated=!1),this.currentFlockUser&&this.followOverlayCreated&&(this.flockOverlayService.removeOverlay(),this.followOverlayCreated=!1)}),this.flockSessionService.currentUser$.subscribe(s=>{if(s!==null&&(this.currentFlockUser&&this.currentFlockUser.isLeader!==s.isLeader&&(this.domSubscriptions.forEach(c=>c.unsubscribe()),this.domSubscriptions=[]),this.currentFlockUser=s,s.sessionId&&this.domSubscriptions.length===0))if(s.isLeader){if(!this.tabFocused||!this.windowFocused)return;this.subscribeToLeaderDOMEvents()}else this.subscribeToFollowerDOMEvents()}),D([this.authService.getUser$(),this.getFlockMode$()]).subscribe(([s,c])=>{s&&s.userSnippylyId&&c?this.flockSessionService.startCurrentFlockUserSubscription(s):this.flockSessionService.stopCurrentFlockUserSubscription()})}catch(s){this.loggingService.catch("Error in FlockService constructor: ",s)}}provisionFollowUser(){try{if(this.currentFlockUser===null){let e=this.authService.getUser();e&&e.userSnippylyId&&(this.currentFlockUser=new E,this.currentFlockUser.snippylyId=e.userSnippylyId)}}catch(e){this.loggingService.catch("Error in FlockService provisionFollowUser: ",e)}}startFollowingUser(e,t){try{if(this.provisionFollowUser(),e&&this.currentFlockUser&&this.currentFlockUser.snippylyId){if(this.currentFlockUser.sessionId){if(this.currentFlockUser.snippylyId&&this.currentFlockUser.isLeader){this.flockSessionService.swapLeader(this.currentFlockUser.snippylyId,e,t);return}this.removeCurrentUserFromSession()}this.flockSessionService.provisionFlockSession(e,t,this.currentFlockUser.snippylyId)}}catch(r){this.loggingService.catch("Error in FlockService startFollowingUser: ",r)}}stopFollowingUser(){try{this.removeCurrentUserFromSession()}catch(e){this.loggingService.catch("Error in FlockService stopFollowingUser: ",e)}}subscribeToUrlChanges(){try{if(this.useHistoryAPI){let e=window.history.pushState,t=window.history.replaceState;window.history.pushState=(...r)=>{e.apply(window.history,r),this.onUrlChange()},window.history.replaceState=(...r)=>{t.apply(window.history,r),this.onUrlChange()},this.domSubscriptions.push({unsubscribe:()=>{window.history.pushState=e,window.history.replaceState=t}}),this.domSubscriptions.push(y(window,"popstate").subscribe(()=>{this.onUrlChange()}))}}catch(e){this.loggingService.catch("Error in FlockService subscribeToUrlChanges: ",e)}}onUrlChange(){try{if(this.currentFlockUser&&this.currentFlockUser.sessionId&&this.currentFlockUser.isLeader){let e=new u;e.type=h.NAVIGATE,this.flockSessionService.addActionToStack(this.currentFlockUser.sessionId,e)}}catch(e){this.loggingService.catch("Error in FlockService onUrlChange: ",e)}}processAction(e){try{switch(e.type){case h.CLICK:this.clickUserElement(e.data);break;case h.HOVER:this.scrollToHoveredElement(e.data);break;case h.SCROLL:this.scrollToFollowedUser(e.data);break;case h.NAVIGATE:this.checkMatchingUrl(e.pageInfo);break}this.currentFlockUser&&this.currentFlockUser.snippylyId&&this.flockSessionService.updateRemoteFlockUser(this.currentFlockUser.snippylyId,{lastProcessedActionTimestamp:e.timestamp})}catch(t){this.loggingService.catch("Error in FlockService processAction: ",t)}}subscribeToLeaderDOMEvents(){try{this.domSubscriptions.length>0&&(this.domSubscriptions.forEach(e=>e.unsubscribe()),this.domSubscriptions=[]),this.domSubscriptions.push(y(window,"mouseover").pipe(C(500)).subscribe(e=>{let t=e?.target;if(t){let r=window.getComputedStyle(t);if(r.position==="fixed"||r.position==="sticky"||t.hasAttribute(m.ATTRIBUTES.VELT_IGNORE))return;t=L(t,{x:e.clientX,y:e.clientY}),this.updateHoveredElement(t)}})),this.domSubscriptions.push(this.domService.onWindowClick$().subscribe(e=>{let t=e?.target;if(t){if(t.hasAttribute(m.ATTRIBUTES.VELT_IGNORE))return;this.updateClickedElement(t)}})),this.subscribeToUrlChanges(),this.subscribeToScrollables()}catch(e){this.loggingService.catch("Error in FlockService subscribeToLeaderDOMEvents: ",e)}}subscribeToFollowerDOMEvents(){}updateClickedElement(e){try{if(this.currentFlockUser&&this.currentFlockUser.sessionId){let t=this.domService.getXPath(e),r=T(e),i=this.domService.getXPath(r),o={id:Math.random().toString(36).substring(2),xpath:t,parentXpath:i},s=new u;s.type=h.CLICK,s.data=o,this.flockSessionService.addActionToStack(this.currentFlockUser.sessionId,s)}}catch(t){this.loggingService.catch("Error in FlockService updateClickedElement: ",t)}}updateHoveredElement(e){try{if(this.currentFlockUser&&this.currentFlockUser.sessionId){let t=this.domService.getXPath(e),r=T(e),i=this.domService.getXPath(r),o={id:Math.random().toString(36).substring(2),xpath:t,parentXpath:i},s=new u;s.type=h.HOVER,s.data=o,this.flockSessionService.addActionToStack(this.currentFlockUser.sessionId,s)}}catch(t){this.loggingService.catch("Error in FlockService updateHoveredElement: ",t)}}subscribeToScrollables(){try{let e=V();e.push(document),e?.forEach(t=>{this.domSubscriptions.push(y(t,"scroll").pipe(C(100)).subscribe(r=>{this.currentFlockUser&&this.currentFlockUser.sessionId&&this.currentFlockUser.isLeader&&this.updateScrollPositionOfElement(t)}))})}catch(e){this.loggingService.catch("Error in FlockService getScrollableElements: ",e)}}updateScrollPositionOfElement(e){try{if(this.currentFlockUser&&this.currentFlockUser.sessionId){let t=new U("","");if(e===document){let o=z();if(o){let s=L(o);s&&(t.targetXpath=this.domService.getXPath(s))}t.xpath=""}else{let o=H(e);t.targetXpath=this.domService.getXPath(o),t.xpath=this.domService.getXPath(e)}let r=!1,i=!1;if(this.localScrollData.forEach((o,s)=>{o.xpath===o.xpath&&(t.targetXpath!==o.targetXpath&&(r=!0),this.localScrollData[s]=Object.assign(o,t),i=!0)}),i||this.localScrollData.push(t),r||!i){let o=new u;o.type=h.SCROLL,o.data=t,this.flockSessionService.addActionToStack(this.currentFlockUser.sessionId,o)}}}catch(t){this.loggingService.catch("Error in FlockService calculateScrollPositionOfAnElement: ",t)}}enableFlockMode(e){try{if(this.flockMode$.next(!0),e){let{useHistoryAPI:t,onNavigate:r,disableDefaultNavigation:i,darkMode:o}=e;t!==void 0&&(this.useHistoryAPI=t),r!==void 0&&typeof r=="function"&&(this.onNavigate=r),i!==void 0&&(this.disableDefaultNavigation=i),this.flockOverlayService.setDarkMode(o)}}catch(t){this.loggingService.catch("Error in FlockService enableFlockMode: ",t)}}disableFlockMode(){try{this.flockMode$.next(!1),this.onNavigateEmitter=void 0,this.useHistoryAPI=!0,this.onNavigate=void 0}catch(e){this.loggingService.catch("Error in FlockService disableFlockMode: ",e)}}setDisableFlockNavigation(e){try{this.disableDefaultNavigation=e}catch(t){this.loggingService.catch("Error in FlockService setDisableFlockNavigation: ",t)}}getFlockMode$(){return this.flockMode$.asObservable()}getFlockMode(){return this.flockMode$.value}setNavigateEmitter(e){try{this.onNavigateEmitter=e}catch(t){this.loggingService.catch("Error in FlockService setNavigateEmitter: ",t)}}setTabFocused(e){try{if(this.tabFocused=e,!this.currentFlockUser)return;this.currentFlockUser.isLeader&&this.currentFlockUser.sessionId&&(this.tabFocused&&this.domSubscriptions.length===0?this.subscribeToLeaderDOMEvents():!this.tabFocused&&this.domSubscriptions.length>0&&(this.domSubscriptions.forEach(r=>{r.unsubscribe()}),this.domSubscriptions=[]))}catch(t){this.loggingService.catch("Error in FlockService setTabFocused: ",t)}}setWindowFocused(e){try{if(this.windowFocused=e,!this.currentFlockUser)return;this.currentFlockUser.isLeader&&this.currentFlockUser.sessionId&&(this.windowFocused&&this.domSubscriptions.length===0?this.subscribeToLeaderDOMEvents():!this.windowFocused&&this.domSubscriptions.length>0&&(this.domSubscriptions.forEach(r=>{r.unsubscribe()}),this.domSubscriptions=[]))}catch(t){this.loggingService.catch("Error in FlockService setWindowFocused: ",t)}}setFlockLeader(e,t){try{this.flockLeader$.next({userId:e,name:t})}catch(r){this.loggingService.catch("Error in FlockService setFlockLeader: ",r)}}isInSession(){try{return!!(this.currentFlockUser&&this.currentFlockUser.sessionId)}catch(e){this.loggingService.catch("Error in FlockService isFollowing: ",e)}return!1}removeCurrentUserFromSession(){try{this.domSubscriptions.forEach(e=>e.unsubscribe()),this.domSubscriptions=[],this.currentFlockUser&&(this.currentFlockUser.isLeader?this.currentFlockUser.sessionId&&this.flockSessionService.deleteSession(this.currentFlockUser.sessionId):this.currentFlockUser.snippylyId&&this.flockSessionService.removeFollowerFromCurrentSession(this.currentFlockUser.snippylyId))}catch(e){this.loggingService.catch("Error in FlockService removeCurrentUserFromSession: ",e)}}checkMatchingUrl(e){try{let r=k()?.url,i=e.url;if(r!==i&&i!==void 0){let{url:o,path:s,baseUrl:c}=e;if(this.onNavigate!==void 0&&typeof this.onNavigate=="function"){this.onNavigate({url:o,path:s,baseUrl:c});return}if(this.onNavigateEmitter&&this.onNavigateEmitter.emit({url:o,path:s,baseUrl:c}),this.disableDefaultNavigation)return;window.location.href=i}}catch(t){this.loggingService.catch("Error in FlockService checkMatchingUrl: ",t)}}scrollToFollowedUser(e){try{if(e.xpath===""){let t=this.domService.getElementFromXPath(e.targetXpath);t&&F(t)}else{let t=this.domService.getElementFromXPath(e.xpath),r=this.domService.getElementFromXPath(e.targetXpath);t&&r&&(F(t),R(t,r))}}catch(t){this.loggingService.catch("Error in FlockService scrollToFollowedUser: ",t)}}clickUserElement(e){try{let t=this.domService.getElementFromXPath(e.xpath);t&&this.lastClickedElement?.id!==e.id&&(t?.click(),this.lastClickedElement=e)}catch(t){this.loggingService.catch("Error in FlockService clickUserElement: ",t)}}scrollToHoveredElement(e){try{let t=this.domService.getElementFromXPath(e.xpath);if(t&&e.parentXpath)if(e.parentXpath==="/html")F(t);else{let r=this.domService.getElementFromXPath(e.parentXpath);r&&R(r,t,!0)}}catch(t){this.loggingService.catch("Error in FlockService clickUserElement: ",t)}}};n.\u0275fac=function(t){return new(t||n)(a(b),a(J),a(g),a(Q),a(Z))},n.\u0275prov=v({token:n,factory:n.\u0275fac,providedIn:"root"});let l=n;return l})();export{Ce as a};
@@ -0,0 +1 @@
1
+ import{Fa as F}from"./chunk-IUD3QEEM.js";import{v as C,w}from"./chunk-EPQLN2EE.js";import{E as h,G as d,Gj as U,He as $,K as v,M as l,V as n,Yf as g,Yi as E,Zi as R,_h as I,_i as y,ba as A,ea as s,l as p,nf as M,pi as D,r as u,rj as k,v as c,we as a,xe as m}from"./chunk-TAGMM5ED.js";var Z=(()=>{let o=class o{constructor(e,t,r,b,f,W,T,j){this.analyticsService=e,this.authService=t,this.contactService=r,this.databaseService=b,this.docService=f,this.configService=W,this.loggingService=T,this.commonDbService=j,this.documentIAM$=new p(null),this.workspaceIAM$=new p(null),this.roles$=new p([]),this.getDocumentIamSubscription=null,this.getOrganizationIamSubscription=null,this.getWorkspaceIamSubscription=null;try{this.authService.setIamService(this),this.databaseService.getDb().pipe(h(i=>!!i),v(1)).subscribe(i=>{i&&(this.getUser(),this.getDocumentPaths())},i=>{this.loggingService.catch("Error in CommentService getDb subscription: ",i)}),this.getRole$().pipe(v(1)).subscribe(i=>{this.authService?.getUser()&&!i&&this.analyticsService.trackEvent(D.Events.Iam.USER_ACCESS_DENIED)}),this.documentIAM$.subscribe(i=>{i?.accessType&&this.contactService.setDocumentAccessType(i.accessType)})}catch(i){this.loggingService.catch("Error in IamService constructor: ",i)}}clearCache(){this.loggingService.log("%c[WB] Calling FUNCTION: clearCache in IamService","color: green;");try{this.documentIAM$.next(null),this.workspaceIAM$.next(null),this.roles$.next([]),this.documentPaths=null}catch(e){this.loggingService.catch("Error in IamService clearCache: ",e)}}getUser(){try{this.authService.getUser$().pipe(h(e=>!!e)).subscribe(e=>{this.user=e,this.user?this.getDocumentIam():(this.getDocumentIamSubscription?.unsubscribe(),this.getOrganizationIamSubscription?.unsubscribe(),this.getWorkspaceIamSubscription?.unsubscribe())},e=>{this.loggingService.catch("Error in IamService getUser$ subscription: ",e)})}catch(e){this.loggingService.catch("Error in IamService getUser: ",e)}}getDocumentPaths(){try{this.docService.getDocumentPaths$().pipe(h(e=>!!e)).subscribe(e=>{this.documentPaths=e,this.getDocumentIam(),this.getWorkspaceIam()},e=>{this.loggingService.catch("Error in IamService getDocumentPaths$ subscription: ",e)})}catch(e){this.loggingService.catch("Error in IamService getDocumentPaths: ",e)}}getDocumentIam(){try{this.getDocumentIamSubscription&&(this.getDocumentIamSubscription.unsubscribe(),this.getDocumentIamSubscription=null),this.user?this.getDocumentIamSubscription=this.docService.getDocumentIam$().subscribe(e=>{let t=e||new M;this.documentIAM$.next(t)},e=>{this.loggingService.catch("Error in IamService getDocumentIam$ subscription: ",e)}):this.documentIAM$.next(null)}catch(e){this.loggingService.catch("Error in IamService getDocumentIam: ",e)}}getWorkspaceIam(){try{this.getWorkspaceIamSubscription||(this.getWorkspaceIamSubscription=this.commonDbService.dbListener({feature:"workspaceIam",properties:{skipFirestore:!0}}).pipe(d(e=>u(null))).subscribe(e=>{this.workspaceIAM$.next(e?.data),this.roles$.next(e?.data?.roles||[])}))}catch(e){this.loggingService.catch("Error in IamService getWorkspaceIam: ",e)}}isUserAllowed$(){return this.getRole$().pipe(c(e=>!!e),l())}getDocumentIAM$(){return this.documentIAM$.asObservable()}getRoles$(){return this.roles$.asObservable().pipe(c(e=>e?.length?e:$.WorkspaceRoles))}getFeaturesAccessLevel$(){return this.documentIAM$.asObservable().pipe(c(e=>e?.features),n(e=>this.getRole$().pipe(c(t=>(t===a.ADMIN&&(e=e&&JSON.parse(JSON.stringify(e||{})),e?.all?.disabled&&(e.all.disabled=!1)),e)))))}hasRole(e){try{return e===this.getRole()}catch(t){return this.loggingService.catch("Error in IamService hasRole: ",t),!1}}hasRoleAny(e=[]){try{return e?.includes(this.getRole()||"")}catch(t){return this.loggingService.catch("Error in IamService hasRoleAny: ",t),!1}}hasRole$(e){try{return this.authService.getUser$().pipe(n(()=>this.documentIAM$.pipe(h(t=>!!t),n(()=>this.workspaceIAM$.pipe(c(()=>e===this.getRole()))))))}catch(t){return this.loggingService.catch("Error in IamService hasRole$: ",t),u(!1)}}getRole$(){try{return this.authService.getUser$().pipe(n(()=>this.configService.getSF$()),n(()=>this.configService.getSF()?this.contactService.isUserGlobalContact$():u(null)),n(()=>this.configService.getSF()?this.documentIAM$.pipe(h(e=>!!e),l(I)):u(null)),n(()=>this.workspaceIAM$.pipe(l(I))),c(()=>this.getRole()))}catch(e){return this.loggingService.catch("Error in IamService getRole$: ",e),u(null)}}getRole(){try{let e=this.configService.getSF();if(this.user?.isAdmin)return a.ADMIN;return a.COMMENTER;if(this.user)switch((this.documentIAM$.value?this.documentIAM$.value?.features?.all?.restricted:!1)?m.RESTRICTED:this.documentIAM$.value?this.documentIAM$.value?.documentAccessType||m.PUBLIC:null){case m.PUBLIC:r=this.getUserFromDocumentIAM(this.user?.email,this.user?.userId),r||(r=this.getUserFromWorkspaceIAM(this.user?.email,this.user?.userId)),t=r?.role?.name||a.COMMENTER;break;case m.RESTRICTED:r=this.getUserFromDocumentIAM(this.user?.email,this.user?.userId),r||(r=this.getUserFromWorkspaceIAM(this.user?.email,this.user?.userId)),t=r?.role?.name||null;break;default:break}}catch(e){this.loggingService.catch("Error in IamService getRole: ",e)}return null}isUserAdmin$(){return this.getRole$().pipe(c(e=>e===a.ADMIN),l())}isUserAdmin(){try{return this.getRole()===a.ADMIN}catch(e){return this.loggingService.catch("Error in IamService isUserAdmin: ",e),!1}}getUserFromDocumentIAM(e,t){try{if(e||t){let r;return e&&(r=this.documentIAM$.value?.users?.[g(e)]),!r&&t&&(r=this.documentIAM$.value?.users?.[g(t)]),r}else return}catch(r){this.loggingService.catch("Error in IamService getUserFromDocumentIAM: ",r)}}getUserFromWorkspaceIAM(e,t){try{if(e||t){let r;return e&&(r=this.workspaceIAM$.value?.users?.[g(e)]),!r&&t&&(r=this.workspaceIAM$.value?.users?.[g(t)]),r}else return}catch(r){this.loggingService.catch("Error in IamService getUserFromWorkspaceIAM: ",r)}}};o.\u0275fac=function(t){return new(t||o)(s(E),s(U),s(F),s(k),s(w),s(y),s(R),s(C))},o.\u0275prov=A({token:o,factory:o.\u0275fac,providedIn:"root"});let S=o;return S})();export{Z as a};
@@ -1 +1 @@
1
- import{a as m}from"./chunk-SC3WVEMZ.js";import{Ra as c,Za as f}from"./chunk-RV7ZJ7J2.js";var l=(()=>{let t=class t{constructor(r){this.translateService=r}transform(r,...i){try{let n=(new Date().getTime()-new Date(r).getTime())/1e3;if(n<1)return this.translateService.translate("now");let s={y:31536e3,mo:2592e3,w:604800,d:86400,h:3600,m:60,s:1};for(let a in s){let o=Math.floor(n/s[a]);if(o>0)return`${o}${this.translateService.translate(a)}`}return r}catch{return r}}};t.\u0275fac=function(i){return new(i||t)(c(m,16))},t.\u0275pipe=f({name:"timeAgo",type:t,pure:!0});let e=t;return e})();export{l as a};
1
+ import{a as m}from"./chunk-MVVXZ2D6.js";import{Ra as c,Za as f}from"./chunk-TAGMM5ED.js";var l=(()=>{let t=class t{constructor(r){this.translateService=r}transform(r,...i){try{let n=(new Date().getTime()-new Date(r).getTime())/1e3;if(n<1)return this.translateService.translate("now");let s={y:31536e3,mo:2592e3,w:604800,d:86400,h:3600,m:60,s:1};for(let a in s){let o=Math.floor(n/s[a]);if(o>0)return`${o}${this.translateService.translate(a)}`}return r}catch{return r}}};t.\u0275fac=function(i){return new(i||t)(c(m,16))},t.\u0275pipe=f({name:"timeAgo",type:t,pure:!0});let e=t;return e})();export{l as a};
@@ -0,0 +1 @@
1
+ import{a as ai}from"./chunk-B3U3OLF6.js";import{a as si}from"./chunk-5ZUX3AU3.js";import{a as ti,f as ii,i as ei,j as rt,k as nt,m as st,r as pt,t as at,u as oi,v as ri,w as ni}from"./chunk-EPQLN2EE.js";import{$f as dt,Ag as ut,Aj as Xt,Dj as qt,E as z,Fi as jt,Fj as Zt,G as H,Gd as Dt,Gg as q,Gj as ot,He as L,Hi as _t,K as W,M as k,O as lt,Q as bt,Qd as Ct,Qf as Ut,U as Ot,Uf as Et,V as b,Vf as $t,Xf as ft,Xi as it,Y as J,Yf as B,Yi as Ht,Zf as gt,Zi as et,_h as zt,_i as kt,a as y,b as P,ba as K,cj as Vt,ea as N,ee as At,fa as yt,g as U,hi as ht,i as ct,ji as Z,jj as Yt,kj as Gt,l as O,lg as wt,m as Nt,mg as Pt,mj as Wt,oj as mt,p as _,pi as V,q as G,qg as Rt,qi as tt,r as A,re as Tt,rg as Ft,rj as Jt,si as xt,tf as Q,tj as Kt,uf as X,ug as Mt,ui as Lt,uj as Qt,v as I,vj as St,w as Y,x as It,zg as Bt}from"./chunk-TAGMM5ED.js";var ci=(()=>{let m=class m{constructor(t,i,e,o,r,a,n){this.commentUtilsService=t,this.loggingService=i,this.usersService=e,this.authService=o,this.commentAnnotationsResolverService=r,this.notificationResolverService=a,this.serviceBook=n,this.serviceBook.set(Lt,this)}getUserIdsToResolveFromNotifications(t){try{let i=new Set;for(let e of t){let{notification:o}=e;switch(o?.actionUser?.userId&&i.add(o?.actionUser?.userId),o?.displayHeadlineMessageTemplateData?.actionUser?.userId&&i.add(o?.displayHeadlineMessageTemplateData?.actionUser?.userId),o?.displayHeadlineMessageTemplateData?.recipientUser?.userId&&i.add(o?.displayHeadlineMessageTemplateData?.recipientUser?.userId),o?.notificationSource){case"comment":if(o?.notificationSourceData){let r=this.commentUtilsService.getUserIdsToResolveFromComments([o?.notificationSourceData]);for(let a of r)i.add(a)}break}}return Array.from(i)}catch(i){return this.loggingService.catch("Error in ReactionUtilsService getUserIdsToResolveFromRecorders:",i),[]}}mergeStrippedDataWithNotification(t){try{if(this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: mergeStrippedDataWithNotification","color: green;"),!this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())return t;let i=this.commentAnnotationsResolverService.getAnnotationById(t?.notification?.targetAnnotationId),e=t?.raw?.targetAnnotationData?.commentId,o=i?.comments?.[e]?.commentText,r=i?.comments?.[e]?.commentHtml;return o&&r&&t?.raw?.notificationSource==="comment"&&(t.notification.displayBodyMessageTemplate=o,t.raw.targetAnnotationData.commentText=o,t.raw.targetAnnotationData.commentHtml=r),t}catch(i){return this.loggingService.catch("Error in NotificationUtilsService mergeStrippedDataWithNotification:",i),t}}mergeLocationWithNotification(t,i){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: mergeLocationWithNotification","color: green;");let e=t?.notification?.notificationSourceData?.location?.id,o=t?.notification?.notificationSourceData?.metadata?.documentId;if(!e||!o)return t;let r=i?.[o]?.[e];return r&&(t.notification.notificationSourceData.location=r?.location,t?.raw?.annotationData?.location&&(t.raw.annotationData.location=r?.location)),t}catch(e){return this.loggingService.catch("Error in NotificationUtilsService mergeLocationWithNotification:",e),t}}mergeNotificationWithUser(t){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: mergeNotificationWithUser","color: green;");let{notification:i}=t;if(i?.actionUser?.userId){let e=this.usersService.getUserById(i?.actionUser?.userId);e&&(i.actionUser=e)}if(i?.displayHeadlineMessageTemplateData?.actionUser?.userId){let e=this.usersService.getUserById(i?.displayHeadlineMessageTemplateData?.actionUser?.userId);e&&(i.displayHeadlineMessageTemplateData.actionUser=e)}if(i?.displayHeadlineMessageTemplateData?.recipientUser?.userId){let e=this.usersService.getUserById(i?.displayHeadlineMessageTemplateData?.recipientUser?.userId);e&&(i.displayHeadlineMessageTemplateData.recipientUser=e)}return i?.notificationSource==="comment"&&i?.notificationSourceData&&this.commentUtilsService.mergeCommentWithUser(i?.notificationSourceData),t}catch(i){return this.loggingService.catch("Error in NotificationUtilsService mergeNotificationWithUser:",i),t}}formatNotification(t,i){try{switch(typeof t=="object"&&(t=JSON.parse(JSON.stringify(t))),this.usersService.userDataProviderAvailable()&&t?.actionUser&&(t.actionUser={userId:t.actionUser.userId}),t.notificationSource){case"comment":this.commentUtilsService.formatCommentData(t.annotationData),this.commentUtilsService.formatCommentThreadData(t.targetAnnotationData);break;case"recorder":this.serviceBook.get(jt)?.formatRecorderData(t.annotationData,i);break}return t}catch(e){return this.loggingService.catch("Error in NotificationUtilsService formatNotification: ",e),t}}getTargetAnnotationIdsFromNotifications(t){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: getTargetAnnotationIdsFromNotifications","color: green;");let i=[];return Object.values(t).forEach(e=>{e?.notification?.targetAnnotationId&&e?.raw?.notificationSource==="comment"&&i.push(e.notification.targetAnnotationId)}),i}catch(i){return this.loggingService.catch("Error in NotificationUtilsService getTargetAnnotationIdsFromNotifications:",i),[]}}handleNotificationEncryption(i){return U(this,arguments,function*({data:t}){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: handleNotificationEncryption","color: green;");let e="notificationwithdocumentidstoencryptanddecryptonsdk"+(this.authService.getUser()?.userId??"");return yield Bt(t,e)}catch(e){return this.loggingService.catch("Error in NotificationUtilsService handleNotificationEncryption:",e),t}})}getCustomNotificationIdsToResolve(t){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: getCustomNotificationIdsToResolve","color: green;");let i=new Set,e=Array.isArray(t)?t:Object.values(t||{});for(let o of e)if(o?.raw?.notificationSource==="custom"){let r=o?.notification?.id||o?.notificationId;r&&i.add(r)}return Array.from(i)}catch(i){return this.loggingService.catch("Error in NotificationUtilsService getCustomNotificationIdsToResolve:",i),[]}}mergeResolvedNotificationData(t){try{if(this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: mergeResolvedNotificationData","color: green;"),!this.notificationResolverService.notificationDataProviderAvailable()||t?.raw?.notificationSource!=="custom")return t;let i=t?.notification?.id||t?.notificationId;if(!i)return t;let e=this.notificationResolverService.getNotificationById(i);if(!e)return t;let o=["displayHeadlineMessageTemplate","displayHeadlineMessageTemplateData","displayBodyMessage","displayBodyMessageTemplate","displayBodyMessageTemplateData","notificationSourceData"];for(let r of o)e[r]!==void 0&&(t.notification&&(t.notification[r]=e[r]),t.raw&&(t.raw[r]=e[r]));return Object.keys(e).forEach(r=>{!o.includes(r)&&r!=="notificationId"&&(t.notification&&(t.notification[r]=e[r]),t.raw&&(t.raw[r]=e[r]))}),t.notification&&(t.notification.isNotificationResolverUsed=!0),t}catch(i){return this.loggingService.catch("Error in NotificationUtilsService mergeResolvedNotificationData:",i),t}}};m.\u0275fac=function(i){return new(i||m)(N(st),N(et),N(rt),N(ot),N(nt),N(at),N(it))},m.\u0275prov=K({token:m,factory:m.\u0275fac,providedIn:"root"});let v=m;return v})();function vt(v,m=new Date){let w=v>0?v:15,t=new Date(m.getTime());return t.setDate(t.getDate()-w),t.getTime()}function li(v){let m={startAtTimestamp:v.startAtTimestamp};return v.currentDocumentOnly&&v.currentDocumentId&&(m.documentId=v.currentDocumentId),v.currentDocumentOnly||(m.limit=v.limit),m}function fi(v,m){let w=[];if(!v||typeof v!="object")return{};for(let e of Object.keys(v)){let o=v[e];if(!o||typeof o!="object")continue;let r=o.timestamp;typeof r!="number"||Number.isNaN(r)||!(r>=m.startAtTimestamp)||m.documentId!==void 0&&o.metadata?.documentId!==m.documentId||w.push({id:e,timestamp:r,row:v[e]})}let t=w;m.limit!==void 0&&(t=[...w].sort((e,o)=>o.timestamp-e.timestamp||(e.id<o.id?1:e.id>o.id?-1:0)).slice(0,Math.max(0,m.limit)));let i={};for(let e of t)i[e.id]=e.row;return i}var Oi=2e4,yi={getNotificationsForDocuments:"the notification list",getDocumentMetadataFromIds:"document metadata by id (used by the notification permission-provider filter)",getCrossOrgUserNotifications:"cross-org notifications"};function Di(v){try{let m=v?.metadata?.documentId;if(m==null||m==="")return;let w=e=>(typeof e=="string"&&e!==""||typeof e=="number"&&Number.isFinite(e))&&gt(String(e))===String(m),t=v?.metadata?.clientDocumentId;if(w(t))return String(t);let i=v?.raw?.annotationData?.metadata?.clientDocumentId;return w(i)?String(i):void 0}catch{return}}function gi(v){if(typeof v!="number"||!Number.isFinite(v))return 25;let t=Math.floor(v);return t<1?25:Math.min(200,t)}function Ci(v){return new ct(m=>{let w=!0,t=v.subscribe({next:i=>{if(w){let e=i?.data??i;if(!!e&&typeof e=="object"&&Object.keys(e).length===0&&!i?.operation)return}m.next(i)},error:i=>m.error(i),complete:()=>m.complete()});return w=!1,()=>t.unsubscribe()})}function di(v,m){let w=t=>!!t&&typeof t=="object"&&Object.keys(t).length>0;return w(v)?v:w(m)?m:{}}var ce=(()=>{let m=class m{constructor(t,i,e,o,r,a,n,c,s,l,f,d,g,u,S,D,E,F,M,x,j,h){this.afAuth=t,this.analyticsService=i,this.authService=e,this.configService=o,this.commonDbService=r,this.commonDbUtilsService=a,this.commentUtilsService=n,this.commentAnnotationsResolverService=c,this.notificationResolverService=s,this.databaseService=l,this.docService=f,this.domService=d,this.iamService=g,this.loggingService=u,this.notificationUtilsService=S,this.usersService=D,this.functions=E,this.userPermissionService=F,this.coreActionsService=M,this.serviceBook=x,this.realtimeAdapter=j,this.adapterSelectorService=h,this.endpointsService=yt(Vt),this.db=null,this.notificationsDb=null,this.documentPaths=null,this.notifications$=new O([]),this.rawNotificationsByIdMap$=new O(new Map),this.processedNotifications$=new O([]),this.userNotificationsFromServer$=new O(null),this.readNotificationsOnForYouTab$=new O(!1),this.currentDocumentOnly$=new O(!1),this.notificationViews$=new O({}),this.notificationsByIdMap$=new O(new Map),this.historyPanelVisible$=new O(!1),this.notificationsForYou$=new O(null),this.notificationsByDocumentIdMap$=new O(null),this.notificationsByDocumentIdSubscription={},this.notificationsHubDisabled=!1,this.reportedDroppedHubPushes=new Set,this.allowedDocumentMetadataMap$=new O(null),this.portableListBoundKey=null,this.portableNotificationListLive=!1,this.reportedUnservedPortableNotificationOps=new Set,this.maxNotificationDays$=new O(15),this.tabConfig$=new O({people:{enable:!1}}),this.settingsConfig$=new O(null),this.setSettingsConfigByOrganization$=new O(!1),this.muteAllNotifications$=new O(!1),this.enableSettings$=new O(!1),this.selfNotifications$=new O(!1),this.userScopedNotifications$=new O({enabled:!1,limit:25}),this.settingsInitialConfig$=new O([{name:"Inbox",id:"inbox",default:"ALL",enable:!0,values:[{name:"All",id:"ALL"},{name:"Only Involved",id:"MINE"},{name:"None",id:"NONE"}]},{name:"Email",id:"email",default:"MINE",enable:!0,values:[{name:"All",id:"ALL"},{name:"Only Involved",id:"MINE"},{name:"None",id:"NONE"}]}]),this.settingsConfigGeneration=0,this.notificationsPanelVisible$=new O(!1),this.crossOrganizationConfig$=new O({enabled:!1}),this.crossOrgNotifications$=new O([]),this.crossOrgIndexOrgs=[],this.crossOrgIndexTimestamps={},this.crossOrgSeenTimestamps={},this.crossOrgInitialFetchDone=!1,this.crossOrgFetchPending=!1,this.lastCrossOrgFetchTime=0,this.CROSS_ORG_FETCH_WINDOW_MS=500,this.CROSS_ORG_PAGE_SIZE=50,this.crossOrgGeneration=0,this.crossOrgResolveRoundInFlight=!1,this.crossOrgStragglerRetryUsed=!1,this.CROSS_ORG_STRAGGLER_RETRY_MS=3e4;try{this.serviceBook.set(xt,this),this.serviceBook.observe(_t).subscribe(p=>{this.commentService=p??void 0}),this.subscribeNotificationsData().subscribe(),this.commentUtilsService.setNotificationService(this),this.databaseService.getDb().pipe(z(p=>!!p),W(1)).subscribe(p=>{if(p){this.db=p;try{let C=this.configService.getProxyConfig(),T=this.endpointsService.getNotificationsDbUrl();Et(T)?(this.notificationsDb=null,this.notificationsHubDisabled=!0):(C?.v1DbHost&&T&&(T=$t(T,C.v1DbHost)),this.notificationsDb=this.realtimeAdapter.getDatabaseInstance(T),C?.v1DbHost&&T&&this.databaseService.lockDatabaseHost(this.notificationsDb))}catch(C){this.loggingService.catch("Error initializing notifications DB, using default: ",C),this.notificationsDb=p}this.getDocumentIds(),this.subscribeGetNotificationsForYou()}},p=>{this.loggingService.catch("Error in NotificationService getDb subscription: ",p)}),this.authService.getUser$().subscribe(p=>{p?(this.subscribeGetNotificationsForYou(),this.getDocumentIds(),this.subscribeToUserSettings()):(Object.keys(this.notificationsByDocumentIdSubscription).forEach(C=>{this.notificationsByDocumentIdSubscription[C]?.unsubscribe()}),this.notificationForYouSubscription?.unsubscribe(),this.documentIdsSubscription?.unsubscribe(),this.resetCacheData())}),St(()=>{try{if(this.adapterSelectorService?.isPortableBackendActive()){if(this.portableNotificationListLive)return;this.getDocumentIds()}}catch(p){this.loggingService.catch("Error re-evaluating portable notification list on chunk registration: ",p)}}),this.docService.getLocationMetadata$().subscribe(p=>{if(p){let C=this.notificationsByDocumentIdMap$.getValue()?JSON.parse(JSON.stringify(this.notificationsByDocumentIdMap$.getValue())):null;Object.keys(p||{}).forEach(T=>{let $=C?.[T]?.notifications;$?.length&&$.forEach(R=>{this.notificationUtilsService.mergeLocationWithNotification({notification:R},p)?.notification})}),this.notificationsByDocumentIdMap$.next(C)}})}catch(p){this.loggingService.catch("Error in NotificationService constructor: ",p)}}setDBConfigDataToInitialConfig(t){try{let i=JSON.parse(JSON.stringify(this.settingsConfig$.getValue()??{}));Object.entries(t||{}).forEach(([e,o])=>{i[e]=o}),this.settingsConfig$.next(i)}catch(i){this.loggingService.catch("Error in NotificationService setDBConfigDataToInitialConfig: ",i)}}getInitialConfigFromDB(t){return U(this,null,function*(){try{this.loggingService.log("%c[WB] Calling NotificationService FUNCTION: getInitialConfigFromDB","color: green;");let i=++this.settingsConfigGeneration,e=B(this.authService.getUser()?.userId??""),o=yield this.commonDbService.getData({feature:"userConfig",properties:{useCollectionGroup:!1,isCollection:!1,documentId:this.getSettingsConfigByOrganization()?void 0:t?.documentId,organizationId:t?.organizationId??this.docService.getOrganizationConfig()?.organizationId,userId:e}});if(i!==this.settingsConfigGeneration)return;if(o?.notificationsConfig)this.setDBConfigDataToInitialConfig(o?.notificationsConfig);else{this.setSettingsInitialConfig(this.settingsInitialConfig$.getValue());let r={};this.settingsInitialConfig$.getValue().forEach(n=>{if(n.enable){let c=n?.values?.find(s=>s.id===n.default);r[n.id]=c||n?.values?.[0]||{id:"NONE",name:"None"}}});let a={};Object.keys(r).forEach(n=>{a[n]=r[n].id}),yield this.updateSettingsConfigToDb(a)}}catch(i){this.loggingService.catch("Error in NotificationService getInitialConfigFromDB: ",i)}})}subscribeToUserSettings(){try{this.loggingService.log("%c[WB] Calling NotificationService FUNCTION: subscribeToUserSettings","color: green;"),this.userSettingsSubscription&&this.userSettingsSubscription.unsubscribe();let t=B(this.authService.getUser()?.userId??"");this.userSettingsSubscription=this.enableSettings$.pipe(z(i=>i===!0),b(()=>Y([this.docService.getDocumentPaths$(),this.getSettingsConfigByOrganization$(),this.docService.getOrganizationConfig$()]).pipe(z(([i,e,o])=>(e||!!i)&&!!o?.organizationId),b(([i,e,o])=>G(this.getInitialConfigFromDB(i)).pipe(b(()=>this.commonDbService.dbListener({feature:"userConfig",properties:{useCollectionGroup:!1,isCollection:!1,documentId:e?void 0:i?.documentId,organizationId:i?.organizationId??o?.organizationId,userId:t}}).pipe(I(r=>{r?.data?.notificationsConfig&&!q(r?.data?.notificationsConfig??{},this.settingsConfig$.getValue()??{})&&this.setDBConfigDataToInitialConfig(r?.data?.notificationsConfig)})))))))).subscribe()}catch(t){this.loggingService.catch("Error in NotificationService subscribeToUserSettings: ",t)}}resetCacheData(){try{this.loggingService.log("%c[WB] Calling NotificationService FUNCTION: resetCacheData","color: green;"),this.setUserNotificationsFromServer(null),this.notificationsByDocumentIdMap$.next(null),this.notificationsForYou$.next(null),this.settingsConfig$.next(null),this.resetCrossOrgForUser()}catch(t){this.loggingService.catch("Error in NotificationService resetCacheData: ",t)}}subscribeGetNotificationsForYou(){try{this.notificationForYouSubscription&&this.notificationForYouSubscription.unsubscribe(),this.notificationForYouSubscription=this.getNotificationsForYou().subscribe(()=>{},t=>{this.loggingService.catch("Error in NotificationService getNotificationsForYou subscription: ",t)})}catch(t){this.loggingService.catch("Error in NotificationService subscriveGetNotificationsForYou: ",t)}}setCommentService(t){try{this.commentService=t}catch(i){this.loggingService.catch("Error in NotificationService setCommentService: ",i)}}getDocumentIds(){try{this.documentIdsSubscription&&this.documentIdsSubscription.unsubscribe();let t=!1,i=It(()=>this.adapterSelectorService?.isPortableBackendActive()?(t=!0,this.subscribePortableUserNotificationList(),_):this.notificationListPipeline$()).subscribe(()=>{},e=>{this.loggingService.catch("Error in NotificationService getDocumentIds subscription: ",e)});t||(this.documentIdsSubscription=i)}catch(t){this.loggingService.catch("Error in NotificationService getDocumentIds: ",t)}}notificationListPipeline$(t){return this.selfNotifications$.pipe(b(()=>this.getCurrentDocumentOnly$().pipe(b(i=>i?this.docService.getDocumentPaths$().pipe(I(e=>{})):A(void 0)))),J(()=>{this.notificationsByDocumentIdMap$.next(null)}),b(()=>this.getDocumentIdsByLastNotificationTimestamp(void 0,t).pipe(lt(),I(([i,e])=>{let o=i?.map(s=>s.documentId),r=e?.map(s=>s.documentId),a=o?.filter(s=>!r?.includes(s)),n=r?.map(s=>({documentId:s,timestamp:e?.find(l=>l.documentId===s)?.timestamp})).filter(s=>!o?.includes(s.documentId)),c=r?.map(s=>{let l=e?.find(f=>f.documentId===s)?.timestamp;return{documentId:s,timestamp:l}}).filter(s=>{let l=i?.find(f=>f.documentId===s.documentId)?.timestamp;return l&&s.timestamp&&l!==s.timestamp});n?.length&&this.fetchNotificationsForDocumentIds(n),c?.length&&this.fetchNotificationsForDocumentIds(c,1),a?.forEach(s=>{this.removeNotificationsForDocumentId(s)}),e&&!e?.length&&!this.notificationsByDocumentIdMap$.getValue()&&(this.notificationsByDocumentIdMap$.next({}),this.setUserNotificationsFromServer([]))}))))}subscribePortableUserNotificationList(){try{this.documentIdsSubscription&&this.documentIdsSubscription.unsubscribe(),this.documentIdsSubscription=this.authService.getUser$().pipe(b(t=>t?.userId?this.docService.getOrganizationConfig$().pipe(I(i=>i?.organizationId||t.organizationId),k(),b(i=>{let e=this.configService.getApiKey();if(!e||!i)return this.notificationsByDocumentIdMap$.next({}),this.setUserNotificationsFromServer([]),_;let r=`${B(t.userId)}:${e}:${i}`;return this.portableListBoundKey!==null&&this.portableListBoundKey!==r&&(this.notificationsByDocumentIdMap$.next({}),this.setUserNotificationsFromServer([])),this.portableListBoundKey=r,this.portableNotificationList$(t,e,String(i))})):(this.notificationsByDocumentIdMap$.next({}),this.setUserNotificationsFromServer([]),_))).subscribe(()=>{},t=>{this.loggingService.catch("Error in portable user notification list subscription: ",t)})}catch(t){this.loggingService.catch("Error in NotificationService subscribePortableUserNotificationList: ",t)}}portableNotificationList$(t,i,e){return new ct(o=>{let r=new Nt(1),a=new O(null),n={rows$:r.asObservable()},c=0,s=0,l=!1,f=null,d=null,g=null,u=h=>{let p=a.getValue();p?.mode===h&&p.epoch===c||a.next({mode:h,epoch:c})},S=()=>{g!==null&&(clearTimeout(g),g=null)},D=()=>{try{d?.()}catch(h){this.loggingService.catch("Error disarming the notification trigger reconnect probe: ",h)}d=null},E=()=>{u("fallback"),D();try{d=this.adapterSelectorService?.resolveRealtimeAdapter?.()?.onServerTimeOffset?.(()=>{Promise.resolve().then(()=>F(!1))})??null}catch(h){this.loggingService.catch("Error arming the notification trigger reconnect probe: ",h)}},F=h=>{if(l)return;let p=++s;h&&(c+=1),D(),S();try{f?.unsubscribe()}catch(R){this.loggingService.catch("Error releasing the notification trigger subscription: ",R)}f=null;let C=()=>!l&&p===s,T=!1,$=this.openPortableNotificationTrigger(i,e,{onState:R=>{C()&&(T=!0,S(),D(),r.next(R),u("hosted"))},onRefused:R=>{C()&&(T=!0,S(),this.loggingService.log(`[WB] Notification trigger channel refused (${R}): keeping the user-channel notification list.`),E())}});if(!C()){$?.unsubscribe();return}if(f=$,!$){E();return}if(!T){let R;try{R=Promise.resolve(this.adapterSelectorService?.resolveRealtimeAdapter?.()?.whenReady?.())}catch{R=Promise.resolve()}R.then(()=>{!C()||T||(g=setTimeout(()=>{g=null,!(!C()||T)&&(this.loggingService.log("[WB] Notification trigger channel did not answer: keeping the user-channel notification list."),E())},Oi))},()=>{})}},M=null,x=a.pipe(z(h=>!!h),k((h,p)=>h.mode===p.mode&&(h.mode==="hosted"||h.epoch===p.epoch)),J(({mode:h})=>{M!==null&&M!==h&&(this.notificationsByDocumentIdMap$.next({}),this.setUserNotificationsFromServer([])),M=h}),b(({mode:h})=>h==="hosted"?this.notificationListPipeline$(n):this.portableFallbackList$(t,i,e))).subscribe({next:h=>o.next(h),error:h=>o.error(h)});this.portableNotificationListLive=!0;let j=St(()=>F(!0));return F(!0),()=>{l=!0,s+=1,this.portableNotificationListLive=!1;try{j()}catch(h){this.loggingService.catch("Error disposing the notification trigger registration listener: ",h)}D(),S();try{f?.unsubscribe()}catch(h){this.loggingService.catch("Error releasing the notification trigger subscription: ",h)}f=null,x.unsubscribe(),r.complete(),a.complete()}})}openPortableNotificationTrigger(t,i,e){try{let o=ei(ii,{apiKey:t,organizationId:i}),r=this.adapterSelectorService?.resolveRealtimeAdapter?.();if(!o||!r)return null;let a=Kt(o.feature)?.mode??"persistent",n={},c={},s=!1,l=!1;return r.subscribe(o,a,f=>{try{if(l)return;if(typeof f.seq=="number"){let d=c[f.id];if(d!==void 0&&f.seq<=d)return;c[f.id]=f.seq}f.type==="removed"?delete n[f.id]:n[f.id]=f.data,s&&typeof f.seq=="number"&&e.onState(y({},n))}catch(d){this.loggingService.catch("Error materializing a notification trigger delta: ",d)}},{onSnapshotComplete:()=>{try{if(l)return;s=!0,e.onState(y({},n))}catch(f){this.loggingService.catch("Error completing the notification trigger snapshot: ",f)}},onError:f=>{try{l=!0;for(let d of Object.keys(n))delete n[d];e.onRefused(f)}catch(d){this.loggingService.catch("Error handling the notification trigger denial: ",d)}}})}catch(o){return this.loggingService.catch("Error subscribing the notification trigger channel: ",o),null}}portableFallbackList$(t,i,e){let o=B(t.userId),r={lastAllowed:null};return Ci(this.commonDbService.dbListener({feature:"allUserNotifications",properties:{id:o,apiKey:i,organizationId:e}})).pipe(H(a=>(this.loggingService.catch("Error in portable user notification list listener: ",a),A({data:{},operation:null}))),b(a=>this.filterPortableRowsByPermissionProvider$(a?.data??a??{},r)),J(a=>{try{this.applyPortableUserNotificationMap(a)}catch(n){this.loggingService.catch("Error applying portable user notification map: ",n)}}))}filterPortableRowsByPermissionProvider$(t,i){let e=!1;try{e=!!this.userPermissionService?.isPermissionProviderAvailable?.()}catch(o){this.loggingService.catch("Error reading the permission provider state for the notification list: ",o)}return e?G(this.filterPortableRowsByPermissionProvider(t,i)):A(t)}filterPortableRowsByPermissionProvider(t,i){return U(this,null,function*(){try{let e=t&&typeof t=="object"?t:{},o=Object.create(null),r=Object.create(null),a=new Set,n=Object.create(null);for(let g of Object.keys(e)){let u=this.portableNotificationRowDocumentId(this.toPortableNotificationEnvelope(g,e[g]));if(n[g]=u,u===void 0){a.add(g);continue}let S=String(u);if(o[S]=Math.max(o[S]??0,Number(e[g]?.timestamp)||0),!r[S]){let D=Di(e[g]);D&&(r[S]=D)}}let c=Object.keys(o).map(g=>({documentId:g,timestamp:o[g]}));if(!c.length){let g=Object.create(null);return a.forEach(u=>{g[u]=e[u]}),g}let s={failed:!1},l=yield this.filterDocumentIdsByPermissionProvider(c,{fallbackClientDocumentIds:r,skipMetadataFetch:this.reportedUnservedPortableNotificationOps.has("getDocumentMetadataFromIds"),outcome:s}),f;s.failed?f=i.lastAllowed??new Set:(f=new Set(l.map(g=>g.documentId)),i.lastAllowed=f);let d=Object.create(null);for(let g of Object.keys(e)){let u=n[g];(a.has(g)||u!==void 0&&f.has(String(u)))&&(d[g]=e[g])}return d}catch(e){return this.loggingService.catch("Error filtering the portable notification list by the permission provider: ",e),{}}})}toPortableNotificationEnvelope(t,i){return!i||typeof i!="object"?{notificationId:t}:y({notificationId:i.notificationId??t},i)}portableNotificationRowDocumentId(t,i=this.getClientNotificationObject(t)){let e=t?.metadata?.documentId??i?.metadata?.documentId;return e===null||e===""?void 0:e}applyPortableUserNotificationMap(t){let i=t&&typeof t=="object"?t:{},e=Object.keys(i).map(r=>this.toPortableNotificationEnvelope(r,i[r]));this.setUserNotificationsFromServer(e);let o={};for(let r of e)try{if((r?.kind??r?.payload?.kind)==="digest")continue;let n=this.getClientNotificationObject(r);if(!n)continue;let c=this.portableNotificationRowDocumentId(r,n);if(!c)continue;o[c]||(o[c]={notifications:[]}),o[c].notifications.push(n)}catch(a){this.loggingService.catch("Error materializing portable notification row: ",a)}for(let r of Object.keys(o))o[r].notifications.sort((a,n)=>(n.timestamp||0)-(a.timestamp||0));this.notificationsByDocumentIdMap$.next(o)}getDocumentIdsByLastNotificationTimestamp(t=15,i){try{return this.authService.getUser$().pipe(b(e=>this.docService.getOrganizationConfig$().pipe(I(o=>{let r=null,a=this.configService.getApiKey(),n=o?.organizationId||e?.organizationId,c=o?.clientOrganizationId||e?.clientOrganizationId||"";return a&&n&&(r=new pt({apiKey:a,organizationId:n})),{user:e,documentPaths:r,clientOrganizationId:c}}))),b(e=>{let{user:o,documentPaths:r,clientOrganizationId:a}=e;if(this.getCurrentDocumentOnly()&&!this.docService?.getDocumentPaths()?.documentId)return A(null);if(o&&r?.organizationNotificationsLastNotificationTimestamp){let n=vt(this.maxNotificationDays$.getValue()),c=li({startAtTimestamp:n,currentDocumentOnly:this.getCurrentDocumentOnly(),currentDocumentId:this.docService.getDocumentPaths()?.documentId,limit:t}),s=o?.userId??"";return G(this.userPermissionService?.getUserPermissionsFromCacheOrFetch({organizationId:a})??Promise.resolve({})).pipe(b(l=>s&&a&&l?.[s]?.organization?.[a]?.errorCode===Ut.PERMISSION_DENIED?A(null):this.lastNotificationTimestampRows$(r,c,i).pipe(I(f=>{let d=()=>!!i||this.commonDbService.shouldUseFirestore(),g=[];return Object.keys(f||{}).forEach(u=>{let S=d()?f[u]?.timestamp??0:f[u],D=d()?f[u]?.deletedNotification??!1:!1;if(D&&D.id&&D?.timestamp===S){let E=D.id,F=f[u]?.metadata?.documentId,M=JSON.parse(JSON.stringify(this.notificationsByDocumentIdMap$.getValue()??{})),x=M?.[F]??{documentMetadata:null,notifications:[]},j=x.notifications??[],h=j?.findIndex(p=>p.id===E);h!==-1&&(j.splice(h,1),this.notificationsByDocumentIdMap$.next(P(y({},M),{[F]:P(y({},x),{notifications:j})}))),this.notificationResolverService.notificationDataProviderAvailable()&&this.notificationResolverService.getNotificationById(E)&&this.notificationResolverService.deleteNotification(E,this.docService.getDocumentPaths()?.clientOrganizationId??"")}g.push({documentId:u,timestamp:S})}),g}),H(f=>(this.loggingService.catch("Error in NotificationService getDocumentIdsByLastNotificationTimestamp: ",f),A([]))))))}return A(null)}))}catch(e){return this.loggingService.catch("Error in NotificationService getDocumentIdsByLastNotificationTimestamp: ",e),A([])}}lastNotificationTimestampRows$(t,i,e){return e?e.rows$.pipe(I(o=>fi(o,i)),Ot(void 0)):this.commonDbService.dbListener({feature:"allLastNotificationTimestamp",properties:{organizationId:t?.organizationId,isCollection:!0,useQuery:!0,firestoreQuery:this.toFirestoreTriggerQuery(i)}}).pipe(I(o=>o?.data))}toFirestoreTriggerQuery(t){let i=[Yt(mt("timestamp",">=",t.startAtTimestamp),...t.documentId!==void 0?[mt("metadata.documentId","==",t.documentId)]:[])];return t.limit!==void 0&&(i.push(Wt("timestamp","desc")),i.push(Gt(t.limit))),i}resolveAndUpdateDocumentNotifications(t,i){try{Object.keys(t).forEach(e=>{let o=t[e]?.documentMetadata||this.docService.getAllDocumentMetadataMap()?.[e]||{},r;if(i==="user")r=this.commonDbUtilsService.mergeUsersWithData({feature:"allDocNotifications",data:t[e]?.notifications||[]});else if(i==="notification"){let a=t[e]?.notifications?.reduce((c,s)=>(c[s.notificationId]=s,c),{}),n=this.commonDbUtilsService.mergeNotificationsWithResolvedData({feature:"allDocNotifications",data:a});r=Object.values(n??{})}else{let a=t[e]?.notifications?.reduce((c,s)=>(c[s.notificationId]=s,c),{}),n=this.commonDbUtilsService.mergeCommentAnnotationsWithData({feature:"allDocNotifications",data:a});r=Object.values(n??{})}r.forEach(a=>{a.notification=this.getClientNotificationObject(a)}),this.setNotificationForDocumentIdInCache(e,o,r)})}catch(e){this.loggingService.catch("Error in NotificationService resolveAndUpdateDocumentNotifications: ",e)}}resolveAndMergeUserNotifications(t,i,e=!1){try{let o=t;if(e&&i==="comment"){let s=this.getUserNotificationsFromServer()??[],l=new Set(t.map(f=>f.notificationId));o=s.filter(f=>l.has(f.notificationId)).concat(t.filter(f=>!s.some(d=>d.notificationId===f.notificationId)))}let r=o.reduce((s,l)=>(s[l.notificationId]=l,s),{}),a;if(i==="user"){let s=this.commonDbUtilsService.mergeUsersWithData({feature:"allUserNotifications",data:r});a=Object.values(s??{})}else if(i==="notification"){let s=this.commonDbUtilsService.mergeNotificationsWithResolvedData({feature:"allUserNotifications",data:r});a=Object.values(s??{})}else{let s=this.commonDbUtilsService.mergeCommentAnnotationsWithData({feature:"allUserNotifications",data:r});a=Object.values(s??{})}a.forEach(s=>{s.notification=this.getClientNotificationObject(s)});let n=this.getUserNotificationsFromServer()??[],c=new Map(n.map(s=>[s.notificationId,s]));a.forEach(s=>{c.set(s.notificationId,s)}),this.setUserNotificationsFromServer(Array.from(c.values()))}catch(o){this.loggingService.catch("Error in NotificationService resolveAndMergeUserNotifications: ",o)}}fetchNotificationsForDocumentIds(t,i=15){return U(this,null,function*(){try{if(t?.length){let e=this.docService.getOrganizationConfig()?.organizationId??"";if(!e)return[];let o=this.getStartAtTimestamp(),r={};t.forEach(u=>{if(u?.documentId){let S=this.getAllowedDocumentMetadataByDocumentId(u.documentId);S&&(r[u.documentId]=S)}}),this.userPermissionService?.isPermissionProviderAvailable()&&(t=yield this.filterDocumentIdsByPermissionProvider(t));let a=this.userScopedNotifications$.getValue(),n=!!a?.enabled&&i!==1&&!this.getCurrentDocumentOnly();if(!t.length&&(this.notificationsByDocumentIdMap$.getValue()||(this.notificationsByDocumentIdMap$.next({}),this.setUserNotificationsFromServer([])),!n))return[];let c=this.userPermissionService?.getPermissionsCache()?.filter(u=>u.type===X.CONTEXT),s=y({organizationId:e,documentIds:t.filter(u=>!!u.documentId&&!!u.timestamp).map(u=>({documentId:u.documentId,timestamp:u.timestamp??0})),timestamp:o,limitToLast:i,selfNotifications:this.selfNotifications$.value,isPermissionProviderUsed:this.userPermissionService?.isPermissionProviderAvailable(),getUserNotifications:!0,isContextEnabled:this.userPermissionService?.getIsContextEnabled(),cachedData:c,isSettingsConfigByOrganization:this.getSettingsConfigByOrganization(),retryConfig:this.userPermissionService?.getPermissionProviderRetryConfig()},n&&{getUserNotificationsForOrganization:!0,userNotificationsLimitToLast:gi(a?.limit)}),{notificationsByDocumentId:l,userNotifications:f=[],userNotificationIdsInDocNotifications:d=[],permissionResults:g=[]}=yield this.callGetNotificationsForDocuments(s);if(this.userPermissionService?.getIsContextEnabled()){let u=[...this.userPermissionService?.getPermissionsCache()??[],...g??[]];this.userPermissionService?.setPermissionsCache(u)}if(l&&typeof l=="object"){let u=this.usersService.userDataProviderAvailable(),S=this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable(),D=this.notificationResolverService.notificationDataProviderAvailable(),E=[],F=[],M=[];Object.keys(l).forEach((h,p)=>{let C=l[h].documentMetadata??this.docService.getAllDocumentMetadataMap()?.[h];if(C){let $=this.allowedDocumentMetadataMap$.value||{};(!$?.[h]||!q($?.[h],C))&&this.allowedDocumentMetadataMap$.next(P(y({},$),{[h]:C}))}let T=l[h].notifications||[];T.forEach($=>{d.includes($.notificationId)&&!f.find(R=>R.notificationId===$.notificationId)&&f.push(JSON.parse(JSON.stringify($))),$.notification=this.getClientNotificationObject($)}),this.setNotificationForDocumentIdInCache(h,C,T),u&&(E.push(this.commonDbUtilsService.formatResponse({feature:"allDocNotifications",data:T,shouldAwait:!0,forceResolve:!0})),E.push(this.commonDbUtilsService.formatResponse({feature:"allUserNotifications",data:f,shouldAwait:!0,forceResolve:!0}))),S&&(F.push(this.commonDbUtilsService.formatResponse({feature:"allDocNotifications",data:T,shouldCommentAnnotationsResolverAwait:!0})),F.push(this.commonDbUtilsService.formatResponse({feature:"allUserNotifications",data:f,shouldCommentAnnotationsResolverAwait:!0}))),D&&(M.push(this.commonDbUtilsService.formatResponse({feature:"allDocNotifications",data:T,shouldNotificationResolverAwait:!0})),M.push(this.commonDbUtilsService.formatResponse({feature:"allUserNotifications",data:f,shouldNotificationResolverAwait:!0})))});let x=JSON.parse(JSON.stringify(f));if(n){let h=new Map((this.getUserNotificationsFromServer()??[]).map(p=>[p?.notificationId,p]));f.forEach(p=>h.set(p?.notificationId,p)),this.setUserNotificationsFromServer(Array.from(h.values()))}else this.setUserNotificationsFromServer([...this.getUserNotificationsFromServer()??[],...f]);(D||u||S)&&(()=>{let h=Promise.resolve();if(D&&(h=h.then(()=>Promise.allSettled(M)).then(()=>{this.resolveAndUpdateDocumentNotifications(l,"notification"),this.resolveAndMergeUserNotifications(x,"notification")})),u&&(h=h.then(()=>Promise.allSettled(E)).then(()=>{this.resolveAndUpdateDocumentNotifications(l,"user"),this.resolveAndMergeUserNotifications(x,"user")})),S){let p=D||u;h=h.then(()=>Promise.allSettled(F)).then(()=>{this.resolveAndUpdateDocumentNotifications(l,"comment"),this.resolveAndMergeUserNotifications(x,"comment",p)})}return h})().catch(h=>{this.loggingService.catch("Error in NotificationService resolveChain: ",h)})}}}catch(e){return this.loggingService.catch("Error in NotificationService fetchNotificationsForDocumentIds: ",e),[]}})}filterDocumentIdsByPermissionProvider(t,i){return U(this,null,function*(){let e=i?.fallbackClientDocumentIds;try{let o=[];if(t.forEach(s=>{this.docService.getDocumentMetadata(s.documentId)||o.push(s.documentId)}),o.length&&!i?.skipMetadataFetch){let s=this.authService.getUser(),l={type:"getDocumentMetadataFromIds",metadata:{organizationId:s?.clientOrganizationId,folderId:this.documentPaths?.folderId},documentIds:o},f=!!this.adapterSelectorService?.isPortableBackendActive(),d=f?void 0:tt(this.functions,Z({url:this.endpointsService.getCloudFunctionUrl("sdkProxy"),apiProxyDomain:this.configService?.getApiProxyDomain()}));try{let g=f?yield this.invokePortableSdkProxyOp("getDocumentMetadataFromIds",l):yield ht({methodName:"getDocumentMetadataFromIds",data:l,getSdkProxy:d,userId:s?.userId??""});if(g?.data?.length){let u={};g.data.forEach(S=>{S?.documentId&&(u[S.documentId]=S)}),this.docService.setAllDocumentMetadata(y(y({},this.docService.getAllDocumentMetadataMap()),u))}}catch(g){this.loggingService.warn("Error in NotificationService fetchNotificationsForDocumentIds: ",g)}}let r=[],a=[];t.forEach(s=>{let l=this.docService.getDocumentMetadata(s.documentId),f=l?.clientDocumentId||e?.[s.documentId];f?r.push({userId:this.authService.getUser()?.userId??"",resource:y({id:f,type:X.DOCUMENT,source:Q.GET_NOTIFICATIONS,organizationId:this.docService.getOrganizationConfig()?.clientOrganizationId??""},l?.folderId&&{parentFolderId:l.folderId})}):a.push(s.documentId)}),a.length&&(t=t.filter(s=>!a.includes(s.documentId)));let n=Ft();this.coreActionsService.triggerAction(At.PERMISSION_PROVIDER,{event:V.Events.PermissionProvider.RESOURCE_ACCESS_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:n,methodName:Q.GET_NOTIFICATIONS,source:"internal",payload:{requests:r}});let c=yield this.userPermissionService?.onResourceAccessRequired({requests:r,uniqueId:n,methodName:Q.GET_NOTIFICATIONS});return c?.success&&c?.data?.length?c.data.forEach(s=>{!s.hasAccess&&s.resourceId&&(t=t.filter(l=>l.documentId!==gt(s.resourceId)))}):(t=[],i?.outcome&&(i.outcome.failed=!0)),t}catch(o){return this.loggingService.warn("Error in NotificationService fetchNotificationsForDocumentIds: ",o),i?.outcome&&(i.outcome.failed=!0),[]}})}callGetNotificationsForDocuments(t){return U(this,null,function*(){if(this.adapterSelectorService?.isPortableBackendActive())return this.callPortableGetNotificationsForDocuments(t);let i=tt(this.functions,Z({url:this.endpointsService.getCloudFunctionUrl("getNotificationsForDocuments"),apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:1200*1e3}),e=yield this.notificationUtilsService.handleNotificationEncryption({data:t}),o=yield i({veltData:e}),r=o?.data?.data?.veltData||{},a=o?.data?.data?.veltAdditionalData||{},n="notificationwithdocumentidstoencryptanddecryptonsdk"+(this.authService.getUser()?.userId??""),c=yield ut(r,n),{userNotifications:s,userNotificationIdsInDocNotifications:l,permissionResults:f}=yield ut(a,n);return{notificationsByDocumentId:c,userNotifications:s,userNotificationIdsInDocNotifications:l,permissionResults:f}})}callPortableGetNotificationsForDocuments(t){return U(this,null,function*(){let i=yield this.adapterSelectorService.resolveDbAdapter().getNotificationsForDocuments({scope:"org",data:t});if(!i?.ok)throw this.reportUnservedPortableNotificationOp("getNotificationsForDocuments",i),new Error(`getNotificationsForDocuments failed on the portable gateway: ${i?.code??"unknown"}`);let e=i.data??{},o=e.veltData??{},{userNotifications:r,userNotificationIdsInDocNotifications:a,permissionResults:n}=e.veltAdditionalData??{};return{notificationsByDocumentId:o,userNotifications:r,userNotificationIdsInDocNotifications:a,permissionResults:n}})}invokePortableSdkProxyOp(t,i){return U(this,null,function*(){try{let e=yield this.adapterSelectorService.resolveDbAdapter()[t]({scope:"org",data:i});return e?.ok?e.data?.veltData:(this.reportUnservedPortableNotificationOp(t,e)?this.loggingService.log(`[WB] NotificationService ${t} is not served by this portable gateway: `,e):this.loggingService.catch(`Error in NotificationService ${t} (portable gateway): `,e),i)}catch(e){return this.loggingService.catch(`Error in NotificationService ${t} (portable gateway): `,e),i}})}reportUnservedPortableNotificationOp(t,i){try{if(!ti(i))return!1;let e=i?.code;if(this.reportedUnservedPortableNotificationOps.has(t))return!0;this.reportedUnservedPortableNotificationOps.add(t);let o=i?.message;return console.warn(`Velt [Tier B]: the portable gateway answered '${e}'${o?` (${o})`:""} for '${t}' \u2014 this image does not serve it, so ${yi[t]} is unavailable on this deployment. This warning fires once per session.`),!0}catch{return!1}}getUserNotificationsFromServer$(){return this.userNotificationsFromServer$.asObservable()}setUserNotificationsFromServer(t){try{let i=JSON.parse(JSON.stringify(t));i=i?.filter((e,o,r)=>o===r.findIndex(a=>a.notificationId===e.notificationId)),this.userNotificationsFromServer$.next(i)}catch(i){this.loggingService.catch("Error in NotificationService setUserNotificationsFromServer: ",i)}}getUserNotificationsFromServer(){return this.userNotificationsFromServer$.getValue()}setNotificationForDocumentIdInCache(t,i,e,o){try{let r=this.docService.getOrganizationConfig()?.organizationId??"",a=this.docService.getOrganizationMetadata(r);i||(i=this.getOwnDocumentMetadata(t)),a||(a=JSON.parse(JSON.stringify(this.docService.getOrganizationMetadata(r)||{})));let n=this.notificationsByDocumentIdMap$.getValue(),c=n?.[t]?.notifications||[],s=this.docService.getLocationMetadatas(),l=e?.map(g=>{let u=g?.notification;return u?(u.metadata&&(u.metadata.documentName=i?.documentName||u.metadata.documentName,u.metadata.organizationMetadata=a||u.metadata.organizationMetadata,u.metadata.documentMetadata=di(i,u.metadata.documentMetadata)),s&&(u=this.notificationUtilsService.mergeLocationWithNotification({notification:u},s)?.notification),u):null})?.filter(g=>!!g)||[],f=new Map(c.map(g=>[g.id,g]));l.forEach(g=>{f.set(g.id,g)});let d=Array.from(f.values()).sort((g,u)=>(u.timestamp||0)-(g.timestamp||0));this.notificationsByDocumentIdMap$.next(P(y({},n),{[t]:{notifications:d,documentMetadata:i||{}}}))}catch(r){this.loggingService.catch("Error in NotificationService setNotificationForDocumentIdInCache: ",r)}}removeNotificationsForDocumentId(t){try{this.notificationsByDocumentIdSubscription[t]&&this.notificationsByDocumentIdSubscription[t].unsubscribe();let i=this.notificationsByDocumentIdMap$.getValue();delete i?.[t],this.notificationsByDocumentIdMap$.next(i)}catch(i){this.loggingService.catch("Error in NotificationService removeNotificationsForDocumentId: ",i)}}getStartAtTimestamp(){try{return vt(this.maxNotificationDays$.getValue())}catch(t){return this.loggingService.catch("Error in NotificationService getStartAtTimestamp: ",t),0}}getCurrentOrgNotificationsForYou(){try{return this.getUserNotificationsFromServer$().pipe(b(t=>A(t).pipe(z(i=>!!i),I(i=>{let e=this.usersService.userDataProviderAvailable(),o=this.commentAnnotationsResolverService?.commentAnnotationDataProviderAvailable(),r=this.notificationResolverService?.notificationDataProviderAvailable();if(r||e||o){let n=i?.reduce((c,s)=>(c[s.notificationId]=s,c),{});r&&(n=this.commonDbUtilsService.mergeNotificationsWithResolvedData({feature:"allUserNotifications",data:n||[]})),e&&(n=this.commonDbUtilsService.mergeUsersWithData({feature:"allUserNotifications",data:n||[]})),o&&(n=this.commonDbUtilsService.mergeCommentAnnotationsWithData({feature:"allUserNotifications",data:n||[]})),i=Object.values(n??{})}return i.forEach(n=>{n.notification=this.getClientNotificationObject(n)}),i.sort((n,c)=>c.timestamp-n.timestamp),i.map(n=>n.notification).filter(n=>!!n)}),b(i=>{let e={data:i?.reduce((o,r)=>(o[r.id]={notification:r},o),{}),operation:null};return this.commonDbUtilsService.mergeLocationMetadataWithData$({data:e,feature:"allUserNotifications"}).pipe(I(o=>Object.values(o?.data||{}).map(r=>r?.notification)))}))),b(t=>{let i=this.docService.getOrganizationConfig()?.organizationId??"";return this.docService.getOrganizationMetadata$(i).pipe(I(()=>t))}),b(t=>this.allowedDocumentMetadataMap$.pipe(I(()=>t))),I(t=>(t?.length&&(t=t.map(i=>{if(i?.metadata){let e=this.docService.getOrganizationConfig()?.organizationId??"",o=this.getAllowedDocumentMetadataByDocumentId(i.metadata.documentId),r=this.docService.getOrganizationMetadata(e);o||(o=this.getOwnDocumentMetadata(i.metadata.documentId)),r||(r=JSON.parse(JSON.stringify(this.docService.getOrganizationMetadata(e)||{}))),i.metadata.documentName=o?.documentName||i.metadata.documentName,i.metadata.organizationMetadata=r||i.metadata.organizationMetadata,i.metadata.documentMetadata=di(o,i.metadata.documentMetadata)}return i})),t)))}catch(t){return this.loggingService.catch("Error in NotificationService getCurrentOrgNotificationsForYou: ",t),A(null)}}getNotificationsForYou(){try{return Y([this.getCurrentOrgNotificationsForYou(),this.crossOrgNotifications$.asObservable()]).pipe(I(([t,i])=>{let e=this.mergeCrossOrgForYou(t,i);return e===null?this.notificationsForYou$.next(null):e?.length?this.notificationsForYou$.next(JSON.parse(JSON.stringify(e))):this.notificationsForYou$.next([]),e}))}catch(t){return this.loggingService.catch("Error in NotificationService getNotificationsForYou: ",t),A({})}}mergeCrossOrgForYou(t,i){try{let e=Array.isArray(i)?i:[];if(!e.length)return t;let o=Array.isArray(t)?t:[],r=c=>c?.id??c?.notificationId,a=new Set;o.forEach(c=>{let s=r(c);s!=null&&a.add(s)});let n=[...o];return e.forEach(c=>{let s=r(c);s!=null&&a.has(s)||(s!=null&&a.add(s),n.push(c))}),n.sort((c,s)=>(s?.timestamp||0)-(c?.timestamp||0))}catch(e){return this.loggingService.catch("Error in NotificationService mergeCrossOrgForYou: ",e),t}}enableCrossOrganization(t){try{if(t&&typeof t=="object"&&t.enabled===!1){this.disableCrossOrganization();return}this.setCrossOrganizationConfig(P(y({},t||{}),{enabled:!0})),this.crossOrgUserSubscription?this.crossOrgIndexSubscription&&(this.crossOrgInitialFetchDone=!1,this.scheduleCrossOrgFetch()):this.attachCrossOrgIndexListener()}catch(i){this.loggingService.catch("Error in NotificationService enableCrossOrganization: ",i)}}disableCrossOrganization(){try{this.teardownCrossOrg();let t=this.crossOrganizationConfig$.getValue();this.crossOrganizationConfig$.next(P(y({},t||{}),{enabled:!1}))}catch(t){this.loggingService.catch("Error in NotificationService disableCrossOrganization: ",t)}}setCrossOrganizationConfig(t){try{let i=t||{},e=Array.isArray(i.feeds)&&i.feeds.length?i.feeds:["forYou"];e.includes("all")&&this.loggingService.warn('NotificationService: cross-organization notifications only support the "forYou" feed; ignoring "all".'),e=e.filter(r=>r==="forYou"),e.length||(e=["forYou"]);let o={enabled:i.enabled??!0,organizationIds:i.organizationIds,excludeOrganizationIds:i.excludeOrganizationIds,feeds:e};this.crossOrganizationConfig$.next(o)}catch(i){this.loggingService.catch("Error in NotificationService setCrossOrganizationConfig: ",i)}}getCrossOrganizationConfig(){return this.crossOrganizationConfig$.getValue()}getCrossOrganizationConfig$(){return this.crossOrganizationConfig$.asObservable()}attachCrossOrgIndexListener(){try{this.teardownCrossOrgUserWatcher(),this.crossOrgUserSubscription=this.authService.getUser$().pipe(I(t=>t?.userId),k(),z(t=>!!t),H(t=>(this.loggingService.catch("Error in NotificationService cross-org user watcher: ",t),_))).subscribe(t=>{try{this.teardownCrossOrgPerUserListeners(),this.resetCrossOrgDeltaState(),this.crossOrgNotifications$.next([]),this.bindCrossOrgListenersForUser(t)}catch(i){this.loggingService.catch("Error in NotificationService cross-org user-change handler: ",i)}})}catch(t){this.loggingService.catch("Error in NotificationService attachCrossOrgIndexListener: ",t)}}bindCrossOrgListenersForUser(t){this.crossOrgIndexSubscription=this.commonDbService.dbListener({feature:"userNotificationIndex",properties:{id:B(t),isCollection:!1,useCollectionGroup:!1}}).pipe(H(i=>(this.loggingService.catch("Error in NotificationService cross-org index listener: ",i),_))).subscribe(i=>{try{let e=this.extractIndexOrgTimestamps(i);this.crossOrgIndexTimestamps=e;let o=Object.keys(e);this.crossOrgIndexOrgs=o,this.pruneCrossOrgBufferToAllowedOrgs(),o.length&&this.scheduleCrossOrgFetch()}catch(e){this.loggingService.catch("Error in NotificationService cross-org index snapshot: ",e)}}),this.crossOrgOrgSwitchSubscription=this.docService.getOrganizationConfig$().pipe(I(i=>i?.organizationId??""),k(),lt(),z(([i])=>!!i),H(i=>(this.loggingService.catch("Error in NotificationService cross-org org-switch listener: ",i),_))).subscribe(()=>{this.crossOrgInitialFetchDone=!1,this.crossOrgSeenTimestamps={},this.scheduleCrossOrgFetch()})}extractIndexOrgTimestamps(t){let i={};try{let e=t?.data??t,o=e?.organizationIds??e?.orgs;return Array.isArray(o)?(o.forEach(r=>{typeof r=="string"&&r.length&&(i[r]=0)}),i):(o&&typeof o=="object"&&Object.keys(o).forEach(r=>{if(typeof r=="string"&&r.length){let a=Number(o[r]);i[r]=Number.isFinite(a)?a:0}}),i)}catch(e){return this.loggingService.catch("Error in NotificationService extractIndexOrgTimestamps: ",e),i}}scheduleCrossOrgFetch(){try{let t=Date.now();t-this.lastCrossOrgFetchTime>=this.CROSS_ORG_FETCH_WINDOW_MS?(this.lastCrossOrgFetchTime=t,this.crossOrgFetchPending=!1,this.fetchCrossOrgUserNotifications(),this.armCrossOrgTrailingTimer()):this.crossOrgFetchPending=!0}catch(t){this.loggingService.catch("Error in NotificationService scheduleCrossOrgFetch: ",t)}}pruneCrossOrgBufferToAllowedOrgs(){try{let t=this.crossOrgNotifications$.getValue();if(!t.length)return;let i=this.crossOrgIndexOrgs||[];if(!i.length){this.crossOrgNotifications$.next([]);return}let e=t.filter(o=>i.includes(o?.metadata?.organizationId));e.length!==t.length&&this.crossOrgNotifications$.next(e)}catch(t){this.loggingService.catch("Error in NotificationService pruneCrossOrgBufferToAllowedOrgs: ",t)}}armCrossOrgTrailingTimer(){this.crossOrgFetchTimer&&clearTimeout(this.crossOrgFetchTimer),this.crossOrgFetchTimer=setTimeout(()=>{this.crossOrgFetchPending&&(this.crossOrgFetchPending=!1,this.lastCrossOrgFetchTime=Date.now(),this.fetchCrossOrgUserNotifications())},this.CROSS_ORG_FETCH_WINDOW_MS)}toCrossOrgClientNotification(t){try{if(!t)return null;if(t.notification){let e=this.getClientNotificationObject(t);if(!e)return null;let o=t?.metadata?.organizationId??e?.metadata?.organizationId;return o!=null&&(e.metadata=P(y({},e.metadata||{}),{organizationId:o})),e}let i=t.id??t.notificationId;return i==null?null:t.id!=null?t:P(y({},t),{id:i})}catch(i){return this.loggingService.catch("Error in NotificationService toCrossOrgClientNotification: ",i),null}}resolveCrossOrgSelfHostedData(t){return U(this,null,function*(){try{if(!t?.length)return t;let i=!!this.notificationResolverService?.notificationDataProviderAvailable?.(),e=!!this.usersService?.userDataProviderAvailable?.(),o=!!this.commentAnnotationsResolverService?.commentAnnotationDataProviderAvailable?.();if(!i&&!e&&!o)return t;let r=new Map;for(let n of t){let c=n?.metadata?.clientOrganizationId??n?.metadata?.organizationId??"",s=r.get(c);s?s.push(n):r.set(c,[n])}let a=[];for(let[n,c]of r){let s=c.reduce((f,d,g)=>{let u=d?.notificationId??d?.id??`__cross_org_${g}`;return f[u]=d,f},{});yield this.commonDbUtilsService.formatResponse({feature:"allUserNotifications",data:s,organizationId:n||void 0,shouldAwait:!0,shouldNotificationResolverAwait:!0,shouldCommentAnnotationsResolverAwait:!0});let l=s;i&&(l=this.commonDbUtilsService.mergeNotificationsWithResolvedData({feature:"allUserNotifications",data:l??{}})),e&&(l=this.commonDbUtilsService.mergeUsersWithData({feature:"allUserNotifications",data:l??{}})),o&&(l=this.commonDbUtilsService.mergeCommentAnnotationsWithData({feature:"allUserNotifications",data:l??{}})),a.push(...Object.values(l??{}))}return a}catch(i){return this.loggingService.catch("Error in NotificationService resolveCrossOrgSelfHostedData: ",i),t}})}fetchCrossOrgUserNotifications(){return U(this,null,function*(){let t=this.crossOrgGeneration;if(this.crossOrgResolveRoundInFlight){this.crossOrgFetchPending=!0;return}this.crossOrgResolveRoundInFlight=!0;try{let i=this.crossOrganizationConfig$.getValue(),e=this.docService.getOrganizationConfig()?.organizationId??"",o=!this.crossOrgInitialFetchDone,r=this.crossOrgIndexTimestamps||{},a=o?[]:Object.keys(r).filter(d=>d!==e&&(r[d]??0)>(this.crossOrgSeenTimestamps[d]??-1));if(!o&&!a.length)return;let n=this.buildCrossOrgRequestData(i,e,{isInitial:o,bumpedOrgs:a}),c=yield this.callGetCrossOrgUserNotifications(n);if(t!==this.crossOrgGeneration)return;let s=Array.isArray(c?.pendingPermissionQueries)?c.pendingPermissionQueries:[],l=!!this.userPermissionService?.isClientDevResolverActive?.(),f=!s.length||!l;if(yield this.processCrossOrgResponse(c,{fetchGeneration:t,currentOrg:e,isInitial:o,indexTimestamps:r,advanceCursors:f}),t!==this.crossOrgGeneration||f){f&&t===this.crossOrgGeneration&&this.clearCrossOrgStragglerRetry();return}yield this.runCrossOrgResolveRound(s,{fetchGeneration:t,config:i,currentOrg:e,isInitial:o,bumpedOrgs:a,indexTimestamps:r})}catch(i){this.loggingService.catch("Error in NotificationService fetchCrossOrgUserNotifications: ",i)}finally{this.crossOrgResolveRoundInFlight=!1,this.crossOrgFetchPending&&t===this.crossOrgGeneration&&(this.crossOrgFetchPending=!1,this.lastCrossOrgFetchTime=Date.now(),this.fetchCrossOrgUserNotifications())}})}runCrossOrgResolveRound(t,i){return U(this,null,function*(){try{let e=yield this.userPermissionService.resolveClientSidePermissions(t);if(i.fetchGeneration!==this.crossOrgGeneration)return;let o=this.buildCrossOrgRequestData(i.config,i.currentOrg,{isInitial:i.isInitial,bumpedOrgs:i.bumpedOrgs});o.clientResolvedResults=e;let r=yield this.callGetCrossOrgUserNotifications(o);if(i.fetchGeneration!==this.crossOrgGeneration)return;yield this.processCrossOrgResponse(r,{fetchGeneration:i.fetchGeneration,currentOrg:i.currentOrg,isInitial:i.isInitial,indexTimestamps:i.indexTimestamps,advanceCursors:!0}),i.fetchGeneration===this.crossOrgGeneration&&this.clearCrossOrgStragglerRetry()}catch(e){this.loggingService.catch("Error in NotificationService runCrossOrgResolveRound: ",e),this.armCrossOrgStragglerRetry(i.fetchGeneration)}})}processCrossOrgResponse(t,i){return U(this,null,function*(){if(this.userPermissionService?.getIsContextEnabled?.()&&t?.permissionResults?.length){let l=[...this.userPermissionService?.getPermissionsCache?.()??[],...t.permissionResults];this.userPermissionService?.setPermissionsCache?.(l)}let e=Array.isArray(t?.forYou)?t.forYou:[],o=this.crossOrgIndexOrgs||[],r=l=>o.includes(l),a=e.filter(l=>{let f=l?.metadata?.organizationId;if(f===i.currentOrg)return this.loggingService.log("%c[WB] Cross-org: dropping current-org echo: "+f,"color: orange;"),!1;let d=r(f);return d||this.loggingService.log("%c[WB] Cross-org: dropping entry from un-indexed org: "+f,"color: orange;"),d}),n=yield this.resolveCrossOrgSelfHostedData(a);if(i.fetchGeneration!==this.crossOrgGeneration)return;let c=n.map(l=>this.toCrossOrgClientNotification(l)).filter(l=>!!l),s;i.isInitial?s=c:s=this.mergeCrossOrgForYou(c,this.crossOrgNotifications$.getValue()).filter(l=>r(l?.metadata?.organizationId)),i.advanceCursors&&(Object.keys(i.indexTimestamps).forEach(l=>{this.crossOrgSeenTimestamps[l]=i.indexTimestamps[l]}),this.crossOrgInitialFetchDone=!0),this.crossOrgNotifications$.next(s)})}armCrossOrgStragglerRetry(t){this.crossOrgStragglerRetryUsed||(this.crossOrgStragglerRetryUsed=!0,this.crossOrgStragglerRetryTimer&&clearTimeout(this.crossOrgStragglerRetryTimer),this.crossOrgStragglerRetryTimer=setTimeout(()=>{this.crossOrgStragglerRetryTimer=void 0,t===this.crossOrgGeneration&&this.fetchCrossOrgUserNotifications()},this.CROSS_ORG_STRAGGLER_RETRY_MS))}clearCrossOrgStragglerRetry(){this.crossOrgStragglerRetryUsed=!1,this.crossOrgStragglerRetryTimer&&(clearTimeout(this.crossOrgStragglerRetryTimer),this.crossOrgStragglerRetryTimer=void 0)}callGetCrossOrgUserNotifications(t){return U(this,null,function*(){if(this.adapterSelectorService?.isPortableBackendActive())return this.invokePortableSdkProxyOp("getCrossOrgUserNotifications",y({type:"getCrossOrgUserNotifications"},t));let i=this.authService.getUser(),e=tt(this.functions,Z({url:this.endpointsService.getCloudFunctionUrl("sdkProxy"),apiProxyDomain:this.configService?.getApiProxyDomain()}));return yield ht({methodName:"getCrossOrgUserNotifications",data:y({type:"getCrossOrgUserNotifications"},t),getSdkProxy:e,userId:i?.userId??""})})}buildCrossOrgRequestData(t,i,e){let o=t||{},r=e?.isInitial??!0,a=e?.bumpedOrgs??[],n=Array.isArray(o.organizationIds),c=n?o.organizationIds.filter(g=>!!g).map(g=>dt(g)):[],s=(o.excludeOrganizationIds||[]).filter(g=>!!g).map(g=>dt(g)),l=new Set(s);i&&l.add(i);let f=this.userPermissionService?.getPermissionsCache?.()?.filter(g=>g?.type===X.CONTEXT),d={organizationId:i,excludeOrganizationIds:Array.from(l),timestamp:this.getStartAtTimestamp(),limitToLast:this.CROSS_ORG_PAGE_SIZE,isContextEnabled:this.userPermissionService?.getIsContextEnabled?.(),cachedData:f,isSettingsConfigByOrganization:this.getSettingsConfigByOrganization(),retryConfig:this.userPermissionService?.getPermissionProviderRetryConfig?.()};if(this.userPermissionService?.isClientDevResolverActive?.()&&(d.clientResolverAvailable=!0),r)n&&(d.organizationIds=this.dedupeIncludeOrgs(c,l));else{let g=a.filter(S=>!!S&&!l.has(S));if(n){let S=new Set(c);g=g.filter(D=>S.has(D))}g=Array.from(new Set(g)),d.organizationIds=g;let u={};g.forEach(S=>{u[S]=this.crossOrgSeenTimestamps[S]??this.getStartAtTimestamp()}),d.orgTimestamps=u}return d}dedupeIncludeOrgs(t,i){let e=new Set;return t.filter(o=>o==null||i.has(o)||e.has(o)?!1:(e.add(o),!0))}teardownCrossOrgPerUserListeners(){this.crossOrgGeneration++,this.crossOrgIndexSubscription&&(this.crossOrgIndexSubscription.unsubscribe(),this.crossOrgIndexSubscription=void 0),this.crossOrgOrgSwitchSubscription&&(this.crossOrgOrgSwitchSubscription.unsubscribe(),this.crossOrgOrgSwitchSubscription=void 0),this.crossOrgFetchTimer&&(clearTimeout(this.crossOrgFetchTimer),this.crossOrgFetchTimer=void 0),this.crossOrgFetchPending=!1,this.clearCrossOrgStragglerRetry()}teardownCrossOrgUserWatcher(){this.teardownCrossOrgPerUserListeners(),this.crossOrgUserSubscription&&(this.crossOrgUserSubscription.unsubscribe(),this.crossOrgUserSubscription=void 0)}resetCrossOrgDeltaState(){this.crossOrgIndexOrgs=[],this.crossOrgIndexTimestamps={},this.crossOrgSeenTimestamps={},this.crossOrgInitialFetchDone=!1}resetCrossOrgForUser(){this.teardownCrossOrgPerUserListeners(),this.resetCrossOrgDeltaState(),this.crossOrgNotifications$.getValue().length&&this.crossOrgNotifications$.next([])}teardownCrossOrg(){this.teardownCrossOrgUserWatcher(),this.resetCrossOrgDeltaState(),this.crossOrgNotifications$.next([])}markCrossOrgEntriesRead(t){try{let i=this.crossOrgNotifications$.getValue();if(!i?.length)return;let e=new Set((t||[]).map(n=>n?.id??n?.notificationId).filter(n=>n!=null));if(!e.size)return;let o=!this.getReadNotificationsOnForYouTab(),r=!1,a=o?i.filter(n=>{let c=n?.id??n?.notificationId,s=c!=null&&e.has(c);return s&&(r=!0),!s}):i.map(n=>{let c=n?.id??n?.notificationId;return c!=null&&e.has(c)&&n?.isUnread!==!1?(r=!0,P(y({},n),{isUnread:!1})):n});r&&this.crossOrgNotifications$.next(a)}catch(i){this.loggingService.catch("Error in NotificationService markCrossOrgEntriesRead: ",i)}}subscribeNotificationsData(t,i){this.loggingService.log("%c[WB] Calling FUNCTION: subscribeViewsData","color: green;");let e,o;try{if(t&&(o=ft(t)),i&&typeof i=="object"){let r=Mt(i);e=ft(JSON.stringify(r))}}catch(r){this.loggingService.catch("Error in ViewsService subscribeViewsData: ",r)}return this.authService.getAuthState$().pipe(z(r=>!!r),b(r=>this.isFeatureAllowed({firebaseUser:r})),b(r=>r.featureAllowed?this.iamService.isUserAllowed$().pipe(I(a=>(r.featureAllowed=a,r))):A(r)),b(r=>!r.featureAllowed||r?.user?.organizationId?(this.notifications$.next([]),this.rawNotificationsByIdMap$.next(new Map),this.processedNotifications$.next([]),this.notificationsByIdMap$.next(new Map),this.notificationViews$.next({}),this.setNotificationsByIdMap(),A([])):A(r).pipe(b(a=>this.docService.getDocumentPaths$().pipe(I(n=>(this.documentPaths=n,a.documentPaths=n,a)))),b(a=>this.getDataFromDocumentId(o)))))}isFeatureAllowed(t){return this.configService.getConfig$().pipe(z(i=>!!i),I(i=>P(y({},t),{config:i})),b(i=>this.authService.getUser$().pipe(I(e=>P(y({},i),{user:e})))),b(i=>Rt(i.config,i.user,Tt.NOTIFICATION)?A(P(y({},i),{featureAllowed:!0})):(this.loggingService.warn("Notification feature is not allowed."),A(P(y({},i),{featureAllowed:!1})))))}getDataFromDocumentId(t){return this.databaseService.getDb().pipe(z(i=>!!i),b(i=>{if(this.db=i,this.loggingService.log(this.db),this.configService?.getApiKey()&&this.documentPaths?.views){let e=`${this.configService.getApiKey()}`;this.documentPaths?.organizationId&&(e+=`/${L.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${this.documentPaths.organizationId}`);let o=this.realtimeAdapter.rtdbRef(this.db,`${t?e+"/"+L.FIREBASE_PARTIAL_PATH_DOCS+"/"+t+"/"+L.FIREBASE_PARTIAL_PATH_VIEWS+"/":this.documentPaths?.notifications}`);return this.realtimeAdapter.rtdbObjectVal$("notification",o).pipe(H(r=>(this.loggingService.catch("Error in NotificationService getDataFromDocumentId: ",r),A(null))),I(r=>{let a=[],n=new Map;r?.raw&&(Object.keys(r?.raw||{}).forEach(s=>{let l=r?.raw[s];l?.id&&a.push(l)}),a.forEach(s=>{s.id&&n.set(s.id,s)})),this.notifications$.next(a),this.rawNotificationsByIdMap$.next(n);let c=[];r?.processed&&Object.keys(r?.processed||{}).forEach(s=>{let l=r?.processed[s];l?.id&&c.push(l)}),this.processedNotifications$.next(c),this.setNotificationsByIdMap()}))}else return A(null)}))}setNotificationsByIdMap(){try{let t=this.authService.getUser();if(t){let i=this.notificationViews$.getValue(),e;t?.email&&(e=B(t?.email));let o;t?.userId&&(o=B(t?.userId));let r=new Map;this.processedNotifications$.getValue().forEach(n=>{if(n.id&&n?.displayHeadlineMessageTemplate){let c=!1;(e&&n.notifyUsers?.[e]||o&&n.notifyUsers?.[o])&&(c=!0);let s={id:n.id,notificationSource:n.notificationSource,actionType:n.actionType,actionUser:n.actionUser,timestamp:n.timestamp,targetAnnotationId:n.targetAnnotationId,displayHeadlineMessage:this.getNotificationHeadlineMessage(n),displayBodyMessage:this.getNotificationBodyMessage(n),forYou:c,notificationSourceData:n.notificationSourceData},l=this.getRawNotificationById(s.id);if(l?.metadata&&(s.metadata={apiKey:l.metadata.apiKey,organizationId:l.metadata.organizationId,clientOrganizationId:l.metadata.clientOrganizationId,documentId:l.metadata.documentId,clientDocumentId:l.metadata.clientDocumentId,location:l?.location,locationId:l?.locationId}),s?.notificationSource==="comment"&&s?.targetAnnotationId){let f=this.commentService?.getAnnotationById(s.targetAnnotationId);f||l?.annotationData&&(f=l.annotationData),f&&(s.notificationSourceData=this.commentService?.getCommentAnnotationForClient(f))}r.set(n.id,s)}}),r.forEach((n,c)=>{n.isUnread=n?.actionUser?.userSnippylyId!==t?.userSnippylyId&&!i?.notification?.[c]?.views?.[t?.userSnippylyId],r.set(c,n)}),this.notificationsByIdMap$.next(r)}}catch(t){this.loggingService.catch("Error in NotificationService setNotificationsByIdMap: ",t)}}getClientNotificationObject({processed:t,raw:i,metadata:e,views:o,notification:r}){try{let a=this.authService.getUser(),n=r||t;if(n.id&&n?.displayHeadlineMessageTemplate&&a){let c=null;a?.email&&(c=B(a?.email));let s=null;a?.userId&&(s=B(a?.userId));let l=!1,f=!0;(c&&n.notifyUsers?.[c]||s&&n.notifyUsersByUserId?.[s])&&(l=!0),s&&o?.[s]&&(f=!1);let d={id:n.id};if(r?d=P(y(y({},d),r),{displayHeadlineMessage:this.getNotificationHeadlineMessage(r),displayBodyMessage:this.getNotificationBodyMessage(r),forYou:l,isUnread:f}):d={id:t.id,notificationSource:t.notificationSource,actionType:t.actionType,actionUser:t.actionUser,timestamp:t.timestamp,targetAnnotationId:t.targetAnnotationId,displayHeadlineMessage:this.getNotificationHeadlineMessage(t),displayBodyMessage:this.getNotificationBodyMessage(t),forYou:l,isUnread:f,metadata:e},d?.notificationSource==="comment"&&d?.targetAnnotationId){let g=this.commentService?.getAnnotationById(d.targetAnnotationId);g||r?.notificationSourceData&&(g=r?.notificationSourceData),g||i?.annotationData&&(g=i.annotationData),g&&(d.notificationSourceData=this.commentService?.getCommentAnnotationForClient(g))}return i?.targetAnnotationData?.isCommentResolverUsed&&(d.isCommentResolverUsed=i?.targetAnnotationData?.isCommentResolverUsed),r?.isNotificationResolverUsed&&(d.isNotificationResolverUsed=r.isNotificationResolverUsed),d}return}catch(a){this.loggingService.catch("Error in NotificationService getClientNotificationObject: ",a);return}}getNotificationsForYou$(){return this.notificationsForYou$.asObservable()}getNotificationsByDocumentId$(){return this.notificationsByDocumentIdMap$.asObservable().pipe(I(t=>t?Object.keys(t??{}).map(i=>{let e=t[i].notifications||[],o=e.filter(a=>a.isUnread).length,r=e.length>0&&e[0]?.timestamp||0;return{documentId:i,notifications:t[i]?.notifications,unreadNotificationsCount:o,latestNotificationTimestamp:r,documentMetadata:t[i]?.documentMetadata}}).filter(i=>i.notifications?.length>0).sort((i,e)=>e.latestNotificationTimestamp-i.latestNotificationTimestamp):null))}getAllNotifications$(){return Y([this.getNotificationsByDocumentId$(),this.crossOrgNotifications$.asObservable(),this.getUserScopedAllTabRows$()]).pipe(I(([t,i,e])=>{let o=Array.isArray(i)?i:[],r=Array.isArray(e)?e:[],a=null;if(t&&(a=[],t.forEach(c=>{c.notifications.forEach(s=>{a?.push(s)})})),!o.length&&!r.length)return t?a.sort((c,s)=>s.timestamp-c.timestamp):null;if(!t)return null;let n=a||[];return r.length&&(n=this.mergeCrossOrgForYou(n,r)),o.length&&(n=this.mergeCrossOrgForYou(n,o)),n}))}getUserScopedAllTabRows$(){return Y([this.userScopedNotifications$,this.userNotificationsFromServer$.asObservable()]).pipe(I(([t,i])=>!t?.enabled||!i?.length?[]:i.map(e=>e?.notification??this.getClientNotificationObject(e)).filter(e=>!!e)))}processNotificationData(t){try{let i=t?.annotationData?.metadata,e=this.docService.getOrganizationConfig()?.organizationId;t.metadata=JSON.parse(JSON.stringify(this.docService.getDocumentMetadata(i?.documentId)||{})),t.metadata||(t.metadata={},this.loggingService.catch("Warning in NotificationService updateNotificationDatabase: ","Document metadata not found")),delete t.metadata.locations,t.metadata.documentMetadata=JSON.parse(JSON.stringify(this.docService.getDocumentMetadata(i?.documentId)||{})),t?.metadata?.documentMetadata?.clientDocumentId&&t?.metadata?.documentMetadata?.documentId&&(t.metadata.documentMetadata.documentId=t?.metadata?.documentMetadata?.clientDocumentId),delete t.metadata.documentMetadata.locations,t.metadata.organizationMetadata=JSON.parse(JSON.stringify(e?this.docService.getOrganizationMetadata(e)||{}:{})),t?.metadata?.organizationMetadata?.clientOrganizationId&&t?.metadata?.organizationMetadata?.organizationId&&(t.metadata.organizationMetadata.organizationId=t?.metadata?.organizationMetadata?.clientOrganizationId);let o=this.configService.getApiKey();t.metadata.apiKey=o,t.platform=this.configService.getSF()?"sf":"sdk",t.actionUser=this.authService.getUser();let r=i?.documentId?new pt({apiKey:o,documentId:i.documentId,organizationId:i?.organizationId}):this.docService.getDocumentPaths();t?.actionUser?.organizationId&&(t.metadata.organizationId=r?.organizationId||t.actionUser.organizationId,t.metadata.clientOrganizationId=r?.clientOrganizationId||t.actionUser.clientOrganizationId);let a=this.docService.getLocation();a&&(t.location=a?.location,t.locationId=a?.locationId),this.loggingService.log(`[NOTIFICATION] ${t?.notificationSource} ${t?.actionType}`,t);let n=this.commonDbService.getServerTimestamp(),c=this.notificationUtilsService.formatNotification(t,n);return JSON.parse(JSON.stringify(c))}catch(i){return this.loggingService.catch("Error in NotificationService processNotificationData: ",i),null}}reportDroppedHubPush(t){try{if(!this.notificationsHubDisabled)return;let i=String(t?.notificationSource??"comment");if(this.reportedDroppedHubPushes.has(i))return;this.reportedDroppedHubPushes.add(i),this.loggingService.catch(`Velt [self-hosted]: a client-side notification-hub push (source '${i}') was dropped \u2014 the notifications hub is deliberately disabled on this deployment (no-egress). Whatever this push fed (in-app notification, email, or webhook fan-out) will not happen for this source.`,void 0,void 0,!0)}catch{}}updateNotificationDatabase(t){try{if(!this.notificationsDb){this.reportDroppedHubPush(t);return}let i=this.realtimeAdapter.rtdbRef(this.notificationsDb),e=this.processNotificationData(t);try{let o=wt(t?.annotationData);if(o&&e&&typeof e=="object"){e.visibility=o;let r=Object.values(t?.annotationData?.subscribedUsers||{}).map(n=>n?.user?.userId).filter(n=>!!n),a=Pt(t?.annotationData,r);a.length&&(e.deniedForYouUsers=[...new Set([...e.deniedForYouUsers??[],...a])])}}catch(o){this.loggingService.catch("Error applying notification visibility in updateNotificationDatabase: ",o)}this.realtimeAdapter.rtdbPush("notificationIndex",i,JSON.parse(JSON.stringify(e)))}catch(i){this.loggingService.catch("Error in NotificationService updateNotificationDatabase: ",i)}}getRawNotifications$(){return this.notifications$.asObservable()}getProcessedNotifications$(){return this.processedNotifications$.asObservable()}getNotifications$(t){return this.authService.getUser$().pipe(b(i=>i?i.organizationId?this.getAllNotifications$().pipe(b(e=>this.notificationsForYou$.pipe(I(o=>{if(e||o){let r=new Map;return(!t?.type||["all","documents"].includes(t.type))&&(e||[]).forEach(a=>{a.id&&r.set(a.id,a)}),(!t?.type||["all","forYou"].includes(t.type))&&(o||[]).forEach(a=>{a.id&&!r.has(a.id)&&r.set(a.id,a)}),Array.from(r.values()).sort((a,n)=>(n.timestamp||0)-(a.timestamp||0))}else return null})))):this.notificationsByIdMap$.asObservable().pipe(I(e=>Array.from(e.values())),I(e=>e.sort((o,r)=>r.timestamp-o.timestamp)),bt()):A(null)),k(zt))}getRawNotificationById(t){try{return this.rawNotificationsByIdMap$.getValue()?.get(t)}catch(i){this.loggingService.catch("Error in NotificationService getRawNotificationById: ",i);return}}setNotificationViews(t){try{this.notificationViews$.next(t),this.setNotificationsByIdMap()}catch(i){this.loggingService.catch("Error in NotificationService setNotificationViews: ",i)}}getNotificationHeadlineMessage(t){try{let i=this.authService.getUser();if(t?.displayHeadlineMessageTemplate&&t?.displayHeadlineMessageTemplateData){let e=t.displayHeadlineMessageTemplate,o=t.displayHeadlineMessageTemplateData,r=/\{(\w+)\}/g,a=e.replace(r,(n,c)=>(c==="actionUser"||c==="recipientUser")&&o[c]?i?.email&&o[c].email===i?.email||i?.userId&&o[c]?.userId===i?.userId?"You":o[c].name||o[c].email||' <velt-skeleton-loader width="50px" height="20px" border-radius="4px"></velt-skeleton-loader> ':o[c]?o[c]:n);return this.domService.sanitizeHtml(a)}return this.domService.sanitizeHtml(t.displayHeadlineMessageTemplate||"")}catch(i){return this.loggingService.catch("Error in NotificationService getNotificationHeadlineMessage: ",i),""}}getNotificationBodyMessage(t){try{if(t?.displayBodyMessageTemplate&&t?.displayBodyMessageTemplateData){let i=t?.displayBodyMessageTemplate;return t?.displayBodyMessageTemplateData&&t?.displayBodyMessageTemplateData?.users?.forEach(e=>{if(e?.userId){let o=this.usersService.getUserById(e?.userId);i=i?.replaceAll(`{{${e.userId}}}`,o?.name||o?.email||'<velt-skeleton-loader width="50px" height="20px" border-radius="4px"></velt-skeleton-loader>'),i=i?.replaceAll(`@User ${e.userId}`,o?.name||o?.email||'<velt-skeleton-loader width="50px" height="20px" border-radius="4px"></velt-skeleton-loader>')}}),this.domService.sanitizeHtml(i)}return this.domService.sanitizeHtml(t.displayBodyMessage||"")}catch(i){return this.loggingService.catch("Error in NotificationService getNotificationBodyMessage: ",i),""}}setHistoryPanelVisibility(t,i=!1,e=!1){try{t?document.querySelector(L.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL)?this.historyPanelVisible$.next(t):this.loggingService.catch("Error in NotificationService setHistoryPanelVisibility: ",`<${L.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`):this.historyPanelVisible$.next(t),t?this.analyticsService.trackEvent(V.Events.Notifications.NOTIFICATION_HISTORY_PANEL_OPENED):this.analyticsService.trackEvent(V.Events.Notifications.NOTIFICATION_HISTORY_PANEL_CLOSED)}catch{this.loggingService.catch("Error in NotificationService setHistoryPanelVisibility: ",`<${L.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`)}}toggleHistoryPanelVisibility(t=!1,i=!1){try{this.historyPanelVisible$.value?this.historyPanelVisible$.next(!this.historyPanelVisible$.value):document.querySelector(L.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL)?(this.historyPanelVisible$.next(!this.historyPanelVisible$.value),this.historyPanelVisible$.value?this.analyticsService.trackEvent(V.Events.Notifications.NOTIFICATION_HISTORY_PANEL_TOGGLED,{action:"closed"}):this.analyticsService.trackEvent(V.Events.Notifications.NOTIFICATION_HISTORY_PANEL_TOGGLED,{action:"opened"})):this.loggingService.catch("Error in NotificationService toggleHistoryPanelVisibility: ",`<${L.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`)}catch{this.loggingService.catch("Error in NotificationService toggleHistoryPanelVisibility: ",`<${L.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`)}}getHistoryPanelVisibility$(){return this.historyPanelVisible$.asObservable()}setNotificationsAsRead(t){return U(this,null,function*(){try{let i=JSON.parse(JSON.stringify(this.getUserNotificationsFromServer()??[]));if(t?.length){for(let a=0;a<t.length;a+=50){let c=t.slice(a,a+50).filter(f=>f?.id),s=c.map(f=>this.setNotificationAsRead({notification:f,userNotifications:JSON.parse(JSON.stringify(i))})),l=yield Promise.all(s);c.forEach((f,d)=>{let g=l[d];if(!g.some(S=>S.notificationId===f.id))i=i.filter(S=>S.notificationId!==f.id);else{let S=i.find(E=>E.notificationId===f.id),D=g.find(E=>E.notificationId===f.id);S&&D?.views&&(S.views=D.views)}})}let o=JSON.parse(JSON.stringify(this.notificationsByDocumentIdMap$.getValue()||{}));t.forEach(a=>{let n=a.metadata?.documentId;if(n&&o?.[n]){let c=o?.[n]?.notifications||[],s=c.find(l=>l.id===a.id);s&&(s.isUnread=!1),o[n].notifications=c}}),this.notificationsByDocumentIdMap$.next(o),this.markCrossOrgEntriesRead(t),!q(i,this.getUserNotificationsFromServer())&&this.setUserNotificationsFromServer(i)}}catch(i){this.loggingService.catch("Error in NotificationService setNotificationsAsRead: ",i)}})}setAllNotificationsAsRead(t){return U(this,null,function*(){try{if(t?.tabId==="for-you"){let i=this.notificationsForYou$.value||[];this.setNotificationsAsRead(i)}else this.getNotifications$().pipe(W(1)).subscribe(i=>{i&&this.setNotificationsAsRead(i)})}catch(i){this.loggingService.catch("Error in NotificationService setAllNotificationsAsRead: ",i)}})}getUnreadNotificationsCount$(){try{return this.notificationsForYou$.pipe(I(t=>t?.filter(e=>e?.isUnread)?.length??null),b(t=>this.getNotifications$().pipe(I(i=>{let e=i?.filter(o=>o?.isUnread)?.length??null;return{forYou:t,all:e}}))))}catch(t){return this.loggingService.catch("Error in NotificationService getUnreadNotificationsCount$: ",t),A({forYou:null,all:null})}}setNotificationAsRead(e){return U(this,arguments,function*({notification:t,userNotifications:i}){try{let o=this.authService.getUser();if(o&&t?.id){let r=B(o?.userId),{metadata:a}=t;if(a){let{apiKey:n,organizationId:c,documentId:s}=a;if(n&&c&&s&&r){let l=yield this.commonDbService.getData({feature:"docNotification",properties:{id:t.id,organizationId:c,documentId:s,apiKey:n}});l?.notificationId&&(l?.views?.[r]||(l.views||(l.views={}),l.views[r]={timestamp:Date.now()},this.commonDbService.updateData({feature:"docNotificationViews",properties:{id:t.id,organizationId:c,documentId:s,apiKey:n},data:l})));let f=yield this.commonDbService.getData({feature:"userNotification",properties:{id:t.id,userId:r,documentId:s,organizationId:c}});if(f?.notificationId){if(!this.getReadNotificationsOnForYouTab())yield this.commonDbService.deleteData({feature:"userNotification",properties:{id:t.id,userId:r,documentId:s,organizationId:c}}),i=i.filter(d=>d.notificationId!==t.id);else if(!f?.views?.[r]){f.views||(f.views={}),f.views[r]={timestamp:Date.now()};let d=i.find(g=>g.notificationId===t.id);d&&(d.views=f.views),this.commonDbService.updateData({feature:"userNotificationViews",properties:{id:t.id,userId:r,documentId:s,organizationId:c},data:f})}}}}}return i}catch(o){return this.loggingService.catch("Error in NotificationService setNotificationAsRead: ",o),i}})}setMaxDays(t){try{t>0?this.maxNotificationDays$.next(t):this.maxNotificationDays$.next(15)}catch(i){this.loggingService.catch("Error in NotificationService setMaxDays: ",i)}}setTabConfig(t){try{t&&this.tabConfig$.next(t)}catch(i){this.loggingService.catch("Error in NotificationService setTabConfig: ",i)}}getTabConfig$(){return this.tabConfig$.asObservable()}getTabConfig(){return this.tabConfig$.value}enableReadNotificationsOnForYouTab(){this.readNotificationsOnForYouTab$.next(!0)}disableReadNotificationsOnForYouTab(){this.readNotificationsOnForYouTab$.next(!1)}getReadNotificationsOnForYouTab$(){return this.readNotificationsOnForYouTab$.asObservable()}getReadNotificationsOnForYouTab(){return this.readNotificationsOnForYouTab$.value}enableCurrentDocumentOnly(){try{if(this.currentDocumentOnly$.value===!0)return;this.currentDocumentOnly$.next(!0)}catch(t){this.loggingService.catch("Error in NotificationService enableCurrentDocumentOnly: ",t)}}disableCurrentDocumentOnly(){try{if(this.currentDocumentOnly$.value===!1)return;this.currentDocumentOnly$.next(!1)}catch(t){this.loggingService.catch("Error in NotificationService disableCurrentDocumentOnly: ",t)}}getCurrentDocumentOnly$(){return this.currentDocumentOnly$.asObservable()}getCurrentDocumentOnly(){return this.currentDocumentOnly$.value}markNotificationAsReadById(t){return U(this,null,function*(){try{this.getNotifications$().pipe(W(1)).subscribe(i=>{if(i){let e=i.filter(o=>o.id===t);this.setNotificationsAsRead(e)}})}catch(i){this.loggingService.catch("Error in NotificationService markNotificationAsReadById: ",i)}})}getOwnDocumentMetadata(t){try{let i=t==null||t===""?null:this.docService.getDocumentMetadata(String(t));return i?JSON.parse(JSON.stringify(i)):null}catch(i){return this.loggingService.catch("Error in NotificationService getOwnDocumentMetadata: ",i),null}}getAllowedDocumentMetadataByDocumentId(t){try{return this.allowedDocumentMetadataMap$.value?.[t]||null}catch(i){return this.loggingService.catch("Error in NotificationService getAllowedDocumentMetadataByDocumentId: ",i),null}}setSettingsConfig(t){try{this.enableSettings$.value&&this.settingsConfig$.next(t)}catch(i){this.loggingService.catch("Error in NotificationService setSettingsConfig: ",i)}}setSettingsConfigWithDB(t){try{this.enableSettings$.value&&(this.settingsConfig$.next(t),this.updateSettingsConfigToDb())}catch(i){this.loggingService.catch("Error in NotificationService setSettingsConfigWithDB: ",i)}}getSettingsConfig$(){return this.settingsConfig$.asObservable()}getSettingsConfig(){return this.settingsConfig$.value}setMuteAllNotifications(){try{this.muteAllNotifications$.value!==!0&&this.muteAllNotifications$.next(!0)}catch(t){this.loggingService.catch("Error in NotificationService setSettingsMuteAll: ",t)}}getMuteAllNotifications$(){return this.muteAllNotifications$.asObservable()}getMuteAllNotifications(){return this.muteAllNotifications$.value}enableSettings(){try{this.enableSettings$.value!==!0&&this.enableSettings$.next(!0)}catch(t){this.loggingService.catch("Error in NotificationService enableSettings: ",t)}}enableSettingsConfigByOrganization(){try{this.getSettingsConfigByOrganization()!==!0&&this.setSettingsConfigByOrganization$.next(!0)}catch(t){this.loggingService.catch("Error in NotificationService enableSettingsConfigByOrganization: ",t)}}disableSettingsConfigByOrganization(){try{this.getSettingsConfigByOrganization()!==!1&&this.setSettingsConfigByOrganization$.next(!1)}catch(t){this.loggingService.catch("Error in NotificationService disableSettingsConfigByOrganization: ",t)}}getSettingsConfigByOrganization$(){return this.setSettingsConfigByOrganization$.asObservable()}getSettingsConfigByOrganization(){return this.setSettingsConfigByOrganization$.value}enableSelfNotifications(){try{this.selfNotifications$.value!==!0&&this.selfNotifications$.next(!0)}catch(t){this.loggingService.catch("Error in NotificationService enableSelfNotifications: ",t)}}disableSelfNotifications(){try{this.selfNotifications$.value!==!1&&this.selfNotifications$.next(!1)}catch(t){this.loggingService.catch("Error in NotificationService disableSelfNotifications: ",t)}}enableUserScopedNotifications(t){try{if(t&&typeof t=="object"&&t.enabled===!1){this.disableUserScopedNotifications();return}this.userScopedNotifications$.next({enabled:!0,limit:gi(t?.limit)})}catch(i){this.loggingService.catch("Error in NotificationService enableUserScopedNotifications: ",i)}}disableUserScopedNotifications(){try{this.userScopedNotifications$.value.enabled!==!1&&this.userScopedNotifications$.next({enabled:!1,limit:this.userScopedNotifications$.value.limit})}catch(t){this.loggingService.catch("Error in NotificationService disableUserScopedNotifications: ",t)}}disableSettings(){try{this.enableSettings$.value!==!1&&this.enableSettings$.next(!1)}catch(t){this.loggingService.catch("Error in NotificationService disableSettings: ",t)}}getEnableSettings$(){return this.enableSettings$.asObservable()}getEnableSettings(){return this.enableSettings$.value}setSettingsInitialConfig(t){try{let i=!1;if(t.forEach(e=>{["email","inbox"].includes(e.id)&&(i=!e.values?.every(o=>["ALL","NONE","MINE"].includes(o.id)))}),i){this.loggingService.catch("Invalid config values for email or inbox, It should have only ALL, NONE, MINE values");return}this.settingsInitialConfig$.next(t)}catch(i){this.loggingService.catch("Error in NotificationService setSettingsInitialConfig: ",i)}}getSettingsInitialConfig$(){return this.settingsInitialConfig$.asObservable()}getSettingsInitialConfig(){return this.settingsInitialConfig$.value}updateSettingsConfigToDb(t){return U(this,null,function*(){try{let i=this.authService.getUser(),e=B(i?.userId??""),o=this.docService.getDocumentPaths(),r=this.docService.getOrganizationConfig(),a=o?.organizationId??r?.organizationId,n=o?.clientOrganizationId??r?.clientOrganizationId,c={apiKey:this.configService.getApiKey(),organizationId:a,documentId:o?.documentId,clientOrganizationId:n,clientDocumentId:o?.clientDocumentId,userId:e,clientUserId:this.authService.getUser()?.userId};e&&this.getEnableSettings()&&this.enableSettings$.value&&(this.getSettingsConfigByOrganization()?this.docService.addUserInfoToOrganization({organizationId:n??i?.clientOrganizationId??"",user:{userId:i?.userId??""},notificationsConfig:t||this.settingsConfig$.getValue()}):o?.documentId&&(yield this.commonDbService.updateData({feature:"userConfig",properties:{documentId:o?.documentId,userId:e},data:{id:o?.documentId,notificationsConfig:t||this.settingsConfig$.getValue(),metadata:c}})))}catch(i){this.loggingService.catch("Error in NotificationService updateSettingsConfigToDb: ",i)}})}openNotificationsPanel(){try{this.notificationsPanelVisible$.next(!0)}catch(t){this.loggingService.catch("Error in NotificationService openNotificationsPanel: ",t)}}closeNotificationsPanel(){try{this.notificationsPanelVisible$.next(!1)}catch(t){this.loggingService.catch("Error in NotificationService closeNotificationsPanel: ",t)}}getNotificationsPanelVisible$(){return this.notificationsPanelVisible$.asObservable()}getNotificationsPanelVisible(){return this.notificationsPanelVisible$.value}};m.\u0275fac=function(i){return new(i||m)(N(Dt),N(Ht),N(ot),N(kt),N(ri),N(oi),N(st),N(nt),N(at),N(Jt),N(ni),N(Zt),N(si),N(et),N(ci),N(rt),N(Ct),N(ai),N(qt),N(it),N(Qt),N(Xt))},m.\u0275prov=K({token:m,factory:m.\u0275fac,providedIn:"root"});let v=m;return v})();export{ci as a,ce as b};